I'm really a beginner with python and in classe I'm analyzing a coin toss task. The number of tosses is 1000, the results possible are 1,2. I'm asked to create row with sequences of same results (such as 1 1 1 1 1 1 1 1 and then 2 2 2 2 2,..) and give the length of the longest appearing sequence.
from numpy.random import randint, seed
seed(0)
for n in range(1000):
r = randint(1,3)
print(r)
which gives me a single column reporting the results as follows
1
2
1
1
2
1
1
I can't manage to find the appropriate code to create those rows of sequences of same results.
You are printing the result of each iteration of your for loop.
A simple solution is to create 2 lists, each containing every occurrence of either 1 or 2:
list1 = []
list2 = []
In your for loop, you can use the list.append method to add the value of r to the corresponding list:
for n in range(1000):
r = randint(1, 3)
if r == 1:
list1.append(r)
else:
list2.append(r)
This way, list1 contains every occurrence of the number 1, and list2 contains all the number 2.
You can now print both list, and use len() to get the number of elements in each list.
Try this:
count1 = 0
count2 = 0
for n in range(1000):
r = randint(1, 3)
if r == 1:
count1 += 1
elif r == 2:
count2 += 1
if count1 > count2:
print('1'*count1)
print('2'*count2)
print('Longest sequence is of 1\'s, with %s occurences' %count1)
else:
print('1'*count1)
print('2'*count2)
print('Longest sequence is of 2\'s, with %s occurences' %count2)
Related
I came up with this logic to count the duplicate
1 take input for list length
2 take input of list
3 search in list for the values from zero to last index increment the counter.
I am getting error can anyone help to fix it, I know my this not accurate way to do this can someone help me out
n = int(input())
l1=[]
for i in range(n):
l1.append(input())
print(l1)
count1=0
count2=0
count3=0
count4=0
for j in range(n):
if 1 in l1[0,n-1]:
count1 =count1+1
elif 2 in l1(0,n-1):
count2=count2+1
elif 3 in l1(0,n-1):
count3= count3+1
elif 4 in l1(0,n-1):
count4=count4+1
print(count1)
input
4
1
1
2
3
4
output should be 2
Simply use set() to remove the duplicates from the original list, then take the length of the original list minus the length of the new set:
s = set(l1)
count = len(l1) - len(s)
I don't think this is the optimal way to do it, but it is the shortest and most intuitive way.
There is a pre built function in list to count the elements
data = [1,2,3,4,1,4]
print("Count of 1 =", data.count(1))
print("Count of 2 =", data.count(2))
print("Count of 3 =", data.count(3))
print("Count of 4 =", data.count(4))
But if the number of duplicate elements is what is expected then count of all the elements and sort only those greater than 1.
Get all number of elements which are duplicate
data = [1,2,3,4,1,4]
print(len([data.count(x) for x in list(set(data)) if data.count(x)>1]))
LeetCode: longest consecutive sequence
Question:Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums = [0,3,7,2,5,8,4,6,0,1]
nums = list(set(nums)) # O(n) operation
res = 0
count = 1
if len(nums)==1: # edge case
res = 1
for i in range(len(nums)-1):
if abs(nums[i] - nums[i+1]) == 1:
count+=1
print(count)
else:
res = max(res, count)
count = 1
print(res)```
this prints as follows (print(count)) adds an unneccessary
2
3
4
5
6
7
8
9
0
And when input is nums = [100,4,200,1,3,2]
Output is for print(count):
2
3
3
Count variable is misbehaving
This one should work efficiently enough (for each element,the set is accessed about 3 times so, including the creation of the set, that would make the complexity O(4n), which is still O(n)):
def longest_seq(a: list) -> int :
a = set(a)
max_seq = 0
for i in a:
if i-1 in a:
continue
else:
j= i+1
while j in a:
j += 1
max_seq = max(max_seq, j-i)
return max_seq
You could also do something like this, without using sets. Just create an array of zeros and assign the values of the given array variables as one and calculate the max_seq.
def longest_seq(a: list) -> int :
bit = [0 for i in range(max(a)+2)]
for i in a:
bit[i] = 1
max_seq = count = 1
for i in range(1,len(bit)):
if bit[i] == bit[i-1] == 1:
count+=1
else:
max_seq = max(max_seq, count)
count = 1
return max_seq
print(longest_seq([5,4,7,8,1,2,3,4,9,10,11,12,13])) # ans = 7
I'm trying to get this program to return all possible multiples of 3 and 5 below 1001 and then add them all together and print it but for some reason these lines of code only seem to be printing one number and that number is the number 2 which is obviously wrong. Can someone point me in the right direction to why this code is grossly wrong?
n = 0
x = n<1001
while (n < 1001):
s = x%3 + x%5
print s
You've got a few mistakes:
x is a boolean type
Your loop never ends
adding values to mimic lists?
Edit
Didn't see the part where you wanted sum, so you could employ a for-in loop or just a simple one like so:
sum = 0
for i in range(1001):
if(i % 3 == 0 or i % 5):
sum += i
print(sum)
(Python 3)
You need to stop while at some point by incrementing n. Here is some code:
nums = []
n = 0
while (n < 1001):
# in here you check for the multiples
# then append using nums.append()
n += 1
This creates a loop and a list that accounts for every number in 0 to 1000. In the body, check for either condition and append to the list, then print out the values in the list.
num is a list where you are going to store all the values that apply, (those numbers who are divisible by 3 and 5, which you calculate with modulo). You append to that list when a condition is met. Here is some code:
nums = []
n = 0
while (n < 1001):
if(n % 3 == 0 or n % 5 ==0):
nums.append(n)
n += 1
print(n) #or for loop for each value
Explanation: a list of numbers called num stores the numbers that are divisible by 3 or 5. The loop starts at zero and goes to 1000, and for all the values that are divisible by 3 or 5, they will be added to the list. Then it prints the list.
Of course there is a simpler approach with a range:
for i in range(1001):
if(i % 3 == 0 or i % 5 == 0):
print(i)
This will print out all the values one by one. It is 1001 because the upper limit is exclusive.
true=1
false=0
so:
x = n<1001
we have x=1 because 0<1001 is true
s = x%3 + x%5
the remainder of 1/3 is 1 and 1/5 is 1
In your code:
1. x=n<1001 - generates a boolean value; on which we can't perform a mathematical operation.
In while loop:
your variable n,x are not changing; they are constant to same value for all the iterations.
Solution 1:
Below code will help you out.
s=0
for i in range(1,1002):
if( i%3 == 0 or i%5 == 0):
s = s + i
print(s)
Solution: 2
There is one more approach you can use.
var = [i for i in range(1,1002) if i%3==0 or i%5 ==0]
print(sum(var))
I wrote the program below to iterate through every possible poker hand and count how many of these hands are a single pair
A hand is any 5 cards.
A single pair is when two cards of the same rank (number) and the other 3 cards of all different ranks e.g. (1,2,1,3,4)
I am representing the deck of cards as a list of numbers e.g.
- 1 = ACE
- 2 = Two
- 3 = Three
...
- 11 = Jack
- 12 = Queen...
The program seems to work find however,
the number of single pair hands it finds = 1101984
But according to multiple sources the correct answer is 1098240.
Can anyone see where the error in my code is?
from itertools import combinations
# Generating the deck
deck = []
for i in range(52):
deck.append(i%13 + 1)
def pairCount(hand):
paircount = 0
for i in hand:
count = 0
for x in hand:
if x == i:
count += 1
if count == 2:
paircount += .5 #Adding 0.5 because each pair is counted twice
return paircount
count = 0
for i in combinations(deck, 5): # loop through all combinations of 5
if pairCount(i) == 1:
count += 1
print(count)
The issue is that your hand can contain the following type of cards as well -
A Three of a kind and a single pair
You are actually calculating this as a single pair as well.
I modified the code to count just the number of hands such that it contains a three of a kind as well as a single pair together. Code -
deck = []
for i in range(52):
deck.append((i//13 + 1, i%13 + 1))
def pairCount(hand):
paircount = 0
threecount = 0
for i in hand:
count = 0
for x in hand:
if x[1] == i[1]:
count += 1
if count == 2:
paircount += .5 #Adding 0.5 because each pair is counted twice
if count == 3:
threecount += 0.33333333
return (round(paircount, 0) , round(threecount, 0))
count = 0
for i in combinations(deck, 5):
if pairCount(i) == (1.0, 1.0):
count += 1
This counted the number as - 3744.
Now, if we subtract this number from the number you got - 1101984 - We get the number you are expecting - 1098240 .
I have written the following block:
number = 12
def checkio(number):
count = 0
for n in bin(number):
print n
if n == 1:
count += 1
print count
checkio(number)
The output I get is:
0
0
b
0
1
0
1
0
0
0
0
0
I can't understand why I'm able to iterate through n in the binary number and print it, but my if won't work correctly and won't add to my count variable.
Why does this happen?
When you iterate through the string produced by bin, each character is itself a one-character string. So the reason this doesn't work is, simply:
1 != '1'
You will need to convert the characters back into integers to compare (be aware that int('b') won't work!), or compare to a string:
if n == '1':
The check should be "if n == '1'".