SoFunction
Updated on 2024-11-17

Python inverts operations that output positive integers

Title:

Gets an input positive integer N and inverts the output of that positive integer, disregarding exceptions.

Input format: Enter a positive integer

output format : output a positive integer

Question:

Why did both of my answers fail the Python Level 2 Online Review test?

My answer one:

num_str = input('Please enter a positive integer:')
# Calculate positive integer digits
num_len = len(num_str)#.count() method is not suitable'
# Method 1
for i in range(-1,-1-num_len,-1):
 print(num_str[i],end='')

My answer two:

num_str = input('Please enter a positive integer:')
# Calculate positive integer digits
num_len = len(num_str)The #.count() method is not suitable for the
new_str = ''
for i in range(-1,-1-num_len,-1):#range(5) is equivalent to range(0,5,1)
 new_str += num_str[i]
print(new_str)

The correct answer is here:

It was me who desecrated the simple and beautiful Python...

#String reversal
s_reverse = s[::-1]

Addendum: Beginning python miscellany - number reversal

Input an integer and output the integer as a string in reverse order.

The program does not take into account the case of negative numbers, if the number contains 0, the inverse form also contains 0, such as the input is 100, the output is 001

print(input()[::-1])

Or:

a=input()
s=str(a)
lis=[]
for i in s:
 (i)
()

print(''.join(lis))

Function Description:

[x:y:z] takes values every z in the (x, y) interval, z defaults to 1.

[::-1] Indicates reverse value.

The str() function converts an object to a string.

grammatical

The following is the syntax of the str() method.

class str(object=”)

parameters

object - an object.

return value

Returns an object in string format.

an actual example

The following shows an example of using the str() method:

s = ‘RUNOOB'
str(s)
‘RUNOOB'
dict = {‘runoob': ‘', ‘google': ‘'};
str(dict)
“{‘google': ‘', ‘runoob': ‘'}”

The Python join() method is used to concatenate the elements of a sequence with the specified characters to create a new string.

(sequence)

parameters

sequence - The sequence of elements to concatenate.

return value

Returns the new string generated by concatenating the elements of the sequence with the specified characters.

The following example shows how join() is used:

an actual example

str = “-“;
seq = (“a”, “b”, “c”); # String sequences
print ( seq );

The output of the above example is as follows: a-b-c

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more. If there is any mistake or something that has not been fully considered, please do not hesitate to advise me.