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))
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 want to print the digits of an integer in order, and I don't want to convert to string. I was trying to find the number of digits in given integer input and then divide the number to 10 ** (count-1), so for example 1234 becomes 1.234 and I can print out the "1". now when I want to move to second digit it gets confusing. Here is my code so far:
Note: Please consider that I can only work with integers and I am not allowed to use string and string operations.
def get_number():
while True:
try:
a = int(input("Enter a number: "))
return a
except:
print("\nInvalid input. Try again. ")
def digit_counter(a):
count=0
while a > 0:
count = count+1
a = a // 10
return count
def digit_printer(a, count):
while a != 0:
print (a // (10 ** (count-1)))
a = a // 10
a = get_number()
count = digit_counter(a)
digit_printer(a, count)
I want the output for an integer like 1234 as below:
1
2
3
4
Using modulo to collect the digits in reversed order and then print them out:
n = 1234
digits = []
while n > 0:
digits.append(n%10)
n //=10
for i in reversed(digits):
print(i)
Recursive tricks:
def rec(n):
if n > 0:
rec(n//10)
print(n%10)
rec(1234)
Finding the largest power of 10 needed, then going back down:
n = 1234
d = 1
while d * 10 <= n:
d *= 10
while d:
print(n // d % 10)
d //= 10
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
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 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