What is the concept on Start:Stop:Step [duplicate] - python

This question already has answers here:
Understanding slicing
(38 answers)
Closed 3 months ago.
I am new to python and I seem to be unable to understand the concept in Start:Stop:Step. For example
word = "Champ"
print (word[0:5:2])
why do I get cap as I result ? if someone could help me with this I would truly appreciated
I tried using different numbers to see what the outcome was but even there I was not able to understand why was I getting that outcome

Let's see this way:
word = "Champ"
print (word[0:5:2])
# you are taking index=0, then index=0+2, then index=0+2+2
# then index=0+2+2+2 (don't have this)
# so you got 0,2, and 4
# Hope, makes sense
print(word[0])
print(word[2])
print(word[4])

Maybe it's best to imagine it as a simple while-loop that creates an output. Take this example:
string = "Champ"
start = 0
stop = 5
step = 2
index = start
output = ""
while index < stop and index < len(string):
output += string[index]
index += step
print(output)
# >>> Cap
Here the current index starts at the start parameter, and then adds the current item to the output, then increments by the value step. If ever the current index is larger than the length of the original string, or larger than the stop value, the while-loop exits. Hope this helps!

Related

Capped at 32-bit maximum, why is my code not able to pull the solution above this maximum? [duplicate]

This question already has answers here:
Numpy is calculating wrong [duplicate]
(2 answers)
Closed 3 years ago.
I am attempting to solve problem 8 of projecteuler. I am having difficulty understanding exactly why my code is not outputting the correct solution. I am aware that the solution to this problem is above the 32 bit maximum, but I do not know how to allow python to work with numbers above that within my code.
For reference, the original question states : "Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?"
from numpy import prod
f = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
z = list(int(i) for i in str(f))
a1 =[]
start = 0
end = start + 13
while end <= len(z):
a1.append(prod(z[start:end]))
start+=1
end+=1
a = a1.index(max(a1))
print(a1[a]) #prints the product solution
print('---')
dimlen=end-start
newstart = a
newend=a+dimlen
print(z[newstart:newend]) #prints the integers that build the solution
I keep getting the number 2091059712, (the solution is 23514624000)
I think it might be numpy.prod. It might be preserving the input type and wrapping the value. Try using:
def prod(it):
p = 1
for m in it:
p *= m
return p

what does `Count : Count` in `CommandList[Count:Count + len(Command)] == Command` do in python? [duplicate]

This question already has answers here:
Understanding slicing
(38 answers)
Closed 4 years ago.
I don't know what 'Count : Count' does in my code. Below is the function that this is used in on line 4
I tried printing it but it gave me an error. CommandList is a string variable as well as Command.
def GetPositionOfCommand(CommandList, Command):
Position = Count = 0
while Count <= len(CommandList) - len(Command):
if CommandList[Count:Count + len(Command)] == Command:
return Position
elif CommandList[Count] == ",":
Position += 1
Count += 1
return Position
Position = GetPositionOfCommand(Items[IndexOfItem].Commands, "get")
Your question is off, since Count: Count does nothing in the code you show. Rather, what acts is Count:Count + len(Command). That would be better written as Count: (Count+len(Command)).
Both CommandList and Command are strings or lists or similar data types (I'll say strings hereafter), while Count is an integer. In particular, Count is an index into CommandList.
The expression CommandList[Count:Count + len(Command)] is a slice of CommandList. In other words, that expression is a sub-string of the string CommandList. That sub-string begins at the index position held in Count and stops just before the index position Count + len(Command). That sub-string has the same length that the string Command has.
Therefore the entire line
if CommandList[Count:Count + len(Command)] == Command:
checks if the sub-string pointed to by variable Count is equal to the string Command. If the sub-string and the string are equal, the next line executes, namely the return statement.
Is that clear? Read up more on Python's slices--the link I gave you is a good start. Slices are just one reason Python handles lists and strings so much better than most other languages. The code is written a little confusingly, so it looks like Count:Count is an expression in itself. The code should have used different spacing and perhaps parentheses to show that the inner expression is Count + len(Command) and the colon is used after that. Order of operations shows itself again!

For loop with raw_input, If-statement should increase input by 1 [duplicate]

This question already has answers here:
How to change index of a for loop?
(5 answers)
Closed 4 years ago.
everybody!
I am currently learning Python (no prior coding skills - at least not enough to mention them) and I am struggling with a for loop in a lottery machine we are supposed to do for homework.
I have spent the past two hours googling this, but I wasn't able to find anything that would hint me in the right direction.
I want the loop to create a list with random numbers. The amount of random numbers printed to the user should be defined by user input and it should not use duplicates. Every time a duplicate is created it should simply pick a different number. Any hints on where i screwed up here? (Pls note it's Python 2.x)
Thank you all! :)
Code:
from random import randint
lotterylist = []
print "Welcome to the lottery machine!"
mynumbers = int(raw_input("How many numbers should be drawn?\n"))
for i in range(0, mynumbers):
lottery_numbers = randint(0, 48)
if lottery_numbers not in lotterylist:
lotterylist.append(lottery_numbers)
else:
mynumbers += 1
continue
print lotterylist
print "End"
You could do it like this because honestly the current code doesn’t make much sense.
for _ in range(0, num):
snum = randint(0, 48)
while snum in numlist:
snum = randint(0, 48)
numlist.append(snum)
This will keep on creating a new number until a number not in the list is selected and then it exits the while loop and appends the number to your list of generated numbers. No need to keep on incrementing the range; going forward you should understand that if your logic requires something like that then it means it is flawed. Your current approach doesn’t make sense.

how can i count the number of times a certain string occurs in a variable? [duplicate]

This question already has answers here:
String count with overlapping occurrences [closed]
(25 answers)
Closed 4 years ago.
im just learning how to program on edx, and theres this question that i just can seem to understand not to even talk of solving. please i need solutions and idea on how to understand the question and implement it
QUESTION-
Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
Number of times bob occurs is: 2
Since you are just learning, start with basic method.
Simplest apporch will be start from the begining consider all the substrings of the length of the substring that is needed to be counted. If there is a match increase the count.
You can refer the following code to get an idea.
s = 'azcbobobegghakl'
sb = 'bob'
results = 0
sub_len = len(sb)
for i in range(len(s)):
if s[i:i+sub_len] == sb:
results += 1
print(results)

Python: Index Out Of Range [duplicate]

This question already has answers here:
Removing Item From List - during iteration - what's wrong with this idiom? [duplicate]
(9 answers)
Closed 6 years ago.
I'm new to python and this may be a simple one line or one character answer but I can't seem to wrap my head around it. I have a list I want to iterate through and check if the element in the index after the current index is the same and delete it if it is.
while i < len(list):
if list[i] == list[i+1]:
del list[i];
i+=1;
I know the problem is coming from "if list[i] == list[i+1]:" when I get to end of the list "list[i+1]" will be out of range of the index. The problem is that I don't know how to stop the code when it gets to that point where it goes out of range
Firstly, list is the built-in function of python, so you should never use it for the name of your variables.
And to your problems itself. The fix for your error is simple:
while i < (len(_list) - 1):
if _list[i] == _list[i+1]:
del _list[i]
i+=1;
The reason for the IndexError is that at the last iteration i is already the last index and you are trying to get the element at the i+1 position.

Categories