I'm trying to create a multiplication table. The user enters their list of numbers and the program spits out the multiplication for each number. for example,
3 x 1 = 3
3 x 2= 6
3 x 3 = 9
......
.....
3 x 12=42
this is what I have tried so far:
enter code here
N = int(input("How many numbers would you like to multiply?:"))
num = []
q=1
p = 1
count=0
for i in range(0,N):
add = int(input(f"number {i}:"))
num.append(add)
print(num)
for j in num:
while q <= 12:
print (j * q, end=" ")
q+=1
#The result is
How many numbers would you like to multiply?:3
number 0:2
number 1:6
number 2:5
[2, 6, 5]
2 4 6 8 10 12 14 16 18 20 22 24
enter code here
How do I get the program to spit out all the multiplication for every number in the list?
Store your tables in a dictionary and call in any way you want. See below code:
def inputmethod():
N = int(input("How many numbers would you like to multiply?:"))
num = []
for i in range(0,N):
add = int(input(f"number {i}:"))
num.append(add)
return num
def multiplication(m,num):
L = list(range(1,m+1))
dict_tables = {}
for n in num:
dict_tables[n] = [e*n for e in L]
return dict_tables
def print_tables(dict_tables):
for key,value in dict_tables.items():
print(f"Table of {key} is : {value}")
num = inputmethod()
generate_tables = multiplication(12,num)
print_tables(generate_tables)
Here's how (and why) I would have written that:
# More verbose variable names are nice documentation!
num_count = int(input("How many numbers would you like to multiply?:"))
numbers = []
# Start at 1 instead of 0, because humans are used to counting from 1.
for i in range(1, num_count + 1):
number = int(input(f"number {i}:"))
numbers.append(number)
print(numbers)
# Loop across the list of numbers you built in the previous step.
for number in numbers:
# `for i in range(...)` is the canonical Python way to loop over numbers.
for i in range(1, 13):
print(number * i, end=" ")
print()
Alternatively:
...
for i in range(12):
print(number * (i + 1), end=" ")
...
gets the same result, but I find it a lot simpler to iterate over the actual list of numbers I want to use, especially in more complex formulas where you're referring to that variable more than once. For instance, if you were calculating squares and writing number * (i + 1) * (i + 1), and you were my coworker, I would wag my finger at you.
Related
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;
I am struggling to write a program that finds the sum of every odd number in a list of 21. this is what I have so far...
sum = 1
numbers = range(1,21,1)
for number in numbers:
if number % 2 == 1;
total += numbers
print(total)
Any help is appreciated.
You can try either already creating a range of odd numbers simply by asking the range to "jump" by 2, starting from 1: 1,3,5,.. and then summing it all:
res = sum(range(1,21,2))
print(res)
>> 100
Or,
create the range, and filter the odd numbers, and then sum it all:
r = range(1,21)
filtered = filter(lambda x: x%2, r)
res = sum(filtered)
#or in 1 line: sum(filter(lambda x: x%2, range(1,21)))
print(res)
>> 100
You had 3 issues:
1) You called on total but never defined it (total+=numbers) while i think you meant to use sum
2) You wrote Total += numbers instead of +=number
3) In this line if number % 2 == 1: you accidentaly used ; instead of :
Here is the fixed code, Enjoy!
EDIT: I want to add that range() is non inclusive, so if you want 21 to be in the list you should use range(1,22,1)
sum = 0
numbers = range(1,21,1)
for number in numbers:
if number % 2 == 1:
sum += number
print(sum)
sum = 0
numbers = range(1,21+1)
for number in numbers:
if number % 2 == 1:
sum += number
print(sum)
or
sum = 0
numbers = range(1,21+1, 2)
for number in numbers:
sum += number
print(sum)
by the way:
range(start, stop, steps) doesn't include stop.
# Imported Modules
import time
import decimal
# Functions
def FindOddNums(a, b):
b = b + 1
for i in range(a, b):
# checks if i / 2 is a float and if float cannot be converted into a int if so than execute below code
if isinstance(i / 2, float) and not float.is_integer(i / 2):
# Check if b is more than 20 if so then no need to wait 1 sec before printing
if b > 20:
print(i)
elif b < 20:
time.sleep(1)
print(i)
def AskWhat():
time.sleep(1)
num1 = input("What first number do you want to check?: ")
time.sleep(1)
num2 = input("What second number do you want to check?: ")
time.sleep(1)
# User input is strings so need to be converted to ints
num1 = int(num1)
num2 = int(num2)
FindOddNums(num1, num2)
if __name__ == '__main__':
AskWhat()
Is this what you're looking for?
This actually calculates the thing but using steps is also a good way to go. But this is another way
The aim is to print a pattern half triangle depending upon the user input for example if the user input is 3 the pattern would be
1
1 2
1 2 3
but upon executing there is a space after the each element of the last column and a new line (\n) after the last row. i would like to remove that please help.
1 \n
1 2 \n
1 2 3 \n
likewise whereas the expected output is
1\n
1 2\n
1 2 3
here is the code i wrote
rows = int(input())
num = 1
for i in range (0, rows):
num = 1
for j in range(0, i + 1):
print(num,end=" ")
num = num + 1
print("")
Others have already shown the alternatives. Anyway, I believe that you are learning, and you want to understand that exact case. So, here is my comment.
YOU print the space. You cannot unprint it when already printed. There are more ways to solve that. If you want to preserve the spirit of your solution, you must not print the space after the last num. You can do one less turn of the inner loop, and print the last num separately, like this:
rows = int(input())
num = 1
for i in range (0, rows):
num = 1
for j in range(0, i):
print(num, end=' ')
num = num + 1
print(num)
In the example, the first num line can be removed. Also, you combine counted loop with your own counting (the num). It usually means it can be simplified. Like this:
rows = int(input('Type the number of rows: '))
for i in range (0, rows):
for j in range(1, i + 1):
print(j, end=' ')
print(i + 1)
Now, some experiment. Everything under the outer loop is actually printing a row of numbers. The sequence is generated by the range -- the generator that produces the sequence. When the sequence is wrapped by list(), you get a list of the numbers, and you can print its representation:
rows = int(input('Type the number of rows: '))
for i in range (1, rows + 1):
print(list(range(1, i + 1)))
It prints the result like...
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
Instead, you want to print the sequences of the same numbers joined by space. For that purpose, you can use join. However, you have to convert each of the elements to a string:
rows = int(input('Type the number of rows: '))
for i in range (1, rows + 1):
print(' '.join(str(e) for e in range(1, i + 1)))
And that is already similar to the solutions presented by others. ;)
Its too simple than the code you have made:
a = int(input("Enter a num: "))
for i in range(a+1):
print(" ".join(list(map(str,range(1,i+1)))),end="")
if i != a:print("")
Executing:
Enter a num: 3
1
1 2
1 2 3
>>>
I suggest you the following soltuion, building the whole result string first before printing it without new line character at the end:
my_input = int(input("Enter a num: "))
s = ""
for i in range(my_input):
s += " ".join([str(j) for j in range(1,i+2)])
s += "\n" if i != my_input-1 else ""
print(s, end="")
My version of your requirement,
rows = int(input('Enter a number - '))
num = 1
for i in range(0, rows):
num = 1
tmp = []
for j in range(0, i + 1):
tmp.append(str(num))
num = num + 1
if i + 1 == rows:
print(repr("{}".format(' '.join(tmp))))
else:
print(repr("{}\n".format(' '.join(tmp))))
p.s - Remove repr() if not required
Output
Enter a number - 3
'1\n'
'1 2\n'
'1 2 3'
Instead of printing a line piece by piece, or building a string by repetitively adding to it, the usual and efficient way in Python is to put all the values you want to print in a list, then to use join to join them.
Also, you don't need two imbricated loops: just append the latest number to your existing list on each loop, like this:
rows = int(input())
values = []
for i in range(1, rows + 1):
values.append(str(i))
print(' '.join(values))
Output:
3
1
1 2
1 2 3
The program asks the user for a number N.
The program is supposed to displays all numbers in range 0-N that are "super numbers".
Super number: is a number such that the sum of the factorials of its
digits equals the number.
Examples:
12 != 1! + 2! = 1 + 2 = 3 (it's not super)
145 = 1! + 4! + 5! = 1 + 24 + 120 (is super)
The part I seem to be stuck at is when the program displays all numbers in range 0-N that are "super numbers". I have concluded I need a loop in order to solve this, but I do not know how to go about it. So, for example, the program is supposed to read all the numbers from 0-50 and whenever the number is super it displays it. So it only displays 1 and 2 since they are considered super
enter integer: 50
2 is super
1 is super
I have written two functions; the first is a regular factorial program, and the second is a program that sums the factorials of the digits:
number = int(input ("enter integer: "))
def factorial (n):
result = 1
i = n * (n-1)
while n >= 1:
result = result * n
n = n-1
return result
#print(factorial(number))
def breakdown (n):
breakdown_num = 0
remainder = 0
if n < 10:
breakdown_num += factorial(n)
return breakdown_num
else:
while n > 10:
digit = n % 10
remainder = n // 10
breakdown_num += factorial(digit)
#print (str(digit))
#print(str(breakdown_num))
n = remainder
if n < 10 :
#print (str(remainder))
breakdown_num += factorial(remainder)
#print (str(breakdown_num))
return breakdown_num
#print(breakdown(number))
if (breakdown(number)) == number:
print(str(number)+ " is super")
Existing answers already show how to do the final loop to tie your functions together. Alternatively, you can also make use of more builtin functions and libraries, like sum, or math.factorial, and for getting the digits, you can just iterate the characters in the number's string representation.
This way, the problem can be solved in a single line of code (though it might be better to move the is-super check to a separate function).
def issuper(n):
return sum(math.factorial(int(d)) for d in str(n)) == n
N = 1000
res = [n for n in range(1, N+1) if issuper(n)]
# [1, 2, 145]
First I would slightly change how main code is executed, by moving main parts to if __name__ == '__main__', which will execute after running this .py as main file:
if __name__ == '__main__':
number = int(input ("enter integer: "))
if (breakdown(number)) == number:
print(str(number)+ " is super")
After that it seems much clearer what you should do to loop over numbers, so instead of above it would be:
if __name__ == '__main__':
number = int(input ("enter integer: "))
for i in range(number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
Example input and output:
enter integer: 500
1 is super
2 is super
145 is super
Small advice - you don't need to call str() in print() - int will be shown the same way anyway.
I haven't done much Python in a long time but I tried my own attempt at solving this problem which I think is more readable. For what it's worth, I'm assuming when you say "displays all numbers in range 0-N" it's an exclusive upper-bound, but it's easy to make it an inclusive upper-bound if I'm wrong.
import math
def digits(n):
return (int(d) for d in str(n))
def is_super(n):
return sum(math.factorial(d) for d in digits(n)) == n
def supers_in_range(n):
return (x for x in range(n) if is_super(x))
print(list(supers_in_range(150))) # [1, 2, 145]
I would create a lookup function that tells you the factorial of a single digit number. Reason being - for 888888 you would recompute the factorial of 8 6 times - looking them up in a dict is much faster.
Add a second function that checks if a number isSuper() and then print all that are super:
# Lookup table for single digit "strings" as well as digit - no need to use a recursing
# computation for every single digit all the time - just precompute them:
faks = {0:1}
for i in range(10):
faks.setdefault(i,faks.get(i-1,1)*i) # add the "integer" digit as key
faks.setdefault(str(i), faks [i]) # add the "string" key as well
def fakN(n):
"""Returns the faktorial of a single digit number"""
if n in faks:
return faks[n]
raise ValueError("Not a single digit number")
def isSuper(number):
"Checks if the sum of each digits faktorial is the same as the whole number"
return sum(fakN(n) for n in str(number)) == number
for k in range(1000):
if isSuper(k):
print(k)
Output:
1
2
145
Use range.
for i in range(number): # This iterates over [0, N)
if (breakdown(number)) == number:
print(str(number)+ " is super")
If you want to include number N as well, write as range(number + 1).
Not quite sure about what you are asking for. From the two functions you write, it seems you have solid knowledge about Python programming. But from your question, you don't even know how to write a simple loop.
By only answering your question, what you need in your main function is:
for i in range(0,number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
import math
def get(n):
for i in range(n):
l1 = list(str(i))
v = 0
for j in l1:
v += math.factorial(int(j))
if v == i:
print(i)
This will print all the super numbers under n.
>>> get(400000)
1
2
145
40585
I dont know how efficient the code is but it does produce the desired result :
def facto():
minr=int(input('enter the minimum range :')) #asking minimum range
maxr=int(input('enter the range maximum range :')) #asking maximum range
i=minr
while i <= maxr :
l2=[]
k=str(i)
k=list(k) #if i=[1,4,5]
for n in k: #taking each element
fact=1
while int(n) > 0: #finding factorial of each element
n=int(n)
fact=fact*n
n=n-1
l2.append(fact) #keeping factorial of each element eg : [1,24,120]
total=sum(l2) # taking the sum of l2 list eg 1+24+120 = 145
if total==i: #checking if sum is equal to the present value of i.145=145
print(total) # if sum = present value of i than print the number
i=int(i)
i=i+1
facto()
input : minr =0 , maxr=99999
output :
1
2
145
40585
Yes, this question has been asked, but I cannot seem to apply the answers to my problem. There are several parts to this problem, and this is the biggest obstacle I've hit.
I need to generate a random list of 10 numbers between 10 & 90. From those random numbers, I need to sum the totals of both the even and odd numbers.
def playlist():
nums = []
for nums in range(10):
# Get random list of 10 numbers
my_nums = random.randint(10, 90)
print (my_nums,end=' ')
even = []
odd = []
for x in my_nums:
if x % 2 == 0:
even.append[x]
print(even)
else:
odd.append[x]
print(odd)
When I run this, sometimes I get one or two numbers (usually the first two odd numbers), but mostly I get TypeError: 'int' object is not iterable.
Not gonna lie - my first language is PHP, not Python and that's becoming a huge problem for me :(
Any help is appreciated.
Creating list with randoms
n = [random.randint(10,90) for x in range(10)]
Getting even and odds:
even = [x for x in n if x % 2 == 0]
odd = [x for x in n if x % 2 == 1]
You should be doing this.
def playlist():
nums1 = []
for nums in range(10):
# Get random list of 10 numbers
my_nums = random.randint(10, 90)
nums1.append(my_nums)
print my_nums
even = []
odd = []
for x in nums1:
if x % 2 == 0:
even.append(x)
print(even)
else:
odd.append(x)
print(odd)
playlist()
There are a few things you seem to have misunderstood:
range(10) will give you (something that looks like) this list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].
You can use it with a for-loop to do something 10 times
random.randint(10, 90) will give you a single random number between 10 and 90 (not a list)
With this information we can change your script to:
import random
even_sum = 0
odd_sum = 0
for number_of_turns in range(10):
# Get a random number
number_this_turn = random.randint(10, 90)
print(number_this_turn,end=' ')
if number_this_turn % 2 == 0:
even_sum += number_this_turn
print("Sum of even numbers so far:", even_sum)
else:
odd_sum += number_this_turn
print("Sum of odd numbers so far:", odd_sum)
print("Final sum of even numbers:", even_sum)
print("Final sum of odd numbers:", odd_sum)
But we can do better. You will learn that in Python, you will want very often to define a list (or an iterable) with the terms you need then do something with every term. So we can change your script to:
import random
even_sum = 0
odd_sum = 0
random_numbers = [random.randint(10, 90) for x in range(10)]
for number in random_numbers:
print(number,end=' ')
if number % 2 == 0:
even_sum += number
print("Sum of even numbers so far:", even_sum)
else:
odd_sum += number
print("Sum of odd numbers so far:", odd_sum)
print("Final sum of even numbers:", even_sum)
print("Final sum of odd numbers:", odd_sum)
random_numbers = [random.randint(10, 90) for x in range(10)] is using a list comprehension to generate a list of 10 random numbers. You can then do a for-loop on each of these numbers where you can add to the evens' sum or to the odds' sum.
You can even simplify it even further like in #Take_Care_ 's answer but I guess you have a lot more to learn before you reach this level.
As mentioned the comments, you can't write for x in followed by a number. I guess what you want is for x in range(my_nums) rather than for x in my_nums.
This is ultimately what I needed:
def playlist():
nums = []
for nums1 in range(10):
# Get random list of 10 numbers
my_nums = random.randint(10, 90)
nums.append(my_nums)
print (my_nums,end=' ')
even = []
odd = []
for x in nums:
if x % 2 == 0:
even.append(x)
else:
odd.append(x)
print ("\n")
print("Total of Even Numbers: ",sum(even))
print ("\n")
print("Total of Odd Numbers: ",sum(odd))
Thanks to everyone for their help...yes I know the call to run the function is missing - like I said this is just one part of the program :)
Following code works:
"""
I need to generate a random list of 10 numbers between 10 & 90. From those random numbers, I need to sum the totals of both the even and odd numbers.
"""
from random import randint
MIN = 10
MAX = 90
sum_odds = sum_evens = 0
for i in range(10):
r = randint(MIN,MAX)
if r % 2:
sum_odds += r
else:
sum_evens += r
return sum_evens, sum_odds