blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ac68226a997c7c29a695f8a7f980010eeb5c2ae8
satyam4853/PythonProgram
/Functional-Programs/Quadratic.py
613
4.15625
4
""" * Author - Satyam Vaishnav * Date - 21-SEP-2021 * Time - 10:30 PM * Title - Quadratic """ #cmath module using to compute the math function for complex numbers import cmath #initalize the variables taking from UserInput. a=float(input("Enter the value of a: ")) b=float(input("Enter the value of b: ")) c=float(input("Enter the value of c: ")) #Math Formula for Quadratic Equation delta= (b*b-(4*a*c)) #To finding Roots of equation root1 = (-b+(cmath.sqrt(delta)))/(2*a) root2 = (-b-(cmath.sqrt(delta)))/(2*a) #Getting the vale of roots print("Root1 of x is : ",root1) print("Root2 of x is : ",root2)
true
3b24e2a04e23058ab07b84286471a9fcb5df678e
luzonimrod/PythonProjects
/Lessons/MiddleEX1.py
250
4.125
4
#Write a Python program to display the current date and time. Sample Output : #Current date and time : #14:34:14 2014-07-05 from datetime import date today=date.today() ti=today.strftime("%d/%m/%Y %H:%M:%S") print("current date and time :\n " + ti)
true
f8551faa26b591b1ee0d4325d236a87da3e5ad6e
imshawan/ProblemSolving-Hackerrank
/30Days-OfCode/Dictionaries and Maps.py
469
4.125
4
# Day 8: Dictionaries and Maps # Key-Value pair mappings using a Map or Dictionary data structure # Enter your code here. Read input from STDIN. Print output to STDOUT N=int(input()) phoneBook={} for _ in range(N): name,contact=input().split() phoneBook[name]=contact try: while(True): check=str(input()) if check in phoneBook: print(check+"="+phoneBook[check]) else: print('Not found') except: pass
true
5fddff1509c6cdd53ecf20c4230f1db35f769544
tawrahim/Taaye_Kahinde
/Kahinde/chp6/tryitout (2).py
1,912
4.125
4
print "First Question:" firstname="Kahinde" lastname="Giwa" print "Hello,my name is,",firstname,lastname print "\n\n\n" print "**************************\n" firstname=raw_input("Enter your first name please:") lastname=raw_input("Now enter your lastname:") print "You entered",firstname,"for your firstname," print "And you entered",lastname,"for your lastname" print "Hello,",firstname,lastname,".How do you do?" print "\n\n\n" print "**************************\n" print """Tell me the dimensions of a rectangular room and I will give you the amount of carpet you need for that room.""" length=int(raw_input("What is the length?")) width=int(raw_input("Now what is the width?")) print "You entered,",length,"for the length." print "And you entered,",width,"for the width." answer=length*width print "The answer is,",answer print "So that's the amount of carpet you need for your floor",answer print "\n\n\n" print "**************************\n" print """Tell me the demensions of a rectangular room and I will give you the amount of money you need for that room in yards and feet""" length=float(raw_input("What is the length?")) width=float(raw_input("Now what is the width?")) money=float(raw_input("What is the amount of money for each sq. yd.")) area_ft=length*width yards=area_ft/9.0 cost=float(area_ft*money) print "The area is," ,int(area_ft),"in feet." print "The area is,",yards,"in yards." print "The cost is,",cost print "\n\n\n" print "**************************\n" print "I will ask you to give me your change so I can add it up for you." quarter=int(raw_input("Enter in how many quarters:"))*25 dime=int(raw_input("Enter in how many dimes:"))*10 nickel=int(raw_input("Enter in how many nickels:"))*5 penny=int(raw_input("Enter in how many pennies:"))*1 formula=quarter+dime+nickel+penny print "For change,you have",formula,"cents"
true
77ef1a85e93549c28e6eeef9fdeeeab5a1365350
tawrahim/Taaye_Kahinde
/Taaye/chp4/dec-int.py
1,346
4.625
5
print "Question #1, Try it out" print"\n" print'This is a way to change a string to a float' string1=12.34 string="'12.34'" print 'The string is,',string point= '12.34' formula= float(string1) print "And the float is,",point print 'We use this formala to change a string into a float, the formula is,', formula print 'So then you get,' print formula print "\n" print 'Question #2, try it out' print "\n" formula= "int(56.78)" working=int(56.78) decimal=56.78 print 'We are going to change the decimal,',decimal,'to an integer(number)' print 'To do that we must use the formula,',formula print 'Ten once once you type it in, you get the answer.......' print working print 'That is how you do it.' print '\n\n' print 'Question #3, try it out' print '\n' string="'1234.56'" string1=1234.56 formula=int(string1) formula2= "('1234.56')" print 'To make the string,',string,'into an integer, we must use the formula , int ().' print 'But since you can not put quotations inside the perantheses,' ,formula2,'or it will not work.' print 'We have to assign,',string,'to a variable, any variable for example I will do number.' print 'Number=',string,'so now we can do, int(number).' print 'Then, once you type that in, you get............' print formula print 'That is how you do it' print 'Done by Taaye'
true
07566268fa1ca3f0e66a41f8fc4d6f758fdaa9d0
tawrahim/Taaye_Kahinde
/Kahinde/chp8/looper_tio.py
1,077
4.125
4
#Kainde's work,Chapter 8,tryitout,question1 number=int(raw_input("Hello, what table should I display? Type in a number:")) print "Here is your table:" for looper in range(number): print looper, "*",number,"=",looper*number print "\n*************************************" #Chapter 8,tryitout,question2 number=int(raw_input("Hello, what table should I display? Type in a number:")) print "Here is your table:" j=0 while (j<5): print j,"*",number,"=",j*number j=j+1 print "\n**************************************" #Chapter 8,tryitout,question3 number=int(raw_input("Which multiplication table would you like?")) number1=int(raw_input("How high do you want to go?")) for looper in range(number1): print looper, "*",number,"=",looper*number if looper==number1: break print "\n**************************************" number=int(raw_input("Which multiplication table do you want?")) number1=int(raw_input("How high do you want to go?")) k=0 while k<number1: print number,"*",k,"=",number*k k+=1
true
89ba7658b45e09a370813e75845e4009e9d4fa28
TrinityChristiana/py-classes
/main.py
882
4.15625
4
# **************************** Challenge: Urban Planner II **************************** """ Author: Trinity Terry pyrun: python main.py """ from building import Building from city import City from random_names import random_name # Create a new city instance and add your building instances to it. Once all buildings are in the city, iterate the city's building collection and output the information about each building in the city. megalopolis = City("Megalopolis", "Trinity", "2020") buildings = [Building("333 Commerce Street", 33), Building("Strada General Traian Moșoiu 24", 5), Building( "5 Avenue Anatole France", 276), Building("1600 Pennsylvania Ave NW", 6), Building("48009 Bilbo", 3)] for building in buildings: person = random_name() building.purchase(person) building.construct() megalopolis.add_building(building) megalopolis.print_building_details()
true
a2e72fc8db97045e7b33c13ec8d40eb9dcb37ca6
lokeshom1/python
/datetransformer.py
682
4.21875
4
month = eval(input('Please enter the month as a number(1-12): ')) day = eval(input('Please enter the day of the month : ')) if month == 1: print('January', end='') elif month == 2: print('February', end='') elif month == 3: print('March', end='') elif month == 4: print('April', end='') elif month == 5: print('May',end='') elif month == 6: print('June',end='') elif month == 7: print('July',end='') elif month == 8: print('August',end='') elif month == 9: print('September',end='') elif month == 10: print('October',end='') elif month == 11: print('November',end='') elif month == 12: print('December',end='') print(day)
true
311ab08d466143062b58036743236330b0c92f57
khamosh-nigahen/linked_list_interview_practice
/Insertion_SLL.py
1,692
4.5625
5
# Three types of insertion in Single Linked List # ->insert node at front # ->insert Node after a given node # ->insert Node at the tail class Node(object): def __init__(self, data): self.data = data self.nextNode = None class singleLinkedList(object): def __init__(self): self.head = None def printLinkedlist(self): temp = self.head while(temp): print(temp.data) temp = temp.nextNode def pushAtBegining(self, data): new_node = Node(data) new_node.nextNode = self.head self.head = new_node def insertAfterNode(self, data, prev_node): if prev_node is None: print("Please provide Node which exits in the linked list") else: new_node = Node(data) new_node.nextNode = prev_node.nextNode prev_node.nextNode = new_node def pushAttail(self, data): new_node = Node(4) temp = self.head while(temp.nextNode != None): temp = temp.nextNode temp.nextNode = new_node new_node.nextNode = None if __name__ == "__main__": sllist = singleLinkedList() # creating 3 nodes of the linked list first = Node(1) second = Node(2) third = Node(3) third.nextNode = None sllist.head = first first.nextNode = second second.nextNode = third #inserting the node at head sllist.pushAtBegining(0) #insert after particular Node sllist.insertAfterNode(2.5, second) #insert after tail sllist.pushAttail(4) #print the linked list sllist.printLinkedlist()
true
2f69c84b0517375ad6e4591ca8ad4dab9279d708
AkashKadam75/Kaggle-Python-Course
/Boolean.py
716
4.125
4
val = True; print(type(val)) def can_run_for_president(age): """Can someone of the given age run for president in the US?""" # The US Constitution says you must "have attained to the Age of thirty-five Years" return age >= 35 print("Can a 19-year-old run for president?", can_run_for_president(19)) print("Can a 45-year-old run for president?", can_run_for_president(45)) print(3.0 == 3) print(type('3')) print('3' == 3.0) def is_odd(n): return (n % 2) == 1 print("Is 100 odd?", is_odd(100)) print("Is -1 odd?", is_odd(-1)) print(bool(1)) # all numbers are treated as true, except 0 print(bool(0)) print(bool("asf")) # all strings are treated as true, except the empty string "" print(bool(""))
true
3a5ba0d910522c04787252d6a8afc8e8cae27952
AdamsGeeky/basics
/04 - Classes-inheritance-oops/51-classes-descriptor-magic-methods.py
2,230
4.25
4
# HEAD # Classes - Magic Methods - Building Descriptor Objects # DESCRIPTION # Describes the magic methods of classes # __get__, __set__, __delete__ # RESOURCES # # https://rszalski.github.io/magicmethods/ # Building Descriptor Objects # Descriptors are classes which, when accessed through either getting, setting, or deleting, can also alter other objects. Descriptors aren't meant to stand alone; rather, they're meant to be held by an owner class. Descriptors can be useful when building object-oriented databases or classes that have attributes whose values are dependent on each other. Descriptors are particularly useful when representing attributes in several different units of measurement or representing computed attributes (like distance from the origin in a class to represent a point on a grid). # To be a descriptor, a class must have at least one of __get__, __set__, and __delete__ implemented. Let's take a look at those magic methods: # __get__(self, instance, owner) # Define behavior for when the descriptor's value is retrieved. instance is the instance of the owner object. owner is the owner class itself. # __set__(self, instance, value) # Define behavior for when the descriptor's value is changed. instance is the instance of the owner class and value is the value to set the descriptor to. # __delete__(self, instance) # Define behavior for when the descriptor's value is deleted. instance is the instance of the owner object. # Now, an example of a useful application of descriptors: unit conversions. # class Meter(object): # '''Descriptor for a meter.''' # def __init__(self, value=0.0): # self.value = float(value) # def __get__(self, instance, owner): # return self.value # def __set__(self, instance, value): # self.value = float(value) # class Foot(object): # '''Descriptor for a foot.''' # def __get__(self, instance, owner): # return instance.meter * 3.2808 # def __set__(self, instance, value): # instance.meter = float(value) / 3.2808 # class Distance(object): # '''Class to represent distance holding two descriptors for feet and # meters.''' # meter = Meter() # foot = Foot()
true
2b4ee967304815ea875dfc6e943a298df143ef48
AdamsGeeky/basics
/04 - Classes-inheritance-oops/05-classes-getters-setters.py
784
4.34375
4
# HEAD # Classes - Getters and Setters # DESCRIPTION # Describes how to create getters and setters for attributes # RESOURCES # # Creating a custom class # Class name - GetterSetter class GetterSetter(): # An class attribute with a getter method is a Property attr = "Value" # GETTER - gets values for attr def get_attr(self): return self.attr # SETTER - sets values for attr def set_attr(self, val): self.attr = val obj = GetterSetter() # Print Values before using setter and direct attribute access print("obj.get_attr()", obj.get_attr()) print("obj.attr", obj.attr) # Use a setter obj.set_attr(10) # Print Values again using setter and direct attribute access print("obj.get_attr()", obj.get_attr()) print("obj.attr", obj.attr)
true
6f45acaeec134b92f051c4b43d100eeb45533be4
AdamsGeeky/basics
/02 - Operators/10-membership-operators.py
1,363
4.59375
5
# HEAD # Membership Operators # DESCRIPTION # Describe the usage of membership operators # RESOURCES # # 'in' operator checks if an item is a part of # a sequence or iterator # 'not in' operator checks if an item is not # a part of a sequence or iterator lists = [1, 2, 3, 4, 5] dictions = {"key": "value", "a": "b", "c": "d"} # Usage with lists for # 'not in' AND 'in' # 'in' checks for item in sequence if (1 in lists): print("in operator - 1 in lists:", (1 in lists)) # 'in' checks for absence of item in sequence if (1 not in lists): print("not in operator - 1 not in lists:", (1 not in lists)) # 'in' checks for absence of item in sequence if ("b" not in lists): print("not in operator - 'b' not in lists:", ("b" not in lists)) # Usage with dictions for # 'not in' AND 'in' # 'in' checks for item in sequence # diction.keys() return a sequence if ("key" in dictions.keys()): print("in operator - 'key' in dictions.keys():", ("key" in dictions.keys())) # 'not in' checks for absence of item in sequence # diction.keys() return a sequence if ("key" not in dictions.keys()): print("not in operator - 'key' in dictions.keys():", ("key" not in dictions.keys())) if ("somekey" not in dictions.keys()): print("not in operator - 'somekey' in dictions.keys():", ("somekey" not in dictions.keys()))
true
57e6b0b5cbb90562a02251739653f405b8237114
AdamsGeeky/basics
/03 - Types/3.1 - InbuiltTypes-String-Integer/05-integer-intro.py
952
4.15625
4
# HEAD # DataType - Integer Introduction # DESCRIPTION # Describes what is a integer and it details # RESOURCES # # int() is a function that converts a # integer like characters or float to a integer # float() is a function that converts a # integer or float like characters or integer to a float # Working with integer # Assigning integer values in different ways integer1 = 1 # Working with int() inbuilt function to create float integer2 = int("2") integer3 = int("3") integer4 = int(4) print(integer1) print(integer2) print(integer3) print(integer4) # Working with float # Assigning float values in different ways # Direct assignation float1 = 1.234 # Working with float() inbuilt function to create float # float() function can also be used to convert an # integer or float like string type to float float2 = float("5") float3 = float("6.789") float4 = float(1) print(float1) print(float2) print(float3) print(float4)
true
b04ae7f2eea4a5301c9439e4403403599358a05f
AdamsGeeky/basics
/04 - Classes-inheritance-oops/54-classes-overwriting.py
1,525
4.375
4
# Classes # Overriding # Vehicle class Vehicle(): maneuver = "Steering" body = "Open Top" seats = 4 wheels = 4 start = 0 end = 0 def __init__(self, maneuver, body, seats, wheels): self.maneuver = maneuver self.body = body self.seats = seats self.wheels = wheels print("Vehicle Instantiated") def move(self, end): self.end = end print("Vehicle moved from {} to {}".format(self.start, self.end)) # Following is not polymorphism # v = Vehicle() # print(v.body, v.maneuver, v.seats, v.wheels, v.start, v.end) # v = Vehicle("Bike", "Handle", 2, 2) # print(v.body, v.maneuver, v.seats, v.wheels, v.start, v.end) class Bike(Vehicle): # overriding - Parent-Child scope # maneuver = None def __init__(self, body, seats, wheels, maneuver= "Handle"): # declare => runs automatically when instantiating class # defining or assigning value to new # attribute is like defining it in class # Use same names in child like parent # overriding => parent:child scoping self.maneuver = maneuver self.body = body self.seats = seats self.wheels = wheels print("Bike Instantiated") # overriding - Parent-Child scope def move(self, end, name): self.end = end print("{} moved from {} to {}".format(name, self.start, self.end)) b = Bike("Yamaha", 2, 2) print(b.body, b.maneuver, b.seats, b.wheels, b.start, b.end)
true
a0f7967a83d0876a37cc74dd8c3c3dc8e1f2eaf3
AdamsGeeky/basics
/01 - Basics/33-error-handling-try-except-intro.py
1,137
4.1875
4
# HEAD # Python Error Handling - UnNamed Excepts # DESCRIPTION # Describes using of Error Handling of code in python # try...except is used for error handling # # RESOURCES # # 'try' block will be be executed by default # If an error occurs then the specific or # related 'except' block will be trigered # depending on whether the 'except' block # has named error or not # 'except' can use a named error and have multiple errors # 'except' without name will handle and # execute if any error occurs # You can have any number of 'except' blocks def obj(divideBy): try: return 42 / divideBy except ZeroDivisionError: print('Error: Invalid argument.') except (TypeError, NameError): print('Error: Multiple Error Block.') except: print('Error: Invalid argument.') print(obj(2)) print(obj(12)) # Will throw ZeroDivisionError and will be # captured triggering respective except block print(obj(0)) print(obj(1)) # # Error Handling using ImportError # try: # # Non-existent module # import def # except ImportError: # print('Module not found')
true
a30f5ca5fac728d808ef78763f16ca54290765f6
AdamsGeeky/basics
/01 - Basics/11-flowcontrol-for-enumerate-loops.py
1,129
4.78125
5
# HEAD # Python FlowControl - for loop # DESCRIPTION # Describes usage of for loop in different ways # for different usages # # 'for' loop can iterate over iterable (sequence like) or sequence objects # Result provided during every loop is an index and the relative item # # RESOURCES # # # USAGE # 1 # # for item in iterator: # # execution block # # Based on total number of items in the list ls = [2, 3, 4, 5, 6, 7, 8] # Using iterator to get # a item which is iterated for item in ls: print("Provides item of the iterator") print('for item in ls ' + str(item)) # Usage of enumerate() function: # enumerate(list) # using enumerate(iterator) function to get # a tuple of (index, value) which can be destructured for item in enumerate(ls): print("Provides index and its item of the iterator") print("enumerate(list) usage: for item with first item as idx& second as item in enumerate(ls): ", item[0], item[1]) for idx, item in enumerate(ls): print("Provides index and its item of the iterator") print("enumerate(list) usage: for idx, item in enumerate(ls): ", idx, item)
true
0640d7d0149ef291a99d472edcaf9e6d6c80ebe4
AdamsGeeky/basics
/01 - Basics/50-datatypes-type-conversion.py
2,961
4.5625
5
# HEAD # Python Basics - Conversion of Data Types # DESCRIPTION # Type Conversion # DESCRIPTION # Describes type conversion methods (inter-conversion) available in python # # RESOURCES # # These function can also be used to declare specific types # When appropriate object is used, these functions can be # used to convert one type to another # Example: list <-> tuple # Example: list <-> str # Example: dict <-> sequence of key value tuples # Other functions also exist like # list(), dict(), tuple(), set(), frozenset(), etc # repr() function and str() function both provide # the string representation of variable value # As per documetation repr() provides more # precise representation than str() import sys # STRING TYPE CONVERSION # str() converts to string sStr1 = str("Testing String") print('str1', sStr1) sStr2 = str(12) print('str2', sStr2) sStr3 = str(1.2345678901234567890) print('str3', sStr3) # repr() gives more precision while conversion to string sRepr1 = repr("Testing String") print('repr1', sRepr1) sRepr2 = repr(12) print('repr2', sRepr2) sRepr3 = repr(1.2345678901234567890) print('repr3', sRepr3) # NUMBER TYPE CONVERSION AND MEMORY USAGE # Type int(x) to convert x to a plain integer cint = int(1.12345678901234567890) print(cint) # Type long(x) to convert x to a long integer - Python 2 # clong = long(1.12345678901234567890) # print(clong) # Type float(x) to convert x to a floating-point number. cfloat = float(1.12345678901234567890) print(cfloat) # Type complex(x) to convert x to a complex number with real part x and imaginary part zero. # Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. # x and y are numeric expressions ccomplex = complex(1.12345678901234567890) print(ccomplex) # (1.1234567890123457+0j) ccomplexs = complex(1, 1.12345678901234567890) print(ccomplexs) # (1+1.1234567890123457j) print("\nByte size of each of following:\n") print("cint:", cint, "bytes", sys.getsizeof(cint)) # print("clong:", clong, "bytes", sys.getsizeof(clong)) print("cfloat:", cfloat, "bytes", sys.getsizeof(cfloat)) print("ccomplex:", ccomplex, "bytes", sys.getsizeof(ccomplex)) print("ccomplexs:", ccomplexs, "bytes", sys.getsizeof(ccomplexs)) # LIST TUPLE TYPE CONVERSIONS # Convert sequence of numbers to a list ls = list(,1,2,3,4) # Convert list to a tuple tpl = tuple(ls) # Convert tuple to a list ls = list(tpl) # Convert list to a set st = set(ls) # Convert tuple to a set st = set(tpl) # Convert set to a list ls = list(st) # Convert set to a tpl tpl = tuple(st) # Create a dictionary using a Key:Value dc = dict({"st": "new", "s": 10}) # Convert list to dictionary ds = dict(ls) # Convert tuple to dictionary ds = dict(tpl) # Convert set to a dictionary ds = set(dc) # Convert dictionary to a list ls = list(dc) # Convert dictionary to a tuple tpl = tuple(dc) # Convert dictionary to a set st = set(dc)
true
ee34a13657d64a8f3300fdf73e34362ad5a49206
AdamsGeeky/basics
/04 - Classes-inheritance-oops/17-classes-inheritance-setters-shallow.py
1,030
4.46875
4
# HEAD # Classes - Setters are shallow # DESCRIPTION # Describes how setting of inherited attributes and values function # RESOURCES # # Creating Parent class class Parent(): par_cent = "parent" # Parent Init method def __init__(self, val): self.par_cent = val print("Parent Instantiated with ", self.par_cent) # Creating ParentTwo class class Child(Parent): # Child Init method def __init__(self, val_two): print("Child Instantiated with ", val_two) # Explicit Instantiation of parent init # Instantiate parent once and passing args # Parent assigns value storing it in object to access # Parent default value remains self.p = super() self.p.__init__(val_two) obj = Child(10) print(""" Value of par_cent is assigned & fetched from Child class & default refs of parent remains """) print("obj.par_cent", obj.par_cent) print("obj.p.par_cent, id(obj.p), id(obj)", obj.p.par_cent, id(obj.p), id(obj))
true
f96d6651e41ca733e06d7b0346137a65688cd20a
RAVURISREESAIHARIKRISHNA/Python-2.7.12-3.5.2-
/Reading_list_INTs_Exception.py
816
4.21875
4
def Assign(n): try: return(int(n)) except ValueError: # Managing Inputs Like 's' print("Illegal Entery\nRetry..") n=input() # Asking User to Re-entry Assign(n) # Calling the Same function,I correct input entered..Integer will be Returned,Else..Calling Recursively return(int(n)) #Returning the Appropriate Int value except SyntaxError: # Managing Inputs like '5a' print("Illegal Entry\nRetr..") # -do-copy- n=input() # -do-copy- Assign(n) # -do-copy- return(int(n)) # -do-copy- List=[] print("Enter Size of the List:") temp=input() size=Assign(temp) print("Size is {}".format(str(size))) for i in range(1,size+1): print("Enter element {} :".format(str(i))) temp=input() List.append(Assign(temp)) print("The List is:") print(List)
true
d673103b6d9361916427652b337b9fbbf1fe7eae
cnkarz/Other
/Investing/Python/dateCreator.py
1,743
4.21875
4
# -*- coding: utf-8 -*- """ This script writes an array of dates of weekdays as YYYYMMDD in a csv file. It starts with user's input, which must be a monday in the same format Created on Wed Jan 25 07:36:22 2017 @author: cenka """ import csv def displayDate(year, month, day): date = "%d%02d%02d" % (year, month, day) return date monthLength = {"01":[31, 31], "02":[28, 29], "03":[31, 31], "04":[30, 30], "05":[31, 31], "06":[30, 30], "07":[31, 31], "08":[31, 31], "09":[30, 30], "10":[31, 31], "11":[30, 30], "12":[31, 31]} leapYears = [2008, 2012, 2016, 2020, 2024, 2028, 2032, 2036, 2040, 2044, 2048, 2052, 2056, 2060] firstDay = raw_input("Please enter the starting date: ") lastDay = int(raw_input("Please enter the ending date: ")) year = int(firstDay[:4]) month = int(firstDay[4:6]) day = int(firstDay[6:]) intFirstDay = int(firstDay) count = 1 listIndex = 0 listOfDates = list() listOfDates.append(intFirstDay) while intFirstDay < lastDay : day += 1 count += 1 for key in monthLength : if year not in leapYears : if int(key) == month and monthLength[key][0] +1 == day : month += 1 day = 1 else : if int(key) == month and monthLength[key][1] + 1 == day : month += 1 day = 1 if month == 13 : year += 1 month = 1 if count == 6 or count == 7: continue elif count == 8 : count = 1 listIndex += 1 firstDay = displayDate(year, month, day) intFirstDay = int(firstDay) listOfDates.append(intFirstDay) with open("dates.csv", "wb") as datecsv: datewr = csv.writer(datecsv) for k in range(len(listOfDates)): datewr.writerow([listOfDates[k]]) datecsv.close()
true
b3ee3c37efe6d97d32869f14d6e5bba5e9e8fc91
bglogowski/IntroPython2016a
/students/Boundb3/Session05/cigar_party.py
594
4.125
4
#!/usr/bin/env python """ When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return True if the party with the given values is successful, or False otherwise. """ print ("this is a test") def cigar_party(cigars, is_weekend): print(cigars,is_weekend, "made it to the def cigar_party function") return (cigars*2) cigar = 40 is_weekend = False x = cigar_party(cigar, is_weekend) print(x)
true
73a241b1ba5d6337a93fe53fdfdb85815953d13e
AaryaVora/Python-Level-1-2
/hw3.py
266
4.125
4
fnum = int(input("Please enter a number: ")) snum = int(input("Please enter a number: ")) if fnum == snum : print("Both numbers are equal") elif fnum < snum: print("Second number is greater") else: print("First number is greater than the second number")
true
e61e0925cb261ff53f4a3ce9cf90314a3d9c4ed9
Harrison-Z1000/IntroProgramming-Labs
/labs/lab_03/pi.py
1,077
4.34375
4
# Introduction to Programming # Author: Harrison Zheng # Date: 09/25/19 # This program approximates the value of pi based on user input. import math def main(): print("This program approximates the value of pi.") n = int(input("Enter the number of terms to be summed: ")) piApproximation = approximate(n) # Calls the approximate method, passing n as the argument print("The sum of the first", n, "terms of this series is", piApproximation) difference = math.pi - piApproximation # Finds the difference between the approximated value and actual value of pi print("The difference between the approximation and the actual value of pi is", difference) def approximate(n): total = 0.0 for i in range(n): total = total + (-1.0) ** i / (2.0 * i + 1.0) # The sign of each term in the sequence is always the opposite # of the last. The denominator of every term is odd and is two more than that of the previous term. return 4 * total # The numerator of every term is 4 so multiply total by 4 to get the approximation of pi main()
true
1b2dea794f55fab9398ec2fcbf258df7007f0f90
yash95shah/Leetcode
/swapnotemp.py
284
4.28125
4
''' know swapping works on python without actually using temps ''' def swap(x, y): x = x ^ y y = x ^ y x = x ^ y return (x, y) x = int(input("Enter the value of x: ")) y = int(input("Enter the value of y: ")) print("New value of x and y: " + str(swap(x, y)))
true
ca312b4e02650221b6bb5f34871ef12f45ad98d9
yash95shah/Leetcode
/sumwithoutarith.py
411
4.3125
4
''' Sum of two integers without actually using the arithmetic operators ''' def sum_without_arith(num1, num2): temp_sum = num1 ^ num2 and_sum = num1 & num2 << 1 if and_sum: temp_sum = sum_without_arith(temp_sum, and_sum) return temp_sum n1 = int(input("Enter your 1st number: ")) n2 = int(input("Enter your 2nd number: ")) print("Their sum is: " + str(sum_without_arith(n1, n2)))
true
3962ed28f3ccc7d4689d73f5839bc6d016e43736
Juhkim90/Multiplication-Game-v.1
/main.py
980
4.15625
4
# To Run this program, # Press Command + Enter import random import time print ("Welcome to the Multiplication Game") print ("Two Numbers are randomly picked between 0 and 12") print ("Try to Answer ASAP. If you do not answer in 3 seconds, You FAIL!") score = 0 ready = input("\n\nAre you ready? (y/n): ") while (ready == 'y'): first = random.randint(0,12) second = random.randint(0,12) for x in range(3,0,-1): print(x) time.sleep(1) print("\nQuestion: ") time1 = time.time() question = int(input(str(first) + " x " + str(second) + " = ")) time2 = time.time() if (question == first * second and time2 - time1 < 3): print ("You got it!") score += 1 else: if (time2 - time1 >= 3): print ("You did not get it in time.") else: print ("Wrong Answer.") print ("Score: " + str(score)) ready = input("\n\nAre you ready? (y/n): ") else: print ("Alright. Prepare yourself") print ("Total Score: " + str(score))
true
442554266ce87af7740511669163b8c575a96950
OliviaParamour/AdventofCode2020
/day2.py
1,553
4.25
4
import re def load_file(file_name: str) -> list: """Loads and parses the input for use in the challenge.""" input = [] with open(file_name) as file: for line in file: parts = re.match(r"^(\d+)-(\d+) ([a-z]): (\w+)$", line) input.append((int(parts.group(1)), int(parts.group(2)), parts.group(3), parts.group(4)) ) return input def is_password_valid(case: tuple) -> bool: """Checks if a password is valid based on provided criteria: Includes number of letters between low and high, inclusive. """ low, high, letter, password = case[0], case[1], case[2], case[3] return low <= password.count(letter) <= high def is_password_valid_two(case: tuple) -> bool: """Checks if a password is valid based on provided criteria: Must contain a letter in either position 1 or 2 but not both. """ first, second, criteria, password = case[0]-1, case[1]-1, case[2], case[3] return (password[first] == criteria) ^ (password[second] == criteria) def main() -> None: """The main function for day 2. Answers question 1 and 2.""" passwords = load_file("day2.txt") schema_1 = sum([is_password_valid(password) for password in passwords]) schema_2 = sum([is_password_valid_two(password) for password in passwords]) print(f"Total Passwords: {len(passwords)}") print( f"Number of valid passwords for schema 1: {schema_1}" ) print(f"Number of valid passwords for schema 2: {schema_2}" ) if __name__ == "__main__": main()
true
1b120b65333495c5bd98f63e0e016942b419a708
DarshAsawa/ML-and-Computer-vision-using-Python
/Python_Basics/Roll_Dice.py
413
4.28125
4
import random no_of_dices=int(input("how many dice you want :")) end_count=no_of_dices*6 print("Since you are rolling %d dice or dices, you will get numbers between 1 and %d" % (no_of_dices,end_count)) count=1 while count==1 : user_inp=input("Do you want to roll a dice : ") if user_inp=="yes" or user_inp=="y" or user_inp=="Y": print("Your number is : %d" % random.randrange(1,end_count,1)) else : break
true
f1d228b0afac00ffc567698775fc594b8e2b1069
nischalshk/pythonProject2
/3.py
385
4.3125
4
""" 3. Write code that will print out the anagrams (words that use the same letters) from a paragraph of text.""" print("Question 3") string1 = input("Enter First String: ") string2 = input("Enter Second String: ") sort_string1 = sorted(string1.lower()) sort_string2 = sorted(string2.lower()) if sort_string1 == sort_string2: print("Anagram") else: print("Not Anagram")
true
e838332cbe89a89c11746c421c6b284c0c05af94
jkfer/LeetCode
/Find_Largest_Value_in_Each_Tree_Row.py
1,117
4.15625
4
""" You need to find the largest value in each row of a binary tree. """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None root = TreeNode(1) root.left = TreeNode(3) root.right = TreeNode(2) root.left.left = TreeNode(5) root.left.right = TreeNode(3) root.right.right = TreeNode(9) class Solution: def largestValues(self, root): result = [] ROOT = [root] def eval(root): result.append(max(root)) def traverse(ROOT): values = [] next_ROOT = [] for root in ROOT: if root: values.append(root.val) next_ROOT.append(root.left) next_ROOT.append(root.right) eval(values) if any(i != None for i in next_ROOT): traverse(next_ROOT) else: return if root: traverse(ROOT) return result S = Solution() x = S.largestValues(root) print(x)
true
ee1f838de3652e533b1600bce3fa33f59ad8d26d
Yasune/Python-Review
/Files.py
665
4.28125
4
#Opening and writing files with python #Files are objects form the class _io.TEXTIOWRAPPER #Opening and reading a file myfile=open('faketext.txt','r') #opening options : #'r' ouverture en lecture #'w' ouverture en ecriture #'a' ouverture en mode append #'b' ouverture en mode binaire print type(myfile) content=myfile.read() print(content) myfile.close() #close a file # myfile=open('faketext.txt','a') # myfile.write('SkillCorner is a badass company ') # myfile.close() #the right way to open a file with open('faketext.txt','r') as dumbtext: dumbcontent=dumbtext.read() print dumbcontent print myfile.closed #verify if file named myfile is closed
true
688c1740371fdc204941281724563f4c813b2ab7
Introduction-to-Programming-OSOWSKI/2-9-factorial-beccakosey22
/main.py
208
4.21875
4
#Create a function called factorial() that returns the factorial of a given variable x. def factorial(x): y = 1 for i in range (1, x + 1): y = y*i return y print(factorial(5))
true
bfa4cd171831f50848856dd016fb4fdf0461bc47
davidjeet/Learning-Python
/PythonHelloWorld/MoreLists 2/MoreLists_2.py
948
4.125
4
z = 'Demetrius Harris' for i in z: print(i,end = '*') print() eggs = ('hello', 323, 0.5) print(eggs[2]) #eggs[1] = 400 # illegal #converting tuple to list a = list(eggs) a[1] = 500 b = tuple(a) print(b) spam = 42 cheese = 100 print(spam) print(cheese) #different than spam, because by-value spam = [0,1,2,3,4,5] cheese = spam cheese[1] = 'Hello!' print(spam) print(cheese) #should be identical, because lists are reference types x = [[3,4,5,6],[7,8,9,10],9.1] y = x.copy() # z = x.deepcopy() y[1] = 'blah' print(x) print(y) # things to learn #1. lists are mutable, strings are not. So z[2] = 'g' is illegal #2. Tuples are like lists but use parens() not square brackets. #3. Tuples are also immutable. (line 7) #4. Use tuples to signal you don't want data changed, # also it optimzes Python for speed working with these. #5. convert to tuples/lists using list() and tuple(). See 10, 12 #6. variables are by-value, but lists are by reference
true
aa1d86e1bd876632b1db4d2d5f9381a162db051f
wavecrasher/Turtle-Events
/main.py
416
4.21875
4
import turtle turtle.title("My Turtle Game") turtle.bgcolor("blue") turtle.setup(600,600) screen = turtle.Screen() bob = turtle.Turtle() bob.shape("turtle") bob.color("white") screen.onclick(bob.goto) #bob.ondrag(bob.goto) screen.listen() #The pattern above consists of circles drawn repeatedly at different angles - #Declare a function to draw a circle - Use a while loop to draw a circle and turn repeatedly
true
b9bc55c14baaf0d0f11234c3c8593fe4b5a4ba47
Benzlxs/Algorithms
/sorting/merge_sort.py
1,103
4.125
4
# merge sortting https://en.wikipedia.org/wiki/Merge_sort import os import time def merge(left, right): # merging two parts sorted_list = [] left_idx = right_idx = 0 left_len, right_len = len(left), len(right) while (left_idx < left_len) and (right_idx < right_len): if left[left_idx] <= right[right_idx]: sorted_list.append(left[left_idx]) left_idx += 1 else: sorted_list.append(right[right_idx]) right_idx += 1 # merging together sorted_list = sorted_list + left[left_idx:] + right[right_idx:] return sorted_list def merge_sort(list_nums): if len(list_nums) <= 1: return list_nums mid = len(list_nums) // 2 left = merge_sort(list_nums[:mid]) right = merge_sort(list_nums[mid:]) return merge(left, right) if __name__=='__main__': # Verify it works random_list_of_nums = [120, 45, 68, 250, 176] print('Before sorting\n') print(random_list_of_nums) sorted_list = merge_sort(random_list_of_nums) print('After sorting\n') print(sorted_list)
true
cac68f6a0cb20080f211d0c83f6482a2827f60c7
Benzlxs/Algorithms
/sorting/selection_sort.py
784
4.40625
4
# merge sortting https://en.wikipedia.org/wiki/Selection_sort # time complexity is O(n^2) import os import time def selection_sort(list_nums): for i in range(len(list_nums)): lowest_value_index = i # loop through unsorted times for j in range(i+1, len(list_nums)): if list_nums[j] < list_nums[lowest_value_index]: lowest_value_index = j list_nums[i], list_nums[lowest_value_index] = list_nums[lowest_value_index], list_nums[i] #return list_nums if __name__=='__main__': # Verify it works random_list_of_nums = [120, 45, 68, 250, 176] print('Before sorting\n') print(random_list_of_nums) selection_sort(random_list_of_nums) print('After sorting\n') print(random_list_of_nums)
true
251b46112a4ba9c6983a3baa6545bd2f47a10edb
PersianBuddy/emailsearcher
/main.py
1,039
4.25
4
#! Python 3 # main.py - finds all email addresses import re , pyperclip # user guid print('Copy your text so it saves into clipboard') user_response = input('Are you ready? y=\'yes\' n=\'no\' :') while str(user_response).lower() != 'y': user_response = input("Make sure type 'y' when you copied your desired text :") # take text from clipboard sample_string = str(pyperclip.paste()) phone_reg_ex = re.compile('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}', re.VERBOSE) emails_list = re.findall(phone_reg_ex, sample_string) # convert list of emails to a string of emails emails_string = '' if len(emails_list) > 0: for email in emails_list: emails_string += email + '\n' pyperclip.copy(emails_string) print('\nThese email addresses copied to your clipboard so you can paste it anywhere') print('All email addresses available in your desired text') print(emails_string) else: print('\nThere is no email address in your desired text') print('Or maybe you just forgot to copy your desired text')
true
7ce7b8965c78c0e772953895bc81b4bd9023f15a
pezLyfe/algorithm_design
/intro_challenges/max_pairwise_product_2.py
615
4.15625
4
# Uses python3 ''' The starter file provided by the course used nested for loops to calculate the solution as a result, the submission failed due to an excessive runtime. The list.sort() method in python works really fast, so use that to order the list and then multiply the largest entry in the list by the second largest entry in the list ''' n = int(input()) a = [int(x) for x in input().split()] assert(len(a) == n) result = 0 a.sort() x = len(a) result = a[x-1] * a[x-2] '''for i in range(0, n): for j in range(i+1, n): if a[i]*a[j] > result: result = a[i]*a[j] ''' print(result)
true
d5af7c56bda22cef4a6855838d23b33ade9ef340
WilliamMcCann/holbertonschool-higher_level_programming
/divide_and_rule/h_fibonacci.py
520
4.21875
4
'''prints out the Fibonacci number for a given input''' import threading class FibonacciThread(threading.Thread): def __init__(self, number): threading.Thread.__init__(self) try: val = int(number) except ValueError: print("number is not an integer") self.number = val def run(self): a = 0 b = 1 for i in range(0, self.number): temp = a a = b b = temp + b print(str(self.number) + "=>" + str(a))
true
5ed3875dee928cc5a1b65ad7d9f1f582e2358660
ShruKin/Pre-Placement-Training-Python
/WEEK-3/1.py
215
4.625
5
# 1. Write a python program to check if a user given string is Palindrome or not. n = input("Enter a string: ") if(n == n[::-1]): print("Its a palindrome string") else: print("Its not a palindrome string")
true
9663393bb56c77a277bc1b62c44a3c6ae3b8b4ee
ShruKin/Pre-Placement-Training-Python
/WEEK-3/2.py
364
4.46875
4
# 2. Write a python program to take Firstname and lastname as input. # Check whether the first letter of both strings are in uppercase or not. # If not change accordingly and print reformatted string. fn = input('Firstname: ') ln = input('Lastname: ') if not fn[0].isupper(): fn = fn.title() if not ln[0].isupper(): ln = ln.title() print(fn + " " + ln)
true
ceaf2f949eb9840fbeed64d74c0cd37b808f5816
kb7664/Fibonacci-Sequence
/fibonacciSequence.py
673
4.3125
4
############################## # Fibinacci Sequence # # Author: Karim Boyd ############################## # This program demonstrates one of the many ways to build the Fibonacci # sequence using recursion and memoization # First import lru_cache to store the results of previous runs to # memory from functools import lru_cache # Set the dictionary to hold upto 1000 items in cache @lru_cache(maxsize = 1000) # Set up Fibinacci function def fibonacci(n): if n == 1: return 1 elif n == 2: return 1 elif n > 2: return fibonacci(n-1) + fibonacci(n-2) # Test the function for n in range (1, 1001): print(n, " : ", fibonacci(n))
true
d48b59a7708afea878e06c1d910ff304e2772316
hintermeier-t/projet_3_liberez_macgyver
/graph/maze.py
1,601
4.125
4
# -*coding: UTF-8-* """Module containing the MazeSpriteClass.""" import pygame as pg from . import gdisplay class MazeSprite (pg.sprite.Sprite): """Class displaying the maze sprite. Gathering all we need to display the walls sprites, and the path sprites. (position, source picture etc...). Inherit the pygame Sprite class. Attributes : sheet (Surface) : SpriteSheet used to design the walls and path. sheet_rect (Rect) : Area of the sprite. """ def __init__(self): """Class constructor. Class constructor whiwh resize the spritesheet to make the 20x20 tiles 2.5 times bigger (50x50). """ self.sheet, self.sheet_rect = gdisplay.load_image( "floor-tiles-20x20.png") self.sheet = pg.transform.scale(self.sheet, (1000, 650)) def print_maze(self, board, screen): """Method to display the entire maze. Args: board (GamingBoard): Core maze to get the walls and path positions. screen (Surface): Surface used to draw the maze. """ x = 0 y = 0 for i in range(226): if x > 1 and x % 15 == 0: x = 0 y += 1 if i in board._walls: # 300px from left, 80px from top, size_x, size_y screen.blit(self.sheet, (x * 50, y * 50), pg.Rect((650, 200, 50, 50))) if i in board._path: screen.blit(self.sheet, (x * 50, y * 50), pg.Rect((500, 0, 50, 50))) x += 1
true
be80b0aea58b2005699f667c15102be2d2398d42
riaz4519/python_practice
/programiz/_6_list.py
922
4.375
4
#list #create list myList = [5,6,7,8] print(myList) #mixed data type list myList = [5,8,'data',3.5] print(myList) #nested list myList = ['hello',[5,6]] print(myList) #accessing the list myList = ['p','r','o','b','e'] #by index print(myList[0]) #nested n_list = ["Happy", [2,0,1,5]] print(n_list[1][1]) print(n_list[1]) #negative print(myList[-1]) #slice list in python listSlice = ['p','r','o','g','r','a','m','i','z'] #index 0 upto index 3 print(listSlice[1:3]) #now begaining to last print(listSlice[:]) #a certain number to last print(listSlice[1:]) #change list or add list odd = [2, 4, 6, 8] #change the 1st item odd[0] =1 print(odd) odd[1:4] = [3,4,5] print(odd) #append list odd.append(7) print(odd) #len print(len(odd)) #extend odd.extend([9,10,11]) print(odd) #using + operator to extend odd = odd + [1,5,6] print(odd) #repeat number print(odd * 3) #insert odd.insert(1,10)
true
51eb5831e885cff30bdefa175b7ba153222156ac
CupidOfDeath/Algorithms
/Bisection Search.py
402
4.15625
4
#Finding the square root of a number using bisection search x = int(input('Enter the number which you want to find the square root of: ')) epsilon = 0.01 n = 0 low = 1 high = x g = (low+high) / 2 while abs(g*g-x) >= epsilon: if (g*g) > x: high = g elif (g*g) < x: low = g g = (low+high) / 2 n += 1 print('The square root of', x, 'is', g) print('The number of computations it took is', n)
true
42a8dcd380e302595f43a72bea8eb5c0c0a1fff3
mightymax/uva-inleiding-programmeren
/module-1-numbers/sequence.alt.py
1,530
4.25
4
highestPrime = 10000 number = 1 #Keep track of current number testing for prime nonPrimes = [] while number < highestPrime: number = number + 1 if (number == 2 or number % 2 != 0): #test only uneven numbers and 2 #loop thru all integers using steps of 2, no need to test even numbers for x in range(3, number, 2): if (number % x) == 0: #Number {number} is not a prime nonPrimes.append(number) break else: nonPrimes.append(number) i = 0 tmpList = [] #temporary list used in for-loop to keep track of current sequence tempSeqCount = 1 longestSeq = [] #placeholder for final result longestSeqCount = 0 for nonPrime in nonPrimes: # compare current non-prime against previous non-prime # if previous == current - 1 then it is part of seq if i > 0 and nonPrime - 1 == nonPrimes[i-1]: tmpList.append(nonPrime) tempSeqCount += 1 #increase seq counter else: # seq has endend, move temp list to placeholder if it's size is bigger than previous placeholder's size if tempSeqCount > longestSeqCount: longestSeq = tmpList longestSeqCount = tempSeqCount #create new tmp-list for next seq test and reset counter tmpList = [nonPrime] tempSeqCount = 1 i += 1 print(f"The longest sequence non-primes under {highestPrime} starts at {longestSeq[0]} and ends at {longestSeq[longestSeqCount-1]}") print(f"The sequence is {longestSeqCount} long.")
true
0bca3a56b899c73b9f63201d6eb1cb0070976972
lasj00/Python_project
/OOP.py
1,965
4.1875
4
import math class Rectangle: # the init method is not mandatory def __init__(self, a, b): self.a = a self.b = b # self.set_parameters(10,20) def calc_surface(self): return self.a * self.b # Encapsulation class Rectangle2(): def __init__(self, a, b): self.__a = a self.__b = b # self.set_parameters(10,20) def calc_surface(self): return self.__a * self.__b r = Rectangle2(4, 6) r.__a = 10 # can't change the parameters - the field (__a) cannot be accessed - creates another filed inside the object r.a = 10 # a is created as a different value print(r.calc_surface()) # Special methods class Rectangle3: def __init__(self, a, b): self.a = a self.b = b def calc_surface(self): return self.a * self.b def __str__(self): return "Rect: {0} by {1}".format(self.a, self.b) def __add__(self, other): a = self.a + other.a b = self.b + other.b return Rectangle(a, b) def __lt__(self, other): self_area = self.calc_surface() other_area = other.calc_surface() return self_area < other_area r1 = Rectangle3(4, 6) r2 = Rectangle3(6, 8) r = r1 + r2 print(r) print(r2 < r1) # inheritance class Shape: def __init__(self, a=0, b=0): self._a = a self._b = b def get_a(self): return self._a def get_b(self): return self._b def __str__(self): return "{0}: [{1},{2}]".format(self.__class__.__name__, self._a, self._b) class RectangleIn(Shape): def calc_surface(self): return self._a * self._b class Circle(Shape): def calc_surface(self): return math.pi * self._a ** 2 # example of polymorphism def __str__(self): return "{0}: [{1}]".format(self.__class__.__name__, self._a) s = Shape(4, 5) r = RectangleIn(4, 5) print(r.calc_surface()) c = Circle(5) print(c.calc_surface())
true
b451055efe0de3395b4c49beb4d67ee77694bece
KaylaBaum/astr-119-hw-1
/variables_and_loops.py
706
4.375
4
import numpy as np #we use numpy for many things def main(): i = 0 #integers can be declared with a number n = 10 #here is another integer x = 119.0 #floating point nums are declared with a "." #we can use numpy to declare arrays quickly y = np.zeros(n,dtype=float) #declares 10 zeros as floats using np #we can use for loops to iterate with a variable for i in range(n): #i in range [0,n-1] y[i] = 2.0 * float(i) + 1. #set y = 2i+1 as floats #we can also simply iterate through a variable for y_element in y: print(y_element) #execute the main function if __name__ == "__main__": main()
true
5fd79aec14f570b55d10153e52c7d67e751d5877
ch1huizong/study
/lang/py/cookbook/v2/19/merge_source.py
1,096
4.1875
4
import heapq def merge(*subsequences): # prepare a priority queue whose items are pairs of the form # (current-value, iterator), one each per (non-empty) subsequence heap = [] for subseq in subsequences: iterator = iter(subseq) for current_value in iterator: # subseq is not empty, therefore add this subseq's pair # (current-value, iterator) to the list heap.append((current_value, iterator)) break # make the priority queue into a heap heapq.heapify(heap) while heap: # get and yield lowest current value (and corresponding iterator) current_value, iterator = heap[0] yield current_value for current_value in iterator: # subseq is not finished, therefore add this subseq's pair # (current-value, iterator) back into the priority queue heapq.heapreplace(heap, (current_value, iterator)) break else: # subseq has been exhausted, therefore remove it from the queue heapq.heappop(heap) if __name__ == '__main__': r = merge([102,1,50,3,7],[11,2,5,6],[3,3,-2,-3]) print list(r)
true
5afb03eae042cc84d9c770e3153fa07d12884906
shashikant231/100-Days-of-Code-
/Pascal Traingle.py
938
4.1875
4
'''Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: Example 1: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] solution We are first creating an 2D array .our array after creation for rows = 5 will look like follows: [[0], [0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0]] we will iterate through each rows and according to the position of "i" pointer ,we will put values. ''' #non recursive solution def generate(numRows): arr = [] for i in range(numRows): col = [] for j in range(i+1): col.append(0) arr.append(col) for line in range(0,numRows): for i in range(0,line+1): if i == 0 or i == line: arr[line][i] = 1 else: arr[line][i] = arr[line-1][i-1] + arr[line-1][i] return arr
true
6763a48aa0e4c976e75b68ae74f18394512b1e85
DrN3RD/PythonProgramming
/Chapter 3/c03e01.py
378
4.34375
4
#Volume calculator from math import * def main(): r = float(input("Enter the radius of the shpere to be calculated: ")) volume = (4/3)*pi*(r**3) area = 4*pi * r**2 print("The area of the Shpere is {0:0.1f} square meters ".format(area)) print("\n The Volume of the sphere is {0:0.1f} cubic meters".format(volume)) input("Enter to quit") main()
true
1ae36388c286daad1d37d101d9ca05db4bd7384a
mamatha20/ifelse_py
/IF ELSE_PY/if else4.py
276
4.34375
4
#write a program to check whethernit is alphabet digit or special character ch=input("enter any character=") if ch>="a" and ch<="z" or ch>="A" and ch<="Z": print("it is alphabet") elif ch>="0" and ch<="9": print("it is digit") else: print("it is special charcter")
true
75c9868ff8d055492da5bb749b20d5a919a440e8
mamatha20/ifelse_py
/IF ELSE_PY/if else25.py
658
4.125
4
day=input('enter any day') size=input('enter any size') if day=='sunday': if size=='large': print('piza with free brounick') elif size=='medium': print('piza with free garlick stick') else: print('free coca') elif day=='monday' or day=='tuesday': if size=='large': print('pizza with 10%discount') elif size=='medium': print('pizza with 20%discount') else: print('pizza without discount') elif day=='wednseday' or day=='Thursday': if size=='large'or size=='medium' or size =='small': print('pizza with garlic stick and coce free') elif day=='friday' or day=='saturday': if size=='large': print('pizza only') else: print('invalid day')
true
a566f238d1a9cc97699986160a108e3c9e88cbd5
yameenjavaid/bigdata2019
/01. Jump to python/Chap07/3_Python_Exercise/21.py
281
4.21875
4
import re # Write a Python program to find the substrings within a string. while True : original_setence = input("입력하세요 : ") if original_setence == "ㅈㄹ" : exit() m = re.findall("exercises", original_setence) for i in m : print(i)
true
9d6ea6b45c26fccabafd08a13e39d54ce906f918
yameenjavaid/bigdata2019
/01. Jump to python/Chap07/3_Python_Exercise/18.py
342
4.40625
4
import re # Write a Python program to search the numbers (0-9) of length between 1 to 3 in a given string. p = re.compile(r"([0-9]{1,3})") while True : original_setence = input("입력하세요 : ") if original_setence == "ㅈㄹ" : exit() m = p.finditer(original_setence) for i in m : print(i.group(0))
true
8822adfd5f0a1d8732e8fa92f0834af2de2764e2
shaheenery/udacity_ds_and_a_project2
/problem_5.py
2,548
4.375
4
# Blockchain # A Blockchain is a sequential chain of records, similar to a linked list. Each # block contains some information and how it is connected related to the other # blocks in the chain. Each block contains a cryptographic hash of the previous # block, a timestamp, and transaction data. For our blockchain we will be using # a SHA-256 hash, the Greenwich Mean Time when the block was created, and text # strings as the data. # Use your knowledge of linked lists and hashing to create a blockchain # implementation. import time import hashlib # We do this for the information we want to store in the block chain such as # transaction time, data, and information like the previous chain. class Block: def __init__(self, timestamp, data, previous): self.timestamp = timestamp self.data = data self.previous_hash = previous.hash self.previous = previous self.hash = self.calc_hash() def calc_hash(self): sha = hashlib.sha256() hash_str = "" hash_str += self.data hash_str += str(self.timestamp) hash_str += self.previous_hash hash_str = hash_str.encode('utf-8') sha.update(hash_str) return sha.hexdigest() def __repr__(self): return f"{str(int(self.timestamp * 100) / 100)}\t{self.hash}\t{self.previous_hash}\t{self.data}" class DummyBlock(Block): def __init__(self): self.timestamp = time.time() self.data = "I am Groot" self.previous_hash = "DummyHashDummyHashDummyHashDummyHashDummyHashDummyHashDummyHashD" self.previous = None self.hash = self.calc_hash() class BlockChain(object): def __init__(self): self.tail = DummyBlock() self.size = 0 def append(self, data): old = self.tail new = Block(time.time(), data, old) self.tail = new self.size += 1 def __repr__(self): if self.size == 0: return "Block Chain Empty" str = "" block = self.tail.previous while block: str += block.__repr__() + "\n" block = block.previous return str # Test 1 - Empty Blockchain chain = BlockChain() print(chain) # Block Chain Empty print (chain.size) # 0 print (chain.tail.data) # I am Groot # Test 2 - 4 Blocks in chain chain.append("Rocket") chain.append("Star Lord") chain.append("Gemorrah") chain.append("Drax") print (chain) # Drax # Test 3 - 10k blocks for _ in range(10_000): chain.append("something else!") print(chain)
true
efce9bd907d2493ea03807cd09ef298ac5facf58
zoecahill1/pands-problem-set
/collatz.py
1,060
4.34375
4
# Zoe Cahill - Question 4 Solution # Imports a function from PCInput which was created to handle user input from PCInput import getPosInt def collatz1(): # Calls the function imported above # This function will check that the number entered is a positive integer only num = getPosInt("Please enter a positive number: ") # Check will run until number gets to 1 while num!=1: # Prints the current value of num. Have to cast int type as anything divided becomes a float type. print(int((num))) # Checking to see if number is even (there will be no remainder if it is) if num%2 == 0: # If this check returns true then program will divide num by 2 num=num/2 # Otherwise then number is not even so it must be odd else: # When number is odd we multiply by 3 and add 1 num = (num*3)+1 # Returns control to beginning of loop to check next number continue # Prints out last number which will be 1 print (int((num))) collatz1()
true
f9dfbf8b29d1a1673076aa512e2d89653af38b6a
codeshef/SummerInternship
/Day5/classesPython.py
483
4.125
4
# <------- Day 8 work -------> # classes in python class User: def __init__(self): print("Hello!! I am constructor of class user") def setUserName(self, fn, ln): print("I am inside setUserNameFunc") self.firstName = fn self.lastName = ln def printData(self): print(self.firstName+" "+self.lastName) ## Creating objects objUser = User() ## Calling class functions objUser.setUserName("abc", "xyz") objUser.printData()
true
bc502be94ca45d1750cce48ca3c39f0eb9dd389c
dergaj79/python-learning-campus
/unit5_function/test.py
959
4.125
4
# animal = "rabbit" # # def water(): # animal = "goldfish" # print(animal) # # water() # print(animal) # a = 0 # # # def my_function() : # a = 3 # print(a) # # # my_function() # print(a) # a=1 # def foo1(): # print(a) # foo1() # print(a) # def amount_of_oranges(small_cups=20, large_cups=10): # oranges_result=small_cups+large_cups*3 # kg_result=oranges_result/5 # print("Today you'll need",oranges_result,"oranges.") # print("Buy",kg_result,"kg of oranges.") # return oranges_result,kg_result # # results=amount_of_oranges(15,5) # print(type(results)) # print(results) def main(): # City forcast generator program city_name = get_city_from_user() valid_city = is_city_valid(city_name) if not valid_city: print("Error! Wrong City!") return None temperature = get_current_weather(city_name) # Show forecast for the user show_weather(temperature, city_name) if __name__ == "__main__": main()
true
9f8220cbed18b0e05822ae99a652b649c682b08f
sandeeppal1991/D08
/mimsmind0.py
2,527
4.5625
5
"""In this version, the program generates a random number with number of digits equal to length. If the command line argument length is not provided, the default value is 1. Then, the program prompts the user to type in a guess, informing the user of the number of digits expected. The program will then read the user input, and provide basic feedback to the user. If the guess is correct, the program will print a congratulatory message with the number of guesses made and terminate the game. Otherwise, the program will print a message asking the user to guess a higher or lower number, and prompt the user to type in the next guess.""" ############################################################################### #import section from random import randint import sys ############################################################################### #Body #function to generate a random n digit number where n is entered by the user or 1 def generate_random_number(no_of_digits): return randint(10**(no_of_digits-1),(10**no_of_digits)-1) def the_game(random_number,no_of_digits): print("Let's play the mimsmind0 game.") #starting of the game user_input = input("Guess a {} digit number : ".format(no_of_digits)) no_of_tries = 0 while True: try: user_input = int(user_input) except: #exception raised if user input is not an integer user_input = input("Invalid Input. Try again : ") continue no_of_tries += 1 #case when the guessed number is the same as the guessed number if(user_input == random_number): print("Congratulations ! You guessed the number in {} tries".format(no_of_tries)) break #case when the number guessed is lower than the random number elif(user_input < random_number): user_input = input("Try Again ! Guess a higher number : ") #case when the number guessex is higher than the random number elif(user_input > random_number): user_input = input("Try Again ! Guess a lower number : ") ############################################################################### #main def main(): no_of_digits = 1 try: if(int(sys.argv[1]) > 0): no_of_digits = int(sys.argv[1]) except: print("The no of digits you entered isnt a valid input. We will proceed with 1 digit for now") the_game(generate_random_number(no_of_digits),no_of_digits) if __name__ == "__main__": main()
true
46888f48af85aa51067e50b537e670510dad01c8
asuddenwhim/DM
/own_text.py
776
4.125
4
from nltk import word_tokenize, sent_tokenize text = "Generally, data mining (sometimes called data or knowledge discovery) is the process of analyzing data from different perspectives and summarizing it into useful information - information that can be used to increase revenue, cuts costs, or both. Data mining software is one of a number of analytical tools for analyzing data. It allows users to analyze data from many different dimensions or angles, categorize it, and summarize the relationships identified. Technically, data mining is the process of finding correlations or patterns among dozens of fields in large relational databases. " sents = sent_tokenize(text) tokens = word_tokenize(text) textObj = Text(tokens) print len(sents) print len(tokens) print textObj
true
1e7db90033a0f66814ddd3eada5fbaf26424755d
rashedrahat/wee-py-proj
/hangman.py
1,407
4.25
4
# a program about guessing the correct word. import random i = random.randint(0, 10) list = [["H*ng*a*", "Hangman"], ["B*n**a", "Banana"], ["*wk*ar*", "Awkward"], ["B*n**", "Banjo"], ["Ba*pi*e*", "Bagpipes"], ["H*p**n", "Hyphen"], ["J*k*b*x", "Jukebox"], ["O*y**n", "Oxygen"], ["Num*sk*l*", "Numbskull"], ["P*j*m*", "Pajama"], ["Rh*t*m*c", "Rhythmic"]] print("Welcome to HANGMAN game :)") print("Guess the below word..") print(list[i][0]) print("You have only one attempt to guess!") while True: left = input("Enter the left hidden letter: ") mid = input("Enter the mid hidden letter: ") right = input("Enter the right hidden letter: ") if len(left) == 0 or len(mid) == 0 or len(right) == 0: print("Empty field(s) not allowed! Please type a letter.") continue elif len(left) > 1 or len(mid) > 1 or len(right) > 1: print("More than one letter(s) not allowed! Please type only a letter.") continue else: letters = [left, mid, right] pos = 0 word = list[i][0] guess_word = "" for l in word: if l == "*": guess_word = guess_word + letters[pos] pos += 1 else: guess_word = guess_word + l guess_word = guess_word.capitalize() if guess_word == list[i][1]: print("Hurrah! You guessed the correct word '", guess_word, "'") break else: print("Sorry! Better luck next time.", "The word is:", list[i][1]) break
true
ae8899b2735de9b712b11e1e20f95afcd5008be2
erikac613/PythonCrashCourse
/11-1.py
483
4.15625
4
from city_functions import city_country print("Enter 'q' at any time to quit.") while True: city = raw_input("\nPlease enter the name of a city: ") if city == 'q': break country = raw_input("Please enter the name of the country where that city is located: ") if country == 'q': break formatted_city_and_country = city_country(city, country, population='') print("\tNeatly formatted location: " + formatted_city_and_country + ".")
true
6db90e6de92dc5a3ca12f22a6e94577abd42a6c1
gungorefecetin/CS-BRIDGE-2020
/Day3PM - Lecture 3.1/khansole_academy.py
1,021
4.375
4
""" File: khansole_academy.py ------------------- This program generates random addition problems for the user to solve, and gives them feedback on whether their answer is right or wrong. It keeps giving them practice problems until they answer correctly 3 times in a row. """ # This is needed to generate random numbers import random def main(): # Your code here # Delete the `pass` line before starting to write your own code counter = 0 while True: num1, num2 = random.randint(10, 99), random.randint(10, 99) answer = int(input('What is ' + str(num1) + ' + ' + str(num2) + '? ')) if answer == num1 + num2: counter += 1 print("Correct! You've gotten " + str(counter) + " correct in a row.") else: print('Incorrect. The expected answer is ' + str(num1 + num2)) counter = 0 if counter == 3: print('Congratulations! You mastered addition.') break if __name__ == "__main__": main()
true
52963e18085b20a2f20020a0093b01ea26e34e0c
LucianoAlbanes/AyEDI
/TP1/Parte1/1/restrictions.py
250
4.125
4
## The purpose of the following code is to have certain functions ## that python provides, but they are restricted in the course. # Absolute Value (Aka 'abs()') def abs(number): if number < 0: return number*-1 else: return number
true
6735f531a626eb2dd8999e26136e950299a978d4
LucianoAlbanes/AyEDI
/TP6/1/fibonacci.py
1,058
4.25
4
# Calc the n-th number of the Fibonacci sequence def fibonacci(n): ''' Explanation: This function calcs and return the number at a given position of the fibonacci sequence. Params: n: The position of the number on the fibonacci sequence. Return: The number at the given position of the fibonacci sequence. Returns 'None' if the given position is negative or non a integer. ''' # Base cases if (n == 0) or (n == 1): return n # Case if negative or non integer if (n < 0) or (n % 1): return None # General case return fibonacci(n-1) + fibonacci(n-2) # Basic interface from algo1 import input_real result = None while result == None: result = fibonacci(input_real( 'Ingrese la posición del número a obtener en la secuencia de fibonacci: ')) if result == None: print('El número ingresado no es válido. (Debe ser un número entero positivo).') print( f'El número de fibonacci que corresponde a la posición dada es: {int(result)}')
true
c828a8ab988f60b7a7c73a79ca678e5d7264415e
navbharti/java
/python-cookbook/other/ex7.py
2,366
4.1875
4
''' Created on Sep 19, 2014 @author: rajni ''' months = ('January','February','March','April','May','June',\ 'July','August','September','October','November',' December') print months cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester'] print cats #fetching items from tupble and list print cats[2] print months[2] #appending items in list cats.append('Catherine') print cats #Remove your 2nd cat, Snappy. Woe is you. del cats[1] print cats #Make the phone book: #this nothing but dictionary phonebook = {'Andrew Parson':8806336, \ 'Emily Everett':6784346, 'Peter Power':7658344, \ 'Lewis Lame':1122345} print phonebook print phonebook['Emily Everett'] #Add the person 'Gingerbread Man' to the phonebook: phonebook['Gingerbread Man'] = 1234567 # Didn't think I would give you # my real number now, would I? print phonebook # deleting item in the dictionary del phonebook['Andrew Parson'] print phonebook #A few examples of a dictionary #First we define the dictionary #it will have nothing in it this time ages = {} #Add a couple of names to the dictionary ages['Sue'] = 23 ages['Peter'] = 19 ages['Andrew'] = 78 ages['Karren'] = 45 #Use the function has_key() - #This function takes this form: #function_name.has_key(key-name) #It returns TRUE #if the dictionary has key-name in it #but returns FALSE if it doesn't. #Remember - this is how 'if' statements work - #they run if something is true #and they don't when something is false. if ages.has_key('Sue'): print "Sue is in the dictionary. She is", \ ages['Sue'], "years old" else: print "Sue is not in the dictionary" #Use the function keys() - #This function returns a list #of all the names of the keys. #E.g. print "The following people are in the dictionary:" print ages.keys() #You could use this function to #put all the key names in a list: keys = ages.keys() #You can also get a list #of all the values in a dictionary. #You use the values() function: print "People are aged the following:", \ ages.values() #Put it in a list: values = ages.values() #You can sort lists, with the sort() function #It will sort all values in a list #alphabetically, numerically, etc... #You can't sort dictionaries - #they are in no particular order print keys keys.sort() print keys print values values.sort() print values #You can find the number of entries #with the len() function: print "The dictionary has", \ len(ages), "entries in it"
true
fc7dd582f1d3fcff14bd071ddf53081faa20488a
mrmezan06/Python-Learning
/Real World Project-2.py
364
4.25
4
# Design a program to find avarage of three subject marks x1 = int(input("Enter subject-1 marks:")) x2 = int(input("Enter subject-2 marks:")) x3 = int(input("Enter subject-3 marks:")) sum = x1 + x2 + x3 avg = sum / 3 print("The average marks:", int(avg)) print("The average marks:", avg) # Formatting the float value print("The average marks:", format(avg, '.2f'))
true
c765b56d4d457bd428b05d59a0c882ccf7325910
kkkansal/FSDP_2019
/DAY 02/pangram.py
956
4.21875
4
""" Code Challenge Name: Pangram Filename: pangram.py Problem Statement: Write a Python function to check whether a string is PANGRAM or not Take input from User and give the output as PANGRAM or NOT PANGRAM. Hint: Pangrams are words or sentences containing every letter of the alphabet at least once. For example: "The quick brown fox jumps over the lazy dog" is a PANGRAM. Input: The five boxing wizards jumps. Output: NOT PANGRAM """ # To check if a string is pangram or not input_string = input("Enter the string :") count = 0 _list = [] _lower = input_string.lower() for alpha in _lower: _list.append(alpha) # remove duplicates final_list = [] for num in _list: if num not in final_list: final_list.append(num) for elements in final_list: if elements in 'abcdefghijklmnopqrstuvwxyz': count += 1 if count == 26: print ("Pangram") else: print ("Not Pangram")
true
0e58b02c59fe57bf55e8c1c61a0442f35146876f
dev-di/python
/helloworld.py
323
4.1875
4
#name = input("What is your name my friend? ") name = "Diana" message = "Hello my friend, " + name + "!" print(message) #comment print(message.upper()) print(message.capitalize()) print(message.count("i")) print(f"message = '{message}', name = '{name}'") print("Hello {}!!".format(name)) print("Hello {0}!".format(name))
true
6cf6799c4f652c47a3cb818ab1910b4c8d3d6d1c
JustinTrombley96/Python-Coding-Challenges
/drunk_python.py
730
4.1875
4
''' Drunken Python Python got drunk and the built-in functions str() and int() are acting odd: str(4) ➞ 4 str("4") ➞ 4 int("4") ➞ "4" int(4) ➞ "4" You need to create two functions to substitute str() and int(). A function called int_to_str() that converts integers into strings and a function called str_to_int() that converts strings into integers. Examples: int_to_str(4) ➞ "4" str_to_int("4") ➞ 4 int_to_str(29348) ➞ "29348" Notes This is meant to illustrate the dangers of using already-existing function names. Extra points if you can de-drunk Python. ''' str, int = int, str def int_to_str(n): return str(n) def str_to_int(s): return int(s) print(int_to_str(25)) print(int_to_str('25'))
true
94db4a5c592136be5afeccac3323c5c598e41900
STProgrammer/PythonExercises
/Rock Paper Scissor.py
1,571
4.125
4
import random print("Welcome to \"Rock Paper Scissor\" game") print("""Type in "rock", "paper", or "scissor" and see who wins. first one that win 10 times win the game.""") HandsList = ["rock", "paper", "scissor"] while True: x = int() #Your score y = int() #Computer's score while x < 10 and y < 10: hand1 = input("Type in your choice:" ) hand2 = random.choice(HandsList) print(hand1, " - ",hand2) if hand1 == hand2: print("It's a tie!") elif hand1 == "rock": if hand2 == "scissor": print("Rocks beats scissor. You score!") x += 1 else: print("Paper beats rock, computer scores!") y += 1 elif hand1 == "paper": if hand2 == "rock": print("Paper beats rock, you score!") x += 1 else: print("Scissor beats paper, computer scores!") y += 1 elif hand1 == "scissor": if hand2 == "paper": print("Scissor beats paper, you score!") x += 1 else: print("Rock beats scissor, computer scores!") y += 1 else: print("""Invalid input. Plese type in: "rock", "paper" or "scissor".""") continue print("You: ", x, " - ", y, " computer") if x == 10: print("You win the game!") if y == 10: print("you lose the game!") print("Let's play again")
true
8f7e92a384cf95b4b45ee3eb41d0edf8afdb38ff
Esther-Guo/python_crash_course_code
/chapter4-working with lists/4.10-slices.py
265
4.40625
4
odd = list(range(1,21,2)) for number in odd: print(number) print('The first three items in the list are: ') print(odd[:3]) print('Three items from the middle of the list are: ') print(odd[4:7]) print('The last three items in the list are: ') print(odd[-3:])
true
0777824a168e8bc5eabcb35a58e2c6aa62e122d2
Esther-Guo/python_crash_course_code
/chapter8-functions/8.8-user_albums.py
651
4.21875
4
def make_album(name, title, tracks=0): """builds a dictionary describing a music album""" album_dict = { 'artist name': f'{name.title()}', 'album title': f'{title.title()}' } if tracks: album_dict['tracks'] = tracks return album_dict name_prompt = 'Please input the name of the artist:("q" to exit) ' title_prompt = 'Please input the title of the album:("q" to exit) ' while True: name = input(name_prompt) if name == 'q': break title = input(title_prompt) if title == 'q': break album = make_album(name, title) print(album) print('Thanks for your respond.')
true
5e29635e085e9f0199f8e7e6b7e97e47fae30fcd
hefeholuwah/wejapa_internship
/Hefeholuwahwave4 lab/Scripting labs/match_flower_name.py
1,388
4.34375
4
#For the following practice question you will need to write code in Python in the workspace below. This will allow you to practice the concepts discussed in the Scripting lesson, such as reading and writing files. You will see some older concepts too, but again, we have them there to review and reinforce your understanding of those concepts. #Question: Create a function that opens the flowers.txt, reads every line in it, and saves it as a dictionary. The main (separate) function should take user input (user's first name and last name) and parse the user input to identify the first letter of the first name. It should then use it to print the flower name with the same first letter (from dictionary created in the first function). #Sample Output: #>>> Enter your First [space] Last name only: Bill Newman #>>> Unique flower name with the first letter: Bellflower # Write your code here # HINT: create a dictionary from flowers.txt # HINT: create a function def user(): dictionary = {} with open('flowers.txt') as file: for names in file: (key,value) = names.split(": ") dictionary[key.upper()] = value return dictionary def my_main(): dictionary = user() user_input = input("Enter your first [space] last name only:") print("unique flower name with first letter : {}".format(dictionary.get(user_input[0]))) my_main()
true
73c3bcce9c5509b858bb2d149ded24f592b78207
xuyichen2010/Leetcode_in_Python
/general_templates/tree_bfs.py
1,170
4.1875
4
# https://www.geeksforgeeks.org/level-order-tree-traversal/ # Method 1 (Use function to print a given level) # O(n^2) time the worst case # Because it takes O(n) for printGivenLevel when there's a skewed tree # O(w) space where w is maximum width # Max binary tree width is 2^h. Worst case when perfect binary tree # Worst cas value 2^h is ceil(n/2) # When tree is balanced BFS takes more space from collections import deque class Node : def __init__(self, v): self.val = v self.left = None self.right = None def printLevelOrder(self, root): h = self.height(root) for i in range (1, h+1): self.printGivenLevel(root, i) def height(self, node): if node is None: return 0 else: lheight = self.height(node.left) rheight = self.height(node.right) return max(lheight, rheight) + 1 def printGivenLevel(self, node, level): if node is None: return if level == 1: print(node.val) else: self.printGivenLevel(node.left, level-1) self.printGivenLevel(node.right, level-1)
true
c03486f525084d5fd5f06c48f371db8cbdfa9666
phganh/CSC110---SCC
/Labs/Lab 3/coffeeShop.py
984
4.15625
4
# Project: Lab 03 (TrinhAnhLab03Sec03.py) # Name: Anh Trinh # Date: 01/20/2016 # Description: Calculate the cost of a coffee # shop's products def coffeeShop(): #Greeting print("Welcome to the Konditorei Coffee Shop!\n") #User's Input fltPound = float(input("Enter the amount of coffee (in pounds): ")) print() #Set Variables Value fltPrice = 10.50 * fltPound #$10.50 per pound fltShippingFee = 0.86 * fltPound #$0.86 per pound fltOverhead = 1.50 #fixed cost fltTotal = fltPrice + fltOverhead + fltShippingFee #Display The Result - round up to 2nd decimal place print("Amount : " , fltPound , "lb(s)") print("Price : $" , round(fltPrice,2) ) print("Shipping fee: $" , round(fltShippingFee,2) ) print("Overhead fee: $" , fltOverhead) print("--------------------------") print("Total: $" , round(fltTotal,2) ) coffeeShop()
true
4a0989e726ccdea9ec4b69028dd3f5b1c5e54312
ccchao/2018Spring
/Software Engineering/hw1/good.py
858
4.34375
4
""" 1. pick a list of 100 random integers in the range -500 to 500 2. find the largest and smallest values in the list 3. find the second-largest and second-smallest values in the list 4. calculate the median value of the elements in the list """ import random #Generate a list containing 100 randomly generated integers ranged between -500 and 500 intList = [] for i in range(100): intList.append(random.randint(-500,500)) #Sort the list to find the largest two, the smallest two, and the median values intList.sort() #Show the result print("The largest value in the list:", intList[0]) print("The smallest value in the list:", intList[-1]) print("The second-largest value in the list:", intList[1]) print("The second-smallest value in the list:", intList[-2]) print("the median value of the elements in the list:", (intList[49]+intList[50])/2)
true
1a5decdca960e40d6c0bd1939d4461176a7fee70
parastooveisi/CtCI-6th-Edition-Python
/Linked Lists/palindrome.py
1,202
4.1875
4
# Implement a function to check if a linked list is a palindrome class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def printList(self): curr = self.head while curr: print(curr.data) curr = curr.next def append(self, data): newNode = Node(data) if not self.head: self.head = newNode return lastNode = self.head while lastNode.next: lastNode = lastNode.next lastNode.next = newNode def palindrome(self): hashMap = {} curr = self.head while curr: if curr.data in hashMap: hashMap[curr.data] += 1 else: hashMap[curr.data] = 1 curr = curr.next countOdds = 0 for value in hashMap.values(): if value % 2 != 0: countOdds += 1 return countOdds <= 1 llist = LinkedList() llist.append("R") llist.append("A") llist.append("D") llist.append("A") llist.append("R") llist.append("R") print(llist.palindrome()) # False
true
5819dbb5b6c308ac62f478185a3d52718832a533
jbehrend89/she_codes_python
/functions/functions_exercises.py
429
4.125
4
# Q1)Write a function that takes a temperature in fahrenheitand returns the temperature in celsius. def convert_f_to_c(temp_in_f): temp_in_c = (temp_in_f - 32) * 5 / 9 return round(temp_in_c, 2) print(convert_f_to_c(350)) # Q2)Write a function that accepts one parameter (an integer) and returns True when that parameter is odd and False when that parameter is even. def odd(x): return x % 2 == 1 print(odd(4))
true
9dcd83d636b054f122adb049fb0ecb97b342d3f4
nishanthegde/bitesofpy
/105/slicing.py
1,848
4.3125
4
from string import ascii_lowercase text = """ One really nice feature of Python is polymorphism: using the same operation on different types of objects. Let's talk about an elegant feature: slicing. You can use this on a string as well as a list for example 'pybites'[0:2] gives 'py'. The first value is inclusive and the last one is exclusive so here we grab indexes 0 and 1, the letter p and y. When you have a 0 index you can leave it out so can write this as 'pybites'[:2] but here is the kicker: you can use this on a list too! ['pybites', 'teaches', 'you', 'Python'][-2:] would gives ['you', 'Python'] and now you know about slicing from the end as well :) keep enjoying our bites! """ another_text = """ Take the block of text provided and strip() off the whitespace at the ends. Split the whole block up by newline (\n). if the first character is lowercase, split it into words and add the last word of that line to the results list. Strip the trailing dot (.) and exclamation mark (!) from the word first. finally return the results list! """ def slice_and_dice(text: str = text) -> list: """Get a list of words from the passed in text. See the Bite description for step by step instructions""" results = [] lines = [l.lstrip() for l in text.split('\n')] for l in lines: # print(l[:1], l[:1].islower()) if l[:1].islower(): words_lower = [word for word in l.split()] results.append(words_lower[-1].replace('.', '').replace('!', '')) # is_first_lower = [c for l in lines for c in l[:1]] return results # def main(): # print('here ..') # actual = slice_and_dice(text) # print(actual) # actual = slice_and_dice(another_text) # print(actual) # if __name__ == '__main__': # main()
true
1ad2e7463aff6086e9506fe45d87a94b0d6b9226
nishanthegde/bitesofpy
/9/palindrome.py
1,805
4.21875
4
"""A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward""" import os import urllib.request as ur import re local = '/tmp' # local = os.getcwd() DICTIONARY = os.path.join(local, 'dictionary_m_words.txt') ur.urlretrieve('http://bit.ly/2Cbj6zn', DICTIONARY) def prep_word(word): """Prep the word for the palindrome test 1. case insensitive 3. strip /n 2. remove non-alpha numeric """ word = word.strip().casefold() word = re.sub(r'[^a-zA-Z0-9]','',word) return word def load_dictionary(): """Load dictionary (sample) and return as generator (done)""" with open(DICTIONARY,'r') as f: return [prep_word(w) for w in f.readlines()] def is_palindrome(word): """Return if word is palindrome, 'madam' would be one. Case insensitive, so Madam is valid too. It should work for phrases too so strip all but alphanumeric chars. So "No 'x' in 'Nixon'" should pass (see tests for more)""" is_palindrome = False if prep_word(word) == prep_word(word[::-1]): is_palindrome = True return is_palindrome def get_longest_palindrome(words=None): """Given a list of words return the longest palindrome If called without argument use the load_dictionary helper to populate the words list""" if words == None: words = load_dictionary() pal = [p for p in words if is_palindrome(p)] m = max([len(p) for p in pal]) max_words = [p for p in pal if len(p) == m] max_words = sorted(max_words) return max_words[0] # def main(): # """ main program entry point""" # p = get_longest_palindrome() # print(p) # if __name__=="__main__": # main()
true
489a9fbaa6d206101364ed5db32b3bf291c3d875
nishanthegde/bitesofpy
/304/max_letter.py
2,435
4.25
4
from typing import Tuple import re from collections import Counter sample_text = '''It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife.''' with_numbers_text = '''20,000 Leagues Under the Sea is a 1954 American Technicolor science fiction-adventure film...''' emoji_text = 'emoji like 😃😃😃😃 are not letters' accents_text = 'Société Générale est une des principales banques françaises' mixed_case_text = 'Short Plays By Lady Gregory The Knickerbocker Press 1916' hyphenated_word_text = 'six-feet-two in height' compound_character_text = 'der Schloß is riesig' no_repeat_characters_text = 'the quick brown fox jumped over the lazy dog' non_ascii_symbols_text = '«¿Tiene sentido la TV pública?»' apostrophe_in_word_text = "but we've been there already!!!" underscore_torture_text = '"____".isalpha() is True, thus this test text' digit_text = '99abc99 __abc__ --abc-- digits _ and - are not letters' repeat_words_text = 'test test test test test correct-answer.' no_words_in_text = '1, 2, 3' empty_text = '' def max_letter_word(text: str) -> Tuple[str, str, int]: """ Find the word in text with the most repeated letters. If more than one word has the highest number of repeated letters choose the first one. Return a tuple of the word, the (first) repeated letter and the count of that letter in the word. # >>> max_letter_word('I have just returned from a visit...') ('returned', 'r', 2) # >>> max_letter_word('$5000 !!') ('', '', 0) """ return_value = ('', '', 0) regex = re.compile('[«¿\"#!@$%%&*()0-9._]') regex1 = re.compile(r'[^ \nA-Za-zÀ-ÖØ-öø-ÿ/]+') if not isinstance(text, str): raise ValueError else: words_orig = [regex.sub('', w) for w in text.split()] words = [regex1.sub('', w.casefold()) for w in text.split()] for i, word in enumerate(words): if word: # print(word) cnt = Counter(word).most_common()[0] # print(cnt) if i == 0: # initiate return_value = (words_orig[i], cnt[0], cnt[1]) else: if cnt[1] > return_value[2]: return_value = (words_orig[i], cnt[0], cnt[1]) # else: # break return return_value
true
c2e0d08cf977c216e326da83a6e1580b01c3af7b
nishanthegde/bitesofpy
/66/running_mean.py
666
4.125
4
import itertools def running_mean(sequence: list) -> list: """Calculate the running mean of the sequence passed in, returns a sequence of same length with the averages. You can assume all items in sequence are numeric.""" it = iter(sequence) n = len(sequence) run_mean = [] for i in range(1, n + 1): win = list(itertools.islice(sequence, 0, i, 1)) run_mean.append(round(sum(win) / len(win), 2)) return run_mean # def main(): # print('thank you...') # print(running_mean([1, 2, 3])) # assert [1.0, 1.5, 2.0] == [1, 1.5, 2] # if __name__ == '__main__': # main()
true
f70649cbba312ef901ac9aa035cc529e46127200
Caleb-o/VU405
/sort.py
694
4.1875
4
""" Author: Caleb Otto-Hayes Date: 11/2/2021 """ def swap(x: int, y: int) -> tuple: return (y, x) def bubbleSort(unsorted: list) -> None: length: int = len(unsorted) full_pass: bool = False # Cannot parse if only 1 number exists if length < 2: return while not full_pass: full_pass = True for i in range(length - 1): if (unsorted[i] > unsorted[i + 1]): unsorted[i], unsorted[i + 1] = swap(unsorted[i], unsorted[i + 1]) full_pass = False if __name__ == '__main__': li: list = [2, 1, 9, 3, 7, 5, 6, 8] print(f'Unsorted list: {li}') bubbleSort(li) print(f'Sorted list: {li}')
true
1572a767db054bb13877a5d56f5efb212d0b844d
ahumoe/dragonfly-commands
/_text_utils.py
1,978
4.15625
4
#!/usr/bin/env python # (c) Copyright 2015 by James Stout # (c) Copyright 2016 by Andreas Hagen Ulltveit-Moe # Licensed under the LGPL, see <http://www.gnu.org/licenses/> """Library for extracting words and phrases from text.""" import re def split_dictation(dictation, strip=True): """Preprocess dictation to do a better job of word separation. Returns a list of words.""" clean_dictation = str(dictation) if strip: # Make lowercase. clean_dictation = clean_dictation.lower() # Strip apostrophe and "the ". clean_dictation = re.sub(r"'|^(a |the )", "", clean_dictation) # Convert dashes and " a " into spaces. clean_dictation = re.sub(r"-| a | the ", " ", clean_dictation) # Surround all other punctuation marks with spaces. clean_dictation = re.sub(r"(\W)", r" \1 ", clean_dictation) # Convert the input to a list of words and punctuation marks. raw_words = [word for word in clean_dictation.split(" ") if len(word) > 0] # Merge contiguous letters into a single word, and merge words separated by # punctuation marks into a single word. This way we can dictate something # like "score test case dot start now" and only have the underscores applied # at word boundaries, to produce "test_case.start_now". words = [] previous_letter = False previous_punctuation = False punctuation_pattern = r"\W" for word in raw_words: current_punctuation = re.match(punctuation_pattern, word) current_letter = len(word) == 1 and not re.match(punctuation_pattern, word) if len(words) == 0: words.append(word) else: if current_punctuation or previous_punctuation or (current_letter and previous_letter): words.append(words.pop() + word) else: words.append(word) previous_letter = current_letter previous_punctuation = current_punctuation return words
true
c3062c4b5da4a684bb5ce8a19b074e6585618620
josepicon/practice.code.py
/Exercise Files/Ch2/functions_start.py
747
4.34375
4
# # Example file for working with functions # # define a basic function def func1(): print("i am a function") # function that takes arguments def func2(arg1, arg2): print(arg1, "", arg2) # function that returns a value def cube(x): return x*x*x # function with default value for an argument def power(num, x=1): result=1 for i in range(x): result = result * num return result #function with variable number of arguments def multi_add(*args): result=0 for x in args: result = result + x return result #func1() #print(func1()) #print(func1) #func2(10, 20) #print (func2(10,20)) #print (cube(3)) #print(power(2)) #print (power(2,3)) #print(power(x=3, num=2)) print (multi_add(10,4,10,5,4))
true
080fa1a292fe225984f8889d5e5bd13ed05b0f07
MayThuHtun/python-exercises
/ex3.py
444
4.28125
4
print("I will now count my chickens") print("Hens", 25+30/6) print("Roosters", 100-25*3 % 4) print("Now I will count the egg:") print(3+2+1-5+4 % 2-1/4+6) print("Is it true that 3+2<5-7?") print(3+2 < 5-7) print("What is 3+2?", 3+2) print("What is 5-7?", 5-7) print("Oh, that is why it is false") print("How about some more") print("It is greater?", 5 > -2) print("It is greater or equal?", 5 >= -2) print("It is less than or equal?", 5 <= -2)
true
aeb5e4b72d128ac04131053125ed663ad059d5f5
Patricia888/data-structures-and-algorithms
/sorting_algos/merge_sort/merge_sort.py
927
4.5
4
def merge_sort_the_list(lst): ''' Performs a merge sort on a list. Checks the length and doesn't bother sorting if the length is 0 or 1. If more, it finds the middle, breaks the list in to sublists, sorts, puts in to a single list, and then returns the sorted list ''' # don't bother sorting if list is less than 2 length if len(lst) < 2: return lst # find middle of inputted list middle_of_list = len(lst) // 2 # recursive part new_list1 = merge_sort_the_list(lst[0:middle_of_list]) new_list2 = merge_sort_the_list(lst[middle_of_list:]) list_for_sorting = [] while len(new_list1) and len(new_list2): if new_list1[-1] > new_list2[-1]: list_for_sorting = [new_list1.pop()] + list_for_sorting else: list_for_sorting = [new_list2.pop()] + list_for_sorting sorted_list = new_list1 + new_list2 + list_for_sorting return sorted_list
true
e10e5f413c7f9e4b84f8fe20a314a4be4d36a9a9
TheWronskians/capture_the_flag
/turtlebot_ws/src/turtle_pkg/scripts/primeCalc.py
912
4.125
4
from math import * import time def checkingPrime(number): #Recieves number, true if prime. Algorithem reference mentioned in readme file. checkValue = int(sqrt(number))+1 printBool = True #print checkValue for i in range(2, checkValue): if (number%i) == 0: printBool = False break return printBool def countPrimes(lLimit, uLimit): #Recieves range limit and returns amount of primes and total search time. start_time = time.time() count = 0 temp=lLimit if lLimit<=1: #Since 1 cannot be considered a prime. lLimit=2 if (uLimit<lLimit) or (uLimit<=1): return 0,0 for number in range(lLimit,uLimit+1): if checkingPrime(number): count = count + 1 elapsed_time = time.time() - start_time lLimit=temp print("There are " + str(count) + " primes between " + str(lLimit) + " and " + str(uLimit)) print("Time elapsed " + str(elapsed_time) + " seconds.") return count, elapsed_time
true
273b92997f588d6aeee2ae42928258d04f0a4187
drliebe/python_crash_course
/ch7/restaurant_seating.py
214
4.28125
4
dinner_party_size = input("How many people are in your dinner group? ") if int(dinner_party_size) > 8: print("I'm sorry, but you will have to wait to be seated.") else: print('Great, we can seat you now.')
true
1a747fc8d6fefd929318c717954420f3e36ce54a
drliebe/python_crash_course
/ch9/ice_cream_stand.py
888
4.28125
4
class Restaurant(): """A class modeling a simple restaurant.""" def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print('Restaurant name: ' + self.restaurant_name + ' Cuisine type: ' + self.cuisine_type) def open_restaurant(self): print('We are now open!') class IceCreamStand(Restaurant): """A class modeling a simple ice cream stand.""" def __init__(self, restaurant_name, flavors): super().__init__(restaurant_name, 'ice cream') self.flavors = flavors def display_flavors(self): for flavor in self.flavors: print('-' + flavor) bonnie_doon = IceCreamStand('Bonnie Doon', ['chocolate', 'vanilla', 'strawberry']) bonnie_doon.display_flavors()
true
42b2a2848527d4f024d2bdc5ff385b2ce9753dc4
aurafrost/Python
/DivisorCheck.py
518
4.21875
4
""" This program takes an int from the user then returns all divisors of that int from lowest to highest. """ num = int(input("Enter an integer: ")) divisorList = [] for x in range(1,num+1): if num%x==0: divisorList.append(x) #adds x to divisorList if it has no remainder when divided into num print("The divisors of "+str(num)+" are: "+", ".join(str(n) for n in divisorList)) if(len(divisorList)==2): print("The number "+str(num)+" is prime.") #prints this if there're only two elements in divisorList
true
edaaa9d51915039e033c950b030fbc08a9ef4084
fharookshaik/Mobius_GUI
/mobius.py
2,932
4.28125
4
''' Möbius function: For any positive integer n,n, define μ(n)μ(n) as the sum of the primitive n^\text{th}nth roots of unity. It has values in \{-1, 0, 1\}{−1,0,1} depending on the factorization of nn into prime factors: a) \mu(n) = 1μ(n)=1 if nn is a square-free positive integer with an even number of prime factors. b) \mu(n) = -1μ(n)=−1 if nn is a square-free positive integer with an odd number of prime factors. c) \mu(n) = 0μ(n)=0 if nn has a squared prime factor. ''' import math def isSquareRoot(num): ''' Checks whether the input num is a square root or not. Output is a boolean. ''' try: num_sqrt = math.sqrt(num) if int(num_sqrt)**2 == num: return True else: return False except Exception as e: return('Error in finding Square Root:' + str(e)) def get_factors(num): try: ''' outputs the factors between 1 and num excluding both eg: for 8 -> [2,4,8] ''' factors = [] for i in range(2, num // 2 + 1): if num % i == 0: factors.append(i) factors.append(num) return factors except Exception as e: return('Error in getting factors: ' + str(e)) def isPrime(num): ''' Checks whether the input num is a prime or not output is a boolean ''' try: if num < 2: return False else: for i in range(2, num): if (num % i == 0): return False return True except Exception as e: return ('Error in evaluating prime number: ' + str(e)) def Mobius(num): ''' Returns the mobius value of a number. ''' try: exp = '' if num <= 0: exp = f'Number can\'t be zero or negative.' return {'val': None, 'exp' : exp} if num == 1: exp = f'The Möbius Value of number 1 is 1.' return {'val': 1, 'exp' : exp} factors = get_factors(num) prime_count = 0 prime_numbers = [] for i in factors: if isSquareRoot(i): exp ="The number {} can be divided by {} which is a perfect square.".format(num,i) return {'val': 0, 'exp' : exp} elif isPrime(i): prime_numbers.append(i) prime_count += 1 exp = 'The number {} can be get by multiplying {}.'.format(num,prime_numbers) if (prime_count % 2 != 0): return {'val': -1, 'exp' : exp} else: return {'val': 1, 'exp' : exp} except Exception as e: return ('Error Finding Möbius function: ' + str(e)) if __name__ == '__main__': n = int(input("Enter a number to get it's mobius value: ")) op = Mobius(n) print('Mobius Value = {} \nExplaination: {}'.format(op['val'], op['exp']))
true
cb98c118df80bbe3ef89900bc63d6e38d01514c8
jpozin/Math-Projects
/TriangleStuff.py
652
4.375
4
import sys from math import sqrt class TriangleException(Exception): pass def isValidTriangle(a, b, c): return (a + b > c) and (a + c > b) and (b + c > a) def Perimeter(a, b, c): return a + b + c def Area(a, b, c): s = Perimeter(a, b, c) / 2 return sqrt(s*(s-a)*(s-b)*(s-c)) if __name__ == '__main__': a = float(sys.argv[1]) b = float(sys.argv[2]) c = float(sys.argv[3]) if not isValidTriangle(a, b, c): raise TriangleException("Your triangle is invalid; please check your side lengths.") ShowThis = f"""The perimeter off your triangle is {Perimeter(a, b, c)}. The area of your triangle is {Area(a, b, c)}."""
true
52756187aec18fc94ecc77d26594ab3d50a502a5
kellylougheed/raspberry-pi
/bubble_sort.py
956
4.375
4
#!/usr/bin/env python # This program sorts a list of comma-separated integers using bubble sort # Swaps two numbers in a list given their indices def swap(l, index1, index2): temp = l[index2] l[index2] = l[index1] l[index1] = temp numbers = input("Enter a list of comma-separated integers: ") lst = numbers.split(",") done = False passes = 0 while not done: # Make done variable true so that it can be changed to false if the sorting is not yet done done = True for index, item in enumerate(lst): # If it's not the end of the list and the two adjacent items are out of order if index + 1 != len(lst) and lst[index] > lst[index + 1]: swap(lst, index, index + 1) # Make done variable false because the list was not done being sorted done = False passes += 1 print("Pass %s: %s" %(passes, ",".join(lst))) print("Original List: %s" %(numbers)) print("Sorted List: %s" %(",".join(lst))) print("Passes: %s" %(passes))
true
473d78088b698ab07eca912a5ef5bf23a76d32dc
dibaggioj/bioinformatics-rosalind
/textbook/src/ba1d.py
2,138
4.3125
4
#!/usr/bin/env # encoding: utf-8 """ Created by John DiBaggio on 2018-07-28 Find All Occurrences of a Pattern in a String In this problem, we ask a simple question: how many times can one string occur as a substring of another? Recall from “Find the Most Frequent Words in a String” that different occurrences of a substring can overlap with each other. For example, ATA occurs three times in CGATATATCCATAG. Pattern Matching Problem Find all occurrences of a pattern in a string. Given: Strings Pattern and Genome. Return: All starting positions in Genome where Pattern appears as a substring. Use 0-based indexing. Sample Dataset ATAT GATATATGCATATACTT Sample Output 1 3 9 Execute like: python src/ba1d.py data/ba1d.txt output/ba1d.txt """ __author__ = 'johndibaggio' import sys import fileinput argv = list(sys.argv) input_pattern = "" input_genome = "" for line in fileinput.input(argv[1]): if len(line) > 0: if len(input_pattern) == 0: input_pattern += line.replace('\n', '') else: input_genome += line.replace('\n', '') def find_occurrences(genome, pattern): """ Find the indices of all occurrences of pattern in genome :param genome: DNA string :type genome: str :param pattern: DNA substring :type pattern: str :return: list of indices of occurrences of pattern in genome :rtype: list[int] """ k = len(pattern) buffer = genome[0:k] genome = genome[k:len(genome)] i = 0 indices = [] if buffer == pattern: indices.append(i) for c in genome: i += 1 buffer = buffer[1:k] + c if buffer == pattern: indices.append(i) return indices occurrences = find_occurrences(input_genome, input_pattern) output_string = str.join(" ", [str(i) for i in occurrences]) print("The following are the occurrences of pattern \"{}\" in genome \"{}\":\n{}".format(input_pattern, input_genome, output_string)) output_file = open(argv[2], "w+") output_file.write(output_string) output_file.close()
true
b2b59660795297211f00f7b98497fb289583e46a
FierySama/vspython
/Module3StringVariables/Module3StringVariables/Module3StringVariables.py
1,330
4.5625
5
#String variables, and asking users to input a value print("What is your name? ") # This allows for the next line to be user input name = input("") country = input("What country do you live in? ") country = country.upper() print(country) # input is command to ask user to enter info!! # name is actually the name of a custom variable that we've created above. #Create a friendly output print("Hello! " + name + ", please create your story! ") print("\n") #Variables allow you to manipulate contents of VARIABLES message1 = "Hello World \n" print(message1.lower()) #hello world print(message1.upper()) #HELLO WORLD print(message1.swapcase()) #hELLO wORLD #Update value of name after user input # name = "banana hammock" #print(name) # Variables are case sensitive!!! Name does NOT EQUAL name # Treat everything like it's case sensitive in python. # Variables cannot start with a number. # name3 name2 name1 are all okay # Newer functions!! print("\n") message2 = "hello World" print(message2.find("world")) print(message2.count("o")) print(message2.capitalize()) print(message2.replace("Hello","Hi")) #Good habit. Initializing values #ex below postalCode = " " #this is declaring that this is a string, with initializing postalCode = input("Please enter your postal code: ") print(postalCode.upper())
true
75db23491fd660c007860b03e4ed99cca64a9025
zengh100/PythonForKids
/lesson02/07_keyboard_number.py
316
4.15625
4
# keyboard # we can use keyboard as an input to get informations or data (such as number or string) from users x1 = input("please give your first number? ") #print('x1=', x1) x2 = input("please give your second number? ") #print('x2=', x2) sum = x1 + x2 #sum = int(x1) + int(x2) print('the sum is {}'.format(sum))
true