I have a method that is retrieving a couple of random numbers. I then want to combine randoma and randomb to be one number
For example if randoma = 2 and randomb = 150, I want it to return 2150
I am unsure how to do so. The #'s are where my unknown return statement would be.
def display()
total = setnums()
print("total = " + total)
def setnums():
randoma = random.randint(1, 5)
randomb = random.randint(100,1000)
return ########
In Python 3.6 and newer:
int(f'{randoma}{randomb}')
In Python older than 3.6:
int(str(randoma) + str(randomb))
Convert them to strings and concatenate them.
return int(str(randoma) + str(randomb))
int(str(randoma) + str(randomb))
If you want to do it using simple mathematic without converting to string
from math import floor, log10, pow
from random import randint
def display():
total = setnums()
print(total)
def setnums():
randoma = randint(1, 5)
randomb = randint(100,1000)
print(randoma)
print(randomb)
numberOfDigitsInFirstRandNumber = floor(log10(randomb))
numberOfDigitsInSecondRandNumber = floor(log10(randomb))
totalDigitCount = numberOfDigitsInFirstRandNumber + numberOfDigitsInSecondRandNumber
multiplyingFactor = pow(10, totalDigitCount - 1)
return (randoma * multiplyingFactor ) + randomb
display()
Basically what you do is to sum the number of digits in both numbers, subtract one from it and raise 10 to the power of the result, then multiple the first random number by the result and add it to the second random number.
you can try it out from here https://repl.it/repls/StainedRashArchive
TL;DR:
In Python >= 3.6 use f-strings:
return int(f'{randoma}{randomb}')
In Python < 3.6 use the + Operator:
int(str(randoma) + str(randomb))
Keep it simple, readable, and test in your own environment which option suits you best.
Given the following function:
def setnums():
randoma = random.randint(1, 5)
randomb = random.randint(100, 1000)
r = ##
return int(r)
Execution time in python3.6:
r = f"{randoma}{randomb}"
2.870281131
r = "%s%s" % (randoma, randomb)
2.9696586189999996
r = str(randoma) + str(randomb)
3.084615994999999
r = "".join((str(randoma), str(randomb)))
3.1661511100000013
def setnums():
randoma = str(random.randint(1, 5))
randomb = str(random.randint(100, 1000))
randoma += randomb
return int(randoma)
3.0611202350000006
Execution time in python2.7:
r = "%s%s" % (randoma, randomb)
2.46315312386
r = str(randoma) + str(randomb)
2.56769394875
r = "".join((str(randoma), str(randomb)))
2.68126797676
def setnums():
randoma = str(random.randint(1, 5))
randomb = str(random.randint(100, 1000))
randoma += randomb
return int(randoma)
2.53426408768
Literal String Interpolation (PEP 498).
Splitting, Concatenating, and Joining Strings in Python
Use the 'str' function to convert randoma and randomb to strings, concatenate by using '=', then convert the concatenated string to integer by using the 'int' function.
Related
I am looking to create a list of 20 random numbers within a list
but looking to print the result of these numbers comma separated.
Getting an error when I am looking to format the Prinicipal list
below.
res = ('{:,}'.format(Principal))
TypeError: unsupported format string passed to list.__format__.
How can I fix this?
def inventory(i,j):
import random
Amount = random.choices([x for x in range(i,j+1) if x%25 == 0],k=20)
return Amount
def main():
Principal = inventory(100000, 1000000)
res = ('{:,}'.format(Principal))
print('\nInventory:\n', + str(res))
minAmt = min(Principal)
maxAmt = max(Principal)
res1 = ('{:,}'.format(minAmt))
res2 = ('{:,}'.format(maxAmt))
print('\nMin amount:' + str(res1))
print('\nMax amount:' + str(res2))
if __name__ == '__main__':
main()
Principal is a list of amounts and , is not a format specifier for lists. Print each amount individually:
import random
def inventory(i,j):
return random.choices([x for x in range(i,j+1) if x%25 == 0],k=20)
amounts = inventory(100000, 1000000)
print('\nInventory:\n')
for amount in amounts:
print(f'{amount:,}')
print(f'\nMin amount: {min(amounts):,}')
print(f'\nMax amount: {max(amounts):,}')
Output:
Inventory:
283,250
904,600
807,800
297,850
314,000
557,450
167,550
407,475
161,550
684,225
787,025
513,975
252,750
217,500
394,200
777,475
621,575
888,625
895,525
846,650
Min amount: 161,550
Max amount: 904,600
You are looking for str.join. E.g.
res = ','.join(map(str, Principal))
Also, the following is not a valid syntax:
print('\nInventory:\n', + str(res))
The + there is illegal.
Hey I have this function in python3 , can anyone explain why it is giving 1 as output instead of the number as reverse
def reverse(a , rev):
if a > 0:
d = a % 10
rev = (rev * 10) + d
reverse(a/10 , rev)
return rev
b = input("Enter the Number")
x = reverse(b , 0)
print(x)
You need to:
use integer division (//)
capture the value returned from the recursive call, and return it
convert the string input to number (int())
Corrected script:
def reverse(a, rev):
if a > 0:
d = a % 10
rev = (rev * 10) + d
return reverse(a//10, rev)
return rev
b = input("Enter the Number")
x = reverse(int(b), 0)
print(x)
I'm not sure why you're doing it like that. Seems like the following is easier
def rev(a):
return int(str(a)[::-1])
Anyway, I believe you should use "//" instead of "/" for dividing without the rest in python 3?
I tried running the following code. I tried returning value of j also but it just doesn't work.
def reverse(n):
j=0
while(n!=0):
j=j*10
j=j + (n%10)
n=n/10
print(j)
reverse(45)
Here is a program to reverse a number
def reverse(n):
v = []
for item in reversed(list(str(n))):
v.append(item)
return ''.join(v)
print(reverse("45"))
returns
54
The reverse() function creates an array, adds each digit from the input to said array, and then prints it as plain text. If you want the data from that as an integer then you can replace the return command to this at the end of the function
return int(''.join(v))
Actually, you made one mistake only: for Python 3 you need to use an integer division: n = n // 10.
Here is the correct code without str and list:
def reverse(n):
j = 0
while n != 0:
j = j * 10
j = j + (n%10)
n = n // 10
print(j)
reverse(12345)
Here is the correct code for Python 3:
import sys
def reverse(x):
while x>0:
sys.stdout.write(str(x%10))
x = x//10 # x = x/10 (Python 2)
print() # print (Python 2)
number = 45
int(str(number)[::-1])
a = 1234
a = int("".join(reversed(str(a))))
print a
This will give a = 4321
reversed functions returns an iterable object. If we do :
a = list(reversed(str(a)))
it will return [“3”,”2″,”1″]. We have then joined it and converted into int.
I'm creating a python script which prints out the whole song of '99 bottles of beer', but reversed. The only thing I cannot reverse is the numbers, being integers, not strings.
This is my full script,
def reverse(str):
return str[::-1]
def plural(word, b):
if b != 1:
return word + 's'
else:
return word
def line(b, ending):
print b or reverse('No more'), plural(reverse('bottle'), b), reverse(ending)
for i in range(99, 0, -1):
line(i, "of beer on the wall")
line(i, "of beer"
print reverse("Take one down, pass it around")
line(i-1, "of beer on the wall \n")
I understand my reverse function takes a string as an argument, however I do not know how to take in an integer, or , how to reverse the integer later on in the script.
Without converting the number to a string:
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n /= 10
return r
print(reverse_number(123))
You are approaching this in quite an odd way. You already have a reversing function, so why not make line just build the line the normal way around?
def line(bottles, ending):
return "{0} {1} {2}".format(bottles,
plural("bottle", bottles),
ending)
Which runs like:
>>> line(49, "of beer on the wall")
'49 bottles of beer on the wall'
Then pass the result to reverse:
>>> reverse(line(49, "of beer on the wall"))
'llaw eht no reeb fo selttob 94'
This makes it much easier to test each part of the code separately and see what's going on when you put it all together.
Something like this?
>>> x = 123
>>> str(x)
'123'
>>> str(x)[::-1]
'321'
best way is
x=12345
a=str(x)[::-1]\\ In this process i have create string of inverse of integer (a="54321")
a=int(a) \\ Here i have converted string a in integer
or
one line code is
a=int(str(x)[::-1]))
def reverse(x):
re = 0
negative = x < 0
MAX_BIG = 2 ** 31 -1
MIN_BIG = -2 ** 31
x = abs(x)
while x != 0:
a = int(x % 10)
re = re * 10 + a
x = int(x // 10)
reverse = -1 * re if negative else re
return 0 if reverse < MIN_BIG or reverse > MAX_BIG else reverse
this is for 32 - bit integer ( -2^31 ; 2^31-1 )
def reverse_number(n):
r = 0
while n > 0:
r = (r*10) + (n % 10)
print(r)
r *=10
n //= 10
return r
print(reverse_number(123))
You can cast an integer to string with str(i) and then use your reverse function.
The following line should do what you are looking for:
def line(b, ending):
print reverse(str(b)) or reverse('No more'), plural(reverse('bottle'),reverse(str(b))), reverse(ending)
Original number is taken in a
a = 123
We convert the int to string ,then reverse it and again convert in int and store reversed number in b
b = int("".join(reversed(str(a))))
Print the values of a and b
print(a,b)
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n /= 10
return r
print(reverse_number(123))
This code will not work if the number ends with zeros, example 100 and 1000 return 1
def reverse(num):
rev = 0
while(num != 0):
reminder = num % 10
rev = (rev * 10 ) + reminder
num = num // 10
print ("Reverse number is : " , rev )
num=input("enter number : ")
reverse(int(num))
#/ always results into float
#// division that results into whole number adjusted to the left in the number line
I think the following code should be good to reverse your positive integer.
You can use it as a function in your code.
n = input() # input is always taken as a string
rev = int(str(n)[::-1])
If you are having n as integer then you need to specify it as str here as shown. This is the quickest way to reverse a positive integer
import math
def Function(inputt):
a = 1
input2 = inputt
while(input2 > 9):
input2 = input2/10
a = a + 1
print("There are ", a, " numbers ")
N = 10
m = 1
print(" THe reverse numbers are: ")
for i in range(a):
l = (inputt%N)/m
print(math.floor(l), end = '')
N = N*10
m = m*10
print(" \n")
return 0
enter = int(input("Enter the number: "))
print(Function(enter))
More robust solution to handle negative numbers:
def reverse_integer(num):
sign = [1,-1][num < 0]
output = sign * int(str(abs(num))[::-1])
An easy and fast way to do it is as follows:
def reverse(x: int|str) -> int:
reverse_x = int(''.join([dgt for dgt in reversed(num:=str(x)) if dgt != '-']))
if '-' in num:
reverse_x = -reverse_x'
return reverse_x
First we create a list (using list comprehension) of the digits in reverse order. However, we must exclude the sign (otherwise the number would turn out like [3, 2, 1, -]). We now turn the list into a string using the ''.join() method.
Next we check if the original number had a negative sign in it. If it did, we would add a negative sign to reverse_x.
Easily you can write this class:
class reverse_number:
def __init__(self,rvs_num):
self.rvs_num = rvs_num
rvs_ed = int(str(rvs_num)[::-1])
print(rvs_ed)
You can use it by writing:
reverse_number(your number)
I have written it in a different way, but it works
def isPalindrome(x: int) -> bool:
if x<0:
return False
elif x<10:
return True
else:
rev=0
rem = x%10
quot = x//10
rev = rev*10+rem
while (quot>=10):
rem = quot%10
quot = quot//10
rev = rev*10+rem
rev = rev*10+quot
if rev==x:
return True
else:
return False
res=isPalindrome(1221)
I don't understand this question and confused. can anyone show me? It's an exercise in a python book. Only can use loop and function. And based on the question, have to ask the user to enter the number and width.
def format(number, width):
The function returns a string for the number with prefix 0s. The size
of the string is the width. For example, format(34, 4) returns "0034"
and format(34, 5) returns "00034". If the number is longer than the
width, the function returns the string representation for the number.
For example, format(34, 1) returns "34".
I don't quite understand what you mean by "Only can use loop and function". Since your can use function, you can use almost anything in Python.
The simplest solution:
def format(n,w):
s = str(n)
return ('0' * w + s)[-max(w,len(s)):]
>>> format(34,4)
'0034'
Or you can use a loop:
def format(n,w):
s = str(n)
result = ''
for i in range(w - len(s)):
result += '0'
return result + s
>>> format(34,1)
'34'
>>> format(34,4)
'0034'
Try:
def format(number, width):
numstr = str(number)
result = ''
numstrlen = len(numstr)
for i in range(width - numstrlen):
result += '0'
result += numstr
return result
I would have simply done subtraction, but you said it needed to be a loop.
If you can't use len:
def format(number, width):
numstr = str(number)
result = ''
numstrlen = 0
for c in numstr:
numstrlen += 1
for i in range(width - numstrlen):
result += '0'
result += numstr
return result