- Task
print Hello, World! on your screen
def main():
my_string = “Hello, World!”
print (my_string)
if __name__ == ‘__main__’:
main()
- Task
Given an integer, , perform the following conditional actions:
- If is odd, print Weird
- If is even and in the inclusive range of to , print Not Weird
- If is even and in the inclusive range of to , print Weird
- If is even and greater than , print Not Weird
Input Format
A single line containing a positive integer, .
Constraints
Output Format
Print Weird if the number is weird. Otherwise, print Not Weird.
import math
import os
import random
import re
import sys
def main():
n = int(raw_input().strip())
if n % 2 == 1:
print (“Weird”)
elif n >= 6 and n <=20:
print (“Weird”)
else: print (“Not Weird”)
if __name__ == ‘__main__’:
main()
- Task
The provided code stub reads two integers from STDIN, and . Add code to print three lines where:
- The first line contains the sum of the two numbers.
- The second line contains the difference of the two numbers (first – second).
- The third line contains the product of the two numbers.
if __name__ == ‘__main__’:
a = int(raw_input())
b = int(raw_input())
print a + b
print a – b
print a * b
- Task
The provided code stub reads two integers, and , from STDIN.
Add logic to print two lines. The first line should contain the result of integer division, // . The second line should contain the result of float division, / .
No rounding or formatting is necessary.
from __future__ import division
def main():
a = int(raw_input())
b = int(raw_input())
print a // b
print a / b
if __name__ == ‘__main__’:
main()
- Task
The provided code stub reads and integer, , from STDIN. For all non-negative integers , i < n , print i ** 2 .
def main():
n = int(input())
i = 0
while i < n:
print (i ** 2)
i = i + 1
if __name__ == ‘__main__’:
main()
- Leap Year
An extra day is added to the calendar almost every four years as February 29, and the day is called a leap day. It corrects the calendar for the fact that our planet takes approximately 365.25 days to orbit the sun. A leap year contains a leap day.
In the Gregorian calendar, three conditions are used to identify leap years:
- The year can be evenly divided by 4, is a leap year, unless:
- The year can be evenly divided by 100, it is NOT a leap year, unless:
- The year is also evenly divisible by 400. Then it is a leap year.
- The year can be evenly divided by 100, it is NOT a leap year, unless:
This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. Source
Task
Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False.
Note that the code stub provided reads from STDIN and passes arguments to the is_leap function. It is only necessary to complete the is_leap function.
def is_leap(year):
leap = False
if year % 4 == 0 and year % 100 != 0:
leap = True
elif year % 100 == 0 and year % 400 == 0:
leap = True
else: leap = False
return leap
year = int(input())
print(is_leap(year))
modify the function a bit as below to test in spyder
year = 2100 # testing year
def is_leap(year):
leap = False
if year % 4 == 0 and year % 100 != 0:
leap = True
elif year % 100 == 0 and year % 400 == 0:
leap = True
else: leap = False
return leap
print (is_leap(year))
- Print Function – List —- Hint ==> print (*list, sep=””)
The included code stub will read an integer, , from STDIN.
Without using any string methods, try to print the following:
Note that “” represents the consecutive values in between.
if __name__ == ‘__main__’:
n = int(input())
i = 1
list = []
while i <= n:
list.append(i)
i = i +1
print (*list, sep=””)
- Regular Expression example
Write a simple program to check if the set of characters contain a-zA-Z0-9
import re
if __name__ == ‘__main__’:
def checkChar(string):
result = re.match(r'[^a-zA-Z0-9.]’, string)
return not bool(result)
print(checkChar(“ABCDEabcde12345”))
print(checkChar(“*&^%$#@!)”))
- Regular Expression example 2
import re
if __name__ == ‘__main__’:
def checkChar(string):
patterns = ‘ab*’
if re.search(patterns, string):
return ‘found a match’
else: return ‘found not match’
print (checkChar(‘abbb’))
print (checkChar(‘ab’))
print (checkChar(‘a’))
print (checkChar(‘ccc’))
- Validating Roman Numeral
You are given a string, and you have to validate whether it’s a valid Roman numeral. If it is valid, print True. Otherwise, print False. Try to create a regular expression for a valid Roman numeral.
Input Format
A single line of input containing a string of Roman characters.
Output Format
Output a single line containing True or False according to the instructions above.
Constraints
The number will be between 1 and 3999 (both included).
regex_pattern = r”(^M{0,3})(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$” # Do not delete ‘r’.
import re
print(str(bool(re.match(regex_pattern, input()))))
- Validating Phone Number
How to read from stdin
https://www.geeksforgeeks.org/take-input-from-stdin-in-python/
Concept
A valid mobile number is a ten digit number starting with a 7,8,9
Sample Input
2
9587456281
1252478965
Sample Output
YES
NO
# Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
import re
if __name__ == ‘__main__’:
for linenum, line in enumerate(sys.stdin):
if linenum != 0:
patterns = r’^[7,8,9][0-9]{9}$’
result = bool(re.match(patterns, line))
if result == True:
print(‘YES’)
else: print(‘NO’)
- Validating and Parsing email addresses
A valid email address meets the following criteria:
- It’s composed of a username, domain name, and extension assembled in this format: username
- The username starts with an English alphabetical character, and any subsequent characters consist of one or more of the following: alphanumeric characters, -,., and _.
- The domain and extension contain only English alphabetical characters.
- The extension is , , or characters in length.
Given pairs of names and email addresses as input, print each name and email address pair having a valid email address on a new line.
Hint: Try using Email.utils() to complete this challenge. For example, this code:
import email.utils
print email.utils.parseaddr(‘DOSHI <[email protected]>’)
print email.utils.formataddr((‘DOSHI’, ‘[email protected]’))
produces this output:
(‘DOSHI’, ‘[email protected]’)
DOSHI <[email protected]>
Input Format
The first line contains a single integer, , denoting the number of email address.Each line of the subsequent lines contains a name and an email address as two space-separated values following this format:
name <[email protected]>
Constraints
0 < n < 100
Output Format
Print the space-separated name and email address pairs containing valid email addresses only. Each pair must be printed on a new line in the following format:
name <[email protected]>
You must print each valid email address in the same order as it was received as input.
Sample Input
2
DEXTER <[email protected]>
VIRUS <virus!@variable.:p>
Sample Output
DEXTER <[email protected]>
Solutions
# Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
import re
import email.utils
for linenum, line in enumerate(sys.stdin):
if linenum != 0:
patterns = r’^[a-zA-Z]{1}[a-zA-Z0-9._-]+[@]{1}[a-zA-Z]+[.]{1}[a-zA-Z]{1,3}$’
nameEmail = email.utils.parseaddr(line)
result = bool(re.match(patterns, nameEmail[1]))
if result == True:
print (email.utils.formataddr(nameEmail))
Modify the solution and run in spyder
import re
import email.utils
if __name__ == “__main__”:
line = input(“Please input name, <email address>:”)
patterns = ‘^[a-zA-Z]{1}[a-zA-Z0-9-._]+[@]{1}[a-zA-Z]+[.]{1}[a-zA-Z]{1,3}$’
nameEmail = email.utils.parseaddr(line)
result = bool(re.match(patterns, nameEmail[1]))
if result == True:
print (email.utils.formataddr(nameEmail))
- Hex Color Code
CSS colors are defined using a hexadecimal (HEX) notation for the combination of Red, Green, and Blue color values (RGB).
Specifications of HEX Color Code
■ It must start with a ‘#’ symbol.■ It can have or digits.■ Each digit is in the range of to . ( and ).■ letters can be lower case. ( and are also valid digits).
Examples
Valid Hex Color Codes
#FFF
#025
#F0A1FB
Invalid Hex Color Codes
#fffabg
#abcf
#12365erff
Solution
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re, sys
[print(j) for i in sys.stdin for j in re.findall(‘[s:](#[a-f0-9]{6}|#[a-f0-9]{3})’, i, re.I)]
Evernote helps you remember everything and get organized effortlessly. Download Evernote. |