I am able to perform the capitalization function using the below for loop and enumerate function.
wordlist = list(word)
for i,v in enumerate(wordlist):
if i%2 != 0:
wordlist[i] = v.upper()
else:
wordlist[i] = v.lower()
word2 = "".join(wordlist)
print(word2)
However when I try to put it into the function in python, I am not able to reproduce the same result as above:
def myfunc(*word):
wordlist = list(word)
for i,v in enumerate(wordlist):
if i%2 != 0:
wordlist[i] = v.upper()
else:
wordlist[i] = v.lower()
word = "".join(wordlist)
return (word)
Can anyone help me with my question?
No need to unpack (*) that makes word equal to (word,) i.e. single element tuple:
def myfunc(word):
wordlist = list(word)
for i,v in enumerate(wordlist):
if i%2 != 0:
wordlist[i] = v.upper()
else:
wordlist[i] = v.lower()
word = "".join(wordlist)
return (word)
Or easier:
def myfunc(word):
word=list(word.lower())
for i,v in enumerate(word):
if i%2 != 0:
word[i] = v.upper()
return ''.join(word)
Better:
def myfunc(word):
word=list(word.lower())
word[1::2]=map(str.upper,word[1::2])
return ''.join(word)
Easier and simpler approach
def func(word):
result = ""
for i in range(len(word)):
if i % 2 == 0:
result += word[i].upper()
else:
result += word[i]
return result
word = "prasanna"
def myfunc(word):
word=list(word.lower())
for i,v in enumerate(word):
if i%2 != 0:
word[i] = v.upper()
print ''.join(word)
myfunc(word)
Related
I'm attempting to implement Python's split() function using recursion with no additional parameters and no loops.
For a given input string, this is the desired output
mySplit('hello,there,world', ',')
=> ['hello', 'there', 'world']
Here is my current attempt, but it really only removes the delimiter and places the string in a list, but I cannot figure out how to append items to the list!
def mySplit(string, delim):
if len(string) == 1:
return [string]
if string[0] == delim:
return [mySplit(string[1:], delim)[0]]
return [string[0] + mySplit(string[1:], delim)[0]]
This code results in ['hellothereworld']
I'd write something like:
def my_split(s, delim):
for i, c in enumerate(s):
if c == delim:
return [s[:i]] + my_split(s[i + 1 :], delim)
return [s]
EDIT: Oops, skipped over a crucial part of your question. I think this works.
def my_split(s, delim, i=0):
if i == len(s):
return [s]
elif s[i] == delim:
return [s[:i]] + my_split(s[i + 1 :], delim)
return my_split(s, delim, i + 1)
EDIT 2: It's a tricky one for sure. Really interesting problem. Hopefully I don't hit any more constraints with this one:
def my_split(s, delim):
if not s:
return [""]
elif s[0] == delim:
a = my_split(s[1:], delim)
return "", *a
b, *rest = my_split(s[1:], delim)
return [s[0] + b] + rest
assert my_split("hello,there,world", ",") == ["hello", "there", "world"]
assert my_split("hello world!", ",") == ["hello world!"]
assert my_split("hello world!", " ") == ["hello", "world!"]
def mySplit(string, delim):
if string.count(delim) == 0:
return [string]
idx = string.index(delim)
return [string[:idx]] + mySplit(string[idx + 1:], delim)
print(mySplit('hello,there,world', ','))
def spin_words(sentence):
adjusted_string = sentence.split()
for i in adjusted_string:
if len(i) > 5:
print(i[::-1], end = ' ')
else:
print(i, end = ' ')
The problem is asking to take a string and return the same string but, with all the five letter words or more in reversed
def spin_words(sentence):
splitted_string = sentence.split()
reversed_fives = [s[::-1] if len(s) >= 5 else s for s in splitted_string]
return " ".join(reversed_fives)
What I want to do
I am trying to make a program that reverses each words, but not reverses words in tags.
Example input and output:
Input:
Thank you stack overflow
Output:
knahT uoy kcats wolfrevo
If the word is in tags, it should be not reversed. Like this:
Input:
<tag>something
Ouput:
<tag>gnihtemos
My code
I tried to solve this using stack algorithm.
s = input()
def stackprint(st):
while st != []:
print(st.pop(), end="")
stack = []
tag = False
for ch in s:
if ch == '<':
stackprint(stack)
tag = True
print(ch, end="")
elif ch == '>':
tag = False
print(ch, end="")
elif tag:
print(ch, end="")
else:
if ch == ' ':
stackprint(stack)
print(ch, end="")
else:
stack.append(ch)
print("".join(stack))
The problem
But, my code is not working if there is only one word or there is no tag. When there is no tag, the last word is not reversed, and when there is only one word, it doesn't get reversed.
The output now:
First
When Input:
<tag>something
Ouput:
<tag>something
^ I need something to be reversed.
Second
Input:
Thank you stack overflow
Ouput:
knahT uoy kcats overflow
^ I need overflow to be reversed.
Important
I need whatever inside < > should be not reversed. If the word is in tags, it should be not reversed
like input:
<tag>word<tag>
output:
<tag>drow<tag>
There will be no space between a tag and a word.
Thank you <tag>stack overflow
knahT uoy <tag>kcats wolfrevo
As I've mentioned in the comment section, instead of printing the stack with the join method, calling the stackprint method to ensure that the stack is emptied will give you the desired result.
s = input()
def stackprint(st):
while st != []:
print(st.pop(), end="")
stack = []
tag = False
for ch in s:
if ch == '<':
stackprint(stack)
tag = True
print(ch, end="")
elif ch == '>':
tag = False
print(ch, end="")
elif tag:
print(ch, end="")
else:
if ch == ' ':
stackprint(stack)
print(ch, end="")
else:
stack.append(ch)
stackprint(stack)
This seems to work with the examples you have provided:
def revSetence(sentence):
sentence = sentence + " ";
flag = False
final_sentence = ""
word = ""
for letter in sentence:
if letter == "<":
flag = True
if letter == ">":
flag = False
if letter.isalpha():
if flag:
final_sentence = final_sentence + letter
else:
word = word + letter
else:
if len(word) > 0:
final_sentence = final_sentence + word[::-1]
final_sentence = final_sentence + letter
word =""
return final_sentence
I have a board with one word in it for example, hippopotamus. I want to add a word to rattlesnake vertically (if the word has one of the same letters as the one on the board). For example, horse could be added to hippopotamus like this:
I have a checkVertical function which returns True if the word can be added vertically and False if it can't
def printboard(board):
print(' 01234567890123456789''\n'' ____________________')
for i in range(20):
print('|', end = '')
for j in range(20):
print(board[i][j], end = '')
print('|', i)
print(' ____________________''\n'' 01234567890123456789')
def addFirstWord(board, word): # Adds first word to the middle of the board
indexRow = len(board)//2
indexCol = (len(board) - len(word))//2
if len(word) < len(board):
for i in range(len(word)):
board[indexRow][indexCol+i] = word[i]
print(True)
elif len(word) > len(board):
print(False)
def checkvertical(board, word, row, col):
#(a) the word is not too long for the board at that spot
if len(word) > 20 - row:
return False
#(b) at least one letter of word must match
#(c) other letters of word must land on blanks
matchesoneletter = False
for k in range(len(word)):
wordletter = word[k]
boardletter = board[row + k][col]
#are these two letters the same?
if wordletter == boardletter:
matchesoneletter = True
#is the boardletter a blank, if so continue
if boardletter == blank:
continue
elif boardletter != wordletter:
return False
return matchesoneletter
def find(board, letter) : #Finds the first occurence of a letter on the board
for i in range(len(board)) :
for j in range(len(board)) :
if board[i][j] == letter :
return (i, j)
return None
def addvertical(board, word) :
# go across and down the whole board looking for a spot to add word
for i in range(len(board)) :
for j in range(len(board)) :
# check if word can go at (i,j) and if it can, then place it there
if board[i][j] ==
return False
word = 'hippopotamus'
addFirstWord(board, word)
printboard(board)
(rowo, colo) = find(board, 'o')
print(checkvertical(board, 'horse', rowo-1, colo))
addvertical(board, 'horse')
I'm stuck trying to check if the word can go at (i, j) and if it can, how to place it there
[edit]
I have made a checkhorizontal function and addhorizontal function
how can I implement a function addL(board, L) which accepts a list of strings and inputs them into the board.
def addwords(board, L):
for i in range(len(L)):
if i == 0:
addFirstWord(board, L[0])
elif i % 2 == 0:
addvertical(board, L[i])
else:
addhorizontal(board, L[i])
L = ['hippopotamus', 'horse', 'loon', 'cat', 'monster', 'rattlesnake', 'dinosaur']
addwords(board, L)
I have this so far where the first word in the list is added to the middle and then words are added horizontally and vertically alternately. The words aren't being outputted.
I don't see the use for the find() function but i think this should work
def checkVertical(board, word, row, col):
D = len(board)
n = len(word)
blank = ' '
if n>(20-row):
return False
matchesoneletter = False
for k in range(n):
wordletter = word[k]
boardletter = board[row + k][col]
if wordletter == boardletter:
matchesoneletter = True
if boardletter == blank:
continue
elif boardletter != wordletter:
return False
return matchesoneletter
def addVertical(board, word):
for i in range(len(board)):
for j in range(len(board)):
if checkVertical(board, word, i, j):
for k in range(len(word)):
board[i + k][j] = word[k]
return True
return False
I am writing a code and want to make it as short as possible, is there any way i can?
text = raw_input("Give me some text > ")
list1 = []
for char in text:
num = ord(char)
if num in range(48,57):
print "ERROR 319: Number entered"
quit()
elif num in range(65,90) or num in range (97,122):
upper = char.upper()
list1.append(upper)
num1 = 0
vowelCount = 0
conCount = 0
for x in range(len(list1)):
if list1[num1] == "A" or list1[num1] == "E" or list1[num1] == "I" or list1[num1] == "O" or list1[num1] == "U":
vowelCount = vowelCount + 1
else:
conCount = conCount + 1
num1 = num1 + 1
print "Vowels: " +str(vowelCount) + " Consonants: " + str(conCount)
Instead of taking ord() of the character, you can use the string methods:
char.isdigit() # check if a char is a digit
char.isalpha() # check if char is letter
For checking the vowel counts, try:
vowel_count = len(filter(lambda c: c in "aeiou", list1))
cons_count = len(list1) - vowel_count
Building off of AmourK's answer, you could do something like this:
text = raw_input("Give me some text > ")
vowel_count = len(filter(lambda c: c in "aeiou", text))
cons_count = len(filter(lambda c: c not in "aeiou" and c.isalpha(), text))
print "Vowels: %d Consonants: %d" % (vowel_count, cons_count)