Making a variable a 'less than' value? - python-3.x

i'm really new to Python and am completely stuck
is there any way to make the less than value a variable
for example
x = int(input ("Input a value for x: "))
i = 1
while i < x:
x += i
i += 1
else:
print ("here is your new number:", x,)
whenever i use this, nothing happens
thanks for your help

It's not technically true to say that nothing happens, plenty is happening.
However, one thing that's not happening is the thing that generates the output (unless you enter a value less than or equal to one).
The while..else construct will only execute the else block if the while block did not do any iterations.
So, if you want output after the loop regardless of whether the loop body executes, get rid of the else and unindent the print.
The other thing that's not happening is the exit condition of the loop itself. If i starts out less than x (and they're both positive to start with), adding i to x then adding 1 to i will never give you a situation where i is not less than x.
Think about (for example):
x i Description
----- ----- -----------
3 1 Initial state
4 2 x += i; i += 1;
6 3 x += i; i += 1;
9 4 x += i; i += 1;
13 5 x += i; i += 1;
18 6 x += i; i += 1;
24 7 x += i; i += 1;
31 8 x += i; i += 1;
You can see that x is increasing at a faster rate than i, hence i < x will always be true.
How you fix that depends entirely on what you're trying to achieve. Since you have described your problem in terms of the code, your code matches perfectly your requirements. Hence, since you state it's not working as you expected, it appears your requirements may need some work :-)
I would suggest stating, in English, what you're trying to achieve here, and we can then suggest where your implementation has gone wrong.

What you wrote will result in an infinite loop if i < x in the beginning. So it will never reach the print statement that you hope it will. Plus, I also believe that you have to delete the else and indent the print statement.

Related

Why i = 1, and i = i + 1 would become 2?

i = 1
i = i + 1
print(i)
I am pretty confused about the code's logic. Why would i eventually become 2?
Lets begin with the first assignment:
i = 1
This creates the variable i and initialize it to the integer value 1.
Then we get to what you seem to have problem understanding:
i = i + 1
This statement can be split into two parts:
The addition
The assignment
The addition i + 1 will take the current values of the variable i, which is 1, and add the value 1 to that. In essence the expression i + 1 is the same as 1 + 1.
The result of the addition will be 2. And this result is then assigned to the variable i, making the value of i be equal to 2.
You then print the (new) current value of i:
print(i)
This will of course print the value 2.
The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1.
Just for completeness:
x += y is not always doing an in-place operation, there are (at least) three exceptions:
If x doesn't implement an __iadd__ method then the x += y statement is just a shorthand for x = x + y. This would be the case if x was something like an int
If __iadd__ returns NotImplemented, Python falls back to x = x + y.
The __iadd__ method could theoretically be implemented to not work in place. It'd be really weird to do that, though.
As it happens your bs are numpy.ndarrays which implements __iadd__ and return itself so your second loop modifies the original array in-place.
You can read more on this in the Python documentation of "Emulating Numeric Types".
'i' is a variable which stored 1 if We add 1 again in 'i' that means
i=1;
i+1 means 1+1=2
i=1
i=i+1// i has already 1 and here we are adding 1 again so result will be 2.
hope you understood.
Let's start from i = 1. So you are assigning i to 1. Now your situation is:
i = i + 1
So if i is 1, then the abovementioned code would be "translated" to:
i = 1 + 1
That's why i = i + 1 is equal to 2.

Polydivisible Calculator Fails, Despite Previous Implementation Working

To begin, a definition:
A polydivisible number is an integer number where the first n digits of the number (from left to right) is perfectly divisible by n. For example, the integer 141 is polydivisible since:
1 % 1 == 0
14 % 2 == 0
141 % 3 == 0
I'm working on a recursive polydivisible checker, which, given a number, will check to see if that number is polydivisible, and if not, recursively check every other number after until it reaches a number that is polydivisible.
Unfortunately, my code doesn't work the way I want it to. Interestingly, when I input a number that is already polydivisible, it does its job and outputs that polydivisible number. The problem occurs when I input a non-polydivisible number, such as 13. The next polydivisible number should be 14, yet the program fails to output it. Instead, it gets stuck in an infinite loop until the memory runs out.
Here's the code I have:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
else:
return num
else:
print("Number must be non-negative")
return None
I'm assuming the problem occurs in the else statement inside the while loop, where, if the number fails to be polydivisible, the program resets i to 0, and adds 1 to the original number so it can start checking the new number. However, like I explained, it doesn't work the way I want it to.
Any idea what might be wrong with the code, and how to make sure it stops and outputs the correct polydivisible number when it reaches one (like 14)?
(Also note that this checker is only supposed to accept non-negative numbers, hence the initial if conditional)
The mistake is that you are no updating number after incrementing num.
Here is working code:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
number = str(num) # added line
else:
return num
else:
print("Number must be non-negative")
return None
I have a similar answer to #PranavaGande, the reason is I did not find any way to iterate an Int. Probably because there isn't one...Duh !!!
def is_polydivisible(n):
str_n = str(n)
list_2 = []
for i in range(len(str_n)):
list_2.append(len(str_n[:i+1]))
print(list_2)
list_1 = []
new_n = 0
for i in range(len(str_n)):
new_n = int(str_n[:i+1])
list_1.append(new_n)
print(list_1)
products_of_lists = []
for n1, n2 in zip(list_1, list_2):
products_of_lists.append(n1 % n2)
print(products_of_lists)
for val in products_of_lists:
if val != 0:
return False
return True
Now, I apologise for this many lines of code as it has to be smaller. However every integer has to be split individually and then divided by its index [Starting from 1 not 0]. Therefore I found it easier to list both of them and divide them index wise.
There is much shorter code than mine, however I hope this serves the purpose to find if the number is Polydivisible or Not. Of-Course you can tweak the code to find the values, where the quotient goes into decimals, returning a remainder which is Non-zero.

Check if number has a digit multiple times

I've come across a puzzling challenge. I have to check if a number contains the same digit multiple times ex. 11, 424, 66 and so on. at first this seems easy enough but i'm having trouble coming up with a logic to check for this. any ideas?
This is what I've got so far. the function takes in a list. (updated)
arr = [[1,20],[1,10]]
for i in arr:
l = list(range(i[0],i[1]))
for num in l:
if num < 11: continue
for c in str(num):
if str(num).count(c) > 1:
# dont know why code is popping off 12 and 13
print(l.pop(num))
If your ultimate goal is simply detecting if there's a double, this function may help:
def has_doubles(n):
return len(set(str(n))) < len(str(n))
The best way I can think about is converting the number to a string and doing a Counter on it
from collections import Counter
a = 98
c = Counter(str(a))
if any(value > 1 for value in c.values()):
print "The number has repeating digits"
#Two-BitAlchemist thanks for the suggestion
looks like you wanted to create your own algorithm probably researching or a student practice well you just have to understand the properties of numbers divided by 10 where 1/10 = 0.1 10/10 = 1 13/10 = 1 reminder 3 13013/10 = 1301 rem 3 hence we can create a function that stores the reminders in an array an check them against the reminder of next number here is the algorithm in python using recursion, you can achieve the same via loops
def countNumber(foundDigits,number):
next_number = int(number/10);
reminder = number % 10;
if(next_number < 1):
for num in foundDigits:
if(num == number or num == reminder):
return True
return False;
foundDigits.append(reminder);
return countNumber(foundDigits,next_number)
example in interpreter could be
digitsFound = list()
countNumber(digitsFound, 435229)
Solved this! I didn't know pop executes based on position not value! remove is a better fit here.
arr = [[1,40],[1,10]]
for i in arr:
l = list(range(i[0],i[1]))
for num in l:
if num < 11: continue
for char in str(num):
if str(num).count(char) < 2: continue
l.remove(num)
break
print(l)
Here is my solution, its simple and works for 2 digit numbers.
nums = list(input().rstrip().split())
def has_doubles(nums):
for number in nums:
if number[0] == number[1]:
print(number)
else:
continue
has_doubles(nums)

How to create function that returns 'change in highest denominations'

I am trying to make a programme that will return the correct change, in the highest denominations possible
i.e $73 will return 1 x $50, 1 x $20, 1 x $2 and 1 $1
(I am using whole values of $100, $50, $20, $10, $5, $2, $1)
I have a long code that works...it is
hundred = x // 100
hundred_remainder = x % 100
fifty = hundred_remainder // 50
fifty_remainder = hundred_remainder % 50
twenty = fifty_remainder // 20
etc....then
if hundred > 0:
print (str(hundred) + " x $100")
if fifty> 0:
print (str(fifty) + " x $50")
etc....which works fine, but I know there must be a way of writing a function that has a loop to work it out with less typing. Something like X = $345, then it gets 3 x $100, subtracts that from the total and updates X with the remainder, then repeats the process going through each denomination, until complete. I'm just a bit unsure how to figure it out, any guidance will be greatly appreciated!
I think a cool model for this problem is defining the values that you consider "legal" up-front, and then iterating over those from the top to the bottom to reach your counts. Consider the following loop:
#where x is the value from which you're making change
legal = [100,50,20,10,5,2,1,.50,.25,.10,.05,.01]
for dolAmount in legal:
count = x//dolAmount
if count > 0:
print int(count),\
dolAmount,\
" coin(s)" if dolAmount<1 else " dollar bill(s)"
x-=count*dolAmount
# prints lines like this for x=103.58:
#
# 1 100 dollar bill(s)
# 3 1 dollars bill(s)
# 1 0.5 coin(s)
# 1 0.05 coim(s)
# 3 0.01 coin(s)
# ehhh actually it will probably say 2 0.01 coin(s) because floating points....
The formatting needs work (what the heck is a 0.5 coin?), but this is a neat way of saving yourself a lot of code-writing, and the pattern is applicable to other programming endeavors. In general, when you find yourself creating a lot of variables/constants by hand, it's probably time to start thinking about a list (or similar collection)!
Check out http://www.codeskulptor.org/#user39_ur6ybhs9HAmknOL.py for a learning-example of what this would look like in practice (used within a function!) Happy coding!
I did something similar in C a few weeks ago; I do not know Python well, so Im just going to write the logic of the function. Im sure you will be able to translate it flawlessly to Python ;)
We know that the highest bill is that of $100;
So, say we have an ammount of $335.
What we should do first is create an int variable for each Bill denomination.
int b100 = 0;
int b50 = 0;
int b20 = 0;
int b10 = 0;
int b5 = 0;
int b2 = 0;
int b1 = 0;
Then, we should make a while loop:
while(ammount >= 100){
ammount = ammount - 100;
b100++;
}
here what we did is obtain the total ammount of $100 bills that we'll need.
After this while loop ammount must be equals to 35, and b100 should have a value of 3;
then we repeat the code with the next bill:
while(ammount >= 50){
ammount = ammount - 50;
b50++;
}
In this case, as ammount has a value of 35, and it's lower that 50, it won't enter the while loop; instead it will pass to the next one:
while(ammount >= 20){
ammount = ammount - 20;
b20++;
}
Etc....
After all those whiles we should have ammount with a value of '0';
And the bills variables with the quantity of bills required.
In the example of $335 the variables value should be like this:
$100 bills --> 3 $20 bills --> 1 $10 bills --> 1 $5 bills --> 1
Hope it helped, any doubts feel free to ask ;)

Prime number python nested loops

I am new to python and I am having some problems with this code that should print all the prime numbers that are smaller than 50 using nested loops.
Here is the code:
i = 2
while(i < 50):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j):
print(i, " is prime")
i = i + 1
Its output is:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
So after 3, j should be 2 and i should be 4. Then it's not a prime number, so it goes back to the while loop.
And the process starts over. j and i should be incremented by one. So j should be 3 and i should be 5, 5 is prime, then it increments again to 6.
So j should still be 3 and i should be 6. But (3 <= (6/3)) <-- this is not true, so it goes to if statement and 3 which is j is bigger than 2 which is i/j, which means 6 should be prime.
But it's not. You can tell that by common sense. And I want to know what part I did wrong here. Did I miss any increments here? Thank you.
First of all, I would like to post the correct syntax for the code.
i = 2
while(i < 50):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j):
print(i, " is prime")
i = i + 1
By writing the code like this, we are able to do several things. The first thing we are able to do is get a nice visual of what is inside of what, instead of assuming anything. The second thing that we are able to do is see what is being incremented where.
Now, let us approach what is going on inside of this code. The first to realize is that we are starting off with i=2. We are then initializing a while loop that is going to stop when i is greater than 50.
So, now we are inside of the first while loop, and the next thing we are doing is calling j. This variable is equal to 2, as we can see. Not only is it equal to 2, but every time we go down to the bottom of this FIRST WHILE LOOP THAT ENDS WHEN i >=50, we go back to the start and reinitialize j to be 2 again.
This means that j is never going to start out to be two, even though we are adding to j in the SECOND (NESTED) while loop.
Everything from here should make sense, if I understood your question right. The only thing that is weird about this code, in my opinion is the:
if not (i%j)
This seems a little odd, for it would be more clerical if it said:
if (i%j == 0):
break
If you have any other questions, please feel free to ask. And if you find this helpful, feel free to accept it as your answer :)
The indented code is as follows.
i = 2
while(i < 50):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j) :
print(i, " is prime")
i = i + 1
In your code, j is getting initialized to 2 with every increment of i.
See this snippet if not(i%j): break
If any j divides i, the if not(i%j) becomes true and the loop breaks but j <= (i/j) still holds else control wouldn't have entered this loop. So control skips print(i, " is prime")
So only way if(j > i/j) becomes true is when above loop never breaks. That would mean i didn't get any divisor, hence i is a prime.
I made this infinite prime number generator:
def primes_generator():
n = 1
while True:
for x in range(2, n):
if n % x == 0:
#not prime
break
else:
#prime
yield n
n+=1
you can use it like:
primes = primes_iterator()
for prime in primes:
print(i)

Resources