Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Python calculate the number of balls?

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how Python calculates the number of balls". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to calculate the number of balls in Python".

The code is as follows:

# author: DE8UG

# create trash cans and trash

# Rule: KRV, a k corresponds to a v, and the code is divided by colons.

# input

# judgment

# Save

# function

# Synthesis

Import json

Rule = {

"Wet garbage": ["vegetable leaves", "orange peel", "spring onions", "biscuits"]

"dry garbage": ["old bathtub", "basin", "sponge", "toilet paper"]

}

# print ('load file:', ljt_gan)

Def load_data (filename):

With open (filename) as f:

Data = json.load (f)

Return data

Def reng_laji (rule_k, laji, ljt):

If rule_k = = ljt ['name']:

Ljt ['data'] .append (laji)

Def fenlei (laji, rule, ljt):

For k, v in rule.items ():

Print (k, v)

If laji in v:

Print ('garbage found:', laji, k)

Reng_laji (k, laji, ljt)

# reng_laji (k, laji, ljt_shi)

# encapsulate the code for writing files with functions

Def save_to_file (filename, data):

With open (filename,'w') as f:

Json.dump (data, f)

Def main ():

# define trash cans

Ljt_shi = {

Name': "wet rubbish"

'data': []

}

Ljt_gan = {

Name': "dry trash"

'data': []

}

# load existing garbage

Ljt_gan = load_data ('gan.json')

Ljt_shi = load_data ('shi.json')

Print ('load file:', ljt_gan, ljt_shi)

# throw out the trash

Laji = input ("enter garbage to throw:")

Print ("junk:", laji)

# Classification

Fenlei (laji, rule, ljt_gan)

Fenlei (laji, rule, ljt_shi)

Print ('- * 20)

Print (ljt_shi)

Print (ljt_gan)

# call the function and save to the specific trash file

Save_to_file ('gan.json', ljt_gan)

Save_to_file ('shi.json', ljt_shi)

If _ name__ = = "_ _ main__":

Main ()

This code is not long, but contains variables, comments, functions and other parts, can be used as the first analysis target.

The following explains what has been done with code and comments.

# Python is a ball

# author:DE8UG

# first prepare the target file

Filename = 'rengleme_07.py'

# write the function to get all the lines in it

Def get_lines (filename):

With open (filename) as f:

Return f.readlines ()

# if you print this function, it will be the following bunch of strings, but, look, it's a list. That would be easy.

"

['# author: DE8UG\ ngarbage,'# create trash cans and garbage\ n'

'# Rule: KRV, a k corresponds to a v, and the code is divided by colons\ n'

'# input\ nmarker,' # judge\ nmarker,'# save\ nkeeper,'# function\ nkeeper,'# synthesis\ nmarker,'\ njudge,'\ n`

'import json\ n','\ n','\ n'

'rule = {\ nbread,' "wet garbage": ["vegetable leaves", "orange peel", "spring onions", "biscuits"]

\ nBy,'

"dry rubbish": ["old bathtub", "basin", "sponge", "toilet paper"]\ ngarbage,'}\ n'

'\ nYou,'\ n'

"# print ('load file:', ljt_gan)\ n"

'def load_data (filename):\ n'

'with open (filename) as f:\ n'

'data = json.load (f)\ n'

Def reng_laji (rule_k, laji, ljt):\ nregions, "if rule_k = = ljt ['name']:\ n", "ljt [' data'] .append (laji)\ n",'\ nstories,'\ ntrees, 'def fenlei (laji, rule, ljt):\ nstories,' for k, v in rule.items ():\ n' 'print (k, v)\ ngarbage,' if laji in v:\ ngarbage, "print ('found garbage:', laji, k)\ n", 'reng_laji (k, laji, ljt)\ ngarbage,' # reng_laji (k, laji, ljt_shi)\ ngarbage,'\ ngarbage,'\ n' '# encapsulate the code to write the file with functions,' def save_to_file (filename, data):\ ncodes, "with open (filename,'w') as f:\ n", 'json.dump (data, f)\ ncodes,'\ ncodes,'\ ncodes, 'def main ():\ ncodes,'\ nboxes,'# define trash cans\ n` 'ljt_shi = {\ ngarbage,'\ 'name\': "wet garbage",\ ngarbage, "'data': []\ n",'}\ ngarbage,'\ ngarbage, 'ljt_gan = {\ ngarbage,'\ 'name\': "dry garbage",\ ngarbage, "'data': []\ n",'}\ n' '\ ngarbage,' # load existing garbage\ ngarbage, "ljt_gan = load_data ('gan.json')\ n", "ljt_shi = load_data (' shi.json')\ n",'\ ngarbage, "" print ('load file:', ljt_gan, ljt_shi)\ n ",'\ ngarbage,'# throw garbage\ n' 'laji = input ("enter garbage to throw:")\ ngarbage,' print ("garbage:", laji)\ ncategories,'\ ncategories, 'fenlei (laji, rule, ljt_gan)\ ngarbage,' fenlei (laji, rule, ljt_shi)\ ngarbage,'\ ngarbage, "print ('-'* 20)\ n", 'print (ljt_shi)\ n' 'print (ljt_gan)\ ncalling,'\ ncalling,'# calling the function Save to a specific trash bin file,\ ngarbage, "save_to_file ('gan.json', ljt_gan)\ n", "save_to_file (' shi.json', ljt_shi)\ n",'\ nbread,'\ nmom,'if _ _ name__ = = "_ _ main__":\\ main__, 'main ()\ n,'\ n']

"

# Let's define the result format, format each line of code into a dictionary, including line number, string, type, meaning, and then combine it into a new list

[

{

'line':1

'str':'def load_data (filename):\ n'

'type':'function', # code, comment, import, var

'The mean':' function load_data, which contains the parameter: filename'

}

]

Def analysis_code (lines):

Analyze each line of code and divide it into different types according to different characteristics. Note that the variables and functions that wrap the line will have internal code. We will decompose and judge by the last saved result. Save the formatted line as a new list and return it.

"

Results = []

Count = 1

For line in lines:

Format_line = {

'line': count

'str': line

'type':'code', # code, comment, import, var

'inner_code': []

'mean':''

}

If line.startswith ('#'):

Format_line ['type'] =' comment'

Elif line.startswith ('import'):

Format_line ['type'] =' import'

Elif line.find ('=') > 0:

Format_line ['type'] =' var'

Elif line.startswith ('def'):

Format_line ['type'] =' function'

# blank line, internal code of function, internal code of variable, no result added

If line.startswith ('') or line.startswith ('}\ n'):

# print (results [- 1])

If results [- 1] ['type'] = =' function' or results [- 1] ['type'] = =' var':

Results [- 1] ['inner_code'] .append (line)

Elif line.startswith ('\ n'):

Pass # blank lines skim directly

Else:

Results.append (format_line)

# Loop the next line

Count + = 1

Return results

# start testing below

If _ name__ = = "_ _ main__":

Print ('* * 50)

Print ('Welcome to use Python to calculate a ball, pinch and point, your code is as follows:')

Lines = get_lines (filename)

# print (lines [: 10])

R = analysis_code (lines)

# print (r)

Comment_list = []

Function_list = []

For line in r:

# print (line)

If line ['type'] = =' comment':

Comment_list.append (line)

Elif line ['type'] = =' function':

Function_list.append (line)

Print (fallow-total {len (comment_list)} comments')

Print (fallow-A total of {len (function_list)} functions:')

For f in function_list:

Print (f'line: {f ["line"]}', f ['str'] .strip ())

As the code shows, we decomposed the object code today, reformatted it according to the different characteristics of each line, and converted it into a dictionary containing four parts: line number, string, type, and meaning. Different formats can also be extended as needed to facilitate our further processing. For example, parsing the meaning of the code, describing the running process and so on.

Thank you for your reading, the above is the content of "how Python calculates the number of balls". After the study of this article, I believe you have a deeper understanding of how Python calculates the number of balls, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report