blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
d4d54e8aba42185e4cb6a5e556e1c3cbc6ced421
talianassi921/python-practice
/Methods/bouncer.py
276
4.125
4
print("How old are you?") age = int(input()) if age: if age >=18 and age <21: print("You can enter but need a wristband") elif age>=21: print("You can enter and drink") else: print("You can not enter") else: print("please enter an age")
true
85761e99170d558e0ac85952c5b7f8b77cff08a9
talianassi921/python-practice
/Methods/args.py
531
4.15625
4
# *args - special operator youc an pass to functions, gathers remaining arguments as a tuple # args is a tuple of all the arguments def sum_all_nums(*args): total = 0 for num in args: total +=num return total print(sum_all_nums(4,6)) print(sum_all_nums(5,1,4)) def ensure_correct_info(*args): if "Colt" in args and "Steele" in args: return "Welcome back Colt!" return "Not sure who you are..." ensure_correct_info() # Not sure who you are... ensure_correct_info(1, True, "Steele", "Colt")
true
2af0488f4996ac04670fb29af7f1a3a23d02782f
alejandroTo/python
/unidad1/metIntegrados.py
613
4.21875
4
#convertir un numero a binario #los primeros dos caracteres indican que tipo de dato es a = 10 print(bin(a)) #convertir un numero a hexadecimal #los primeros dos caracteres indican que tipo de dato es print(hex(a)) #convertir de binario a base 10 o normal #en el primeros dos caracteres va el tipo a convertir #en la segunda va al base en la que estamos convirtiendo print(int("0b1010",2)) #convertir de hexadecimal a base 10 o normal print("Conversion de hexadecimal a base normal",int("0xb",16)) #saber la longitud de una cadena nombre = "jose" print(f"hello {nombre} your name have {len(nombre)} characters")
false
199378efaad8817d2cd61913481cb49d52f40a08
ChoppingBroccoli/Python_Exercises
/Calc_Square_Root.py
397
4.125
4
user_response=float(input("Enter a number: ")) guess=user_response/2 accuracy=0.01 iteration=0 while abs(user_response-(guess**2)) > accuracy: print("Guessed square root is:",guess) guess=(guess+(user_response/guess))/2 iteration=iteration+1 print("Original number is: ", user_response) print("Square root of the number is: ", guess) print("The loop ran",iteration,"times")
true
21fa39452077c1183cfcc275ed79c6bda46798c3
ChoppingBroccoli/Python_Exercises
/another for loop.py
860
4.25
4
# Receive input from the user user_input = input("Enter a number:") #Convert the user input from a str to a int n = int(user_input) #Initialize count to 0. count will store sum of all the numbers count = 0 #Initialize iterations to 0. iterations will keep track of how many iterations it takes to complete the loop iterations = 0 for x in range(1,n+1): #Store the value of count before it's changed pre_count = count print("Count is now", count, "and x is now", x) #Add the value of count to the value of x count = count + x print(pre_count,"plus", x, "is",count) #Increment iterations by one iterations = iterations + 1 print("You entered", user_input) print("The sum of all numbers from 1 to", user_input, "is", count) print("Loop completed in", iterations, "iterations") """ print(count) """
true
40fdfef0505312f53ed56b03ec5c98698f8f80e9
leeban99/python-practice
/function_list.py
481
4.21875
4
# Write your code here :-) #Functions in list def func(): print('Inside func') def disp(): print('Inside disp') def msg(): print('Inside msg') lst = [func, disp, msg] for f in lst: f() ############################################ lst1 = [1,2,3,4,5,6] lst2 = [9,8,7,6,5,4] maplst = map(lambda n1,n2 : n1+n2,lst1,lst2) print(list(maplst)) ############################################ lst3 = [2,3,8,-4,6,-3] mapsqr = map(lambda n1:n1*n1,lst3) print(list(mapsqr))
false
2fb43c8d11bf0b7629cee530490ad8b58f0d043e
jisshub/python-django-training
/code-snippets/phone_no_valid.py
262
4.125
4
# Phone number Validation import re def phone_num(phone): regex = re.fullmatch('^[6-9]\d\d{5}', phone) if regex is None: return 'Invalid Phone' else: return 'Valid Number' number = input('Enter Phone: ') print(phone_num(number))
true
3fc1b978e652550c15fe35ddfb3c1546cbac35e9
jisshub/python-django-training
/oops-python/operator_overloading.py
1,611
4.3125
4
# OPERATOR OVERLOADING class Books: def __init__(self, pages): self.pages = pages b1 = Books(300) b2 = Books(400) print(b1 + b2) # here v cant add both the objects since it is an object type # here can use special method or magic method called add() # ie. __add__() class Books: def __init__(self, pages): self.pages = pages def __add__(self, other): # return 'hello' return self.pages + other.pages b1 = Books(300) b2 = Books(400) add = b1 + b2 print(type(add)) # here while v perfrom '+' operation of two objects, # then special method called add is invoked. # here self points to object b1 and other keyword points to other objects. # similarly there are special methods for each operators class Books: def __init__(self, pages): self.pages = pages def __sub__(self, other): # return 'hello' return other.pages - self.pages b1 = Books(300) b2 = Books(400) print(b1 - b2) # adding 3 objects at a time class Books: def __init__(self, pages): self.pages = pages def __add__(self, other): bk = Books(self.pages + other.pages) return bk def __str__(self): return str(self.pages) b1 = Books(300) b2 = Books(400) b3 = Books(100) add = b1 + b2 + b3 print(add) print(type(add)) # here v initially perform b1 + b2 and later add it with b3 # it returns error since b1+b2 is an int type and v add it with an object type b3 # so we add first two objects and later add it with third object and finally convert it to an object type # Thus v can add all three together.
true
36ebbd30c49b486649326d084075f441739f39eb
jisshub/python-django-training
/regex/match_using_pipe.py
1,310
5
5
# Matching Multiple Groups with the Pipe # # The | character is called a pipe. You can use it anywhere you want to match one # of many expressions. For example, the regular expression r'Batman|Tina Fey' # will match either 'Batman' or 'Tina Fey' . import re pattern = re.compile(r'jiss|jose') match = pattern.search('jiss and jose') print(match.group()) # examples import re pattern = re.compile(r'batman|ironman|spiderman') try: match = pattern.search('superheroes r the saviuors of the world. is dead now who?') print(match.group()) except Exception as e: print(e.args) finally: print(pattern) # You can also use the pipe to match one of several patterns as part of # your regex. For example, say you wanted to match any of the strings 'superman' , # 'superwomen' , 'supergirl' , and 'superboy' . Since all these strings start with super , it # would be nice if you could specify that prefix only once. This can be done # with parentheses. import re pattern = re.compile(r'super(man|women|girl|boy)') match = pattern.search('superboy') match = match.group() # print(match) try: with open('super2.txt', 'w') as file_to: file_to.write(match) with open('super2.txt', 'r') as file_to_rd: print(file_to_rd.read(), end='') except Exception as err: print(err.args)
true
b07326cd738f97339c160e810093bace567efbf0
goldgator/BinaryBattlesClient
/Question1.py
331
4.21875
4
"""Greeting Name! [Easy]""" """Code a Function that takes a name(string) and adds a greeting""" """Ex: Input("Danny") --> Output = "Hey Danny!" """ """Solution""" def hello_name(name): return "Hello {}!".format(name) # Test print(hello_name("Danny")) print(hello_name("Gali")) print(hello_name("Jesse"))
false
feaf84136bb18ef9712ea7f2bc687c7f4faaebfe
CBarreiro96/holbertonschool-higher_level_programming
/0x06-python-classes/5-square.py
930
4.40625
4
#!/usr/bin/python3 """ Class square with follow restriction Default size to 0. Raise error on invalid size inputs. Methods Getter and Setter properties for size. Methods of Area to find the size Methods of print to pint # """ class Square: """A class that defines a square by size, which defaults 0. Square can also get area, and print square using '#'. """ def __init__(self, size=0): self.size = size @property def size(self): return self.__size @size.setter def size(self, size): if type(size) != int: raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") self.__size = size def area(self): return self.__size * self.__size def my_print(self): if self.__size is 0: print("") for i in range(self.__size): print("#" * self.__size)
true
b4fcdf4f4d64314d40ec3bff2bb3103c8003afe6
Tvashta/cp
/BFS and DFS/LargestInLevel.py
979
4.15625
4
# You have a binary tree t. Your task is to find the largest value in each row of this tree. # In a tree, a row is a set of nodes that have equal depth. For example, a row with depth 0 is a tree root, # a row with depth 1 is composed of the root's children, etc. # Return an array in which the first element is the largest value in the row with depth 0, # the second element is the largest value in the row with depth 1, # the third element is the largest element in the row with depth 2, etc. def largestValuesInTreeRows(t): l = [] if t: q = [t, None] l1 = [] while len(q): s = q.pop(0) if s == None: if l1: l.append(max(l1)) q.append(None) l1 = [] else: l1.append(s.value) if s.left: q.append(s.left) if s.right: q.append(s.right) return l
true
8120e1e0c841585435bcafa63e9a71a28904900a
nupurj24/comp110-21f-workspace
/exercises/ex01/relational_operators.py
448
4.125
4
"""A program that shows how relational operators work.""" __author__ = "730391424" a: str = input("Choose a whole number for the left-hand side of the equations. ") b: str = input("Choose a whole number for the right-hand side of the equations. ") c = int(a) d = int(b) print(a + " < " + b + " is " + str(c < d)) print(a + " >= " + b + " is " + str(c >= d)) print(a + " == " + b + " is " + str(c == d)) print(a + " != " + b + " is " + str(c != d))
true
f4ee9c06880c6bbf9166658025cb80c3bf4c749b
imshaiknasir/PythonProjectx
/Basics/Constructor01.py
359
4.28125
4
#constructor in python... class Truck: brand = "BMW" def __init__(self): #to create constructor is __init__(); this function will be executed while object creation print("Constructor is executed first.") def getName(self): print("Simple method execution.") obj = Truck() #constructor executed; obj.getName() print(obj.brand)
true
6511be165f3d7c476c8a6dfce32fd82a534c33f4
SandeshKarumuri/Telusko-Python
/telusko/OOP/Operator Overloading.py
824
4.125
4
# a = 5 # b = 'th Dimension' # print(a + b) # print(int.__add__(a,b)) used for addition of two integers class Student: def __init__(self, m1, m2): self.m1 = m1 self.m2 = m2 def __add__(self, other): # Student.__add__(self,other) m1 = self.m1 + other.m1 m2 = self.m2 + other.m2 s3 = Student(m1, m2) return s3 def __gt__(self, other): r1 = self.m1 + self.m2 r2 = self.m1 + self.m2 if r1 > r2: return True else: return False def __str__(self): return '{} {}'.format(self.m1, self.m2) s1 = Student(76, 79) s2 = Student(86, 75) s3 = s1 + s2 print(s3.m1) print(s3.m2) if s1>s2: print("S1 WINS") else: print("S2 WINS") print(s1) print(s2)
false
e622423eae6d1f6a2c82aab4fba13d446b45c05c
SteveChristian70/Coderbyte
/vowelCounter.py
478
4.1875
4
''' Have the function VowelCount(str) take the str string parameter being passed and return the number of vowels the string contains (ie. "All cows eat grass" would return 5). Do not count y as a vowel for this challenge. Use the Parameter Testing feature in the box below to test your code with different arguments. ''' def VowelCount(str): count = 0 for x in str: if x in "aeiou": count += 1 return count print VowelCount(raw_input())
true
629b337e0a0d4fedc8bfb38f3625640b0ad2f291
ArunVasanthmdu/Python-Tricks
/numbertotext.py
1,030
4.375
4
# Function to convert number to text def convertValue(digit): if digit == '0': print("Zero ", end = " ") elif digit == '1': print("One ", end = " ") elif digit == '2': print("Two ", end = " ") elif digit=='3': print("Three",end=" ") elif digit == '4': print("Four ", end = " ") elif digit == '5': print("Five ", end = " ") elif digit == '6': print("Six ", end = " ") elif digit == '7': print("Seven", end = " ") elif digit == '8': print("Eight", end = " ") elif digit == '9': print("Nine ", end = " ") # Function to loop through each character in the given number def changeWord(N): i = 0 length = len(N) while i < length: convertValue(N[i]) i += 1 print("") movenext="Y" while movenext=="Y": n=input('Please enter a number to convert: ') changeWord(n) movenext = input("Do you want to continue using the converter (Y/N): ")
false
91ce4b1cf253455e9f528d8d34d258f1e09ac41c
redi-backend-python/celsius-fahrenheit-converter
/celsius-fahrenheit-converter.py
719
4.25
4
def print_celsius_values_with_signature(celsius): if False: # Please add the condition print("The celsius value you entered is positive") elif False: # Please add the condition print("The celsius value you entered is zero") else: print("The celsius value you entered is negative") def compute_fahrenheit(celsius): result = 0 # Please calculate fahrenheit return result def main(): celsius = float(input("Enter a Temperature in Celsius to convert it to Fahrenheit: ")) print_celsius_values_with_signature(celsius) fahrenheit = compute_fahrenheit(celsius) print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' % (celsius, fahrenheit)) main()
true
f2f0d723ac0515704dfd0a64e8dc53840110112a
pagliuca523/Python--Intro-to-Comp-Science
/month_abbreviation.py
316
4.1875
4
#Program to show a short name for months def main(): months = "JanFebMarAprMayJunJulAugSepOctNovDec" usr_month = int(input("Please enter the month number (1-12): ")) usr_month = ((usr_month -1) * 3) month_abbrev = months [usr_month:usr_month+3] print("Month: {}".format(month_abbrev)) main()
false
039e5d861330d79c47a6df234f14d41a7077650b
pagliuca523/Python--Intro-to-Comp-Science
/month_complete_name.py
355
4.25
4
#Program to show a long name for months def main(): months = ("January","February","March", "April", "May", "June", "July", "August", "September", "October", "November", "December") usr_month = int(input("Please enter the month number (1-12): ")) usr_month = usr_month -1 #print(type(months)) -- Tuple print(months[usr_month]) main()
true
906a54c881a62712a2fe243695a76d6c5c68f4e1
pagliuca523/Python--Intro-to-Comp-Science
/vol_suf_sphere.py
321
4.125
4
import math def main(): print("Calculus Sphere Volume & Surface") radius = float(input("Please enter radius value: ")) #pi = 3.1415 volume_sph = ((4/3) * (math.pi * (radius**3))) area_sph = 4*(math.pi*(radius**2)) print ("Volume = {}" "\nArea = {}".format(volume_sph,area_sph)) main()
false
93b662ec86fd09571214a98bf17ab609f9cc1256
NotSvipdagr/Python-course
/mystuff/ex20.py
2,618
4.5625
5
# The below line imports the argv module from sys from sys import argv # The below line gives the argument variables to unpack using argv on the command line script, input_file = argv # The below line defines function "print_all" with one FuncVar "f" def print_all(f): # The below line prints/uses whatever value is entered for FuncVar "f", then reads it print f.read() # The below line defines function "rewind" with one FuncVar "f" def rewind(f): # The below line prints/uses whatever value is entered for FuncVar "f" and # seeks line number 0 in that doc f.seek(0) # The below line defines function print_a_line with 2 FuncVar "line_count" and "f" def print_a_line(line_count, f): # The below line prints/uses whatever value is entered for FuncVar "line_count" and # prints just the corresponding N++ line number # then # prints/uses whatever value is entered for FuncVar "f" and prints a single line # SO it uses the file entered for f, prints the line number, then the text on that line print line_count, f.readline() # The below line gives variable "current_file" a value of -- opening the input_file # which was entered by the user as an argument in the command line current_file = open(input_file) # The below line prints the words in "" and uses \n to leave a line empty afterwards print "First let's print the whole file:\n" # The below line calls function "print_all" with global variable "current_file" # see above, you'll recall global variable "current_file" = open(input_file) # SO, global variable "current_file" opens the file input by user print_all(current_file) # The below line prints the words in "" print "Now let's rewind, kind of like a tape." # The below line calls function "rewind" with global variable "current file" rewind(current_file) # The below line prints the words in "" print "Let's print three lines:" # The below line sets global variable current_line = to line 1 # probably needs the rewind or a fresh start to be able to do that current_line = 1 # The below line calls function "print_a_line" with global variables # "current_line" and "current_file" print_a_line(current_line, current_file) # The below line sets global variable "current_line" to the current line + 1 current_line += 1 print_a_line(current_line, current_file) current_line += 1 print_a_line(current_line, current_file) # I think when we open a file, we move through it consecutively and Shell saves our # progress. Thats why we need to use the function "rewind" and why we can use # current_line + 1 and it knows to go from 1 to 2 to 3 etc
true
14b22a3a90b2065ab876dabc6a0d00280c050db8
Harmandhindsa19/Python-online
/class6/assignment6.py
1,672
4.15625
4
#print the taken input to screen l=[] for x in range(10): l.append(int(input("enter the element:"))) print(l) #infinite loop x=10 while True: print("hello world") x+=1 #list list=[] for i in range(6): list.append(int(input("enter the element:"))) squarelist=[] for i in range(6): squarelist.append(list[i]*list[i]) print(list) print(squarelist) # From a list containing ints, strings and floats, # make three lists to store them separately. list=[1,5.5,'izmir',70,40,'ali','bella','cow','denzili',8,2.2] x=[] y=[] z=[] for i in list: if type(i)==int: x.append(i) elif type(i)==float: y.append(i) elif type(i)==str: z.append(i) print(list) print(x) print(y) print(z) #Using range(1,101), make a list containing even and odd numbers. even=[] odd=[] for x in range(1,101): if x%2==0: even.append(x) else: odd.append(x) print(even) print(odd) #print the star pattern for x in range(10): print("*"*x) #Create a user defined dictionary and get keys corresponding to the value using for loop. dict={} keys="" value="" for x in range(4): keys=str(input("enter the keys:")) values=str(input("enter the values:")) dict[keys]=values print(dict) for k in dict.keys(): print(k,dict[k]) #Take inputs from user to make a list. #Again take one input from user and search it in the list and delete that element,if found. #Iterate over list using for loop. list=[] for i in range(6): list.append(str (input("enter the element:"))) print(list) name=str(input("enter the name:")) for j in list: if j==name: list.remove(j) print(list)
true
a1f4767db03a0eafa55d610176496a25b6d7aab2
gadlakha/Two-Pointers-2
/Problem2.py
1,309
4.15625
4
#Two Pointers 2 #Problem1 : https://leetcode.com/problems/merge-sorted-array/ #All test cases passed on Leetcode #Time Complexity-O(N) #Space Complexity-O(1) class Solution: def merge(self, nums1, m, nums2, n) : """ Do not return anything, modify nums1 in-place instead. """ #Take two pointers starting from last of both the lists p1 = m - 1 p2 = n - 1 # set pointer for nums1 # no of elements initialised currently are m and n , so the pointer in nums1 would be m+n-1 (since index started from O) p = m + n - 1 while p1 >= 0 and p2 >= 0: #if nums2 element is greater than nums1 element at which pointers are currently pointed, we 'll assign that 'to the right side of the list if nums1[p1] < nums2[p2]: nums1[p] = nums2[p2] p2 -= 1 else: #otherwise assign nums1 element to the right hand side nums1[p] = nums1[p1] p1 -= 1 p -= 1 # add missing elements from nums2 nums1[:p2 + 1] = nums2[:p2 + 1] sol = Solution() nums1=[1,2,3,0,0,0] nums2=[2,5,6] m=3 n=3 sol.merge(nums1, m, nums2, n) print(nums1)
true
82968b5f157b80902e356e4a22d7ebe945772507
zz45/Python-for-Data-Structures-Algorithms-and-Interviews
/Sentence Reversal.py
1,048
4.28125
4
# -*- coding: utf-8 -*- ''' Given a string of words, reverse all the words. For example: Given: 'This is the best' Return: 'best the is This' As part of this exercise you should remove all leading and trailing whitespace. So that inputs such as: ' space here' and 'space here ' both become: 'here space' ''' # My answer def rev_word(s): word_list = s.split() word_list.reverse() # get the reversed list into a string rev_String = ' '.join(word_list) return rev_String # Jose's answer for this # The same # Testing from nose.tools import assert_equal class ReversalTest(object): def test(self,sol): assert_equal(sol(' space before'),'before space') assert_equal(sol('space after '),'after space') assert_equal(sol(' Hello John how are you '),'you are how John Hello') assert_equal(sol('1'),'1') print ("ALL TEST CASES PASSED") # Run and test t = ReversalTest() t.test(rev_word)
true
c71d32560377d57ca57802fa196cc58610081680
wangrui0/python-base
/com/day07/demo04_global_attention.py
620
4.3125
4
# 注意 全局变量定义的顺序:全局变量在函数调用之前定义就可以啦;故为了好看:我们一般在开头调用 a = 100 # b = 200 # c = 300 def test(): print("a=%d" % a) print("b=%d" % b) print("c=%d" % c) b = 200 test() c = 300 # 有问题 ''' a=100 Traceback (most recent call last): b=200 File "C:/File/2-workspace/python/python-base/com/day07/demo04_global_attention.py", line 15, in <module> test() File "C:/File/2-workspace/python/python-base/com/day07/demo04_global_attention.py", line 10, in test print("c=%d" % c) NameError: name 'c' is not defined '''
false
e99ba66f99a5ca461eb42a8b3ae25d4edcd825f2
wangrui0/python-base
/com/day10/Demo13ClassPropertyObjectProperty.py
711
4.34375
4
""" 实现记录创建对象个数的功能 """ class Tool(object): def __init__(self, new_name): self.name = new_name # 底下这个方法太笨啦 num = 0 tool1 = Tool("铁锹") num += 1 print(num) tool2 = Tool("工兵铲") num += 1 print(num) tool3 = Tool("水桶") num += 1 print(num) """ 1 2 3 """ class Tool2(object): """ 实例属性为某个类所有,对象共有 """ # 类属性 num = 0 # 方法 def __init__(self, new_name): # 实例属性 self.name = new_name # 对类属性+=1 Tool2.num += 1 # 这个比较好 tool1 = Tool2("铁锹") tool2 = Tool2("工兵铲") tool3 = Tool2("水桶") print(Tool2.num) """ 3 """
false
457755022b554a1df8f956ee5cc93949c2a8a9b8
Xelanos/Intro
/ex2/quadratic_equation.py
1,994
4.15625
4
import math def quadratic_equation(a, b, c): """A function that returns the solution/s of an quadratic equation by using it's coefficients """ discriminant = math.pow(b, 2) - 4 * a * c # Discriminant variable if a == 0: first_solution = (-c) / b second_solution = None # no solutions elif discriminant < 0: first_solution = None second_solution = None # one solution elif discriminant == 0: first_solution = ((-b) + math.sqrt(discriminant)) / 2 * a second_solution = None # two solutions elif discriminant > 0: first_solution = ((-b) + math.sqrt(discriminant)) / 2 * a second_solution = ((-b) - math.sqrt(discriminant)) / 2 * a return first_solution, second_solution def numbers_extract(user_string): """A function that takes a string in the from of 'NUMBER-space-NUMBER-space-NUMBER' and returns those numbers in float """ spilt_string = user_string.split() # extracting the numbers spilt_a = float(spilt_string[0]) spilt_b = float(spilt_string[1]) spilt_c = float(spilt_string[2]) return spilt_a, spilt_b, spilt_c def quadratic_equation_user_input(): """A function that lets user input coefficients for a quadratic equation and prints the solution/s of said equation """ math_string = input("Insert coefficients a, b, and c: ") user_a, user_b, user_c = numbers_extract(math_string) # getting the results solution_1, solution_2 = quadratic_equation(user_a, user_b, user_c) # print the results # # no solutions if solution_1 is None and solution_2 is None: print('The equation has no solutions') # one solution elif solution_1 is not None and solution_2 is None: print('The equation has 1 solution: ' + str(solution_1)) # two solutions else: print('The equation has 2 solutions: ' + str(solution_1) + ' and ' + str(solution_2))
true
2bb86c4c828cc8fcd05f02c2f7bab3e209897721
lucasjacintho/pyCamp
/Projetos/Session-05/18_calculadora_simples.py
1,110
4.1875
4
""" Problem: Faça um programa que mostre ao usuario um menu com 4 opções de operações matematicas (as basicas, por exemplo). O usuario escolhe uma das opções e o seu programa então pede dois valores numericos e realiza a operação, mostrando o resultado e saindo Author: João Lucas Pycamp """ print('======= Calculadora Simples =======') print("=============================================\n") print("======= Escolha um dos Itens abaixo ======= \n") print("1 - Soma") print("2 - Multiplicação") print("3 - Divisão") print("4 - Subtração") print("=============================================") menu = int(input()) if menu > 0 and menu < 5: num_um = float(input("Digite um primeiro numero \n")) num_dois = float(input("Digite um segundo numero \n")) res = 0 if menu == 1: res = num_um + num_dois pass elif menu == 2: res = num_um * num_dois pass elif menu == 3: res = num_um / num_dois pass elif menu == 4: res = num_um - num_dois pass print("Resultado: ", res)
false
eb5d0bc7c7d56a93e2c6b618292e32cd4cdf24fb
sdotpeng/Python_Jan_Plan
/Jan_26/Image.py
1,880
4.40625
4
# Images # For the next weeks, we'll focus on an important area of computer science called image processing ''' What is an image? ''' ''' You are probably accustomed to working with .jpg, .gif, .png, and other types of image on your computer ''' ''' How do computers store the data that make up an image? It's represented as a 2D regular grid of pixel values ''' ''' We'll say that there are x columns and y rows ''' ''' Recall that Python 'counts' starting at 0 and goes to n-1. So the pixel numbering in the grid go from (0,0) on the top-left corner to (X-1, Y-1) on the bottom right corner, where again X is the image width in pixels and Y is the image height in pixels (X columns = width, Y rows = height). This seemingly strangle coordinate system is common to images and computer graphics ''' ''' In the case of grayscale images, computer just stores a single intensity value at each pixel ... you can think of the value as an integer ranging from 0 for black and 255 for white. We'll often be working with color images, which store the color at each position of the 2D image grid a (R, G, B) triplet, which specifies the amount of red, green, and blue color. So the dimensions of a color image are (X, Y, 3). The values for each RGB value would also be 0 to 255 inclusive. For example, (0, 255, 0) for a green colored pixel. ''' ''' What would be a white pixel value? (255, 255, 255) ''' ''' What would be a black pixel value? (0, 0, 0) ''' # Grayscale image image = [ [1,2,3], [4,5,6], [7,8,9] ] ''' The PPM format ''' ''' Zelle's Graphics module provides a convenient way for us to work this complex type of data. It assumes your image is in the format you may never have heard of called .ppm. There are instructions followed for your project. ''' ''' Images in Zelle Graphics ''' # 1. Make and show an image using Image object in the module
true
b6019fafc668be24a49ec0580281f4cf43284e05
sdotpeng/Python_Jan_Plan
/Jan_19/shallow_copy.py
657
4.46875
4
my_list = [1,2,3,4,5] # Shallow Copy # my_list2 = my_list # print("my_list:", my_list) # print("my_list2:", my_list2) # my_list2[2] = 99 # print("Assigning 99...") # print("my_list:", my_list) # print("my_list2:", my_list2) # # Deep copy # my_list2 = my_list.copy() # print("my_list:", my_list) # print("my_list2:", my_list2) # my_list[2] = 99 # print("Assigning 99...") # print("my_list:", my_list) # print("my_list2:", my_list2) # Slicing can also make deep copy of list my_list2 = my_list[:] print("my_list:", my_list) print("my_list2:", my_list2) my_list[2] = 99 print("Assigning 99...") print("my_list:", my_list) print("my_list2:", my_list2)
false
1514457b8e3f3d13e3202c1201bb3e7fcd47ff73
sdotpeng/Python_Jan_Plan
/Jan_14/loops.py
1,046
4.25
4
# Why do we need loops? # Because it saves time for a repeated task # for <loop index> in range(<number of loop iterations>): # <loop body> # range(number) returns an iterator # for i in range(10): # print(i) # for element in [1,3,5]: # print(element) import turtle window = turtle.Screen() t = turtle.Turtle() input('Press return to start...') t.speed(1) t.forward(300) t.left(90) t.speed(5) t.forward(300) t.left(90) t.speed(10) t.forward(300) t.left(90) t.speed(0) t.forward(300) for i in range(4): t.forward(300) t.left(90) t.up() t.setposition(-300,-300) t.down() for speed in [1,5,10,0]: t.speed(speed) t.forward(300) t.left(90) for i in range(5): t.forward(200) t.left(72) t.setposition(0, -300) t.speed(10) for num_side in range(4, 100): for i in range(num_side): t.forward(100) angle = (num_side - 2) * 180 / num_side t.left(180 - angle) for i in range(500): t.forward(2) angle = (500 - 2) * 180 / 500 t.left(180 - angle) window.exitonclick()
false
0efcdc8af2d92a5e90dd8cd093bfd1e073904ea2
sdotpeng/Python_Jan_Plan
/LI_CS151Project1/Project01/extension2.py
298
4.15625
4
'''Draw an n-gon''' import turtle window = turtle.Screen() t = turtle.Turtle() def n_gon(side_length, num_side): angle = 360 / num_side for i in range(num_side): t.forward(side_length) t.right(angle) n_gon(60, 18) n_gon(30,5) n_gon(40,12) n_gon(20,6) window.exitonclick()
false
99c10717fb45b38ed64a5b91c294c5996eccd2e4
kobaltkween/python2
/Lesson 03 - Test Driven Development/testadder.py
997
4.40625
4
""" Demonstrates the fundamentals of unittest. adder() is a function that lets you 'add' integers, strings, and lists. """ from adder import adder # keep the tested code separate from the tests import unittest class TestAdder(unittest.TestCase): def testNumbers(self): self.assertEqual(adder(3,4), 7, "3 + 4 should be 7") def testStrings(self): self.assertEqual(adder('x', 'y'), 'xy', "'x' + 'y' should be 'xy'") def testLists(self): self.assertEqual(adder([1,2], [3,4]), [1,2,3,4], "[1,2] + [3,4] should be [1,2,3,4]") def testNumberNString(self): self.assertEqual(adder(1, 'two'), '1two', "1 + 'two' should be '1two'") def testNumberNList(self): self.assertEqual(adder(4, [1, 2, 3]), [1, 2, 3, 4], "4 + [1, 2, 3] should be [1, 2, 3, 4]") def testStringNList(self): self.assertEqual(adder('x', [1, 2, 3]), [1, 2, 3, 'x'], "'x' + [1, 2, 3] should be [1, 2, 3, 'x']") if __name__ == "__main__": unittest.main()
true
37f3b9a8889fb1715439edb85a72eac1b72fd147
steveflys/data-structures-and-algorithms
/sorting_algos/selection.py
536
4.125
4
"""Do a selection sort of a list of elements.""" def selection_sort(my_list): """Define the selection sort algorithm.""" if len(my_list) < 2: return my_list for index in range(0, len(my_list)-1, +1): index_of_min = index for location in range(index, len(my_list)): if my_list[location] < my_list[index_of_min]: index_of_min = location temp = my_list[index] my_list[index] = my_list[index_of_min] my_list[index_of_min] = temp return my_list
true
2e56375e2bb4412f5634fe64f7051fc76ef54d99
steveflys/data-structures-and-algorithms
/sorting_algos/radix_sort.py
953
4.21875
4
"""Write a function that accepts an array of positive integers, and returns an array sorted by a radix sort algorithm.""" def radix_sort(my_list): """Define a radix sort.""" if len(my_list) < 2: return my_list RADIX = 10 maxLength = False tmp = -1 placement = 1 while not maxLength: maxLength = True """declare and initialize buckets""" buckets = [list() for _ in range(RADIX)] """split my_list between lists""" for i in my_list: tmp = i / placement buckets[int(tmp % RADIX)].append(i) if maxLength and tmp > 0: maxLength = False """empty lists into my_list array""" a = 0 for b in range(RADIX): buck = buckets[b] for i in buck: my_list[a] = i a += 1 """move to next digit""" placement *= RADIX return my_list
true
bfcb1b39c27515ff0baeba72e18d72d092fc2aeb
viserati/obey
/ch1text.py
1,769
4.375
4
# Sample text to be analyzed. text = """The first thing that stands between you and writing your first, real, piece of code, is learning the skill of breaking problems down into acheivable little actions that a computer can do for you. Of course, you and the computer will also need to be speaking a common language, but we'll get to that topic in just a bit. Now breaking problems down into a number of steps may sound a new skill, but its actually something you do every day. Let’s look at an example, a simple one: say you wanted to break the activity of fishing down into a simple set of instructions that you could hand to a robot, who would do your fishing for you. Here’s our first attempt to do that, check it out: You can think of these statements as a nice recipe for fishing. Like any recipe, this one provides a set of steps, that when followed in order, will produce some result or outcome in our case, hopefully, catching some fish. Notice that most steps consists of simple instruction, like "cast line into pond", or "pull in the fish." But also notice that other instructions are a bit different because they depend on a condition, like “is the bobber above or below water?". Instructions might also direct the flow of the recipe, like "if you haven’t finished fishing, then cycle back to the beginning and put another worm on the hook." Or, how about a condition for stopping, as in “if you’re done” then go home. You’re going to find these simple statements or instructions are the first key to coding, in fact every App or software program you’ve ever used has been nothing more than a (sometimes large) set of simple instructions to the computer that tell it what to do.""" # print(text) - Moved this to the analyze.py file
true
96abaf71b418165023b18d20d62656b8d86b3237
Elvistor/ejerciciosPy
/listas_tuplas/Ejercicio_6.py
935
4.34375
4
"""Escribir un programa que almacene las asignaturas de un curso (por ejemplo Matemáticas, Física, Química, Historia y Lengua) en una lista, pregunte al usuario la nota que ha sacado en cada asignatura y elimine de la lista las asignaturas aprobadas. Al final el programa debe mostrar por pantalla las asignaturas que el usuario tiene que repetir.""" materias = [] eliminar = [] while input("Desea agregar una materia? (s/n): ") == "s": materias.append(input("Ingrese el nombre de la materia: ")) else: #Recorre la lista materias y pregunta la nota. #Si es mayor o igual a 7 agrega a la lista eliminar. for materia in materias: if int(input(f"Qué nota obruvo en {materia}?: ")) >= 7: eliminar.append(materia) #Recorre la lista eliminar, y remueve el elemento de la lista de materias. for materia in eliminar: materias.remove(materia) print(f"Las materias desaprobadas son: {materias}")
false
8a8363ac9d3829f15629afa31c409c916ea31c9e
Elvistor/ejerciciosPy
/condicionales/Ejercicio_1.py
237
4.125
4
#Escribir un programa que pregunte al usuario su edad y muestre por pantalla si es mayor de edad o no. edad = int(input("Ingrese su edad: ")) if edad >= 18: print("Usted es mayor de edad.") else: print("Usted es menor de edad.")
false
3520e85161da8905a37384c79a917d6150be0ba2
Elvistor/ejerciciosPy
/string/Ejercicio_7.py
465
4.125
4
"""Escribir un programa que pregunte el correo electrónico del usuario en la consola y muestre por pantalla otro correo electrónico con el mismo nombre (la parte delante de la arroba @) pero con dominio ceu.es""" mail = input("Ingrese su mail: ") if "@" in mail: for letra in range(len(mail)): if mail[letra] == "@": nuevo_mail = mail[:letra] + "@ceu.es" print(nuevo_mail) break else: print("No es un mail")
false
57580c8a588560f4dab0389789e4efdfd1dfd21b
Elvistor/ejerciciosPy
/listas_tuplas/Ejercicio_8.py
261
4.25
4
"""Escribir un programa que pida al usuario una palabra y muestre por pantalla si es un palíndromo.""" palabra = input("Ingrese una palagra: ") if palabra.lower() == palabra[::-1].lower(): print("Es un palíndromo") else: print("No es un palíndromo")
false
443c2c70bda52833f40ab1b99c827304ec649803
Elvistor/ejerciciosPy
/listas_tuplas/Ejercicio_1.py
329
4.3125
4
"""Escribir un programa que almacene las asignaturas de un curso (por ejemplo Matemáticas, Física, Química, Historia y Lengua) en una lista y la muestre por pantalla""" materias = [] while input("Desea agregar una materia?: ") == "s": materias.append(input("Ingrese el nombre de la materia: ")) else: print(materias)
false
aeb6a963512560aef34639f66ce7928a100359f1
Elvistor/ejerciciosPy
/listas_tuplas/Ejercicio_11.py
287
4.15625
4
"""Escribir un programa que almacene los vectores (1,2,3) y (-1,0,2) en dos listas y muestre por pantalla su producto escalar.""" x = (1,2,3) y = (-1,0,2) prod_escalar = 0 for a in range(len(x)): prod_escalar += x[a] * y[a] print(f"El producto escalar de x e y es: {prod_escalar}")
false
02a0eb26186f1e94a1d9c58f2ba3fa2cfa72ddfa
mayrazan/exercicios-python-unoesc
/comparação/8.py
465
4.1875
4
produto1 = float(input("Qual o valor do produto 1 em R$? ")) produto2 = float(input("Qual o valor do produto 2 em R$? ")) produto3 = float(input("Qual o valor do produto 3 em R$? ")) if produto1 < produto2 and produto1 < produto3: print("Você deve comprar o produto 1") elif produto2 < produto1 and produto2 < produto3: print("Você deve comprar o produto 2") elif produto3 < produto1 and produto3 < produto2: print("Você deve comprar o produto 3")
false
9e3101c4372ea5a241840ee7415bae874614e0be
shekhar316/Cyber-Security_Assignments_CSE_3rdSem
/Assignment_02/Solution_06.py
337
4.15625
4
#string is palindrome or not def isPalindrome(string): i = 0 j = len(string) - 1 flag = 0 while j >= i: if not string[i] == string[j]: flag = 1 i += 1 j -= 1 if (flag == 1): print("String is not palindrome.") else: print("String is Palindrome.") st = input("Enter the string : ") isPalindrome(st)
true
d405d71afd926403cc81f83f5279086202b9d7b9
jonlorusso/projecteuler
/problem00007.py
800
4.1875
4
#!/usr/bin/env # 10001st prime # Problem 7 # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # What is the 10 001st prime number? import math from itertools import islice def isprime(n): if n == 1: return False for i in xrange(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True def naturalnumbers(): x = 0 while True: x += 1 yield x def primenumbers(): for x in naturalnumbers(): if isprime(x): yield x # from itertools recipes def nth(iterable, n, default=None): "Returns the nth item or a default value" return next(islice(iterable, n, None), default) nth_prime=lambda n: nth(primenumbers(), n) n=10001 print(nth_prime(n))
true
b1b741e7757f261aaf6376e14d3b14d82743db38
jonlorusso/projecteuler
/problem00019.py
2,083
4.21875
4
#!/usr/bin/env python # Counting Sundays # Problem 19 # You are given the following information, but you may prefer to do some research for yourself. # 1 Jan 1900 was a Monday. # Thirty days has September, # April, June and November. # All the rest have thirty-one, # Saving February alone, # Which has twenty-eight, rain or shine. # And on leap years, twenty-nine. # A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. # How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? def isleap(year): if year % 4 == 0: if year % 100 == 0 and year % 400 != 0: return False return True return False def thirtyone(year): return 31 def thirty(year): return 30 def february(year): return 29 if isleap(year) else 28 class Date: def __init__(self, day, month, year, day_of_week): self.day = day self.month = month self.year = year self.day_of_week = day_of_week days_of_week = { 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', 7: 'Sunday' } month_lengths = { 1: thirtyone, 2: february, 3: thirtyone, 4: thirty, 5: thirtyone, 6: thirty, 7: thirtyone, 8: thirtyone, 9: thirty, 10: thirtyone, 11: thirty, 12: thirtyone } def issunday(date): return True def days(start_date): d = start_date while True: yield d d.day += 1 if d.day_of_week == 7: d.day_of_week = 1 else: d.day_of_week += 1 if d.day > month_lengths[d.month](d.year): d.day = 1 if d.month == 12: d.month = 1 d.year += 1 else: d.month += 1 start_date = Date(1, 1, 1900, 1) sundays = 0 for d in days(start_date): if d.year > 2000: break if d.year > 1900: if d.day == 1 and d.day_of_week == 7: sundays += 1 print(sundays)
false
803e02d25fc177746dbca3ceba2b9ce9c9451788
joao04joao/teste_das_aulas
/Aula01.py
555
4.125
4
# print('Olá, estou aprendendo Python!') # FAÇA UM PROGRAMA QUE LEIA UM NOME E IMPRIMA: O SEU NOME É FULANO DE TAL nome = input('Informe o nome:') print('O seu nome é:', nome) # FAÇA UM PROGRAMA QUE LEIA UM NÚMERO E IMPRIMA A FRASE: O NÚMERO INFORMADO É TAL num = input('Informe o número: ') print('O número informado foi ', num) #FAÇA UM PROGRAMA QUE PEÇA DOIS NÚMEROS E IMPRIMA A SOMA. num1 = int(input('Informe o primeiro número')) num2 = int(input('Informe o segundo número')) soma = num1 + num2 print('O resultado é:',soma)
false
24f8941fca82fcc36e85574a14708e38dce6033e
lolNickFox/pythonWorkshop
/demo.py
2,934
4.21875
4
# coding: utf-8 # Live Demo # --------- # # Let's implement a function that returns the $n$th element of a certain series. # # The first two elements of the series are given: # # $$F_0 = 1, F_1 = 1$$ # # The function returns $F_n$ such that: # # $$F_n = F_{n - 2} + F_{n - 1}$$ # In[13]: def fibonacci(n): if 0 <= n <= 1: return 1 else: return fibonacci(n - 2) + fibonacci(n - 1) # check print fibonacci(0), fibonacci(1), fibonacci(2) # check again print for n in range(10): print n, fibonacci(n) # plotting get_ipython().magic(u'matplotlib inline') x = range(10) y = [fibonacci(n) for n in x] import matplotlib.pyplot as plt plt.scatter(x, y) # NumPy # ----- # # NumPy provides the _ndarray_ object, which implements an efficient homogeneous multi-dimensional array type. # In[14]: import numpy as np A = np.arange(6.).reshape(3, 2) B = np.array([1, 0]) # element-wise C = A * B # matarix multiplication D = np.dot(A, B) # See how fast it finds the maximum among a 1 million cells. # In[15]: np.random.seed(1234) print "numpy.ndarray" M = np.random.rand(1000, 1000) get_ipython().magic(u'time M.max()') print "\nlist" M2 = [M[i,j] for i in xrange(1000) for j in xrange(1000)] get_ipython().magic(u'time max(M2)') # NumPy has many built-in functions, for instance, Singular Value Decomposition can be as simple as: # In[16]: a = np.random.randn(9, 6) U, s, V = np.linalg.svd(a) print U.shape, s.shape, V.shape # check S = np.zeros((9, 6)) S[:6, :6] = np.diag(s) aa = np.dot(U, np.dot(S, V)) np.allclose(a, aa) # SciPy libraries # --------------- # # An example from scipy.optimize module. Minimizing the Rosenbrock function of N variables: # # $$f(\mathbf{x}) = \sum_{i=1}^{N-1} {100 (x_i - x_{i-1}^{2})^2 + (1 - x_{i-1})^2}.$$ # # The minimum value of this function is 0 which is achived when $x_i = 1$. # In[17]: import numpy as np from scipy.optimize import minimize def rosen(x): return sum(100.0*(x[1:] - (x[:-1])**2.0)**2.0 + (1-x[:-1])**2.0) # using simplex method x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2]) res = minimize(rosen, x0, method='nelder-mead', options={'xtol':1e-8, 'disp': True}) print res.x # R interface # ----------- # # From http://tinyurl.com/mf5m5ey. Requires R and rpy2 python module being already installed. (Rmagic is now a part of rpy2.) # In[18]: get_ipython().magic(u'matplotlib inline') get_ipython().magic(u'load_ext rpy2.ipython') import matplotlib.pyplot as plt X = np.array(xrange(5)) Y = np.array([3, 5, 4, 6, 7]) plt.scatter(X, Y) # In[19]: get_ipython().magic(u'Rpush X Y') get_ipython().magic(u'R lm(Y ~ X)$coef') # In[20]: # check the coef's in python Xr = X - X.mean() Yr = Y - Y.mean() slope = (Xr * Yr).sum() / (Xr**2).sum() intercept = Y.mean() - X.mean() * slope print "{0:.1f}, {1:.1f}".format(intercept, slope) # In[21]: a = get_ipython().magic(u'R resid(lm(Y ~ X))') print a
true
ab78a3d3e88d09367b3783bdf66de31dbcfed698
psm18/16ECA_parksunmyeong
/lab 01 intro/08_streamplot_demo_features.py
1,086
4.21875
4
# -*- coding: utf8 -*- """ Demo of the 'streamplor' function. A streamplot, or streamline plot, is used to display 2D vector fields, This example shows a few features of the stream plot function: *Varying the color along a streamline. *Varying the desity of streamlines. *Varying the line width along a stream line: """ #"images_contours_and_gields example code: streamplot_demo_features.py" images_contours_and_fields example code: #streamplot_demo_features.py - Matplotlib 1.5.1 documentation. [Online]. Avilable: #http://matplotlib.org/examples/images_contours_and_fields/streamplot_demo_features.html. [Accessed: 21-Aug-2016]. import numpy as np import matplotlib.pyplot as plt Y, X = np.mgrid[-3:3:100j, -3:3:100j] U = -1 -X **2 + Y V = 1 + X -Y ** 2 speed = np.sqrt(U * U + V * V) plt.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn) plt.colorbar() f, (ax1, ax2) = plt.subplots(ncols=2) ax1.streamplot(X, Y, U, V, density=[0.5, 1]) lw = 5 * speed / speed.max() ax2.streamplot(X, Y, U, V, density=0.6, color= 'k', linewidth=lw) plt.show()
true
d2ce0f86bc7aee4e348337ff2414e04696b1947e
tolik0/Lab_3
/point.py
417
4.125
4
class Point: """ Class that represent point """ def __init__(self, x=0, y=0): """ (Point, float, float) -> NoneType Create new point """ self.x = x self.y = y def distance(self, p): """ (Point, Point) -> float Return distance between two points """ return ((self.x - p.x) ** 2 + (self.y - p.y) ** 2) ** 0.5
false
032ec8b52b6a31902a63d98f1caba75830101d42
riturajkush/Geeks-for-geeks-DSA-in-python
/hashing/Sorting Elements of an Array by Frequency.py
1,388
4.125
4
#User function Template for python3 ''' Your task is to sort the elements according to the frequency of their occurence in the given array. Function Arguments: array a with size n. Return Type:none, print the sorted array ''' def values(dic): return dic.values def sortByFreq(arr,n): dic = dict() for i in arr: if(i not in dic): dic[i] = 1 else: dic[i] += 1 val = max(dic) #print(dic) #print(a) a = sorted(dic.values(), reverse=True) #print(a) for j in a: for i in sorted(dic.keys()): if(j==dic.get(i)): for k in range(j): print(i,end=" ") dic[i] = 0 break print() #{ # Driver Code Starts #Initial Template for Python 3 import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) if __name__ == '__main__': t = int(input()) for tt in range(t): n=int(input()) a = list(map(int, input().strip().split())) sortByFreq(a,n) # } Driver Code Ends
true
70475137935f83421aaea43af6b5607ac606837c
www-wy-com/StudyPy01
/180202_input_output.py
1,233
4.21875
4
# -*- coding: utf-8 -*- import pickle # 用户输入内容 def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) something = input('enter text: ') if is_palindrome(something): print('yes, this is palindrome') else: print('no, this is not a palindrome') # 再议input birth=input('brith:') if int(birth)<2000: print('00前') else: print('00后') # 文件 poem =''' Programming is fun When the work is done if you wanna make your work also fun: use Python! ''' # 打开模式,有 # -'r' 阅读模式 # -'w' 写入模式 # -'t' 文本模式 # -'b' 二进制模式 f=open('poem.txt','w') f.write(poem) f.close() f=open('poem.txt') while True: line=f.readline() # 当空字符串返回时,说明到达到了文件末尾 if len(line) == 0: break print(line,end='') f.close() # pickle shoplistfile = 'shoplist.dara' shoplist = ['apple', 'mango', 'carrot'] f = open(shoplistfile, 'wb') # Dump the object to a file pickle.dump(shoplist, f) f.close() # Destroy the shoplist variable del shoplist # Read back from the storage f = open(shoplistfile, 'rb') # Load the object from the file storedlist = pickle.load(f) print(storedlist)
true
a96ffed047aae4ae9c795c20b13af35f168a9030
bhargavraju/practice-py2
/hashing/copy_list.py
1,248
4.125
4
""" A linked list is given such that each node contains an additional random pointer which could point to any node in the list or NULL. Return a deep copy of the list. Example Given list 1 -> 2 -> 3 with random pointers going from 1 -> 3 2 -> 1 3 -> 1 You should return a deep copy of the list. The returned answer should not contain the same node as the original list, but a copy of them. The pointers in the returned list should not link to any node in the original input list. """ class RandomListNode: def __init__(self, x): self.label = x self.next = None self.random = None # @param head, a RandomListNode # @return a RandomListNode def copyRandomList(head): parser = head dummy = copy_parser = RandomListNode(0) node_map = {} while parser: copy_node = RandomListNode(parser.label) copy_parser.next = copy_node node_map[parser] = copy_node parser = parser.next copy_parser = copy_parser.next copy_parser.next = None random_parser = dummy.next while random_parser: random_parser.random = node_map[head.random] if head.random else None head = head.next random_parser = random_parser.next return dummy.next
true
6c605d2e08388d3b94983568b1fd925184e23e55
bhargavraju/practice-py2
/arrays/insert_interval.py
1,252
4.15625
4
""" Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9] insert and merge [2,5] would result in [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] would result in [1,2],[3,10],[12,16]. This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. Make sure the returned intervals are also sorted. """ # Definition for an interval. class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e # @param intervals, a list of Intervals # @param new_interval, a Interval # @return a list of Interval def insert(intervals, new_interval): left = right = 0 start = new_interval.start end = new_interval.end while right < len(intervals): if start <= intervals[right].end: if end < intervals[right].start: break start = min(start, intervals[right].start) end = max(end, intervals[right].end) else: left += 1 right += 1 return intervals[:left] + [Interval(start, end)] + intervals[right:]
true
6285c75c7972f537d3a73ad89d2d938ee086be44
zhgmyron/python_ask
/hellworld.py
441
4.15625
4
names=['mama','mike','jim'] def list_all(names): print("--------") for i in names: print (i) list_all(names) absent=names.pop(1) print(absent+"can't present the party") names.append('mao') list_all(names) names.insert(0,'ba') names.insert(2,'di') names.append("chou") list_all(names) a=names.pop() print(a) print ("--------------") print (names) b=len(names) for i in range(b-3): print (i) del names[i] print (names)
true
660fcf161264ed8b3315707172eabd77b1fd125e
JorJeG/python
/9/icecreamstand.py
902
4.125
4
class Restaurant(object): """Simple restaurant class""" def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): print(self.restaurant_name) print(self.cuisine_type) def open_restaurant(self): print("Restaurant is open.") def set_number_served(self, number): self.number_served = number def increment_number_served(self, number): self.number_served += number class IceCreamStand(Restaurant): def __init__(self, restaurant_name, cuisine_type): super(IceCreamStand, self).__init__(restaurant_name, cuisine_type) self.flavors = ['chocolate', 'vanilla', 'strawberry'] my_icecreamstand = IceCreamStand('your ice cream', 'ice cream stand') print(my_icecreamstand.flavors)
false
7effc9859d4c01502a739f97055913f0312a61ca
kk0174lll/codewars
/Infix to Postfix Converter/main.py
1,413
4.15625
4
''' Construct a function that, when given a string containing an expression in infix notation, will return an identical expression in postfix notation. The operators used will be +, -, *, /, and ^ with standard precedence rules and left-associativity of all operators but ^. The operands will be single-digit integers between 0 and 9, inclusive. Parentheses may be included in the input, and are guaranteed to be in correct pairs. ''' def toPostfix(expr): result = '' stack = [] for c in expr: if c.isdigit(): result = result + c elif c == "(": stack.append(c) elif c == ")": result = processClosingBracket(result, stack) else: result = process(c, result, stack) while len(stack) != 0: result = result + stack.pop() return result def processClosingBracket(result, stack): flag = True while(flag): symbol = stack.pop() if symbol != "(": result = result + symbol else: flag = False return result def process(c, result, stack): precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3, '(': 0} flag = True while(flag and len(stack) > 0): operation = stack[len(stack)-1] if precedence[operation] >= precedence[c]: result = result + stack.pop() else: flag = False stack.append(c) return result def main(): print(toPostfix("(5-4-1)+9/5/2-7/1/7")) main()
true
4d738768501ceef38bda1496afefc3849cddc557
OlegZhdanoff/algorithm
/lesson_2/task_3.py
561
4.1875
4
# 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если # введено число 3486, надо вывести 6843. def reverse(num): if num // 10: tmp = num exp = 0 while tmp > 9: tmp //= 10 exp += 1 return (num % 10) * (10 ** exp) + reverse(num // 10) return num num = int(input('Введите целое число')) print(reverse(num))
false
bad8984b8b21df30f8cd186a4efad8ee4e5b8b14
Ntalemarvin/python
/list.py
398
4.3125
4
#LISTS names = ['john','isaac','Marvin','frost','Mary','Benj'] print(names[4]) print(names[2:3]) print(names[:]) names[3]='frosts' print(names) #write a program to find the largest number in a list numbers = [2,3,5,6,17,69,7,9,10,69,200,453,23,45] '''lets assume the largest number is numbers[0]''' max = numbers[0] for number in numbers: if number > max: max = number print(max)
true
c112260af77340ed69565e507527486656cb43da
kidusasfaw/addiscoder_2016
/labs/server_files_without_solutions/lab9/trionacci2/trionacci2_solution.py
337
4.125
4
import sys # the input to this function is an integer n. The output is the nth trionacci number. def trionacci(n): # student should implement this function ########################################### # INPUT OUTPUT CODE. DO NOT EDIT CODE BELOW. n = int(sys.stdin.readline()) ans = trionacci(n) sys.stdout.write(str(ans)) print ''
true
769173e701119ce1a7d0f12f310eed2c4adfc291
Ttibsi/AutomateTheBoringStuff
/Ch.07 - Pattern Matching with Regular Expressions/FindPhoneNumberDividedIntoGroups.py
649
4.15625
4
# More Pattern Matching with Regular Expressions import re phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') phoneNumRegexWithBrackets = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') mo = phoneNumRegexWithBrackets.search('my number is (415) 555-4242') #This gets the parenthesis sections of the regex, with item 0 returning everything print(mo.group(1)) print(mo.group(2)) print(mo.group(0)) #get all the groups printed out with a visible division between them print(mo.groups()) # In Regex, the following symbols all have special meaning: # . ^ $ * + ? { } [ ] \ | ( ) # To use one, it needs to be "escaped" with a backslash before it
true
e7f360ad026af0dab1c535b40445a55154c2da00
katiaOlem/poo-1719110962
/semana_codigos/manejo.py
2,860
4.21875
4
import math #Ayuda con las funciones matemáticas lista_numeros=[]#Contador de los números class NumerosError ():#Clase def __init__(self): #Metodo Constructor pass def numeros_evaluar(self): #Metodo try:#Declaracion de Try para identificar errores numeros=int(input(" Ingrese el total de numeros que desea evaluar = ")) #Variable del # de numeros que deseamos evaluar y realizar las siguientes operaciones. for i in range (numeros):#EL rango de los numeros numero=int(input("Ingrese el numero que desea evaluar = ")) #Variable que nos permite Ingresar los numeros a evaluar lista_numeros.append (numero) #Reemplazaremos los numeros en el contador de la lista_numeros except Exception as error: # Except captura el error print("!!! ERROR !!!",error.args) def Indice_numeros(self): #Metodo del indice r="s" or "S" #Respuesta S OR s try: #Declaracion de Try para identificar errores while r == "s" or r == "S": #Si la respuesta es S OR s el programa realizara Lo siguiente indice=int(input(" Introduza un índice = "))#Variable que nos permite Ingresar el # del Indice que deseamos Imprimir con las operaciones qu estan a continuacion seletion=lista_numeros[indice]#Variable que seleccionara el Indice de los numeros agregados para evaluar print(seletion) #Imprimira el valor seleccionado raiz_cuadrada=math.sqrt(seletion)#Math sqrt nos permite sacar la raiz del numero seleccionado print("Su Raiz Cuadrada es= "+ str (raiz_cuadrada)) #imprime la raiz cuadrada del numero seleccionado cubo=(seletion * seletion * seletion) #El numero seleccionado se elebara al cubo print("Elevado al cubo es= "+ str (cubo))#imprime el resultado elevado al cubo if seletion == 0:# Si el numero es = a 0 el numero es par print ("Este número es par= ") #Imprime el mensaje elif seletion%2 == 0: #si el numero es divisible hasta o es numero par print ("El numero es par") #Imprime else: print ("El numero es impar ") # Si no es impar r=input(" ¿Desea realizar otro calculo? s/n ") #Varible de respuesta para saber si regresa al ciclo o termina el prgrama if r=="n" or r=="N": #si la respuesta es N o n break #Finaliza except Exception as error: #Except captura el error print(" !! ERROR !!",error.args) #Imprime el error obj=NumerosError ()#Objeto de la Class obj.numeros_evaluar()#Objeto del Metodo de numeros_evaluar obj.Indice_numeros()#Objeto del Metodo de Indice_numeros
false
23970409685018fba3be8c38d9c2fa46a4dd3073
shriya246/Python-internship-Best-Enlist
/Day8.py
2,062
4.28125
4
dict1={"a":1,"b":2} dict2={"c":3,"d":4} dict3=(dict2.update(dict1)) print(dict2) #sorting and convert list into set list1 = [4,3,2,1] list2 =list1[::-1] set1 = set(list2) print(set1) #3) program to list number of items in a dictionary key names = {3:"a",2:"b",1:"c"} list3 = dict.keys(names) print("list of dictionary keys",list3) sorted_list3 = sorted(list3) print("sorting the list of dictionary keys", sorted_list3) #sorting list without using function names = {3:"a",2:"b",1:"c"} list4 = dict.keys(names) list3 = list(list4) print(list3) asscending_list = list3[::-1] print(asscending_list) #4) string1 = input("enter a string") string = string1[0:10] print(string) firstword = string[0:7] print(firstword) user_word = input("enter a word") final_string = string.replace(firstword,user_word) print(final_string) #5) name = input("enter a name") first_char = name[0] user_char = input("emter a char") finalname = name.replace(first_char,user_char) print(finalname) #6) repeated items of list numbers = [1,4,3,2,4,2] nums = [] for i in numbers: if i not in nums: nums.append(i) else: print(i,end=" ") #7) elements = [1,2,3] sum= 0 for i in elements: sum = sum+i print(sum) user_value = int(input("enter a number")) dividing_number = sum/user_value print(dividing_number) #8) given_numbers = [1,2,2] addition = 0 for i in given_numbers: addition = addition +i print("addition",addition) length = len(given_numbers) mean = addition/length print("mean :",mean) given_numbers.sort() if length%2==0: median1 = given_numbers[length//2] median2=given_numbers[length//2-1] median = (median1+median2)/2 else: median = given_numbers[length//2] print("median is:",median) import statistics mode1=statistics.mode(given_numbers) print("mode is :",mode1) #9) given_string = "India" update_string = given_string.swapcase() print(update_string) #10) given_int = 11 binary = bin(given_int) print(binary) octal = oct(given_int) print(octal)
true
57acdcb38d4b52d2878b2ee8ee795af745fcd506
alexguldemond/MA173A_Sample_Code
/python/data_structures/tuples.py
457
4.375
4
#!/usr/bin/python3 # Tuples are like lists, but they are immutable, i.e. cannot be changed tup = (1, 2, "Hello") # We can index them like lists print(tup[1]) # But we cannot change them # tup[0] = 3 # The above will error out # Tuples can also be easily unpacked. This can be useful for getting several values out at once (one, two, hello) = tup print(one) print(two) print(hello) #Tuples arecommonly used for returning multiple values from a function
true
786f227d47997cb4c425bbfb5a86dd5ea4d079bc
alexguldemond/MA173A_Sample_Code
/python/printing/formatted_printing.py
369
4.46875
4
#!/usr/bin/python3 # Sometimes you want to print data without worrying about building strings. # Formatted printing makes this convenient datum1 = 1.1 datum2 = 1.2 datum3 = 1.3 # Note the prefix f, and the use of curly braces inside the string print(f"Here is some data: {datum1}, {datum2}, {datum3}") # Should print the following: # Here is some data: 1.1, 1.2, 1.3
true
cdf12952bb23eb100f0087eeecb10d871abe0e5d
LuisMoranDev/Python-Projects
/Python Projects/Change.py
1,192
4.125
4
def changeBack(): cents = {"Quarters: ":.25, "Dimes: ":.10, "Nickels: ":0.05, "Pennies ": 0.01} while True: try: cost = float(input("Enter the cost of the item: ")) except ValueError: print("Cost must be an integer") else: if cost < 0: print("The cost of the item must be greater than 0") else: break while True: try: money_given = float(input("Enter the amount of money given ")) except ValueError: print("Money given to pay must be an integer") else: if money_given < cost: print("Money given must be equal to or more than cost of item ") elif money_given >= cost: break change = money_given - cost for cent in cents: if change / cents[cent] > 1: a = change / cents[cent] change = round(change % cents[cent],2) cents[cent] = int(a) else: cents[cent] = 0 cents[cent] = int(cents[cent]) print("Change back will be") for x, y in cents.items(): print(x, y) changeBack() # cents = {"Quarters: ":.25, "Dimes: ":.10, "Nickels: ":0.05, "Pennies ": 0.01} # for x, y in cents.items(): # print(x,y) # left = 1.40 / .25 # change = round(1.40 % .25, 2) # print(change) a = .30 b = .25 # print(round(a % b,2))
true
b5e8bbc2d21bbedb292067b7963fbcabe67138be
coryeleven/learn_python
/range.py
832
4.375
4
# -*- coding: utf-8 -*- # @Time : 2021/7/24 4:40 下午 # @File : range.py # @Description : # range() 指定步长,函数从2开始,每次加3,直至达到或不超过终值 #rang生成一个列表 even_numbers = list(range(2,20,3)) print(even_numbers) # ** 乘方运算 squares = [] for values in range(1,11): square = values**2 squares.append(square) #append 追加之列表元素的末尾 print(squares) print(max(squares)) print(min(squares)) print(sum(squares)) #列表解析将for循环和创建新元素的代码合并成一行 square1 = [i**2 for i in range(1,5)] print(square1) # 指定步长,函数从3开始,每次加N for i in range(1,20,2): print(i) print(list(range(3,30,2))) print(list(range(3,30,3))) print(list(range(3,30,4))) numbers = [i**3 for i in range(1,11)] print(numbers)
false
94c8188c7661f1a499d8f80378e1ae3d0722b8f4
coryeleven/learn_python
/input_while.py
2,875
4.1875
4
""" 1.input str、int,求模运算符 2.while 循环 3.break continue结束或跳出循环 """ #存储成一个变量提示信息 int ''' prompt = "If you tell us who are you , we can personalize the message you see." prompt += "\nWhat is your first name?\n" name = input(prompt) print(name) height = input("How tall are you, in inches? ") height = int(height) #int函数 print(height) if height >= 36: print("\nYou're tall enough to ride!") else: print("\nYou'll be able to ride when you're a little older!") ''' #求模运算符 # height = input("How tall are you, in inches? ") # height = int(height) #int函数 # if height % 2 == 0: # print("\nThe number " + str(height) + " is even.") # else: # print("\nThe number " + str(height) + " is add.") #7-1 # car = input("What kind of car would you like? ") # print("Let me see if I can find you a " + car.title() + ".") #7-2 # party_size = input("How many people are in your dinner party tonight? ") # party_size = int(party_size) # if party_size > 8: # print("I'm sorry, you'll have to wait for a table.") # else: # print("Your table is ready.") # print("...") #7-3 # number = input("Give me a number,please: ") # number = int(number) # if number %10 == 0 : # print(str(number) + "is a muitple of 10.") # else: # print(str(number) + " is not a multiple of 10.") # while 循环 current_number = 1 while current_number <= 5: print(current_number) current_number += 1 #while循环 让用户选择时退出 prompt = "\nTell me somthing,and I will repeat it back to you: " prompt += "\nEnter 'quit' to end the program. " # message = "" # while message != "quit": # message =input(prompt) # if message != "quit": # print(message) # active = True # while active: # message = input(prompt) # if message == "quit": # active = False # else: # print(message) #Break 推出循环 while True: city = input('prompt:') if city == "quit": break else: print("I'd love to go to " + city.title()) #使用continue current_number = 0 while current_number <= 10: current_number += 1 if current_number%2 == 0: print("模余运算:" + str(current_number)) continue print(current_number) # x = 1 # while x <= 5: # x += 1 # print("\n" + str(x)) #7-4 # while True: # topping = input(prompt) # if topping != "quit": # print(" I'll add " + topping + " to your pizza.") # else: # break #7-5 # prompt = "How old are you?" # prompt += "\nEnter 'quit' when you are finished. " # while True: # age = input(prompt) # if age == "quit": # break # age = int(age) # if age < 3 : # print(" You get in free!") # elif age < 13: # print(" Your ticket is $10.") # else: # print(" Your ticket is $15.")
true
8a45ef85f2d529e5abfee8b8c2b64b94bd87d202
micmor-m/Hangman
/main.py
1,028
4.125
4
import random from hangman_words import word_list from hangman_art import stages, logo end_of_game = False # word_list = ["aardvark", "baboon", "camel"] chosen_word = random.choice(word_list) lives = 6 print(logo) # print(f'The solution is {chosen_word}.') display = [] for ch in chosen_word: display.append("_") while not end_of_game: guess = input("Guess a letter: ").lower() if guess in display: print("You already guessed it.") i = 0 for ch in chosen_word: if ch == guess: display[i] = guess i += 1 if guess not in chosen_word: print(f"{guess} is not in the word") print(stages[lives]) lives -= 1 # Join all the elements in the list and turn it into a String. print(f"{' '.join(display)}") # Check if user has got all letters. if lives < 0: end_of_game = True print("You lose.") # Check if user has got all letters. if "_" not in display: end_of_game = True print("You win.")
true
018a792e66958a5d8683eb50b0062806417586d2
arcSlayer85/random_python_bits
/inchesToCms.py
876
4.71875
5
#! /usr/bin/python """ program that offers the user the choice of converting cm to inches or inches to centimetres. Use functions for each of the conversion programs. """ # Function for cm's to inches... def calculateCms ( int ): _cm = _height * 2.54; print (_cm); # function for inches to cm's... def calculateInches ( int ): _inches = _height / 2.54; print (_inches); # get the type of conversion the user wants to do... convType = int(input("Your height inches/centimeters(1) \nor centimeters/inches(2)?...")); # If they press 1, do this... if convType == 1: _height = int(input("Enter your height in inches...")); calculateCms(_height); # If they press 2, do this... else: if convType == 2: _height = int(input("Enter your height in centimeters...")); calculateInches(_height);
true
0c971beb8153ccefa16c9ce4cafd459718021198
DerianQM/algo_and_structures_python
/Lesson1/2.py
645
4.34375
4
# 2. Выполнить логические побитовые операции "И", "ИЛИ" и др. # над числами 5 и 6. Выполнить # над числом 5 побитовый сдвиг вправо и влево на два знака. a = 5 b = 6 print(f"{a} имеет вид в битах {bin(a)}\n {b} имеет вид в битах {bin(b)}") print(f"{a} И {b} = {a&b} в битах {bin(a&b)}") print(f"{a} ИЛИ {b} = {a|b} в битах {bin(a|b)}") print(f"Сдвиг {a} влево на 2 = {a<<2} в битах {bin(a<<2)}") print(f"Сдвиг {a} вправо на 2 = {a>>2} в битах {bin(a>>2)}")
false
8690cf0bf9a05db858172dd1e96b87e139e5eb6b
longchushui/How-to-think-like-a-computer-scientist
/exercise_0312.py
646
4.40625
4
#Write a program to draw a face of a clock that looks something like this: import turtle # get the turtle module # set up screen wn = turtle.Screen() wn.bgcolor("lightgreen") # set up turtle tess = turtle.Turtle() tess.color("blue") # make tess blue tess.shape("turtle") # now tess looks like a turtle tess.penup() # and tess takes her pen up # the for loop to make a clock for i in range(12): tess.forward(120) tess.pendown() tess.forward(15) tess.penup() tess.forward(15) tess.stamp() tess.backward(150) tess.left(360/12) wn.mainloop() # the user can close the window
true
f27a17b433ae7e6d8149eb9738d0859f4c016ceb
longchushui/How-to-think-like-a-computer-scientist
/exercise_0501.py
733
4.46875
4
# Assume the days of the week are numbered 0,1,2,3,4,5,6 from Sunday to Saturday. # Write a function which is given the day number, and it returns the day name (a string). def day_name(day_number): """ The function day_name() returns the day_name {Sunday-Saturday} given the day_number {0-6}. """ if day_number == 0: print("Sunday") elif day_number == 1: print("Monday") elif day_number == 2: print("Tuesday") elif day_number == 3: print("Wednesday") elif day_number == 4: print("Thursday") elif day_number == 5: print("Friday") elif day_number == 6: print("Saturday") else: print("Give a number between 0 and 6.")
true
c884357afb95680b5ffb0d2b4875305db8eefa9e
longchushui/How-to-think-like-a-computer-scientist
/exercise_0404.py
603
4.28125
4
import turtle def draw_poly(t, n, sz): """ The function draw_poly() makes a turtle t draw a regular polygon with n corners of size sz. """ for i in range(n): t.forward(sz) t.left(360/n) # set up screen wn = turtle.Screen() wn.bgcolor("lightgreen") # make the background green # set up turtle tess = turtle.Turtle() tess.color("blue") tess.width(3) # Make a pretty figure, consisting of 20 squares for i in range(20): draw_poly(tess, 4, 100) # draw a square tess.left(360/20) wn.mainloop() # wait for user to close window
true
7b5bec25ca82e213e87aea54d4db5ca6106b05c9
ctlnwtkns/itc_110
/abs_hw/ch7/regexStriptest.py
1,707
4.5
4
''' Write a function that takes a string and does the same thing as the strip() string method (remove whitespace characters, i.e. space, tab, newline). If no arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string. ''' import re def regexStrip(str): regexString = re.compile(r'\S.*\S', re.I|re.DOTALL) mo = regexString.search(str) print(mo.group()) str = ' hello world' regexStrip(str) ''' import re # An example string. v = "running eating reading" # Replace words starting with "r" and ending in "ing" # ... with a new string. v = re.sub(r"r.*?ing", "ring", v) print(v) Output ring eating ring import re def v(str, sub = None): if sub != None: regex = re.compile(sub) mo = regex.search(str) strip = re.sub(mo.group(),'', str) print(strip) else: regexString = re.compile(r'\S.*\S', re.I|re.DOTALL) mo = regexString.search(str) print(mo.group()) v(' hello world', 'orld') import re def v(str, sub = None): #compile whole string if sub != None: regex = re.compile(sub) #compile the string to be removed mo = regex.search(str) #create match object by searching for #remove 'orld' v1 = regex.sub('', mo.group(), 1) #replace mo with blank space print(v1) else: str = re.compile(r'\S.*\S', re.I|re.DOTALL) mo = str.search(v) print(mo.group()) v('hello world', 'orld') ''' ''' print'Type something: ' mnstr = raw_input()#.decode('string-escape') print'Type something else, or hit enter: ' substr = raw_input()#.decode('string-escape') v(mnstr, substr) ''' '''
true
72c0a270951ee86997d0cc30cccef052e29f4d31
affiong/switch_affiong
/hangman1.py
1,713
4.125
4
import random wordlist = "one two three four five six seven".upper().split() random.shuffle(wordlist) secret_word = wordlist.pop() correct = [] incorrect = [] #print("DEBUG: %s" % secret_word) def display_word(): #display random word for i in secret_word: if i in correct: print(i, end=" ") else: print("_", end=" ") print("\n\n") print("****MISSED LETTERS****") for i in incorrect: print(i, end=" ") print("\n*************************") def user_guess(): #allow user to take a guess. append that letter to correct or incorrect while True: guess = input("Guess a letter\n: ").upper() if guess in correct or guess in incorrect: print("you have already guessed that letter, Guess again.") elif guess.isnumeric(): print("please enter only letters not numbers. Guess again.") elif len(guess) > 1: print("please enter only one letter at a time. Guess again.") elif len(guess) == 0: print("please enter your selection.") else: break if guess in secret_word: correct.append(guess) else: incorrect.append(guess) def check_win(): #if the gamer win or loss if len(incorrect) > 5: return "loss" for i in secret_word: if i not in correct: return "no win" return "win" while True: display_word() user_guess() win_condition = check_win() if win_condition == "loss": print("GAME OVER!!! the word was ***%s***" % secret_word ) break elif win_condition == "win": print("YOU WIN!!! the word was ***%s***" % secret_word)
true
dcaa2fe4a88600d9d2aba51c8b56031c39a9b089
slickFix/Python_algos
/DS_ALGO/gcd.py
470
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 8 19:34:01 2019 @author: siddharth """ # Implementing Greatest Common Divisor def gcd(m,n): if (m<n): (m,n) = (n,m) if (m%n==0): return n else: return gcd(n,m%n) # gcd(m,n) = gcd(n,m%n) if __name__ == '__main__': m = int(input("enter 1st number: ")) n = int(input("enter 2nd number: ")) print("GCD of the numbers = "+ str(gcd(m,n)))
false
cf3229f2a98ca503348020f2e821d5f1dcabe1d3
pdefusco/Python
/app_development/lpth/ex24.py
797
4.34375
4
#putting concepts together: print("This is a variation of the original exercise") text = """Ma quanto e bello andare in giro per i colli bolognesi \t se hai una vespa special che \n ti toglie i problemi anche con l\'apopstrofo """ print("----") print(text) print("----") result = 1**2+3**6 print("now doing some simple math:", result) print(f"now printing the same result again: {result}") def more_math(result): var1 = result**2 var2 = result*var1 var3 = var1/var2 return var1, var2, var3 #now back to formatting strings: print("This was anotehr way to print the formatted result: {}".format(result)) print("now we output the three variables from the more_math method:") more_math_result = more_math(result) print("Var1: {}, Var2: {}, Var3: {}.".format(*more_math_result))
false
88addc9e635a001adef7b8a0738130032830ef7d
pdefusco/Python
/app_development/lpth/ex11.py
454
4.21875
4
#working with inputs and printing the text print("How old are you?", end= ' ') age = input() print("How tall are you?", end = ' ') height = input() print(f"The age is {age} and the height is {height}") #now inputting numbers: print("Let's do some math. Multuply value x times value y") print('Assign value for x: ', end=' ') x = int(input()) print('Now assign value for y:', end= ' ') y = int(input()) print("The two values multiplied yield: ", x*y)
true
34b2c0dfa65c7f51f4b6ed3ee54b64fd407882a9
ShwetaAkiwate/GitDemo
/pythonTesting/write.py
462
4.28125
4
# read the file and store all the lines in list #reverse the list #write the list back to the file with open('test.txt', 'r') as reader: # with is used for open the file, shortcut of "file = open('test.txt') file.close())" content = reader.readlines() #[abc,bretwer,cere, derre,egrete] reversed(content) #[egrete,derre,cere,bretwer,abc] with open('test.txt','w') as writer: for line in reversed(content): writer.write(line)
true
c8ba9f5518d1e54101e500afd2341a5a5ac5827d
ShwetaAkiwate/GitDemo
/pythonTesting/demo2nd.py
885
4.40625
4
values = [1, 2, "Krunal", 4, 5] # list is data type that allows multiple values and can be different data type print(values[0]) print(values[3]) print(values[-1]) # if you want to print last value in the list. this is shortcut print(values[1:3]) values.insert(3, "shweta") print(values) values.append("End") print(values) values[2] = "KRUNAL" # update values del values[0] #[2, 'KRUNAL', 'shweta', 4, 5, 'End'] print(values) # Tuple - same as list data type, but immutable where updation is not possible #val = (1, 2, "SHWETA", 4.5) #print(val[1]) #val[2] = "shweta" #print(val) # dictionary dic = {"a" : 2, 4 : "shweta", "c" : "Hello world"} print(dic[4]) print(dic["c"]) # how to create dictionary at run time and add data into it dict = {} dict["firstname"] = "Krunal" dict["lastname"] = "Intwala" dict["gender"] = "Male" print(dict) print(dict["lastname"])
true
9b7adad9b27492dbe0ac4f5f232b9ed02e4c78d9
BrodyCur/oop-inheritance
/class_time.py
679
4.125
4
class Person: def __init__(self, name): self.name = name def greeting(self): print(f"Hi my name is {self.name}.") class Student(Person): def learn(self): print("I get it!") class Instructor(Person): def teach(self): print("An object is an instance of a class.") teacher = Instructor('Nadia') teacher.greeting() student = Student('Chris') student.greeting() teacher.teach() student.learn() #These don't work because the student object has no relation to the Instructor class, so it cannot call methods from that class. It only shares a relation with Instructor objects with the Person class. And vice-versa. student.teach() teacher.learn()
true
496c0f74a51698cb39a0cce23c6a462ac775f41b
MaxTyson/GH
/GH/HT_6/HT_6-2.py
1,417
4.4375
4
''' Створити клас Person, в якому буде присутнім метод __init__ який буде приймати * аргументів, які зберігатиме в відповідні змінні. Методи, які повинні бути в класі Person - show_age, print_name, show_all_information. Створіть 2 екземпляри класу Person та в кожному з екземплярів створіть атребут profession. ''' class Person: ''' Make class to printing some person's information ''' def __init__(self, name, age, *args): ''' initialisation pesrons ''' self.name = name self.age = age def print_name(self): ''' printing person's name ''' print('Person\'s name is {}.'.format(self.name)) def show_age(self): ''' printing person's age ''' print('Person\'s age is {}.'.format(self.age)) def show_all_information(self): ''' printing all person's info ''' print('{}\'s age is {}, profession - {}.\n'.format(self.name, \ self.age, self.profession)) # make some persons for example author = Person(name = 'Maxim', age = 25) poroh = Person(name = 'Petia', age = 53) # add professions for persons author.profession = 'Programmer' poroh.profession = 'President' # examples author.print_name() author.show_age() author.show_all_information() poroh.print_name() poroh.show_age() poroh.show_all_information()
false
7b1ed9f05b439119fbba39393cea3e7d5bc3bc27
rtuita23/bicycle
/bicycle.py
1,659
4.40625
4
""" BICYCLE CLASS TODO - A bicycle has a model name TODO - A bicycle has a weight TODO - A bicycle has a cost TODO - Return as dictionary () """ class Bicycle: def __init__(self, modelName, weight, cost): self.modelName = modelName self.weight = weight self.cost = cost def bike(self): return {'Model': self.modelName, 'Weight': self.weight, 'Cost': self.cost} """ BIKE SHOP CLASS TODO - has a name TODO - has an inventory of different bicycles TODO - can sell bicycles with a margin over their cost TODO - Can see how much profit they have made from selling bikes """ class Bike_Shop(): def __init__(self, name, inventory): self.name = name self.inventory = inventory def __str__(self): models = '' for bikes in self.inventory: for key in bikes.keys(): if key == 'Model': models += bikes[key] + '\n' return 'Models are: ' + '\n' + str(models) def price(self): for bikes in self.inventory: for key in bikes.keys(): if key == "Cost": bikes[key] = bikes[key] + bikes[key] * self.margin return 'New Pricing: ' + self.inventory """ class Customer: # Create a Customer class def __init__(self, name, fund): # Get name and fund of customers self.name = name self.fund = fund def __str__(self): return 'Customer Name: '+ self.name + '\n' + \ 'Fund Amount: ' + str(self.fund) """
true
72446ac72787e677c180957a9fd3d871f3dfd0ea
ThiruArasuGit/PYTHON
/Programs/dummy.py
933
4.15625
4
nlist = [1, 2, 0, 3, 0, 4] print(nlist) ''' sum of min and max numbers''' sumOf_min_max = max(nlist) + min(nlist) print(f'Sum of min and max: {sumOf_min_max}') ''' Method:1 find sum of even numbers''' even_lst = [] for i in range(len(nlist)): if nlist[i] > 0 and nlist[i] % 2 == 0: even_lst.append(nlist[i]) print(f'[Method 1]Sum of even numbers: {sum(even_lst)}') ''' Method:2 find sum of even numbers''' eLst = [] for i in nlist: if i > 0 and i % 2 == 0: eLst.append(i) print(f'[Method 2 ] Sum of even numbers: {sum(eLst)}') ''' find min and max value using function''' def min_val(x): min_num = x[0] for check in x: if check < x[0]: min_num = check return min_num def max_val(x): max_num = x[0] for check in x: if check > x[0]: max_num = check return max_num print(f' Min value: {min_val(nlist)}, Max value: {max_val(nlist)}')
false
2a3186ce3f5f0c3c5bcae47810b04285541eac56
gaolingshan/LeetcodePython
/500KeyboardRow.py
1,239
4.15625
4
''' 500. Keyboard Row Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. Example 1: Input: ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"] Note: You may use one character in the keyboard more than once. You may assume the input string will only contain letters of alphabet. ''' ''' Tag: hashtable Thoughts: 1. Create a list of sets where each set contains one row of letters on the keyboard. -> mother set 2. Iterate over the word list, convert each word to a set, compare this set with mother set 2. Iterate over the word list, convert each word to a set, compare this set with mother set. ''' class Solution: def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ d = [{'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'}, {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'}, {'z', 'x', 'c', 'v', 'b', 'n', 'm'}] res = [] for i in range(len(words)): w_set = set(words[i].lower()) if w_set <= d[0] or w_set <= d[1] or w_set <= d[2]: res.append(i) return [words[i] for i in res]
true
23a076b0d68ae363d2226119184ea976d5a6b1d7
gaolingshan/LeetcodePython
/414ThirdMaximumNumber.py
1,199
4.15625
4
''' 414. Third Maximum Number Difficulty: Easy Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). Example 1: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1. Example 2: Input: [1, 2] Output: 2 Explanation: The third maximum does not exist, so the maximum (2) is returned instead. Example 3: Input: [2, 2, 3, 1] Output: 1 Explanation: Note that the third maximum here means the third maximum distinct number. Both numbers with value 2 are both considered as second maximum. ''' class Solution(object): def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ res = [float('-inf'), float('-inf'), float('-inf')] for number in nums: if number not in res: if number > res[0]: res = [number, res[0], res[1]] elif number > res[1]: res = [res[0], number, res[1]] elif number > res[2]: res = [res[0], res[1], number] return max(res) if float('-inf') in res else res[2]
true
bb63af901b9acacc65d119ab5444da3bb25d20c6
hyc121110/LeetCodeProblems
/String/isValidParentheses.py
629
4.15625
4
''' Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. ''' def isValidParentheses(s): dict = {')': '(', ']': '[', '}': '{'} stack = [] for p in s: if p in dict.values(): stack.append(p) elif stack == [] or dict[p] != stack.pop(): return False return stack == [] print(isValidParentheses("()[]{}"))
true
ae871173fa6e77f1423dda6dcecfc0407e7d8239
hyc121110/LeetCodeProblems
/Others/maxProduct.py
864
4.28125
4
''' Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. ''' def maxProduct(nums): # initialize max product r = nums[0] # imax/imin stores the max/min product of subarray that ends with the current number A[i] imax = imin = r for num in nums[1:]: # multiplied by a negative makes big number smaller, small number bigger so we redefine the extremums by swapping them if num < 0: imax, imin = imin, imax # max/min product for the current number is either the current number itself or the max/min by the previous number times the current one imax = max(num, imax * num) imin = min(num, imin * num) r = max(r, imax) # the newly computed max value is a candidate for our global result return r print(maxProduct(nums=[-2,0,-1]))
true
d215f6192e52fcfb423810ed9d3cef7bf453ddbb
hyc121110/LeetCodeProblems
/String/letterCombinations.py
980
4.21875
4
''' Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. ''' def letterCombinations(digits): map_ = { '2' : 'abc', '3' : 'def', '4' : 'ghi', '5' : 'jkl', '6' : 'mno', '7' : 'pqrs', '8' : 'tuv', '9' : 'wxyz' } result = [] # helper function def make_combinations(i, cur): # at the end of the list -> concatenate chars in cur and add to result if len(digits) == 0: return if i == len(digits): result.append(''.join(cur)) return for ch in map_[digits[i]]: cur.append(ch) make_combinations(i+1, cur) cur.pop() make_combinations(0, []) return result print(letterCombinations(digits="23"))
true
e2df8c6429a4423480779f58e94c207b78bf500e
hyc121110/LeetCodeProblems
/Array/subsets2.py
721
4.21875
4
''' Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets. ''' def subsetsWithDup(nums): # similar to subset.py but with sorting and checking # if subset in result list or not res = list() # base case with empty set res.append(list()) for num in nums: size = len(res) for i in range(size): # add num to each of the subsets subset = list(res[i]) subset.append(num) # added the subset to the result list if subset not in res: res.append(subset) print(subsetsWithDup(nums=[4,4,4,1,4]))
true
2e4cd6eccf5231c205e6b8846224721b9516dd74
chanhosuh/algorithms
/sorting/quicksort/utils.py
1,383
4.125
4
from random import randrange def position_pivot(a, lo, hi, pivot=None): """ various possibilities, but here we select a reasonably robust pivot selection methodology: median of three After possibly several swaps, a[hi] is the "median" value of a[lo], a[hi-1], a[hi]. Note: - it's assumed lo < hi """ m = hi - 1 if a[hi] > a[m]: swap(a, hi, m) if a[lo] > a[m]: swap(a, lo, m) if a[hi] < a[lo]: swap(a, hi, lo) if pivot: swap(a, hi, pivot) def swap(a, i, j): a[i], a[j] = a[j], a[i] def shuffle(a): for i in reversed(range(len(a))): n = randrange(i + 1) swap(a, n, i) def print_head(a, num=10): """ print head of the list only """ print(" ", a[:num] + ["..."]) def is_sorted(a): last = None for x in a: if last and last > x: return False last = x return True def random_list(num, max_num): return [randrange(max_num + 1) for _ in range(num)] # ANSI escape codes BOLD = "\033[1m" RESET = "\033[0m" REVERSE = "\033[7m" RED = "\033[00;31m" GREEN = "\033[0;32m" FAILED_MSG = f"{BOLD}sort{RESET}: {RED}FAILED{RESET}" SUCCEEDED_MSG = f"{BOLD}sort{RESET}: {GREEN}SUCCEEDED{RESET}" def print_if_sorted(a): if is_sorted(a): print(SUCCEEDED_MSG) else: print(FAILED_MSG) print_head(a)
true
1fc0c94d2dd509c2d8becbba0ed16b67fe3d02ef
misohan/Jmk
/dict_test.py
789
4.34375
4
# Create a dict directory which stores telephone numbers (as string values), # and populate it with these key-value pairs: directory = { 'Jane Doe': '+27 555 5367', 'John Smith': '+27 555 6254', 'Bob Stone': '+27 555 5689' } # Change Jane’s number to +27 555 1024 directory['Jane Doe'] = '+27 555 1024' # Add a new entry for a person called Anna Cooper with the phone # number +27 555 3237 directory['Anna Cooper'] = '+27 555 3237' # Print Bob’s number. print(directory['Bob Stone']) # Print Bob’s number in such a way that None would be printed if # Bob’s name were not in the dictionary. print(directory.get("Bob Stone", None)) # Print all the keys. The format is unimportant, as long as they’re all visible. print(directory.keys()) # Print all the values. print(directory.values())
true
0471166b0d6f9d6252987d7ed81d8cc61e767c0f
ashrafm97/pycharm_oop_project
/dogs_class.py
1,597
4.46875
4
# abstract and create the class dog # class Dog(): # pass #initializing a Dog object # dog_instance1 = Dog() #print the Dog object # print(dog_instance1) # print(type(dog_instance1)) # you want to define classes on one side and run them on the other... you need to chop this code and place it in the run file class Dog(): #adding init 'method'... after everything #it comes defined but we can redefine it # this method stands for initializing class object - aka 'constructor' in other languages # allows us to set attributes to our dog objects # like the poor thing isnt even named lol # we should name it right? #self refers to the 'instance' of the 'object' def __init__(self, name = 'Mad Max'): self.name = name self.age = 7 self.paws = 4 self.fur = 'black and grey' self.fav_food = 'Steak' # setting attributes 'name' to 'instances' of the Dog class... 'name is hardcoded now to be Max' # this is a 'method' that can be used by the 'instance' Dog def voice(self, creature = " "): return 'woof, woof! I see you, damn ' + creature # polymorphism, by default creature is nothing def eat(self): return 'nom, nom, NOM'.lower() def fetch(self): return 'zoom zoom' def tail(self): return 'wagging' def sleep(self): return 'zzzzZZZZzzz *drool* ' # in this file, you define the class dog and add attributes and method to the class, like fur or eyes or no. of legs etc etc. so no print statements... # print("Filipe is a cool guy, as is Shahrukh")
true
d6f148e6819e4e16c5a6fe547db13b7f54996a3a
pqGC/Core_python_programming
/python/6-15.py
2,211
4.25
4
#! /usr/bin/env python # encoding:utf-8 import time from datetime import date def calcdate(string1,string2): temp_list1 = string1.split('/') temp_list2 = string2.split('/') days_count = "" first_date = date(int(temp_list1[2]),int(temp_list1[1]),int(temp_list1[0])) second_date = date(int(temp_list2[2]),int(temp_list2[1]),int(temp_list2[0])) if first_date < second_date: date_count = abs(second_date - first_date) return days_count.days def calcbirth(string): today = date.today() time_to_birth = "" time_list = string.split('/') birth = date(int(temp_list[2]),int(temp_list[1]),int(temp_list[0])) if birth < today: time_to_birth = abs(today - birth) else: print("please input the right birth") return time_to_birth.days def nextbirth(string): today = date.today() time_to_birth = "" temp_list = string.split('/') month_day = date(today.year,int(temp_lsit[1]),int(temp_list[0])) birth = date(int(today.year + 1),int(temp_list[1]),int(temp_list[0])) if today < month_day: next_time_to_birth = abs(month_day-today) elif today < birth: next_time_to_birth = abs(birth - today) else: print("Please input the right birth") return next_time_to_birth.days if __name__ == "__main__": while True: choice = raw_input("I can do something:\na: Count the number of days between two date\n" "b:Count the number of days since you born\n" "c:Count the number of days before your next birth\n" "q to exit\n") if choice == 'q': break elif choice == 'a': str_1 = raw_input("Please enter your first date:like DD/MM/YY \n") str_2 = raw_input("Please enter your second date\n") try: print("The number of gays between two date is ",calcdate(str_1,str_2)) except: print("Please check your enter format DD/MM/YY") elif choice == 'b': str_date = raw_input("Please enter your date:like DD/MM/YY \n") try: print "You had born" ,calcbirth(str_date),"days" except: print("Please check your enter format DD/MM/YY") elif choice == 'c': str_date = raw_input("Please enter your birth date:like DD/MM/YY\n") try: print "There are",nextbirth(str_date),"days of your next birthdays" except: print("Please check your enter format DD/MM/YY")
false
cd9cbd6cbe29ed79ee8775368599218fe0e0a151
duqcyxwd/python-practice-
/MaxProductOfThree.py
1,884
4.28125
4
#!/usr/bin/env python # For example, array A such that: # A[0] = -3 # A[1] = 1 # A[2] = 2 # A[3] = -2 # A[4] = 5 # A[5] = 6 # contains the following example triplets: # (1, 2, 4), product is 1 * 2 * 5 = 10 # (2, 4, 5), product is 2 * 5 * 6 = 60 # Your goal is to find the maximal product of any triplet. # Write a function: # int solution(int A[], int N); # that, given a non-empty zero-indexed array A, returns the value of the maximal product of any triplet. # For example, given array A such that: # A[0] = -3 # A[1] = 1 # A[2] = 2 # A[3] = -2 # A[4] = 5 # A[5] = 6 # the function should return 60, as the product of triplet (2, 4, 5) is maximal. # Assume that: # N is an integer within the range [3..100,000]; # Complexity: # expected worst-case time complexity is O(N*log(N)); # expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments). # Elements of input arrays can be modified. def solution1(A): # write your code in Python 2.7 size = len(A) maxValue = 0; for x in xrange(0, size): for x1 in xrange(1, size): for x2 in xrange(2, size): if (x != x1 and x1 != x2 and x2 !=x): res = x * x1 * x2 if res > maxValue: maxValue = res return maxValue def solution(A): # write your code in Python 2.7 size = len(A) maxValue = 0; i1 = 0 i2 = size/2 i3 = size - 1 maxValue = A[i1] * A[i2] * A[i3] while true: maxValue = A[i1] * A[i2] * A[i3] pass return maxValue def solution3(A): # write your code in Python 2.7 size = len(A) sortedList = sorted(A) return sortedList[size-1] * sortedList[size-2] * sortedList[size-3] print "hi" A = [-5, 5, -5, 4] print A print sorted(A) print solution3(A) A.sort() print A print max(1, 2, 3, 5)
true
2a10483d5ba863777c8bc3411ba5fa91e476df16
ashish6194/pythonbasics
/chapter_04/01_comp_op.py
351
4.3125
4
name = input("What's your name? ") if name == "Jessica": print("Hello, nice to see you {}".format(name)) elif name == "Danielle": print("Hello, you are a great person!") elif name != "Mariah": print("You're not Mariah!") elif name == "Kingston": print("Hi, {}, let's have lunch soon!".format(name)) else: print("Have a nice day!")
true
b9c455b5b293307355cea6d4a5239a4b86a2f9d5
JeffreyAsuncion/CSPT15_Graphs_I_GP
/src/demos/demo1.py
780
4.125
4
""" You are given an undirected graph with its maximum degree (the degree of a node is the number of edges connected to the node). You need to write a function that can take an undirected graph as its argument and color the graph legally (a legal graph coloring is when no adjacent nodes have the same color). The number of colors necessary to complete a legal coloring is always one more than the graph's maximum degree. *Note: We can color a graph in linear time and space. Also, make sure that your solution can handle a loop in a reasonable way.* """ # Definition for a graph node. class GraphNode: def __init__(self, label): self.label = label self.neighbors = set() self.color = None def color_graph(graph, colors): # Your code here pass
true
14bb42f59d4bdbc07ac76c43936e4cb347d63e10
muigaipeter/Python_class
/workingfolder/classes/demo1.py
1,505
4.21875
4
#is a blue print in oop #an object/instance #syntax #class name_of_the_class(): #the blue print attributes class Person(): name = 'Developer' d1 = Person() d2 = Person() print(d1.name) print(d2.name) #all classes has a function called _init_() # which is always executed when the class is being initiated #Use the _init_() function to assign values to properties or other operations that are neccessary class Animal(): country = 'kenya'#class property def __init__(self,name): self.thename = name def sound(self): if self.thename == 'cutty': print('mweeew') def kitty(self): if self.thename == 'cutty': print('such a playerful cat') def fear(self): if self.thename == 'Betty': print('betty is not feeling well') def white(self): if self.thename == 'cutty': print('cutty is a deaf cat') def sounds(self): if self.thename == 'bob': print('woooof') cat = Animal('cutty') print(cat.thename) cat2= Animal('Betty') print(cat.thename) print(cat.country) print('bob is a nice puppy') dog = Animal('bob') #deleting a property #del object.property #el cat.thename print(cat.thename) print(cat2.thename) #deleting an object #del object del cat print(cat) cat.sound() cat.kitty() cat2.fear() cat.white() dog.sounds() #modifying objectproperty #object.property='new value' cat.country = 'Uganda' print(cat.country)
true