check duplicity of a upcoming element in list - python - python

I'm trying to check if a string is the same as any string in the list.
This is what I coded in python:
word_split = action_one(element)
while word_split in new_element:
word_split = action_one(element)
new_element.extend(word_split)
This is action one function do:
def action_one(element):
random_position = randint(0, len(element) - 1)
if random_position == len(element) - 1:
word_split = [characters[:random_position] + characters[random_position].upper() for characters in element.split()]
else :
word_split = [characters[:random_position] + characters[random_position].upper() + characters[random_position + 1 : len(element)] for characters in element.split()]
return word_split
But the output list still have duplicate elements in it.
Can anyone point out where I did wrong?
Thanks!!

There definitely seems to be a typo on this line:
while word split in new_element:
It shouldn't be more complicated than this:
for my_string in my_list
if my_string not in my_new_list:
my_new_list.append(my_string)

Related

Appending a char to an empty list

I am very new to programming, so sorry for a basic question. I am trying to write a function that will take a string in which words are divided by ',' and return a list of these words (the Split method). My code is:
def str_to_list(my_shop_str):
my_shop_list = ['']
word_in_list = 0
for letter in my_shop_str:
if letter != ',':
my_shop_list[word_in_list] += letter
else:
word_in_list += 1
my_shop_list + ['']
return my_shop_list
print(str_to_list("Milk,Cottage,Tomatoes")) should look like [Milk, Cottage, Tomatoes]
but I am keep getting IndexError: list index out of range.
I read some answers here and couldn't find something to work.
Can anyone explain what is wrong.
list has the method append so a solution will be something like this:
def str_to_list(my_shop_str):
my_shop_list = ['']
word_in_list = 0
for letter in my_shop_str:
if letter != ',':
my_shop_list[word_in_list] += letter
else:
word_in_list += 1
my_shop_list.append('')
return my_shop_list
PS: Do not forgot about empty spaces between words in string like "aaa, bbb, ccc" will be ['aaa', ' bbb', ' ccc'] with spaces.
def sp(s):
l =[]
while True:
comma = s.find(',')
if comma == -1:
l.append(s)
break
l.append(s[:comma])
s = s[comma+1:]
print(l)
this is a simplified version hope it helps.
Simplest Way:
We can use an inbuilt split function.
def Convert(string):
# split the string whenever "," occurs
# store the splitted parts in a list
li = list(string.split(","))
return li
# Driver code
str1 = "Hello,World"
print(Convert(str1))
Output:
["Hello", "World"]

How to capitalise last letter of string in python?

I tried this:
def capitalize_first_last_letters(str1):
str1 = result = str1.title()
result = ""
for word in str1.split():
result += word[:-1] + word[-1].upper() + " "
return result[:-1]
print(capitalize_first_last_letters("resource"))
Output:
ResourcE
I just want to capitalize the last letter.
Simply slice, turn to str.upper() the last letter and add together:
s = 'Resource'
s[:-1] + s[-1].upper()
# 'ResourcE'
Use title after reversing the string and reverse it back
s[::-1].title()[::-1]
To capitalise just the last character of a string:
string = "resource"
result = string[:-1] + string[-1].upper()
Result:
'resourcE'
string[:-1] is the substring from the start of the string, stopping 1 position before the end.
If you come here looking for a solution that will work with Pandas try this one. This solution will work even if you have NULLs.
def uppercase_last_letter(series):
"""Func to uppercase the last letter in a string"""
return series.map(lambda x: (x[:-1] + x[-1].upper()) if type(x) == str else x)
df[col1] = uppercase_last_letter(df[col1])

What's the role of string = "" in a program Python

i know the title may not be the best, as i'm not exactly how to explain my problem in short words. However i recently was looking at some codes online and i didn't get the reason why some code was used i tried looking on the internet but as i dont know what that part of the code is called ive no idea what to search up so you guys are my last hope.
In this function
def NumIntoChar(LineLis):
for n in LineLis:
string = "" # Here is what im not sure. why is this used here ?
for i in range(n):
string += '-'
print(string)
Im unsure why string = "" is used between the 2 for looks
another example is:
message = """SAHH""" # Add Code
message = message.upper()
keyShift = 1
encryptedMsg = ""
result = {}
while keyShift <= 26:
encryptedMsg = ""
for character in message:
if character.isalpha() is True:
x = ord(character) - 65
x += keyShift
x = x % 26
encryptedMsg += chr(x + 65)
else:
encryptedMsg += character
result[keyShift] = encryptedMsg
keyShift += 1
for r in result.keys():
print(r,result[r])
Here we see ' encryptedMsg = "" ' being used just like in the previous code.
Just below that line of code, you have this for loop:
for i in range(n):
string += '-'
The x += y operator is syntactic sugar for x = x + y. In order to use this operator, x must have a defined value first.
For the first iteration of the loop, string will essentially be assigned like this:
string = string + '-'
In order to avoid NameError being thrown, string first needs to be declared and assigned some value, which is what string = "" does. The expression in the first iteration of the loop then essentially becomes:
string = '' + '-'
Here you initialize a variable with empty string using var = ''.
It is commonly followed in scenarios where you have to iteratively concatenate content to form a bigger string. Your code starts with initializing the empty string and within the loop, content of the string is concatenated. For example:
my_str = ""
while repeat:
my_str += some_str
# Do some stuff
Other scenario in which you might need it is: when you have to set default value of string as empty, but based on some condition reset the content of string. For example:
my_name = ''
if user.is_logged_in():
my_name = user.name
Also read: Initialize a string variable in Python: “” or None?

Is there a better way to accomplish this python excercise? (Beginner)

I'm just starting to learn Python and I'm going through an exercise at the end of a chapter. So far, all I've learned about in the book is the very basics, flow control, functions, and lists.
The exercise is:
Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns
a string with all the items separated by a comma and a space, with "and"
inserted before the last item. For example, passing the previous spam list to
the function would return 'apples, bananas, tofu, and cats'. But your function
should be able to work with any list value passed to it.
To solve this, I use the following code (python 3.x.x). I'm wondering if there is a better way to do this. It took a little trial and error, but I fumbled through it until I got this:
myList = ['apples', 'bananas', 'tofu', 'cats']
myList2 = ['apples', 'bananas', 'tofu', 'cats', 'added1', 'added2']
def listFunc(List):
x = 0
for i in List:
x += 1
if x < len(List):
print(i, end=' ')
elif x == len(List):
print('and ' + i)
listFunc(myList2)
Another way to accomplish this would be to use slices and joins:
def listFunc(lst):
if len(lst) == 0: return ''
if len(lst) == 1: return lst[0]
return ", and ".join([", ".join(lst[:-1]), lst[-1]])
Here's a more readable version of the above function using the same core concepts.
def listFunc(lst):
if len(lst) == 0: return '' #no elements? empty string
if len(lst) == 1: return lst[0] #one element? no joining/separating to do, just give it back
firstPart = lst[:-1] #firstPart is now everything except the last element
retFirst = ", ".join(firstPart) #retFirst is now the first elements joined by a comma and a space.
retSecond = ", and " + lst[-1] #retSecond is now ", and [last element]"
return retFirst + retSecond;
The only potentially confusing bits here I think are the slice syntax, negative indices, and string.join
The code lst[:-1] means get everything in lst excepting the last element This is a list slice
The code lst[-1] means get the last element in lst This is negative indexing
And finally, the code ", ".join(firstPart) means get a string containing each element in firstPart separated by a comma and a space
Here is a simple version of the function that doesn't use anything very "fancy" and should be understandable by a beginner. Slicing is probably the most advanced stuff here but should be ok if you went through lists. It also handles two special cases of an empty list and one-item list.
def listFunc(List):
if len(List) == 0: return ''
if len(List) == 1: return List[0]
value = List[0]
for item in List[1:-1]:
value = value + ', ' + item
return value + ', and ' + List[-1]
This is not the way you would normally do it in Python but should be good for learning purposes.
Let's have fun with Python 3 and keep it simple:
def listFunc(myList):
*rest, last = myList
return ", ".join(rest) + (", and " if rest else "") + last
You can make it slightly shorter using enumerate:
def printList():
# x will be the string in the list, y will be an integer
aString = ""
for (y,x) in enumerate(myList):
if y < len(myList) - 1:
aString = aString + x + ", "
else:
aString = aString + "and " + x
.
.
.

Why is the following Python code wrong?

I have the following problem for my assignment:
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = azcbobobegghakl, then your program should print:
Longest substring in alphabetical order is: beggh
The code I wrote for the problem is this:
s = 'azcbobobegghakl'
current_index = 1
first_index = 0
result_string = ''
current_string = s[first_index]
while current_index < len(s):
if ord(s[first_index]) <= ord(s[current_index]):
current_string += s[current_index]
elif ord(s[current_index]) < ord(s[first_index]):
current_string = ''
if len(current_string) > len(result_string):
result_string = current_string[:]
current_index += 1
first_index += 1
print('Longest substring in alphabetical order is: ' + result_string)
The code doesn't give out the correct result, for some reason, it gives out eggh instead of beggh.
And since this is an assignment, I do not ask that you give me the corrected code, but just give me an hint on where I am wrong since I wanna solve my problem BY MYSELF and don't wanna cheat.
Thanks.
Error is here:
current_string = ''
you should not clear it when you find s[current_index]) < s[first_index].
Other hints:
no need to use ord.
what happens if s='a'?
no need to copy result_string = current_string[:], since strings are immutables
Hints OVER ;P

Categories

Resources