How to multiply a value each month? [closed] - python

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}

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.

How to skip a fixed number of lines in a python code? [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
In a python code, how to skip a few lines of code?
For example, this is the code:
if value == 10:
<skip_the_next_seven_lines_of_code>
if value == 15:
<skip_the_next_eight_lines_of_code>
#code continues...
Note that this can be done using a lot of workarounds, like putting the code in the else statement, but I want to avoid that as it would require a lot of elses as I have a lot of ifs.
I am asking whether there is a function which is like:
skiplines(7)
Then the next 7 lines are skipped.
Also, this question has been downvoted many times, but I do not understand why. If there is no such way to accomplish this it can be answered in that way...
I don't think you can handle by the number of lines.
A closest I could think of is to define a function of the corresponding code block as below.
value = 10 # or set other value
task = lambda: print("this is original task")
if value == 10:
task = lambda: None
task() # if value==10, this does nothing.
This is the original answer to the original question (see question edits):
if value != 10:
<some_seven_lines>
<the_rest_of_the_code>
The updated question shows a slightly more complicated pattern. Let's say something like this (I have to create an example since OP does not provide specific code/problem that he/she is trying to solve):
a = 0 # some variable that lines of code will modify
if value == 10:
goto L1 # same as "skip next 7 lines"
if value == 15: # line 1 to "skip"
goto L2 # line 2 to "skip"; same as "skip next 8 lines"
a += 1 # line 3 (or 1 from second "if") to "skip"
a += 10 # line 4 (or 2 from second "if") to "skip"
a += 100 # line 5 (or 3 from second "if") to "skip"
a += 1000 # line 6 (or 4 from second "if") to "skip"
a += 10000 # line 7 (or 5 from second "if") to "skip"
L1: a += 100000 # line - (or 6 from second "if") to "skip"
a += 1000000 # line - (or 7 from second "if") to "skip"
a += 10000000 # line - (or 8 from second "if") to "skip"
L2: a += 100000000 # line 11 (or 13 from second "if")
This could be done in the following way:
a = 0
def f1(a):
a += 1
a += 10
a += 100
a += 1000
a += 10000
return a
def f2(a):
a += 100000
a += 1000000
a += 10000000
return a
if value == 10:
a = f2(a)
elif value == 15:
pass
else: # or elif value != 15 and skip the branch above
a = f1(a)
a = f2(a)
a += 100000000
Of course, specific answer would depend on the question with a specific example, which, as of now, is missing.
Also, see https://stackoverflow.com/a/41768438/8033585

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]

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.

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 can I print the string "aaabbbccaa" as a3b3c2a2 [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
I am given a user entered string 'aaabbbccaa'.
I want to find the duplicates and print the string back as 'a3b3c2a2'
Maybe with this way:
from itertools import groupby
s = "aaabbbccaa"
# group by characters
groups = groupby(s)
# process result
result = "".join([label + str(len(list(group))) for label, group in groups])
print(result)
Output:
a3b3c2a2
def process_string(source):
new = ''
while source:
counter = 0
first_char = source[0]
while source and source[0] == first_char:
counter += 1
source = source[1:]
new += f'{first_char}{counter}'
return new
print(process_string('aaabbbccaa'))
'a3b3c2a2'
this kind of solution could mabye solve it, it does what you specify, however if you are able to put it into your context, no idea :)
hope it helps!
c = 0
foo = "aaabbbccaa"
bar = ""
prev = None
for counter, index in enumerate(foo):
print(c)
if prev == None:
print("first")
elif prev == index:
print("second")
elif prev != index:
c = 0
c += 1
prev = index
try:
if index in foo[counter+1]:
print("third")
else:
print("fourth")
bar += index + str(c)
except:
print("fifth")
bar += index + str(c)
print("foo is {}".format(foo)) # will output aaabbbccaa
print("bar is {}".format(bar)) # will output a3b3c2a2

Categories

Resources