Python, comment that wraps entire code - python

been trying to wrap entire code in a comment, how do i do that? i tried #, """, with no success, and as a question, is this even possible? i guess im stacking comments on top of other comments but im sure there is a way, im wrapping this code because i want to keep it in one file along with other projects in the same file but i dont want to activate ALL of the code. here's the code i want to wrap as a comment:
"""Artithmetic expressions"""
addition = 1 + 1;
subtraction = 2-1;
miltiplication = 2*2;
division = 5/3; """5/3 = 1"""
"""Variables and Assignment"""
a, b = addition, subtraction; """a = addition, b = subtraction"""
""" prints 2 1"""
print a, b
"""Strings, indexing strings"""
string1 = "hello world hell"
string2 = string1[2]
"""prints 1"""
print string2
"""string extraction"""
string3 = string1[0:5]
""" hello """
print string3
"""Finding"""
stringfind1 = string1.find("hell", 4)
""" prints 12 """
print stringfind1
"""Python 2"""
"""If statement"""
if (3 < 10):
print "true"
else:
print "false"
""" Logical Operators"""
if (3 and 4 < 10):
print "true"
"""may use or"""
"""Loops, ex prints 10 iterations"""
count = 0
while (count < 10):
print 'The count is: ', count
count = count + 1
print "Good bye!"
"""converting between numbers and strings: str(one) converts int to string"""
"""use 'ord' for string --> int, lastly chr = """
one = 1
convert = str(one)
if convert == 1:
print "true"
else:
print "false"
'''returns one character string from number input'''
var1 = chr(65)
print var1
"""splitting strings: () prints all words in a string"""
""" ' ', 1 prints all except the last word?"""
string10 = "fucking hell i hate your life"
var2 = string10.split()
print var2
print string10.split(' ', 1)
"""Looping through strings with 'for' loop, ex prints all chars in 'string10' in new lines"""
for fuckoff in string10:
print 'Current letter :', fuckoff

You can't: Python comments are single line. And docstrings are not comments. However, during development if you need to "switch off" a block of code you can put it into an if False: block.
Eg:
if False:
addition = 1 + 1;
subtraction = 2-1;
miltiplication = 2*2;
division = 5/3;

After seven years of being not right answered here the right answer to the question above:
You can 'switch off' a block of code using appropriate triple quotes.
It will not always be possible (if the code uses both kinds of triple quoted strings), but in the case of code in the question it is possible to use ''' single quoted triple quoted string to achieve what you are after.
Below how it looks like:
'''
"""Artithmetic expressions"""
addition = 1 + 1;
subtraction = 2-1;
miltiplication = 2*2;
division = 5/3; """5/3 = 1"""
"""Variables and Assignment"""
a, b = addition, subtraction; """a = addition, b = subtraction"""
""" prints 2 1"""
print a, b
"""Strings, indexing strings"""
string1 = "hello world hell"
string2 = string1[2]
"""prints 1"""
print string2
"""string extraction"""
string3 = string1[0:5]
""" hello """
print string3
"""Finding"""
stringfind1 = string1.find("hell", 4)
""" prints 12 """
print stringfind1
"""Python 2"""
"""If statement"""
if (3 < 10):
print "true"
else:
print "false"
""" Logical Operators"""
if (3 and 4 < 10):
print "true"
"""may use or"""
"""Loops, ex prints 10 iterations"""
count = 0
while (count < 10):
print 'The count is: ', count
count = count + 1
print "Good bye!"
"""converting between numbers and strings: str(one) converts int to string"""
"""use 'ord' for string --> int, lastly chr = """
one = 1
convert = str(one)
if convert == 1:
print "true"
else:
print "false"
'''returns one character string from number input'''
var1 = chr(65)
print var1
"""splitting strings: () prints all words in a string"""
""" ' ', 1 prints all except the last word?"""
string10 = "fucking hell i hate your life"
var2 = string10.split()
print var2
print string10.split(' ', 1)
"""Looping through strings with 'for' loop, ex prints all chars in 'string10' in new lines"""
for fuckoff in string10:
print 'Current letter :', fuckoff
'''
You can see the evidence that it works as expected from the kind of highlighting of the above piece of code in its code textbox.

Related

How to compare two strings by character and print matching positions in python

I want to compare two strings by character and then print how many times they have the same character in the same position. If I were to input 'soon' and 'moon' as the two strings, it would print that they match in 3 positions.
I've run into another problem where if the 2nd string is shorter, it gives me an error "string index out of range".
I tried
a = input('Enter string')
b = input('Enter string')
i=0
count = 0
while i<len(a):
if b[i] == a[i]:
match = match + 1
i = i + 1
print(match, 'positions.')
You have some extraneous code in the form of the 2nd if statement and you don't have the match incrementor in the first if statement. You also don't need the found variable. This code should solve the problem
# get input from the user
A = input('Enter string')
B = input('Enter string')
# set the incrementors to 0
i=0
match = 0
# loop through every character in the string.
# Note, you may want to check to ensure that A and B are the same lengths.
while i<len(A):
# if the current characters of A and B are the same advance the match incrementor
if B[i] == A[I]:
# This is the important change. In your code this line
# is outside the if statement, so it advances for every
# character that is checked not every character that passes.
match = match + 1
# Move to the next character
i = i + 1
# Display the output to the user.
print(match, 'positions.')
num_matching = 0
a = "Hello"
b = "Yellow"
shortest_string = a if len(a) <= len(b) else b
longest_string = b if shortest_string == a else a
for idx, val in enumerate(shortest_string):
if val == b[idx]:
num_matching += 1
print(f"In {a} & {b} there are {num_matching} characters in the same position!")
Simplifying my answer in light of #gog's insight regarding zip versus zip_longest:
string1 = "soon"
string2 = "moon"
matching_positions = 0
for c1, c2 in zip(string1, string2):
if c1 == c2:
matching_positions += 1
print(matching_positions)
Output:
3

Sum of Digits in a specific way in Python

I'm looking for a code that runs, i.e:
int(input) = 2565
Printed Output should be like:
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
I wrote the code that gives final answer "9". But I couldn't managed to write it with every digit separated "+" sign. Assuming that I need to use while loop but how can I write the code so it will be like the output above?
You can use something like this:
def sum_of_digits(s):
if s < 10:
return s
return sum_of_digits(sum(int(c) for c in str(s)))
> sum_of_digits(2565)
9
It recursively checks if the numerical value is less than 10. If it does, it returns this value. If not, it adds the digits, then recursively calls itself on the result.
Edit
To print out the steps as it goes along, you could do something like this:
def sum_of_digits(s):
if s < 10:
print(s)
return s
print(' + '.join(c for c in str(s)) + ' = ')
return sum_of_digits(sum(int(c) for c in str(s)))
First, initiate an empty string output_str.
With a while loop which contniues when our integer is > 9:
[s for s in str(x)] would create a list of the digits (as strings) of our integer. It's called a list comprehension, is very useful, and my advice is to read a bit about it.
With " + ".join() we create a string with " + " between the
digits. Add this string at the end of output_str.
Add " = " to the end of output_str.
Calculate the sum of the digits (we cannot use sum(lst_of_digits) because it's a list of strings. sum([int(s) for s in lst_of_digits]) converts the string list into an inter list, which can be summed using sum()). Store the sum into x.
Add the new x + " = " to output_string.
At the end of the string, we have a redundant " = " (because the last (5) was not needed), let's just remove the last 3 chars (=) from it.
x = 2565
output_str = ""
while x > 9:
lst_of_digits = [s for s in str(x)]
output_str += " + ".join(lst_of_digits)
output_str += " = "
x = sum([int(s) for s in lst_of_digits])
output_str += f"{x} = "
output_str = output_str[:-3]
outputs:
output_str = '2 + 5 + 6 + 5 = 18 = 1 + 8 = 9'
You can play around with the end keyword argument of the print function which is the last character/string that print will put after all of its arguments are, well, printed, by default is "\n" but it can be change to your desire.
And the .join method from string which put the given string between the given list/iterable of strings to get the desire result:
>>> " + ".join("123")
'1 + 2 + 3'
>>>
Mixing it all together:
def sum_digit(n):
s = sum(map(int,str(n)))
print(" + ".join(str(n)),"=",s, end="")
if s<10:
print()
return s
else:
print(" = ",end="")
return sum_digit(s)
Here we first get the sum of the digit on s, and print it as desire, with end="" print will not go to the next line which is necessary for the recursive step, then we check if done, and in that case print a new empty line if not we print an additional = to tie it for the next recursive step
>>> sum_digit(2565)
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
9
>>>
This can be easily be modify to just return the accumulated string by adding an extra argument or to be iterative but I leave those as exercise for the reader :)
I am a noob but this should do what you want.
Cheers,
Guglielmo
import math
import sys
def sumdigits(number):
digits = []
for i in range( int(math.log10(number)) + 1):
digits.append(int(number%10))
number = number/10
digits.reverse()
string = ''
thesum = 0
for i,x in enumerate(digits):
string += str(x)
thesum += x
if i != len(digits)-1: string += ' + '
else: string += ' = '
if thesum > 10:
return string,thesum,int(math.log10(number))+1
else:
return string,thesum,0
def main():
number = float(sys.argv[1])
finalstring = ''
string,thesum,order = sumdigits(number)
finalstring += string
finalstring += str(thesum)
while order > 0:
finalstring += ' = '
string,thesum,order = sumdigits(thesum)
finalstring += string
finalstring += str(thesum)
print 'myinput = ',int(number)
print 'Output = ',finalstring
if __name__ == "__main__":
main()

Irregular display when printing functions

I'm trying to write a script that when called prompts a user for a string and it displays the string forward, backward, tests if 2 strings are the same, and tests if a string is a palindrome. I want to test the individual functions for correctness before I input a menu, however the output when calling palindrome() function seems irregular. Any help on why the two statements in the palindrome() function prints this way would be appreciated.
string = raw_input('Enter a string\n>>>')
def forward():
for i in string:
print i,
return str(i)
def backwards():
back = len(string) - 1
while back > 0:
print string[back],
back -= 1
return str(string[back])
def match():
next_string = raw_input('Enter another string')
if string.upper() == next_string.upper():
print 'the strings ', string, ' and ', next_string, ' match.'
else:
print 'the strings ', string, ' and ', next_string, ' do not match.'
def palindrome():
print backwards() # When I don't print this call it only displays the last value in the string
y = forward() # When I do print this call it displays the last value in the string twice
# This is the only way where these calls are opposite
palindrome()

Count the number of spaces between words in a string

I am doing this problem on Hackerrank,and I came up with the idea, which includes splitting the input and join it afterwards (see my implementation below). However, one of the test cases contains the input (hello< multiple spaces> world), which crashed my code because the input string has more than 1 space between each words. So, I am just wondering if anyone could please help me out fix my code, and I am just wondering how to count how many spaces(esp multiple spaces) in a string in Python. I found how to count spaces in Java, but not in Python. For testcase, I attached the pic.
Thanks in advance.
My implementation:
input_string = input()
splitter = input_string.split()
final = []
for i in range(0,len(splitter)):
for j in range(0,len(splitter[i])):
if(j==0):
final.append(splitter[i][j].upper())
else:
final.append(splitter[i][j])
# Assumed that there is one space btw each words
final.append(' ')
print(''.join(final))
For Test case pic,
You can fix it by splitting with pattern ' ' (whitespace)
splitter = input_string.split(' ')
You can also use .capitalize() method instead of splitting the token again
s = "hello world 4lol"
a = s.split(' ')
new_string = ''
for i in range(0, len(a)) :
new_string = a[i].capitalize() if len(new_string)==0 else new_string +' '+ a[i].capitalize()
print(new_string)
Output:
Hello World 4lol
For counting number of spaces between two words, you can use python's regular expressions module.
import re
s = "hello world loL"
tokens = re.findall('\s+', s)
for i in range(0, len(tokens)) :
print(len(tokens[i]))
Output :
7
2
What I suggest doing for the tutorial question is a quick simple solution.
s = input()
print(s.title())
str.title() will capitalise the starting letter of every word in a string.
Now to answer the question for counting spaces you can use str.count()) which will take a string and return the number of occurrences it finds.
s = 'Hello World'
s.count(' ')
There are various other methods as well, such as:
s = input()
print(len(s) - len(''.join(s.split())))
s2 = input()
print(len(s2) - len(s2.replace(' ', '')))
However count is easiest to implement and follow.
Now, count will return the total number, if you're after the number of spaces between each world.
Then something like this should suffice
s = input()
spaces = []
counter = 0
for char in s:
if char== ' ':
counter += 1
elif counter != 0:
spaces.append(counter)
counter = 0
print(spaces)
import re
line = "Hello World LoL"
total = 0
for spl in re.findall('\s+', line):
print len(spl)
total += len(spl) # 4, 2
print total # 6
>>> 4
>>> 2
>>> 6
For you problem with spaces
my_string = "hello world"
spaces = 0
for elem in my_string:
if elem == " ":
#space between quotes
spaces += 1
print(spaces)
you can use count() function to count repeat of a special character
string_name.count('character')
for count space you should :
input_string = input()
splitter = input_string.split()
final = []
for i in range(0, len(splitter)):
for j in range(0, len(splitter[i])):
if(j==0):
final.append(splitter[i][j].upper())
else:
final.append(splitter[i][j])
final.append(' ')
count = input_string.count(' ')
print(''.join(final))
print (count)
good luck
I solved that problem a time ago, just add " " (white space) to the split function and then print each element separated by a white space. Thats all.
for i in input().split(" "):
print(i.capitalize(), end=" ")
The result of the split function with "hello world lol" is
>>> "hello world lol".split(" ")
>>>['hello', '', '', '', 'world', '', '', '', 'lol']
Then print each element + a white space.
Forget the spaces they are not your problem.
You can reduce the string to just the words without the extra spaces using split(None) which will give you a word count and your string i.e.
>>> a = " hello world lol"
>>> b = a.split(None)
>>> len(b)
3
>>> print(" ".join(b))
hello world lol
Edit: After following your link to read the actual question, next time include the relevant details in your question, it makes it easier all round,
your issue still isn't counting the number of spaces, before, between or after the words. The answer that solves the specific task has already been provided, in the form of:
>>> a= " hello world 42 lol"
>>> a.title()
' Hello World 42 Lol'
>>>
See the answer provided by #Steven Summers
Approach
Given a string, the task is to count the number of spaces between words in a string.
Example:
Input: "my name is geeks for geeks"
Output: Spaces b/w "my" and "name": 1
Spaces b/w "name" and "is": 2
Spaces b/w "is" and "geeks": 1
Spaces b/w "geeks" and "for": 1
Spaces b/w "for" and "geeks": 1
Input: "heyall"
Output: No spaces
Steps to be performed
Input string from the user’s and strip the string for the removing unused spaces.
Initialize an empty list
Run a for loop from 0 till the length of the string
Inside for loop, store all the words without spaces
Again Inside for loop, for storing the actual Indexes of the words.
Outside for loop, print the number of spaces b/w words.
Below is the implementation of the above approach:
# Function to find spaces b/w each words
def Spaces(Test_string):
Test_list = [] # Empty list
# Remove all the spaces and append them in a list
for i in range(len(Test_string)):
if Test_string[i] != "":
Test_list.append(Test_string[i])
Test_list1=Test_list[:]
# Append the exact position of the words in a Test_String
for j in range(len(Test_list)):
Test_list[j] = Test_string.index(Test_list[j])
Test_string[j] = None
# Finally loop for printing the spaces b/w each words.
for i in range(len(Test_list)):
if i+1 < len(Test_list):
print(
f"Spaces b/w \"{Test_list1[i]}\" and \"{Test_list1[i+1]}\": {Test_list[i+1]-Test_list[i]}")
# Driver function
if __name__ == "__main__":
Test_string = input("Enter a String: ").strip() # Taking string as input
Test_string = Test_string.split(" ") # Create string into list
if len(Test_string)==1:
print("No Spaces")
else:
Spaces(Test_string) # Call function

saving the number into the variable in every run of cycle python

I wrote the function that converts the string in argument to number. If the string does not contain number the cycle breaks and the new variable with numbers is printed.
If the argument is "123" the function returns 6. I don't want to return the sum, just placing every number in a row. How do I accomplish the result 123? I don!t know what to use instead of string2 += float(c).
def try_parse(string):
string2=0
for c in string:
if c.isdigit() == True:
string2 += float(c)
else:
break
return string2
I modified your code:
def try_parse(string):
string2 = ""
for c in string:
if not c.isdigit() and c != '.':
break
string2 += c
return string2
You can see that now I use string2 as a string and not an int (When the + sign is used on an int you sum, and with a string + is used for concatenation).
Also, I used a more readable if condition.
Update:
Now the condition is ignoring the '.'.
Tests:
>>> try_parse('123')
'123'
>>> try_parse('12n3')
'12'
>>> try_parse('')
''
>>> try_parse('4.13n3')
'4.13'
Note
The return type is string you can use the float() function wherever you like :)
You need to use a string for string2, and str instead of float.
You want string2 = "", and string2 += c. (You don't need to call str on c because it is already a string.)
You could leave the conversion to a number to Python (using int(), rather than float(); you only filter on digits), and only worry about filtering:
def try_parse(string):
digits = []
for c in string:
if c.isdigit():
digits.append(c)
return int(''.join(digits))
but if you really want to build a number yourself, you need to take into account that digits are not just their face value. 1 in 123 does not have the value of one. It has a value of 100.
The easiest way then to build your number would be to multiply the number you have so far by 10 before adding the next digit. That way 1 stays 1, and 12 starts as 1 then becomes 10 as you add the 2, etc:
def try_parse(string):
result = 0
for c in string:
if c.isdigit():
result = result * 10 + int(c)
return result

Categories