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
Related
I am doing a program of say digit in python using recursion and i want that if digit==0 return nothing.
Code:
# Q1
# Say digit
# i/p = 412 - o/p = four one two
list = ['zero','one','two','three','four','five','six','seven','eight','nine']
n=412
def say_digit(n, list):
if n==0:
return ''
digit = int(n % 10)
n = n / 10
say_digit(n, list)
print(list[digit], end=' ')
return ''
if __name__ == "__main__":
n=int(input("Enter Number: "))
ans = say_digit(n, list)
print(ans)
Output:
The code does a division by 10 at each iteration. But there's no guarantee this will reach 0. In Python3, it does a floating point division. You can get to 0 with integer division (using // instead of /).
Here's an updated version:
# Q1
# Say digit
# i/p = 412 - o/p = four one two
numbers = ['zero','one','two','three','four','five','six','seven','eight','nine']
n=412
def say_digit(n, numbers):
if n==0:
return ''
digit = int(n % 10)
n = n // 10
return say_digit(n, numbers) + ' ' + numbers[digit]
if __name__ == "__main__":
n=int(input("Enter Number: "))
ans = say_digit(n, numbers)
print(ans)
It also translates each digit in the words from list.
Ideally, one shouldn't shadow built-in names like 'list'. To avoid that, this version uses the name 'numbers'.
Use // instead of /
i.e. n = n // 10
/ gives float and // gives int
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 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)))
I set an algorithm which sum a number's digits but I couldn't make it till single digit. It only work for one step.
For example:
a=2, b=8
a^b=256 = 6+5+2 = 13
But I want to reach single digit, like:
a^b=256 = 6+5+2 = 13 = 3+1 = 4
Below you can see my codes.
a = int(input("Enter a value"))
b = int("Enter second value")
number = pow(a, b)
sum= 0
while float(number) / 10 >= .1:
m = number % 10
sum += m
number = number // 10
if float(number) / 10 > .1:
print(m, end=" + ")
else:
print(m, "=", sum)
Here you go:
n = 256
while n > 9:
n = sum(int(i) for i in str(n))
print(n)
So whats going on? str(n) converts n to a string, strings in python can be iterated over so we can access digit by digit. We do this in a generator, converting each digit back to a integer, int(i) for i in str(n), we use sum to sum the elements in the generator. We repeat this process until n is a single digit.
Added a solution that gives the calculation explicitly:
def sum_dig(n):
_sum = sum(int(i) for i in str(n))
explained = "+".join(list(str(n)))
return _sum, explained
n = 256
s = ""
while n > 10:
n, e = sum_dig(n)
s+= f'{e}='
s += str(n)
print(s)
yields:
2+5+6=1+3=4
you can try this.
a = int(input("Enter a value"))
b = int(input("Enter second value"))
number = pow(a, b)
result = str(a)+'^'+str(b) + ' = ' + str(number)
while number > 9:
digit_sum = sum(map(int, str(number)))
result += ' = ' + '+'.join(str(number)) + ' = ' + str(digit_sum)
number = digit_sum
print ( result )
for a=2, b=8 result:
2^8 = 256 = 2+5+6 = 13 = 1+3 = 4
This produces the output in the format OP asked for:
a = int(input("Enter a value: "))
b = int(input("Enter second value: "))
n = pow(a, b)
while n >= 10:
nums = [i for i in str(n)]
op = "+".join(nums)
n = eval(op)
print("{}={}".format(op, n))
Logic:
Store the input in an array of individual numbers as strings.
Create the summation string using "+".join(nums) - for the output print.
Calculate the sum using eval(op) which works on strings (a built-in function) - store in n.
Print the summation string and what it equals.
Output:
Enter a value: 2
Enter second value: 8
2+5+6=13
1+3=4
Enter a value: 2
Enter second value: 6
6+4=10
1+0=1
Enter a value: 2
Enter second value: 50
1+1+2+5+8+9+9+9+0+6+8+4+2+6+2+4=76
7+6=13
1+3=4
sol = 0
if (a^b)%9==0:
sol = 9
else:
sol = (a^b)%9
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)