Is there a way to get increment counter from a Python 'for' loop with decrement range? - python-3.x

I read everyone uses enumerate, but I don't think I know how to use it in my code. I want to print the value of an alphabet in a string according to alphabet order and the next character will increment the value by 1 and I want to start it from the last character in the string.
I can solve the code, but how can I replace the counter i without using i = i+1 to make this code a bit shorter? Is there a way to implement something in the for loop?
This is my code:
def project(r):
i = 0
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+i)
i=i+1
project(str(input()).lower())
For example, if I insert a string such as "sad", the output will be [4,2,21] because d = 4, a = 1, s = 19.
Is there a way to implement the counter without initializing i?

According to your question what I can understand is you want to use enumerate to get your result.
You can simply do as below:
def project(r):
for (i, char) in enumerate(r, 0):
print(ord(r[-i-1])-96+i)
project(str(input()).lower())
And the enumerate() method adds a counter to an iterable and returns it in a form of an enumerate object.
Syntax: enumerate(iterable, start)
Here 0 is the default value of start which you can give according to your requirement. For example, if you want your counter to start from 100, then you can do like enumerate(iterable, 100).
In the above code, I have used enumerate() function and initialized the counter from 0 and as you want to display from the last, I used -ve index to get the last item in a list.
And as I initialized the counter 0 so how can I get the items from last? For that, I subtract the index by -1 like r[-i-1]. So for the first iteration the i value becomes 0, so r[-i-1] becomes r[-0-1] which is r[-1] and on the second iteration, i becomes 1, so r[-i-1] becomes r[-1-1]which isr[-2]` which result second last item. Similarly it goes on.
For more information about enumeration, please check the below link so you can get a clear idea.
Python enumerate()
13. Enumerate

Dcoder14, actually I want to make my code a bit shorter. Even there is a way other than enumerate, but still thank you very much... I used your code, but I edited it a little bit to make it one line shorter...
This is my code:
def project(r):
for (i, char) in enumerate(r, 0):
print(str(ord(r[-i-1])-96+i))
project(str(input()).lower())

If you want to make it shorter, you can use the decrement char value since we can get an increment by subtracting the length of the string (input) with char in the for loop.
For example, this is my code:
def project(r):
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+(len(r)-char))
project(str(input()).lower())

Related

Reverse a string using while(),pop() and insert

using
while
.pop()
insert()
pop() the first item in the list and add to the beginning of a new string that will be reversed
# [ ] Challenge: write the code for "reverse a string" reversing some_numbers
some_numbers =[1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77]
rev_string = []
while len(some_numbers):
rev = some_numbers.pop()
rev_string.insert(0,rev)
print(rev)
print(some_numbers)
print(rev_string)
My first question is that:
As i am printing rev in line 7, i am getting 1 as the answer but we know that an empty pop is used to denote the last element then why i am getting 1 instead of 77.
I am getting the right answer by putting 0 inside the pop in line 5. How ?
Your assumption pop() the first item in the list is wrong. When you call some_numbers.pop, you get the last element of the list popped, check the docs. This should answer both of your questions.
pop() without parameters returns and then deletes the last element but you are assuming just the opposite. you should use
del listname[0]
But note this simply deletes (does not return and delete like pop)
so use
listname[0]
to access your element beforeusing del
1.rev equals to 77 at the first while iteration. since you are looping until
len(some_numbers) rev equals to 1 in the end of the loop.
2.The pop function gets index as input, which means if u put 0 inside the pop, every iteration it pops the index 0 in the list. And leaves you with the last number of the list at the end of the loop.

Getting a "list index can't be a float" error when i use the same iterator from a loop in an if statment in Python 3.4

I try to iterate through a list and check each value if it is a negative number, using the following code :
for i in listy:
if (listy[i]<0):...
For some reason, python tries to evaluate listy[0.5]<0, which is the 1st item on the list. How can I fix this ?
i is the value not the index.
This line is not what you want (listy[i]<0).
You probably meant to do i<0
(listy[i]<0) is trying to use the value as the index. In you list the value is a float which can't be used as an index.
If you really want to use the index you could do:
for i in range(len(listy)):
if listy[i] < 0:
#do something
In C and many other languages, you often use the length of an array when iterating through it. You can do this in Python as well but you can also iterate through the elements without explicitly using the index (position). You seem to be mixing the two approaches and therefore you get an unexpected result.
This will iterate through the values only:
for i in listy:
# here, i is the value of the list entry
print(i)
This will use the length of the list and the index (position):
for i in range(len(listy)):
# here, i is the index (position) of the list entry, not the value
print(listy[i])
This will give you both index and value:
for i, val in enumerate(listy):
# here, i is the index (position) and val is the value
print(i, val)

Finding consecutive characters in an array

I have a boolean function that evaluates a 1d array of characters. It has two parameters: a 1d array of characters , and a char c. I want the function to return true if the given char c appears at least four consecutive times within the given array, otherwise it will return false.
I don't know how to start or complete this function at all. Please help! Thanks.
I hope I'm not doing you're homework for you ;). So here's the sudo-code for this problem to help you get started
The first thing you would want is the method header that returns a boolean, and has a parameter for an array of characters and a char
The next step would be to create a counter and run a loop to sift threw every character in the array. Every time you encounter that specific character in the array you would add one to the counter, if the next character isn't the one you want then you would reset the counter to 0. Then add a conditional in the loop to check if the counter reaches 4, if so you would return true. If it never reaches 4 then you would want to return false. Go ahead and try to code that up and see if you get it.
Simple problem. If this is your homework then you shouldn't be doing this. Your question needs to be changed. Firstly give it a try before asking and then once you are done trying you can post the errors or the snippets of codes that you are unsure of and then ask for help. Else you are not going to learn anything. Got a simple solution to your problems. I'm not going to give you the complete solution but instead a guide to help you with your question.
In my opinion string is always a better choice to use instead of char because of the functions that come with that package. Char is just plain old annoying (again in my opinion) unless your question or whatever you are doing this program for requires you to use char.
First,
Create your main program -> create your array and initialize it if you want or you can prompt the user for their input. whichever works.
use the "bool" data type to create your Boolean variable.
Prompt the user to input the char value to check for.
Now call the function and provide the parameters. I'm guessing the function is where you are stuck with so i'm going to provide you the snippets from the code that i wrote for this question.
bool check(char* <array_name>, char* <array_name>) //for the array list and the
//value to check for
{
int size;
size = strlen(<array_name>); //to get the size of the array (array list)
int counter=0; //to keep count of the occurrence of the char to check
for(int x=0; x<size; x++) //ar = array list and token = char to check
{
if(ar[x]==token[0]) //check for each iteration if token is in ar[x]
counter++; //if it is then counter increases by 1
else
counter = 0; //To reset the value to 0 if its not consecutive.
if(counter == 4) //to stop the loop when 4 consecutive values has been found.
break;
}
if(counter >= 4) //as per your requirement 4 or above
return true;
else
return false;
}
EDIT: This is to check the values just until 4 consecutive values of what you are searching for is found and to end the loop. If you want it in a different way then please feel free to comment on this answer. You can always add another counter or anything at all to check how many consecutive times the value is found. For example 1,1,1,1,2,3,4,1,1,1,1,2,3,4,1,1,1,1,2,3,4.
The counter for that will be 3 since it happens 3 times with each time repeating the same value for 4 times consecutively.
If this is your homework then you better study properly because it's a really simple problem and your shouldn't be asking for a solution but instead ask for guidance and try first.
Good luck! If you need further clarification or help just comment on this.

Cl0sed Functions in Druid

I'm trying to write a function that takes an 8-character binary string s and a positive number as an integer n, and prints a sequence of n binary numbers that increase according to my increment function.
How to I edit my function so that I can print these?
Assuming all of your other code is correct, there are five problems in your recursive code.
First, you're trying to use the value returned by the recursive call to count. But you have no return statements anywhere, so what could that value possibly be? So that inc*cnt is just going to try to multiply a string by None and raise a TypeError. If you look at your code, you have no need to return anything upward; count just takes some values, prints something, and calls itself again. So just ignore the None that it returns.
Next, you're trying to increment s[-1]. But s is a string, so that's just going to be the last character. You want to "increment" the whole string, right? So just pass s.
Next, you're trying to call yourself with s[:-1]. Again, s is a string; this is going to try to increment the first 7 digits of that string, then the first 6, and so on. Why would you want that? What you want to increment is the value you just incremented. That is, the same thing you just stored in inc. So just pass inc.
Next, you're doing the print after the recursive call. This means you're going to call the function that prints the second and later values, then print the first value. And so on. So they're going to show up in reverse order. If you want the first value first, print before the recursive call.
Finally, you clearly want the original value and the next 4 to get printed, not the next 5 without the original value. So you have to print out the pre-incremented value, not the post-incremented one.
So, the minimal change to your code is:
def count(s, n):
if n == 0:
return
else:
inc = increment(s)
print(s)
count(inc, n-1)

How can I write the following script in Python?

So the program that I wanna write is about adding two strings S1 and S2 who are made of int.
example: S1='129782004977', S2='754022234930', SUM='883804239907'
So far I've done this but still it has a problem because it does not rive me the whole SUM.
def addS1S2(S1,S2):
N=abs(len(S2)-len(S1))
if len(S1)<len(S2):
S1=N*'0'+S1
if len(S2)<len(S1):
S2=N*'0'+S2
#the first part was to make the two strings with the same len.
S=''
r=0
for i in range(len(S1)-1,-1,-1):
s=int(S1[i])+int(S2[i])+r
if s>9:
r=1
S=str(10-s)+S
if s<9:
r=0
S=str(s)+S
print(S)
if r==1:
S=str(r)+S
return S
This appears to be homework, so I will not give full code but just a few pointers.
There are three problems with your algorithm. If you fix those, then it should work.
10-s will give you negative numbers, thus all those - signs in the sum. Change it to s-10
You are missing all the 9s. Change if s<9: to if s<=9:, or even better, just else:
You should not add r to the string in every iteration, but just at the very end, after the loop.
Also, instead of using those convoluted if statements to check r and substract 10 from s you can just use division and modulo instead: r = s/10 and s = s%10, or just r, s = divmod(s, 10).
If this is not homework: Just use int(S1) + int(S2).

Resources