Python: Reversing print order from a while loop - python

I am writing some code takes values, the values number and N as input and prints, the first N lines of a multiplication table as below:
3 * 4 = 12
2 * 4 = 8
1 * 4 = 4
What I'd like to do is reverse said output to look like this:
1 * 4 = 4
2 * 4 = 8
3 * 4 = 12
The code is here below. I've thought about using slicing such as [:-1] but I'm not sure how to implement it. Assistance would be appreciated. Thanks.
number = input("Enter the number for 'number ': ")
N = input("Enter the number for 'N': ")
if number .isdigit() and N.isdigit():
number = int(number )
N = int(N)
while int(N) > 0:
print('{} * {} = {}'.format(N,number ,N*number))
N = N - 1
else:
print ('Invalid input')

I would instead recommend using a for loop with the range method as such:
for i in range(1, N+1):
print('{} * {} = {}'.format(i,number ,i*number)

I think, you can let the program count upwards.
N = int(N)
i = 1
while int(N) >= i:
print('{} * {} = {}'.format(N,number ,N*number)) # TODO: adjust formula
i = i + 1

Reversing a list is [::-1] (you missed ':') and you are parsing twice the same number N, but in this case you can do
counter = 0
while counter != N:
print('{} * {} = {}'.format(N,number ,N*number))
counter = counter + 1

You could change your while loop like so:
int i = 0
while i < N:
print('{} * {} = {}'.format(i,number ,i*number))
i = i + 1

If you absolutely have to do it using while loops, perhaps something like the following will work.
m = 1
while m <= N:
#Do stuff with m
m += 1
Although I much suggest using a for loop instead.

Related

I have a double while loop, and it does not seem to be working because of some logic I'm doing incorrectly

I have a double while loop, and it does not seem to be working because of some logic I'm doing incorrectly. I'm not sure what is wrong exactly, but I feel the code may be too complicated and somewhere, there is an error.
enter code here
import math
print("How many numbers am I estimating John?")
count = int(input("COUNT> "))
print("Input each number to estimate.")
better_guess = 0
initial_guess = 10
i = 0
j = 0
t = 1
list = []
for j in range(count):
num = float(input("NUMBER> "))
list.append(num)
j = j + 1
if j == count:
print("The square roots are as follows:")
while i <= len(list):
while t != 0 :
initial_guess = 10
better_guess = (initial_guess + (list[i])/initial_guess) / 2
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {list[i]}^0.5 = {better_guess}")
i = i + 1
break
initial_guess = better_guess
i = i + 1
There are some errors in your code, #x pie has pointed out some of them but not all. The most important is that you are need to initalize t for every number in the list, so you can get the iterations for the numbers separately. Also, t needs to be incremented in the while loop, not inside the if block.
You can also clean up the code considerably, for example the j variable is not being used, list comprehension can be used to shorten the code (pythonic way), and iterating over lists can be done with for num in list.
Putting this altogether produces this:
count = int(input('How many numbers am I estimating John? \nCOUNT> '))
print("Input each number to estimate.")
list = [float(input(f'NUMBER {i+1}> ')) for i in range(count)]
print("The square roots are as follows:")
for num in list:
initial_guess = 10
t = 0
while True:
better_guess = (initial_guess + num/initial_guess) / 2
t += 1
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {num}^0.5 = {better_guess}")
break
initial_guess = better_guess
Sample run:
How many numbers am I estimating John?
COUNT> 4
Input each number to estimate.
NUMBER 1> 1
NUMBER 2> 9
NUMBER 3> 16
NUMBER 4> 4
The square roots are as follows:
OUTPUT After 9 iterations, 1.0^0.5 = 1.0
OUTPUT After 7 iterations, 9.0^0.5 = 3.0
OUTPUT After 7 iterations, 16.0^0.5 = 4.0
OUTPUT After 8 iterations, 4.0^0.5 = 2.0
#viggnah is right, and I just ignored the num of iterations. But I think #viggnah 's num of iterations are 1 bigger than the actual num of iterations. E.g., if input is 4 and initial guess is 2, the iteration should be 0 rather than 1. Also I add except in case of illegal input.
I suppose the following code works as you expect.
import math
print("How many numbers am I estimating John?")
count = int(input("COUNT> "))
print("Input each number to estimate.")
better_guess = 0
initial_guess = 10
i = 0
j = 0
t = 1
list = []
while True:
try:
num = float(input("NUMBER> "))
list.append(num)
j = j + 1
if j == count:
print("The square roots are as follows:")
break
except:
print("Invalid input! Try again.")
while i < len(list):
initial_guess = 10
t = 0
while True:
better_guess = (initial_guess + (list[i])/initial_guess) / 2
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {list[i]}^0.5 = {better_guess}")
break
t = t + 1
initial_guess = better_guess
i = i + 1
You need to understand:
We only need initialize guess once for each number. So do it in the first while loop;
tneeds to be updated when initial_guess==better_guess rather than i, I believe this is a clerical error;
initial_guessneeds to be updated in the second loop;

Printing digits of an integer in order in Python

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

How can you sum these outputs in Python?

I made this code about a number and it's power. It will ask a number and it's power and show the output like a horizontal list.. Like
Number = 2
Power = 3.... then output will be like=
1
2
4
Number and power can be +/-.
But I want to sum those numbers like Sum = 7 after it shows
1
2
4
I have no idea how to do it after the output. I am new to programming maybe that's why can't figure out this problem.
Here is the code in Python :
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
while i < B:
print(A**i)
i = i + 1
while i >= B:
print(A**i)
i = i - 1
You could simplify this with numpy as follows
import numpy as np
A =float(input("Number:"))
B =int(input("Power:"))
print("Result of Powers:")
power = np.arange(B)
power_result = A ** power
sum_result = np.sum(power_result)
print(power_result)
print(sum_result)
I made B into an int, since I guess it makes sense. Have a look into the numpy documentation to see, what individual functions do.
You can create another variable to store the sum
and to print values on the same line use end=" " argument in the print function
a = float(input("Number:"))
b = int(input("Power:"))
sum = 0.0
i = 0
while b < 0:
ans = a**i
i = i - 1
print(ans, end=" ")
sum = sum + ans
b += 1
while b >= 0:
ans = a**i
i = i + 1
print(ans, end=" ")
sum = sum + ans
b -= 1
print("\nSum = " + str(sum))
I'm not sure what you want to achieve with the second loop. This works:
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
n_sum = 0
while i < B:
n_sum += A**i
print(A**i)
i = i + 1
while i >= B:
n_sum += A**i
print(A**i)
i = i - 1
print(n_sum)

How to make loop repeat until the sum is a single digit?

Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum 2+3+4+5 = 14 which is not a single digit so repeat with 1+4 = 5 which is a single digit.
This is the code I have so far. It works out for the first part, but I can't figure out how to make it repeat until the sum is a single digit. I'm pretty sure I'm supposed to nest the code I already have with another while statement
n = int(input("Input an integer:"))
sum_int=0
while float(n)/10 >= .1:
r= n%10
sum_int += r
n= n//10
if float(n)/10 > .1: print(r, end= " + ")
else: print(r,"=",sum_int)
this is a sample output of the code
Input an integer: 98765678912398
8 + 9 + 3 + 2 + 1 + 9 + 8 + 7 + 6 + 5 + 6 + 7 + 8 + 9 = 88
8 + 8 = 16
1 + 6 = 7
This should work, no division involved.
n = int(input("Input an integer:"))
while n > 9:
n = sum(map(int, str(n)))
print(n)
It basically converts the integer to a string, then sums over the digits using a list comprehension and continues until the number is no greater than 9.
You could utilize recursion.
Try this:
def sum_of_digits(n):
s = 0
while n:
s += n % 10
n //= 10
if s > 9:
return sum_of_digits(s)
return s
n = int(input("Enter an integer: "))
print(sum_of_digits(n))
you can try this solution,
if n=98 then your output will be 8
def repitative_sum(n):
j=2
while j!=1:
n=str(n)
j=len(n)
n=list(map(int,n))
n=sum(n)
print(n)
You don't need to convert your integer to a float here; just use the divmod() function in a loop:
def sum_digits(n):
newnum = 0
while n:
n, digit = divmod(n, 10)
newnum += digit
return newnum
By making it a function you can more easily use it to repeatedly apply this to a number until it is smaller than 10:
n = int(input("Input an integer:"))
while n > 9:
n = sum_digits(n)
print(n)
def add_digits(num):
return (num - 1) % 9 + 1 if num > 0 else 0
A simple, elegant solution.
I'm not sure if it's anti-practice in Python because I know nothing about the language, but here is my solution.
n = int(input("Input an integer:"))
def sum_int(num):
numArr = map(int,str(num))
number = sum(numArr)
if number < 10:
print(number)
else:
sum_int(number)
sum_int(n)
Again I am unsure about the recursion within a function in Python, but hey, it works :)
If you like recursion, and you must:
>>> def sum_digits_rec(integ):
if integ <= 9:
return integ
res = sum(divmod(integ, 10))
return sum_digits(res)
>>> print(sum_digits_rec(98765678912398))
7
def digit_sum(num):
if num < 10:
return num
last_digit = num % 10
num = num / 10
return digit_sum(last_digit + digit_sum(num))
input_num = int(input("Enter an integer: "))
print("result : ",digit_sum(input_num))
This may help you..!
Try with strings comprehension:
new = input("insert your number: ")
new = new.replace(" ","")
new =sum([int(i) for i in new])
if new not in range (10):
new = str(new)
new = sum ([int(i) for i in new])
print (new)
Note that the answers which convert int to str are relying on the python conversion logic to do internally the divmod calculations that we can do explicitly as follows, without introducing the non-numeric string type into an intrinsically numerical calculation:
def boilItDown(n):
while n >= 10:
t = 0
while n:
d, m = divmod(n, 10)
n, t = d, t + m
n = t
return n
n = 98765678912398
print(boilItDown(n))
Output:
7

sum of the product of even positioned digits

I have attempted this problem like this :
a = input("Enter number : ")
s = 3
w = 1
while a>0:
digit=a%10
if n%2 == 0:
p = p*digit
else:
s = s+digit
a=a/10
n=n+1
print "The sum is",s
it works perfectly for even no of digits but for odd no of digits like for 234 it shows the sum as 6 and product 3
No explicit loop:
import operator
from functools import reduce # in Python 3 reduce is part of functools
a = input("Enter number : ")
lst = [int(digit) for digit in a]
add = sum(lst[1::2])
mul = reduce(operator.mul, lst[::2],1)
print("add =",add,"mul =",mul,"result =",add+mul)
Producing:
Enter number : 234
add = 3 mul = 8 result = 11
You have to start with n = 0 for this to work
a = int(input("Enter number"))
s = 0
p = 1
n = 0
while a>0:
digit=a%10
if n%2 == 0:
p *= digit
else:
s += digit
a /= 10
n += 1
print "The sum is",s
print "Product is",p
Easy mistake to make about the numbering. The first item of any string, list or array is always index 0. For example, be careful in future to take away 1 from the value returned from len(list) if you are iterating through a list's items with a for loop e.g.
for x in range(len(list)-1):
#your code using list[x]
Here's the mathematical version:
n = input('Enter a number: ')
digits = []
while n > 0:
digits.append(n%10)
n //= 10
s = 0
p = 1
i = 0
for digit in reversed(digits):
if i%2 == 0:
s += digit
else:
p *= digit
i += 1
print 'Sum of even digits:', s
print 'Product of odd digits:', p
print 'Answer:', s+p
I have tried to make this as simple as possible for you.
Here's a function that does the same thing:
def foo(n):
s = 0
p = 1
for i, digit in enumerate(str(n)):
if i%2 == 0:
s += digit
else:
p *= digit
return s+p
def foo(num):
lst = [int(digit) for digit in str(num)]
mul, add = 1, 0
for idx, val in enumerate(lst):
if not idx % 2:
mul *= val
else:
add += val
return add, mul
And using it:
>>> foo(1234)
(6, 3)
>>> foo(234)
(3, 8)
This function will take an integer or a string representation of an integer and split it into a list of ints. It will then use enumerate to iterate over the list and preform the required operations. It returns a 2 element tuple.

Categories