blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
2a3d2d00ccba81a596ec9e9b6296c115ac1b583a
woshiZS/Snake-Python-tutorial-
/Chapter3/cube.py
336
4.40625
4
cubes=[value for value in range(1,11)] for cube in cubes: print(cube) print("The first 3 items in the list are : ") for num in cubes[:3]: print(num) print("Three items from the middle of the list are : ") for num in cubes[4:7]: print(num) print("The last 3 items in the list are : ") for num in cubes[-3:]: print(num)
true
0d8a2dea4bdafa61851e58509bbf5adc04022818
andres925922/Python-Design-Patterns
/src/3_examples/Structural/adapter.py
829
4.125
4
""" Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. """ from abc import ABC, abstractmethod # ---------------- # Target Interface # ---------------- class Target(ABC): """ Interface for Client """ def __init__(self): self._adaptee = Adaptee() @abstractmethod def request(self): pass # ---------------- # Adapter Class # ---------------- class Adapter(Target): def request(self): self._adaptee.adaptee_request() # ---------------- # Adaptee Class # -------------- class Adaptee: def adaptee_request(self): print("Adaptee function called.") def main(): adapter = Adapter() adapter.request() if __name__ == "__main__": main()
true
d63b47cc028440f91de93b4f2afe0e729bda88fd
Environmental-Informatics/building-more-complex-programs-with-python-Gautam6-asmita
/Second_attempt_Exercise5.2.py
1,180
4.53125
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Created on 2020-01-24 by Asmita Gautam Assignment 01: Python - Learning the Basics Think Python Chapter 5: Exercises 5.2 ##Check fermat equation Modified for resubmission on 2020-03-04 """ """ This function 'check_fermat' takes 4 parameters: a,b,c and d to check the 'check fermat' equation given in exercise 5.2 """ def check_fermat(a,b,c,n): #Define a function check_fermat if 2<n and a**n+b**n==c**n: #** denotes ^, if the given 2 statement holds true than print print("Holy smokes,fermat was wrong") else: #else than also print print("No, that doesnot work") """ This function 'check_fermat_input' doesnot take any arguments It prints the input inquiry """ def check_fermat_input(): # to print input inquiry in the console a = int(input("Input 'a' value here: ")) # int(input...) is to convert the input to be integer instead of string b = int(input("Input 'b' value here: ")) c = int(input("Input 'c' value here: ")) n = int(input("Input 'n' value here: ")) return check_fermat(a,b,c,n) check_fermat_input()
true
ea3a06ac165152baade99a551f6fe2d7740ba635
mrsleveto/PythonProgrammingAssignmentSolutions
/Conversation with a computer.py
743
4.1875
4
#Conversation with a computer, by: Mrs. Leveto doing_well=input("Hello, are you doing well today? (y/n): ") if doing_well == "y" or doing_well == "Y": print("Wonderful! I'm so glad!") reason=input("What has you in such a great mood today? (weather/school/friends): ") if reason == "weather": print("Yes - the sunshine will do that!") elif reason == "school": print("Learning something new is great fun!") elif reason == "friends": print("Friends are the best!") else: print("Something else then. That's ok, you don't have to explain.") elif doing_well == "n" or doing_well == "N": print("I'm very sorry to hear that.") else: print("I can't understand you, you're mumbling")
true
a4134eb61c9d56b6c11d4d993c18b72f92e9fdf3
FilipDuz/CodeEval
/Moderate/ARRAY_ABSURDITY.py
1,495
4.125
4
#ARRAY ABSURDITY """ Imagine we have an immutable array of size N which we know to be filled with integers ranging from 0 to N-2, inclusive. Suppose we know that the array contains exactly one duplicated entry and that duplicate appears exactly twice. Find the duplicated entry. (For bonus points, ensure your solution has constant space and time proportional to N) INPUT SAMPLE: Your program should accept as its first argument a path to a filename. Each line in this file is one test case. Ignore all empty lines. Each line begins with a positive integer(N) i.e. the size of the array, then a semicolon followed by a comma separated list of positive numbers ranging from 0 to N-2, inclusive. i.e eg. 5;0,1,2,3,0 20;0,1,10,3,2,4,5,7,6,8,11,9,15,12,13,4,16,18,17,14 OUTPUT SAMPLE: Print out the duplicated entry, each one on a new line eg 0 4 #imports script, filename from sys import argv script, filename=argv #Assigns fie object to text txt=open(filename,"r") #For loop to read in each line separately for line in txt.read().split("\n"): #If line isn't empty if line: #Splits line into two parts; one part before the ";", and one part after the ";" line=line.split(";") #Separates the comma separated values line2=line[1].split(",") #Creates set with values listed above setA=set(line2) #Prints the value that is listed twice for x in setA: if line2.count(x)==2: print x
true
5a82cacd4bf322b1200c0f66f89e5a9d950856f9
FilipDuz/CodeEval
/Moderate/REMOVE_CHARACTERS.py
1,393
4.34375
4
#REMOVE CHARACTERS """ Write a program which removes specific characters from a string. INPUT SAMPLE: The first argument is a path to a file. The file contains the source strings and the characters that need to be scrubbed. Each source string and characters you need to scrub are delimited by comma. For example: how are you, abc hello world, def OUTPUT SAMPLE: Print to stdout the scrubbed strings, one per line. Ensure that there are no trailing empty spaces on each line you print. For example: how re you hllo worl """ #imports script, filename from sys import argv script, filename=argv #Assigns file object to text txt=open(filename,"r") #For loop to read in lines and perform requested actions for line in txt.read().split("\n"): #Performs loop only if there is text in the line if line: #Splits the file into two parts line2=line.split(",") #Assigns the string to be edited to string string=line2[0] #Creates list of characters to remove from proceeding string #Removes unnecessary whitespace chars=line2[1] chars=chars.strip() chars=list(chars) #Removes selected characters from original string for x in chars: string=string.replace(x,"") #Prints edited string print string #Closes file object txt.close()
true
289ad787090b4a6c692fc2088213b73171add2a5
sonalpawar2196/PythonTrainingDecember
/List/ListDemo.py
1,637
4.4375
4
thisList = ['sonal','priya','abc','pqr'] print(thisList) print(thisList[1]) thisList[1] = "jjj" print(thisList) # iterating over list for x in thisList: print(x) if "sonal" in thisList: print("string is in the list") else: print("not present ") print("length of list = ",len(thisList)) #To add an item to the end of the list, use the append() method: thisList.append("pooja") print(thisList) #To add an item at the specified index, use the insert() method: thisList.insert(1,"one") print(thisList) print("length of list = ",len(thisList)) #There are several methods to remove items from a list: # remove, pop, clear, del #The remove() method removes the specified item: thisList.remove("pooja") print("1 item removed from list") #The pop() method removes the specified index, (or the last item if index is not specified): thisList.pop(3) print(thisList) #The del keyword removes the specified index: del thisList[0] print(thisList) # ------------------------------------------------------------------ # clear() make entire list empty thisList[:] print(thisList) # coping one list to another fruites = ["apple","banana","grapes","orange","apple"] x = fruites print(x) #--------------------------------------------------------------------- # count() function returns how many times perticular item occure in the list countAPPLE = fruites.count("apple") print(countAPPLE) # extend() used when you want to add element at the end of current list cars = ["BMW","AUDI","MERCEDIES","JAGUAR"] fruites.extend(cars) print(fruites) # index() : returns the index of perticular item y = fruites.index("BMW") print(y)
true
525fa2c6b200496b8c9a5a748127f5e4f60a6819
swapnilz30/python
/create-file.py
734
4.4375
4
#!/usr/bin/python3.6 # This script create the file. import os from sys import exit def check_file_dir(file_name): # Check user enter value is dir or file. if os.path.isdir(file_name): print("The ", file_name, "is directory") exit() elif os.path.isfile(file_name): print("The ", file_name, "is file already exist") exit() def create_file(file_name): # Open the file in write mode. f = open(file_name, 'w') f.close() print("The empty file ", file_name, "is created.") ### Main Section ### file_name = input("Enter file name: ") if file_name == "": print("The file name should not be empty") exit() else: check_file_dir(file_name) create_file(file_name)
true
6f84b439cc1b1a3b547281c6ef9d05a2c6cd6145
Shubhu0500/Shubhu0500
/ROCK_PAPER_SCISSORS.py
1,072
4.28125
4
rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' #Write your code below this line 👇0 import random player_choice = int(input("what do you choose? 0 for rock, 1 for paper and 2 for scissors ")) if player_choice == 0: print(rock) elif player_choice == 1: print(paper) else: print(scissors) computer_choice = random.randint(0,2) print(f"Computer chose: {computer_choice}") if computer_choice == 0: print(rock) elif computer_choice == 1: print(paper) else: print(scissors) if player_choice == 0 and computer_choice == 2: print("Congratulations!! You won") elif computer_choice > player_choice: print("AHH! Hard luck You lose") elif computer_choice == player_choice: print("OHHH! It's a draw") else: print("Invalid Choice, Game Over!!") print("Hope you enjoyed the game!")
false
0f9944079b744b6d2074ca765b018fa61a3866e6
olives8109/CTI-110-1001
/M2_HourstoMinutes.py
522
4.28125
4
# Hours to Minutes # with formatting # CTI-110 # Sigrid Olive # 6/7/2017 #convert minutes to hh:mm format #input number of minutes totalMinutes = int(input("Number of minutes: ")) print ("You entered " + str(totalMinutes) + " minutes." ) #calculate hours hours = totalMinutes // 60 #print ("That is ", hours, " hours.") #calculates minutes only minutes = totalMinutes % 60 #print("and ", minutes, " minutes.") #print output print ("That is ", hours, "hours", \ "and ", minutes, " minutes.")
true
6f3db28210ead31da475367df0416c569b69ab04
olives8109/CTI-110-1001
/M5T2_FeetToInches_SigridOlive.py
539
4.46875
4
# Feet to Inches - Converts an input of feet into inches. # CTI-110 # Sigrid Olive # 6/26/2017 # explains what program does print("This program takes a number of feet and gives out the number of inches in that many feet.") # defines the variable "feet_to_inches" which will take an input of feet and convert it into inches def feet_to_inches(): feet = int(input("Enter a number of feet: ")) inches = feet*12 print("The number of inches in", + feet,"feet is: ", + inches) def main(): feet_to_inches() main()
true
d284f26b04c9f8f44f73bf67150132d79262912a
krupadhruva/CIS41A
/home/unit_c_1.py
2,722
4.46875
4
""" Krupa Dhruva CIS 41A Fall 2020 Unit C take-home assignment """ """ First Script - Working with Lists All print output should include descriptions as shown in the example output below. Create an empty list called list1 Populate list1 with the values 1,3,5 Create list2 and populate it with the values 1,2,3,4 Create list3 by using + (a plus sign) to combine list1 and list2. Print list3. Use sequence operator in to test list3 to see if it contains a 3, print True/False result (do with one line of code). Count the number of 3s in list3, print the result. Determine the index of the first 3 in list3, print the result. Pop this first 3 and assign it to a variable called first3, print first3. Create list4, populate it with list3's sorted values, using the sorted built-in function. Print list3 and list4. Slice list3 to obtain a list of the values 1,2,3 from the middle of list3, print the result. Determine the length of list3, print the result. Determine the max value of list3, print the result. Sort list3 (use the list sort method), print list3. Create list5, a list of lists, using list1 and list2 as elements of list5, print list5. Print the value 4 contained within list5. Example output: d) list3 is: [1, 3, 5, 1, 2, 3, 4] e) list3 contains a 3: True f) list3 contains 2 3s g) The index of the first 3 contained in list3 is 1 h) first3 = 3 j) list3 is now: [1, 5, 1, 2, 3, 4] j) list4 is: [1, 1, 2, 3, 4, 5] k) Slice of list3 is: [1, 2, 3] l) Length of list3 is 6 m) The max value in list3 is 5 n) Sorted list3 is: [1, 1, 2, 3, 4, 5] o) list5 is: [[1, 3, 5], [1, 2, 3, 4]] p) Value 4 from list5: 4 """ list1 = [] list1.extend([1, 3, 5]) list2 = [1, 2, 3, 4] list3 = list1 + list2 print(f"list3 is: {list3}") print(f"list3 contains a 3: {3 in list3}") print(f"list3 contains {list3.count(3)} 3s") print(f"The index of the first 3 contained in list3 is {list3.index(3)}") first3 = list3.pop(list3.index(3)) print(f"first3 = {first3}") print(f"list3 is now: {list3}") list4 = sorted(list3) print(f"list4 is: {list4}") print(f"Slice of list3 is: {list3[2:-1]}") print(f"Length of list3 is {len(list3)}") print(f"The max value in list3 is {max(list3)}") list3.sort() print(f"Sorted list3 is: {list3}") list5 = [list1, list2] print(f"list5 is: {list5}") print(f"Value 4 from list5: {list5[1][3]}") """ Execution results: list3 is: [1, 3, 5, 1, 2, 3, 4] list3 contains a 3: True list3 contains 2 3s The index of the first 3 contained in list3 is 1 first3 = 3 list3 is now: [1, 5, 1, 2, 3, 4] list4 is: [1, 1, 2, 3, 4, 5] Slice of list3 is: [1, 2, 3] Length of list3 is 6 The max value in list3 is 5 Sorted list3 is: [1, 1, 2, 3, 4, 5] list5 is: [[1, 3, 5], [1, 2, 3, 4]] Value 4 from list5: 4 """
true
dad8256f39a3457447851ad0909580611603b8c8
martiinmuriuki/python_projects
/tempconverter.py
2,529
4.28125
4
import math import time # Function def again(): try_again = print() User_Temp = input("your temperature,'C' for celsius, 'F' for fahrenheit 'K' for kelvin: ").upper() convert_Temp = input("The temperature you want to convert to, 'C' for celsius, 'F' for fahrenheit 'K' for kelvin: ").upper() # conversion equations if User_Temp == "C": if convert_Temp == "F": degree = float(input("enter the degree: ")) result = (degree * 9/5) + 32 print(f"{result}°F") elif convert_Temp == "K": degree = float(input("enter the degree: ")) result = degree + 273.15 print(f"{result}°K") elif convert_Temp == "C": print("This is the same type of temperature") time.sleep(1) again() else: print("Type a temperature") time.sleep(10) again() elif User_Temp == "F": if convert_Temp == "C": degree = float(input("enter the degree: ")) result = (degree - 32) * 5/9 print(f"{result}°C") elif convert_Temp == "K": degree = float(input("enter the degree: ")) result = (degree - 32) * 5/9 + 273.15 print(f"{result}°K") elif convert_Temp == "F": print("This is the same type of temperature") time.sleep(10) again() else: print("Type a unit") time.sleep(10) again() elif User_Temp == "K": if convert_Temp == "C": degree = float(input("enter the degree: ")) result = degree - 273.15 print(f"{result}°F") elif convert_Temp == "F": degree = float(input("enter the degree: ")) result = (degree - 273.15) * 9/5 + 32 print(f"{result}°K") elif convert_Temp == "K": print("This is the same type of temperature") time.sleep(10) again() else: print("Type a unit") time.sleep(10) again() else: print("Type a temperature") time.sleep(10) again() # try again while try_again != "Yes" and try_again != "No": print("Do you want to try again?") try_again = input("Yes | No | ").lower().capitalize() if try_again == "Yes": again() break elif try_again == "No": print("Goodbye") break again()
true
e206a46f537f4c71479fa063703bef27646c7efc
justgolyw/my-python-scripts
/Interview/code/select_sort.py
560
4.15625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @Author : yangwei.li @Create date : 2019/4/20 @FileName : select_sort.py """ # 选择排序 def select_sort(arr): n = len(arr) if n<=1: return arr for i in range(0,n-1): min_index= i for j in range(i+1,n): if arr[j]<arr[min_index]: min_index = j if min_index != i: arr[min_index],arr[i]=arr[i],arr[min_index] return arr if __name__ == "__main__": arr = [3,1,5,2,4] new_arr = select_sort(arr) print(new_arr)
false
382be9db811b8a824a796111e0691aea58b3c4a8
JayT25/30-days-of-code
/arrays.py
757
4.1875
4
""" Task: Given an array, A, of N integers, print A's elements in reverse order as a single line of space-separated numbers. Input Format: The first line contains an integer, N (the size of our array). The second line contains N space-separated integers describing array A's elements. Sample input: 4 1 4 3 2 Sample output: 2 3 4 1 """ #!/bin/python3 import math import os import random import re import sys def reverse_arr(an_array): index = (len(an_array) - 1) result = '' for x in range((len(an_array))): result += str(an_array[index]) + ' ' index -= 1 return result if __name__ == '__main__': n = int(input()) arr = list(map(int, input().rstrip().split())) print(reverse_arr(arr))
true
96ea47c02375e6ec964b9cb198dfcaf87b8f3cd8
danielreedcombs/zoo-python
/zoo.py
703
4.53125
5
#Create a tuple named zoo that contains your favorite animals. zoo = tuple(["Dog","Chicken","Lama","Otter"]) #Find one of your animals using the .index(value) method on the tuple. num_of_chicken = zoo.index("Chicken") print(num_of_chicken) #Determine if an animal is in your tuple by using value in tuple. print("Chicken" in zoo) #Create a variable for each of the animals in your tuple with this cool feature of Python. #Convert your tuple into a list. zoo_list = list(zoo) print(zoo_list) #Use extend() to add three more animals to your zoo. zoo_list.extend(["Zac", "Daniel", "Ousama"]) print(zoo_list) #Convert the list back into a tuple. zoo_list_tuple = tuple(zoo_list) print(zoo_list_tuple)
true
53261c105ebb6551e5e3a0072d952a67da1d63d6
poofplonker/EffectivePython
/Chapter1/lesson_six.py
1,668
4.15625
4
""" Lesson Six: Don't use start, end and slice in a single Slice """ from itertools import islice A = list(range(10)) #We can use the slice stride syntax like this: print("Even: ", A[::2]) print("Odds: ", A[1::2]) # Seems good right? The problem is that :: can introduce bugs. # Here's a cool idiom for reversing a string or list: print("Reversed: ", A[::-1]) #However lets try this with a utf-8 string: FANCY_STRING = "Thé String".encode('UTF-8') try: print("Reversed UTF-8", FANCY_STRING[::-1].decode()) except UnicodeDecodeError: print("Can't reverse \"%s\": We messed with the order of the bytes by " \ "reversing them!" % FANCY_STRING.decode()) # What would [::-2] correspond to? Well, start at the end and take every second # after that right? print("A[::-2] ", A[::-2]) #What about [2::-2] - well, it probably mean start at 2, and take every second # before that. print("A[2::-2] ", A[2::-2]) # What if you put a end in this statement? print("A[6:8:-2]", A[6:8:-2]) print("A[6:2:-2]", A[6:2:-2]) #Uhhh..... what? print("A[6:2]", A[6:2]) # So using start end with negative slice is fine, but if you do it without # negative slice you get empty list? # Preferred style is not to use slice, but rather to use sequentially # slice then subset. Or you can use islice in collections # islice is great because if you are subsetting then you need to temporarily # copy a subset of the list, whcih is a waste. Islice returns a generator, # so you never have too much memory wasted. B = list(range(1000)) B_1 = B[::2] print("Every even element except first and last: ", B_1[1:-1]) print("Same Result: ", list(islice(B, 1, len(B)-1, 2)))
true
d7c7217a1ce1d50f493ac86eea040675f43d0ad1
agrisjakob/QA-Academy-Work
/Python/Python Exercises and Tasks/Grade calculator.py
1,242
4.40625
4
# Challenge # • Create an application which asks the user for an input for a maths mark, a chemistry mark and a physics mark. # • Add the marks together, then work out the overall percentage. And print it out to the screen. # • If the percentage is below 40%, print “You failed” # • If the percentage is 40% or higher, print “D” # • If the percentage is 50% or higher, print “C” # • If the percentage is 60% or higher, print “B” # • If the percentage is 70% or higher, print “A” maths = int(input("Enter your Maths grade: ")) chem = int(input("Enter your Chemistry grade: ")) phys = int(input("Enter your Physics grade: " )) def averageGrade(): average = (maths + chem + phys) / 3 return average def actualGrade(): if averageGrade() > 70: print("You scored a grade of A.") elif averageGrade() > 60: print("You scored a grade of B.") elif averageGrade() > 50: print("You scored a grade of C.") elif averageGrade() > 40: print("You scored a grade of D") else: print("You failed.") print("Your average grade is: ", averageGrade()) averageGrade() actualGrade()
true
ca9b75d544748d4af11132b84c70d2940e7341f8
ArslanAhmad117/CALCULATOR
/main.py
366
4.25
4
int_1 = int(input("ENTER THE FRIST NUMBER")) int_2 = int(input("ENTER THE SECOND NUMBER")) operator = str(input("ENTER THE OPERATOR")) if operator == '+': print (int_1 + int_2) elif operator == '-': print (int_1 - int_2) elif operator == '*': print (int_1 * int_2) elif operator == '/': print (int_1 /int_2) else: print('WRONG INPUT')
false
a0909ccd877dbd4db33f1c32e965b68b3296aeb7
cubitussonis/WTAMU
/assignment2/program4_table_of_powers.py
1,029
4.15625
4
#! /usr/bin/env python3 #welcome message print("Table of Powers") choice = "y" while choice.lower() == "y": #user input - start number must be lower than stop number startNumber = int(input("\nStart number:\t")) stopNumber = int(input("Stop number:\t")) while startNumber >= stopNumber: print("Error: Start number must be less than stop number. Please try again") startNumber = int(input("Start number:\t")) stopNumber = int(input("Stop number:\t")) #displaying the results print() print("Number\t|\tSquared\t\t|\tCubed") print("======\t|\t=======\t\t|\t=====") for i in range(startNumber,stopNumber+1): print(str(i)+"\t|\t"+str(i**2)+"\t\t|\t"+str(i**3)) print("-----------------------------------------------------") # asking to start again choice = input("\nContinue? (y/n): ") while choice.lower() != "y" and choice.lower() != "n": choice = input("Continue? (y/n): ") print("\nBye!")
false
305faad0957f6d8092c4c4d3a099f2e6ef3ad338
cubitussonis/WTAMU
/assignment4/p5-2_guesses.py
1,574
4.21875
4
#!/usr/bin/env python3 import random def display_title(): print("Guess the number!") print() def get_limit(): limit = int(input("Enter the upper limit for the range of numbers: ")) # limit must be at least 2, otherwise the game makes no sens while limit < 2: print("Smallest possible limit is 2. Please enter valid input.") limit = int(input("Enter the upper limit for the range of numbers: ")) return limit def play_game(limit): number = random.randint(1, limit) print("I'm thinking of a number from 1 to " + str(limit) + "(included).\n") count = 1 # initializing the counter while True: guess = int(input("Your guess: ")) if guess < number: print("Too low.") count += 1 elif guess > number: print("Too high.") count += 1 elif guess == number: print("You guessed it in " + str(count) + " tries.\n") return def main(): display_title() again = "y" while again.lower() == "y": limit = get_limit() play_game(limit) #starting the game with the limit set again = input("Play again? (y/n): ") #asking again if invalid input while again.lower()!="y" and again.lower()!="n": print("Invalid entry. Please enter 'y' or 'n'.") again = input("Play again? (y/n): ") print() print("Bye!") # if started as the main module, call the main function if __name__ == "__main__": main()
true
f4216b05170c13a8363ebe7ad5f37dc2cf23563b
karans5004/Python_Basics
/ClassesAndObjects.py
2,400
4.875
5
""" # Python3 program to # demonstrate instantiating # a class class Dog: # A simple class # attribute attr1 = "mammal" attr2 = "dog" # A sample method def fun(self): print("I'm a", self.attr1) print("I'm a", self.attr2) # Driver code # Object instantiation Rodger = Dog() # Accessing class attributes # and method through objects print(Rodger.attr1) Rodger.fun() """ # Self And Init """ # A Sample class with init method class Person: # init method or constructor def __init__(self, name): self.name = name # Sample Method def say_hi(self): print('Hello, my name is', self.name) p = Person('Nikhil') p.say_hi() """ # Classes and Instance Variables # Python3 program to show that the variables with a value # assigned in the class declaration, are class variables and # variables inside methods and constructors are instance # variables. # Class for Dog """ class Dog: # Class Variable animal = 'dog' # The init method or constructor def __init__(self, breed, color): # Instance Variable self.breed = breed self.color = color # Objects of Dog class Rodger = Dog("Pug", "brown") Buzo = Dog("Bulldog", "black") print('Rodger details:') print('Rodger is a', Rodger.animal) print('Breed: ', Rodger.breed) print('Color: ', Rodger.color) print('\nBuzo details:') print('Buzo is a', Buzo.animal) print('Breed: ', Buzo.breed) print('Color: ', Buzo.color) # Class variables can be accessed using class # name also print("\nAccessing class variable using class name") print(Dog.animal) """ # Accessing Attributes and Methods """ # Python code for Accessing attributes and methods # of one class in another class class ClassA(): def __init__(self): self.var1 = 1 self.var2 = 2 def methodA(self): self.var1 = self.var1 + self.var2 return self.var1 class ClassB(ClassA): def __init__(self, class_a): self.var1 = class_a.var1 self.var2 = class_a.var2 object1 = ClassA() # updates the value of var1 summ = object1.methodA() # return the value of var1 print (summ) # passes object of classA object2 = ClassB(object1) # return the values carried by var1,var2 print( object2.var1) print (object2.var2) """
true
f0511f12ac8b02f306d5b5f2a5eac9d26d53528e
karans5004/Python_Basics
/day1_solution3.py
600
4.25
4
# Python3 Program to check whether a # given key already exists in a dictionary. # Function to print sum def checkKey(dict, key): if key in dict.keys(): return 1 else: return 0 # Driver Code dict = {'a': 100, 'b':200, 'c':300} key = input('Please Enter the Key : ') flag = checkKey(dict, key) if flag == 1: print("Value for given key is : " ,dict[key]) #print its val else: new_value = input('Please enter a value for key') dict[key] = new_value #add the new key to the dictionary #fincal dictionary print("final Dictionary is : ", dict)
true
3df6ef4c4be687872ea8f2bb323fd81700ca5f2c
karans5004/Python_Basics
/AnonymousFunctions.py
2,108
4.75
5
""" In Python, anonymous function means that a function is without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. It has the following syntax: Syntax lambda arguments : expression This function can have any number of arguments but only one expression, which is evaluated and returned. One is free to use lambda functions wherever function objects are required. You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression. It has various uses in particular fields of programming besides other types of expressions in functions. """ """ # Python program to demonstrate # lambda functions x ="GeeksforGeeks" # lambda gets pass to print (lambda x : print(x))(x) """ """ # Python program to illustrate cube of a number # showing difference between def() and lambda(). def cube(y): return y*y*y; g = lambda x: x*x*x print(g(7)) print(cube(5)) """ #Illustration from when inside a function """ # Python program to demonstrate # lmabda functions def power(n): return lambda a : a ** n # base = lambda a : a**2 get # returned to base base = power(2) print("Now power is set to 2") # when calling base it gets # executed with already set with 2 print("8 powerof 2 = ", base(8)) # base = lambda a : a**5 get # returned to base base = power(5) print("Now power is set to 5") # when calling base it gets executed # with already set with newly 2 print("8 powerof 5 = ", base(8)) """ #filter and map """ # Python program to demonstrate # lambda functions inside map() # and filter() a = [100, 2, 8, 60, 5, 4, 3, 31, 10, 11] # in filter either we use assignment or # conditional operator, the pass actual # parameter will get return filtered = filter (lambda x: x % 2 == 0, a) print(list(filtered)) # in map either we use assignment or # conditional operator, the result of # the value will get returned maped = map (lambda x: x % 2 == 0, a) print(list(maped)) """
true
0add3d75735397e008ddce6dc18c04990428fab1
Cobraderas/LearnPython
/PythonGround/PythonIterators.py
1,880
4.71875
5
# an iterator is an object which implements the iterator protocol, which consists of the methods __iter__() # and __next__() # return an iterator from tuple, and print each value mytuple = ("apple", "banana", "cherry") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit)) print(" ") mystr = "banana" myit = iter(mystr) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(" ") # iterate the values of a tuple mytuple = ("apple", "banana", "cherry") for x in mytuple: print(x) print(" ") mystring = "caledonia" for x in mystring: print(x) print(" ") # Create an Iterator # To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. # As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__(), # which allows you do some initializing when the object is being created. # The __iter__() method acts similar, you can do operations (initializing etc.), but must always return the # iterator object itself. # The __next__() method also allows you to do operations, and must return the next item in the sequence. class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 1 return x myclass = MyNumbers() myiter = iter(myclass) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(" ") # stop after 20 iterations class MyNumbersa: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration myclassa = MyNumbersa() myitera = iter(myclassa) for x in myitera: print(x)
true
87639ce4dc7891b3b325ec2c5a331c5addf1defb
Cobraderas/LearnPython
/PythonGround/DateTime.py
516
4.25
4
import datetime x = datetime.datetime.now() print(x) print(x.year) print(x.strftime("%A")) # create date object x = datetime.datetime(2020, 5, 17) print(x) # The datetime object has a method for formatting date objects into readable strings. # The method is called strftime(), and takes one parameter, format, to specify the format of the returned string: x = datetime.datetime(2018, 6, 1) print(x.strftime("%B")) print(x.strftime("%c")) print(x.strftime("%%")) print(x.strftime("%U")) print(x.strftime("%j"))
true
eeb2b2dcee223e8b7808fd88f3c59c01093c3cd9
hkalipaksi/pyton
/week 1/hello_word.py
525
4.125
4
#mencetak string print("hello word") #mencetak angka print(90) #mencetak contanse string "1"+"2" hasilnya 12 print("1"+"2") #mencetak contanse string "hello"+"word" hasilnya 12 print("hello"+"word") #mencetak angka hasil perjumlahan hasil yang dicetak 3 print(1+3) #deklarasi variabel dengan nama var var=12 #Perkalian variabel 'var' dengan angka print(var*2) #deklatasi variabel string(teks)dengan nama var2 var2="yoho" print var2 #perkalian variabe string 'var2' dengan angka hasilnya yohoyoho print var2*2
false
14346136e7119326a97dda86e47bdcbd35aa4cf5
bardia-p/Raspberry-Pi-Projects
/button.py
923
4.1875
4
''' A program demonstrating how to use a button ''' import RPi.GPIO as GPIO import time import lcd_i2c PIN = 25 #Setup and initialization functions of the LCD def printLCD(string1, string2): lcd_i2c.printer(string1, string2) def setup(): lcd_i2c.lcd_init() #General GPIO Setup GPIO.setmode(GPIO.BCM) #sets how we reference GPIO pins GPIO.setup( PIN ,GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #sets pin 17 to a pull-down pin, pulls the voltage of the pin to 0V when nothing is connected setup() #calls setup function of the LCD try: while True: printLCD("Press the button!!"," ") #prints to LCD if(GPIO.input( PIN ) == GPIO.HIGH): #Checks if input is high (3.3V), if so the button is pressed (connects 3.3V rail to pin) printLCD("Button Pressed!!!", "Reset in 2s") time.sleep(2) time.sleep(0.1) except KeyboardInterrupt: pass GPIO.cleanup() lcd_i2c.cleanup()
true
af60ea8239d8ec4755cd6ffafcfd76753c2f4590
VisargD/Problem-Solving
/Day-10/(3-Way Partitioning) Sort-Colors.py
2,748
4.25
4
""" Problem Name: Sort Colors Platform: Leetcode Difficulty: Medium Platform Link: https://leetcode.com/problems/sort-colors/ """ """ APPROACH: In this approach, 3 pointers will be used. Initially zero_index will point to the first index (beginning) of list and two_index will point to the last index (end). In order to sort the color list, we need all the 0's in the beginning, all the 2's in the end and all 1's in-between. Everytime a 0 will be found it will be swapped with value at zero_index and then zero_index will be incremented by 1. By doing this, all the 0's will be placed in the beginning starting from 0 index. Everytime a 2 will be found it will be swapped with value at two_index and then two_index will be decremented by 1. By doing this all the 2's will be placed in the end. So 1's will be in the middle. """ class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ # Function to perform swapping using index. def swapValue(nums, index1, index2): nums[index1], nums[index2] = nums[index2], nums[index1] # Initializing zero_index and index to 0 and two_index to the last index as explained earlier. zero_index = 0 two_index = len(nums) - 1 index = 0 # Using while loop until index is less than or equal to two_index. while index <= two_index: # If the current value is 0 then swap it with zero_index value. # Increment zero_index to store the next 0 whenever found. # Increment the index. if nums[index] == 0: swapValue(nums, index, zero_index) zero_index += 1 index += 1 # If the current value is 2 then swap it with two_index value. # 2's will be placed from the end so after every swap the two_index needs to be decremented to store the next 2 whenever found. # Here index is not incremented because the swapped value may not be in its correct position. So it needs to be checked again. elif nums[index] == 2: swapValue(nums, index, two_index) two_index -= 1 # If the current value is 1 then no need to swap it as we need 1's in the middle for the sorted list. # Simply increment the index. else: index += 1 # In the end, the modified list will have this form: # Index Range: # (0 -> zero_index - 1) (Inclusive): filled with 0's # (zero_index -> index - 1) (Inclusive): filled with 1's # (two_index + 1 -> len(nums) - 1) (Inclusive): filled with 2's
true
fb163e0d9d66defdc5be489c432da4c9c7459bc8
tolgagolbasi/HomeworkCENG
/algorithm analysis/timeit Presentation-Buket/fibRepeater.py
824
4.1875
4
from timeit import Timer #Iterative method def fibIter(n): if n<=2: return 1 else: a,b,i=1,1,3 while i<=n: a,b=b,a+b i+=1 return b # Recursive method def fibRec(n): if n<=2: return 1 else: return fibRec(n-2)+fibRec(n-1) n=int(input("Enter a number :")) s1 = fibIter(n) s2 = fibRec(n) #print(n,".Fibonacci number (iterative function)=",s1) t1 = Timer("fibIter(n)","from __main__ import fibIter,n") #print("Time of Iterative method =",t1.repeat(3)) #print(n,".Fibonacci number (recursive function)=",s2) t2 = Timer("fibRec(n)","from __main__ import fibRec,n") #print("Time of Recursive =",t2.repeat(3)) print("Time of Iterative method =",min(t1.repeat(3))) print("Time of Recursive =",min(t2.repeat(3)))
false
ef047d9fab947eae8cddb4c3a96bc5a9c17edbfd
tj3407/Python-Projects-2
/math_dojo.py
2,282
4.15625
4
import math class MathDojo(object): def __init__(self): self.result = 0 def add(self, arg, *args): # Check the type() of 1st argument # if tuple (which can be a list or another tuple), iterate through values if type(arg) == tuple or type(arg) == list: for i in arg: if type(i) == list or type(i) == tuple: # add values inside list or tuple using sum() function self.result += sum(i) else: # if type() int, add value to self.result without using sum() function - syntax error if sum() is used self.result += i else: # type() int self.result += arg # Check the type() of additional arguments using same logic as 1st argument if type(args) == tuple: for i in args: if type(i) == list or type(i) == tuple: self.result += sum(i) else: self.result += i return self def subtract(self, arg, *args): # Check the type() of 1st argument # if tuple (which can be a list or another tuple), iterate through values if type(arg) == tuple or type(arg) == list: for i in arg: if type(i) == list or type(i) == tuple: # subtract the sum() of values in list/tuple from result self.result -= sum(i) else: # subtract value if type() int self.result -= i else: # type() int self.result -= arg # Check the type() of additional arguments using same logic as 1st argument if type(args) == tuple: for i in args: if type(i) == list or type(i) == tuple: self.result -= sum(i) else: self.result -= i return self md = MathDojo() print "Result: ", md.add([1], 3,4).add([3,5,7,8], [2,4.3,1.25]).subtract(2, [2,3], [1.1,2.3]).result cd = MathDojo() print "Result: ", cd.add(2).add(2,5).subtract(3,2).result rd = MathDojo() print "Result: ", rd.add((2,3), 4).add(5,[5,7,1.2]).add(1,(4,2)).subtract([3,4],(2,1)).result
true
3e3cd7196e617b13fc28175678ec43baee4d941f
janaki-rk/silver_train
/Coding Challenge-5.py
766
4.4375
4
# DAILY CODING CHALLENGE 5 # Question asked by:JANE STREET # cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For # example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.Implement car and cdr. # Step 1: Defining the already implemented cons function to get the pair as result def cons(a, b): def pair(f): return f(a, b) return pair # Step 2: Implementing the "car" and "cdr" function def car(pair): return pair(lambda a, b: a) def cdr(pair): return pair(lambda a, b: b) # Step 3: Calling the main function which calls these above functions and displays the result result = cons(3,4) car_result = car(result) cdr_result = cdr(result) print(car_result) print(cdr_result)
true
886dff703a512ddee03210bb0d14d922b315e314
janaki-rk/silver_train
/Coding Challenge_14.py
1,319
4.28125
4
# DAILY CODING CHALLENGE 14 # Question asked by: GOOGLE # The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method. from random import uniform from math import pow # Step1: Solving the area of the circle with detailed descriptions # 1--Set r to be 1 (the unit circle) # 2--Randomly generate points within the square with corners (-1, -1), (1, 1), (1, -1), (-1, 1) # 3--Keep track of the points that fall inside and outside the circle # 4--You can check whether a point (x, y) is inside the circle if x2 + y2 < r2, which is another way of # representing a circle # 5--Divide the number of points that fall inside the circle to the total number of points -- that # should give us an approximation of π / 4. def generate(): return uniform(-1, 1), uniform(-1, 1) def is_in_circle(coordinates): return coordinates[0] * coordinates[0] + coordinates[1] * coordinates[1] < 1 def estimate(): iterations = 10000000 in_circle = 0 for _ in range(iterations): if is_in_circle(generate()): in_circle += 1 pi_over_four = in_circle / iterations return pi_over_four * 4 # Step 2: Calling the main function which calls these above functions and displays the result a = [0, 4] is_in_circle(a) print(generate()) print(estimate())
true
fb8228b605e522e35535b2ab06f755a2f7e21677
force1267/num_analysis
/hazvigaos.py
985
4.21875
4
print("""حذفی گاوس برای تبدیل به بالا مثلثی""") def matprint(mat, start = 1): m = len(mat) n = len(mat[0]) s = "" for i in range(start, m): for j in range(start, n): s += str(mat[i][j]) + "\t" s += "\n" print(s) n = int(input("سایز ماتریس : ")) + 1 # 2d n*n matrices : a = [[None for i in range(n)] for r in range(n)] b = [None for r in range(n)] # input: for i in range(1,n): for j in range(1,n): a[i][j] = float(input("A({},{}) : ".format(i, j))) for i in range(1,n): b[i] = float(input("b({}) : ".format(i))) # algorithm: stop = 0 for j in range(1, n-1): for i in range(j+1, n): if a[i][j] != 0: mij = a[i][j] / a[j][j] else: break a[i][j] = 0 b[i] = b[i] - mij*b[j] for k in range(j+1, n): a[i][k] = a[i][k] - mij*a[j][k] # output: print("A = ") matprint(a) print("b = ") matprint([b,b])
false
228dca898f80a9175d8d7d612a0a8dc34d9846d7
saurabhgrewal718/python-problems
/factorial of a number.py
288
4.25
4
# Write a program which can compute the factorial of a given numbers. # The results should be printed in a comma-separated sequence on a single line. # Suppose the following input is supplied to the program: # 8 # Then, the output should be: # 40320 num=input() print("num is "+ num)
true
cb96167da7853f9385ead70b54e48d4db0af49fd
varunbelgaonkar/Beginner-Python-projects
/database_gui.py
2,704
4.125
4
from tkinter import * import sqlite3 root = Tk() root.title("Employee Data") root.geometry("400x400") #cxreating a databse #conn = sqlite3.connect("employee.db") #creating curser #c = conn.cursor() #creating table #c.execute("""CREATE TABLE employees( # emp_id integer, # first_name text, # last_name text, # age integer, # pay real # )""") # #inserting values in database def insert_data(): conn = sqlite3.connect("employee.db") c = conn.cursor() c.execute("INSERT INTO employees VALUES(:emp_id,:first_name,:last_name,:age,:pay)",{ 'emp_id':emp_id_t.get(), 'first_name':first_name_t.get(), 'last_name':last_name_t.get(), 'age':age_t.get(), 'pay':pay_t.get()}) conn.commit() emp_id_t.delete(0, END) first_name_t.delete(0, END) last_name_t.delete(0, END) age_t.delete(0, END) pay_t.delete(0, END) conn.close() def show(): conn = sqlite3.connect("employee.db") c = conn.cursor() c.execute("SELECT * FROM employees") data = c.fetchall() print(data) record = "" for records in data: record += str(records) + "\n" label = Label(root, text = record, padx = 10, pady = 10) label.grid(row = 9, column = 1, columnspan = 3) conn.close() ##employee details widget labels emp_id = Label(root, text="Emp_ID", padx = 10, pady = 10) first_name = Label(root, text="Name", padx = 10, pady = 10) last_name = Label(root, text="Last", padx = 10, pady = 10) age = Label(root, text="Age", padx = 10, pady = 10) pay = Label(root, text="Pay", padx = 10, pady = 10) #textbox emp_id_t = Entry(root, width = 30) first_name_t = Entry(root, width = 30) last_name_t = Entry(root, width = 30) age_t = Entry(root, width = 30) pay_t = Entry(root, width = 30) #submit button submit_btn = Button(root, text = "Add Record", padx = 50, pady = 20, command = insert_data) submit_btn.grid(row = 5, column = 1, columnspan = 3) #exit button exit_btn = Button(root, text = "Exit", padx = 71, pady = 20, command = root.quit) exit_btn.grid(row = 7, column = 1, columnspan = 3) #query button query_btn = Button(root, text = "Query", padx = 65, pady = 20, command = show) query_btn.grid(row = 6, column=1, columnspan = 3) #placing labels emp_id.grid(row=0, column = 0) first_name.grid(row=1, column = 0) last_name.grid(row=2, column = 0) age.grid(row=3, column = 0) pay.grid(row=4, column = 0) #placing textboxes emp_id_t.grid(row=0, column = 1, columnspan = 3) first_name_t.grid(row=1, column = 1, columnspan = 3) last_name_t.grid(row=2, column = 1, columnspan = 3) age_t.grid(row=3, column = 1, columnspan = 3) pay_t.grid(row=4, column = 1, columnspan = 3) root.mainloop()
false
35ef3abdfd3f7a7dab0e2cc1a1f2417e830c1bea
ZacharySmith8/Python40
/33_sum_range/sum_range.py
804
4.1875
4
def sum_range(nums, start=0, end=None): """Return sum of numbers from start...end. - start: where to start (if not provided, start at list start) - end: where to stop (include this index) (if not provided, go through end) >>> nums = [1, 2, 3, 4] >>> sum_range(nums) 10 >>> sum_range(nums, 1) 9 >>> sum_range(nums, end=2) 6 >>> sum_range(nums, 1, 3) 9 If end is after end of list, just go to end of list: >>> sum_range(nums, 1, 99) 9 """ count = 0 counter_list = nums[start:end] print(counter_list) for num in counter_list : count += num return count nums = [1, 2, 3, 4] print(sum_range(nums)) print(sum_range(nums,1)) print(sum_range(nums,end=2))
true
34e02349a424c11e8e25f72e28dfbfb21bd10501
Frank1126lin/Leecode
/reversenum.py
428
4.125
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # @File : reversenum.py # @Author: Frank # @Date : 2018-10-12 def reversenum(x): """ :type x: int :rtype: int """ if x < 0 and x > -2**31 and int(str(-x)[::-1]) < 2**31-1: return -(int(str(-x)[::-1])) elif x >= 0 and x < 2**31-1 and int(str(x)[::-1])<2**31-1: return int(str(x)[::-1]) else: return 0 print(reversenum(-123))
false
da50ea2dbed6771f589867f84304f543dcdb6ae4
sanjiv576/LabExercises
/Lab2/nine_leapYear.py
469
4.1875
4
""" Check whether the given year is leap year or not. If year is leap print ‘LEAP YEAR’ else print ‘COMMON YEAR’. Hint: • a year is a leap year if its number is exactly divisible by 4 and is not exactly divisible by 100 • a year is always a leap year if its number is exactly divisible by 400 """ year = int(input("Please, enter the year : ")) if (year % 4 == 0 or year % 400 == 0) and year % 100 != 0: print("LEAP YEAR") else: print("COMMON YEAR")
true
8ccdd26d1ecc5918c9736bb294ebc39b8b344c56
sanjiv576/LabExercises
/Lab4_Data_Structure__And_Iternation/Dictionary/Four_check_keys.py
291
4.46875
4
# Write a Python script to check if a given key already exists in a dictionary. dic1 = {1: 'one', 2: 'two', 3: 'three'} keyOnly = dic1.keys() check = int(input("Input a key : ")) if check in keyOnly: print(f"{check} key already exists.") else: print(f"{check} key is not in {dic1}")
true
9193689da08cab23f2b621569036570ea5d03bc2
sanjiv576/LabExercises
/Conditions/Second.py
330
4.5
4
""" If temperature is greater than 30, it's a hot day other wise if it's less than 10; it's a cold day; otherwise, it's neither hot nor cold. """ temp = float(input("Enter the temperature : ")) if temp > 30: print("It's s hot day ") elif temp < 10: print("It is a cold day") else: print("It is neither hot nor cold")
true
05bc68517729cf3bd4f2463c0b52b87f52799731
sanjiv576/LabExercises
/Lab2/ten_sumOfIntergers.py
456
4.25
4
# Write a Python program to sum of three given integers. However, if two values are equal, sum will be zero num1 = int(input("Enter the first integer number : ")) num2 = int(input("Enter the second integer number : ")) num3 = int(input("Enter the third integer number : ")) if num1 == num2 or num1 == num3 or num2 == num3: sum = 0 print(sum) else: sum = num1 + num2 + num3 print() print(f"The sum of {num1},{num2} and {num3} is {sum}")
true
4b69189aa69becee50a00c534ac15e1cb7814b7f
sanjiv576/LabExercises
/Lab2/eight_sum_of_three-digits.py
279
4.28125
4
""" Given a three-digit number. Find the sum of its digits. 10. """ num = int(input("Enter any three-digits number : ")) copidNum = num sum = 0 for i in range(3): remainder = copidNum % 10 sum += remainder copidNum //= 10 print(f"Sum of each digit of {num} is {sum}")
true
27d6d4a16a3acb9da7f3fc436d77ec1d1433416f
sanjiv576/LabExercises
/Lab4_Data_Structure__And_Iternation/Question_answers/Four_pattern.py
666
4.28125
4
""" Write a Python program to construct the following pattern, using a nested for loop. * ** *** **** ***** **** *** ** * """ for rows1 in range(1,6): for column_increment in range(1,rows1+1): print("*", end=" ") print() for rows2 in range(4,0,-1): for column_decrement in range(1,rows2+1): print("*", end=" ") print() """loop = 0 for row in range(1,10): for column_increment in range(row): if row >= 6: loop += 1 for column_decrement in range(4,1,-1): print("*", end=" ") print() else: print("*", end=" ") if row <= 5: print()"""
true
529b127ab15d54aa298124f2721c83d40a3f7aa5
sanjiv576/LabExercises
/Conditions/Five.py
848
4.125
4
""" game finding a secret number within 3 attempts using while loop import random randomNum = random.randint(1, 3) guessNum = int(input("Guess number from 1 to 10 : ")) attempt = 1 while attempt <= 2: if guessNum == randomNum: print("Congratulations! You have have found the secret number.") break else: again = int(input("Guess again : ")) attempt += 1 else: print("Sorry ! You have crossed the limitation.") """ import random randomNo = random.randint(0, 2) guessNo = int(input('Guess a number from 0 to 9 : ')) attempt = 1 while randomNo != guessNo: if attempt <= 2: guessNo = int(input('Guess again : ')) else: print("Sorry ! you've reached your limitation.") break attempt += 1 if guessNo == randomNo: print("Congratulations! You've found the secret number.")
true
9f51539430d010667a5c75af4521382f4a565761
sadashiv30/pyPrograms
/rmotr/class1-Datatypes/printNumbersWithStep.py
864
4.28125
4
""" Write a function that receives a starting number, an ending number (not inclusive) and a step number, and print every number in the range separated by that step. Example: print_numbers_with_a_step(1, 10, 2) > 1 > 3 > 5 > 7 > 9 Extra: * Use a while loop * Use a flag to denote if the ending number is inclusive or not: print_numbers_with_a_step(1, 10, 2, inclusive=True) * Use ranges """ def print_numbers_with_a_step(start, end, step): i=start while(i<=end): print i i+=step def print_numbers_with_a_step(start, end, step, inclusive): i=start if(inclusive): while(i<end): print i i+=step else: while(i<=end): print i i+=step def print_numbers_with_a_step3(start, end, step): list= range(start,end,step) print list
true
84d9e2001b0c977317c5b8a4b76f7b61f12fac76
sadashiv30/pyPrograms
/rmotr/class2-Lists-Tuples-Comprehensions/factorial.py
671
4.375
4
""" Write a function that produces all the members to compute the factorial of a number. Example: The factorial of the number 5 is defined as: 5! = 5 x 4 x 3 x 2 x 1 The terms o compute the factorial of the number 5 are: [5, 4, 3, 2, 1]. Once you have that function write other function that will compute the factorial using the reduce funcion (related to functiona programming). Example: terms = factorial_terms(5) # [5, 4, 3, 2, 1] factorial = compute_factorial(terms) # 120 """ def factorial_terms(a_number): terms = range(a_number,0,-1) return terms def compute_factorial(terms): fact=1; for i in terms: fact*=i return fact
true
b3525d32194630f56c9fcc3597096be6bf1e4e51
subaroo/HW08
/mimsmind0.py
2,341
4.65625
5
#!/usr/bin/env python # Exercise 1 # 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 random import sys ''' get a length of number from the comand line if no number, length = 1 create a number that has the right # of digits have the user guess a number, telling them the length of that number if correct: print congratulatory message and state number of guesses made elif too low: have them guess again and tell them it was too low else to high: have them guess again and tell them it was too high ''' def set_length(): '''Set the length of the computer generated number to the number set by the user or to one, if not set ''' user_length = len(sys.argv[1]) if user_length < 1: user_length = 1 return user_length else: return user_length def create_random(): '''Generate random number ''' computer_num = random.randint(1, 50) return computer_num def get_user_num(): '''Get the user's first guess and succeeding guesses if needed ''' user_number = raw_input("Guess a ?? digit number: ") try: user_guess = int(user_number) except: user_guess = raw_input("Try again: ") return get_user_num() else: return user_guess def test_numbers(): computer_num = create_random() guesses = 1 while True: user_guess = get_user_num() if user_guess == computer_num: print("Great job you got the number right in " + str(guesses) + " tries.") break else: if user_guess < computer_num: print("Your number is too low.") else: print("Your number was too high") guesses = guesses + 1 ############################################################################## def main(): # DO NOT CHANGE BELOW test_numbers() if __name__ == '__main__': main()
true
9afb638ca9a41c3b77c2ec6181f4b3f257c65196
L7907661/21-FunctionalDecomposition
/src/m1_hangman.py
2,152
4.4375
4
""" Hangman. Authors: Zeyu Liao and Chen Li. """ # done: 1. PUT YOUR NAME IN THE ABOVE LINE. # done: 2. Implement Hangman using your Iterative Enhancement Plan. ####### Do NOT attempt this assignment before class! ####### import random def main(): print('I will choose a random secret word from a dictionary.' 'You will set the MINIMUM length of that word') N = mm_length() M = wrong_words() print('You set the DIFFICULTY of the game by setting the number of unsuccessful choices you can make before' 'you LOSE the game') print('Here is what you currently know about the secret word:') words = word(N) empty = list(len(words) * '-') print(empty) hangman(words,M) play() def mm_length(): print('What MINIMUM length do you want for the secret word ?') N = input() return N def wrong_words(): print('How many unsuccessful choices do you want to allow yourself?') M = input() return M def word(N): while True: with open('words.txt') as f: string = f.read() aa = string.split() r = random.randrange(0,len(aa)) words = aa[r] if int(len(words)) >= int(N): break return words def hangman(words,M): empty = list(len(words) * '-') wrongtime = int(M) while True: print(' What letter do you want to try?') letter = input() if letter in words: for i in range(len(words)): if letter == words[i]: empty[i] = letter print('Your succeed') else: wrongtime = wrongtime -1 print("Sorry, there is no", letter, 'in the secret word. ') print('here is what you currently know about the secret word:') print(empty) if '-' not in empty: return print('Your succeed :)') if wrongtime == 0: return print(' You lose!','The secret word was:',words) print('You can still try', wrongtime, 'times') def play(): print('PLay another game? (y/n)') A = input() if A == 'y': main() main()
true
fcc92cf50ac64f94f3fba6983559bc15f095a705
noahnaamad/my-first-python-blog
/Untitled1.py
255
4.15625
4
# print "hello cruel world" #if 3 > 2: # print("it works!") #else: # print("uh oh") # this is a comment def hi(names): for name in names: print('hey ' + name + '!') print('whats up') hi(['noah', 'hoshi', 'spanky', 'mitzi'])
false
11bec9486cb05e5a2957249cb47d750f4a947934
ElficTitious/tarea3-CC4102
/utilities/math_functions.py
848
4.40625
4
from math import * def next_power_of_two(x): """Returns the next power of two after x. """ result = 1 << ceil(log2(x)) return result def is_power_of_two(x): """Returns if x is a power of two or not. """ return log2(x).is_integer() def prev_power_of_ten(x): """Returns the previous power of ten before x. """ result = 10 ** floor(log10(x)) return result def lower_sqrt(x): """Returns the lower square root of x, defined as 2^(floor(log2(x)/2)). """ result = 1 << floor(log2(x)/2) return result def upper_sqrt(x): """Returns the upper square root of x, defined as 2^(ceil(log2(x)/2)). """ result = 1 << ceil(log2(x)/2) return result if __name__ == "__main__": print(prev_power_of_ten(3)) print(is_power_of_two(8)) print(is_power_of_two(21))
true
d5a2fa6dbe4e5ba184c1ffc6b6d6f513946e6882
jonathanstallings/data-structures
/merge_sort.py
1,850
4.15625
4
"""This module contains the merge_srt method, which performs an in-place merge sort on a passed in list. Merge sort has a best case time complexity of O(n log n) when list is nearly sorted, and also a worst case of O(n log n). Merge sort is a very predictable and stable sort, but it is not adaptive. See the excellent 'sortingalgorithms.com' for more information. """ def merge_srt(un_list): """Perform an in-place merge sort on list. args: un_list: the list to sort """ if len(un_list) > 1: mid = len(un_list) // 2 left_half = un_list[:mid] right_half = un_list[mid:] merge_srt(left_half) merge_srt(right_half) x = y = z = 0 while x < len(left_half) and y < len(right_half): if left_half[x] < right_half[y]: un_list[z] = left_half[x] x += 1 else: un_list[z] = right_half[y] y += 1 z += 1 while x < len(left_half): un_list[z] = left_half[x] x += 1 z += 1 while y < len(right_half): un_list[z] = right_half[y] y += 1 z += 1 if __name__ == '__main__': even_half = range(0, 1001, 2) odd_half = range(1, 1000, 2) BEST_CASE = range(0, 1001) WORST_CASE = even_half + odd_half from timeit import Timer SETUP = """from __main__ import BEST_CASE, WORST_CASE, merge_srt""" best = Timer('merge_srt({})'.format(BEST_CASE), SETUP).timeit(1000) worst = Timer('merge_srt({})'.format(WORST_CASE), SETUP).timeit(1000) print("""Best case represented as a list that is already sorted\n Worst case represented as a list that is absolute reverse of sorted""") print('Best Case: {}'.format(best)) print('Worst Case: {}'.format(worst))
true
51433315d604c4cb973f97a875954c722674aa78
kristinadarroch/django
/Django-Python-Full-Stack-Web-Devloper-master/Python_Level_One/my-notes/lists.py
1,099
4.25
4
# LISTS my_list = ['adfsjkfdkfjdsk',1,2,3,23.2,True,'asd',[1,2,3]] print(my_list) # PRINTS THE LENGTH OF A LIST. this_list = [1,2,3] print(len(this_list)) print(my_list[0]) my_list[0] = 'NEW ITEM' print(my_list) # .append can add something to a list my_list.append('another new item - append') print(my_list) listtwo = ['a', 'b', 'c'] # .extend adds a list to another list my_list.extend(listtwo) print(my_list) # .pop returns the last item from a list anotherlist = ['a', 'b', 'c', 'd', 'e'] item = anotherlist.pop() # you can specify what item in the list you want taken off. firstone = anotherlist.pop(0) print(anotherlist) print(item) print(firstone) # .reverse() reverses the items in a list anotherlist.reverse() print(anotherlist) # .sort() will sort the numbers numericallist = [4,5,7,6,3,2,4,1] numericallist.sort() print(numericallist) # how to index a nested list alphabetlist = [1,2,['x','y','z']] print(alphabetlist[2][0]) matrix = [[1,2,3],[4,5,6],[7,8,9]] # LIST COMPREHENSION # row counts for each item in the list first_col = [row[0] for row in matrix] print(first_col)
true
e80183defbc0fadafe7c978157eaff786387f22d
GaikwadHarshad/ML-FellowShip-Program
/WEEK 1/program41.py
831
4.28125
4
""" Write a Python program to convert an integer to binary keep leading zeros. Sample data : 50 Expected output : 00001100, 0000001100 """ def convert_to_binary(num): if num < 0: return 0 else: i = 1 bin1 = 0 # loop for convert integer to binary number while num > 0: rem = num % 2 # get remainder multiply with ith and add to bin1 bin1 = bin1 + (rem * i) # divide num by 2 num //= 2 i *= 10 return bin1 n = 8 # method call convert = convert_to_binary(n) print("Binary conversion without leading zero's :", convert) # format binary number with leading zero's print("Binary conversion with leading zero's : "+format(n, '08b')) print("Binary conversion with leading zero's : "+format(n, '010b'))
true
cc7a4731ccb33f08769d283c87cf504a2b50be76
GaikwadHarshad/ML-FellowShip-Program
/WEEK_2/Tuple/program1.py
257
4.28125
4
""" Write a Python program to create a tuple. """ class Tuple: # creating tuple tuple1 = (2, 3, 5, 6, 5) def create_tuple(self): print("Tuple : ", self.tuple1) # instance creation Tuple_object = Tuple() Tuple_object.create_tuple()
false
beb2df68eb4747c631909dad5c61ab3b01e5f902
GaikwadHarshad/ML-FellowShip-Program
/WEEK_2/String/program9.py
1,653
4.40625
4
""" Write a Python program to display formatted text (width=50) as output. """ from myprograms.Utility import UtilityDS class String9: string = ''' Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java.''' # perform operation on string def format_string(self): while 1: print("--------------------------------------------------") print("1.Display String""\n""2.Get format result""\n""3.Exit") try: choice = int(input("Enter choice :")) # validate choice ch = UtilityDS.validate_num(choice) if ch: if choice == 1: print("The String : ", self.string) elif choice == 2: if self.string.__len__() < 1: print("Enter string first") else: # get formatted result of string result = UtilityDS.format_string(self.string) print(result) elif choice == 3: exit() else: print("Invalid choice") else: print("Enter choice between 1 - 3") except Exception as e: print(e) # instantiation String9_object = String9() String9_object.format_string()
true
533a25953d7f4b983fb28c0895016e3c72231845
GaikwadHarshad/ML-FellowShip-Program
/WEEK 2/List/program11.py
1,152
4.125
4
""" Write a Python program to generate all permutations of a list in Python. """ from myprograms.Utility import UtilityDS class List11: create = [] k = 0 @staticmethod # function to perform operations on list def specified_list(): while 1: print("---------------------------------------------------") print("1.Generate permutations of list ""\n""2.Exit") try: choice = int(input("Enter any choice :")) # validating choice number ch = UtilityDS.validate_num(choice) if ch: # generate permutation of list if choice == 1: li = [1, 2, 3] print("List is : ", li) UtilityDS.perm(li) elif choice == 2: # exit from program exit() else: print("Invalid choice") except Exception as e: print(e) # instantiation of class List11_object = List11() List11_object.specified_list()
true
2de26bfd186e7ff89dc92e968b9db2125039416a
GaikwadHarshad/ML-FellowShip-Program
/WEEK 2/Dictionary/program7.py
1,733
4.21875
4
"""Write a Python program to print all unique values in a dictionary. Sample Data : [{"V":"S001"},{"V": "S002"},{"VI": "S001"},{"VI": "S005"},{"VII":"S005"},{"V":"S009"},{"VIII":"S007"}] Expected Output : Unique Values: {'S005', 'S002', 'S007', 'S001', 'S009'}. """ from myprograms.Utility import UtilityDS class Unique: # function definition for performing to get unique values def unique_val(self): sample = [{"V": "S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII": "S005"}, {"V": "S009"}, {"VIII": "S007"}] print("Original data : ", sample) while 1: try: print("1: Find unique values in dictionary ""\n""2: Original dictionary""\n""3: Exit") ch = int(input("Enter your choice: ")) # validate choice number choice = UtilityDS.validate_num(ch) if choice: if ch == 1: # get all unique values in dictionary unique_data = UtilityDS.unique_values(sample) print("Unique value in dictionary : ", unique_data) elif ch == 2: # get original dictionary print("Original Dictionary : ", sample) elif ch == 3: exit() else: print("please enter valid choice") else: # if entered literals except int print("please enter number only") except Exception as e: print(e) # instance creation Unique_object = Unique() Unique_object.unique_val()
false
cdf3c07056e0fa2a6421a02aeefb69e535947ca6
GaikwadHarshad/ML-FellowShip-Program
/WEEK 1/program6.py
360
4.1875
4
""" Write a Python program to calculate number of days between two dates. Sample dates : (2014, 7, 2), (2014, 7, 11) Expected output : 9 days. """ from datetime import date date1 = date(2019, 2, 14) date2 = date(2019, 2, 26) calculatedDays = date2 - date1 delta = calculatedDays print("Total numbers of days between two dates :", delta.days, "days")
true
8bab9aa97d88d37ba0b094f84a1c61c09a9e4e64
GaikwadHarshad/ML-FellowShip-Program
/WEEK 2/Tuple/program5.py
737
4.15625
4
""" Write a Python program to find the repeated items of a tuple. """ from myprograms.Utility import UtilityDS class Tuple5: tuple1 = (3, 5, 6, 5, 4, 3) # function performing on tuple to get items repeat or not def repeat_items(self): try: print("Tuple1 : ", self.tuple1) # function call to check whether item repeated or not find = UtilityDS.get_repeat_items(self.tuple1) if find: # if repeat item found print("Items is repeated : ", find) else: print("No items are repeated") except Exception as e: print(e) # instance create Tuple5_object = Tuple5() Tuple5_object.repeat_items()
true
77e973baa87d0c6e53dda194e49c79945f734a61
Oyelowo/Exercise-2
/average_temps.py
1,161
4.5
4
# -*- coding: utf-8 -*- """ Prints information about monthly average temperatures recorded at the Helsinki Malmi airport. Created on Thu Sep 14 21:37:28 2017 @author: oyedayo oyelowo """ #Create a script called average_temps.py that allows users to select a #month and have the monthly average temperature printed to the screen. #For example, if the user sets month to "March", the script will display #The average temperature in Helsinki in March is -1.0""" #create list for the 12 months of the year month = ['January', 'February', 'March', 'April', 'May', 'June', 'July',\ 'August', 'September', 'October' ,'November', 'December'] #create list for average temperature of each month temp = [-3.5, -4.5, -1.0, 4.0, 10.0, 15.0, 18.0, 16.0, 11.5, 6.0, 2.0, -1.5] #set the selected month selectedMonth = 'April' #find the location of the selected month indexMonth = month.index(selectedMonth) #get the average temperature of the selected month monthTemp = temp[indexMonth] #print the month and the average temperature of that month print 'The average temperature in Helsinki in', selectedMonth , 'is', monthTemp
true
cc1fdd0a07c688ee2bf9c5449765ed328f4455e4
udbhavsaxena/pythoncode
/ex1/ex3.py
420
4.1875
4
print "I will now count my chickens:" print "Hens", 25+30/6 print "Roosters", 100-25 * 3%4 print "Now I will count my eggs:" print 3+2+1-5+4%2-1/10 print "Is it true that 3+2<5-7?" print 3+2<5-7 print "What's 3+2?", 3+2 print "What's 5-7?", 5-7 print "Oh that is why it is false" print "How about some more" print "Is is greater?", 5>-2 print "Is it greater or equal?", 5>=-2 print "Is it less or equal?", 5<=2
true
6a0ddaf8d7fef42fb22e047150e9914dc118efb7
derekb63/ME599
/lab2/sum.py~
683
4.375
4
#! usr/bin/env python # Derek Bean # ME 599 # 1/24/2017 # Find the sum of a list of numbers using a for loop def sum_i(list): list_sum = 0 for i in list: list_sum += i return list_sum # Caclulate the sum of a list of numbers using recursion def sum_r(list): list_sum = 0 return list_sum if __name__ == '__main__': example_list = [1, 2, 3, 4, 5, 6] if sum_i(example_list) != example_list.sum(): print 'The function sum_i has returned an incorrent value' else: print 'sum_i returned the correct value' if sum_r(example_list) != example_list.sum(): print 'The function sum_r has returned an incorrent value' else: print 'sum_r returned the correct value'
true
c55dfb4e6512462c5d25aefeb533de1fe4579993
derekb63/ME599
/hw1/integrate.py
2,485
4.3125
4
#! usr/bin/env python # Derek Bean # ME 599 # Homework 1 # 1/24/2017 from types import LambdaType import numpy as np import matplotlib.pyplot as plt ''' Integrate uses the right rectangle rule to determine the definite integral of the input function Inputs: f: a lambda function to be inetgrated a: the lower bound of the variables b: the upper bound of the variables step: the step size or delta used for the integration Outputs: value: the value resulting from the definite integration ''' def integrate(f, a, b, step=0.001): if isinstance(f, LambdaType) is False: print 'The input function is not of type: LambdaType' return None try: float(step) except: print 'The step size is not one of the accepted types: int or float' return None else: # This try block is for computing the integral of an n variable # function f(x,y,z,...,n) with except block being for a function # of x only. try: if len(a) != len(b): print 'The interval variables a and b are not same length' return None value = 0 limits = [] delta = [step]*len(a) try: for i in xrange(len(a)): limits.append([a[i], b[i]]) except: limits = [a, b] interval = [] for idx, val in enumerate(limits): interval.append(np.arange(val[0], val[1]+step, step)) interval = np.transpose(interval) for i in interval: value += f(*i)*np.prod(delta) return value except: value = 0 interval = np.arange(a, b+step, step) for i in interval: value += f(i)*step return value # Function to define the implicit eqution of a circle def circle(x, y): return x * x + y * y - 1 def line(x): return x if __name__ == '__main__': # Test the integral of a circle test_function = circle a = (-1, -1) b = (1, 1) area_circle = integrate(test_function, a, b) print 'Circle Error : ', abs(area_circle) # Test the integral of a line at different steps area_line = [] steps = np.linspace(1e-6, 0.1, 1000) for i in steps: area_line.append(integrate(line, 0, 1, i)) error = [abs(i-0.5) for i in area_line] plt.plot(steps, error, '-k')
true
fd4c56fb77d2bca1b5837022acf9da5ab71d5082
AR123456/python-deep-dive
/work-from-100-days/Intermediate days 15-100/Day-19/turtle-race-anne-final/main.py
1,318
4.28125
4
from turtle import Turtle, Screen from random import randint is_race_on = False screen = Screen() # set screen size using setup method screen.setup(width=500,height=400) # set the output of the screen.textinput() to user_bet user_bet =screen.textinput(title="Make your bet", prompt="Who do you think will win the race? :") colors =["red", "orange", "yellow", "green", "blue", "purple"] # need to use specific vals or y so that they are spaced out correctly y_val = [-70, -40, -10, 20, 50, 80] all_turtles=[] for i in range(0, 6): new_turtle = Turtle("turtle") new_turtle.penup() new_turtle.color(colors[i]) print(y_val[i]) new_turtle.goto(-230, y_val[i]) # each new_turtle has different state all_turtles.append(new_turtle) if user_bet: is_race_on = True while is_race_on: for turtle in all_turtles: if turtle.xcor() >= 230: is_race_on = False winning_color = turtle.pencolor() if winning_color == user_bet: print(f"You won ! The {winning_color} turtle is the winner") else: print(f"You lost. the {winning_color} turtle is the winner ") rand_distance=randint(0, 10) turtle.forward(rand_distance) # stopping x val of 250 - size of turtle 40 /2 or 230 screen.exitonclick()
true
4409d6ef0ae89f509322a9987188386ae484e566
AR123456/python-deep-dive
/work-from-100-days/Intermediate days 15-100/Day-25/Day-26-pandas-rows-cols/main.py
1,617
4.21875
4
# # weather_list = open("weather_data.csv", "r") # print(weather_list.readlines()) # # with open("weather_data.csv") as data_file: # data = data_file.readlines() # print(data) # # use pythons csv library https://docs.python.org/3/library/csv.html # import csv # with open("weather_data.csv") as data_file: # data = csv.reader(data_file) # temperatures = [] # #data is now an object # for row in data: # # print(row) # # print(row[1]) # # dont print the temp row # if row[1] != "temp": # # temperatures.append(row[1]) # # convert to int # temperatures.append(int(row[1])) # print(temperatures) import pandas data = pandas.read_csv("weather_data.csv") data_dict = data.to_dict() print(data_dict) temp_list=data["temp"].to_list() print(temp_list) avg_temp= round(sum(temp_list)/len(temp_list)) print(avg_temp) # using the mean method from the pandas library avg_pandas_temp = data["temp"].mean() print(avg_pandas_temp) max_pandas_temp = data["temp"].max() print(max_pandas_temp) # using data.temp print(data.temp) #Get data from row print(data[data.day == "Monday"]) print(data[data.temp == data.temp.max()]) monday = data[data.day == "Monday"] print(monday.condition) monday = data[data.day == "Monday"] monday_temp = int(monday.temp) monday_temp_F = monday_temp * 9/5 + 32 print(monday_temp_F) print(data.columns) #### create a csv from data in python data_dict = { "students":["Amy", "James", "Brad"], "scores":[76,56,65] } data = pandas.DataFrame(data_dict) # print(data) data.to_csv("annes_data_csv")
true
ebb49e7ace998b22a0c5d71abdd116d0a3463b8d
AR123456/python-deep-dive
/work-from-100-days/Intermediate days 15-100/Day-24/Day-24-file-write-with/main.py
709
4.1875
4
# # file= open("my_file.txt") # # contents =file.read() # print(contents) # #also need to close the file # file.close() ####### another way to open a file that dosent require an explice file.close, does it for you #this is read only mode - mode defaluts to "r with open("my_file.txt")as file: contents = file.read() print(contents) #######3 #write to a file with open("my_new.txt", mode="w")as file: # This overwrites, or if no file exists it will be created file.write("Some new text ") # write by appending to the file with open("my_file.txt", mode="a")as file: file.write("\nAnd soup is good too ! ") with open("my_file.txt")as file: contents = file.read() print(contents)
true
f79bc79ea4993f59665d55a4e3b5671920e575cf
AR123456/python-deep-dive
/work-from-100-days/Intermediate days 15-100/Day-21/Class-Inheritance/main.py
814
4.40625
4
class Animal: def __init__(self): #defining attributes self.num_eyes = 2 # defining method associated with the animal class def breathe(self): print("Inhale, exhale.") # passing Animal into Fish class so Fish has all the attributes # and methonds from the Animal class, then can have some of its own class Fish(Animal): def __init__(self): # making call to super class which in this case is Animal # and init it super().__init__() def breathe(self): #bring in super class and call breath super().breathe() #adding this to just the Fish class print("doing this underwater.") def swim(self): print("moving in water.") # creating object from the fish class nemo = Fish() nemo.breathe() print(nemo.num_eyes)
true
fea9c9a4deb9d09218eb3957ed0a74fe7b760609
DenysZakharovGH/Python-works
/HomeWork4/The_Guessing_Game.py
624
4.15625
4
#The Guessing Game. #Write a program that generates a random number between 1 and 10 and let’s #the user guess what number was generated. The result should be sent back #to the user via a print statement. import random RandomVaried = random.randint(0,10) while True: UserGuess = int(input("try to guess the number from 0 to 10 :")) if UserGuess>=0 and UserGuess <= 10: if UserGuess > RandomVaried: print("Less") elif UserGuess < RandomVaried: print("more") else: print("BINGO") else:print("wrong number") if(input("q for try again") !='q'): break
true
47bcd9f7c97992fc73a6c7df2f318f760ed1a67e
DenysZakharovGH/Python-works
/PythonHomework_6_loops.py
943
4.375
4
#1 #Make a program that generates a list that has all squared values of integers #from 1 to 100, i.e., like this: [1, 4, 9, 16, 25, 36, …, 10000] Squaredlist = [x**2 for x in range(100)] print(Squaredlist) #2 #Make a program that prompts the user to input the name of a car, the program #should save the input in a list and ask for another, and then another, #until the user inputs ‘q’, then the program should stop and the list of #cars that was produced should be printed. UserCarsList=[] while True: UserCarsList.append(input("Write a new car there :")) if input("press q for exit") == 'q': break for i in UserCarsList: print(i,end=" ") #3 #Start of with any list containing at least 10 elements, then print all elements #in reverse order. CusualList = ["Table", "Chairs", 10, 3.1415926, 0x0010, "Soft", 228, 'q',UserCarsList[0],UserCarsList ] print(CusualList) ReverseList =CusualList[::-1] print(ReverseList)
true
2213d66214f18d0bf2e78837e6de8b2ed5058a9e
vamshidhar-pandrapagada/Data-Structures-Algorithms
/Array_Left_Rotation.py
1,169
4.3125
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 11 04:32:11 2017 @author: Vamshidhar P """ """A left rotation operation on an array of size shifts each of the array's elements unit to the left. For example, if left rotations are performed on array 1 2 3 4 5, then the array would become 3 4 5 1 2 Given an array of n integers and a number d, perform left rotations on the array. Then print the updated array as a single line of space-separated integers. Input Format The first line contains two space-separated integers denoting the respective values of n (the number of integers) and d (the number of left rotations you must perform). The second line contains space-separated integers describing the respective elements of the array's initial state. """ def array_left_rotation(a, n, k): shiftedArray = a.copy() for j in range(n): new_position = (j - k) + n if new_position > n - 1: new_position = j - k shiftedArray[new_position] = a[j] return shiftedArray n, k = map(int, input().strip().split(' ')) a = list(map(int, input().strip().split(' '))) answer = array_left_rotation(a, n, k); print(*answer, sep=' ')
true
d533d93ced02eb641961555b90435128c9489dae
rohangoli/PythonAdvanced
/Leetcode/LinkedList/p1215.py
1,863
4.1875
4
## Intersection of Two Linked Lists # Example 1: # Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 # Output: Intersected at '8' # Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). # From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. # Example 2: # Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 # Output: Intersected at '2' # Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). # From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. # Example 3: # Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 # Output: No intersection # Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. # Explanation: The two lists do not intersect, so return null. # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: hashSet = set() temp = headA while temp!=None: hashSet.add(id(temp)) temp = temp.next temp = headB while temp!=None: if id(temp) in hashSet: return temp temp = temp.next return None
true
010f18a43932a52eb66c529dd57b85243f369b93
rohangoli/PythonAdvanced
/Leetcode/Arrays/p1164.py
672
4.25
4
## Reverse Words in a string # Example 1: # Input: s = "the sky is blue" # Output: "blue is sky the" # Example 2: # Input: s = " hello world " # Output: "world hello" # Explanation: Your reversed string should not contain leading or trailing spaces. # Example 3: # Input: s = "a good example" # Output: "example good a" # Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. class Solution: def reverseWords(self, s: str) -> str: # N=len(s) temp = [] for x in s.split(): if x!='': temp.append(x) return " ".join(temp[::-1])
true
496a7816bc06781a0f66278a8d6998a459e73d29
rohangoli/PythonAdvanced
/Leetcode/Trie/p1047.py
2,071
4.28125
4
## Implement Trie (Prefix Tree) # Example 1: # Input # ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] # [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] # Output # [null, null, true, false, true, null, true] # Explanation # Trie trie = new Trie(); # trie.insert("apple"); # trie.search("apple"); // return True # trie.search("app"); // return False # trie.startsWith("app"); // return True # trie.insert("app"); # trie.search("app"); // return True class TrieNode: def __init__(self): self.children = dict() self.isWord = False class Trie: def __init__(self): self.root = TrieNode() #print('-'*30) def insert(self, word: str) -> None: #print('insert:start') curr = self.root for char in word: #print(curr.children) if char not in curr.children: curr.children[char] = TrieNode() curr = curr.children[char] curr.isWord = True #print("insert", word) def search(self, word: str) -> bool: #print("search:start") curr = self.root for char in word: #print(curr.children) if char not in curr.children: #print('search: FALSE') return False curr = curr.children[char] if curr.isWord: #print('search: TRUE') return True else: #print('search: FALSE') return False def startsWith(self, prefix: str) -> bool: #print("startWith:start") curr = self.root for char in prefix: #print(curr.children) if char not in curr.children: #print('startsWith: FALSE') return False curr = curr.children[char] #print('startsWith: TRUE') return True # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
false
375d845bd8d74cc52a913e2fa0bb47bbab49196d
mosesxie/CS1114
/HW #4/hw4q2a.py
361
4.15625
4
userCharacter = input("Enter a character: ") if userCharacter.isupper(): print(userCharacter + " is a upper case letter.") elif userCharacter.islower(): print(userCharacter + " is a lower case letter.") elif userCharacter.isdigit(): print(userCharacter + " is a digit.") else: print(userCharacter + " is a non-alphanumeric character.")
false
0573712cf14f4e7fb92107ddee746a70dff5d9e2
mosesxie/CS1114
/Lab #4/q1.py
485
4.125
4
xCoordinate = int(input("Enter a non-zero number for the X-Coordinate: ")) yCoordinate = int(input("Enter a non-zero number for the Y-Coordinate: ")) if xCoordinate > 0 and yCoordinate > 0: print("The point is in the first quadrant") elif xCoordinate < 0 and yCoordinate > 0: print("The point is in the second quadrant") elif xCoordinate < 0 and yCoordinate < 0: print("The point is in the third quadrant") else: print("The point is in the fourth quardrant")
true
98612114f9f90aa761c9a75921703e0b96f78c5f
apaskulin/euler
/problems.py
1,989
4.15625
4
#!/user/bin/env python2 def problem_01(): # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. sum = 0 for i in range(1, 1000): if i % 3 == 0 or i % 5 == 0: sum = sum + i return sum def problem_02(): # Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. sum = 0 prev = 1 curr = 1 while curr <= 4000000: if curr % 2 == 0: sum = sum + curr next = prev + curr prev = curr curr = next print sum def problem_03(): # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? result = factorize(600851475143) print result[-1] def factorize(num): factors = [] divisor = 2 while num != 1: if num % divisor == 0: num = num / divisor factors.append(divisor) else: divisor = divisor + 1 return factors def is_palindrome(num): num = str(num) if num[::-1] == num: return True else: return False def problem_04(): # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. current = 0 for multi1 in range(100,1000): for multi2 in range(100,1000): product = multi1 * multi2 if is_palindrome(product): if current < product: current = product print current print problem_04()
true
6fd9f34ee976576be14c02a6e9aebbd12d504a30
jonathan-durbin/fractal-stuff
/gif.py
1,371
4.125
4
#! /usr/bin/env python3 # gif.py """Function to generate a gif from a numbered list of files in a directory.""" def generate_gif(directory: ("Folder name", "positional"), image_format: ('Image format', 'positional') = '.png', print_file_names=False): """Generate a gif from a numbered list of files in a directory.""" import imageio from glob import glob from natsort import natsorted images = [] # Create a list of file names in the specified directory filenames = glob(directory + '/*' + image_format) filenames = natsorted(filenames, key=lambda y: y.lower()) # Sort the list 'filenames' using the traditional method. # Traditional method - # isolate the entire first number in the string, then sort by that number # If this step is not included, # files will be sorted like so: 0, 100, 110, 200, 3, 420, etc... if print_file_names: # For troubleshooting for i in filenames: print(i) for filename in filenames: images.append(imageio.imread(filename)) # Append each file to the list that will become the gif imageio.mimsave(directory + '.gif', images) # Save the gif as the name of the directory # that the images were generated from return if __name__ == "__main__": import plac plac.call(generate_gif)
true
010fb9b9923482c36309301fc16ea978fb7cd52c
yunusemree55/PythonBTK
/lists/list-comprehension.py
653
4.1875
4
for x in range(10): print(x) numbers = [x for x in range(10)] print(numbers) for x in range(10): print(x**2) numbers = [x**2 for x in range(10)] print(numbers) numbers = [x*x for x in range(10) if x % 3 == 0] print(numbers) myString = "Hello" myList = [letter for letter in myString] print(myList) years = [1983,1999,2008,1956,1986] ages = [2021 - year for year in years] print(ages) results = [x if x %2 == 0 else "TEK" for x in range(1,10)] print(results) results = [] for x in range(3): for y in range(3): results.append((x,y)) print(results) numbers = [(x,y) for x in range(3) for y in range(3)] print(numbers)
false
c982dd14121836aa11c9aa226a665c5b8cfc80ea
yunusemree55/PythonBTK
/otherss/iterators.py
325
4.21875
4
liste = [1,2,3,4,5] iterator = iter(liste) # try: # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) # except StopIteration: # print("Hata ! İndex dışına çıkıldı") print(next(iterator))
false
bcb9a6a66fa28599294e53248a4e3fc55da636e2
ankawm/NowyProjektSages
/exception_catch_finally.py
1,415
4.46875
4
""" * Assignment: Exception Catch Finally * Required: yes * Complexity: easy * Lines of code: 8 lines * Time: 8 min English: 1. Convert value passed to the function as a `degrees: int` 2. If conversion fails, raise exception `TypeError` with message: 'Invalid type, expected int or float' 3. Use `finally` to print `degrees` value 4. Non-functional requirements a. Write solution inside `result` function b. Mind the indentation level 5. Run doctests - all must succeed Polish: 1. Przekonwertuj wartość przekazaną do funckji jako `degrees: int` 2. Jeżeli konwersja się nie powiedzie to podnieś wyjątek `TypeError` z komunikatem 'Invalid type, expected int or float' 3. Użyj `finally` do wypisania wartości `degrees` 4. Wymagania niefunkcjonalne a. Rozwiązanie zapisz wewnątrz funkcji `result` b. Zwróć uwagę na poziom wcięć 5. Uruchom doctesty - wszystkie muszą się powieść Tests: >>> import sys; sys.tracebacklimit = 0 >>> result(1) 1 >>> result(180) 180 >>> result(1.0) 1 >>> result('one') Traceback (most recent call last): TypeError: Invalid type, expected int or float """ def result(degrees): try: degrees = int(degrees) except ValueError: raise TypeError('Invalid type, expected int or float') finally: print(degrees)
false
72cd03a29488ec0cae62134473df244739a548f1
ankawm/NowyProjektSages
/type_int_trueDiv.py
1,740
4.40625
4
""" * Assignment: Type Int Bits * Required: yes * Complexity: easy * Lines of code: 3 lines * Time: 3 min English: 1. Calculate altitude in kilometers: a. Kármán Line Earth: 100_000 m b. Kármán Line Mars: 80_000 m c. Kármán Line Venus: 250_000 m 2. In Calculations use floordiv (`//`) 3. Run doctests - all must succeed Polish: 1. Oblicz wysokości w kilometrach: a. Linia Kármána Ziemia: 100_000 m b. Linia Kármána Mars: 80_000 m c. Linia Kármána Wenus: 250_000 m 2. W obliczeniach użyj floordiv (`//`) 3. Uruchom doctesty - wszystkie muszą się powieść References: * Kármán line (100 km) - boundary between planets's atmosphere and space Hints: * 1 km = 1000 m Tests: >>> import sys; sys.tracebacklimit = 0 >>> assert karman_line_earth is not Ellipsis, \ 'Assign result to variable: `karman_line_earth`' >>> assert karman_line_mars is not Ellipsis, \ 'Assign result to variable: `karman_line_mars`' >>> assert karman_line_venus is not Ellipsis, \ 'Assign result to variable: `karman_line_venus`' >>> assert type(karman_line_earth) is int, \ 'Variable `karman_line_earth` has invalid type, should be int' >>> assert type(karman_line_mars) is int, \ 'Variable `karman_line_mars` has invalid type, should be int' >>> assert type(karman_line_venus) is int, \ 'Variable `karman_line_venus` has invalid type, should be int' >>> karman_line_earth 100 >>> karman_line_mars 80 >>> karman_line_venus 250 """ m = 1 km = 1000 * m # int: 100_000 meters in km karman_line_earth = 100000 // km # int: 80_000 meters in km karman_line_mars = 80000 // km # int: 250_000 meters in km karman_line_venus = 250000 // km
false
1c5790befa09be2072c7e663f8abf862eceb4458
ankawm/NowyProjektSages
/conditional_modulo_operator.py
1,539
4.34375
4
""" * Assignment: Conditional Operator Modulo * Required: yes * Complexity: easy * Lines of code: 3 lines * Time: 3 min English: 1. Read a number from user 2. User will input `int` and will not try to input invalid data 3. Define `result: bool` with parity check of input number 4. Number is even, when divided modulo (`%`) by 2 reminder equal to 0 5. Do not use `if` statement 6. Run doctests - all must succeed Polish: 1. Wczytaj liczbę od użytkownika 2. Użytkownika poda `int` i nie będzie próbował wprowadzać niepoprawnych danych 3. Zdefiniuj `result: bool` z wynikiem sprawdzania parzystości liczby wprowadzonej 4. Liczba jest parzysta, gdy dzielona modulo (`%`) przez 2 ma resztę równą 0 5. Nie używaj instrukcji `if` 6. Uruchom doctesty - wszystkie muszą się powieść Hints: * `%` has different meaning for `int` and `str` * `%` on `str` is overloaded as a string formatting * `%` on `int` is overloaded as a modulo division Tests: >>> import sys; sys.tracebacklimit = 0 >>> assert result is not Ellipsis, \ 'Assign result to variable: `result`' >>> assert type(result) is bool, \ 'Variable `result` has invalid type, should be bool' >>> result True """ from unittest.mock import MagicMock # Simulate user input (for test automation) input = MagicMock(side_effect=['4']) number = input('What is your number?: ') # bool: Whether input number is even or odd (modulo divide) result = float(number) % 2 == 0 print(result)
false
ba13ea5794eb0940acd21f591f84f13514468452
bsadoski/entra21
/aula11/create-db.py
969
4.28125
4
#sqlite3 já faz parte do python :D import sqlite3 # isso cria o banco, caso não exista! conn = sqlite3.connect('poke.db') # para fazermos nossas operações, sempre precisaremos de um cursor cursor = conn.cursor() # criando a tabela (schema) cursor.executescript(""" CREATE TABLE treinadores( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, nome TEXT NOT NULL, idade INTEGER, cidade TEXT ); CREATE TABLE pokemons ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, nome TEXT NOT NULL, tipo TEXT NOT NULL ); CREATE TABLE pokemons_treinador ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, id_treinador INTEGER NOT NULL, id_pokemon INTEGER NOT NULL, data_capturado DATE, FOREIGN KEY (id_treinador) references treinadores(id), FOREIGN KEY (id_pokemon) references pokemons(id) ); """) print('Tabela criada com sucesso.') # isso fecha a conexão conn.close()
false
8cc2bcc6aa36aa941b90bb538609c818e6509556
angelmtenor/AIND-deep-learning
/L3_NLP/B_read_text_files.py
1,140
4.25
4
"""Text input functions.""" import os import glob def read_file(filename): """Read a plain text file and return the contents as a string.""" # Open "filename", read text and return it with open(filename, 'r') as f: text = f.read() return text def read_files(path): """Read all files that match given path and return a dict with their contents.""" # Get a list of all files that match path (hint: use glob) files = glob.glob(path) my_dict = dict() # Read each file using read_file() for file in files: content = read_file(file) # Store & return a dict of the form { <filename>: <contents> } filename = os.path.basename(file) my_dict[filename] = content # Note: <filename> is just the filename (e.g. "hieroglyph.txt") not the full path ("data/hieroglyph.txt") return my_dict def example(): # Test read_file() print(read_file("data/input.txt")) # Test read_files() texts = read_files("data/*.txt") for name in texts: print("\n***", name, "***") print(texts[name]) if __name__ == '__main__': example()
true
e3c201cfb4a65055a71a83dc8e570fb6db86ef1c
ebinezh/power-of-number
/power of a number.py
221
4.15625
4
# power of a number n=float(input("Enter a number:")) e=int(input("Enter exponent: ")) for i in range(1, e): x=n**e print(n, "^", e, "=", x) # thanks for watching # like, share & subscribe # Dream2code
false
9414f815d96dcbea31a100ce8c005334c0a6afb8
LeBoot/Practice-Code
/Python/number_divis_by_2_and_or_3.py
704
4.3125
4
#Ask for favorite number. favnum = int(input("What is your favorite whole number? ").strip()) #Divisible by 2. if (favnum/2 == int(favnum/2)) and (not(favnum/3 == int(favnum/3))) : print("Divisible by 2 but not by 3.") #Divisible by 3. elif (not(favnum/2 == int(favnum/2))) and (favnum/3 == int(favnum/3)) : print("Divisible by 3 but not by 2.") #Divisible by 2 and 3. elif (favnum/2 == int(favnum/2)) and (favnum/3 == int(favnum/3)) : print("Divisible by both 2 and 3.") #Divisible by neither 2 nor 3. elif (not(favnum/2 == int(favnum/2))) and (not(favnum/3 == int(favnum/3))) : print("Divisible by neither 2 nor 3.") #Other option. else : print("Programmer missed something.")
false
705d9deaa4f8bcec1980a6756d2e18cfbf7e955e
LeBoot/Practice-Code
/Python/Udemy-The-Python-Bible/name_program.py
309
4.1875
4
#Ask user for first then last name. namein = input("What is your full name? ").strip() #Reverse order to be last, first. forename = namein[:namein.index(" "):] surname = namein[namein.index(" ") + 1 ::] #Create output. output = "Your name is {}, {}.".format(surname, forename) #Print output. print(output)
true
cc596f40bc8604a4f83499ae2521c2ebf336b734
ericachesley/code-challenges
/zero-matrix/zeromatrix.py
1,293
4.25
4
"""Given an NxM matrix, if a cell is zero, set entire row and column to zeroes. A matrix without zeroes doesn't change: >>> zero_matrix([[1, 2 ,3], [4, 5, 6], [7, 8, 9]]) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] But if there's a zero, zero both that row and column: >>> zero_matrix([[1, 0, 3], [4, 5, 6], [7, 8, 9]]) [[0, 0, 0], [4, 0, 6], [7, 0, 9]] Make sure it works with non-square matrices: >>> zero_matrix([[1, 0, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) [[0, 0, 0, 0], [5, 0, 7, 8], [9, 0, 11, 12]] """ def zero_matrix(matrix): """Given an NxM matrix, for cells=0, set their row and column to zeroes.""" rows_to_zero = set() cols_to_zero = set() for row in range(len(matrix)): for col in range(len(matrix[0])): if matrix[row][col] == 0: rows_to_zero.add(row) cols_to_zero.add(col) for row in rows_to_zero: for col in range(len(matrix[row])): matrix[row][col] = 0 for row in range(len(matrix)): if row not in rows_to_zero: for col in cols_to_zero: matrix[row][col] = 0 return matrix if __name__ == "__main__": import doctest if doctest.testmod().failed == 0: print("\n*** TESTS PASSED! YOU'RE DOING GREAT!\n")
true
2a32fb6338772f353e2432df396221bc027a6838
MikeyABedneyJr/CodeGuild
/python_basic_exercises/class2(dictionaries).py
519
4.4375
4
dictionary = {'name':'Mikey', 'phone_number': '867-5309'} #python orders in most memory efficient manner so phone # might appear first print dictionary['name'] dictionary['name'] = 'Mykee' #changed value of name print dictionary['name'] dictionary['age'] = 32 print dictionary #just added a key named "age" which is 32 {'age': 32, 'name': 'Mykee'} dictionary = {'Chantel': {'name' : 'Chantel', 'phone': 'you wish'}} print dictionary['Chantel']['phone'] #pulls Chantel key, then accesses 2nd dictionary for phone info
true
32094ffec3b86176f0856be0944f89350d9aad16
newphycoder/USTC_SSE_Python
/练习/练习场1/练习4.py
343
4.3125
4
from tkinter import * # Import all definitions from tkinter window = Tk() label = Label(window , text = "Welcome to Python") # Create a "label button = Button(window , text = "Click Me") # Create a button label.pack() # PI ace the "label in the window button.pack() # Place the button in the window window.mainloop() # Create an event loop
true
aac6288953cdbc80caf8134621d1309cf7a99666
Luis-Ariel-SM/Modulo-02-Bootcamp0
/P05, La recursividad en funciones.py
1,048
4.15625
4
# La recursividad es un paradigma de programacion basado en funciones solo se necesitan a asi mismas y se invocan a si mismas. Su mayor # problema es que puede ejecutar bucles infinitos ya que no para de llamarse por lo cual su punto mas importante es la condicion de # parada. Es un codigo original y elegante a nivel de sintaxis pero muy poco eficiente lastrando asi su utilidad. # 1er ejemplo: Retrocontador def retrocontador (entrada): print ("{},".format(entrada), end = "") # if entrada == 0: Esta seria otra sintaxis para ejecutar la salida del bucle. Cuando tu valor sea 0... # return ... te paras aqui if entrada > 0: # condicion de salida, si el numero es mayor que 0... retrocontador (entrada - 1) # ... vuelve a ejecutarte restandote el valor. Cuando llegue a 0 parará de ejecutarse retrocontador (10) # 2do ejemplo: Sumatorio recursivo def sumatorio (entrada): if entrada > 0: return entrada + sumatorio (entrada - 1) else: return 0 print("\n",sumatorio(4))
false
168577bc4d0ba59a9dc1e8dfc19ec2cde1c3c452
lucifer773/100DaysofPythonCode
/Day4 - Rock Paper and Scissor Game/Rock Paper Scissor/main.py
1,191
4.40625
4
"""Using ASCI art for console printing""" rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' output = [rock , paper , scissors] """Take Input from user""" print("Hello, Welcome to the game !") user_input = input("Type 0 for Rock , Type 1 for Paper and Type 2 for Scissors.") if int(user_input) >2 or int(user_input) < 0: print("Please select valid input and try again !") else: print(output[int(user_input)]) """Generate Random Output from Rock Paper and Scissors""" import random random_number = random.randint(0 , len(output)-1) print(output[random_number]) if int(user_input) >= 3 or int(user_input) < 0: print("You typed an invalid number, you lose!") elif int(user_input)==0 and random_number == 2: print("You Lost !") elif random_number > int(user_input): print("You Lost !") elif int(user_input) > random_number: print("You Win !") elif random_number == int(user_input): print("Its a Draw !")
false
5bfa5c7b40fa5469f5454f7edb00d366dc137000
KyleMcInness/CP1404_Practicals
/prac_02/ascii_table.py
579
4.4375
4
LOWER = 33 UPPER = 127 # 1 character = input("Enter a character: ") ascii_code = ord(character) print("The ASCII code for {} is {}".format(character, ascii_code)) # 2 ascii_code = int(input("Enter a number between 33 and 127: ")) while ascii_code < LOWER or ascii_code > UPPER: print("Enter a number greater than or equal to 33, or lower than or equal to 127") ascii_code = input("Enter a number between 33 and 127: ") character = chr(ascii_code) print("The character for {} is {}".format(ascii_code, character)) # 3 for i in range(LOWER, UPPER): print(i, chr(i))
true
0865ce79212062970ef2647f3fa6243b55ce8fde
KyleMcInness/CP1404_Practicals
/prac_04/list_exercises.py
450
4.28125
4
numbers = [] for i in range(5): number = int(input("Number: ")) numbers.append(number) print("The first number is {}".format(numbers[0])) print("The last number is {}".format(numbers[-1])) numbers.sort() print("The smallest numbers is {}".format(numbers[0])) print("The largest number is {}".format(numbers[-1])) average = 0 for i in numbers: average += i average = average / 5 print("The average of the numbers is {}".format(average))
true
fe1ae86c4f9fb4ba800a0c7d478f617a13df498d
A01029961/TC1001-S
/Python/01_turtle.py
663
4.5625
5
#!/usr/bin/python3 """ First example of using the turtle graphics library in Python Drawing the shape of a square of side length 400 Gilberto Echeverria 26/03/2019 """ # Declare the module to use import turtle #Draw a square, around the center side = 400 # Move right turtle.forward(side/2) # Turn to the left turtle.left(90) # Move up turtle.forward(side/2) # Turn to the left turtle.left(90) # Move left turtle.forward(side) # Turn to the left turtle.left(90) # Move down turtle.forward(side) # Turn to the left turtle.left(90) # Move right turtle.forward(side) # Turn to the left turtle.left(90) # Move up turtle.forward(side/2) # Start the drawing loop turtle.done()
true
145b7416b4f46ff8fa1b60cf57ac425cfc911fae
mohsinkazmi/Capture-Internet-Dynamics-using-Prediction
/Code/kNN/kNN.py
1,328
4.1875
4
from numpy import * from euclideanDistance import euclideanDistance def kNN(k, X, labels, y): # Assigns to the test instance the label of the majority of the labels of the k closest # training examples using the kNN with euclidean distance. # # Input: k: number of nearest neighbors # X: training data # labels: class labels of training data # y: test data # Instructions: Run the kNN algorithm to predict the class of # y. Rows of X correspond to observations, columns # to features. The 'labels' vector contains the # class to which each observation of the training # data X belongs. Calculate the distance betweet y and each # row of X, find the k closest observations and give y # the class of the majority of them. # # Note: To compute the distance betweet two vectors A and B use # use the euclideanDistance(A,B) function. # row = X.shape[0] col = X.shape[1] dis = zeros(row) for i in range(row): dis[i] = euclideanDistance(X[i,:],y) index = dis.argsort() labels = labels[index] count = zeros(max(labels)+1) for j in range(k): count[labels[j]] += 1 label = argmax(count) argmax(dis) return label
true
6122e404e29b3c97b7fe2bdd8705bfc7f7bb202f
Vinay795-rgb/code
/Calendar.py
496
4.3125
4
# Write a program to print the calendar of any given year import calendar y = int(input("Enter the year : ")) m = 1 print("\n***********CALENDAR*******") cal = calendar.TextCalendar(calendar.SUNDAY) # An instance of TextCalendar class is created and calendar. SUNDAY means that you want to start dis[playing the calendar from SUNDAY i=1 while i<=12: cal.prmonth(y,i) i+=1 # Prmonth() is a function of the class that print the calendar for given month and year
true
0fa5f57b1351604b6f1c7d8858d26909637ca57b
dakshitgm/Specialization-Data-structure-and-Algorithm-Coursera
/algorithm on string/week4/kmp.py
827
4.125
4
# python3 import sys def find_pattern(pattern, text): """ Find all the occurrences of the pattern in the text and return a list of all positions in the text where the pattern starts in the text. """ result = [] # Implement this function yourself conc=pattern+'$'+text values=[0]*len(conc) last=0 for i in range(1, len(conc)): while last>=0: if conc[i]==conc[last]: last+=1 values[i]=last break else: if last!=0: last=values[last-1] else: break pl=len(pattern) for i in range(pl, len(conc)): if values[i]==pl: result.append(i-pl-pl) return result if __name__ == '__main__': pattern = sys.stdin.readline().strip() text = sys.stdin.readline().strip() result = find_pattern(pattern, text) print(" ".join(map(str, result)))
true
a44fb9384ca70cfc7ea65c57a825efae379e1fc1
wickyou23/python_learning
/python3_learning/class_inheritance.py
1,429
4.34375
4
#####Python inheritance and polymorphism # class Vehicle: # def __init__(self, name, color): # self.__name = name # self.__color = color # def getColor(self): # return self.__color # def setColor(self, color): # self.__color = color # def getName(self): # return self.__name # class Car(Vehicle): # def __init__(self, name, color, model): # super().__init__(name, color) # self.__model = model # def __str__(self): # return self.getName() + self.__model + " in " + self.getColor() + " color" # c = Car("Ford Mustang", "Red", "GT350") # print(c.__str__()) # print(c.getName()) #####Multiple inheritance class SuperClass1: def method_super1(self): print("This is a SuperClass1") class SuperClass2: def method_super2(self): print("This is a SuperClass2") class SubClass(SuperClass1, SuperClass2): def child_method(self): print("This is a SubClass") s = SubClass() s.method_super1() s.method_super2() s.child_method() #####Overriding methods class A: def __init__(self): self.__x = 1 def m1(self): print("m1 from A") class B(A): def __init__(self): self.__y = 2 def m1(self): print("m1 from B") c = B() c.m1() #####isinstance() function print(isinstance(c, B)) print(isinstance(1.2, int)) print(isinstance([1, 2, 3, 4], list))
false