blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
fd6f4950b4fdd76631619868f22938333061c7e3
kheraankit/coursera
/interactive_python_rice/rock_paper_scissors_lizard_spock.py
2,975
4.28125
4
# The key idea of this program is to equate the strings # "rock", "paper", "scissors", "lizard", "Spock" to numbers # as follows: # # 0 - rock # 1 - Spock # 2 - paper # 3 - lizard # 4 - scissors import random # helper functions def number_to_name(number): """ This function accepts a 'number' as a key and return the corresponding value 'name' """ if number == 0: return "rock" elif number == 1: return "Spock" elif number == 2: return "paper" elif number == 3: return "lizard" elif number == 4: return "scissors" else: print "Unrecognized number:" + str(number) def name_to_number(name): """ This function accepts 'name' as a key and return the corresponding value 'number' """ if name == "rock": return 0 elif name == "Spock": return 1 elif name == "paper": return 2 elif name == "lizard": return 3 elif name == "scissors": return 4 else: print "Unrecognized name:" + name def print_results(winning_number,computer_name,player_name): """ This function pretty prints the results """ print "Player chooses " + player_name print "Computer chooses " + computer_name # 0-player_wins 1-computer_wins 2-tie if(winning_number == 0): print "Player wins!" elif(winning_number == 1): print "Computer wins!" else: print "Player and computer tie!" print "" def rpsls(name): """ This function accepts the player's choice as a function argument and generates a random choice for computer, plays the Rock-paper-scissors-lizard-Spock game [Player vs Comptuer] and prints the results """ # holds the results. 0-player_wins 1-computer_wins 2-tie winning_number = 0 # convert name to player_number using name_to_number player_number = name_to_number(name) # compute random guess for comp_number using random.randrange() comp_number = random.randrange(0, 5) # compute difference of player_number and comp_number modulo five if(comp_number != None and player_number != None): diff_number = (comp_number - player_number) % 5 if diff_number > 0 and diff_number <=2: winning_number = 1 elif diff_number > 2: winning_number = 0 else: # difference is zero, tie between computer and player winning_number = 2 # convert comp_number to name using number_to_name computer_name = number_to_name(comp_number) # print results print_results(winning_number,computer_name,name) else: print comp_number,player_number # test your code rpsls("rock") rpsls("Spock") rpsls("paper") rpsls("lizard") rpsls("scissors") # always remember to check your completed program against the grading rubric
true
2b6117afba9745fddf4f5622132b528848badc9a
bellajcord/Python-practice
/controlflow.py
2,822
4.4375
4
# Logical operators # and (1 > 2) and (2 < 3) # multiple (1 == 2) or (2 == 3) or (4 == 4) ################################## ### if,elif, else Statements ##### ################################## # Indentation is extremely important in Python and is basically Python's way of # getting rid of enclosing brackets like {} we've seen in the past and are common # with other languages. This adds to Python's readability and is huge part of the # "Zen of Python". It is also a big reason why its so popular for beginners. Any # text editor or IDE should be able to auto-indent for you, but always double check # this if you ever get errors in your code! Code blocks are then noted by a colon (:). if 1 < 2: print('yep') if 1 < 2: print('first') else: print('last') # To add more conditions (like else if) you just use a single phrase "elif" if 1 == 2: print('first') elif 3 == 3: print('middle') else: print('last') #loops # Time to review loops with Python, such as For Loops and While loops # Python is unique in that is discards parenthesis and brackets in favor of a # whitespace system that defines blocks of code through indentation, this forces # the user to write readable code, which is great for future you looking back at # your older code later on! # loop with list seq = [1,2,3,4,5] for item in seq: print(item) # Perform an action for every element but doesn't actually involve the elements for item in seq: print('yep') # You can call the loop variable whatever you want: for jelly in seq: print(jelly+jelly) ## For Loop with a Dictionary ages = {"sam":3, "Frank":2, "Dan":4} for key in ages: print("This is the key") print(key) print("this is the value") print(ages[key]) # A list of tuple pairs is a very common format for functions to return data in # Because it is so common we can use tuple un-packing to deal with this, example: mypairs = [(1,10),(3,30),(5,50)] #normal for tup in mypairs: print(tup) #unpacking for item1, item2 in mypairs: print(item1) print(item2) ####################### ### WHILE LOOPS ####### ####################### # While loops allow us to continually perform and action until a condition # becomes true. For example: i = 1 while i < 5: print('i is: {}'.format(i)) i = i+1 # RANGE FUNCTION # range() can quickly generate integers for you, based on a starting and ending point # Note that its a generator: range(5) list(range(5)) for i in range(5): print(i) # List Comprehension # This technique allows you to quickly create lists with a single line of code. # You can think of this as deconstructing a for loop with an append(). For Example: x = [1,2,3,4] out = [] for item in x: out.append(item**2) print(out) #writen in list comp form [item**2 for item in x]
true
0352bb392701674291b3c5d2ce0af52a5834e9d4
NathanontGamer/Multiplication-Table
/multiplication table.py
894
4.46875
4
#define function called multiplication table def muliplication_table (): #input number and number of row number = int(input("Enter column / main number: ")) number_row = int(input("Enter row / number that (has / have) to times: ")) #for loop with range number_row for i in range (1, number_row + 1): print (number, "*", i, "=", number * i) #input continue or not continue_choice = input("Do you want to coninue? (y/n)\n") #if statement decide that want to continue or not if continue_choice == "y": muliplication_table() elif continue_choice == "n": print ("Good Bye!") else: print ("Error!") #print This program can display multiplication table / Describe program plan print ("This program can display multiplication table") #called multiplication_table funcion muliplication_table()
true
5fb8a8668dbc03e0c18b3e98ec85662217cdb38b
suraj13mj/Python-Practice-Programs
/13. Python 05-06-20 --- Dictionary/Program3.py
405
4.125
4
#Program to read Student details into Dictionary and append it a List college=[] N=int(input("Enter No of Students:")) for i in range(0,N): stud={} stud["roll"]=int(input("\nEnter Roll No:")) stud["name"]=input("Enter Name:") stud["per"]=float(input("Enter Percentage:")) college.append(stud) for stud in college: print("\nRoll No:",stud["roll"],"\nName:",stud["name"],"\nPercentage:",stud["per"])
false
01d46d24b6c692f85aec4efcba110013b0b0a579
suraj13mj/Python-Practice-Programs
/10. Python 31-01-20 --- Lists/Program5.py
218
4.21875
4
#Program to sort a 2D List lst=[[25,13],[18,2],[19,36],[17,3]] def sortby(element): #sorts based on column 2 return(element[1]) print("Before Sorting:",lst) lst.sort(key=sortby) print("After Sorting:",lst)
true
706558592b4863c72ef112dfc3ab98588d5f796b
suraj13mj/Python-Practice-Programs
/32. Python 06-03-20 --- File Handling/Program1.py
1,247
4.34375
4
#Program to demonstrate basic file operations in Python def createFile(filename): fh=open(filename,"w") print("Enter File contents:") print("Enter '#' to exit") while True: line=input() if line=="#": break fh.write(line+"\n") fh.close() def appendData(filename): fh=open(filename,"a") print("Enter the data to append:") print("Enter # to exit") while True: line=input() if line=='#': break fh.write(line+"\n") fh.close() def displayFile_1(filename): try: fh=open(filename,"r") print("\nFile contents are:\n") data=fh.read() print(data) fh.close() except Exception: print("File does not exist") #OR def displayFile_2(filename): try: fh=open(filename,"r") print("\nFile contents are:\n") for line in fh: print(line,end="") fh.close() except Exception as e: print(e) if __name__=="__main__": while True: ch=int(input("\n1.Create New File 2.Display File contents 3.Append Data to the File 4.Exit\n")) if ch==1: fnm=input("Enter the Filename to Create:") createFile(fnm) elif ch==2: fnm=input("Enter the Filename to Open:") displayFile_2(fnm) elif ch==3: fnm=input("Enter the Filename to append Data:") appendData(fnm) else: break
true
30342271877f7edcf5c7b66362c5955599dee4f7
suraj13mj/Python-Practice-Programs
/38. Python 15-04-20 --- NumPy/Program2.py
498
4.125
4
# Program to read a m x n matrix and find the sum of each row and each column import numpy as np print("Enter the order of the Matrix:") r = int(input()) c = int(input()) arr = np.zeros((r,c),dtype=np.int8) print("Enter matrix of order "+str(r)+"x"+str(c)) for i in range(r): for j in range(c): arr[i,j] = int(input()) for i in range(r): row = arr[i,...] print("Sum of Row "+str(i)+"="+str(sum(row))) for i in range(c): col = arr[...,i] print("Sum of Column "+str(i)+"="+str(sum(col)))
true
cc88f1c06b6491398275065144285e7ab8e033ca
Mhtag/python
/oops/10public_protected_pprivate.py
862
4.125
4
class Employee: holidays = 10 # Creating a class variables. var = 10 _protec = 9 # Protected variables can be used by classes and sub classes. __private = 7 # Private Variables can be used by only this class. def __init__(self, name, salary, role): self.name = name self.salary = salary self.role = role # Self is the object where this function will run def printdetails(self): return f'Name is {self.name}, salary is {self.salary}, role is {self.role}.' @classmethod def change_holidays(cls, newholidays): cls.holidays = newholidays # Class method as an alternative constructor. @classmethod def from_str(cls, string): return cls(*string.split('-')) emp = Employee('Mohit', 222, 'programmer') print(emp._protec) print(emp.__private)
true
1236969d33c8c56768f35f63367e8fd54db295ab
BALAVIGNESHDOSTRIX/py-coding-legendary
/Advanced/combin.py
473
4.1875
4
''' Create a function that takes a variable number of arguments, each argument representing the number of items in a group, and returns the number of permutations (combinations) of items that you could get by taking one item from each group. Examples: combinations(2, 3) ➞ 6 combinations(3, 7, 4) ➞ 84 combinations(2, 3, 4, 5) ➞ 120 ''' def combinations(*items): num = 1 for x in items: if x != 0: num = num * x return num
true
7c2acffba62cb6408f085fb2bf233c1ac2714c64
jotawarsd/Shaun_PPS-2
/assignments_sem1/assign6.py
375
4.3125
4
''' Assignment No: 6 To accept a number from user and print digits of number in a reverse order using function. ''' num1 = input("number : ") #get input from user def reverse(s1): n = len(s1) - 1 #establish index of last digit for i in range(n,-1,-1): #printing the number in reverse print(s1[i], end='') print("reverse = ", end = '') reverse(num1)
true
6a32a530aa936c83f2f7853c530948a0a2fded0b
MaximSidorkin/test
/task_2.py
448
4.375
4
''' 2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк. ''' seconds = int(input('введите секунду - ')) hours = seconds // 3600 minutes = (seconds // 60) % 60 seconds = seconds % 60 print(f"{hours}:{minutes}:{seconds}")
false
b97639963d80069a0c86b5eac5b58cae944877fd
guohuacao/Introduction-Interactive-Programming-Python
/week2-Guess-The-Number.py
2,559
4.21875
4
# "Guess the number" mini-project # This code runs under http://www.codeskulptor.org/ with python 2.7 #mini-project description: #Two player game, one person thinks of a secret number, the other peson trys to guess #In this program, it will be user try to guess at input field, program try to decide #"higher", "lower" or "correct" # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random import math num_range = 100 remaining_guess = 7 # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global num_range global computer_guess global remaining_guess if (num_range == 100): remaining_guess = 7 else: remaining_guess = 10 print "\n" print "New game. Range is from 0 to ",num_range print "Number of remaining guess is ",remaining_guess computer_guess = random.randint(0, num_range) #print "computer gues was " ,computer_guess # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game global num_range global remaining_guess num_range = 100 remaining_guess = 7 new_game() def range1000(): # button that changes the range to [0,1000) and starts a new game global num_range global remaining_guess num_range = 1000 remaining_guess = 10 new_game() def input_guess(guess): global num_range global computer_guess global remaining_guess print "guess was ", guess guess_int = int(guess) if (guess_int > num_range or guess_int < 0): print 'number is out of range' elif guess_int > computer_guess: print 'Lower!' remaining_guess -=1 print "remaining guess is ",remaining_guess elif guess_int < computer_guess: print 'Higher!' remaining_guess -= 1 print "remaining guess is ",remaining_guess else: print 'Correct!' new_game() if (remaining_guess==0): print "Number of remaining guesses is 0" print " You ran out of guesses. The number was ", computer_guess new_game() else: print "\n" # create frame f = simplegui.create_frame("guess number", 200, 200) f.add_button("Range is [0, 100)", range100, 200) f.add_button("Range is [0, 1000)", range1000, 200) f.add_input("Enter a guess", input_guess, 200) new_game() # always remember to check your completed program against the grading rubric
true
e725ed708943e6bbfcd9edb3d44f1b685bf50d61
shishir-kr92/HackerRank
/Algorithm/problem_solving/The_Time_In_Word.py
1,632
4.21875
4
time = ["o' clock", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "quarter", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twenty one", "twenty two", "twenty three", "twenty four", "twenty five", "twenty six", "twenty seven", "twenty eight", "twenty nine", "half" ] def time_in_word(hrs, minute): time_str_format = "" hrs_part = (12 - hrs + 1) if hrs == 12 else (hrs + 1) if minute == 0: time_str_format = f"{time[hrs]} o' clock" elif minute == 1: time_str_format = f"{time[minute]} minute past {time[hrs]}" elif minute == 15 or minute == 30: time_str_format = f"{time[minute]} past {time[hrs]}" elif minute < 30: time_str_format = f"{time[minute]} minutes past {time[hrs]}" elif minute == 45: time_str_format = f"{time[60 - minute ]} to {time[hrs_part]}" elif minute < 59: time_str_format = f"{time[60 - minute ]} minutes to {time[hrs_part]}" elif minute == 59: time_str_format = f"{time[60 - minute ]} minute to {time[hrs_part]}" return time_str_format if __name__ == "__main__": """ https://www.hackerrank.com/challenges/the-time-in-words/problem """ hrs = int(input().strip()) minute = int(input().strip()) result = time_in_word(hrs, minute) print(result)
false
a98c0c257dc9f921fa02386b918b46ef8d009487
zb14755456464/pythonCookbook
/第四章:迭代器与生成器/4.12 不同集合上元素的迭代.py
864
4.21875
4
# 问题 # 你想在多个对象执行相同的操作,但是这些对象在不同的容器中,你希望代码在不失可读性的情况下避免写重复的循环 #解决方案 """ itertools.chain() 方法可以用来简化这个任务。 它接受一个可迭代对象列表作为输入, 并返回一个迭代器,有效的屏蔽掉在多个容器中迭代细节。 为了演示清楚,考虑下面这个例子 """ from itertools import chain a = [1, 2, 3, 4] b = ['x', 'y', 'z'] for x in chain(a, b): # 都是循环遍历,a,b两个列表,为了避免这样的重复操作,可以使用chain print(x) #讨论 """ itertools.chain() 接受一个或多个可迭代对象作为输入参数。 然后创建一个迭代器, 依次连续的返回每个可迭代对象中的元素。 这种方式要比先将序列合并再迭代要高效的多。 """
false
feed0a4b5bbb7163c3cd4cce74b7457d3b898a3d
zb14755456464/pythonCookbook
/第四章:迭代器与生成器/4.1 手动遍历迭代器.py
1,066
4.21875
4
# 问题 # 你想遍历一个可迭代对象中的所有元素,但是却不想使用for循环。 # 解决方案 #为了手动的遍历可迭代对象,使用 next() 函数并在代码中捕获 StopIteration 异常。 比如,下面的例子手动读取一个文件中的所有行 items = [1, 2, 3, 4] it = iter(items) def manual_iter(): try: while True: line = next(it) print(line, end='') except StopIteration: # StopIteration 用来指示迭代的结尾 pass # 果你手动使用上面演示的 next() 函数的话,你还可以通过返回一个指定值来标记结尾,比如 None 。 下面是示例: def manual_iter(): try: while True: line = next(it,None) # 如果到达结尾的话,可以返回一个指定值来标记结尾 if line is None: break print(line, end='') except StopIteration: # StopIteration 用来指示迭代的结尾 pass if __name__ == '__main__': manual_iter()
false
e33f71ec867753fa1a5029f0891fad03c9fce52b
sachinsaxena021988/Assignment7
/MovingAvarage.py
599
4.15625
4
#import numpy module import numpy as np #define array to for input value x=np.array([3, 5, 7, 2, 8, 10, 11, 65, 72, 81, 99, 100, 150]) #define k as number of column k=3 #define mean array to add the mean meanarray =[] #define range to loop through numpy array for i in range(len(x)-k+1): #internal sum of all kth value internalSum =0.0 for j in range(i,i+k): internalSum =internalSum+x[j] meanarray.append(internalSum/k) #print mean array print(meanarray)
true
19801fea421a78906fc5cd0de64b9ff864d85983
polora/polora.github.io
/scripts_exercices_1/C6Ex3_moyenne_amélioré.py
1,152
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @author : YF # @date : octobre 2022 ### Correction de l'exercice - Calcul d'une moyenne de 3 notes - version améliorée # déclaration des variables et initiation nb_notes=0 somme=0 moyenne=0 i=1 # demande du nombre de notes while True: try: nb_notes=float(input("Nombre de notes ? : ")) break except ValueError: print("La saisie n'est pas un nombre... Essayez à nouveau") # saisie des notes if nb_notes>0: # verifie que le nombre de notes saisi est supérieur à 0 while i<=nb_notes: note=input("Saisir la note : ") note=float(note) # convertit la note en nombre décimal if (note>=0) and (note<=20): # vérifie que la note est comprise entre 0 et 20 somme=somme+note i+=1 else: print("La note doit etre comprise entre 0 et 20") else: print("Le nombre de notes doit etre supérieur ou égal à 0") # calcul de la moyenne et affichage moyenne=somme/nb_notes print("La moyenne de ces notes est : ", moyenne)
false
4fa2954258c033bc635614a03bde2f888e9e360f
Veraxvis/PRG105
/5.2/derp.py
726
4.1875
4
def main(): costs = monthly() print("You spend", '$' + "{:,.2f}".format(costs) + " on your car per month.") per_year = yearly(costs) print("In total you spend", '$' + "{:,.2f}".format(per_year) + " on your car per year.") def monthly(): car_payment = float(input("Please enter your monthly car payment: ")) insurance = float(input("Please enter your monthly insurance bill: ")) gas = float(input("Please enter how much you spend on gas each month: ")) repairs = float(input("Please enter how much you spend on repairs: ")) monthly_total = car_payment + insurance + gas + repairs return monthly_total def yearly(monthly_total): year = monthly_total * 12 return year main()
true
7a23e70d9095909a575ebcad73b29b016b8f4da0
miklo88/cs-algorithms
/single_number/single_number.py
1,612
4.125
4
''' Input: a List of integers where every int except one shows up twice Returns: an integer ''' ''' UPER UPER TIME so this function takes in a list of ints. aka a list[1,2,3,4,5,6] of nums where every int shows up twice except one so like list[1,1,2,2,3,4,4,5,5,6,6] so i need to return the int that is only listed once in a list. "so what needs to be done" as an arr list being passed into single_number(arr): fn i need to look over each value in that list. while doing so i need to be able to check each value and see if there are more than one of the same value. if there is only one of a certain value. then return it. "how am i going to do it?" i'm thinking that i need to loop over the data, so either a for or while loop - then check each value if it meets certain conditions. if elif else. most likely if and else will be needed. ''' ''' solution, returning the sum of the set of the arr. so grabbing each individual unique element and adding them all up.then mult that sum by 2. then you add up the entire array. you take the sum of the set *2 - this second sum of all ele in arr and you get the difference which equals the one element that doesnt have a double. DOES NOT WORK FOR MULTIPLE ELEMENTS WITH ONLY ONE INT. it returns the sum of both nums of the single ints. ''' def single_number(arr): # Your code here return 2 * sum(set(arr)) - sum(arr) if __name__ == '__main__': # Use the main function to test your implementation arr = [1, 1, 4, 4, 5, 5, 3, 3, 9, 0, 0] print(set(arr)) print(f"The odd-number-out is {single_number(arr)}") # print(arr)
true
235df1baba7c9ffe9222dfee29da356e2a1762fa
timlax/PythonSnippets
/Create Class v2.py
1,369
4.21875
4
class Animal(object): """All animals""" alive = "" # Define the initialisation function to define the self attributes (mandatory in a class creation) def __init__(self, name, age): # Each animal will have a name and an age self.name = name self.age = age # The description function will print the animals name & age attributes def description(self): print(self.name) print(self.age) # The SetAlive function will define the attribute "alive" for an animal as alive def setAlive(self, alive): self.alive = alive # The getAlive function will show the value of the attribute "alive" for an animal def getAlive(self): return self.alive # Define your first animal with its values for the "self attributes" horse = Animal("Hilda", 22) # Call the description function to print name & age horse.description() # Call the setAlive function to define that your animal is alive horse.setAlive(True) # Call the getAlive function to know if your animal is alive print(horse.getAlive()) # Call the setAlive function to define that your animal is NOT alive horse.alive=False # Call the getAlive function to know if your animal is alive print(horse.getAlive()) # Change the value of the age attribute for your selected animal & print the new age horse.age += 1 print(horse.age)
true
07f57f122c2f0f6f3f558d78a27ff656bab8ac24
Pratyush-PS/tathastu_week_of_code
/day6/program11.py
275
4.28125
4
size= int(input("\nEnter your list size:")) li=[] for i in range(size): li.append(int(input("Enter element {}:".format(i+1)))) print("\nGiven list is:",li) max_product=1 for i in sorted(li)[-3:]: max_product *=i print("\nMaximum possible product is:",max_product)
false
06b37c4c13983bbe4f9446dc6736755b834f35c9
LKlemens/university
/python/7zestaw/circle.py
1,496
4.125
4
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- from math import pi, sqrt from point import Point class Circle(object): """Klasa reprezentująca okręgi na płaszczyźnie.""" def __init__(self, x=0, y=0, radius=1): if radius < 0: raise ValueError('negative radius') self.center = Point(x, y) self.radius = radius def __repr__(self): return 'Circle(%s, %s, %s)' % (self.center.x, self.center.y, self.radius) def __str__(self): return '(%s, %s, %s)' % (self.center.x, self.center.y, self.radius) def __eq__(self, other): return self.center == other.center and self.radius == other.radius def __ne__(self, other): return not self == other def area(self): return pi * self.radius * self.radius def move(self, x, y): self.center.x += x self.center.y += y def cover(self, other): # radius x_length = max(self.center.x, other.center.x) - \ min(self.center.x, other.center.x) y_length = max(self.center.y, other.center.y) - \ min(self.center.y, other.center.y) radius = sqrt(x_length * x_length + y_length * y_length) + max( self.radius, other.radius) x_coordinate = max(self.center.x, other.center.x) - x_length / 2 y_coordinate = max(self.center.y, other.center.y) - y_length / 2 return Circle(x_coordinate, y_coordinate, radius)
false
c9894657052e2db7a9bafdf51ae0f63fe25258bb
mikkope123/ot-harjoitustyo
/src/city/city.py
1,752
4.5
4
import math class City: """A class representing a city on the salesman's route.': Attributes: x1, x2: cartesian coordinates representing the location of the city on the map """ def __init__(self, x1: float, x2: float): """Class constructor that creates a new city Args: self.__x1, self.__x2: cartesian coordinates representing the location of the city on the map""" self.__x1 = x1 self.__x2 = x2 def __str__(self): """Returns the string attribute of the class. Returns: A string consisting of a tuple of city coordinates.""" city_tuple = (self.__x1, self.__x2) return str(city_tuple) def distance(self, other): """Calculates the distance from the city to another Args: City class object Returns: euclidian distance between the cities""" return math.sqrt((self.__x1-other.__x1)**2 + (self.__x2-other.__x2)**2) def find_nearest(self, other_cities): """Finds the city nearest to this one. Args: A list of cities. Returns: A tuple consisting of the nearest city and the distance from self to there.""" nearest_city = None shortest_distance = math.inf for city in other_cities: r = self.distance(city) if r < shortest_distance: shortest_distance = r nearest_city = city return (nearest_city, shortest_distance) def get_coordinates(self): """A method to get the cartesian coordinates of the city. Returns: Cartesian coordinates of the city.""" return self.__x1, self.__x2
true
b2035acc0a2b2d9a4e764809f20d64fee47e6aa0
Filipe-Amorim1/Scripts-Python
/Aula16/Aula16_exemplos_TUPLAS.py
1,335
4.25
4
# Tupla é entre parenteses () # Lista é entre [] colchetes # Dicionário é entre {} chaves ########### TUPLAS ########## # tuplas são imutavéis lanche = ('hamburguer','suco','pizza','pudim','alface') print(lanche) print(lanche[1]) print(lanche[3]) print(lanche[-2]) print(lanche[1:3]) # nesse caso como vimos , ele vai do 1 até o 2 desconsiderando o final print(lanche[0:4])# printar elementos 0,1,2,3 print(lanche[:2]) # mostrar do ínicio até o elemento 2 print(lanche[-2:]) for c in lanche: # Aqui o laço vai passar uma a uma das palavrar na tuple print(f'Estou com fome eu vou comer {c}') # e colocar no lugar do c aqui printando cada vez que passar ( print dentro da indentação for cont in range (0, len(lanche)): print(f'Estou com fome eu vou comer {cont}') for c in enumerate (lanche): print(f'Estou com fome eu vou comer {c}') print('Comi muito to cheio!!') # este printa só depois que sair do laço devido a indentação print( sorted(lanche)) # sorted coloca em ordem A-Z #Juntando Tuplas a = (1,2,3,4,5) b = (5,6,6,7,8) c = a+b print(a) print(b) print(c) print(b+a) print(c.count(5)) # var.count aqui mostra qunatas vezes temos o número 5 na var c ( quie é a junção das var a e b) print(c.index(4)) # var.index mostra a primeira ocorrência do número na tupla print(c.index(5,))
false
00fefe5e093ea3f4cc2561a0d1ff54c2509a9586
Filipe-Amorim1/Scripts-Python
/Aula 19 Dicionários/Exemplos_aula19.py
1,557
4.1875
4
filme = {'Titulo':'star wars','Ano':1977,'Diretor':'George Lucas' } print(filme.values()) print(filme.keys()) print(filme.items()) print() # usando o for para interagir com a var filme # esse comando é igual o enumerate para listas e tuplas for k,v in filme.items(): print(f'O {k} é {v}') del filme ['Diretor'] # apaga a chave Diretor print(filme) filme['Diretor'] = 'FiLipe' # trocando os valores dentro das chaves no dicionário filme['Ano'] = '1984' filme['lançamento'] = 1986 # adicionando uma chave e valor ao item for k,v in filme.items(): print(f'O {k} é {v}') print() # LISTAS com Dicionários brasil = [] estado1 = {'uf': 'Rio de janeiro','sigla':' RJ'} estado2= {'uf':'São paulo','sigla':'SP'} brasil.append(estado1) brasil.append(estado2) print(brasil) print(brasil[1]) print(brasil[0]) print(brasil[0]['uf']) print(brasil[1]['sigla']) # Usando o for e input para adicionar dados ao dicionãrios estado = {} brasil1 = [] for c in range (0,3): estado['uf'] = str(input('Unidade Federativa: ')) estado[' sigla'] = str(input('Sigla do estado:')) brasil1.append(estado.copy()) # .copy para copiar os dados para o dicio cada vez que passar no laço é semelahnte ao colocar na lista[:] , se não fizer este comando no caso o print sairia 3 vezes com o mesmo estado e sigla print(brasil1) # no for abaixo o 1º for é para percorrer os itens na lista brasil # O 2º for passara pelas chaves e valores nos itens dos dicionário estado for e in brasil1: for k,v in e.items(): print(f'O campo {k} tem valor {v}')
false
744e938d38501aea487ccc54554851dec46f3bd3
Filipe-Amorim1/Scripts-Python
/Aula09/Desafio22aula09manistring.py
1,477
4.3125
4
# Ler o nome de uma pessoa e mostrar # nome com todas letras maiúsculas # todas minúsculas # letras ao todo sem considerar espaços # letras tem o primeiro nome nome = str(input('Digite seu nome completo:')).strip() # o .strip no final é para eliminar os espaços no ínicio e no fim para não conta-los print('Analisando seu nome...') print('Seu nome tem letras maiúsculas é {}'.format(nome.upper())) # upper todas maiúsculas print('Seu nome tem letras minúsculas é {}'.format(nome.lower())) #lower todas minúsculas print('Seu nome tem {} letra'.format(len(nome)- nome.count(' '))) # len para analisar todo nome , -nome.count(' ') para contar os espaços e subtrailos ] print('Seu primeiro nome tem {} letras'.format(nome.find(' '))) #EM python podemos ter outras formas de resolver os problemas # Para contar as letras do primeiro nome usamos a função find para retornar o primeiro espaço que encontrar # Como o python começa a contar do zero ele vai contar até o espaço e nos dará quantas letras tem no primeiro nome separa = nome.split() print('Seu primeiro nome é {} e ele tem {} letras '.format(separa[0], len(separa[0]))) # Criamos a var separa recebendo a var nome e separando cada pedaço com o comando split # Depois mandamos printar a var separa com o primeiro pedaço que é zero ( o comando split corta em pedaços e esses pedaços recebem a numeração começando em zero # o comando len analisou a parte zero e nos deu o número de letras
false
7a93885bf363e77b5a2faa17f55e2c83e0006603
Filipe-Amorim1/Scripts-Python
/Aula16/Desafio75_Aula16_analise_de_dados.py
749
4.125
4
# Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: # A) Quantas vezes apareceu o valor 9. # B) Em que posição foi digitado o primeiro valor 3. # C) Quais foram os números pares. digite = (int(input('Digite um valor: ')), int(input('Digite um valor: ')), int(input('Digite um valor: ')), int(input('Digite um valor: ')), int(input('Digite um valor: '))) print(digite) print(f'O número 9 apareceu {digite.count(9)} vezes') if 3 in digite: print(f'O número 3 está na posição:{(digite.index(3)+1)}') else: print('Não tem número 3') print('Os valores pares digitados foram:') for c in digite: if c%2==0: print(c,' ',end='')
false
0cbcf5fc45f1ff8287a3bc01e3b61e78f32db9d1
Filipe-Amorim1/Scripts-Python
/Aula14/Desafio63_Fibonacci1.0.py
840
4.15625
4
#Escreva um programa que leia um número N inteiro qualquer # e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci. Exemplo: # 0 – 1 – 1 – 2 – 3 – 5 – 8 # É uma sucessão de números que, misteriosamente, aparece em muitos fenômenos da natureza. # Descrita no final do século 12 pelo italiano Leonardo Fibonacci, ela é infinita e começa com 0 e 1. # Os números seguintes são sempre a soma dos dois números anteriores. # Portanto, depois de 0 e 1, vêm 1, 2, 3, 5, 8, 13, 21, 34… print('\033[1;33m ------- Sequência de Fibonacci 1.0 -------') n = int(input('Digite um número: ')) inicial1 = 0 inicial2 = 1 fibo = 0 num =0 cont = 0 print(inicial1,'->',inicial2,end='') while cont <= n: fibo = inicial1 + inicial2 inicial1 = inicial2 inicial2 = fibo cont = cont + 1 print('->',fibo,end='')
false
eac6933afc3d425a8e812527802619da6548b228
Filipe-Amorim1/Scripts-Python
/Aula09/Desafio28_Aula10_.py
876
4.1875
4
# Fazer o PC pensar em um numero inteiro entre 0 e 5 # Usuario vai tentar descobrir qual foi o número esolhido pelo PC # O programa deverá ecrever na tela se o usuário venceu ou perdeu import random import emoji ale = int(random.randint(0,5)) num = int(input('Tente adivinhar o número que estou pensando de 1 até 5:').strip()) # strip para não ter problems com o usuário dar espaços no começo print(('-'*25))# Esses comandos são para colorir a tela , vai printar 25 vezes o traço - if num == ale: print("Parabéns você acertou!!!",ale,'\nfoi exatamente o número que pensei ') else: print(emoji.emojize("Você errou:punch:!!! o número que pensei foi {}".format(ale),use_aliases=True)) # coloquei algo mais para ter um emoji ( ver exercicio aula 08) #print(emoji.EMOJI_ALIAS_UNICODE_ENGLISH) # esse coando printa todos os códigos para botar os emojis
false
395d1fab2a05c1ffb4ed95a51d41e55e3706685c
Filipe-Amorim1/Scripts-Python
/Aula 13/Aula13exemplos1.py
1,192
4.125
4
for c in range (0,6): # para c (c é o nome do laço pode ser qquer nome ) in (no) range (intervalo) 0 até 6 , print('oi') # sempre no útimo número o python vai parar ou sair do laço para o px comando. vai contar de 0 a 5 ou seja 6x saira ou parara no 7 print('Fim') # O print com a indentação mais recuada indicando a saida do laço , se tivesse alinhado abaixo do print acima entraria no laço e repetiria Oi e Fim 6x for c in range (0,6): print(c) # nesse caso ele vai printar o laço que nomeamos como c . 0,1,2,3,4,5 , o último o python ignora , se quizer até seis tem que colocar (0,7) print('FIM') for c in range (6,0,-1): # para contar de trás para frente colocar o -1 para contagem regressiva de um em um , se quiser regressiva de 2 em dois coolcar - 2 e assim sucessivamente print(c) print('FIM') n = int(input('Digite um número:')) for c in range(1,n+1): # Nesse caso a contagem sera de 1 até o número digitado pelo usuário , o +1 é para contar até o número que o usuário digitou , # pois se não contaria 1 a menos pois no ultimo número o pythin não conta ele tem como a saída do laço print(c)
false
dff9d0f6b9dca11422d9d97ff54352aca8e6eacf
Faranaz08/assignment_3
/que13.py
600
4.1875
4
#write a py program accept N numbers from the user and find the sum of even numbers #product of odd numbers in enterd in a list lst=[] even=[] odd=[] sum=0 prod=1 N=int(input("enter the N number:")) for i in range(0,N): ele = int(input()) lst.append(ele) if ele%2==0: even.append(ele) sum=sum+ele else: odd.append(ele) prod=prod*ele print(lst) print("Even numbers :" +str(even)) print("odd numbers :" +str(odd)) print("the sum of even numbers in list :"+str(sum)) print("the product of odd numbers in the list :"+str(prod))
true
2b783a4762657b56447de189929a210aa8e69bac
exclusivedollar/Team_5_analyse
/Chuene_Function_3.py
724
4.28125
4
### START FUNCTION """This function takes as input a list of these datetime strings, each string formatted as 'yyyy-mm-dd hh:mm:ss' and returns only the date in 'yyyy-mm-dd' format. input: list of datetime strings as 'yyyy-mm-dd hh:mm:ss' Returns: returns a list of strings where each element in the returned list contains only the date in the 'yyyy-mm-dd' format.""" def date_parser(dates): # Creating a new date list. date_only = [] for date in dates: my_list = date[:len(date)-9] # Append values from my list to date_only list. date_only.append(my_list) date_only[:] # returned list contains only the date in the 'yyyy-mm-dd' format. return date_only ### END FUNCTION
true
987de188f535849170f5d44dafef82c543ad1bb6
sstagg/bch5884
/20nov05/exceptionexample.py
237
4.125
4
#!/usr/bin/env python3 numbers=0 avg=0 while True: inp=input("Please give me a number or the word 'Done': ") if inp=="Done": break else: x=float(inp) avg+=x numbers+=1 avg=avg/numbers print ("The average is %.2f" % (avg))
true
cee079505a684ef5a58041492ed437eba43572b5
JayAgrawalgit/LearnPython
/1. Learn the Basics/1.9 Functions/1. What are Functions.py
1,282
4.5625
5
# Functions are a convenient way to divide your code into useful blocks, # allowing us to order our code, make it more readable, reuse it and save some time. # Also functions are a key way to define interfaces so programmers can share their code. # How do you write functions in Python? # As we have seen on previous tutorials, Python makes use of blocks. # A block is a area of code of written in the format of: # block_head: # 1st block line # 2nd block line # ... # Where a block line is more Python code (even another block), and the block head is of the following format: # block_keyword block_name(argument1,argument2, ...) Block keywords you already know are "if", "for", and "while". # Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. # For example: def my_function(): print("Hello From My Function!") # declaration # Functions may also receive arguments (variables passed from the caller to the function). For example: def my_function_with_args(username, greeting): print("Hello, %s , From My Function!, I wish you %s"%(username, greeting)) # Functions may return a value to the caller, using the keyword- 'return' . For example: def sum_two_numbers(a, b): return a + b
true
a10abea0005837374d7908ed655aa4fddfe87e61
JayAgrawalgit/LearnPython
/1. Learn the Basics/1.2 Variables and Types/1. Numbers.py
628
4.4375
4
# Python supports two types of numbers - integers and floating point numbers. (It also supports complex numbers, which # will not be explained in this tutorial). # To define an integer, use the following syntax: myint = 7 print("Integer Value printed:",myint) # To define a floating point number, you may use one of the following notations: myfloat = 7.0 print("Float Value printed:",myfloat) myfloat = float(7) print("Float Value printed:",myfloat) # Assignments can be done on more than one variable "simultaneously" on the same line like this a , b = 3 , 4 print("print a:",a) print("print b:",b) print("print a,b:", a,b)
true
55d49ce7240c7af9c27430d134507103cc6739c7
JayAgrawalgit/LearnPython
/1. Learn the Basics/1.11 Dictionaries/1. Basics.py
688
4.15625
4
# A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. # Each value stored in a dictionary can be accessed using a key, # which is any type of object (a string, a number, a list, etc.) instead of using its index to address it. # For example, a database of phone numbers could be stored using a dictionary like this: phonebook = {} phonebook["John"] = 938477561 phonebook["Jack"] = 938377262 phonebook["Jill"] = 947662783 print(phonebook) # Alternatively, a dictionary can be initialized with the same values in the following notation: phonebook2 = { "Jony" : 938477564, "Jay" : 938377265, "Jeny" : 947662786 } print(phonebook2)
true
a9ad5d63cd98a178b4efdf2343c9e4f083d42a24
uc-woldyemm/it3038c-scripts
/Labs/Lab5.PY
486
4.15625
4
print("Hello Nani keep doing your great work") print("I know you're busy but is it okay if i can get some information about you") print("How many years old are you?") birthyear = int(input("year: ")) print("What day you born") birthdate = int(input("date: ")) print("Can you also tell me what month you were born") birthmonth = int(input("month: ")) seconds = birthyear * 24 * 60 * 60 * 365 + birthmonth * 30 * 60 + birthdate * 60 print ("you are about" , seconds , "seconds old")
true
235bd7c02a7555c8d059e401b18bf9bb4c6ee2dc
PranilDahal/SortingAlgorithmFrenzy
/BubbleSort.py
854
4.375
4
# Python code for Bubble Sort def BubbleSort(array): # Highest we can go in the array maxPosition = len(array) - 1 # Iterate through the array for x in range(maxPosition): # For every iteration, we get ONE sorted element. # After x iterations, we have x sorted elements # We don't swap on the sorted side - only go up to (maxPosition-x) for y in range(0,maxPosition - x): # If an element is greater than the element after it, swap places if array[y] > array[y+1]: array[y], array[y+1] = array[y+1], array[y] #Done! def main(): TestArray = [3,11,98,56,20,19,4,45,88,30,7,7,7,8,8] BubbleSort(TestArray) print ("#LetsCodeNepal: The bubble sorted result is-") for i in range(len(TestArray)): print ("%d" %TestArray[i]) if __name__ == '__main__': main()
true
7a5ecb354bfdd283896bcbfdb5b177bd53b90b15
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Strings/WildCardMatching.py
1,442
4.40625
4
""" String matching where one string contains wildcard characters Given two strings where first string may contain wild card characters and second string is a normal string. Write a function that returns true if the two strings match. The following are allowed wild card characters in first string. * --> Matches with 0 or more instances of any character or set of characters. ? --> Matches with any one character. For example, “g*ks” matches with “geeks” match. And string “ge?ks*” matches with “geeksforgeeks” (note ‘*’ at the end of first string). But “g*k” doesn’t match with “gee” as character ‘k’ is not present in second string. """ def match(str1,str2,first,second): if first == len(str1) and second == len(str2) : return True if first < len(str1) and second == len(str2) : return False if (first < len(str1) and str1[first] == '?' ) or (first<len(str1) and second < len(str2) and str1[first]==str2[second]) : return match(str1,str2,first+1,second+1) if first < len(str1) and str1[first] == '*' : return match(str1,str2,first,second+1) or match(str1,str2,first+1,second+1) return False if __name__=='__main__': print(match('g*ks','geeksforgeeks',0,0)) print(match('ge?ks','geeks',0,0)) print(match('g?ek*','geeksforgeeks',0,0)) print(match('*p','geeks',0,0))
true
38333c31be9bf385cbc0ad0f612ce39907f30648
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/LinkedList/MoveLastToFirst.py
787
4.46875
4
from GeeksForGeeks.LinkedList.SinglyLinkedList import LinkedList """ Move last element to front of a given Linked List Write a C function that moves last element to front in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4. """ def move_nth(head): if not head : return else : current = head prev = head while current.next is not None : prev = current current = current.next prev.next = None current.next = head head = current return head if __name__=='__main__': ll = LinkedList() for i in range(1,10): ll.insert_at_ending(i) ll.head = move_nth(ll.head) ll.print_list()
true
b5a1b48719e01685184f6546f5bac08e7804502e
vidyasagarr7/DataStructures-Algos
/Cormen/2.3-5.py
761
4.125
4
def binary_search(input_list,key): """ Binary search algorithm for finding if an element exists in a sorted list. Time Complexity : O(ln(n)) :param input_list: sorted list of numbers :param key: key to be searched for :return: """ if len(input_list) is 0: return False else : mid = len(input_list)//2 if key == input_list[mid]: return True elif key < input_list[mid-1]: return binary_search(input_list[:mid-1],key) elif key > input_list[mid]: return binary_search(input_list[mid:],key) if __name__=="__main__": test = [23,45,65,13,778,98,25,76,48,28,85,97] test.sort() print(binary_search(test,98)) print(binary_search(test,12))
true
f0420e011a39072b2edd46884b9bcdb1ede1270b
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Arrays/CheckConsecutive.py
1,492
4.125
4
import sys """ Check if array elements are consecutive | Added Method 3 Given an unsorted array of numbers, write a function that returns true if array consists of consecutive numbers. Examples: a) If array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers from 1 to 5. b) If array is {83, 78, 80, 81, 79, 82}, then the function should return true because the array has consecutive numbers from 78 to 83. c) If the array is {34, 23, 52, 12, 3 }, then the function should return false because the elements are not consecutive. d) If the array is {7, 6, 5, 5, 3, 4}, then the function should return false because 5 and 5 are not consecutive. """ def check_duplicates(input_list): return len(input_list) == len(set(input_list)) def check_consecutive(input_list): if not input_list : return else : _max = -sys.maxsize _min = sys.maxsize for num in input_list : if num < _min : _min = num if num > _max : _max = num if _max - _min == len(input_list)-1 and check_duplicates(input_list): return True return False if __name__=='__main__': test = [5, 2, 3, 1, 4] print(check_consecutive(test)) test1 = [83, 78, 80, 81, 79, 82] print(check_consecutive(test1)) test2 = [34, 23, 52, 12, 3] print(check_consecutive(test2)) test3 = [7, 6, 5, 5, 3, 4] print(check_consecutive(test3))
true
7eefbcb7099c14384b4046d2cfcece1fba35a473
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Strings/InsertSpaceAndPrint.py
916
4.15625
4
""" Print all possible strings that can be made by placing spaces Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. Input: str[] = "ABC" Output: ABC AB C A BC A B C """ def toString(List): s = [] for x in List: if x == '\0': break s.append(x) return ''.join(s) def print_string(string,out_str,i,j): if i == len(string) : out_str[j] = '\0' print(toString(out_str)) return out_str[j] = string[i] print_string(string,out_str,i+1,j+1) out_str[j] = ' ' out_str[j+1] = string[i] print_string(string,out_str,i+1,j+2) def print_strings(string): n = len(string) out_str = [0]*2*n out_str[0]=string[0] print_string(string,out_str,1,1) if __name__=='__main__': string = 'abc' print(print_strings(string))
true
dd9088ed2e952a61cbc2f117274edd650d4aae16
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/LinkedList/ReverseAlternateKnodes.py
1,182
4.15625
4
from GeeksForGeeks.LinkedList.SinglyLinkedList import LinkedList """ Reverse alternate K nodes in a Singly Linked List Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm. Example: Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3 Output: 3->2->1->4->5->6->9->8->7->NULL. """ def reverse_alt_knodes(head,k): if not head : return else : current = head next = None prev = None count = 0 while current and count < k : next = current.next current.next = prev prev = current current = next count += 1 if next : head.next = current count = 0 while current and count < k-1 : current = current.next count += 1 if current : current.next = reverse_alt_knodes(current.next,k) return prev if __name__=='__main__': ll = LinkedList( ) for i in range(1,10): ll.insert_at_ending(i) ll.head = reverse_alt_knodes(ll.head,3) ll.print_list()
true
57e66fcfe37a98d3b167627e8d0451ad9f37f567
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Arrays/ConstantSumTriplet.py
1,203
4.25
4
""" Find a triplet that sum to a given value Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false. For example, if the given array is {12, 3, 4, 1, 6, 9} and given sum is 24, then there is a triplet (12, 3 and 9) present in array whose sum is 24. Solution : - Brute force - use 3 nested loops - O(n^3) - Sort and iterating through the list, use two pointers for start and end - O(n^2) """ def find_triplet(input_list,value): input_list.sort() for i in range(len(input_list)): left = i+1 right = len(input_list)-1 while left < right : if input_list[i] + input_list[left] + input_list[right] > value : right = right -1 elif input_list[i] + input_list[left] + input_list[right] < value : left = left + 1 else : return input_list[i],input_list[left],input_list[right] return 'sum not found' if __name__=="__main__": input_list = [12, 3, 4, 1, 6, 9] value = 24 print(find_triplet(input_list,value))
true
6356464fb2f5e1c1440e0a5af8c7bc2ab5188183
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Arrays/TwoRepeatingNumbers.py
1,133
4.28125
4
""" Find the two repeating elements in a given array You are given an array of n+2 elements. All elements of the array are in range 1 to n. And all elements occur once except two numbers which occur twice. Find the two repeating numbers. For example, array = {4, 2, 4, 5, 2, 3, 1} and n = 5 The above array has n + 2 = 7 elements with all elements occurring once except 2 and 4 which occur twice. So the output should be 4 2. """ def find_repeating(input_list,n): if not input_list : return else : _xor = input_list[0] for i in range(1,n+1): _xor = _xor ^ input_list[i] ^ i _xor = _xor ^ input_list[n+1] set_bit = _xor & ~(_xor-1) a,b = 0,0 for i in range(len(input_list)): if input_list[i] & set_bit : a = a ^ input_list[i] else: b = b ^ input_list[i] for i in range(1,n+1): if i & set_bit : a = a ^ i else : b = b^i return a,b if __name__=='__main__': test = [4, 2, 4, 5, 2, 3, 1] print(find_repeating(test,5))
true
ee861e0efdb6e5515dd24ad97b15d2fecefde994
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/LinkedList/NthElement.py
877
4.125
4
from GeeksForGeeks.LinkedList.SinglyLinkedList import LinkedList,Node """ Write a function to get Nth node in a Linked List Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1->10->30->14, index = 2 Output: 30 The node at index 2 is 30 """ def getNthNode(head,n): """ function to return nth node from the start in a singly linkedlist :param head: :param n: nth node :return: """ if not head : return None count = 0 temp = head while temp and count < n: temp = temp.next count += 1 if temp : return temp.data else : return temp if __name__=="__main__": ll = LinkedList() for i in range(1,10): ll.insert_at_begining(i) print(getNthNode(ll.head,5)) xt
true
c71547e58e1d6c3c5d5caade6d1091312a3d6f71
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Strings/PrintDistinctPermutations.py
1,065
4.125
4
""" Print all distinct permutations of a given string with duplicates Given a string that may contain duplicates, write a function to print all permutations of given string such that no permutation is repeated in output. Examples: Input: str[] = "AB" Output: AB BA Input: str[] = "AA" Output: AA Input: str[] = "ABC" Output: ABC ACB BAC BCA CBA CAB Input: str[] = "ABA" Output: ABA AAB BAA Input: str[] = "ABCA" Output: AABC AACB ABAC ABCA ACBA ACAB BAAC BACA BCAA CABA CAAB CBAA REVISIT """ def print_distinct_permutations(input_string,left,right): if left==right: print(''.join(input_string)) else: #print('printing left {}'.format(left)) for i in range(left,right): input_string[left],input_string[i] = input_string[i],input_string[left] print_distinct_permutations(input_string,left+1,right) input_string[left],input_string[i]=input_string[i],input_string[left] if __name__=='__main__': string = list('ABCD') print_distinct_permutations(string,0,len(string))
true
b5b4d136247ccd07ddc1da1a665775f36c1713a4
vidyasagarr7/DataStructures-Algos
/Trees/SearchElement.py
1,191
4.21875
4
from Karumanchi.Trees import BinaryTree from Karumanchi.Queue import Queue def search_element(node,element): """ Algorithm for searching an element Recursively :param node: :param element: :return: """ if not node: return False else: if node.data == element: return True return search_element(node.get_left(),element) or search_element(node.get_right(),element) def _search_element(root,element): """ Non-Recursive implementation for searching an element in binary Tree :param root: :param element: :return: """ if not root : return False else: que = Queue.Queue1() que.enqueue(root) while not que.is_empty(): node = que.dequeue() if node.data == element: return True if node.get_left(): que.enqueue(node.get_left()) if node.get_right(): que.enqueue(node.get_right()) return False if __name__=="__main__": tree= BinaryTree() for i in range(1,10): tree.add_node(i) for i in range(1,15): print(_search_element(tree.root,i))
true
18858b1ec937e1850ab9ae06c83dc35d15d36c85
vidyasagarr7/DataStructures-Algos
/609-Algos/Lab-2/BubbleSort.py
513
4.28125
4
def bubble_sort(input_list): """ Bubble Sort algorithm to sort an unordered list of numbers :param input_list: unsorted list of numbers :return: sorted list """ for i in range(len(input_list)): for j in range(len(input_list)-1-i): if input_list[j]>input_list[j+1]: input_list[j],input_list[j+1] = input_list[j+1],input_list[j] return input_list if __name__=="__main__": test = [23,25,12,14,17,85,98,34,32,109,56] print(bubble_sort(test))
true
2f45a066f0b461b0992094cb8f515ce3f4dd2269
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Strings/ReverseWords.py
420
4.4375
4
""" Reverse words in a given string Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i” """ def reverse_words(string): words_list = string.split(' ') words_list.reverse() return ' '.join(words_list) if __name__=='__main__': string = ' i like this program very much ' print(reverse_words(string))
true
e20c9d2168f9e5c23ef638185ae2e00adbb90dfa
vidyasagarr7/DataStructures-Algos
/Karumanchi/Searching/CheckDuplicates.py
1,726
4.28125
4
from Karumanchi.Sorting import MergeSort from Karumanchi.Sorting import CountingSort def check_duplicates(input_list): """ O(n^2) algorithm to check for duplicates :param input_list: :return: """ for i in range(len(input_list)): for j in range(i+1,len(input_list)): if input_list[i]==input_list[j]: return True return False def check_duplicates_opt(input_list): """ O(n*log(n)) algorithm - Sort the list :param input_list: :return: """ sorted_list = MergeSort.merge_sort(input_list) for i in range(len(sorted_list)-1): if sorted_list[i] == sorted_list[i+1]: return True return False def check_duplicates_opt2(input_list): """ considering the input elements in the range 0-(n-1) --> we can sort the array using counting sort in O(n) time and traverse in linear time :param input_list: :return: """ sorted_list = CountingSort.counting_sort(input_list,10) for i in range(len(sorted_list)-1): if sorted_list[i]==sorted_list[i+1]: return True return False def check_duplicates_negation(input_list): """ Assumption : input list values range from 0-(n-1) and all numbers are positive. :param input_list: :return: """ for i in range(len(input_list)): if input_list[input_list[i]]<0: return True else : input_list[input_list[i]] = -input_list[input_list[i]] return False if __name__=="__main__": test = [1,2,3,4,6,7,8,9,4] print(check_duplicates(test)) print(check_duplicates_opt(test)) print(check_duplicates_opt2(test)) print(check_duplicates_negation(test))
true
2ef19d4886644d077c1f53c97f7de400c7019540
vidyasagarr7/DataStructures-Algos
/GeeksForGeeks/Arrays/Rearrange.py
1,096
4.1875
4
""" Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space Given an array arr[] of size n where every element is in range from 0 to n-1. Rearrange the given array so that arr[i] becomes arr[arr[i]]. This should be done with O(1) extra space. Examples: Input: arr[] = {3, 2, 0, 1} Output: arr[] = {1, 0, 3, 2} Input: arr[] = {4, 0, 2, 1, 3} Output: arr[] = {3, 4, 2, 0, 1} Input: arr[] = {0, 1, 2, 3} Output: arr[] = {0, 1, 2, 3} If the extra space condition is removed, the question becomes very easy. The main part of the question is to do it without extra space. """ def rearrange(input_list): if not input_list : return else : n = len(input_list) for i in range(len(input_list)) : input_list[i] += (input_list[input_list[i]]%n)*n for i in range(len(input_list)): input_list[i] = input_list[i]//n return input_list if __name__=='__main__': test = [3, 2, 0, 1] print(rearrange(test)) test = [4,0,2,1,3] print(rearrange(test)) test = [0,1,2,3] print(rearrange(test))
true
4b1793f6d8c391ad17ecdfabc74702886aa02ebc
vidyasagarr7/DataStructures-Algos
/Karumanchi/Selection/KthSmallest.py
1,531
4.40625
4
from Karumanchi.Sorting import QuickSort def partition(list,start,end): """ Partition Algorithm to partition a list - selecting the end element as the pivot. :param list: :param start: :param end: :return: """ i=start-1 pivot = list[end] for j in range(start,end): if list[j] <= pivot: i+=1 list[i],list[j]=list[j],list[i] list[i+1],list[end]=list[end],list[i+1] return i+1 def _find_k_smallest(input_list,start,end,k): """ Algorithm using partitioning for finding kth smallest number. :param input_list: :return: """ if k>0 and k <= end-start+1: part = QuickSort.partition_end(input_list,start,end) if part-start == k-1: return input_list[part] elif part-start> k-1: return _find_k_smallest(input_list,start,part-1,k) else: return _find_k_smallest(input_list,part+1,end,k-part+start-1) return False def find_k_smallest(input_list,k): return _find_k_smallest(input_list,0,len(input_list)-1,k) def find_k_smallest_opt(input_list,k): """ Median of medians. :param input_list: :param k: :return: """ return 0 def find_median(input_list): """ Algorithm to find the median of inputlist :param input_list: :return: """ return find_k_smallest(input_list,len(input_list)//2) if __name__=="__main__": test_input = [3,2,1,7,6,5,8,9,4,5,10,11,12,13,14,15] print(find_median(test_input))
true
d7f32f9626f66394f459babf3b22b0ad229a0203
chenliang15405/python-learning
/study_day01-基础/11_切片.py
553
4.21875
4
""" 切片: 语法: 序列[开始位置下标:结束位置下标:步长] 注意: 不包含结束位置的下标数据 步长是选取间隔,默认步长为1,步长是可选参数 """ str = '0123456789' print(str[2:]) # 如果不写结束,表示到结尾 print(str[:3]) # 如果不写开始,表示从头开始 print(str[:]) # 开始和结尾都不写,表示选取所有 print(str[-3:-1]) # 负数表示从后向前,-3 表示最后一个数 # 如果选取的方向和步长的方法冲突,那么无法选择数据
false
de78157337b2849f1bde3dceda7ce00ff7325e79
chenliang15405/python-learning
/study_day07-python高级语法/06_创建property其他属性的方式.py
1,154
4.21875
4
""" 在对象中,可以通过定义property的三种方式,来触发属性的更新等情况并进行计算: 1。 获取数据: 必须返回一个值,并且没有参数,可以通过计算返回一个值 @property def price(self): return 100 2. setter: 通过@<propertyname>.setter的定义形式,当给property装饰的变量赋值的时候触发此方法 @price.setter def price(self, value): # 传递的参数是赋值时的参数 self.xxx = value 3. deleter: 通过@<propertyname>.deleter,当删除该property变量的时候触发此方法 @price.deleter def price(self): del self.xxx """ class Goods(object): def __init__(self): self.origin_price = 100 self.discount = 0.8 @property def price(self): new_price = self.origin_price * self.discount return new_price @price.setter def price(self, value): self.origin_price = value @price.deleter def price(self): del self.origin_price obj = Goods() obj.price obj.price = 200 del obj.price
false
c7e45ee0ceb6dcb6edd694ef58b8eaf10cfcac41
chenliang15405/python-learning
/study_day03-面向对象/文件/01_文件的基本操作.py
2,059
4.40625
4
""" python中操作文件的函数/方法: 1. open 函数: 打开文件,并返回文件操作对象 2. read 方法: 将文件内容读取到内存, 在同一个打开的文件中,读取一次,文件的指针会指向文件末尾,再次读取就读取不到数据 3. wirte 方法: 将制定内容写入到文件 4. close 方法: 关闭文件 打开文件的方式: 1. open() 函数: 默认的是以只读方式打开文件,只读不可写 2. open("文件名", "打开方式") 以指定的方式打开文件 打开方式: r : 默认模式,以只读方式打开 w: 只写的方式打开,如果文件存在会被覆盖,如果文件不存在会创建文件 a: 追加的方式打开,不能读,如果文件存在,会在末尾追加内容,如果文件不存在,则创建文件进行写入 r+ : 读写的方式打开 w+ : 读写的方式打开,如果文件存在会被覆盖,如果文件不存在会创建文件 a+ : 读写的方式打开,如果文件存在,会在末尾追加内容,如果文件不存在,则创建文件进行写入 读取文件的方式: 1. read 方法会一次性读取所有的内容到内存 2. readline 可以一次读取一行到内存 """ # 打开文件,默认是只读方式 file = open("README") # 读取 text = file.read() print(text) # 关闭 file.close() # 打开文件,以追加的方式 file = open("README", "a") # 写入 file.write("这是一段内容") # 关闭 file.close() # 打开文件,默认是只读方式 file = open("README") # 读取 while True: text = file.readline() if not text: break print(text) # 关闭 file.close() # 注意,文件中操作简洁方式: """这种方式就相当于try except了整个打开和关闭的过程,并且最后一定会自动关闭流""" """rb的读取方式 就是说 只读模式并且读取的数据为二进制""" with open("README", 'rb') as f: print(f.read())
false
706d32805925b2d80a4c9c1be436dd3f19bd8d11
buxuele/algo_snippet
/二叉树/sub_tree.py
1,955
4.28125
4
# python3 实现二叉树 # 最好是参考这篇再看一遍: # https://www.cnblogs.com/maxiaonong/p/10060086.html class Node: def __init__(self, element, lchild=None, rchild=None): self.element = element self.lchild = lchild self.rchild = rchild class Tree: def __init__(self, root=None): self.root = root def add(self, item): node = Node(item) if self.root is None: self.root = node return else: queue = [] queue.append(self.root) while queue: cur_node = queue.pop() # 拿到列表的最后一个元素,作为当前的指针节点 if cur_node.lchild is None: cur_node.lchild = node return elif cur_node.rchild is Node: cur_node.rchild = node return else: queue.append(cur_node.lchild) queue.append(cur_node.rchild) # 广度优先 def width_circle(self): if self.root is None: return '' else: queue = [] queue.append(self.root) while queue: cur_node = queue.pop() print(cur_node.element, end=" ") if cur_node.lchild is not None: queue.append(cur_node.lchild) if cur_node.rchild is not None: queue.append(cur_node.rchild) # 前序遍历 def pre_order(self, node): if node == None: return print(node.element, end="") self.pre_order(node.lchild) self.pre_order(node.rchild) # 中序遍历 def in_order(self, node): if node == Node: return print(node.element, end="") self.in_order(node.lchild) self.in_order(node.rchild) # 后序遍历
false
638c098b21f50c29ddbb8136459117a099677acc
educa2ucv/Material-Apoyo-Python-Basico
/Codigos/2-TiposDeDatos/Logico.py
579
4.375
4
""" En Python tenemos las siguientes operaciones logicas y operandos logicos: Mayor estricto (>) Mayor o igual (>=) Menor estricto (<) Menor o igual (<=) Igualdad (==) Diferente (!=) Y lógico (and) O lógico (or) Negación lógico (not) """ """expresion = 6 >= 3 print(expresion) print(10 < 10)""" """expresion = "Alexanyer" == "Jose" expresion2 = "Alexanyer" != "Educa2" print(expresion,expresion2)""" #print(6 >= 10 and 5 < 4) #print("Educa2" == "Educa2" or "Alexanyer" != 5) print(not 5 >= 10)
false
270b0e19adea8d97c788ff31305616b65c516f76
shenzekun/leetcode
/Sqrt_x.py
844
4.15625
4
""" 实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。 思路: 由于 x^2是单调递增,因此使用二分法 """ class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ if x == 0 or x == 1: return x l, r = 1, x while l <= r: m = int((l+r)/2) if m == x/m: return m elif m > x/m: r = m-1 else: l = m+1 res = m return res
false
0f1edc71a026eac62eb4b641c0bd9ede2a98bbee
imran9891/Python
/PyFunctionReturns.py
882
4.125
4
#!/usr/bin/env python # coding: utf-8 # <h3 align="center">Function Return</h3> # In[ ]: def sum1(num1, num2): def another_func(n1,n2): return n1 + n2 return another_func def sum2(num1, num2): def another_func2(n1,n2): return n1 + n2 return another_func2(num1, num2) print(sum1(10,5)) # this will just return the address of the function print(sum1(10,5)(5,8)) # this will give arguments to the another_func # above is same as doing: total = sum1(10,5) print(total) print(total(5,8)) print(sum2(10,5)) # print(another_func(45, 55)) # this will give error, because the function is actually undefined # , and to call this function, first we will have to call the # parent function. So we can get the memory location of the # function.
true
d7c4c21563a09c85d82d652626eb7f5230b9254d
khairooo/Learn-linear-regression-the-simplest-way
/linear regression.py
1,829
4.4375
4
# necessary packages import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error,r2_score # generate random data-set np.random.seed(0) # generate 100 random numbers with 1d array x = np.random.rand(100,1) y = 2 + 3 * x + np.random.rand(100,1) # Implemantations with sckit- learn # Model initialization regression_model = LinearRegression() # fit the data (train the model) regression_model.fit(x,y) # Predict y_predicted = regression_model.predict(x) # hint: '''to visualize the data we can just import the misxtend packages as follow: >>>from mlxtend.plotting import plot_linear_regression >>>intercept, slope, corr_coeff = plot_linear_regression(X, y) >>>plt.show() ''' # Model evaluation: # 1) rmse (root mean squared error) '''what happen here under the hood is a juste the implimentation of the math equation >>> np.sqrt(((predictions - targets) ** 2).mean())''' rmse = mean_squared_error(y,y_predicted) # 2) R2 ( coefficient of determination) '''Explains how much the total variance of the dependent varaible can be reduced by using the least sqaured regression mathematically : R2 = 1 - (SSr/SSt) where: # sum of square of residuals ssr = np.sum((y_pred - y_actual)**2) # total sum of squares sst = np.sum((y_actual - np.mean(y_actual))**2) # R2 score r2_score = 1 - (ssr/sst) ''' r2 = r2_score(y,y_predicted) # Printing values,slope, intercept, root mean squared error, r2 print('Slope:' ,regression_model.coef_) print('Intercept:', regression_model.intercept_) print('Root mean squared error: ', rmse) print('R2 score: ', r2) # plotting values : # data points plt.scatter(x, y, s=10) plt.xlabel('x') plt.ylabel('y') plt.show()
true
efa056ec08f3358df04e1da1bdef6db73dec39c3
chenlongjiu/python-test
/rotate_image.py
936
4.25
4
''' You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Follow up: Could you do this in-place? ''' class Solution(object): def rotate(self, matrix): for row in xrange(len(matrix)): for col in xrange(row,len(matrix)): matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col] #then reverse: for row in xrange(len(matrix)): for col in xrange(len(matrix)/2): matrix[row][col], matrix[row][-col-1] = matrix[row][-col-1], matrix[row][col] print matrix[0] print matrix[1] print matrix[2] print "//////////////////////////" #print matrix """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ matrix = [[1,2,3],[4,5,6],[7,8,9]] print Solution().rotate(matrix)
true
1290224ca58fbf8f17c968dcb9318ce6594845bd
geekysid/Python-Basics
/3. List, Set, Tuple/SetOperations.py
1,967
4.4375
4
print("SET OPERATIONS") setA = {1, 2, 3, 4, 5, 6, 7, 8, 9} setB = {2, 4, 6, 8, 10} setC = {"2", "4", "6", "8"} print(f"SetA : {setA}") print(f"SetB : {setB}") print(f"SetC : {setC}") print() print("==UNION (|)==") # returns every elements in two sets print(f"setA.union(setB): {setA.union(setB)}") print(f"setA | setB: {setA | setB}") print(f"setB | setA: {setB | setA}") print() print("==INTERSECTION (&)==") # returns only common elements in two sets print(f"setA.intersection(setB): {setA.union(setB)}") print(f"setA & setB: {setA & setB}") print(f"setB & setA: {setB & setA}") print() print("==DIFFERENCE (-)==") # returns elements of one set which are not in 2nd sets print(f"setA.difference(setB): {setA.difference(setB)}") print(f"setA - setB: {setA - setB}") print(f"setB - setA: {setB - setA}") print() print("==SYMMETRIC_DIFFERENCE (^)==") # returns set of elements in in 2 sets except those that are common in both. print(f"setA.symmetric_difference(setB): {setA.symmetric_difference(setB)}") print(f"setA ^ setB: {setA ^ setB}") print(f"setB ^ setA: {setB ^ setA}") print() print("==ISSUBSET==") # returns True if every element of 1st set is also available in set 2 else returns False print(f"setA.issubset(setB): {setA.issubset(setB)}") print(f"setB.issubset(setA): {setB.issubset(setA)}") print() print("==ISDISJOINT==") # returns True if no element of in 2 sets are common else returns False print(f"setA.isdisjoint(setB): {setA.isdisjoint(setB)}") print(f"setB.isdisjoint(setA): {setB.isdisjoint(setA)}") print(f"setC.isdisjoint(setA): {setC.isdisjoint(setA)}") print(f"setC.isdisjoint(setB): {setC.isdisjoint(setB)}") print() print("==DIFFERENCE_UPDATE==") # this functions acts similar to difference() but instead of returning a value, # its updates the set to the value setA.difference_update(setB) print(f"setA.difference_update(setB): {setA}") print()
false
4debf55c34b266031b2c68890e629717f6043d76
geekysid/Python-Basics
/4. Dictionary/Dictionary Challenge Modified 2.py
1,714
4.21875
4
# Modify the program so that the exits is a dictionary rather than a list, with the keys being the numbers of the # locations and the values being dictionaries holding the exits (as they do at present). No change should be needed # to the actual code. locations = {0: "You are sitting in front of a computer learning Python", 1: "You are standing at the end of a road before a small brick building", 2: "You are at the top of a hill", 3: "You are inside a building, a well house for a small stream", 4: "You are in a valley beside a stream", 5: "You are in the forest"} # Here we simply converted list to dictionary by using index of list as the key of the map. This makes our code work # without any change exits = {0: {"Q": 0}, 1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0}, 2: {"N": 5, "Q": 0}, 3: {"W": 1, "Q": 0}, 4: {"N": 1, "W": 2, "Q": 0}, 5: {"S": 1, "W": 2, "Q": 0}} loc = 1 while True: print() # Using join() to fetch and converts all the keys of the exits[loc] dictionary availableMovements = ", ".join(exits[loc].keys()) print(f"{locations[loc]}") userInput = input("Available Movements Are: {}\nPlease enter where you wnt to move: ".format(availableMovements)) if userInput.upper() in exits[loc].keys(): # checking if the direction entered by user or not loc = exits[loc][userInput.upper()] if loc == 0: # if user press 'Q' and want to exit print("You have successfully exited game.") break else: # if user enters invalid direction print("That is not a valid movements. Please try again.") continue
true
e75b0ab18452e7da90b5f6c81bc317224eaf24f1
jmshin111/alogrithm-test
/merge two sorted list.py
1,746
4.15625
4
# A single node of a singly linked list import sys import timeit class Node: # constructor def __init__(self, data=None): self.data = data self.next = None # A Linked List class with a single head node class LinkedList: def __init__(self): self.head = None self.end = None self.len = 1 def add(self, node): self.end.next = node self.end = node self.len = self.len + 1 # Linked List with a single node def mergeTwoSortedList(linked_list1, linked_list2): min_data = sys.maxsize result_linked_list = LinkedList() result_linked_list.end = result_linked_list.head = Node('start') while linked_list1 or linked_list2: if not linked_list1: result_linked_list.add(Node(linked_list2.data)) linked_list2 = linked_list2.next if not linked_list2: result_linked_list.add(Node(linked_list1.data)) linked_list1 = linked_list1.next if int(linked_list1.data) < int(linked_list2.data): result_linked_list.add(Node(linked_list1.data)) linked_list1 = linked_list1.next else: result_linked_list.add(Node(linked_list2.data)) linked_list2 = linked_list2.next return result_linked_list linked_list = LinkedList() linked_list.end = linked_list.head = Node(1) linked_list.add(Node(2)) linked_list.add(Node(4)) linked_list2 = LinkedList() linked_list2.end = linked_list2.head = Node(1) linked_list2.add(Node(3)) linked_list2.add(Node(4)) start_time = timeit.default_timer() print(mergeTwoSortedList(linked_list.head, linked_list2.head)) terminate_time = timeit.default_timer() # 종료 시간 체크 print("%f초 걸렸습니다." % (terminate_time - start_time))
true
439f8e77560fa42094e061ba7c4e1bd71956b8fd
mohdelfariz/distributed-parallel
/Lab5-Assignment3.py
1,284
4.25
4
# Answers for Assignment-3 # Importing mySQL connector import mysql.connector # Initialize database connection properties db_connection = mysql.connector.connect( host="localhost", user="root", passwd="", database="my_first_db" ) # Show newly created database (my_first_db should be on the list) print(db_connection) # (a)Write a MySQL statement to create a simple table countries including columns-country_id, country_name and region_id. # 1) Creating database_cursor to perform SQL operation db_cursor = db_connection.cursor() # 2) We create and execute command to create a database table (countries) db_cursor.execute( "CREATE TABLE countries(country_id INT AUTO_INCREMENT PRIMARY KEY, country_name VARCHAR(255), region_id INT(6))") # 3) Print the database table (Table countries should be on the list) db_cursor.execute("SHOW TABLES") for table in db_cursor: print(table) # (b)Write a MySQL statement to rename the table countries to country_new. # 1) Altering the database table countries name db_cursor.execute( "ALTER TABLE countries RENAME TO country_new") # 2) Print the newly altered table (countries should changed to country_new) db_cursor.execute("SHOW TABLES") for table in db_cursor: print(table)
true
453d4cfd55465b4793848e9ba7935aff0592dde1
gopikris83/gopi_projects
/GlobalVariables.py
401
4.25
4
# -------- Defining variables outside of the function (Using global variables) ---------------- x = "Awesome" def myfunc(): print (" Python is "+x) myfunc() # ---------- Defining variables inside of the function (Using local variables) -------------------------- x = "Awesome" def myfunc(): x = "Fantastic" print ("Python is "+x) myfunc() print ("Python is"+x)
true
07c316740d12e1696356fea2dfef3d0e224e5193
ShalomVanunu/SelfPy
/Targil5.3.5.py
342
4.15625
4
def distance(num1, num2, num3): num1_num2 = abs(num2-num1) num3_num2 = abs(num3-num2) # print(num3_num2) # print(num1_num2) if (num1_num2 == 1 and num3_num2 > 2 ): return True else: return False print('distance(1, 2, 10)') print(distance(1, 2, 10)) print('distance(4, 5, 3)') print(distance(4, 5, 3))
false
85fa0da795f8130c75bbdb6695fae9319234c74f
ShalomVanunu/SelfPy
/Targil7.3.1.py
640
4.21875
4
def show_hidden_word(secret_word, old_letters_guessed): hidden_word = [] for letter in secret_word: if letter not in old_letters_guessed: hidden_word.append(' _') else: hidden_word.append(letter) return ' '.join(hidden_word) def main(): # Call the function func secret_word = "mammals" old_letters_guessed = ['s', 'p', 'j', 'i', 'm', 'k'] print(show_hidden_word(secret_word, old_letters_guessed)) # m _ m m _ _s secret_word = "mammals" old_letters_guessed = [ ] print(show_hidden_word(secret_word, old_letters_guessed)) if __name__ == "__main__": main()
false
c23b5e18a881d02083b06c9e0cca83197c62e928
deficts/hackerrank-solutions
/PythonDataStructures/Lists.py
489
4.21875
4
MyList=[1,2,4,5] #Agregar algo al final MyList.append("hola") print(MyList) #Agregar algo en un cierto índice MyList.insert(1,"mundo") print(MyList) #Remover un objeto pasado MyList.remove("mundo") print(MyList) #Regresar y quitar un objeto de un indice o el ultimo MyList.pop() MyList.pop(0) print(MyList) #Quitar un objeto de la lista sin regresarlo del MyList[0] print(MyList) #Voltear una lista MyList.reverse() print(MyList) #Copiar lista MyCopy = MyList.copy() print(MyCopy)
false
e65c2135625c668523ea865f75bc320b2cdab043
gr8tech/pirple.thinkific.com
/Python/Homework3/main.py
931
4.1875
4
''' Python Homework Assignment 3 Course: Python is Easy @ pirple Author: Moosa Email: gr8tech01@gmail.com `If` statements; Comparison of numbers ''' def number_match(num1, num2, num3): ''' Functions checks if 2 or more of the given numbers are equal Args: num1, num2, num3 num1, num2, num3 can be an Integer or an Integer string Returns: True if 2 or more numbers are equal, False otherwise Examples: number_match(1,2,1) returns True number_match(1,2,"1") returns True number_match(1,2,3) return False Logic: There are three posibilities 1. num1 is equal to num2 OR 2. num1 is equal to num3 OR 3. num2 is equal to num3 ''' num1, num2, num3 = int(num1), int(num2), int(num3) if (num1 == num2) or (num1 == num3) or (num2 == num3): return True else: return False # Function tests # Returns False print(number_match(1,2,3)) # Returns True print(number_match(1,2,1)) #Returns True print(number_match("5",6,5))
true
fbc4c72d145f853991cda9bba427f33de8ab8d08
jagadeeshindala/python
/Project.py
850
4.28125
4
#Rock paper scissors game with computer import random #Function def game(a,b): if(a == b): return None if(a=="r"): if(b=="s"): return False else: return True if(a=="s"): if(b=="p"): return False else: return True if(a=="p"): if(b=="w"): return False else: return True #Driver code n = random.randint(1,3) if(n == 1): comp = 'r' if(n == 2): comp = 'p' if(n == 3): comp = 's' chr = input("Enter your choice: Rock(r) Paper(p) Scissors(s): ") # ch = random.randint(1,3) # if(ch == 1) : # chr = 'r' # if(ch == 2): # chr = 'p' # if(ch == 3): # chr = 's' winner = game(comp,chr) print(f"computer choose {comp}") print(f"You choose {chr}") if(winner == None): print("The game is tied !") elif(winner): print("Hurray! You Won") else: print("Better luck next time")
false
1582966887ebcfcec8a2ddb74e0823cb7b72c95e
Chethan64/PESU-IO-SUMMER
/coding_assignment_module1/5.py
212
4.25
4
st = input("Enter a string: ") n = len(st) flag = 0 for i in st: if not i.isdigit(): flag = 1 if(flag): print("The string is not numeric") else: print("The string is numeric")
true
b024cf8229c1ea31c1299d283b52375d0c11ec10
Abdelmuttalib/Python-Practice-Challenges
/Birthday Cake Candles Challenge/birthDayCakeCandles.py
815
4.15625
4
####### SOLUTION CODE ######## def birthdayCakeCandles(candles): ## initializing an integer to hold the value of the highest value highest = 0 ## count of highest to calculate how many the highest value is found in the array count_of_highest = 0 ## iterate over the array to determine the highest value for i in candles: if i > highest: highest = i ## iterate over the array to determine how many time the highest value occurs for i in candles: if i == highest: count_of_highest += 1 ## Returning the number of times the highest value is found in the array return count_of_highest ## Simple Test print(birthdayCakeCandles([2, 4, 6, 6])) """ OUTPUT: 2 ## as the highest number is 6 and it occurs two times in the array """
true
067c383afe1a81e2b864b2f8d274c2e7768ed190
shreyashg027/Leetcode-Problem
/Data Structure/Stacks.py
504
4.125
4
class Stack: def __init__(self): self.stack = [] def push(self, data): if data not in self.stack: self.stack.append(data) def peek(self): return self.stack[len(self.stack)-1] def remove(self): if len(self.stack) <= 0: return 'No element in the stack' else: return self.stack.pop() test = Stack() test.push('Mon') test.push('Tue') test.push('wed') print(test.peek()) print(test.remove()) print(test.peek())
true
4bce5f49c82972c9e7dadd48794bcc545e25095b
miketwo/euler
/p7.py
704
4.1875
4
#!/usr/bin/env python ''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? ''' from math import sqrt, ceil def prime_generator(): yield 2 yield 3 num = 3 while True: num += 2 if is_prime(num): yield num def is_prime(num): for i in xrange(2, int(ceil(sqrt(num))) + 1): if num % i == 0: return False return True def main(): print is_prime(9) loop = 0 for prime in prime_generator(): loop += 1 print "{}: {}".format(loop, prime) if loop == 10001: break if __name__ == '__main__': main()
true
9e84eeb486846d437d69a8d08c717240cbb462a5
TejaswitaW/Advanced_Python_Concept
/RegEx12.py
260
4.125
4
#use of function fullmatch in regular expression import re s=input("Enter string to be matched") m=re.fullmatch(s,"abc") if(m!=None): print("Complete match found for the string:",m.start(),m.end()) else: print("No complete match found for the string")
true
aa4804d2a19435b061d58c5855bee819aee31751
TejaswitaW/Advanced_Python_Concept
/RegEx23.py
232
4.5
4
#Regular expression to find valid mobile number import re n=input("Enter mobile number") v=re.search("^+91",n) if v!=None: print("It is a valid mobile number in India") else: print("It is not valid mobile number in India")
false
d139c57f5add5f8be6008fad651ea3eca04e4c39
TejaswitaW/Advanced_Python_Concept
/ExceptionElse.py
385
4.15625
4
#Exception with else block #else block is executed only when there is no exception in try block try: print("I am try block,No exception occured") except: print("I am except block executed when there is exception in try block") else: print("I am else block,executed when there is no exception in try block") finally: print("I am finally block I get executed everytime")
true
8784f56f872cea6ffab7517f482296ea9904a1b4
SerdarKuliev/proj1
/4/4-1.py
622
4.15625
4
#Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. #В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия. #Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. import my_func print(str(my_func.my_f(int(input("time")), int(input("price")), int(input("премия")))))
false
57f541234da83f773c5e138adedb2caf20cfceb3
SerdarKuliev/proj1
/2/2-1.py
1,320
4.125
4
#1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных каждого элемента. #Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. my_list = [34, None, 3.14, "Yo!", [1,2,67], 8*5, '8*5', True, '1:key'] print("Всего элементов: " + str(len(my_list))) print("Тип списка: " + str(type(my_list))) print("1-й элемент: " +str(type(my_list[0])) + " = " + str(my_list[0])) print("3-й элемент: " +str(type(my_list[2])) + " = " + str(my_list[2])) print("4-й элемент: " +str(type(my_list[3])) + " = " + str(my_list[3])) print("5-й элемент: " +str(type(my_list[4])) + " = " + str(my_list[4])) print("6-й элемент: " +str(type(my_list[5])) + " = " + str(my_list[5])) print("7-й элемент: " +str(type(my_list[6])) + " = " + str(my_list[6])) print("8-й элемент: " +str(type(my_list[7])) + " = " + str(my_list[7])) print("9-й элемент: " +str(type(my_list[8])) + " = " + str(my_list[8])) print(my_list) ok = input("!")
false
1f4069a21af18b88a7ddf117162036d212f2135c
lfarnsworth/GIS_Python
/Coding_Challenges/Challenge2/2-List_Overlap.py
1,133
4.375
4
# 2. List overlap # Using these lists: # # list_a = ['dog', 'cat', 'rabbit', 'hamster', 'gerbil'] # list_b = ['dog', 'hamster', 'snake'] # Determine which items are present in both lists. # Determine which items do not overlap in the lists. # #Determine which items overlap in the lists: def intersection(list_a, list_b): list_c =[str for str in list_a if str in list_b] return list_c list_a = ['dog', 'cat', 'rabbit', 'hamster', 'gerbil'] list_b = ['dog', 'hamster', 'snake'] print('These are in common:') print(intersection(list_a, list_b)) print('\r\n') #Determine which items DO NOT overlap in the lists: list_a = ['dog', 'cat', 'rabbit', 'hamster', 'gerbil'] list_b = ['dog', 'hamster', 'snake'] def exclusion(list_a, list_b): list_c =[str for str in list_a if not str in list_b] list_c.extend([str for str in list_b if not str in list_a]) return list_c print('These are NOT in common:') print(exclusion(list_a, list_b)) print('\r\n') # Feedback - Great! Thanks for the helpful print statement in common/not in common. Keep an eye on how you are laying # out your code to keep it clean and organized.
true
f91c9dd7ea1c66a0a757d32dc00c3e1f0adef7e7
udhayprakash/PythonMaterial
/python3/06_Collections/03_Sets/a_sets_usage.py
1,219
4.40625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Purpose: Working with Sets Properties of sets - creating using {} or set() - can't store duplicates - sets are unordered - can't be indexed - Empty sets need to be represented using set() - stores only immutable object - basic types, tuple, string - sets are mutable objects """ running_ports = [11, 22, 11, 44, 22, 11] print("type(running_ports)", type(running_ports)) print("len(running_ports) ", len(running_ports)) print("running_ports ", running_ports) print() # Method 1 - To remove duplicates in a list/tuple of elements filtered_list = [] for each_port in running_ports: if each_port in filtered_list: continue filtered_list.append(each_port) print("len(filtered_list) ", len(filtered_list)) print("filtered_list: ", filtered_list) print() unique_ports = {11, 22, 11, 44, 22, 11} print(f"{type(unique_ports) =}") print(f"{len(unique_ports) =}") print(f"{unique_ports =}") print() # Method 2 - using sets to remove duplicates filtered_list = list(set(running_ports)) print("len(filtered_list) ", len(filtered_list)) print("filtered_list: ", filtered_list) print()
true
627c4ac2e040d41a4e005253e1dd7c20f9d5cf63
udhayprakash/PythonMaterial
/python3/04_Exceptions/11_raising_exception.py
1,248
4.28125
4
#!/usr/bin/python3 """ Purpose: Raising exceptions """ # raise # RuntimeError: No active exception to reraise # raise Exception() # Exception # raise Exception('This is an error') # Exception: This is an error # raise ValueError() # ValueError # raise TypeError() # raise NameError('This is name error') # NameError: This is name error try: raise NameError("This is name error") except NameError as ne: print(f"{ne =}") # try: # raise NameError('This is name error') # except NameError as ne: # ne.add_note("PLEASE ENSURE NOT TO REPEAT") # raise # # print(f"{ne =}") # NOT REACHABLE try: try: raise NameError("This is name error") except NameError as ne: ne.add_note("PLEASE ENSURE NOT TO REPEAT") raise # print(f"{ne =}") # NOT REACHABLE except Exception as ex: print(f"{ex =}") try: num1 = int(input("Enter an integer:")) num2 = int(input("Enter an integer:")) if num2 == 0: # raise Exception("Ensure that num2 is NON-ZERO") raise ZeroDivisionError("Ensure that num2 is NON-ZERO") except ZeroDivisionError as ze: print(repr(ze)) except Exception as ex: print(repr(ex)) else: division = num1 / num2 print(f"{division =}")
true
79eb6b4be07ee81b3a360a3fe2ab759947735a5e
udhayprakash/PythonMaterial
/python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/b1_process_pool.py
1,587
4.40625
4
""" Purpose: Multiprocessing with Pools Pool method allows users to define the number of workers and distribute all processes to available processors in a First-In-First-Out schedule, handling process scheduling automatically. Pool method is used to break a function into multiple small parts using map or starmap — running the same function with different input arguments. Whereas Process method is used to run different functions. """ import multiprocessing import os import time def task_sleep(sleep_duration, task_number): time.sleep(sleep_duration) print( f"Task {task_number} done (slept for {sleep_duration}s)! " f"Process ID: {os.getpid()}" ) if __name__ == "__main__": time_start = time.time() # Create pool of workers pool = multiprocessing.Pool(2) # Map pool of workers to process pool.starmap(func=task_sleep, iterable=[(2, 1)] * 10) # Wait until workers complete execution pool.close() time_end = time.time() print(f"Time elapsed: {round(time_end - time_start, 2)}s") # Task 1 done (slept for 2s)! Process ID: 20464 # Task 1 done (slept for 2s)! Process ID: 22308 # Task 1 done (slept for 2s)! Process ID: 20464 # Task 1 done (slept for 2s)! Process ID: 22308 # Task 1 done (slept for 2s)! Process ID: 20464 # Task 1 done (slept for 2s)! Process ID: 22308 # Task 1 done (slept for 2s)! Process ID: 20464 # Task 1 done (slept for 2s)! Process ID: 22308 # Task 1 done (slept for 2s)! Process ID: 20464 # Task 1 done (slept for 2s)! Process ID: 20464 # Time elapsed: 12.58s
true
1bad217136738b325f1dd38d8484904f13d69989
udhayprakash/PythonMaterial
/python3/07_Functions/014_keyword_only_args.py
1,541
4.3125
4
#!/usr/bin/python3 """ Purpose: Functions Demo Function with Keyword ONLY args Named arguments appearing after '*' can only be passed by keyword Present only in Python 3.X """ def servr_login(server_name, user_name, password): print( f""" {server_name =} {user_name =} {password =} """ ) servr_login("facebook.com", "udhay", "udhay123") servr_login("facebook.com", "udhay123", "udhay") servr_login( "udhay", "udhay123", "facebook.com", ) def servr_login(server_name, *, user_name, password): print( f""" {server_name =} {user_name =} {password =} """ ) servr_login("facebook.com", user_name="udhay", password="udhay123") # servr_login('facebook.com', 'udhay123', 'udhay') # TypeError: servr_login() takes 1 positional argument but 3 were given # ---------------------------- # Function Definition def recv(maxsize, *, block=True): print("\ntype(maxsize) ", type(maxsize)) print("type(block) ", type(block)) print("maxsize " + str(maxsize)) print("block " + str(block)) print("-" * 20) # Function Call recv(1234) recv(maxsize=1234, block=False) recv(1234, block=False) # recv(1234, False) # TypeError: recv() takes 1 positional argument but 2 were given """ Recommended order for the arguments def func(positional, keyword=value, *args, **kwargs): pass """ def f(a, b, /, c, d, *, e, f): print(a, b, c, d, e, f) f(10, 20, 30, d=40, e=50, f=60)
false
6782bce539f905db7c05238f1b906edf054b5aeb
udhayprakash/PythonMaterial
/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/f_custom_thread_class.py
939
4.375
4
#!/usr/bin/python # Python multithreading example to print current date. # 1. Define a subclass using Thread class. # 2. Instantiate the subclass and trigger the thread. import datetime import threading class myThread(threading.Thread): def __init__(self, name, counter): threading.Thread.__init__(self) self.threadID = counter self.name = name self.counter = counter def run(self): print("Starting " + self.name) print_date(self.name, self.counter) print("Exiting " + self.name) def print_date(threadName, counter): datefields = [] today = datetime.date.today() datefields.append(today) print("%s[%d]: %s" % (threadName, counter, datefields[0])) # Create new threads thread1 = myThread("Thread", 1) thread2 = myThread("Thread", 2) # Start new Threads thread1.start() thread2.start() thread1.join() thread2.join() print("Exiting the Program!!!")
true
0f39ba4fb7de201f9bf21ceac445f5246c785886
udhayprakash/PythonMaterial
/python3/04_Exceptions/13_custom_exceptions.py
1,183
4.15625
4
#!/usr/bin/python3 """ Purpose: Using Custom Exception """ # # Method 1 - stop when exception is raised # try: # votes = 0 # i = 0 # while i < 5: # age = int(input('Enter your age:')) # if age <= 0: # raise Exception('Invalid Entry for the age!') # elif age < 18: # raise Exception('You are Ineligible to vote!!') # else: # votes += 1 # i += 1 # except Exception as ex: # print(f'{ex=}') # # print(f"Total Eligible Voters: {votes}") # Method 2 - skip the loop with exception class InvalidInput(Exception): pass class InvalidAge(Exception): pass votes = 0 attempt = 0 while attempt < 5: print(f"\n{attempt =}") try: age = int(input("Enter your age:")) if age <= 0: raise InvalidInput("Invalid Entry for the age!") elif age < 18: # raise InvalidAge('You are Ineligible to vote!!') raise InvalidAge(f"You are short by {18 - age} years for voting") else: votes += 1 attempt += 1 except Exception as ex: print(f"{ex=}") else: print(f"Your voterID is {attempt}")
false
2e7734c27ca1713f780710c935c2981fa7bc0577
udhayprakash/PythonMaterial
/python3/09_Iterators_generators_coroutines/02_iterators/e_user_defined_iterators.py
926
4.65625
5
#!/usr/bin/python3 """ Purpose: Iterators - To get values from an iterator objects 1. Iterate over it - for loop - converting to other iterables - list(), tuple(), set(), dict() 2. To apply next() - will result in one element at a time """ a = ["foo", "bar", "baz"] itr = iter(a) for value in itr: print("value:", value) itr = iter(a) print("\n", itr) # <list_iterator object at 0x0000016CFEF10E20> print("\nitr.__next__()", itr.__next__()) print("next(itr) ", next(itr)) print("next(itr) ", next(itr)) try: print("next(itr) ", next(itr)) except StopIteration as ex: print(repr(ex)) print("\nReassigning") itr = iter(a) while True: try: print("next(itr) ", next(itr)) except StopIteration as ex: print(repr(ex)) break
true
37b606ca02ac4bfd4e53e038c0280ee660d3277c
udhayprakash/PythonMaterial
/python3/10_Modules/04a_os_module/display_tree_of_dirs.py
637
4.125
4
#!/usr/bin/python """ Purpose: To display the tree strcuture of directories only , till three levels test sub1 sub2 subsub1 """ import os import sys MAX_DEPTH = 3 # levels given_path = sys.exec_prefix # input('Enter the path:') print(given_path) def display_folders(_path, _depth): if _depth != MAX_DEPTH: _depth += 1 files_n_flders = os.listdir(_path) for each in files_n_flders: if os.path.isdir(os.path.join(_path, each)): print("+" + "--" * _depth, each) display_folders(os.path.join(_path, each), _depth) display_folders(given_path, 0)
true
f99296176c5701a5fe9cbc10d37767fa91ab06f4
udhayprakash/PythonMaterial
/python3/15_Regular_Expressions/d_re_search.py
965
4.59375
5
""" Purpose: Regular Expressions Using re.match - It helps to identify patterns at the starting of string Using re.search - It helps to identify patterns at the ANYWHERE of string """ import re target_string = "Python Programming is good for health" # search_string = "python" for search_string in ("python", "Python", "PYTHON", "PYThon"): reg_obj = re.compile(search_string, re.I) # re.IGNORECASE print(reg_obj, type(reg_obj)) # result = reg_obj.match(target_string) # .match can get only at the starting of string result = reg_obj.search(target_string) # .search - can get any where in the string, including starting print(f"{result =}") if result: print(f"result.group():{result.group()}") print(f"result.span() :{result.span()}") print(f"result.start():{result.start()}") print(f"result.end() :{result.end()}") else: print("NO match found") print()
true
a9bafcaa72533199973fad8a3ea5ba444dadf162
udhayprakash/PythonMaterial
/python3/14_Code_Quality/04_unit_tests/b_using_unittest_module/d_MultipleTestScripts_ex/mymod.py
240
4.15625
4
""" Purpose: anagram cat <--> act """ def is_anagram(a_word, b_word): """ >>> is_anagram('cat', 'act') True >>> is_anagram('tom', 'mat') is not True True """ return sorted(a_word) == sorted(b_word)
false
e12c213d1234b0229d1a6e9c51de5d809c4a3968
udhayprakash/PythonMaterial
/python3/02_Basics/01_Arithmetic_Operations/b_arithmetic_operations.py
1,265
4.3125
4
#!/usr/bin/python3 """ Purpose: Arithmetic Operations NOTE: PEP 8 recommends to place one space around the operator """ print("power operation **") print("4 ** 2 = ", 4**2) print("64 ** (1/2) = ", 64 ** (1 / 2)) # square root print("64 ** (1/2.0) = ", 64 ** (1 / 2.0)) # square root print("64 ** 0.5 = ", 64**0.5) # square root print() # Operator precedence - PEMDAS print("64 ** 1/2 = ", 64**1 / 2) # 32 print("(64 ** 1)/2 = ", (64**1) / 2) # 32 print("64 ** (1/2) = ", 64 ** (1 / 2)) # 8.0 print() print("pow(4,2) =", pow(4, 2)) print("pow(64,1/2) =", pow(64, 1 / 2)) print("pow(64,1/2.0) =", pow(64, 1 / 2.0)) print("pow(64,0.5) =", pow(64, 0.5)) print() print("pow(4,2,9) =", pow(4, 2, 9)) # (4 ** 2) % 9 print("(4**2) % 9 =", (4**2) % 9) print() # == value level equivalence check - check LHS & RHS print("pow(4, 2, 9) == (4 ** 2) % 9:", pow(4, 2, 9) == (4**2) % 9) print(pow(0, 0) == 0**0 == 1) print() print("Exponent Notation/Representation") print("1e1 = ", 1e1) print("1 * 10.0 ** 1 = ", 1 * 10.0**1) print("3e2 =", 3e2) # 3 * 10.0 ** 2 print("-2.3e4 = ", -2.3e4) # -2.3 * 10.0 ** 4 print("velocity of light", 3e8) # 3 * 10.0 ** 8
false
da46171c56e002b5bc69e5d5fc2264fe80d0e5a4
udhayprakash/PythonMaterial
/python3/14_Code_Quality/01_static_typing/f_iterator.py
375
4.125
4
""" Purpose: Static typing """ from typing import Iterator # Using Dynamic typing def fib(n): a, b = 0, 1 while a < n: yield a a, b = b, a + b # Static typing def fib1(n: int) -> Iterator[int]: a, b = 0, 1 while a < n: yield a a, b = b, a + b if __name__ == "__main__": print(list(fib(10))) print(list(fib1(10)))
false
a09bab1878819e6069d4afe189fcf43f63593695
udhayprakash/PythonMaterial
/python3/14_Code_Quality/01_static_typing/g_example.py
1,046
4.3125
4
""" Purpose: Static typing """ from typing import Dict, List, Tuple # Traditional Approach my_data = ("Adam", 10, 5.7) print(f"{my_data =}") # Adding Typing my_data2: Tuple[str, int, float] = ("Adam", 10, 5.7) print(f"{my_data2 =}") # -------------------------------- # A list of integers # Traditional Approach numbers = [1, 2, 3, 4, 5, 6] print(f"numbers:{numbers}") # Adding Typing numbers2: List[int] = [1, 2, 3, 4, 5, 6] print(f"numbers2:{numbers2}") # ------------------------------------- # List of Tuples - Alias LatLngVector = List[Tuple[float, float]] points: LatLngVector = [ (25.91375, -60.15503), (-11.01983, -166.48477), (-11.01983, -166.48477), ] print(f"points:{points}") # -------------------------------------- # A dictionary where the keys are strings and the values are ints name_counts: Dict[str, int] = {"Adam": 10, "Guido": 12} # -------------------------------------- # A list that holds dicts that each hold a string key / int value list_of_dicts: List[Dict[str, int]] = [{"key1": 1}, {"key2": 2}]
false
66c6cf5dc25e81f8e1adad58ac56c932f0d4a41e
udhayprakash/PythonMaterial
/python3/04_Exceptions/06_handling_multiple_exceptions.py
761
4.1875
4
#!/usr/bin/python3 """ Purpose: Exception Handling Exception Hierarchy """ # try: # num1 = int(input("Enter an integer:")) # num2 = int(input("Enter an integer:")) # division = num1 / num2 # except Exception as ex: # print(f"{ex =}") # print("Please enter integers only (or) denominator is 0") # else: # print(f"{division = }") try: num1 = int(input("Enter an integer:")) num2 = int(input("Enter an integer:")) division = num1 / num2 except ValueError as ve: print(f"{ve =}") print("Please enter integers only") except ZeroDivisionError as ze: print(f"{ze =}") print("Denominator should be NON-zero") except Exception as ex: print(f"Unhandled Exception: {ex =}") else: print(f"{division = }")
false
5399535d50a3bc576a80fd1cd911b70a8891d6c6
udhayprakash/PythonMaterial
/python3/10_Modules/03_argparse/b_calculator.py
1,183
4.5
4
#!/usr/bin/python """ Purpose: command-line calculator """ import argparse def addition(n1, n2): return n1 + n2 def subtraction(s1, s2): return s1 - s2 def multiplication(m1, m2, m3): return m1 * m2 * m3 # Step 1: created parser object parser = argparse.ArgumentParser(description="Script to add two/three numbers") # Step 2: add arguments to parser object parser.add_argument("-num1", help="First value", type=int, default=0) parser.add_argument("-num2", help="Second Value", type=int, default=0) parser.add_argument("-num3", help="optonal value", type=float, default=0.0) # Step 3: Built parser objects and extract values args = parser.parse_args() num1 = args.num1 num2 = args.num2 print(f" {type(num1) =} {num1 = }") print(f" {type(num2) =} {num2 = }") print(f" {type(args.num3) =} {args.num3 = }") print() # Default Values are None for the args print(f"{addition(num1, num2) =}") print(f"{subtraction(num1, num2) =}") print(f"{multiplication(num1, num2,args.num3) =}") # python b_calculator.py # python b_calculator.py -num1 10 # python b_calculator.py -num1 10 -num2 20 # python b_calculator.py -num1 10 -num2 20 -num3 30
true
d85262260f5fcfc72b9d23bb046cc460d51bc8e3
udhayprakash/PythonMaterial
/python3/14_Code_Quality/01_static_typing/k_Union_type.py
610
4.21875
4
""" Purpose: Union type """ from typing import Union def is_even_whole(num) -> Union[bool, str]: if num < 0: return "Not a whole number" return True if num % 2 == 0 else False assert is_even_whole(10) is True assert is_even_whole(19) is False assert is_even_whole(-2) == "Not a whole number" def is_even_whole2(num) -> Union[bool, Exception]: if num < 0: return Exception("Not a whole number") return True if num % 2 == 0 else False assert is_even_whole2(10) is True assert is_even_whole2(19) is False res = is_even_whole2(-2) assert res.args[0] == "Not a whole number"
false
ef14eb6c7361331b6c3ba966a7a128a48d7b0b45
udhayprakash/PythonMaterial
/python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/c_locks/b1a_class_based_solution.py
760
4.21875
4
""" Purpose: Class based implementation of synchronization using locks """ from threading import Lock, Thread from time import sleep class Counter: def __init__(self): self.value = 0 self.lock = Lock() def increase(self, by): self.lock.acquire() current_value = self.value current_value += by sleep(0.1) self.value = current_value print(f"counter={self.value}") self.lock.release() counter = Counter() # create threads t1 = Thread(target=counter.increase, args=(10,)) t2 = Thread(target=counter.increase, args=(20,)) # start the threads t1.start() t2.start() # wait for the threads to complete t1.join() t2.join() print(f"The final counter is {counter.value}")
true