In Python, how can I make it so the first 2 elements of a list are added together, then the first 4, then the first 6, and so on? [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am making a game where two players take turns adding a number 1 to 10 to the running total. The player who adds to get 100 wins. I stored the inputs of the players in a list, and at the end of the game, I want to display the total after every turn. The list is in the format:
allTurns = [player1move1, player2move1, player1move2, player2move2, ...]
How can I add only the first 2 elements and display them, then add only the first 4 elements and display them, and then the first 6, and so on?

for i in range(0, len(list)):
if i % 2 == 0:
print(sum(list[:i+1]))
Or
sums = []
for i in range(0, len(list)):
if i % 2 == 0:
sums.append(sums[-1] + list[i-1] + list[i])

Try this:
allTurns = [1,2,3,6,12,23]
out = []
for n in range(len(allTurns)):
if n % 2 is 1:
out.append(allTurns[n] + allTurns[n-1])
if len(allTurns) % 2 is 1:
out.append(allTurns[-1])
print(out)
I've coded it so that it could work for any situation, and not just yours.

Try this:
allTurns = [1,2,3,6,12,23,4]
out = []
for n in allTurns:
if allTurns.index(n) % 2 is 0:
i = 0
for a in range(allTurns.index(n)+2):
try:
i=i+allTurns[a]
except IndexError:
pass
out.append(i)
print(out)
This is probably as simple as it can get.

Related

can you explain how this Loop works and how do we get that output? [closed]

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 1 year ago.
Improve this question
if __name__ == '__main__':
n = int(input())
for i in range (0,n):
result = i**2
print(result)
#input : 5
#output : 0 1 4 9 16
range 0,n = 0,1,2,3,4 and
we gave i**2 but how we got 0,1,4,9,16 as output?
range(start, stop, step)
** = square of Number
start Optional. An integer number specifying at which position to
start. Default is 0
stop Required. An integer number specifying at which position to
stop (not included).
step Optional. An integer number specifying the incrementation. Default is 1
you are passing required parameter as 5 which will not be included in the loop. so as per your calculation it will start from 0
result = 0**2 = 0
result = 1**2 = 1
result = 2**2 = 4
result = 3**2 = 9
result = 4**2 = 16
'i' will not reach 5 because of non-inclusive nature of range() operator.

Extract n first consecutive numbers from a string in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Let's consider this string :
st = 'text1text6253text'
How could I please extract the two first consecutive figures ?
Expected output :
62
You can either use regex with \d{2}and return that, or go over the string:
st = 'text1text6253text'
for i in range(len(st)-1):
if st[i].isdigit() and st[i+1].isdigit():
print(st[i]+st[i+1])
break
import re
def find_con(n, s):
result = re.search('\d{%s}'%n, s)
return result.group(0) if result else result
st = 'text1text6253text'
print(find_con(2, st))
st = 'text1text6253text'
lst = list(st)
lst2 = []
for i,v in enumerate(lst):
if lst[i].isdigit() and lst[i+1].isdigit():
lst2.append(lst[i])
lst2.append(lst[i+1])
ans = int(lst2[0] + lst2[1])
print(ans)
Thanks to your answers, I built a general function that I propose you below :
def extract_n_consecutive_numbers(st,nb):
for i in range(len(st)-nb+1):
is_numeric = True
for j in range(nb):
is_numeric = is_numeric & st[i+j].isdigit()
if is_numeric :
output = ""
for j in range(nb):
output += st[i+j]
return output
return ""
Example :
extract_n_consecutive_numbers('text1text6253text',2)
Out[1]: 62

How can I do this effectively? [closed]

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 2 years ago.
Improve this question
This problem:
Input: 123456
Result:
1+2+3+4+5+6 = 21
2+1 = 3
Return: 3
This is my code:
num = input()
print(sum(list(map(int, list(num)))))
I don't know how to do until it is 1 digit.
Try this (example in IPython):
In [1]: s = '123456'
Out[1]: '123456'
In [2]: digits = [int(j) for j in s]
Out[2]: [1, 2, 3, 4, 5, 6]
In [3]: s = str(sum(digits))
Out[3]: '21'
Repeat steps 2 and three until len(s) == 1.
One way:
while len(str(ans))>1:
ans = sum(map(int, str(ans)))
Full code:
num = 45637
ans = num
while len(str(ans))>1:
ans = sum(map(int, str(ans)))
print(ans)
Output for input 45637:
7
You can try this:
s = input()
while(len(s)>1):
s = str(sum(list(map(int,s))))
One way to do it using sum(), list comprehension and recursion,
def simulated_sum(input):
"""This is a recursive function
to find the simulated sum of an integer"""
if len(str(input)) == 1:
return input
else:
input_digits = [int(x) for x in str(input)]
latest_sum = sum(input_digits)
return simulated_sum(latest_sum)
input = int(input('Enter a number'))
print(simulated_sum(input))
DEMO: https://rextester.com/WCBXIL71483
Is this what you want? (instructions unclear):
def myfunction(number):
total = 0
answertotal = 0
for i in str(number):
total += int(i)
for i in str(total):
answertotal += int(i)
return answertotal
myfunction(123456)
This function returns 3

Google Codejam 2020 Qualification Round: Problem 3 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
This is for the Third Problem on Google's Codejam Qualification Round 2020
The Judging System says this solution gives a wrong answer, but I could not figure out why. Any insights would be much appreciated.
num_test_cases = int(input())
def notOverlap(activity, arr):
# returns true if we have no overlapping activity in arr
for act in arr:
if not (act[0] >= activity[1] or act[1] <= activity[0]):
return False
return True
def decide(act, num_act):
C, J = [], []
result = [None]*num_act
for i in range(num_act):
if notOverlap(act[i], C):
C.append(act[i])
result[i] = "C"
elif notOverlap(act[i], J):
J.append(act[i])
result[i] = "J"
else:
return "IMPOSSIBLE"
return "".join(result)
for i in range(num_test_cases):
num_act = int(input())
act = []
for _ in range(num_act):
act.append(list(map(int, input().split())))
print("Case #" + str(i+1) + ": " + decide(act, num_act))
You implemented a brute force way to solve it. Your code runs slow, Time complexity O(N^2), but you can do it in O(N*log(N))
Instead of check with notOverlap(activity, arr), sort the array and check with the last ending time activity of C or J. ( Greedy Way to solve it )
You have to store the index of activity before sorting the array.
Here is my solution, but before reading the solution try to implement it yourself
for testcasei in range(1, 1 + int(input())):
n = int(input())
acts = []
for index in range(n):
start, end = map(int, input().split())
acts.append((start, end, index)) # store also the index
acts.sort(reverse=True) # sort by starting time reversed
# so the first activity go to the last
d = ['']*n # construct the array for the answer
cnow = jnow = 0 # next time C or J are available
impossible = False # not impossible for now
while acts: # while there is an activity
start_time, end_time, index = acts.pop()
if cnow <= start_time: # C is available to do the activity
cnow = end_time
d[index] = 'C'
elif jnow <= start_time:
jnow = end_time
d[index] = 'J'
else: # both are'nt available
impossible = True
break
if impossible:
d = 'IMPOSSIBLE'
else:
d = ''.join(d) # convert the array to string
print("Case #%d: %s" % (testcasei, d))
I hope you find this informative and helped you to understand, and keep the hard work.

How to multiply a value each month? [closed]

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 years ago.
Improve this question
I just started taking classes of python and I am trying to make a code in where the value of the first month = 1 and multiply its value by 2 next month, and then by 3 next month, and 2 next month and so on. Until it reaches 6 months. I am using this code but it only gives me Month 1 = 1 which is the initial value.
P = 1
count = 12
print ("month 1: ",P)
for month in range(count-1):
if month %2 == 0:
P = P*2
else:
P = P*3
print:("month", month+2 ,":",P)
Change
print:("month", month+2 ,":",P)
to
print("month", month+2 ,":",P)
I'm not sure why python didn't complain about the colon. You can actually put anything there
weird: ("month", month+2 ,":",P)
And it won't complain. Awesome mistake, thanks!
Remember that range(count-1) will return numbers between 0 and 11 (the last number is non-inclusive)
Your logic could be like this:
(a) A counter that starts at 1 (cnt)
(b) A loop that watches for the counter to reach 6, then exits
(c) A running total (month_val or some such)
cnt = 1
month_val = 1
while cnt < 7:
month_val = month_val * cnt
print(month_val)
cnt += 1
The above assumes that you retain the new value of month_num -- but re-reading your question, you might just want to print the values 1 to 6, in which case the month_num value should just remain 1 all the time:
cnt = 1
month_val = 1
while cnt < 7:
print(month_val * cnt)
cnt += 1
You can define a dictionary for your problem like
month_values={}
for i in range(1,7):
if i == 1:
month_values['Month'+str(i)]=1
elif i%2 == 0:
month_values['Month'+str(i)]=i*2
elif i%2 == 1:
month_values['Month'+str(i)]=i*3
print(month_values)
prints
{'Month1': 1, 'Month2': 4, 'Month3': 9, 'Month4': 8, 'Month5': 15, 'Month6': 12}

Categories

Resources