Reverse a string using while(),pop() and insert - python-3.x

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.

Related

Is there a way to get increment counter from a Python 'for' loop with decrement range?

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())

Finding position of first letter in subtring in list of strings (Python 3)

I have a list of strings, and I'm trying to find the position of the first letter of the substring I am searching for in the list of strings. I'm using the find() method to do this, however when I try to print the position of the first letter Python returns the correct position but then throws a -1 after it, like it couldn't find the substring, but only after it could find it. I want to know how to return the position of the first letter of he substring without returning a -1 after the correct value.
Here is my code:
mylist = ["blasdactiverehu", "sdfsfgiuyremdn"]
word = "active"
if any(word in x for x in mylist) == True:
for x in mylist:
position = x.find(word)
print(position)
The output is:
5
-1
I expected the output to just be:
5
I think it may be related to the fact the loop is searching for the substring for every string in the list and after it's found the position it still searches for more but of course returns an error as there is only one occurrence of the substring "active", however I'm not sure how to stop searching after successfully finding one substring. Any help is appreciated, thank you.
Indeed your code will not work as you want it to, since given that any of the words contain the substring, it will do the check for each and every one of them.
A good way to avoid that is using a generator. More specifically, next()
default_val = '-1'
position = next((x.find(word) for x in mylist if word in x), default_val)
print(position)
It will simply give you the position of the substring "word" for the first string "x" that will qualify for the condition if word in x, in the list 'mylist'.
By the way, no need to check for == True when using any(), it already returns True/False, so you can simply do if any(): ...

How to add one to he last value in a list Python

Im fairly new to python and want to know how to add one to the last value in a list such as [1,5,9] or [44,45,20] I know it needs a for loop somewhere but how?
you can do this my_list[-1] += 1 .
the negative index let you start from the ending of a list (or any other iterable object), so -1 index is the last element in your list.
If by "adding" you mean arithmetic addition (i.e. +), do:
mylist[-1] += 1
If by "adding" you mean appending a new item to the list, do:
mylist.append(1)

Change list elements to a string with spaces in Prolog

In Prolog, if I am taking a list such as [hello,this,is,a,sentence] as a parameter for a predicate, how do I get a return value Y such that it will return that list as a string with spaces? e.g. [hello,this,is,a,sentence] will return hello this is a sentence.
makesentence([H|T],Y):- % some code here
I was able to run through the list recursively and have Y return the same list input with this:
makesentence([],[]). % base case returns an empty list
makesentence([X],[X]). % one list element returns that element in a list
makesentence([H|T],Y):- % a list of more than one element
makesentence(T,Result), % recursively call function on the tail
append([H],Result,Y). % append the head to the rest of the list
But when I try to make the output without a list and with spaces I faulter. I have tried this:
makesentence([],'').
makesentence([X],X).
makesentence([H|T],Y):-
makesentence(T,Result),
append(H,Result,Y).
I think it has to do with the fact the append predicate in Prolog only deals with appending a list, but I am unsure. How would I procede? Thanks in advance.
SWI-Prolog has a specialized built-in for that: atomic_list_concat/3
?- atomic_list_concat([hello,this,is,a,sentence],' ',A).
A = 'hello this is a sentence'.
figured it out with the help of Daniel. To put a list into a string with spaces use atomics_to_string/3. In my case:
makesentence([X],X).
makesentence([H|T],Y):-
makesentence(T,Result),
atomics_to_string([H,Result],' ',Y).
In the line atoms_to_string([H,Result],' ',Y)., the first parameter is the list, the second is what I want to add in between each entry, in this case a space ' ' and the third parameter is the assignment of the output, which in my case is Y. Thanks to Daniel for pointing me in the right direction.

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)

Resources