My aim is to be able to input a large (6 digit) number into a terminal and for it to return the middle two digits, swapped.
My code is as follows:
a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
f = int(input())
addition = ((a * 0) + (b * 0) + (d * 10))
addition_two = ((c) + (e * 0) + (f * 0))
print(addition + addition_2)
I'm unsure of how to adjust this in order for it to work correctly.
I don't understand all the complexity. If you only want the middle two digits (and they're swapped), you can simply use:
n = input("Enter number: ")
ans = n[2:4]
return int(ans) //if you want int type, else ans would suffice as str
Ask for inputs until it is 6 long and only consists of digits. there is no need to convert anything to a number, you can work with the string directly by slicing it correctly:
while True:
k = input("6 digit number")
if not all(c.isdigit() for c in k) or len(k) != 6:
print("Not a six digit number")
else:
break
# string slicing:
# first 2 letters
# reversed 4th and 3rd letter
# remaining letters
print(k[:2] + k[3:1:-1] + k[4:])
See Asking the user for input until they give a valid response and Understanding slice notation
Related
I need help with this Python program.
With the input below:
Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
the program must output:
Output: 54321
My code is:
n = 0
t = 1
rev = 0
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
a = n % 10
rev = rev * 10 + a
n = n // 10
print(rev)
Its output is "12345" instead of "54321".
What should I change?
try this:
t = 1
rev = ""
while(t <= 5):
n = input("Enter a number:")
t+=1
rev = n + rev
print(rev)
Try:
x = [int(input("Enter a number")) for t in range(0,5)]
print(x[::-1])
There could be an easier way if you create a list and append all the values in it, then print it backwards like that:
my_list = []
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
my_list.append(n)
my_list.reverse()
for i in range(len(my_list)):
print(my_list[i])
You can try this:
n = 0
t = 1
rev = []
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
rev.append(n)
rev.reverse()
rev = ''.join(str(i) for i in rev)
print(rev)
Maintaining a numerical context: use "10 raised to t" (10^t)
This code is not very different from your solution because it continues to work on integer numbers and return rev as an integer:
t = 0
rev = 0
while (t < 5):
n = int(input("Enter a number:"))
# ** is the Python operator for 'mathematical raised to'
rev += n * (10 ** t)
t += 1
print(rev)
(10 ** t) is the Python form to do 10^t (10 raised to t); in this context it works as a positional shift to left.
Defect
With this program happens that: if you insert integer 0 as last value, this isn't present in the output.
Example: with input numeric 12340 the output is the number 4321.
How to solve the defect with zfill() method
If you want manage the result as a string and not as a integer we can add zeroes at the start of the string with the string method zfill().
In this context the zfill() method fills the string with zeros until it is 5 characters long.
The program with this modification is showed below:
NUM_OF_INTEGER = 5
t = 0
rev = 0
while (t < NUM_OF_INTEGER):
n = int(input("Enter a number: "))
rev += n * (10 ** t)
t += 1
# here I convert the number 'rev' to string and apply the method 'zfill'
print(str(rev).zfill(NUM_OF_INTEGER))
With previous code with input "12340" the output is the string "04321".
n = int(input("How many number do you want to get in order? "))
list1 = []
for i in range(n):
num = int(input("Enter the number: "))
thislist = [num]
list1.extend (thislist)
list1.sort()
print ("The ascending order of the entered numbers, is: " ,list1)
list1.sort (reverse = True)
print ("The descending order of the entered numbers, is: " ,list1)
I'm writing a program that accepts as input a 9 digit number with each number from 1-9 (i.e 459876231) The program takes that number and then finds the next highest number with the same digits. The code I have works, but only when I put the print statement within the for loop.
n = int(input("Please input a 9 digit number"))
n_str = str(n)
n_str1 = str(n+1)
while n < 1000000000:
for char in n_str:
if not char in n_str1:
n += 1
n_str1 = str(n)
print(n)
If I put don't indent the print statement to where it is now, the program will not work. Putting the print statement here also displays every number that the program tries on the way to the correct number, and I only want to display the final answer. Why is this happening? I've tried storing n in a completely new variable and then trying to print outside the loop but get the same thing.
It's because if you do n += 1, n will be 1, then 2, 3.., so you need to print n every time. If you print n outside of the for, it will only print its last value.
Your code is fixed like:
n = int(input("Please input a 9 digit number: "))
n_str = str(n)
n_str1 = str(n+1)
while n < 1000000000:
found = True
for char in n_str:
if not char in n_str1:
n += 1
n_str1 = str(n)
found = False
break
if found:
print(n)
break
There is a bug in your condition
for char in n_str:
if not char in n_str1:
If input number is 333222323, n_str1 is 333222324, digit check char in n_str1 would be all true and 333222323 would be the result.
I find the LeetCode problem 31. Next Permutation is quite similar to your question, and there are already many recommended solutions, most are more efficient than yours.
This example code is based on my LeetCode answer:
nstr = input("Please input a 9 digit number: ")
nums = [int(c) for c in nstr]
l = len(nums) # length should be 9
for i in range(l-2, -1, -1):
swap_idx, swap_n = None, None
for j in range(i+1, l):
if (nums[i] < nums[j]) and (not swap_n or (nums[j] < swap_n)):
swap_idx, swap_n = j, nums[j]
if swap_idx:
tmp = nums[i]
nums[i] = nums[swap_idx]
nums[swap_idx] = tmp
break
nums = nums[:i+1] + sorted(nums[i+1:])
print(''.join([str(i) for i in nums]))
With a test:
Please input a 9 digit number: 459876231
459876312
Please input a 9 digit number: 333222323
333222332
Sample value of n is 5
n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = n.split("+")
a=n[0]
b=n[1]
c=n[2]
n = (a + b + c)
print(n)
Expected Result : 615
You can use this.
n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
out=sum([int(i) for i in n.split('+')])
if you want only the first three elements to be added then use this.
out_3=sum([int(i) for i in n.split('+')[:4]])
After splitting n is a list of strings, you should cast them to int.
n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = n.split("+")
a=int(n[0])
b=int(n[1])
c=int(n[2])
n = (a + b + c)
print(n)
And if necessary add try/except to handle correctly situations when not a valid number would be passed.
You just have to add 1 extra line in your code and it should be running.
You need to convert all the elements in your list to int for performing addition.
Try this :
n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = n.split("+")
n = list(map(int, n))
a=n[0]
b=n[1]
c=n[2]
n = (a + b + c)
print(n)
Here, how you should do it:
n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = list(map(int, n.split("+")))
print(sum(n))
I have used map to convert a list of string to a list of int and sum to sum all the elements of the list. I assume you need to sum all the elements of your list. If you want to sum only first three elements, then:
a=n[0]
b=n[1]
c=n[2]
n = (a + b + c)
print(n)
Note: If you are using latest version of Python, then n = map(int, n) will return a TypeError: 'map' object is not subscriptable. You need to explicitly convert object returned by map to a list.
I got my homework problem. I need to input 2 variables and print them out alternatively n number of times without using if-else or loop statement.
a = input() #character
b = input() #character
n = input("n ")
I want to print out string of "ababa"
e.g.
a = "#"
b = "%"
n = 5
Expected output: #%#%#
or
n = 4
Expected output: #%#%
Since you have shown some effort in your comments I will give an answer. This uses the // integer division and % modulus operators. Note that I had to convert the value of n to an integer.
a = input("a? ") # character
b = input("b? ") # character
n = int(input("n? "))
print((a + b) * (n // 2) + a * (n % 2))
I am writing a program that calculates the factorial of a number, I am able to display the correct answer, however along with the answer I need the actual calculation to display, I am having trouble with that. So for example, when the user enters 4, I need it to display as:
I have been trying to figure out the right code, but do not know what to do.
Here is the code I have so far
number = int(input("Enter a number to take the factorial of: "))
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
print (factorial)
Right now, it displays the correct answer, however I need for it to include the equation as well as follows: 4! = 1 x 2 x 3 x 4 = 24
The simplest approach is to construct the string as you are iterating:
equation = str(number) + "! = "
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
equation += str(i) + "x"
equation = equation[:-1] + " = " + str(factorial)
print(equation)
Note that this method appends an unwanted 'x' after the last factor. This is removed by equation[:-1].
Alternatively, you could append this one-line solution to the end of your code. It uses the join method of the string class to concatenate an array of strings:
print(str(number) + "! = " + "x".join(str(n) for n in range(1, number + 1)) + " = " + str(factorial))
As you loop through the numbers to be multiplied, you can append each number's character to a string containing the equation, e.g ans, and print it at last. At the end of the code, I omitted the last letter because I didn't want an extra 'x' to be displayed.
def fact(number):
num_string=str(number)
factorial = 1
ans=num_string+"!="
for i in range(1, number + 1):
factorial = factorial * i
ans+=str(i)+"x"
ans=ans[:-1]
print(ans)
return factorial
fact(4)
You can append each value to the list and then print the equation using the f-string:
num = 5
l = []
f = 1
for i in range(1, num + 1):
f *= i
l.append(i)
print(f"{num}! = {' x '.join(map(str, l))} = {f}")
# 5! = 1 x 2 x 3 x 4 x 5 = 120