OK so this is my code, it's a base calculator that will convert base to base with no problem, but once the answer is over 9, I want the number to be represented as a letter, just like in base 16, 10 represent 'a', so I'm stuck on how can I do that just using Ascii tables. Right now the code is running well, if I type 1011,base2, I want to convert to base 16. So the output turns out to be 11, which is correct, but I want it to be 'b'
number = input("what's your number: ")
o_base = int(input("what is your oringal base: "))
base = int(input("what's the base you want to convert: "))
answer = ""
total = 0
for i, d in enumerate(reversed(number)):
total = total + int(d) * o_base ** i
while (total != 0):
answer += str(total % base)
total //= base
print (answer)
Python can first convert your number into a Python integer using int(number, base). Next all you need to do is convert it into you target base. This is often done using divmod() which combines doing a division of two numbers and getting their remainder into one function.
To convert each digit into the correct number or letter, the easiest way is to create an string holding all of your required symbols in order, and then use an index into this to give you the one you need, e.g. digits[0] here will return 0, and digits[10] would return A.
import string
number = input("What's your number: ")
o_base = int(input("What is your original base: "))
base = int(input("What is the base you want to convert to: "))
number = int(number, o_base)
digits = string.digits + string.ascii_uppercase # 0 to 9 + A to Z
output = []
while number:
number, remainder = divmod(number, base)
output.insert(0, digits[remainder])
print(''.join(output))
This example works up to base 36 (i.e. 0 to 9 and A to Z). You could obviously extend digits to give you more symbols for higher bases.
Using a list to create the output avoids doing repetitive string concatenation which is not very efficient.
Related
let's say I have an decimal number like 20.65. I want to get x random decimal number that follows:
Should have same number of digits.
Should have same number of decimal places.
Should be negative if the input integer is.
There should be no repetition of any outputs or same as the input.
Example
I gave an input like:
Enter number : 50.26
Enter no of random numbers to be generated : 5
then it's output should be like:
12.36
69.74
58.39
54.56
94.45
Example 2:
Input:
Enter number : 5650.265
Enter no of random numbers to be generated : 5
then it's output should be like:
1652.326
6925.743
5844.394
5464.562
9448.454
Example 3:
Input:
Enter number : -456
Enter no of random numbers to be generated : 5
then it's output should be like:
-566
-492
-452
-151
-944
What I have tried :
from random import randint
n = float(input("Enter number : "))
x = int(input("Enter no of random integers to be generated : "))
min_choice = int('1'+''.join('0' for i in range(len(str(n))-1)))
max_choice = int(''.join('9' for i in range(len(str(n)))))
for i in range(x):
print(randint(min_choice, max_choice))
which outputs as:
Enter number : 53.25
Enter no of random integers to be generated : 5
44864
29942
25832
20500
68083
So, as I can't the decimal places where I am struck.
You can split it into two functions, one to generate a single number, and the other to collect the values making sure no duplicates are included:
import random
def gen_num(inp):
out = ""
if inp[0] == '-':
out += "-"
inp = inp[1:] # Skip sign
# The loop insures the generated numbers
# are of the same length as inp
for dig in inp:
if dig == ".": # Keeping decimal separator where it was
out += "."
else:
out += str(random.randint(1, 9))
return out
def gen_nums(inp, n):
out = set() # Sets can't contain duplicates
while len(out) < n:
num = gen_num(inp)
if num != inp: # Making sure no output number is same as input
out.add(num)
return out
if __name__ == "__main__":
inp = input("Enter number: ")
n = int(input("Enter no of random numbers to be generated: "))
for v in gen_nums(inp, n):
print(v)
Beware of casting the input to a float and back, you might be subject to floating point error.
Also be aware that there is a finite number of numbers that can be generated given the constraints (you can't generate 9 values from input 1) and you might want to define what should happen in such case (what do you think would happen using the code above?).
You could convert the input to a str and then use split
user_input = 123.321
input_parts = str(user_input).split('.') # This will return a list ["123", "321"]
Then you could get the lengths of each with len
left_side = len(input_parts[0])
right_side = len(input_parts[1])
Use those lenghts to generate appropriate length integers and join them.
left_num = str(random.randint(10**(left_side - 1),(10**left_side)-1))
right_num = str(random.randint(10**(right_side - 1),(10**right_side)-1))
Now you have 2 numbers of appropriate length. Just join them.
sides = [left_num, right_num]
merge = '.'.join(sides)
final_num = float(merge)
So for my assignment I have to start with these parameters.
"Write a program that will average all of a numbers digits. You must use % for this lab to access the right most digit of the number. You will use / to chop off the right most digit."
Now I'm kinda confused where to start here's the code provided we must follow
def go( num ):
return 0
while ( True ):
# enter a number
val = int(input("Enter a number :: "))
print( go( val ) )
As a beginner I'm pretty damn confused where to start.It's supposed to average the digits in a number, and this is confusing me right now.
You can do something like this, i followed Crytofool's method
number = int(input("Enter a number"))
count = 0
result = 0
while number:
result, number = result + number % 10, number // 10 #grabbing induvidual digits of base 10, chopping off right most digit
count = count +1
print(result/count)
I'm trying to replace a value entered by a user with a string to make the output cleaner
I thought an if statement would help, but I'm not sure how it would tie in with my intended output
def main() :
number = int(input("Enter your number: "))
base = int(input("Convert to\n" \
" Binary[2] - Octal[8] - Hexadecimal[16]: "))
if base == 2 :
"binary"
elif base == 8 :
"octal"
else:
"hexadecimal"
print("\n"+str(number) +" in "+ str(base) + " is: " + str(convert(number, 10, base)))
def convert(fromNum, fromBase, toBase) :
toNum = 0
power = 0
while fromNum > 0 :
toNum += fromBase ** power * (fromNum % toBase)
fromNum //= toBase
power += 1
return toNum
main()
What I'm trying to get:
if user enters 5 as their number and 2 as conversion. Output would be:
"5 in binary is: 101"
Try
def main() :
number = int(input("Enter your number: "))
base = int(input("Convert to\n" \
" Binary[2] - Octal[8] - Hexadecimal[16]: "))
base_string = "None"
if base == 2 :
base_string = "binary"
elif base == 8 :
base_string = "octal"
else:
base_string = "hexadecimal"
print("\n {} in {} is: {}".format(str(number), base_string, str(convert(number, 10, base))))
def convert(fromNum, fromBase, toBase) :
toNum = 0
power = 0
while fromNum > 0 :
toNum += fromBase ** power * (fromNum % toBase)
fromNum //= toBase
power += 1
return toNum
main()
Your issue was the "binary" part in the if-statement. It has virtually no effect neither on your code nor on your output. You have to store the literal representation ("binary",...) in some variable ("base_string"). Then you can use this variable in your output.
As an aside, it looks like your base conversion won't actually do what you want. You should look at How to convert an integer in any base to a string? to do the conversion properly (hexadecimal has letters A-F in it, those aren't handled by your code, for example).
To accept a name instead of a number, you need to change this line of code:
base = int(input("Convert to\n Binary[2] - Octal[8] - Hexadecimal[16]: "))
What's happening here? input() takes a line from stdin. In the interactive case, this means the user types something (hopefully a number) and then hits enter. We get that string. Then int converts that string to a number.
Your convert expects base to be a number. You want inputs like "binary" to correspond to base = 2. One way to achieve this is with a dict. It can map strings to numbers:
base_name_to_base = {'binary': 2, 'octal': 8, 'hexadecimal': 16}
base = base_name_to_base[input('Choose a base (binary, octal, hexadecimal): ')]
Note that base_name_to_base[x] can fail (raise KeyError) if x is not a key in the dict. So you want to handle this (what if the user enters "blah"?):
while True:
try:
base = base_name_to_base[input('Choose a base (binary, octal, hexadecimal): ')]
break
except KeyError:
pass
This will loop until we hit the break (which only happens when indexing into base_name_to_base doesn't raise the key error.
Additionally, you may want to handle different cases (ex. "BINARY") or arbitrary whitespace (ex. " binary "). You can do this by calling .lower() and .strip() on the string returned by input().
I'm using python 3.5.2 to make this program. It'supposed to take any decimal number and convert it to binary.
number = int(input('Enter a number in base 10: '))
base2 = ''
while(number > 0):
rem = number % 2
number = number // 2
base2 = srt(number) + str(rem)
print(rem)
#This was to prevent the end text from sticking to the print
input('\nEnter to end')
It returns the correct values, but backwards and in a column and I don't know why.
Some modifications to your code:
number = int(input('Enter a number in base 10: '))
base2 = ''
while(number > 0):
rem = number % 2
number = number // 2 # can be number //= 2, or number >>= 1
base2 += str(rem)
#print(rem) # no need to print
print(base2[::-1])
Or more simple:
base2 = bin(number)[2:]
Your code prints the lowest bit of remaining number on separate lines so that's why you see them in reverse order. You could change your code to store bits to an array and then after the loop print them in reverse order:
number = int(input('Enter a number in base 10: '))
base2 = []
while(number > 0):
base2.append(str(number % 2))
number = number // 2
print(''.join(reversed(base2)))
Python also has built-in method bin than can do the conversion for you:
>>> bin(10)
'0b1010'
I am a complete beginner to Python. I wrote some code to perform base conversion and I was wondering if there were better alternatives that were shorter to code (one-liners) or significantly faster. The code looks ugly and feels "non-Pythonic" though being a beginner I should not have any such opinion. Any feedback to improve the code would be appreciated. This is purely for learning purposes.
#!/usr/bin/env python
import math
def number_to_digits( number, radix ):
'Converts a number into a vector of digits in given radix'
digits = [0]*int(math.ceil(math.log(number,radix)))
for ii in range(len(digits)):
(number,digit) = divmod(number,radix)
digits[ii] = digit
return digits
def digits_to_number( digits, radix ):
'Converts a vector of non-negative digits in given radix into a number'
number = 0;
for ii in range(len(digits)-1,-1,-1):
number *= radix
number += digits[ii]
return number
if __name__ == '__main__':
try:
number = int(raw_input('Enter number: '))
if number <= 0: raise ValueError()
radix = int(raw_input('Enter radix: '))
if radix <= 0: raise ValueError()
digits = number_to_digits(number,radix)
print digits
number_again = digits_to_number(digits,radix)
if not number_again == number:
print 'test failed'
except ValueError:
print 'unexpected input'
A sample session on the terminal produces:
Enter number: 44
Enter radix: 6
[2, 1, 1]
It is easy to check that 2 + 1*6 + 1*6**2 == 44. Thanks!
Here's a nice recursive version that will convert up to hexadecimal from Problem Solving with Algorithms and Data Structures
def toStr(n,base):
convertString = "0123456789ABCDEF"
if n < base:
return convertString[n]
else:
return toStr(n//base,base) + convertString[n%base]
print(toStr(1453,16))
Python provides some built-in functions to convert a value represented in one Integer base to another Integer base. Integer is represented in four forms i.e. decimal, binary, octal, and hexadecimal form.
Python provides built-in bin() functions to convert from non-binary number to binary number, oct() function to convert from non-octal number to octal number and hex() function to convert from non-hexadecimal number to hexadecimal number. These functions return a string literal to represent the values.
You can learn these functions from the tutorial on Integer base Conversion Functions in Python
You can find (slightly) cleaner example in the following thread:
Python elegant inverse function of int(string,base).
Taking the top ranked example, you can clean it up a bit to:
def digit_to_char(digit):
if digit < 10:
return str(digit)
return chr(ord('a') + digit - 10)
def str_base(number, base):
while number > 0:
number, digit = divmod(number, base)
yield digit_to_char(digit)
Results in:
>>> list(str_base(44, 6))
['2', '1', '1']
If you don't care about bases larger than 10, it simplifies to:
def str_base(number, base):
if base > 10:
raise ValueError('Base must be less than 10')
while number > 0:
number, digit = divmod(number, base)
yield digit
>>> list(str_base(44, 6))
[2, 1, 1]