Writing a function to find the factorial of an inputed number - python

I have written a code to calculate the factorial of any number a user inputs. The code is not running. I want to know what have I done wrong in this code.
num = int(input("Please enter a number : "))
fact = num
lst = list(range(1, num + 1))
lst.sort(reverse = True)
print(lst)
for x in lst :
while x > 1:
fact = fact * (x - 1)
print(fact)

It is because or your while x>1. Basically, your programme loops for a fixed value of x, which won't change.
You're pretty close:
num = int(input("Please enter a number : "))
fact = num
lst = list(range(1, num + 1))
lst.sort(reverse = True)
print(lst)
for x in lst :
if x > 1:
fact = fact * (x - 1)
else:
break
print(fact)

Related

Code that have exact function like oct() in Python

I need code that have exact function like oct() in Python but without using any other methods and functions.
I wrote this, but I think it's so large and also I don't want use range and len:
def get_oct(x):
next_step = [x]
r_mod = []
while True:
x /= 8
i = int(x)
next_step.append(i)
if int(x / 8) == 0:
break
for m in range(len(next_step)):
next_step[m] %= 8
j = int(next_step[m])
r_mod.append(j)
t_mod = r_mod[::-1]
return "0o" + "".join(str(e) for e in t_mod)
entry = int(input("Enter a number: "))
print(get_oct(entry))
If you want this to work like the built-in oct(), you need to account for zero and negative numbers. A nicer way to deal with this is to use the function divmod() the returns the result of integer division and the remainder. Just keep doing that until the value is zero:
def get_oct(x):
if x == 0: return '0o0'
prefix = '-0o' if x < 0 else '0o'
x = abs(x)
res = ''
while x:
x, rem = divmod(x, 8)
res = str(rem) + res
return (prefix + res)
assert(get_oct(80) == oct(80))
assert(get_oct(1) == oct(1))
assert(get_oct(0) == oct(0))
assert(get_oct(-2) == oct(-2))
assert(get_oct(-201920) == oct(-201920))
assert(get_oct(12345678910) == oct(12345678910))
If all that is needed is to print in octal without oct() function,string formatting could be the easiest option.
num = int(input("Enter a number: "))
print("{:o}".format(num))
Output:
Enter a number: 10
12
This is also possible with string variable
num = int(input("Enter a number: "))
s = "{:o}".format(num)
print(s)
Output:
Enter a number: 10
12

Printing largest number from a given input

I created a code to print the largest number from a given input(string) but it is only valid for inputs containing distinct digits and gives an error 'string index out of range' when the input consists of repetitive digits. Why so?
Note: "The concept of list cannot be used"
My code is as follows:
def largest_num(num):
nums = ""
length = len(num)
while length:
max_num = num[0]
for i in num:
if i > max_num:
max_num = i
num = num.replace(max_num,"")
nums = nums + max_num
length-=1
return nums
x = input("Entered number: ")
a = largest_num(x)
print(a)
Output:
Output of above code
#Husnian Mehdi - the original code has error in the line - "num.replace(max_num, ""). You could put print statement after that to see what's happening when you input a number with duplicated digits: such as '454'. I also change some variable names to make it more descriptive. [Hint: that num.replace() statement has removed both duplicated digits....!]
def largest_num(num):
ans = ""
size = len(num)
while size:
max_digit = num[0]
for n in num[1:]:
if n > max_digit:
max_digit = n
ans = ans + max_digit
num = num.replace(max_digit, "")
print(f' num is: {num} now ...')
size -=1
print(f' len: {size}')
return ans
x = input("Entered number: ")
It's more straightforward to take the advantage of the fact that the input is a string, and string can be sorted easily. Please try the code next:
from functools import cmp_to_key
def largestNum(num):
num = [str(n) for n in num]
num.sort(key=cmp_to_key(lambda b, a: ((a+b)>(b+a))-((a+b)<(b+a)) ))
return ''.join(num).lstrip('0') or '0'
x = input("Entered number: ")
#a = largest_num(x)
print(largestNum(x))
Demo:
>>>Entered number: 321895
985321
>>>Entered number: 10957
97510
>>>Entered number: 4576889
9887654
>>>
Or simply do the sorting directly (you can convert this to function):
1. num = list(num). # num is string input of number
2. num = num.sort(reverse=True)
3. largest = int(‘’.join(num)) # answer

I want to print the list of prime numbers in a given range, what is wrong with my code?

I am trying to print the list of prime numbers in a given range. I know we can directly use print statement in the for loop to print each prime number however, I want to print the entire list of prime numbers. What is wrong with my code?
def prime():
upper_bound = int(input())
while True:
lower_bound = int(input())
if lower_bound <= 2:
print("Please enter number greater than 2")
else:
break
prime_num = [2]
i = lower_bound
while i <= upper_bound+1:
for k in range(2,i):
if (i%k) == 0:
i = i + 1
break
else:
prime_num.append(i)
i = i + 1
print(prime_num)
You need to call the prime() function, then it'll print the array out.
Otherwise, you could loop through the array and add every character to a string so that you don't get the array formatting.
So:
Result = "";
for x in range(0, len(prime_num)):
Result += str(prime_num[x]) + " ";
print(Result);
I think it working properly I run it and give the output. Just call the prime() function.
def prime():
upper_bound = int(input("please enter upper bound"))
while True:
lower_bound = int(input("please enter lower bound"))
if lower_bound <=2:
print("Please enter number greater than 2")
else:
break
prime_num = [2]
i = lower_bound
while i <= upper_bound + 1:
for k in range(2, i):
if (i % k) == 0:
i = i + 1
break
else:
prime_num.append(i)
i = i + 1
prime()
and here is the output
please enter upper bound20
please enter lower bound3
[2, 3, 5, 7, 11, 13, 17, 19]
The fastest method:
import sympy
print(list(sympy.primerange(0, 1_000_000_000)))

how do i optimise this code of finding a number X whose sum with its digit is equal to n?

Find a Number X whose sum with its digits is equal to N
n = int(input())
for i in range(n//2, n):
z = [int(x) for x in str(i)]
zz = sum(z)
if zz<=100:
ans = int(i) + int(zz)
if(int(i) + int(zz) == n) :
print(i)
tile limit is exceeding
If it can be any number, this would be a fast way to do it.
i = int(input("Your number: "))
result = ""
while i > 9:
result += "9"
i -= 9
result += str(i)
print(result)
How about
for k in range(1000):
if sum([int(i) for i in str(k)]) == k:
print(k)
But there seem to be only very few numbers with that property...

Beginners python program

Decided to help out with doing a lab for my buddy, first time ever doing this so please don't make fun of my code lol. I have to get a number "num" of how many numbers to add to array, then a total number. Then from that I want to add user defined numbers from the size of the array. Then if any of those numbers adds up to the total then print them out, else print sorry. Can't understand why it doesn't work :(
EXTRA EDIT: Problem is, my script does not show the numbers that add up to the total value, only the print('sorry')
edit: I learned prior to this java and C, couldn't figure out the foor loops or how variable types are instantiated.
num = int(input('Please enter the amount of numbers you wish to use: '))
total = int(input('Please the total wild card number: '))
hasValue = int(0)
ar = []
i = int(0)
j = int(0)
k = int(0)
l = int(0)
m = int(0)
while (i < num):
j = i + 1
inNum = input('Please enter number %d:' %j)
ar.append(inNum)
i = i + 1
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
if (hasValue == 0):
print('sorry, there no such pair of values')
As I got it, your current script is looking for two consequent numbers where sum equal to total, but should search for any pair in array, right? So if we have
ar = [1, 2, 3]
and
total = 5
program should display 2, 3 pair. But it will not find 1+3 for total=4.
Here are some general advices:
There is error in print invocation, where pair is printed (string should go first in str+int concatenation). Use format
print('%d, %d'.format(ar[k], ar[k])
or print result as tuple
print(ar[k], ar[l])
Use for k in range(num) instead of while
hasValue is better to be boolean value
Well, here is my solution (python2.7)
num = int(input("Array size: "))
sum = int(input("Search for: "))
a = []
found = False
# Fill array
for i in range(num):
a.append(int(input("Enter number #{}: ".format(i+1))))
# More effective algorithm - does not check same numbers twice
for i in range(num):
for j in range(i+1, num):
if a[i] + a[j] == sum:
print "{}, {}".format(a[i], a[j])
found = True
if not found:
print "Sorry..."
This is how to do for-loops in python:
for x in range(10):
# code for the for loop goes here
This is equivalent to:
for (int x = 0; x < 10; x++) {
// code for the for loop goes here
}
... in C++
(Notice how there is no initializing the variable 'x'. When you do a for loop, python automatically initializes it.
Here is what I think you wish to do:
def main():
num = int(input("Enter the amount of numbers: "))
total = int(input("Enter the total: "))
array = []
counter, elem = 0, 0
for user_numbers in range(num):
array.append(int(input("Please enter number: ")))
for each_element in array:
counter += each_element
elem += 1
if counter == total:
print(array[:elem])
break
if counter != total:
print("sorry...")
main()
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
Apart from the fact that the loops are not "pythonic", you need to initialize l = 0 within the k loop.
while (k < num):
l = 0
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
or slightly more python way:
for num1 in ar:
for num2 in ar:
if num1+num2==total:
print(num1 +' , '+ num2) # not sure about this syntax. I am a python beginner myself!
hasValue = hasValue + 1

Categories

Resources