So I am trying to solve a problem, where a user will input a number and you have to find the next number that has all unique digits. For example:
Input: 1987, Output:
2013
Input:
999, Output:
1023
The way I thought of tackling this question was to go through every number after the number given by the user until I find a number that has all unique digits.
My question is that is there a way to check through every whole number greater than a number given. Until I find a specific one. So this is without a list or range. Just want to check every number until I find a specific type. Would I have to use a for loop or something similar.
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
num = 5
given = 10
new = [i for i in arr if i >= num and i <= given]
i dont know if this is what you wanted you did not specify it.
The beginner way - while True loop
i = int(input()) + 1
while True:
if digits_are_unique(i): # Undefined
break
i += 1
print(i)
The pro way - itertools.count()
import itertools
i = int(input()) + 1
for i in itertools.count(i):
if digits_are_unique(i): # Undefined
break
print(i)
Assignment expression - new in Python 3.8
Right now Python 3.8 is in beta and I don't have the interpreter to test this with, but it should work.
i = int(input()) + 1
while i := i + 1:
if digits_are_unique(i): # Undefined
break
print(i)
Related
This question already has answers here:
Scope of python variable in for loop
(10 answers)
Closed 9 years ago.
I am trying to do something as simple as changing the varible in which I am iterating over (i) but I am getting different behaviours in both Python and C.
In Python,
for i in range(10):
print i,
if i == 2:
i = 4;
I get 0 1 2 3 4 5 6 7 8 9, but the equivalent in C:
int i;
for (i = 0; i < 10; i++) {
printf("%d", i);
if (i == 2)
i = 4;
}
I get 01256789 (note that numbers 3 and 4 don't appear, as expected).
What's happening here?
Python has a few nice things happening in the background of for loops.
For example:
for i in range(10):
will constantly set i to be the next element in the range 0-10 no matter what.
If you want to do the equivalent in python you would do:
i = 0
while i < 10:
print(i)
if i == 2:
i = 4
else: # these line are
i += 1 # the correct way
i += 1 # note that this is wrong if you want 1,2,4,5,6,7,8,9
If you are trying to convert it to C then you have to remember that the i++ in the for loop will always add to the i.
The function range() creates a list.
For example, range(10) will create the following list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].
When you say for i in range(10), first off all the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] will be generated, and then i will be assigned all the values from that list, in order.
It doesn't matter if you change the value of i because on the next iteration it will be assigned the next element from the list.
It C/C++ on the other hand, at the end of each iteration the value of i is incremented and then compared to the maximum allowed value (in this case 9) and if it is greater, then the loop ends.
When you call range(10) you create an iteratable list [0,1,2,3,4,5,6,7,8,9].
And the for loop just pick up one number after the other from the list at each turn, whether or not you haved changed the value of i.
Python gives you the elements in range(10), one after another. C repeatedly increments a variable.
Both of them don't really care what else you do with the variable inside the loop, but since the two language constructs do slightly different things, the outcome is different in some cases.
You can not do this by using range function.
you have to do it by using while loop only because for loop uses range function and in range function variable will get incremented by its internal method no matter what you specify in the loop it will get incremented by range list only.
for i in range(10):
... print i
... if i == 2:
... i = 4
... else:
... i += 1
...
0
1
2
3
4
5
6
7
8
9
An interesting example is here....
for i in range(10):
... print i
... i = i + 10
... print i
...
this will print...
0
10
1
11
2
12
3
13
4
14
5
15
6
16
7
17
8
18
9
19
It's because when you use the range() function in python. Your variable i will be go through the value in range. For example,
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
However, the C language that you have written is just using the normally condition to change the value of i. There is no function involved.
a = [2, 5, 6, 12, 21, 25, 32, 41]
This is my list and I want to remove all the numbers which are not in difference of 7.
Before diving into the answers, let's go over what we're dealing with.
You got a list 'A', which you need to loop through to get a list of numbers that are greater than the previous value + 7
If you boil down the question, you get left with two main goals
We need a loop
and we have a list with the final answer
There are two generic ways of approaching this question. In a loop, we populate a new list. The second way is to manipulate the original list.
Although the First approach requires additional memory, I'll be using the First approach for simplicity.
a = [2, 5, 6, 12, 21, 25, 32, 41] # your original list
b = [] # Empty list that will contain final product
for i in range(len(a)):
if len(b) == 0: # if the list is empty, we add first item from 'a' (In our example, it'll be 2)
b.append(a[i])
else:
if a[i] > b[len(b)-1]+7 or a[i] < b[len(b)-1]-7: # for every value of a, we compare the last digit from list b
b.append(a[i])
As far as I have understood your question, in your output list, only those elements should be there whose sum is 7. So that can be achieved by
i=1;
while i<len(a):
if(a[i]-a[i-1] < 7):
a.remove(a[i])
else:
i+=1
print(a)
This is one of the lab questions: I try to create a program that generates a list of N random integers between 0 and 19 and computes the element strictly less than 5, 10, 15 and 20. I want to print all of the 'There are {} elements between x and y' statements.
When I run the program, it only shows the first one, and not the others. How do I correct it?
from random import randint
import sys
while True:
nb_of_elements = input('How many element do you want to generate? ')
try:
nb_of_elements = int(nb_of_elements)
break
except ValueError:
print('Input is not an integer, try again...')
L = [randint(0, 19) for _ in range (nb_of_elements)]
print('The list is :', L)
number = [0] * 4
for i in range (nb_of_elements):
number[L[i] // 5]+=1
for i in range(4):
if number[i] < 5:
print('There are {} elements between 0 and 4'.format (number[i]))
elif 5<= number[i] < 10:
print('There are {} elements between 5 and 9'.format(number[i]))
elif 10<= number[i] < 15:
print('There are {} elements between 10 and 14'.format(number[i]))
else:
print('There are {} elements between 15 and 20'.format(number[i]))
Your mistake is that you're attempting to count numbers in a range twice.
First, you use the trick with integer division:
for i in range (nb_of_elements):
number[L[i] // 5]+=1
So, number already contains the count of elements in the ranges 0--4, 5--9, 10--14 and 15--19 (inclusive).
Then, in your if-elif-elif-else block, you look at the value of number, whether it fits in any of these ranges. number, however, contains counts. On average, it will contain about nb_of_elements / 5 counts for each element.
You don't need the if-elif-elif-else block. Instead, loop through range(4) as you do know, and print each element number[i]. Each time, it'll correspond to the next range (you may need some smart thing to print the range. 5*i and 5*i+4 may do that).
It's kind-of interesting that you came up with a smart way to count the numbers in a range (number[L[i]//5] += 1), and then fell back to standard range comparison in an if-elif-else chain. I guess one can outsmart oneself.
You already have found a smart way to count fill the nb_of_elements list. Now you may want a smart way to print it. You can use enumerate to get the current index in the for loop: with this index, you can create the 'between X and Y' variables.
counts = [0] * 4
for i in range (nb_of_elements):
counts[L[i] // 5]+=1
# Loop the counts, and keep track of the index for enumerate
for i,count in enumerate(counts):
# i * 5 will be [0,5,10,15] and i * 5 + 5 will be [5,10,15,20]
print('There are {} elements between {} and {}'.format (count, i*5, i*5 + 5))
#The list is : [7, 10, 5]
#There are 0 elements between 0 and 5
#There are 2 elements between 5 and 10
#There are 1 elements between 10 and 15
#There are 0 elements between 15 and 20
In Python, a range is exclusive, meaning 'between 0 and 5' is [0,1,2,3,4]. I have chosen this notation for the print function as well: it now states 'between 0 and 5' (exclusive) instead of 'between 0 and 4' (inclusive) like you used in your code. This can of course be easily changed: i*5 + 5 > i*5 + 4.
def improve_bubble_sort(list_of_values):
count = 0
for i in range(len(list_of_values)):
for j in range(len(list_of_values)-1,i,-1):
if list_of_values[j]<list_of_values[j-1]:
count += 1
bubble(values)
count += 1
return count
I want to know whats wrong with this code, as when i test to print(improved_bubble_sort([1, 2, 3, 4, 5, 6]) the count comes to 6 instead of 5 :/ the bubble(values) code refers to another code which is all correct. any help would be great thanks !!
I am trying to understand these instructions.
Set up a new function in your main program file named “summer” that takes a list as a parameter and returns a value we will determine in the next steps.
In the “summer” function, set up a loop that uses a counter variable named “n” that will take on the values 0, 2, 4, 6, 8, 10, 12.
Each time through the loop, you are to call your “powerval” function from the “mymath” module passing as parameters item “n” and “n+1” from the list of data passed into “summer”. Add up all these values and return the final result to the caller.
So far I have:
def summer(list):
for n in range(0,13,2):
value=powerval(n,n+1)
After that I am lost. How do i perform step 3?
You add them up:
from mymath import powerval
def summer(somelist):
sum = 0
for n in range(0, 13, 2):
sum += powerval(somelist[n], somelist[n + 1])
return sum
So the return value of powerval() is added to the total sum so far, which was started at 0. You do need to pass in the somelist[n] and somelist[n + 1] values, not the indices themselves.
You need to add them up:
from mymath import powerval
def summer(lst):
total = 0
for n in range(0, 13, 2):
total += powerval(lst[n], lst[n + 1])
return total
I'm not sure where you use lst (I renamed list to lst, as list is a built-in function), so I'm guessing you're trying to get the nth and n + 1th elements from that list.
You can use the sum method to accomplish this in a very fashionable way :)
def summer(myList):
return sum(powerval(myList[n], myList[n+1]) for n in range(0, 13, 2))
This is also the fastest way.
PS: It's not a good idea to name you list "list", bacause that's a reserved name in python. That's why I have renamed it to myList in the example above.