I have a list like below
list1 = [cont1,cont2,cont4,cont5]
how do i implement round robin logic in python to select elements of a list,
each time i try to access element
I'd suggest using itertools.cycle.
Make an iterator returning elements from the iterable and saving a
copy of each. When the iterable is exhausted, return elements from the
saved copy. Repeats indefinitely.
Sample usage:
seq = [1,2,3,4]
round_robin = itertools.cycle(seq)
assert round_robin.next() == 1
assert round_robin.next() == 2
assert round_robin.next() == 3
assert round_robin.next() == 4
assert round_robin.next() == 1
assert round_robin.next() == 2
assert round_robin.next() == 3
assert round_robin.next() == 4
seq = [1,2,3,4]
n = -1
def round_rob_seq():
global n
n = n + 1
return seq[n % len(seq)]
or
def round_rob_seq():
global n
n = n + 1
if n == len(seq):
n = 0
return seq[n]
Related
populate each hand with two cards. Take a card from the deck
and put it in the player_hand list. Then, take a card from the deck and
put it in the dealer_hand list. Do that one more time in that order so that the dealer and player have each two cards. Make sure the dealer's first card is face down. I keep receiving this error from my 2 tests.
My code:
while len(dealer_hand) != 2 and len(player_hand) != 2:
player_card = random.choice(deck)
player_hand.append(player_card)
deck.remove(player_card)
if len(player_hand) == 2:
player_hand[0].face_up()
player_hand[1].face_up()
dealer_card = random.choice(deck)
dealer_hand.append(dealer_card)
deck.remove(dealer_card)
if len(dealer_hand) == 2:
dealer_hand[0].face_down()
dealer_hand[1].face_up()
return player_hand and dealer_hand
False != True
Expected :True
Actual :False
def test_deal_cards():
deck = []
for suit in cards.SUITS:
for rank in cards.RANKS:
deck.append(cards.Card(suit, rank))
dealer_hand = []
player_hand = []
blackjack.deal_cards(deck, dealer_hand, player_hand)
assert len(dealer_hand) == 2
assert len(player_hand) == 2
> assert dealer_hand[0].is_face_up() is True
E assert False is True
E + where False = <bound method Card.is_face_up of [10 of Hearts]>()
E + where <bound method Card.is_face_up of [10 of Hearts]> = [10 of Hearts].is_face_up
test_deal_cards.py:19: AssertionError
(test_deal_cards_alternates_between_player_and_dealer)
[7 of Hearts] != [6 of Spades]
Expected :[6 of Spades]
Actual :[7 of Hearts]
def test_deal_cards_alternates_between_player_and_dealer():
card1 = cards.Card(cards.SPADES, cards.SIX)
card2 = cards.Card(cards.HEARTS, cards.SEVEN)
card3 = cards.Card(cards.CLUBS, cards.EIGHT)
card4 = cards.Card(cards.DIAMONDS, cards.NINE)
deck = [card4, card3, card2, card1]
dealer_hand = []
player_hand = []
blackjack.deal_cards(deck, dealer_hand, player_hand)
assert len(dealer_hand) == 2
assert len(player_hand) == 2
> assert player_hand[0] is card1, 'Player 1st card should be Six of Spades'
E AssertionError: Player 1st card should be Six of Spades
E assert [7 of Hearts] is [6 of Spades]
test_deal_cards.py:39: AssertionError
I think the error lies within the first line:
while len(dealer_hand) and len(player_hand) != 2:
If you want to check if the dealer also has 2 cards, you need to fix that line to:
while len(dealer_hand) != 2 and len(player_hand) != 2:
This is my code. I have looked at many similar codes and have mine set up exactly how I should. I do not receive an error!
The problem is the output I receive is [11]. When the user inputs [1,2,3,4,5,6,7,8,9,11]. Why is it only pulling one odd number??
totlist = []
max_int = 10
oddlist = []
while len(totlist) < max_int:
nums = int(input('Enter a number: '))
totlist.append(nums)
def find_odds(totlist, oddlist):
if len(totlist) == 0:
return
v = totlist.pop()
if v % 2 == 1:
oddlist.append(v)
find_odds(totlist,oddlist)
print(oddlist)
You have forgoot the loop boucle inside the function
def find_odds(totlist, oddlist):
for item in range(len(totlist)) : # here
if len(totlist) == 0:
return
v = totlist.pop()
if v % 2 == 1:
oddlist.append(v)
I am trying to implement the merge sort algorithm using the following code but am getting a list index is out of range error.
def mergeSort (unSortedList):
if len(unSortedList) == 1 :
return unSortedList
else:
midpoint = len(unSortedList)//2
A = mergeSort (unSortedList[:midpoint] )
B = mergeSort (unSortedList[midpoint:] )
i = 0
j = 0
C = []
for k in range(len(unSortedList)):
if A[i] >= B[j]:
C.append(A[i])
if i == len(A):
C.append(B[j:])
else:
i += 1
elif A[i] < B[j] :
C.append(B[j])
if j == len(B):
C.append(A[i:])
else:
j += 1
return C
testlist = [2,1,4,2,5,6,8,9]
print (mergeSort(testlist))
Any help would be appreciated.
Here is my version of your mergeSort, with the merge function extracted:
def mergeSort (unSortedList):
if len(unSortedList) == 1 :
return unSortedList
else:
midpoint = len(unSortedList)//2
A = mergeSort (unSortedList[:midpoint] )
B = mergeSort (unSortedList[midpoint:] )
return merge(A, B)
def merge(a, b):
i = 0
j = 0
c = []
while True:
if a[i] < b[j]:
c.append(b[j])
j += 1
elif a[i] >= b[j]:
c.append(a[i])
i += 1
if i == len(a):
c.extend(b[j:])
break
if j == len(b):
c.extend(a[i:])
break
return c
Output:
>>> testlist = [2,1,4,2,5,6,8,9]
>>> mergeSort(testlist)
[9, 8, 6, 5, 4, 2, 2, 1]
Couple of things to note:
Appending a list to a list. When you do C.append(A[j:]) you end up with nested lists. That is because A[j:] always returns a list. You either need to use list addition - C += A[j:] - or call extend - C.extend(A[j:])
Missing breaks. When your i or j got to the end of their lists you correctly appended the rest of the other list but you did not terminate the loop. That is what caused the range error because in the next iteration (which should not happen) you tried to get an item at the index equal to the length of the list which is out of range.
This is my code:
def second_test(numbers):
for x in numbers:
if 1 in x:
numbers.remove(x)
elif 7 in x:
numbers.remove(x)
print numbers
second_test(numbers)
Numbers is a list that contains int values from 10 to 1000. I am trying to remove numbers within this range that contain either a 1 or a 7 in them. Any suggestions?
You'll have to check if any digit of the number is a 1 or 7. There are two ways to do this:
The first way: Keep dividing the number by 10 and check the remainder (this is done with the modulus operator), until the number becomes 0
def check_num(n):
while n:
if n%10 == 1 or n%10 == 7:
return True
n /= 10
return False
def second_test(numbers):
to_delete = []
for i,x in enumerate(numbers):
if check_num(x):
to_delete.append(i)
for d in to_delete[::-1]:
del numbers[d]
The second way: Turn the number into a string, and check each character of the string
def check_num(n):
for char in str(n):
if char=='1' or char=='7':
return True
return False
def second_test(numbers):
to_delete = []
for i,x in enumerate(numbers):
if check_num(x):
to_delete.append(i)
for d in to_delete[::-1]:
del numbers[d]
I need to remove the unique elements of the list, the first thought is:
def cut_uniq(data):
for x in data:
if data.count(x) == 1:
data.remove(x)
print(data)
cut_uniq([1, 2, 3, 4, 5,])
return
[2, 4]
please, tell me why?
Look at each iteration:
i x data
0 1 [1,2,3,4,5]
1 3 [2,3,4,5]
2 5 [2,4,5]
[2,4]
You can iterate over a different list than you are modifying. This returns a copy of the list
def cut_uniq(data):
return [x for x in data if data.count(x) > 1]
or more efficiently
from collection import Counter
def cut_uniq(data):
return [x for x, count in Counter(data) if count > 1]
If you really do want to modify the original list, and not return a copy
def cut_uniq(data):
i = 0
while i < len(data):
if data.count(data[i]) == 1:
del data[i]
else:
i += 1
or
from collections import Counter
def cut_uniq(data):
for x, count in Counter(data):
if count == 1:
data.remove(x)
95% of the time that you modify the same list as you're iterating over, you'll have problems.
When you use
for x in data:
it translates to
for i in [0,1,2,3,4]:
x = data[i]
So in the first loop, i = 0 data[i]=1. you remove 1 from data, the data is [2,3,4,5]
on the second loop , i = 1, because now data is [2,3,4,5], data[i] = 3. So 2 is left in the data list and never been visited.
Same as the number 4.
So when you finished your loop, the [2,4] leted in the list.