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

What are the exercises in Python?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces what Python exercises have, which can be used for reference by interested friends. I hope you will gain a lot after reading this article. Let the editor take you to know it.

The first question

Def accum (s):

# write your code and output the result

# accum ("abcd") # "A-Bb-Ccc-Dddd"

# accum ("cwAt") # "C-Ww-Aaa-Tttt"

This to the title of the string of all letters in uppercase and all letters in lowercase and string concatenation, copy, the functions used are json the contents of the list in accordance with the specified characters concatenated into a string, upper () all letters in uppercase and lower () all letters lowercase, with the built-in function enumerate return value is the index and the corresponding value.

For an iterable (iterable) / traverable object (such as list, string), enumerate forms it into an index sequence, which can be used to obtain both index and value.

Enumerate is mostly used to get a count in a for loop.

The specific code is as follows

Def asuum (s):

Return'- '.join (y.upper () + y.lower () * x for xrecoy y in enumerate (s))

A = asuum ('abcd')

Print (a)

Second question

Def get_sum (aformab):

# write code and output results

# get_sum (1,0) = = 1 / / 1 + 0 = 1

# get_sum (1,2) = = 3 / / 1 + 2 = 3

# get_sum (0,1) = = 1 / / 0 + 1 = 1

# get_sum (1,1) = = 1 / / 1 Since both are same

# get_sum (- 1,0) =-1 / /-1 + 0 =-1

# get_sum (- 1,2) = = 2 / /-1 + 0 + 1 + 2 = 2

The minimum and maximum values min () and max () are used.

And the summation function sum ()

The specific implementation is made up of the following code

Def get_sum (aformab):

Return sum (range (min (arecom b), max (arecom b) + 1))

A = get_sum (2mai Mi 9)

The third question

Def duplicate_count ():

# write code that requires the following functions to give you a string of characters you want to return the number of repeated letters including the size

# test.assert_equals (duplicate_count ("abcde"), 0)

# test.assert_equals (duplicate_count ("abcdea"), 1)

# test.assert_equals (duplicate_count ("indivisibility"), 1)

It involves converting all the letters to lowercase, collections, and lists.

The code is as follows

Def duplicate_count (text):

# Your code goes here

Text = text.lower ()

Texts = set (text)

Lists = []

For i in texts:

Numbers = text.count (I)

If numbers! = 1:

Lists.append (numbers)

Return len (lists)

Question 4

Def likes ():

# enter the code to implement the following

#

# likes [] / / must be "no one likes this"

# likes ["Peter"] / / must be "Peter likes this"

# likes ["Jacob", "Alex"] / / must be "Jacob and Alex like this"

# likes ["Max", "John", "Mark"] / / must be "Max, John and Mark like this"

# likes ["Alex", "Jacob", "Mark", "Max"] / / must be "Alex, Jacob and 2 others like this"

This method is a bit ruthless, mainly using only points, that is, lists and len () functions.

The specific code is as follows

Def likes (names):

# your code here

If names:

If len (names) = = 1:

Return names [0] + 'likes this'

Elif len (names) = = 2:

Return names [0] + 'and' + names [1] + 'like this'

Elif len (names) = = 3:

Return names [0] +','+ names [1] + 'and' + names [2] + 'like this'

Else:

Return names [0] +','+ names [1] + 'and' + str (len (names)-2) + 'others like this'

Else:

Return'no one likes this'

Question 5

Your task is to create a function that takes any non-negative integer as an argument and returns it as a descending number. Basically, rearrange the numbers to create the highest possible numbers.

Example:

Input: 21445 output: 54421

Input: 145263 output: 654321

Input: 1254859723 output: 9875543221

It uses the sorting of lists, from large to small, and type conversion.

The Great God Code

Def Descending_Order (num):

Return int ("" .join (sorted (str (num), reverse=True)

My code

Def Descending_Order (num):

# Bust a move right here

Nums = list (str (num))

Nums.sort (reverse=True)

Return int ('.join (nums))

Question 6

Given: an array containing a name hash

Return: a string in the form of a comma-separated list of names, separated by a hyphen except for the last two names.

Example:

Namelist ([{'name':' Bart'}, {'name':' Lisa'}, {'name':' Maggie'}])

# returns' Bart, Lisa & Maggie'

Namelist ([{'name':' Bart'}, {'name':' Lisa'}])

# returns' Bart & Lisa'

Namelist ([{'name':' Bart'}])

# returns' Bart'

Namelist ([])

# returns''

This mainly uses the knowledge of lists and strings.

Def namelist (names):

# your code here

If len (names) > 1:

Return'{} & {} '.format (', '.join (I [' name'] for i in names [:-1]), names [- 1] ['name'])

Elif len (names) = = 1:

Return names [0] ['name']

Else:

Return''

Question 7

In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for the sake of simplicity, are named with letters from a to m.

The colors used by the printer are recorded in a control string. For example a "good" control string would be aaabbbbhaijjjm meaning that the printer used three times color a, four times color b, one time color h then one time color a

Sometimes there are problems: lack of colors, technical malfunction and a "bad" control string is produced e.g. Aaaxbbbbyyhwawiwjjjwwm.

You have to write a function printer_error which given a string will output the error rate of the printer as a string representing a rational whose numerator is the number of errors and the denominator the length of the control string. Don't reduce this fraction to a simpler expression.

The string has a length greater or equal to one and contains only letters from ato z.

# Examples:

S = "aaabbbbhaijjjm"

Error_printer (s) = > "0ram 14"

S = "aaaxbbbbyyhwawiwjjjwwm"

Error_printer (s) = > "8DB 22"

To put it simply, you are asking you to prove whether these strings are in abcdefghijkml' or not.

My code is as follows

Def printer_error (s):

# your code

A = 0

For i in range (0jinlen (s)):

If's [I] not in 'abcdefghijklm':

A + = 1

Return'{} / {} '.format (str (a), len (s)

The Great God solution

From re import sub

Def printer_error (s):

Return "{} / {}" .format (len (sub ("[Amurm]",', s)), len (s))

# he uses the replacement sub of strings here

Let's talk about the use of sub.

Detailed explanation of each parameter of re.sub

Re.sub has five parameters.

Re.sub (pattern, repl, string, count=0, flags=0)

Three of the required parameters: pattern, repl, string

Two optional parameters: count, flags

First parameter: pattern

Pattern, which represents the pattern string in the regular, there is not much to explain.

Second parameter: repl

Repl, which means replacement, is the string that is replaced.

Repl can be either a string or a function.

Repl is a string

If repl is a string, any backslash escape characters in it will be processed.

That is:

\ n: will be processed as the corresponding newline character

\ r: will be treated as a carriage return

Other unrecognized transfer characters are only recognized as ordinary characters:

For example,\ j will be treated as the letter j itself.

The backslash plus g and the name in parentheses, namely:\ g, corresponds to the named group, named group.

The third parameter: string

String, which represents the string string to be processed and replaced.

There's nothing special to explain.

Question 8

Convert to binary

Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.

The binary number returned should be a string.

Require output result

Test.assert_equals (add_binary (1, 1), "10")

Test.assert_equals (add_binary (0Pol 1), "1")

Test.assert_equals (add_binary (1J0), "1")

Test.assert_equals (add_binary (2), "100")

Test.assert_equals (add_binary (51 and 12), "111111")

The specific implementation code is as follows

Def add_binary (aformab):

Return bin (ahumb) .lstrip ('0b')

Something simpler.

Def add_binary (a, b):

Return format (a + b,'b')

Question 9

Write Number in Expanded Form

You will be given a number and you will need to return it as a string in Expanded Form. For example:

Expanded_form (12) # Should return'10 + 2'

Expanded_form (42) # Should return'40 + 2'

Expanded_form (70304) # Should return '70000 + 300 + 4'

The code is as follows

Def expanded_form (num):

Nums = str (num)

X = []

For i in range (0jinlen (nums)):

If int (Nums [I])! = 0:

S = str (int (nums [I]) * (10 * * (len (nums)-I-1)

X.append (s)

Return'+ '.join (x)

First convert the number to a string

Then create an empty list

Loop the length of this string

Then judge whether his string has 0 or not.

If there is no 0, it is calculated that the number of digits is based on the length of the character, as if 78 is about to output 7 * 10 "1 8" 10 "0.

Finally add to the list

Then the splicing of the string should pay attention to the space of the string.

Question 10

My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried because each month a list with the weights of members is published and each month he is the last on the list which means he is the heaviest.

I am the one who establishes the list so I told him: Don't worry any more, I will modify the order of the list. It was decided to attribute a "weight" to numbers. The weight of a number will be from now on the sum of its digits.

For example 99 will have "weight" 18,100 will have "weight" 1 so in the list 100 will come before 99. Given a string with the weights of FFC members in normal order can you give this string ordered by "weights" of these numbers?

Example:

"56 65 74 100 99 68 86 180 90" ordered by numbers weights becomes: "100 180 90 56 65 74 68 86 99"

When two numbers have the same "weight", let us class them as if they were strings and not numbers: 100 is before 180 because its "weight" (1) is less than the one of 180 (9) and 180 is before 90 since, having the same "weight" (9) it comes before as a string.

All numbers in the list are positive numbers and the list can be empty.

To the point, it is mainly about the weight of numbers.

That is to say, the sum of numbers

Order_weight ("2000 10003 1234000 44444444 9999 11 11 22 123"), "11 11 2000 10003 22 123 1234 000 4444 44 9999")

For example, 2000 is 2 10003, which is 4, which is the sum of these numbers.

My idea is to use the function sorted () according to this set of numbers.

The code is as follows

Def order_weight (strng):

# your code

Return'. Join (sorted (sorted (strng.split ('')), key = lambda x:sum (int (c) for c in x)

First cut this number, then use lambda to calculate the cumulative sum of this number, and sort according to the cumulative sum.

Question 11

Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number.

Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case

# this problem is to calculate binary numbers. 1 the number of occurrences

Def countBits (n):

S = lambda x: sum (int (z) for z in x)

Return s (format (n,'b'))

What I use here is cumulative sum.

There's a simpler way.

Def countBits (n):

Return format (n,'b'). Count ('1')

Question 12

Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.

Examples

"()" = > true

") (())" = > false

"(" = > false

"(()) (() ()) ()" = > true

# parenthesis question to determine whether it is a valid empty number

Def valid_parentheses (string):

# your code here

Cnt = 0

For i in string:

If I = "(": cnt+=1

If I = ")": cnt-=1

If cnt < 0: return False

Return True if cnt = = 0 else False

Thank you for reading this article carefully. I hope the article "what are the Python exercises" shared by the editor will be helpful to everyone? at the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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