Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Is it possible to add a random number create with random.randint to a Dict ? Or is it better to add it to a List. I ask because I wan to get random.randit(0,100) and check it the List or Dict have already the number that is now generated and print out the possition on which the second same number is
So I already tried it with append to a dict but that doesn' work!
EDIT
import random
randomdict = {}
numbposition = {}
def randomnumber(numb):
for i in random.randint(0,numb+1):
randomdict.append(i)
if i in randomdict:
numbposition.index(i)
print (numbposition)
print (randomdict)
while True:
numb = int(input('Give me number: '))
print(randomnumber(numb))
break
It is certainly possible to add the value returned by random.randint to a dictionary or list; it's just an integer, and can be treated like any other. However, you cannot append to a dictionary; that syntax is for adding to the end of a list, to add a new object to a dictionary use d[key] = value. Also, dictionaries don't have an index in the same way that e.g. lists and tuples do; just a key, and no guaranteed order.
Here is an example that is close to what you're describing:
import random
l = []
for _ in range(10):
n = random.randint(0, 10)
print(n)
if n not in l:
print("New item.")
l.append(n)
else:
print("Item found at index {0}.".format(l.index(n)))
print(l)
The output from this is:
2
New item.
2
Item found at index 0.
2
Item found at index 0.
1
New item.
3
New item.
10
New item.
6
New item.
4
New item.
4
Item found at index 5.
10
Item found at index 3.
[2, 1, 3, 10, 6, 4]
Edit
To add all numbers and get the largest preexisting index, you need a slight tweak:
if n not in l:
print("New item.")
else:
index = max(i for i, v in enumerate(l) if v == n)
print("Item found at index {0}.".format(index))
l.append(n)
Note that append is moved to the end (so the new n isn't in the list when we look for the largest prior index) and we can no longer use list.index (which finds the first index) - a more complex calculation is required.
This gives:
0
New item.
4
New item.
10
New item.
10
Item found at index 2.
3
New item.
4
Item found at index 1.
1
New item.
8
New item.
8
Item found at index 7.
1
Item found at index 6.
[0, 4, 10, 10, 3, 4, 1, 8, 8, 1]
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
In a for loop, let's assume it contains 100 iterations, and what I need is, i need to print the first element and skip the next two element, and then need to prit the fourth element.. for example,
0 #should print
1 #should skip
2 #should skip
3 #should print
4 #should skip
5 #should skip
6 #should print
.
. like wise
I tried some existing skipping solutions out this platform, but didn't fit for my problem.
I know the continue statement allows you to skip over the current iteration, but I can't figure out how to skip the next two iterations. Ttried some itertool fuctions also.
If you iterate on your own range, generate one over three elements
values = ["dog0", "dog1", "dog2", "dog3", "dog4", "dog5", "dog6"]
for i in range(0, 8, 3):
print(i, values[i])
If you iterate over an iterable of values, use enumerate to filter
values = ["dog0", "dog1", "dog2", "dog3", "dog4", "dog5", "dog6"]
for i, value in enumerate(values):
if i % 3 != 0:
continue
print(i, value)
One possible approach would be using enumerate and mod (%).
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8]
for index, num in enumerate(nums):
print(num) if index % 3 == 0 else None
If it's a range you can use the optional step argument range(start, stop, step)
for k in range(start, stop, 3): print(k)
or
for k in range(len(my_data), step=3): print(k)
If it's a list you can use list slicing
where once again the optional arguments for slicing is start, stop and step!
for k in my_array[::3]: print(k)
I would use enumerate as others have mentioned. Your problem basically consists in printing all positions [i] that are multipes of 3. You can use i%3 to detect when the iteration counter i is not a multiple of 3:
for i,x in enumerate(???):
if i%3: continue
print(x)
enumerate also works when you have an iterator f of unkown size (like when you read a file, etc.)
You can do something like this
arr = [1,2,3,4,5,6,7,8,9,10]
skip_count = 2 # how many to skip
counter = skip_count
for num in arr:
if counter == skip_count:
counter = 0
print(num)
else:
counter += 1
Alternatively, this will work too
arr = [1,2,3,4,5,6,7,8,9,10]
for index in range(0, len(arr), 3):
print(arr[index])
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
So I am trying to make a searching function. But that doesn't work right everytime. Gives the right output sometimes tough. Here is what i did:
import random
def normal_search(l, target):
# printing the list
l1 = l
x = ' '.join([str(l)])
print(f'The list is {x}')
choose = random.choice(l)
if choose == target:
index = l.index(choose)
index += 1
print(f"I found it! It's {index}. element.")
while choose != target:
l.remove(choose)
choose = random.choice(l)
print(choose)
index = l1.index(choose)
index += 1
print(f"normal_search I found it! It's {index}. element.")
# creating a shuffled list of 0 to 10
a = []
n = 0
while len(a) < 10:
n += 1
a.append(n)
random.shuffle(a)
normal_search(a, 5)
I am trying to get the target as output. What is making the output wrong?
I think the error is due to the fact that every time it does not find the target element the list decreases by 1 and if the removed element is before the target element it will change index.
I think the only solution is to stop removing the wrong elements, this would guarantee the correct functioning of the program but would increase its execution times.
import random
def normal_search(l, target):
# printing the list
x = ' '.join([str(l)])
print(f'The list is {x}')
while True:
choose = random.choice(l)
if choose == target:
index = l.index(choose)
index += 1
print(f"normal_search I found it! It's {index}. element.")
break
# creating a shuffled list of 0 to 10
a = list(range(10))
random.shuffle(a)
normal_search(a, 5)
As #FraRomee said, you are removing one element every step, suppose at first you have a list like: [0, 6, 4, 2, 3, 5, 1, 8, 9, 7], and index(5) is 6 and you randomly choose an element: 3 and it is not equal to 5 and you remove it, then you have [0, 6, 4, 2, 5, 1, 8, 9, 7] and length of list is 9 and index(5) is 5
and so on you choose 6 and remove it and you have [0, 4, 2, 5, 1, 8, 9, 7].
so if this time you select 5 correctly, index is 4 and it is correct for new list but is wrong for initial list and you cant use it for your own.
my code points:
you can create a list from a to b using list(range(a,b+1)) and you don't need while loop.
you can choose all elements from first in while body using break statement. if condition is False, so break loop, if not, go on and choose a new element.
I am currently attempting to make a program that will count and print the number of unique elements in a list.
My code:
def solution(N, A):
yee = 1
for i in range(1, len(A)):
j = 0
for j in range(i):
if(A[i] == A[j]):
yee-=1
if(i==j+1):
yee +=1
print(yee)
N = int(input())
A = []
n = 0
for e in input().split():
if(n<N):
A.append(int(e))
n+=1
solution(N, A)
With the list containing (1 2 3 1 4 2 5 6 7 8) the output is supposed to be 6. However, my program is returning 8. I believe this is due to the program counting the 1 and 2, even though they are not technically unique in the problem. I'm sure it's and easy fix, but I just can't seem to figure it out. Any help would be greatly appreciated!!
The only way you would get the output of 6 for (1, 2, 3, 1, 4, 2, 5, 6, 7, 8) would be if you wanted to count the number of elements that appear exactly once, as opposed to the number of unique elements (there are 8 elements, of which two are repeated more than once).
You could do this in a one-liner:
def num_single_elements(A):
return len(list(e for e in A if A.count(e) == 1))
Similarly if you need to keep check of the number of elements further on in your code, I like dictionary comprehension for this kind of problem:
dict_A = {x:A.count(x) for x in A}
print(len([x for x in dict_A if dict_A[x] == 1]))
As Green Cloak Guy said, you seem to be looking for the number of elements which appear exactly once, and his answer contains a solution to that. Here's a simple solution for finding the number of unique elements:
def unique_elements(A):
return len([ 1 for (index, a) in enumerate(A) if A.index(a) == index ])
The idea here is to count up the first occurrence of each unique value.
enumerate allows us to get the index of the item, as well as the item itself, as we iterate;
A.index(a) gives the index of the first time the value of a appears in A.
So, if we count up all the times index equals A.index(a), we're counting the first time an item appears which has never appeared before, which is equal to the number of unique elements.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
For example, the lists are [1,2,3],[4,5,6], and [7,8,9]. I want to add only the even numbers up in all the lists, so that would be 2+4+6+8=20. How would I go about doing this?
You can just do it like this for example:
l = [[1,2,3], [4,5,6], [7,8,9]]
sum(val for v in l for val in v if val % 2 ==0)
Simply loop through each list, and sum up the even values.
theSum = 0
lists = [[1,2,3],[4,5,6],[7,8,9]]
for list in lists:
for item in list:
if item % 2 == 0:
theSum += item
The (%) sign used in this context is known as modulus, it will return the number of remainders when a number is divided by another. So far example here, any number that can be divided by 2 without any remainders is an even number e.g. 8 % 2 returns 0.
if item % 2 == 0:
theSum += item
As you can see by the if statement, we go through all the items and test if they can be divided by 2 without leaving remainders. If they can be, we add them together.
Here is more information about modulus.
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
sum = 0
for x in a+b+c:
if x%2 == 0:
sum += x
There are many solutions, but here is a good start for you.
You can merge all the lists together into one list:
lst =[1,2,3] + [4,5,6] + [7,8,9]
Then you can make a list of just the evens:
new_list = [n for n in lst if is_even(n)]
Note: you must write is_even
def is_even(n):
# return True if even
# otherwise return False
Then you can iterate through the list and add up all the numbers in the list.
a=[1,2,3]
b=[4,5,6]
c=[7,8,9]
sum(filter(lambda x:x%2==0,a+b+c))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am brand new to python. I have been learning this on my own. I always make sure to exhaust every resource before asking a question on here.
but I will show you two sets of code. One does what I want, the other doesn't the only difference that appears to me, is how the ranges are set up. I don't understand the significance of this difference. Could someone please explain?
Thank you.
Code that works
def geometric(lst):
'checks whether the integers in list lst form a geometric sequence'
if len(lst) <= 1:
return True
ratio = lst[1]/lst[0]
for i in range(1, len(lst)-1):
if lst[i+1]/lst[i] != ratio:
return False
return True
**code that doesn't **
def geometric(integerList):
'checks whether the integers in list lst form a geometric sequence'
if len(lst) <= 1:
return True
ratio = integerList[1]/integerList[0]
for i in range (integerList[0], len(integerList))
if lst[i+1]/lst[i] != ratio:
return False
return True
In the first case, range(1, len(lst)-1) is a list
1, 2, 3, ..., len(lst)-1
In the second case, it depends on the value of the first list element. If integerList[0] is 3, then range() is
3, 4, 5, ..., len(lst)-1
and the first call of the if() statement compares integerList[4] / integerList[3] and ignores the first three elements in the list. So, the code only works, if integerList[0] == 1
However, there are two further pitfalls:
range() only takes integers as elements. If the first element is a float, pyhon will throw an error.
If the ratio always is an integer, you can compare the ratios for equality, as you do. But if ratio is a floating value, you can get into trouble: Though two ratios are mathematically equal, a computer (due to its floating point arithmetic) may calculate slightly different values. It is better to use
import math
...
if (math.fabs(lst[i+1]/lst[i] - ratio) < smallNumber)
where smallNumer is a very small number suitable for you.
By the way: In your second code, you use lst[] , but I guess, it was just a typo.
As Noelkd said, the range in your second code block starts with the value of the first element of the list, not its position.
If my list is the geometric sequence (1, 2, 4, 8, 16), your first block's range is
range(1, len(lst)-1) =
range(1, 5 - 1) =
range(1, 4) =
[1, 2, 3]
and your second block's range is
range(integerList[0], len(integerList)) =
range(1, 5) =
[1, 2, 3, 4]
This difference gets even weirder if my sequence doesn't start with 1, such as for the sequence (3, 9, 27):
First block's range is
range(1, len(lst)-1) =
range(1, 3 - 1) =
range(1, 2) =
[1]
and second block's range is
range(integerList[0], len(integerList)) =
range(3, 3) =
[]
for i in range(1, len(lst)-1):
...
This code first creates a list containing the numbers [1,2,3,...,len(lst)-1] and then loops over these values by setting i to a value in this list on every iteration.
for i in range (integerList[0], len(integerList))
This code actually creates a list containing the numbers:
[integerList[0],integerList[0] + 1,integerList[0] + 2,...,len(integerList)]
Here you're starting the range at integerList[0] not it's index. And if integerList[0] is bigger than len(integerList) you'll get an array with no values []
You also then try to use lst in the second function when really you're looking for integerList
This should help you understand what's happening:
>>> x = [2,4,5,6,7,8]
>>> for i in range(1,len(x)):
... print x[i]
...
4
5
6
7
8
So that's printing from the second to the last item.
>>> for i in range(x[0],len(x)):
... print x[i]
...
5
6
7
8
The second block is starting from x[0] which is 2 so from the third element to the last element.
Unless integerList[0] is always equal to 1 then you will not get the same range as range(1, len(lst)-1) which starts at 1, if integerList[0] == 5 your range will be range(5, len(integerList)) so you would miss elements from indexes 1 - 4 that you get in your first block of code and it would also throw an index error as lst[i+1] would be 1 index past the end of the list:
It would also be better to use enumerate:
def geometric(lst):
'checks whether the integers in list lst form a geometric sequence'
if len(lst) <= 1:
return True
ratio = lst[1] / lst[0]
for ind, ele in enumerate(lst[1:-1]):
if lst[ind+1] / ele != ratio:
return False
return True
In [4]: lst = ["foo","bar","foobar"]
In [5]: for ind, ele in enumerate(lst):
...: print ind,ele
...:
0 foo
1 bar
2 foobar