How to get random similar integers of the format like input? - python

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)

Related

What is the function for Varied amount input data for Python?

Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max.
Ex: If the input is:
15 20 0 5
the output is:
10 20
nums = []
# initialse
number = 0
# loop until there isn't an input
while number != "":
# ask for user input
number = input('Enter number:')
# validate the input isn't blank
# prevents errors
if number != "":
# make input integer and add it to list
nums.append(int(number))
avg = sum(nums) / len(nums)
print(max(nums), avg)
All is gives me is Enter number:
I solved the problem correctly using this:
user_input = input()
tokens = user_input.split() # Split into separate strings
nums = []
for token in tokens: # Convert strings to integers
nums.append(int(token))
avg = sum(nums) / len(nums) # Calculates average of all integers in nums
print(int(avg), max(nums)) # Prints avg as an Integer instead of a Float
nums = []
# loop until there isn't an input
while not nums:
# ask for user input
number = input()
nums = [int(x) for x in number.split() if x]
avg = int(sum(nums) / len(nums))
print(avg, max(nums))
Zybooks
9.16 LAB: Varied amount of input data
user_input = input().split(" ")
average = 0.00
for x in range(len(user_input)):
average += float(user_input[x])
user_input[x] = float(user_input[x])
average = float(average) / len(user_input)
print(f'{max(user_input):.2f} {round(average,2):.2f}')

I need to calculate mean, median and std but asking the user numbers until user puts 0

import numpy as np
count = 0
number = 1
while number != 0:
number = int(input("Enter values"))
print(np.mean(number))
print(np.median(number))
print(np.std(number))
if count == 0:
print("let's see some values")
print(np.mean(number))
print(np.median(number))
print(np.std(number))
So far this is what I got but I keep getting an error when trying to run it. It's not allowing me to input many values
This is your code Fixed:
import numpy as np
numbers = []
number = input("Enter values: ")
number = number.split()
for n in number:
if n == "0":
break
numbers.append(int(n))
print(numbers)
print("Mean is {:.2f}".format(np.mean(numbers)))
print("Median is {:.2f}".format(np.median(numbers)))
print("Standard deviation is {:.2f}".format(np.std(numbers)))
You need to enter values separated with space then split at white spaces and store splitted values in an array then convert each element into an int to operate on.

Python- Find nearest greater number with unique digits

I came across this problem in which you will take an integer as a input from the user and then return the nearest greater number with unique digits.
First it seem like an easy one and i wrote it's code which gave me an desired outputs but for some inputs returns an integer with repeating digits or a unique number with higher value then expected,
I want to know why my code is showing different behaviour than expected and what would be the right answer to this problem.
Also i don't know what to do when a digit will become two digit number how to make it unique eg. 9999
code
n = int(input("enter a no.:"))+1 #taking input adding 1 to make sure if the input is
#unique it should return higher no. with uniq
a =[] #creating an empty list
while n!=0: #loop to store digits in a list
a.append(n%10) #at index 0 ones digit is stored
n = int(n/10) #at index 1 tens digit is stored an so on...
while len(set(a)) != len(a): #checking if the list is unique
for i in range(0,len(a)): #
occur = a.count(a[i]) #taking occurence of a list item
if occur != 1: #if no. is repeated
a[i]+=occur-1 #incrementing the repeating digit.
a.reverse() #converting list to integer and printing
n = 0
for i in a:
n = n*10+i
print(n)
Behaviour
1.Printing repeating digits for some inputs
2.Printing Higher values than expected for some inputs
3.When a digit becomes a two digit no. it treats it like a single digit
Some outputs
enter a no.:1233
output: 1234 #desired output: 1234
enter a no.:7885
output: 7896 #desired output: 7890
enter a no.:7886
output: 8008 #desired output: 7890
enter a no.:999
output: 2013 #desired output: 1023
You're probably over complicating this for yourself.
Would something like this work rather than doing all of the conversions?
n = int(input("enter a no.:"))+1 #taking input adding 1 to make
#sure if the input is unique then
#program does't return the input itself
a = str(n) # simply convert to a string
while len(set(a)) != len(a): #checking if the string is unique
n += 1
a = str(n)
print(n)
Why not simply increment the number until you find one with unique digits?
def next_uniq(n):
a = str(n)
while len(set(a)) != len(a):
a = str(int(a) + 1)
return a
for i in [1233, 7885, 7886, 999]:
print(next_uniq(i))
# 1234, 7890, 7890, 1023

Get Better Time Complexity

This code is for asserting values into the list until the user inputs a negative number.
Is there a way better to implement it?
Below is my tried version.
i = -1
while i > -1:
x = raw_input("Enter array limit")
for i in limit(x):
listArr = list()
y = raw_input("Enter number")
y.append(listArr)
print (listArr)
Something like this should meet the requirements:
odds = [] # similiar to `listArr` but we only want odd numbers
limit = 5
for _ in range(limit): # Input 5 numbers into an array
y = int(input('Enter number: '))
if y > -1 and y % 2 !=0: # if odd number
odds.append(y) # add to array
else:
break # break after a negative number as input
if odds:
print(min(odds)) # and display minimum odd number
# and if no negative integer input then also display minimum odd number
else:
print(0) # and if no odd number display zero
If Python2 use raw_input() as used in question code, otherwise use input().

Python-an integer is required

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.

Categories