1: Find the character with the highest number of occurrences in the string s="aaabbbccceeefff111144444".
(1) consider the de-emphasis, first of all, the string will be filtered and de-emphasized, so that in the loop query based on these characters, will reduce the number of loops, improve efficiency. But I wrote the code is more bloated, there is a better hope that the message comment!
str = 'a1fsfs111bbbcccccvvvvvnnnnboooooosssnb' class Countvalue(): def countvalue(self, str1): ''' Using set's own de-duplication :param str1: Filter the incoming strings. :return: Returns a list without duplicate characters. ''' list1 = [] result = [] for x in str1: (x) result = set(list1) return result def count(self, str1): ''' Iterate over a list that has been de-duplicated due to de-duplication This reduces the number of loops and improves retrieval efficiency :param str1. :return. ''' list = Countvalue().countvalue(str1) a = 0 tump = {} for x in list: test = (x) if test > a: () a = test tump[x] = a elif test == a: a = test tump[x] = a return tump if __name__ == '__main__': print(Countvalue().count(str))
(2) No consideration of de-emphasis
s = "xssdddeeeeeeeffff" max_times = 0 result = {} for i in s: if (i) > max_times: () result[i] = (i) max_times = (i) elif (i) == max_times: result[i] = (i) print result
The following is excerpted from: /watfe/article/details/79206165
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' 2018.1.30 Python Practice 100 Questions /python/ ''' ''' Topic 001: How many three-digit numbers that are different from each other and have no repeating digits can be formed from four numbers: 1, 2, 3, and 4? What is the number of each? ''' def tm001(): ''' [Personal Remarks]: Write it out directly according to the title ''' arr = [] for i in range(1,5): for j in range(1,5): for k in range(1,5): num = 100*i+10*j+k if i!=j and j!=k and i!=k and num not in arr:# Three-digit numbers that are not identical and have no repeating digits (num) print(len(arr),arr) def tm001_1(): ''' [Personal note]: In fact, python comes with a permutation module that can be called directly. Also know this writing method, just function can not remember, or Baidu to write out. If this is an interview question, can write the latter of course, if not, or honestly in accordance with the above ideas. ''' import itertools temp_arr = list(([1, 2, 3, 4], 3)) # Ranking # A_4^3 = (4)! /(4-3)! = (4*3*2*1)/1 = 24 arr = [100*t[0]+10*t[1]+t[2] for t in temp_arr] print(len(arr),arr) ''' Topic 002: Bonuses paid by companies are withdrawn based on the amount of profit (I): Below or equal to $100,000, the bonus is withdrawn by 10%; When profits are above $100,000 and below $200,000, the portion below $100,000 is withdrawn at 10%, and the portion above $100,000 is withdrawn at 7.5%; Between $200,000 and $400,000 above $200,000, 5%; 3% on the portion above $400,000 when between $400,000 and $600,000 1.5% on the portion above $600,000 when between $600,000 and $1 million; 1% on the portion above $1 million when it is above $1 million. From the keyboard, enter the profit I for the month and find the total amount of bonuses due? ''' def tm002(): ''' Program Analysis: Please use the number axis to delimit and locate. [Personal Remarks]: This way of writing to deal with the problem of the number axis is worth referring to. It is much more concise and convenient than the elif way of writing. ''' money = int(input('Net profit:')) arr = [1000000,600000,400000,200000,100000,0] rat = [0.01,0.015,0.03,0.05,0.075,0.1] bonus = 0 for i in range(len(arr)): if money>arr[i]: # For the portion of the interval bonus+=(money-arr[i])*rat[i] # Calculate and accrue incentives money=arr[i] # Remainder print(bonus) ''' Topic 003: What is an integer which, when added to 100, is a perfect square number, and when added to 168 is another perfect square number? ''' def tm003(): ''' [Personal note]: the website was solving for the equation, didn't look at it in detail. It's not like python doesn't have an equation function, so I solved it directly and literally. ''' import math for i in range(1000): x = (i+100) y = (i+100+168) if x%1==0 and y%1==0: print(i) ''' Question 004: Enter a day of a certain year and month to determine what day of the year it is? ''' def tm004(): ''' 【Personal Remarks】:realizepythonThere is the concept of time tuples,This question requires no calculations at all。 The time tuple contains nine attributes tm_year surname Nian tm_mon moon(1~12) tm_mday date(1~31) tm_hour hour(0~23) tm_min ingredient(0~59) tm_sec unit of angle or arc equivalent one sixtieth of a degree(0~61, 60maybe61是闰unit of angle or arc equivalent one sixtieth of a degree) tm_wday last week(0~6, 0It's Monday.) tm_yday first few days(1~366, 366Julian calendar) tm_isdst 夏令hour(平hourexpense or outlay不到) ''' import time date = input('importationhour间(for example2018-01-23):') st = (date,'%Y-%m-%d') # Time text converted to time metazoans num = st.tm_yday print(num) ''' Question 005: Input three integers x,y,z. Output these three numbers from smallest to largest. ''' def tm005(): print('Enter three numbers') x = input('Enter the 1st digit:') y = input('Enter the 2nd digit:') z = input('Enter the 3rd digit:') l = [x,y,z] arr = sorted(l) # You can also use the () method to sort, at which point the list itself will be modified print(arr) ''' Topic 006: Fibonacci series. ''' def tm006(): ''' Program Analysis: The Fibonacci series, also known as the golden section series, refers to such a series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ....... [Personal note]: many kinds of solutions, I am in accordance with the division of the way, each time to take the last two items of the list, and then add up. ''' l = [0,1] for i in range(10): arr = l[-2:] (arr[0]+arr[1]) print(l) ''' Topic 007: Copying data from one list to another. ''' def tm007(): ''' [Personal note]: If you have systematically read python tutorials and such you should know. Everything in Python is an object, and lists need to be copied using [:]. As for b=a, it's just like giving a an alias to a. It's pointing to the same list, not copying. ''' a = [1, 2, 3] b = a[:] '''Off topic''' a[0]=0 print(id(a),id(b)) # You can see that a,b's memory doesn't match, it's a copy # print(a,b) # Modify a, b unchanged a = [1, 2, 3] b = a a[0]=0 print(id(a),id(b)) # If you remove the [:], you can see that a,b have the same memory and are not copied, pointing to the same list print(a,b) # Change a, change b ''' Topic 008: Title: Output 9*9 multiplication table. ''' def tm008(): ''' 【Personal Remarks】:I've forgotten.,I had to go to Baidu to figure out what the mnemonic chart looked like.。 take note of %-7s respond in singing end='' usage, and not much else. ''' for i in range(1,10): for j in range(1,10): if j<=i: string = '%d*%d=%d'%(j,i,j*i) print('%-7s'%string,end='') print('') def tm008_1(): ''' The csdn user isgoto generates the string using the format method, see also. Using the loop to i+1 method, you can also write one less line than above. ''' for i in range(1,10): for j in range(1, i + 1): print("{0} * {1} = {2}".format(i, j, i * j),end="\t") print() ''' Topic 009: Suspend output for one second. ''' def tm009(): ''' [Personal Remarks]:(), those who have used it know it. ''' import time a = () (1) b = () print(b-a) ''' Topic 010: Pause the output for one second and format the current time. ''' def tm010(): ''' [Personal Remarks]: Used it a couple times, used it and forgot it. ''' import time a = ('%Y-%m-%d %H:%M:%S',(())) # () Timestamps converted to time metazoans print(a) (1) b = ('%Y-%m-%d %H:%M:%S',(())) # () Time meta-ancestors converted to time text print(b) ''' Topic 011: Classical Question: There is a pair of rabbits that Each month from the 3rd month of life onwards a pair of rabbits is born. The young rabbits grow up to the third month and give birth to another pair of rabbits every month. Suppose none of the rabbits die. What is the total number of rabbits in each month? ''' def tm011(): ''' Actually, this question is the origin of the Fibonacci series. [Personal note]: Sorting it out is the key to understanding it as a good idea to have rabbits every month after two full months. ''' m1=1 # Full moon m2=0 # Two months old (rabbits next month) mm=0 # You can have rabbits month after month for i in range(1,10): # After a month mm = mm+m2 # Join the new adult rabbits m2 = m1 # A full moon becomes two full months m1 = mm # New rabbits born this month print(i,mm+m1+m2) # How many pairs of rabbits per month ''' Topic 012: Determine how many prime numbers there are between 101-200 and output all of them. ''' def tm012(): ''' [Personal Remarks]: take all the prime numbers up to 200 according to the fact that a prime number is not divisible by a previous prime number, and then take out the portion between 101 and 200. ''' arr = [2,3] # Take all prime numbers up to 200 for i in range(4,201): for j in arr: if i%j==0: break # else: # This is the way I wrote it at first, but then I realized that for can be followed by an else clause. # if j==arr[-1]: # (i) else: # The clause at else will be executed when the object to be iterated over has been successfully iterated over, whereas if break is included in the for loop, the loop is terminated and the else clause is not executed. (i) # Take out the portion between 100 and 200 for i in range(len(arr)): if arr[i]>100: l = arr[i:] print(len(l),l) break ''' Topic 013: Print out all the "Daffodil Counts. A "Daffodil Count." is a three-digit number whose cubic sum of digits is equal to the number itself. For example, 153 is a "Daffodil Count." because 153 = 1 cubic + 5 cubic + 3 cubic. ''' def tm013(): ''' 【Personal Remarks】: // rounding, % remainder, **3 triples. If you know how to write rounding and remainder, you'll be fine. ''' for i in range(100,1000): b = i//100 # Hundreds s = i%100//10 # Ten g = i%10 # individual if b**3+s**3+g**3==i: print(i) ''' title014:将一classifier for individual things or people, general, catch-all classifier正整数ingredient解质因数。for example:importation90,print out90=2*3*3*5。 ''' def tm014(): ''' [Personal Remarks]: dismantle it until it can't be dismantled, similar to question 012. ''' import math num = int(input('Enter an integer:')) arr = [] while num>1: for i in range(2,int((num))+1): # Since the subject is an unspecified positive integer, the square can effectively reduce the amount of computation when the value is too large. if num%i==0: (i) num = num//i break else: (num) break print(arr) ''' Topic 015: Use the nesting of conditional operators to complete this question: students with academic scores >=90 are denoted by A, those with scores between 60 and 89 are denoted by B, and those with scores below 60 are denoted by C. ''' def tm015(): ''' [Personal note]: basic if-else usage, not much to say. ''' score = float(input('Enter a grade:')) if score>=90: print('A') elif score>=60: print('B') else: print('C') ''' Topic 016: Output a date in a specified format. ''' def tm016(): ''' [Personal note]: not much use often forget, organized a reference answer and some conversion 2019-5-29 The following date time codes are for reference only. I've organized the commonly used date time methods in my other blog post Python3 Date-Text Interchange, Timestamps, Time Differences, and Time Zone Transformations. /watfe/article/details/84943732 ''' import time print(()) # Time stamp 1498539133.655 print(()) # time meta-anchor tm_year=2017, tm_mon=6, tm_mday=27, tm_hour=12, tm_min=53, tm_sec=16, tm_wday=1, tm_yday=178, tm_isdst=0 print(()) # A readable text form of time 'Tue Jun 27 12:53:50 2017' print(('%Y-%m-%d %H:%M:%S',())) # Output the time '2017-06-27 13:00:57' in the specified text format st = (()) # Timestamps transformed into time metazoans st = ('2018/1/23','%Y/%m/%d') # Time text transformed into time meta-anchor date = ('%Y-%m-%d',st) # time meta-anchor into time text '%Y-%m-%d %H:%M:%S' print(date) # The first two functions work together to reformat the time text. # Alternatively we can calculate the time difference with the datetime module, for example: import datetime dt1 = (1517302458) print(dt1,type(dt1)) dt2 = () print(dt2) print('A difference of %d days and %.1f hours'%((dt2-dt1).days,(dt2-dt1).seconds/60/60)) ''' 2018-01-30 16:54:18 <class ''> 2018-02-01 16:27:47.524774 There is a difference of 1 day and 23.6 hours ''' # Note that the date above, while appearing to be text, is actually of type datetime. # can be obtained by timestamp/time text conversion before datetime calculations can be performed. d1 = ('2017-10-16 19:21:22', '%Y-%m-%d %H:%M:%S') ''' Question 017: Enter a line of characters and count the number of letters, spaces, numbers and other characters in it. ''' def tm017(): ''' 【Personal Remarks】:I was going to write it in this format import string if c in string.ascii_letters: # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ if c == ' ': # Space if c in : # 0123456789 看了参考答案才realize有现成的函数可以expense or outlay。 Actually, any of them will do.,Even just gluing a bunch of letters on looks more straightforward。 ''' s = input('input a string:\n') letters,space,digit,others = 0,0,0,0 for c in s: if (): letters += 1 elif (): space += 1 elif (): digit += 1 else: others += 1 print('char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others)) ''' Topic 018: Find the s=a+aa+aaa+aaa+aaa.... ...the value of a, where a is a number. For example, 2+22+222+2222+22222 (at this point, there are a total of 5 numbers added together), several numbers are added together controlled by the keyboard. ''' def tm018(): ''' [Personal note]: The answer gives a variety of solutions, but I still think the method I wrote is the easiest. 2+22+222+2222+22222 It can be understood as: 20000 + 2*2000 + 3*200 + 4*20 + 5*2 That is: 1*2*10^4 + 2*2*10^3 + 3*2*10^2 + 4*2*10^1 + 5*2*10^0 So a simple iteration yields the result ''' a = 2 t = 5 num = 0 for i in range(1,t+1): num+=i*a*(10**(t-i)) print(num) ''' Topic 019: A number is called "Finished." if it is exactly equal to the sum of its factors. For example, 6 = 1 + 2 + 3. Program all the finished numbers up to 1000. ''' def tm019(): ''' [Personal note]: The question is not too understandable, so Baidu: the perfect number is the sum of all the approximate numbers except itself is equal to itself. The first perfect number is 6, which has the approximate numbers 1, 2, 3, 6, excluding itself 6, the remaining 3 numbers add up to 1 + 2 + 3 = 6. The second perfect number is 28, which has the approximate numbers 1, 2, 4, 7, 14, 28, and excluding itself 28, the remaining 5 numbers add up, 1+2+4+7+14=28. Finally read the question. Just find all the approximate numbers first, then sum and compare to see if they are equal, no difficulty! ''' for num in range(1,1000): arr = [] for i in range(1,num): if num%i==0: (i) if sum(arr)==num: print(num,arr) ''' Topic 020: A ball is dropped freely from a height of 100 meters, and each time it hits the ground it rebounds back to half its original height; then it falls again; find the total number of meters it passes by the time it hits the ground for the 10th time? How high does it rebound the 10th time? ''' def tm020(): ''' [Personal Remarks]: It's simple, not much to say. ''' total = 0 m = 100 # The first landing, after a hundred meters # total += m for i in range(10-1): # And then nine bounces to the ground m = m/2 # The height of the bounce total += 2*m # The total distance traveled to bounce up and back down # print(total) print(m/2) ''' Topic 021: Monkey eating peaches problem On the first day, a monkey picks a number of peaches, immediately eats half of them, and is not yet addicted to them, and eats one more The next morning he ate half of the remaining peaches and ate one more. Every morning after that, he ate half and one of the peaches left over from the previous day. On the 10th morning, when you tried to eat another peach, you saw that there was only one peach left. Find the total number picked on the first day. ''' def tm021(): ''' 【Personal Remarks】:tenth daynum=1classifier for individual things or people, general, catch-all classifier,Day nine is bound to be4classifier for individual things or people, general, catch-all classifier:4/2-1=1,i.e.(num+1)*2=4。 do this sort of thing,Let's start with an arithmetic equation.,Then just describe it in code。 ''' num = 1 for i in range(10-1): num = (num+1)*2 print(num) ''' Topic 022: Two table tennis teams play a match, each with three players. Team A has three players a,b,c and team B has three players x,y,z. Lots have been drawn to determine the playing roster. Someone asks the players about the match list. A says that he does not play against x. C says that he does not play against x,z. Program to find out the list of players for the three teams of the tournament. ''' def tm022(): ''' [Personal note]: The key is abstraction, abstracting the problem into a code approach. The way I solved the problem, I used a permutation and combination function, listed the options, and then eliminated them. And there is a pure for loop plus if solution inside the official answer. It's a bit more abstract, and uses a very common fixed paradigm, which is directly used to solve the problem. The abstract method is slightly annotated. ''' import itertools jia = ['a','b','c'] yi = ['x','y','z'] arr = list((yi,3)) # When facing Team A a,b,c, all of Team B's permutations [('x', 'y', 'z'), ('x', 'z', 'y'), ('y', 'x', 'z'), ('y', 'z', 'x'), ('z', 'x', 'y'), ('z', 'y', 'x')] arr = [[jia[i]+a[i] for i in range(3)] for a in arr] #Write a,b,c to get all pairwise combinations [['ax', 'by', 'cz'], ['ax', 'bz', 'cy'], ['ay', 'bx', 'cz'], ['ay', 'bz', 'cx'], ['az', 'bx', 'cy'], ['az', 'by', 'cx']] for i in arr: if 'ax' in i: pass elif 'cx' in i or 'cz' in i: pass else: print(i) # Got ['az', 'bx', 'cy'] def tm022_1(): for a in ['x','y','z']: # a pick one of x,y,z to hit for b in ['x', 'y', 'z']: # b Pick one of x, y, z to play # for c in ['x', 'y', 'z']: # c pick a hit in x,y,z three levels totaling 27 hits # if a!=b and b!=c and c!=a: # a,b,c can't pick the same guy Downsizing to six hits # if a!='x' and c!='x' and c!='z': # Can't ax,cx,cz be reduced to one play based on the meaning of the question # print('a'+a,'b'+b,'c'+c) ''' Title 023: Print out the following pattern (diamond shape):. * *** ***** ******* ***** *** * ''' def tm023(): ''' [personal note]: thinking of absolute values. Then turned [0,1,2,3,4,5,6] into [3,2,1,0,1,2,3], which is the number of spaces to the left of each line. ''' num = 7 for i in range(num): blank = abs(num//2-i) print(' '*blank+'*'*(num-2*blank)+' '*blank) ''' Topic 024: There is a sequence of fractions: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13... Find the sum of the first 20 terms of this sequence. ''' def tm024(): ''' There's nothing to say. ''' a,b,num = 2,1,0 for i in range(20): num+=a/b a=a+b b=a-b print(num) ''' Topic 025: Find the sum of 1+2!+3!+... +20! of the sum. ''' def tm025(): ''' [Personal note]: It's simple to implement. The official code, below, is more concise than what I wrote. ''' s,t=0,1 for n in range(1,21): t*=n s+=t print(s) ''' Topic 026: Using recursive methods to find 5! ''' def fac(x): if x>1: return x*fac(x-1) else: return x def tm026(): ''' 【Personal Remarks】:按title要求,formulasf(n)=n*f(n-1),Recursive call solving。 ''' print(fac(5)) ''' Topic 027: Print out the 5 characters entered, in reverse order, using recursive function calls. ''' def output(s,l): if l==0: return print (s[l-1]) output(s,l-1) def tm027(): ''' [Personal note]: copied directly from the official website, don't like recursion. ''' s = input('Input a string:') l = len(s) output(s,l) ''' Question 028: There are 5 people sitting together. Ask the fifth man how old he is. He says two years older than the 4th person. Ask the 4th man and he says he is 2 years older than the 3rd man. Ask the third man and he says he is two years older than the second man. Ask the second man, he says he is two years older than the first man. Finally, ask the first person and he says he is 10 years old. Ask the fifth person how old he is. ''' def age(x): if x>1: return 2+age(x-1) else: return 10 def tm028(): ''' [Personal note]: The official website gives the recursive method still, because it's a verbal math problem if you don't use recursion. ''' print(age(5)) ''' Topic 029: Given a positive integer with not more than 5 digits, it is required to: i) find how many digits it is, and ii) print the digits in reverse order. ''' def tm029(): ''' 【Personal Remarks】:expense or outlayPython,So Easy~ list倒序可以expense or outlay(); 字符串就只能expense or outlay步长=-1The way to reverse the order of the。 ''' num = 12345 s = str(num) print(len(s)) print(s[::-1]) ''' Topic 030: A 5-digit number, determine if it is an iambic number. That is, 12321 is an iambic number, the digit is the same as the 10,000 digit, and the tens digit is the same as the thousands digit. ''' def tm030(): ''' [Personal note]: not much to say. ''' num = 12321 s = str(num) for i in range(len(s)//2): if s[i]!=s[-i-1]: print(False) break else: print(True) ''' Question 031: Please enter the first letter of the day of the week to determine what day of the week it is, and if the first letter is the same, proceed to the second letter. ''' def tm031(): ''' [Personal Remarks]: Just follow the requirements of the question and realize it. ''' week = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'] inp = '' while 1: arr = [] inp = inp+input('Please enter a letter:') for day in week: # Pick out weeks that meet the inputs if inp==day[:len(inp)]: (day) if len(arr)==1: # Only one left, indicating uniqueness, can output results print('Words starting with %s are :%s'%(inp,arr[0])) inp='' elif len(arr)==0: # None of them means there's a mistake, you need to re-enter them. print('No words beginning with %s'%inp) inp='' ''' Topic 032: Output the values of a list in reverse order. ''' def tm032(): ''' [Personal Remarks]: It's been done before! ''' # Method I a = [1,2,3,4,5] print(a[::-1]) # Method II a = [1,2,3,4,5] () print(a) # Method III a = [1,2,3,4,5] (reverse=True) print(a) ''' Topic 033: Separate lists by comma. ''' def tm033(): ''' 【Personal Remarks】:一开始没看懂title项干啥,indirectlyprint(list)不就是逗号ingredient隔么 实际上title的意思是,Merge list items,comma-delimited ''' a = ['1','2','3','4','5'] print(','.join(a)) ''' Topic 034: Practicing function calls. ''' def tm034(): ''' [Personal Remarks]: A question with no beginning and no end, before the recursion is actually a function call. I'm not going to write about it. ''' pass ''' Topic 035: Text color settings. ''' def tm035(): ''' [Personal note]: doesn't feel like it's a python question or not. ''' pass ''' Topic 036: Finding prime numbers within 100. ''' def tm036(): ''' [Personal Remarks]: A prime number is a prime number. ''' arr = [2] for i in range(3,100): for j in arr: if i%j==0: break else: (i) print(arr) ''' Topic 037: Sorting 10 numbers. ''' def tm037(): ''' [Personal note]: actually examined the sorting. After speculating on the question, I wrote two solutions ''' # Method 1, python solution a = [1,5,7,3,2,4,9,10,6,8] () print(a) # Method 2, conventional solution a = [1,5,7,3,2,4,9,10,6,8] b = [a[0]] for num in a[1:]: for i in range(len(b)): if num<b[i]: (i,num) break else: (num) print(b) ''' Topic 038: Sum the main diagonal elements of a 3*3 matrix. ''' def tm038(): ''' [Personal note]: the idea is relatively simple, n*n matrices can be solved with this. ''' a = [[1,2,3],[4,5,6],[7,8,9]] s = 0 n = len(a) for i in range(n): # A line from upper left to lower right s+=a[i][i] for i in range(n): # A line from upper right to lower left s+=a[i][n-i-1] if n%2==1: # If it's an odd number, delete the double-counted midpoints s-=a[n//2][n//2] print(s) ''' Topic 039: There is an already ordered array. Now a number is entered and it is asked to insert it into the array in the original order. ''' def tm039(): ''' [Personal Remarks]: just written in question 037. ''' aaa = [1,5,8,14,28,39,60,89,134,324,612,900] b = 555 for a in aaa: if b<a: ((a),b) break else: (b) print(aaa) ''' Topic 040: Output an array in reverse order. ''' def tm040(): ''' [Personal Remarks]: it's question 032, repeated. ''' pass ''' Topic 041: Mimicking the use of static variables. ''' def tm041(): ''' [Personal note]: Not quite sure what it means, read the official website's answer directly. If it is a local variable in a function, it will be initialized every time the function is called. While variables in a class are initialized when the class is created, class variables are not initialized every time a function in the class is executed. It looks like it's trying to say something like this. ''' def varfunc(): var = 0 print('var = %d' % var) var += 1 if __name__ == '__main__': for i in range(3): varfunc() # StaticVar as a property of the class, equivalent to a static variable class Static: StaticVar = 5 def varfunc(self): += 1 print() print() a = Static() for i in range(3): () ''' Topic 042: Learning the usage of defining variables using auto. ''' def tm042(): ''' [Personal note]: Again, I didn't understand the question, so I looked at the answer on the official website and realized that it was actually about variable scopes. I found that the actual variable scope, python is divided into local variables, global variables, and other distinctions. I'm not sure I understand the question.'' num = 2 def autofunc(): num = 1 print('internal block num = %d'%num) num += 1 for i in range(3): print('The num = %d'%num) num += 1 autofunc() ''' The output of the above example is: The num = 2 internal block num = 1 The num = 3 internal block num = 1 The num = 4 internal block num = 1 ''' ''' Topic 043: Mimicking static variables (static) Another case. ''' def tm043(): ''' [Personal note]: the official website's answer is not much different from 041, and again ''' ''' title044:两classifier for individual things or people, general, catch-all classifier3*3matrices,Realize the addition of data at its corresponding position,并返回一classifier for individual things or people, general, catch-all classifier新矩阵: X = [[12,7,3], [ 4,5,6], [ 7,8,9]] Y = [[5,8,1], [ 6,7,3], [ 4,5,9]] ''' def tm044(): ''' [Personal note]: wrote one myself, but I was under the impression that python has a matrix calculation tool. The official website on someone with that tool numpy wrote about it, very concise. ''' x = [[12,7,3],[4,5,6],[7,8,9]] y = [[5,8,1],[6,7,3],[4,5,9]] z = x[:] for i in range(3): for j in range(3): z[i][j]=x[i][j]+y[i][j] print(z) def tm044_1(): import numpy # pip install numpy Required modules x = ([[12,7,3],[4,5,6],[7,8,9]]) y = ([[5,8,1],[6,7,3],[4,5,9]]) z = x+y print(z) ''' Topic 045: Counting sums from 1 to 100. ''' def tm045(): ''' [Personal note]: simple, but someone on the official website wrote it even simpler ''' s = 0 for i in range(1,101): s+=i print(s) # A more concise approach print(sum(range(1,101))) ''' Topic 046: Find the square of an input number and exit if the square operation is less than 50. ''' def tm046(): ''' [Personal Remarks]: Simple ''' while 1: x= input('Enter a number to get the square value:') print(x*x) if x*x<50: break ''' Topic 047: Swapping two variable values. ''' def tm047(): ''' [Personal Remarks]: It's simple ''' a,b=1,2 a,b=b,a print(a,b) ''' Topic 048: Comparison of numbers. ''' def tm048(): ''' [Personal note]: took a look at the official website answer, which is so simple that I'm too lazy to write it. The following official website answer. ''' i = 10 j = 20 if i > j: print('%d greater than %d' % (i,j)) elif i == j: print('%d equals %d' % (i,j)) elif i < j: print('%d less than %d' % (i,j)) else: print('Unknown') ''' Topic 049: Using lambda to create anonymous functions. ''' def tm049(): ''' [Personal Remarks]: Not used much and forgotten, looked at the online tutorials and organized them. ''' A #lambda function is also called an anonymous function, i.e., the function has no specific name. Let's look at the simplest example first: def f(x): return x**2 print(f(4)) #With lambda in Python, write it like this g = lambda x:x**2 print(g(4)) The raison d'être of #lambda is the concise representation of simple functions. #lambda statement with parameters before the colon, which can be more than one, separated by commas, and the return value to the right of the colon. # Often paired with built-in functions map, filter, reduce, are built-in functions applied to sequences. Common sequences include list, tuple, str. #map(func, *iterables) --> map object #filter(function or None, iterable) --> filter object #reduce(function, sequence[, initial]) -> value foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] print(list(map(lambda x: x * 2 + 10, foo))) # Mapping [14, 46, 28, 54, 44, 58, 26, 34, 64] print(list(filter(lambda x: x % 3 == 0, foo))) # Filter [18, 9, 24, 12, 27] from functools import reduce # In Python 3, the reduce() function has been removed from the global namespace, and is now placed in the fucntools module. print(reduce(lambda x, y: x + y, foo)) # Cumulative 139 ''' Topic 050: Output a random number. ''' def tm050(): ''' [Personal note]: Before learning random when organizing things, use to time to find on the line! ''' import random # Random number operations () # 0.85415370477785668 # Randomize a float between [0,1) (0, 100) # 18.7356606526 # Randomize a floating-point number between [0,100] (0, 100, 2) # 44 # Randomize an even number between [0,100) (0, 100) # 22 # Randomize an integer between [0,100] # Random character manipulation seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+=-" # Arbitrary strings (as random character seed banks) (seed) # 'd' # A random character (seed, 3) # ['a', 'd', 'b'] # Randomize multiple characters (characters can be repeated) ''.join((seed,3)) # '^f^' # Random string of specified length (characters can be repeated) # Random list operations (list) # List elements are broken up ''' Topics 051 to 053 and 055: Learning to use press-and & Learning to use per-position or | Learning to use bitwise or ^ Learning to use inverse by bit ~ ''' def tm051(): # tm052 # tm053 # tm055 ''' [Personal note]: probably read the information, bitwise operation can be realized by bin () function to convert to binary. Feel the binary calculation if not learning encryption and so on basically can not be used. So this question, probably write the use of the set, &, | in python is a set set () only with the symbols The intersection and union of two lists is also usually converted to a set and then computed. ''' # Iterable variables converted to set form x = set('runoob') y = set('google') print(x, y) # Duplicates removed {'n', 'o', 'b', 'u', 'r'} {'o', 'g', 'e', 'l'} # Intersection, union, difference of sets print(x & y) # Intersection {'o'} print(x | y) # Concatenate {'e', 'o', 'g', 'l', 'u', 'n', 'b', 'r'} print(x - y) # Difference sets {'n', 'b', 'u', 'r'} # can of course be written in function form, but it's really not as memorable as the above notation. print((y)) print((y)) print((y)) ''' Topic 054: Take an integer a in bits 4-7 from the right end. ''' def tm054(): ''' [Personal Remarks]: the official website answer is not correct ''' a = 123456789 b = str(a) print(b[-7:-3]) # When you write it, note that the python slice is [-7:-4)left-closed-right-open, and doesn't contain [-4], so you'll have to write it as -3 to get the ''' Topic 056: Drawing, learning to draw circles with CIRCLE. Topic 057: Drawing a line. Topic 058: Drawing, learning to draw a square with a rectangle. Topic 059: Drawing and synthesizing examples. Topic 063: Drawing ellipses. Topic 064: Drawing with ellipse and rectangle. Topic 065: A most graceful pattern. All drawing questions pass Love to refer to the following yourself, change the official website answer to python3 run can be. ''' def tm056(): # tm057、tm058、tm059、tm063、tm064、tm065、 ''' [Personal note]: This skill doesn't feel like it can be used. I copied the Python2 answer from the official website and adjusted it to run successfully on python3. ''' import tkinter canvas = (width=600, height=500, bg='yellow') (expand='yes', fill='both') k = 1 j = 1 for i in range(0,26): canvas.create_oval(300 - k,250 - k,300 + k,250 + k, width=1) k += j j += 0.6 () ''' Topic 060: Calculating string length. ''' def tm060(): ''' [Personal Remarks]: None ''' a = 'aegweg' print(len(a)) ''' Topic 061: Print out the Yang Hui triangle (10 lines are required as shown below). 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 The following is a summary of the information contained in the report of the Committee on Conventions and Recommendations.'' def tm061(): ''' [Personal note]: I feel that my own writing is simpler and better understood than the official website ''' arr = [1] print(1) while len(arr)<10: # [1,1] a = [0]+arr # [0,1,1] b = arr+[0] # [1,1,0] arr = [a[i]+b[i] for i in range(len(a))] # [1,2,1] s = [str(i) for i in arr] print(' '.join(s)) ''' Topic 062: Finding strings. ''' def tm062(): s = 'abcde' print(('c')) ''' Topic 066: Input 3 numbers a,b,c and output them in order of magnitude. ''' def tm066(): arr=[] for i in range(3): a = input('Please enter the number:') (int(a)) (reverse=True) print('From big to small',arr) ''' Topic 067: input array, exchange the largest with the first element and the smallest with the last element, output the array. ''' def tm067(): ''' [Personal note]: I feel that I wrote it easier and better than the official website, and it's really convenient to write it directly with python thinking! ''' a = [6,3,10,2,5,1,4,7,9,8] i = (max(a)) a[0],a[i] = a[i],a[0] i = (min(a)) a[-1],a[i] = a[i],a[-1] print(a) ''' Topic 068: There are n integers such that the order of the preceding numbers is shifted backward by m positions, and the last m numbers become the top m numbers ''' def tm068(): a = [1,2,3,4,5,6,7,8,9,10] m = 3 b = a[-m:]+a[:-m] print(b) ''' Topic 069: There are n people in a circle, numbered in order. Starting with the first person to report the number (report the number from 1 to 3), anyone who reports 3 exits the circle, and ask who is left at the end who was originally numbered. ''' def tm069(): ''' [Personal note]: python base variables don't have this kind of circle loop. The most direct way is a list, tap the end of the queue and start from the beginning. The disadvantage is that the list removes the middle item, and all the index values behind it change and need to be calculated. So I've switched to a different approach. Abstract the problem as a queue to enter the door Disregard the indexing problem altogether. ''' # Initialization n = 34 arr = list(range(1,n+1)) # All men stand in a line outside the door [a], and when they enter the door, they remain in order [b]. count,a,b = 0,arr,[] # Start solving the problem while len(a+b)>1: # Cycle until there's only one left num,count=(0),count+1 # Line up to enter the door. For each person [ ], press the counter. if count%3!=0:(num) # Entering the door and still standing in order [ ], the counter is eliminated at 3. if a==[]:a,b=b,[] # If there's no one left at the door [a=[]], everyone get back to standing outside the door [a=b] print(a[0]) ''' Topic 070: Write a function to find the length of a string, input the string in the main function and output its length. ''' def tm070(): ''' [Personal Remarks]: Simple ''' def getlength(string): return len(string) if __name__ == '__main__': x = 'abcde' print(getlength(x)) ''' Topic 071: Write input() and output() functions to input, output data records of 5 students. ''' def tm071(): ''' [Personal Remarks]: write whatever you want with the dictionary type ''' def inp(data): name = input('Enter student name:') score = input('Enter student grades:') data[name]=score print('Successful entry') return data def outp(data): name = input('Enter student name:') print('The student's grades are:',(name)) return data if __name__ == '__main__': data = {} while 1: a = input('importation/Exporting student grades(i/o):') if a=='i': data = inp(data) elif a=='o': data = outp(data) else: print('Incorrect input value') ''' Topic 072: Creating a chained table. Topic 073: Reverse output of a chained table. ''' def tm072(): ''' [Personal note]: I'd almost forgotten about chained tables, and after searching the web I finally remembered what they were. There's no need to use python to simulate this kind of underlying stuff. /nForum/#!article/Python/73818?p=10 ''' pass ''' Topic 074: List sorting and concatenation. Topic 079: String sorting. (It's the same.) ''' def tm074(): # tm079 ''' [Personal Remarks]: Used them all before. ''' a = [3,2,1] b = [4,5,6] () print(a) print(a+b) ''' Topic 075: Relax and count a simple question. ''' def tm075(): ''' [Personal note]: Σ( ° △ °|||)︴, it's not that I'm cutting corners, the title is this one, and it's too much in the back ''' pass ''' Topic 076: Write a function that, when the input n is even, calls the function to find 1/2+1/4+... +1/n, when input n is odd, call the function 1/1+1/3+... +1/n ''' def tm076(): ''' [Personal note]: I learned lambda to juggle a bit, and realized that the official website is written more succinctly than I am! ''' n =17 fenmu = range(2,n+1,2) if n%2==0 else range(1,n+1,2) s = sum(map(lambda x:1/x,fenmu)) print(s) # Official website reference answer n =17 ls = sum([1/i for i in range(n,0,-2)]) print(ls) ''' Topic 077: Loop output list ''' def tm077(): ''' [Personal Remarks]: No brain required ''' l = [1,2,3,4,5] for i in l: print(i) ''' Topic 078: Find the oldest person and output. person = {"li":18, "wang":50, "zhang":20, "sun":22} ''' def tm078(): ''' [Personal note]: the official website has basically the same answer. ''' person = {"li":18,"wang":50,"zhang":20,"sun":22} name,age='',0 for p in (): if (p)>age: name,age=p,(p) print(name,age) ''' Topic 080: There is a pile of peaches on the beach and five monkeys to divide them. The first monkey divides the pile of peaches into five equal parts, and has one extra. This monkey throws the extra one into the sea and takes a share. The second monkey divides the rest of the peaches into five equal parts, and there is one more. Again, he throws the extra one into the sea and takes a share. The third, fourth and fifth monkeys do the same. Ask at least how many peaches were originally on the beach? ''' def tm080(): ''' [Personal note]: Disregarding solving equations and whatnot, the problem actually boils down to "Integer n, iterate 5 times and get an integer each time, find the minimum value of n". At first, I thought it was simple, I thought the last monkey only took one, and I found that it was not an integer when I substituted it in. So the direct violence of input, one by one until 3121, get the integer division. Of course, you can also try the opposite, assuming that the last monkey to get n peaches, remove = lambda t:t/4*5+1. Trying one by one until 1020 and getting an integer division also leads to the conclusion that the very first monkey got 3121 peaches. ''' for total in range(10000): t = total # There's t peaches on the beach # remain = lambda t:(t-1)/5*4 # Peaches remaining after each split. for i in range(5): t = remain(t) if t%1!=0:break # If it's not an integer, it's not true else: print(total,t) # 5 times you get a whole number, 3121 for the first monkey, and 1020 left over after five monkeys take the beach. break ''' Title 081: 809*???? =800*?? +9*?? where ???? represents a two-digit number. 809*?? is a four-digit number, 8*?? results in two digits, and 9*?? results in 3 digits. Find the two-digit number represented by ? represents a two-digit number, and the result after 809*??? and the result after 809*? ''' def tm081(): ''' Suppose ??? for x, because 8*x<100, gives x<13. In fact, because 9*x>100 gives x>11, it is clear that x is 12, and the question is given too fully. The program is as follows: ''' l = lambda x:len(str(x)) for i in range(20): if l(809*i)==4 and l(8*i)==2 and l(9*i)==3: x = i print(x) print(809*x==800*x+9*x) print(809*x) ''' Topic 082: Converting Octal to Decimal ''' def tm082(): ''' [Personal note]: knowing this, feel free to spin it. ''' print(bin(10)) #10 to #2 print(oct(10)) #10 turns 8 print(hex(10)) #10 to 16 print(int('10',8)) #8 turn 10 print(int('10',2)) #2 to 10 print(int('10',16)) #16 to 10 ''' Topic 083: Find the number of odd numbers that can be formed from 0-7. ''' def tm083(): ''' [Personal note]: Doesn't say how many digits are formed or whether they are reused. Assuming 1-8 digits are fine and cannot be reused. Use the permutation function directly, add up and then de-duplicate, and you've got your answer. ''' s = [i for i in '01234567'] import itertools arr = [] for i in range(1,9): a = list((s,i)) # Lengths 1-8 aligned left to right l = list(map(lambda x:int(''.join(x)),a)) # Organized into numerical form (avoiding cases like 02, which is actually 2) arr+=l print(i,len(l)) arr1 = set(arr) # De-duplication arr2 = list(filter(lambda x:x%2==1,arr1)) # Leave only odd numbers print(len(arr),len(arr1),len(arr2)) # The answer is 46972 def tm083_1(): ''' [Personal note]: Because I don't know if it's right or wrong, I verified it again with the exhaustive verification method. ''' count = 0 for i in range(76543211): # The biggest number that can be formed is 76543210 # s = str(i) # Converted to text form s if '8' in s or '9' in s: # 8 and 9 are not included in s continue else: cs = set([c for c in s])# s in the number of de-emphasis, if the de-emphasized and de-emphasized before the length of the same, that is, the number is not reused if len(s)==len(cs) and s[-1] in '1357': # Each of you has no duplicates and is an odd number count+=1 if i%100000==0:print(i,count) # Output the results every 100,000 to avoid the program getting stuck and not being able to find out. print(count) # The company's computer is worse, ran for more than 2 minutes, also out of the results of 46972. ''' Topic 084: Concatenating strings. ''' def tm084(): ''' [Personal note]: The usage of join has been used many times before ''' pass ''' Topic 085: Enter an odd number, then determine the least number of 9's that divide that number to result in an integer. ''' def tm085(): ''' [Personal note]: Just try them one by one until they are divisible. ''' x = int(input('input a number:')) for i in range(1,61): if int('9'*i)%x==0: print(i) break else: print('no way') ''' Topic 086: Two string concatenation programs. ''' def tm086(): # Just '+' it. pass ''' Topic 087: answering results (structure variable passing). ''' def tm087(): ''' No topic, no work. ''' pass ''' Topic 088: Read 7 numbers (1-50) of integer values, for each value read, the program prints the * of the number of values. ''' def tm088(): # There's nothing to say for i in [1,4,5,14,22]: print('*'*i) ''' Topic 089: A company uses a pay phone to transmit data, which is a four-digit integer. It is encrypted during transmission and the encryption rules are as follows: Add 5 to each digit, then replace that digit with the remainder of the sum divided by 10, then exchange the first and fourth digits, and the second and third digits. ''' def tm089(): x,c = 1234,5 q,b,s,g = x//1000,x//100%10,x//10%10,x%10 s = (g+c)%10*1000+(s+c)%10*100+(b+c)%10*10+(q+c)%10 print(s) ''' Topic 090: Examples of list usage. ''' def tm090(): # No specific requirements pass ''' Topic 091: Example of the time function 1. Topic 092: Example of the Time Function 2. Topic 093: Examples of Time Functions 3. Topic 095: Converting a String Date to an Easy-to-Read Date Format. Title 095: Converting String Dates to Readable Date Format.'' def tm091(): #tm092、tm093、tm095 # See tm016 pass ''' Topic 094: Example 4 of a function of time, a guessing game to determine how quickly a person reacts. ''' def tm094(): import time,random print('"Guess the size between 0-1000"') x = (0,1000) flag = input('Whether or not to start(y/n):') if flag=='y': s = () while 1: m = int(input('Please enter the number:')) if m>x: print('Bigger') elif m<x: print('Smaller') else: print('bingo!') break e = () print('Took %.2f seconds'%(e-s)) print((5)) ''' Topic 096: Counting the number of occurrences of a substring in a string. ''' def tm096(): ''' [Personal note]: Just use count! ''' x = 'ababaabbaaa' print(('ab')) ''' Topic 097: Enter some characters from the keyboard and write them to a disk file one by one until you enter a # To end. ''' def tm097(): ''' [Personal note]: A way to save the file, just remember it. with ... as ... Open will be closed automatically. Other ways to open, don't forget to close by code. ''' path = 'd:/' with open(path,'w+') as f:('') while 1: c = input() if c=='#': break else: with open(path,'a+') as f:(c) ''' Topic 098: Input a string from the keyboard, convert all lowercase letters to uppercase, and then output it to a disk file "test" for saving. ''' def tm098(): ''' [Personal Remarks]: String capitalization ''' c = input() c = () with open('d:/','w+') as f:(c) ''' Topic 099: There are two disk files A and B, each storing a line of letters, and it is required to merge the information in these two files (in alphabetical order), and output them to a new file C. ''' def tm099(): ''' [Personal Remarks]: Reading and writing files ''' with open('d:/','r+') as f:a=() with open('d:/','r+') as f:b=() with open('d:/','w+') as f:(a+b) ''' Topic 100: List to dictionary conversion. ''' def tm100(): ''' [Personal note]: finally the last question is done~, not much to say. ''' l = ['ak17','b51','b52','#64'] d = {} for i in range(len(l)): d[i]=l[i] print(d) # Get: {0: 'ak17', 1: 'b51', 2: 'b52', 3: '#64'} def tm100_1(): # Easier with the zip function l = ['ak17','b51','b52','#64'] print(dict(zip(range(4),l))) # Get: {0: 'ak17', 1: 'b51', 2: 'b52', 3: '#64'}
This is the entire content of this article.