blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
360bfe21b479da8cef2a3363242e0d926ed41c09
fercibin/Python
/Funcao_Sorted.py
1,069
4.625
5
# -*- coding: utf-8 -*- """ SORTED() -------- - sorted() pode ser utilizado com qualquer iterável, serve para ordenar. - SEMPRE retorna como resultado uma LISTA com os elementos ordenados, não altera a coleção original - sort() só funciona em lista. Altera a lista original """ numeros = [9, 1, 7, 3, 12] print(numeros) print(sorted(numeros)) # Adicionando parâmetros ao sorted() print(sorted(numeros, reverse=True)) # Ordena do maior para o menor # Podemos utilizar sorted() para coisas mais complexas usuarios = [ {'username': 'Samuel', 'tweets': ['Eu adoro bolos', 'Eu adoro pizza']}, {'username': 'Carla', 'tweets': ['Eu amo meu gato']}, {'username': 'jeff', 'tweets': []}, {'username': 'bob123', 'tweets': []}, {'username': 'Doggo', 'tweets': ['Eu gosto de cachorro', 'Vou pra zona hoje']}, {'username': 'gal', 'tweets': []} ] print(usuarios) # Ordenando por username print(sorted(usuarios, key=lambda usr: usr['username'])) # Ordenando pela quantidade de tweets print(sorted(usuarios, key=lambda usr: len(usr['tweets'])))
false
8c6671912024336f95d0f7ac9aaa4c45f856c9b6
ofirn21-meet/meet2019y1lab3
/lab_3-greeting.py
267
4.1875
4
name=(input("what is your name?")) name=(name.capitalize()) print("your name is "+str(len(name))+" letters long") print("the first letter of your name is "+(name[0].upper())+" and the last letter is "+name[-1].upper()) print(name[1:-1]) print("hello there,"+name)
true
8930376c21b5558e580b870276b6fc50282797e6
hyoputer/adder
/adder.py
310
4.125
4
while True: a = int(input("1st number: ")) b = int(input("2nd number: ")) if a == 0 & b == 0: break; print("a + b = ") print(a+b) print("a - b = ") print(a-b) print("a * b = ") print(a*b) if b != 0: print("a / b = ") print(a/b) print("a % b = ") print(a%b) print("a ** b = ") print(a**b)
false
f7b48f5f9dd62b25d36a7dd736da78d68c92ce2d
danilo-souza/PPA2
/SplitTheTip.py
1,352
4.34375
4
def check_3decimal(number): #checking if the input has more than 3 decimal places. #if the input only has 2 decimal places then round(number, 3) = round(number, 2) if not (round(number, 3) == round(number, 2)): #taking off the extra decimal digits number = (round(number - 0.005, 2)) number = round(number + 0.01, 2) return number def split_the_tip(amount, n): #adding the tip, rounding to the second decimal place try: amount = float(amount) if amount < 0: return "Invalid dinner amount inputted. A negative number was passed" except (TypeError, ValueError): return "Invalid dinner amount inputted. A value other than a number was passed" try: n = int(n) if n < 0: return "Invalid number of guests inputted. A negative number was passed" except (TypeError, ValueError): return "Invalid number of guests inputted. A value other than a number was passed" total_amount = round(amount * 1.15, 2) output = '' for i in range(0, n): #using rounding to make sure that the remaining number only goes up to 2 decimal places temp = round(check_3decimal(total_amount/(n-i)), 2) output = output + "guest" + str(i + 1) + " - " + str(temp) + " " total_amount-=temp return output
true
ca458b86f2e635c9c456006d705626717581f5ad
noeljt/ComputerScience1
/hws/hw3/hw3_part2.py
1,969
4.21875
4
""" Determines whether there are enough legos or substitutes. Author: Joe Noel (noelj) """ def lego_count(legos): size = raw_input("What type of lego do you need? ==> ") print size amount = int(raw_input("How many pieces of this lego do you need? ==> ")) print amount if size == '1x1': if amount <= legos.count('1x1'): print "I have %d peices of 1x1 for this" %(legos.count('1x1')) else: print "I don't have enough pieces of this lego" elif size == '2x1': if amount <= legos.count('2x1'): print "I have %d pieces of 2x1 for this" %(legos.count('2x1')) elif amount <= (legos.count('1x1')/2): print "I have %d pieces of 1x1 for this" %(legos.count('1x1')) else: print "I don't have enough pieces of this lego" elif size == '2x2': if amount <= legos.count('2x2'): print "I have %d pieces of 2x2 for this" %(legos.count('2x2')) elif amount <= (legos.count('2x1')/2): print "I have %d pieces of 2x1 for this" %((amount*2)) elif amount <= (legos.count('1x1')/4): print "I have %d pieces of 1x1 for this" %((amount*4)) else: print "I don't have enough pieces of this lego" elif size == '2x4': if amount <= legos.count('2x4'): print "I have %d peices of 2x4 for this" %(legos.count('2x4')) elif amount <= (legos.count('2x2')/2): print "I have %d pieces of 2x2 for this" %((amount*2)) elif amount <= (legos.count('2x1')/4): print "I have %d pieces of 2x1 for this" %((amount*4)) elif amount <= (legos.count('1x1')/8): print "I have %d pieces of 1x1 for this" %((amount*8)) else: print "I don't have enough pieces of this lego" import hw3_util legos = hw3_util.read_legos('legos.txt') lego_count(legos)
true
2fd705b7228976f6d3f0da04c34d03abaf0ee832
noeljt/ComputerScience1
/hws/hw3/hw3_part1.py
2,138
4.34375
4
""" Program to compare any two FIFA teams. Author: Joe Noel (noelj) """ import hw3_util teams = hw3_util.read_fifa() #[group id, country, games, win, draw, lose, goals scored, goals against] def select_teams(): t1 = int(raw_input("First team index (0-31) ==> ")) print t1 t2 = int(raw_input("Second team index (0-31) ==> ")) print t2 return (t1,t2) def compare_teams( (t1,t2) ): team1 = teams[t1] team2 = teams[t2] Pts1 = 3 * team1[3] + team1[4] Pts2 = 3 * team2[3] + team2[4] Gdiff1 = team1[-2] - team1[-1] Gdiff2 = team2[-2] - team2[-1] GF1 = team1[-2] GF2 = team2[-2] if Pts1 > Pts2: print team1[1] + " is better than " + team2[1] elif Pts2 > Pts1: print team2[1] + " is better than " + team1[1] elif Pts1 == Pts2: if Gdiff1 > Gdiff2: print team1[1] + " is better than " + team2[1] elif Gdiff2 > Gdiff1: print team2[1] + " is better than " + team1[1] elif Gdiff1 == Gdiff2: if GF1 > GF2: print team1[1] + " is better than " + team2[1] elif GF2 > GF1: print team2[1] + " is better than " + team1[1] elif GF1 == GF2: print team2[1] + " same as " + team1[1] def teams_info( (t1,t2) ): team1 = teams[t1] team2 = teams[t2] Gdiff1 = team1[-2] - team1[-1] Gdiff2 = team2[-2] - team2[-1] Pts1 = 3 * team1[3] + team1[4] Pts2 = 3 * team2[3] + team2[4] print "\nGroup " + "Team" + (" "*16) + "Win Draw Lose GF GA Gdiff Pts " print str(team1[0]).ljust(6) + team1[1].ljust(20) + str(team1[3]).ljust(6) + str(team1[4]).ljust(6) + str(team1[5]).ljust(6) + str(team1[-2]).ljust(6) + str(team1[-1]).ljust(6) + str(Gdiff1).ljust(6) + str(Pts1).ljust(6) print str(team2[0]).ljust(6) + team2[1].ljust(20) + str(team2[3]).ljust(6) + str(team2[4]).ljust(6) + str(team2[5]).ljust(6) + str(team2[-2]).ljust(6) + str(team2[-1]).ljust(6) + str(Gdiff2).ljust(6) + str(Pts2).ljust(6) compare_teams( (t1,t2) ) teams_info(select_teams())
false
c966e80891eac9cc7e81a436d1c5c099ee753bce
noeljt/ComputerScience1
/hws/hw2/hw2part3.py
1,352
4.5
4
""" A program to calculate area and print the coinciding rectangle made of asteriks. Author: Joe Noel (noelj) """ height = int(raw_input("Height==> ")) print height width = int(raw_input("Width==> ")) print width area = height * width def burger(height, width): bun = "*" * width meat = "*" + (" " * (width-2)) + "*" side = (meat + "\n") * (height - 2) burger = bun + "\n" + side + bun print burger def labeled_burger(height, width): bun = "*" * width label1 = "h: %d, w: %d" %(height, width) label2 = "area: " + str(area) meat = "*" + (" " * (width-2)) + "*" side = (meat + "\n") * (height - 2) if (len(label1) + 2) > width: burger(height, width) print "h: %d, w: %d" %(height, width) print "area: " + str(area) elif (len(label1) + 2) <= width: top_meat = (meat + "\n") * (height/2 - 2) ketchup = "*" + (" " * ((width - 2 - len(label1))/2)) + label1 + (" " * ((width - 2 - len(label1))/2)) + "*\n" mustard = "*" + (" " * ((width - 2 - len(label1))/2)) + label2 + (" " * ((width - 2)-((width - 2 - len(label1))/2)-len(label2))) + "*\n" bottom_meat = top_meat labeled_burger = bun + "\n" + top_meat + ketchup + mustard + bottom_meat + bun print labeled_burger labeled_burger(height, width)
true
6902d83a4ffde4a77f1abe9dffbb7d8f5b0c3cf2
LiChangNY/fun_projects
/pandigital_prime.py
2,557
4.15625
4
""" A shortcut to solve this problem is to limit the search results. If you run process(9) below, the kernel will for sure die because there are too many combinations to check, let alone iterating from process(1) to process(9). Hence, we can test if the sum of the digits is divisible by 3. If it is, no matter how you arrange the digits, the number won't be a prime number. You may ask why not checking 6,7....? I guess you can. But it's not worth it because by testing 3, it already narrows down to 1-digit(Forget it. Nick already told us that 2143 is a prime pandigital and it's bigger than 1.), 4-digit(promising) and 7-digit(Oooh). """ ########################################################################## ############uncommment codes below to see sum of n-digit number########### #for n in range(1, 10): # combo = [i for i in range(1,n+1)] # if sum(combo) % 3 == 0: # continue # else: # print("%i-digit number can't be evenly divisible by 3" % n) ########################################################################## import time #check if a number is pandigital def pandigital_check(num, n): num_combo = [i for i in map(int, str(num))] #The first criteria ensures numbers composed of 1-n digit, #thus eliminating numbers like 7652319 #The second criteria checks if every digit appears once, #thus eliminating numbers like 7654333 if max(num_combo) == n and len(set(num_combo)) == n: return True else: return False ##check if number is divisible by any odd number def partial_prime_check(num): for i in range(3, num, 2 ): if (num%i) == 0: return False break return True def process(n): #define the largest number to start with, e.g. 7654321 num = int(''.join(map(str, [-i for i in range(-n, 0)]))) #keep trying a smaller number if any of tests fails while n > 0 and \ (pandigital_check(num, n) == False or partial_prime_check(num) == False): num -=2 #decrease by 2 to keep trying odd numbers return num start_time = time.time() #If process(7) finds a number, no need to check prcess(4). #If not, we know at least 2143 is a prime pandigital number, #thanks to Nick. seven_digit = process(7) if seven_digit > 0: print "The largest n-pandigital number is ", seven_digit else: print "The largest n-pandigital number is ", process(4) print "processing time: ", (time.time() - start_time)," seconds"
true
61f1067aaebb09ef406c6cf7482359eabc15bdd7
cupofjoey/UdemyPython1
/numInput.py
788
4.15625
4
#lets do a small program to see if a person can guess the magic number. They have 3 chances. magic_numbers = [3, 9] chances = 3 for i in range(chances): print("This is attempt {}".format(i)) user_number = int(input("Enter a number between 1 and 10: ")) if user_number in magic_numbers: print("You guessed the magic number! Congratulations!!!") #I was trying to just use a simple 'else' statement here, and it worked at first, but after #mark 4 it kept giving me an error, so I went with the ugly 'not in' statement #I'm sure it works, I just don't like the way it looks. Giving me a minor 'No!' in the back of my head. if user_number not in magic_numbers: print("You didn't guess the magic number. That's a bummer. Try it again.")
true
46cf81159474f5a7f11d186e63d84cad13d9aa08
cupofjoey/UdemyPython1
/lowestInt.py
363
4.125
4
import random #Random number generator, 1-10. Each time it logs lowest number and prints it. minimum = 100 for index in range(10): random_number = random.randint(0, 100) print("The number generated is {}".format(random_number)) if random_number <= minimum: minimum = random_number print("The lowest number in that loop is: " + str(minimum))
true
5d07d7024b7a41d8cb8e8d774ca16cd2abcf04de
samruddhichitnis02/machine_learning
/week2/program2.py
230
4.34375
4
"""Write a Python program to reverse the order of the items in the array. """ x=[ ] n=int(input('Enter the number of elements-')) for i in range(n): a=input('Enter the elements-') x.append(a) print(x) x.reverse() print(x)
true
87cdb550cf481b5ab066f96f35b9093f798ac4c9
samruddhichitnis02/machine_learning
/week3/statistics/program6.py
407
4.25
4
"""Write a program to find transpose matrix of matrix Y in problem 1""" Y = [[5,8,1], [6,7,3], [4,5,9]] a11=Y[0][0] a12=Y[0][1] a13=Y[0][2] a21=Y[1][0] a22=Y[1][1] a23=Y[1][2] a31=Y[2][0] a32=Y[2][1] a33=Y[2][2] transpose=[[a11,a21,a31], [a12,a22,a32], [a13,a23,a33]] for i in range(len(Y)): for j in range(len(Y)): print(transpose[i][j],end=' ') print( )
false
a12eea58d985d04493860c3f05ce114692811a49
samruddhichitnis02/machine_learning
/week2/List/program2.py
320
4.125
4
"""Write a Python program to multiplies all the items in a list.""" x=[ ] n=int(input('Enter the number of elements-')) for i in range(n): a=int(input('Enter the elements-')) x.append(a) print(x) mul=1 for i in range(len(x)): mul=mul*x[i] print('The multiplication of all the elements of the list is-',mul)
true
08defb345ecc26c325e8303a1f0e79fc64af0078
nwthomas/Intro-Python-I
/src/13_file_io.py
998
4.21875
4
""" Python makes performing file I/O simple. Take a look at how to read and write to files here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files """ # Open up the "foo.txt" file (which already exists) for reading # Print all the contents of the file, then close the file # YOUR CODE HERE with open("foo.txt") as f: for line in f: print(line, end="") # Open up a file called "bar.txt" (which doesn't exist yet) for # writing. Write three lines of arbitrary content to that file, # then close the file. Open up "bar.txt" and inspect it to make # sure that it contains what you expect it to contain # YOUR CODE HERE with open("bar.txt", "w") as b: b.write("The ships hung in the sky in much the same way that bricks don't.\n") b.write("Don't Panic.\n") b.write("If there's anything more important than my ego around, I want it caught and shot now.\n") b.close() with open("bar.txt") as t: for line in t: print(line, end="")
true
b4f5e366402472de7b3fad0447546dd64777e7a9
sprungknoedl/python-workshop
/2010/src/workshop1.py
1,563
4.40625
4
#!/usr/bin/python # This file contains some example solutions to exercises given during the first # python workshop. spelling and grammar mistakes are my present to you ;) import os def find_mail(arg): """ searches a string for e-mail addresses. returns a list. """ # to append to a list, the list must exist res = [] # iterate over every word in arg, split without arguments split at every whitespace for word in str(arg).split(): # first solution: # if word.find('@') != -1: # better solution: if '@' in word: # append to end of list res.append(word) return res def read_file(filename): """ read file and return content as string """ # open file `filename` in read mode with open(filename, 'r') as f: # read whole file at once return f.read() def write_list(filename, list): """ write a list to a file new line seperated """ # open file `filename` in write mode with open(filename, 'w') as f: # join a list with newline (os dependent) and write # the string to the file f.write(os.linesep.join(list)) def read_list(filename): """ read in previosly written file as python list """ # open file `filename` in read mode with open(filename, 'r') as f: # read whole file and split by lines return f.read().splitlines() # dummy calls to functions mails = find_mail(read_file('file_with_emails')) write_list('foo', mails) new_list = read_list('foo')
true
e123f84ee35ccdc36f10be03f16326e8e3949ba6
ZakBrinlee/Python-CSC-110
/Adventure_Game_Start.py
1,536
4.21875
4
# North Seattle College, CSC 110 # Week 0 Programming Assignment # Author: Zak Brinlee # Email: zbrinlee@gmail.com # This program is the start of an adventure game using python # Currently taking in 4 character attributes and a starting day of the story # Using multiple variables in multiple places in the story # input section character_name = input("Please enter your character's name: ") character_planet = input("Which of the 8 planets in our solar system is your character from? ") character_nickname = input("Please enter your character's nickname: ") starting_day = input("Please enter a day of the week: ") character_career = input("What is your character's career? ") # output section print("\nWelcome to the great Python story teller! Where you create story elements as you go!") #using escape character \n to create new line from the prompt print("\nOur story starts on a " + starting_day + ", just like every other day.") #using escape character \n to create a space from the story intro for cleaner formatting print("Nothing out of the ordinary on the home planet of " + character_planet + ".") print("The unlikely hero of our story is the humble " + character_name + ".") print(character_name + " worked as a " + character_career + ".") print("A very skilled " + character_career + " that was liked by everyone, always friendly, polite and welcomed everywhere around " + character_planet + ".") print("Closest friends often called " + character_name + " by " + character_nickname + ".") print("An endearing nickname from childhood.")
true
58df8ee5223a342ab463cc0ac55c5f0bda9e951d
vivsnguyen/LeetCode-May-Challenge-2020
/cousins_in_a_binary_tree.py
2,046
4.125
4
""" In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1. Two nodes of a binary tree are cousins if they have the same depth, but have different parents. We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree. Return true if and only if the nodes corresponding to the values x and y are cousins. Example 1: 1 / \ 2 3 / 4 Input: root = [1,2,3,4], x = 4, y = 3 Output: false Example 2: 1 / \ 2 3 \ \ 4 5 Input: root = [1,2,3,null,4,null,5], x = 5, y = 4 Output: true Example 3: 1 / \ 2 3 / 4 Input: root = [1,2,3,null,4], x = 2, y = 3 Output: false Note: The number of nodes in the tree will be between 2 and 100. Each node has a unique integer value from 1 to 100. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isCousins(self, root: TreeNode, x: int, y: int) -> bool: def find_height(root, parent, value, height): if not root: return 0 elif root.val == value: return (height, parent) parent = root.val left = find_height(root.left, parent, value, height+1) if left: return left parent = root.val right = find_height(root.right, parent, value, height+1) if right: return right if root.val == x or root.val == y: return False x_height, x_parent = find_height(root, -1, x, 0) y_height, y_parent = find_height(root, -1, y, 0) if x_parent != y_parent and x_height == y_height: return True return False
true
b897ab2a5f27398836936ce96ad1edb6cf1aa852
learnmv/HackerrankProblems
/string_manipulation/alternating_characters.py
541
4.1875
4
# title : ALternating Charecters #given a string containing characters A nad B only # we have to change it into a string such that there # are no matching adjacent characters. we are allowed # to delete zero or more characters in the string. def alternating(a): previous = a[0] delete = 0 for i in a[1:]: if previous == i: delete += 1 previous = i print(f'Answer is : {delete}') if __name__ == '__main__': t = int(input()) for _ in range(t): a = input() alternating(a)
true
e6efe1d716c6ef79c89bb9b0f52bb9329c63d2cc
ruqaiyasattar/androidproject2017
/exersice_3.10.py
868
4.25
4
#3.10 print("\n Exercise 3.10") river=['indus','jhelum','chenab','sutlej','kabul'] print("\n"+str(river)) print("Length od list "+str(len(river))+"\n") river.reverse() print("value in reverse order:\n"+str(river)) river.reverse() print("\nhere is the original list \n"+str(river)) print("Here is the sorted list \n"+str(sorted(river))) river.reverse() river.sort() print("sorting by sort() function\n"+str(river)) vanish='kabul' river.remove(vanish) print("remove() function \n"+str(river)) print("'"+vanish+"'"+" item in list is removed by using remove()\n") rivers=river.pop() print(rivers+" is removed from list by pop() function\n") del river[0] print("item at zero index is deleted by using del function \n"+str(river)+"\n") river.insert(0,'new item') print("new item at zero index is added by using insert()\n"+str(river))
true
b4c4ec6a7449c71dbb0908a5a17a1a0264764491
ruqaiyasattar/androidproject2017
/example_3.4.py
2,361
4.4375
4
#example 3.4 print("Guest invitation example\n") invitation=['daniel','john','michele'] print("whole list is :"+str(invitation)) print("I would like to invite you Mr "+invitation[0]+" for dinner"+"\n"+"I would like to invite you Mr "+invitation[1]+" for dinner"+"\n"+"I would like to invite you Mr "+invitation[2]+" for dinner") print("Mr "+invitation[0]+" has busy schedule so he can't attend tonights' dinner invitation\n") print("So i have modified invitation list") invitation.insert(0,'david') print(invitation) print("I would like to invite you Mr "+invitation[0]+" for dinner"+"\n"+"I would like to invite you Mr "+invitation[1]+" for dinner"+"\n"+"I would like to invite you Mr "+invitation[2]+" for dinner"+"\nI would like to invite you Mr "+invitation[-1]+" for dinner") print("\nAttention!".upper()+" Everyone "+"i have found bigger table for dinner".upper()+"\n") invitation.insert(0,'charlie') invitation.insert(int(len(invitation)/2),'ayaan') invitation.append('hafeez') print("I would like to invite you Mr "+invitation[0]+" for dinner"+"\n"+"I would like to invite you Mr "+invitation[1]+" for dinner"+"\n"+"I would like to invite you Mr "+invitation[2]+" for dinner"+"\nI would like to invite you Mr "+invitation[3]+" for dinner"+"\nI would like to invite you Mr "+invitation[4]+" for dinner"+"\nI would like to invite you Mr "+invitation[5]+" for dinner"+"\nI would like to invite you Mr "+invitation[-1]+" for dinner") print("\nattention all".upper()+" i can only invite two guest to dinner\n") last=invitation.pop(-1) print("sorry ".title()+"mr ".title()+last+" I can't invite you in tonights' dinner") sec_last=invitation.pop(-1) print("sorry ".title()+"mr ".title()+sec_last+" I can't invite you in tonights' dinner") third_last=invitation.pop(-1) print("sorry ".title()+"mr ".title()+third_last+" I can't invite you in tonights' dinner") four_last=invitation.pop(-1) print("sorry ".title()+"mr ".title()+four_last+" I can't invite you in tonights' dinner") fifth_last=invitation.pop(-1) print("sorry ".title()+"mr ".title()+fifth_last+" I can't invite you in tonights' dinner") #3.5 example print("\nExample 3.5\n") print("i have invited ".title()+str(len(invitation))+" guests") del invitation[-1] del invitation[-1] print("\nhere is the empty list \n".upper()+str(invitation))
true
79ac0ebfbd72fd24a79b85f060163294c29276b7
moranpatrick/python-fundamentals
/02-date_time.py
767
4.40625
4
# Problem 2 - Write a program that prints the current time and date to the console. # This program displays the current date and time on the console screen. # Author - Patrick Moran g00179039 import datetime # import required for data nad time # Variable to store the current date and time curr_date_and_time = datetime.datetime.now() # Display The full Timestamp to the Console print("The Current Date And Time Stamp is %s" % curr_date_and_time) # Display the date print("Todays Date is: %s" % curr_date_and_time.strftime("%Y-%m-%d")) # Display the current Time in Hours And Minutes print("The Current Time is: %d:%d" % (curr_date_and_time.hour, curr_date_and_time.minute)) # References # https://www.saltycrane.com/blog/2008/06/how-to-get-current-date-and-time-in/
true
3dfda1ed02c4cfa89fa63a8471f7a551f3925a1a
pydjangoboy/python-for-kids
/SampleCode/09ConditionIfElse.py
395
4.15625
4
# ============================================================ # Sample : Day 9 - Condition If..Else.. # By : Wriju Ghosh # Created On : 19-Sept-2020 # Last Updated : # Git Repo : https://github.com/wrijugh/python-for-kids # ============================================================ i = 9 j = 9 if (i == j): print("equal") else: print('not Equal')
false
cd22aebdb1a0c47fe47106eeb0129e3cfe02d565
pydjangoboy/python-for-kids
/SampleCode/11ForLoop.py
1,303
4.40625
4
# ============================================================ # Sample : Day 11 - For Loop # By : Wriju Ghosh # Created On : 18-Sept-2020 # Last Updated : # Git Repo : https://github/wrijugh/python-for-kids # ============================================================ # Multiplication Table num = 5 print (1 * num) print (2 * num) print (3 * num) print (4 * num) print (5 * num) print (6 * num) print (7 * num) # Multiplication Table in Intelligent way num = 5 allNums = {1,2,3,4,5,6,7,8,9,10} for i in allNums: print(i * num) num = 5 for i in range(1,11): print(i * num) # To print all the items in a Collection nums = {1,2,3,4,5,6,7,8,9} for i in nums: print(i) # in a string print all the letters myname = "Wriju Ghosh" for s in myname: print(s) # break a loop upon a condition nums1 = {1,2,3,4,5,6,7,8,9} for j in nums1: if(j == 5): break else: print(j) # using range # Start zero till 9. 10 is not included. for i in range(10): print(i) #Start 2 and till 9. 10 is not included for i in range(2,10): print(i) # Start from 2, till 20 and take +2 for next (Step=2 - the last parameter) for i in range(2, 21, 2): print(i) # Using else range in for for i in range(5): print(i) else: print("Done.")
false
01f060aad86a4ca1b555a4eff0c58eae920c702a
Lost-vox/Official-TC-RPS
/RPS Game Python.py
2,007
4.21875
4
import random human = 0 computer = 0 name = input("What is your name?") print("Hello",name) def Game(): global human global computer print("Computer score:", computer) print("Your score:", human) choice = input("Okay " + name + " Please choose Rock, Paper, or Scissors ") choice = choice.lower() while (choice != "rock" and choice != "paper" and choice != "scissors"): print(choice); choice = input("That choice is not valid. Enter your choice (rock/paper/scissors): "); choice = choice.lower() compGuess = random.randint(0,2) if (compGuess == 0): comp = "rock"; elif (compGuess == 1): comp = "paper"; elif (compGuess == 2): comp = "scissors"; else: comp = "Bad noises"; if (choice == comp): print("Its a draw"); elif (choice == "rock"): if (comp == "paper"): print("Computer wins!") computer += 1; else: print("You win!") human += 1; elif (choice == "paper"): if (comp == "rock"): print("You win!") human += 1; else: print("Computer wins!") computer += 1 elif (choice == "scissors"): if (comp == "rock"): print("Computer wins!") computer += 1; else: print("You win!") human += 1; while human < 5 and computer < 5: Game() if human == 5 or computer == 5: end = input("Do you want to play again Yes or No").lower() if (end == "yes"): human = 0 computer = 0 Game() else: pass
true
9339c9a7790feec91de21f061dc4c1eeaefd9fd5
gopinathPersonal/general-python-scripts-
/oop.py
585
4.28125
4
# OOP class MyCar: is_automatic = True # this is class obj attribute and its not dynamic def __init__(self, name, age): # constructor method of class called when creating an object if (self.is_automatic): # we can also write Mycar.is_automatic self.x = name # when obj is created, obj will create the attribute 'x' assigned with name we used to create obj self.age = age def drive(self): print(f'{self.x} is driving') return 'Done' myobj = MyCar('Gopi', 40) print(myobj.x) print(myobj.is_automatic) myobj.drive() print(myobj.age) myobj.age = 44 print(myobj.age)
true
21569911949d77b7eafd0c21c0bd00d9866a27e1
naimadswdn/isapy9-Damian
/dzien_3/zad3.py
1,039
4.1875
4
# Number of level is linear function of # amount # i # # 0 1 # 1 3 # 2 5 # 3 7 # # y=ax+b # i=1/2#-1/2 # #=2i+1 def pyramid_draw(): """Script to draw a pyramid consist of #, with given height.""" from time import sleep from dzien_2.repeat_y_or_n import repeat_y_or_n from dzien_2.check_if_good import check_if_good print('Hello! This program is drawing a pyramid consist of #, with given height. ') sleep(1.5) height = None height = check_if_good(height, int, 'Please provide height of the pyramid: ') # while True: # height = input('Please provide height of the pyramid: ') # try: # height = int(height) # break # except: # print('Please provide integer number!') # continue width = 2 * height + 1 for i in range(height): a = 2 * i + 1 line = '#'*a print(line.center(width)) repeat_y_or_n(pyramid_draw) def main(): pyramid_draw() if __name__ == "__main__": main()
true
ed4864b5be3182f5cbfe09e31c2c564a2ce72e12
kamesh051/django_tutorial-master
/python/control/loop.py
1,154
4.28125
4
import random import math print "Welcome to Sam's Math Test" '''logic to print random numbers''' num1 = random.randint(1, 1000) num2 = random.randint(1, 1000) num3 = random.randint(1, 1000) list = [num1, num2, num3] maxNum = max(list) minNum = min(list) sqrtOne = math.sqrt(num1) correct= False while(correct == False): guess1= input("Which number is the highest? "+str(list) + ": ") if maxNum == guess1: print("Correct!") correct = True else: print("Incorrect, try again") correct = False while(correct == False): guess2= input("Which number is the lowest? " + str(list) +": ") if minNum == guess2: print("Correct!") correct = True else: print("Incorrect, try again") correct= False while(correct == False): guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ") if sqrtOne >= 2.0 and str(guess3) == "y": print("Correct!") correct = True elif sqrtOne < 2.0 and str(guess3) == "n": print("Correct!") correct = True else: print("Incorrect, try again") print("Thanks for playing!")
true
f9482b39fbe1972b87402e9666fcd8acd3e7eecd
darknesspaladin/alllllien
/python_work/人生阶段.py
276
4.3125
4
age=17 if age<2: print('he is a baby!') elif age>=2 and age<4: print('he is studing walk.') elif age>=4 and age<13: print('he is a adult') elif age>=13 and age<=20: print('he is a teenager') elif age>=20 and age<=65: print('he is a man') else: print('he is an oldman!!')
true
15d554d1ce4400d1adabfe3747e546848ccad13f
Mampson/Cp1404
/Prac_02/valueError.py
975
4.5
4
""" CP1404/CP5632 - Practical Answer the following questions: 1. When will a ValueError occur? 2. When will a ZeroDivisionError occur? 3. Could you change the code to avoid the possibility of a ZeroDivisionError? """ try: numerator = int(input("Enter the numerator: ")) denominator = int(input("Enter the denominator: ")) # denominator_checked = denominator # 3)This is to so the needs for ZeroDivisionError or just stating the rule in the early prompt to avoid confusion while denominator == 0: print("Cannot divide by zero!") denominator = int(input("Enter the denominator: ")) fraction = numerator / denominator except ValueError: print("Numerator and denominator must be valid numbers!") # except ZeroDivisionError: print("Finished.") # 1 when the entered values are not int type or number type # 2 when the denominatior == 0 # 3 Possibly by re prompting for denomionator if zero is entered before assigning and calculating
true
c3b08c65e9bbaf429fb954828e8be94685776514
Vikaslakkacs/Python-understanding
/inheritance.py
2,620
4.28125
4
''' Created on Oct 12, 2018 Inheritance: Meaning: Taking something from your ancestors or from your father's Inhertance Definition: You can inherit classes and their method into the class which you are creating and use their methods. when you create a method with the same name as that their in the inherited method then it will be overridden @author: LAVIKAS ''' ''''Lets take the old class and paste it.''' class SolarSystem(): '''A class object attribute is created just above the init and it is true for the whole class''' star_of_system='Sun' '''We create a constructor which will call everytime when you initiate the class''' def __init__(self,solarsystem_name,planets): '''Here you define attribute planet_count and assign the input parameter to the attribute.''' self.planet_count = 'There are '+ str(planets) +' planets in the solar system' self.name='The name of the solar system is '+solarsystem_name '''Method is not generic operation but a particular operation bounded it can manipulate and return objects''' def names(self,ss_name='Moon'): if ss_name.upper()=='SUN': planet_list=['Mer','Ven', 'Ear', 'Mar', 'Jup', 'Sat', 'Uran', 'Nep', 'Plu'] print('Mer,Ven, Ear, Mar, Jup, Sat, Uran, Nep, Plu are the list of planets for the solar system {}'.format(self.name)); '''If you want to add the class object attribute''' print(self.star_of_system) ''' You can write in the following manner also''' print(SolarSystem.star_of_system) '''You can assign the attribute values in the method and can call through Classname.attribute but not methodname.attribute.''' self.small_planet='Pluto' return planet_list ''' Now create the class of our own and inherit the class solarsystem''' class Universe(SolarSystem): '''While creating init method you have to call the Solarsystem Init method also to inherit''' def __init__(self): SolarSystem.__init__(self,'Sun system',9) print('Welcome to the Universe!!') def galaxy(self,galaxy_name): galaxy_name='This is a '+ galaxy_name + ' galaxy.' return galaxy_name '''Now we will call these class and let us see the result''' universe=Universe() '''Now you can call the object attribute of the solarsystem class''' print(universe.planet_count) print(universe.name) '''Now you can call the method associated to Solarsystem class''' universe.names('Sun') galaxy_name=universe.galaxy('Milky Way') print(galaxy_name)
true
6dbfbb33c4bad064f6af416e725bc07987ac808f
Vikaslakkacs/Python-understanding
/Special_methods.py
1,113
4.53125
5
''' Created on Oct 12, 2018 Special methods are methods which are used like normal functions for an objcet Eg: For a list we have Append method and that we cannot use it for the class method. Special methods are used as methods of the objects. @author: LAVIKAS ''' class Book(): def __init__(self,name): self.name=name def author(self,author): return 'Author name is '+ author def book_type(self): print('Type of the book is Hard cover.') '''To show the details of the book we use''' def __str__(self): return 'Name of the book is '+self.name def __del__(self): pass def __hello__(self): pass '''We will call the class and method''' mybook=Book('The beginning of Infinity!') print(mybook.name) print(mybook.author('David Deutsch')) '''But the problem comes here what happens when you print the class itself''' print(mybook)#This will show the location but not the details of it unless you have a __str__ calss #del mybook#This will delete book class object mybook.__hello__() print(mybook.name)
true
74de0da708c7eb792dea15afb23713d9d71af520
khang-le/assignment-7
/ass7.py
815
4.3125
4
#!/usr/bin/env python3 # Created by: Khang Le # Created on: Dec 2019 # This program uses lists and rotation def rotation(list_of_number, ratating_time): numbers = list_of_number[0] numbers = [list_of_number[(i + ratating_time) % len(list_of_number)] for i, x in enumerate(list_of_number)] return numbers def main(): lst = [] # number of elemetns as input user_input = int(input("Enter number of elements : ")) rotating_time = int(input("Enter how many times you want to rotate: ")) print("The numbers are:") for i in range(0, user_input): ele = int(input()) lst.append(ele) # adding the element numbers = rotation(lst, rotating_time) print("Rotated by {0}: {1}".format(rotating_time, numbers)) if __name__ == "__main__": main()
true
ec62b4a1441ac0362b044bb054c689118510f655
gracesin/hearmecode
/demos/lesson3_scrabblescore.py
595
4.15625
4
score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, "x": 8, "z": 10} word=raw_input("Enter the word you'd like to score:\n") word=word.lower() word_score = 0 letter_score = 0 for w in word: #print "getting a score for {0}".format(w) letter_score = score[w] #print letterscore word_score = word_score + letter_score print "The score for {0} is {1}".format(word,word_score)
false
32d66c76145b6482fae5f1a56701cccb496c1104
CodeTemplar99/learnPython
/Functions/default_and _optional_arguments.py
862
4.625
5
# functions have default parameters # this means that when ever a function is called it must have it's argument equal to the # number of parameters # example of default argument def increment(number, by): return number + by # when this is called the number of arguments must be equal to the number of parameters print(increment(2, by=3)) # this will print 5 # to set optional argument, we simply define the parameter with a value # example def increment1(number, by=3): return number + by print(increment1(2)) # this will print 5 # NOTE: the required argument is a parameter that is not defined with value # NOTE: optional argument is a parameter that is defined with value when defining the function # NOTE: the optional argument in this case 3 should not come before any required argument(s) # NOTE: the optional argument always comes last
true
0be04f727842960ca7c0adf46c7dbc02bfbf3c66
CodeTemplar99/learnPython
/Fundamentals_of_programming/infinite_loop.py
713
4.25
4
# an infinite loop is an endless loop that will continue # infinite loops useful when they are managed well but they can cause major memory consumption if not properly managed # example of a command review built on infinite loop while True: command = input("Enter a command: ") print(">>>" + " " + command) if command.lower() == "quit": break print("hello, the app stopped because you called quits") # in the above program the while will always evaluate to true thereby making the program to be able to run as long as possible. # this can be check when a command equals quit thereby invoking the break statement on the loop # this in turn does not affect the truthiness of the while loop
true
7bb0040c38361ab5d9ffc69e11478a49db594b87
CodeTemplar99/learnPython
/Functions/keyword_arguments.py
1,023
4.25
4
# an argument is a value passed when calling a function def increment(number, by): return number+by value = increment(2, 1) print(value) # the above code will return 3 # to simplify this it can be written as def increment2(number, by): return number + by # value2 = increment2(2, 2) print(increment2(2, 2)) # the above code prints 4 # now because the use of "value2" will be infinitesimal or negligible because it's used once # it can be replaced by calling the increment with arguments inside the print function # but this will made the code less understandable. # this means as the parameters and arguments increase we may loose track of what what is # to check for this we use keyword arguments # KEYWORD ARGUMENTS # this is by definition as the name implies: it is passing a key word to an argument # this makes the code almost like simple english and increases readability and maintenace def increment3(number, by): return number + by print(increment3(2, by=3)) # the above code prints 5
true
8019e7fedd6f7f9ef0028aba4c714dabbda81129
CodeTemplar99/learnPython
/Data_structures/generator.py
1,306
4.5
4
from sys import getsizeof values = (x * 2 for x in range(5000)) # 64 bytes print("gen:", getsizeof(values)) values = (x * 2 for x in range(500000)) # 64 bytes still print("gen:", getsizeof(values)) values = [x * 2 for x in range(500)] # 2,140 bytes in memory print("list:", getsizeof(values)) # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * # when we create a list using a list comprehension expression like the code below we # will get a list of all the items in the values values = [x * 2 for x in range(5)] for x in values: print(values) # the above code stores the values in memory # when you are working with a large number of values or an infinite number of values # it will be wrong to store all the values in memory because that an inefficient memory management # in this case we use generators values = (x * 2 for x in range(5)) for x in values: print(x) # in the above code, values is no longer a list it is a generator object # at each iteration it "generates" new values # proof print(values) # generator objects are memory efficient because of their sizes in memory # example on line 1 # a backdrop for generators is that you can not get the length, doing this will throw an error because you don't know how many items will be generated
true
0c8df849c660e282cc8c1a19dee176766b10dd7f
CodeTemplar99/learnPython
/Fundamentals_of_programming/loop.py
1,077
4.53125
5
# loops are used to perform an action repeatedly # printing a message thrice for number in range(3): print("attempt") print("\n") # printing a message thrice and addingthe count for number in range(3): print("attempt", number) print("\n") # printing a message thrice and adding a number to the count for number in range(3): print("attempt", number + 1) # printing a message thrice and adding a number to the count and increasing a dot ny the count number for number in range(3): print("attempt", number + 1, (number + 1) * ".") print("\n") # printing a message thrice and adding a number to the count and increasing a dot ny the count number # manipulating the range method for number in range(0, 4): print("attempt", number + 1, (number + 1) * ".") print("\n") # printing a message thrice and adding a number to the count and increasing a dot ny the count number # manipulating the range method: starting from behind 0, stopping before 9 and jumping 3 numbers for number in range(1, 9, 2): print("attempt", number, number * ".") print("\n")
true
dd819e983cb7b66582c5a4026d9b5db1ac462d87
Dysonnnn/python_code
/201901-yueqian-python/day2pythonlearn2.py
513
4.21875
4
a = 3 b =5 #交换数据: ##方法一: temp = 0 temp = b b = a a = temp print(a,b) ##方法二: a,b = b,a print(a,b) print("/------------------------------/") zhangsan = {"name" : "zhangsan","age" : 20} print(zhangsan.get("age")) #获取字典的值 #集合、字典遍历 for key,value in zhangsan.items(): print(key,value) print("/------------------------------/") list1 = [2,3,"true","hello"] print(len(list1)) # 列表遍历方式 for i in list1: print(i)
false
6e0be4d4001ed398176a92718ccac61411e7a4bd
annebell881/ENGR-102
/Lab3a_Act1_f.py
884
4.28125
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 4 08:08:17 2020 @author: Anne """ # By submitting this assignment, I agree to the following: # "Aggies do not lie, cheat, or steal, or tolerate those who do." # "I have not given or received any unauthorized aid on this assignment." # # Name: Annemarie Bell # Section: 405 # Assignment: Lab 3 - 1f # Date: 09 04 2020 # #This line of code tells the user what the program does print("This program converts the number of degrees Fahrnheit into degrees celsius") #This line of code takes user input fahrenheit = float(input("Enter degrees Farenheit here:")) #This line of code calculates degrees in celsius celsius = 5/9 *(fahrenheit - 32) #This line of code prints out the output print(('%.2f' % fahrenheit), "degrees in farenheit is equal to ", ('%.2f' % celsius), " degrees celsius.")
true
b2878ba11f69b77d2a0e8fb4c80808a6c8cf18c7
poturnak/Python_practice
/0_Basics/4_Strings_custom_formatting.py
1,286
4.75
5
#! /library/Frameworks/Python.framework/Versions/3.5/python3.5 # =================================================================================================== # +++++++++ String format +++++++++ # in the old python notation we used % with some parameters to generate custom strings # new python way is to use string.format() method to generate custom strings name = 'Nikolay' string = 'Hello {}'.format(name) print(string) # the string output will be 'Hello Nikolay' # we can specify multiple arguments with several {} # they are names and they start with 0, 1, 2, etc. # arguments can be positional p0, p1, p2 etc. or named name=value # positional argument needs to be accessed by placing number in {}, {1} # keyword parameters are used by name=value pair print('Hey {1} how are you {0}?'.format('fucking', 'Nikolay')) print('Hey {name} how are you {action}?'.format(action='fucking', name='Nikolay')) print("Second argument: {1:3d}, first one: {0:7.1f}".format(47.42,11)) print("various precisions: {0:6.2f} or {0:6.3f}".format(1.4148)) print("Art: {a:5d}, Price: {p:8.2f}".format(a=453, p=59.058)) # it is possible to left or right justify the number within the alloted space print("{0:<20s} {1:6.1f}".format('Spam & Eggs:', 6.99)) # here the number is rounded to a whole
true
c2bfca2aa7bfedb2c3dd3b6ecff6a74622f8ce02
poturnak/Python_practice
/3_Machine_learning/1_Numpy/5_Broadcasting.py
773
4.15625
4
#! /library/Frameworks/Python.frameork/Versions/3.5/python3.5w # when we add/subtract the arrays of different shape, numpy needs to do the broadcasting # broadcasting is when you bring arrays to the same dimensions import numpy as np arr = np.tile(np.arange(0, 40, 10), (3, 1)) arr = arr.transpose() print(arr) # arr1 = np.array([0, 1, 2]) # print(arr1) # # print(arr + arr1) # # another form of broadcasting # a = np.arange(0, 40, 10) # a = a[:, np.newaxis] # print(a) # # print(a + arr1) # let's work on the example mileposts = np.array([0, 198, 303, 736, 871, 1175, 1475, 1544, 1913, 2448]) distance = np.abs(mileposts - mileposts[:, np.newaxis]) print(distance) x, y = np.arange(5), np.arange(5)[:, np.newaxis] distance = np.sqrt(x ** 2 + y ** 2) print(distance)
true
69bd5e7ce93d2e960c18ffab9b835ddc42e36647
poturnak/Python_practice
/2_Modules/12_Time.py
758
4.34375
4
#! /library/Frameworks/Python.framework/Versions/3.5/python3.5 # =================================================================================================== # ______________________ Time module ______________________ # time.time() - get current time # - can be used to calculate how long the program is running # time.sleep(# of seconds) - will pause the program for a while # =================================================================================================== import time def calculate(length): product = 1 for i in range(1, length): product = product * i return product start_time = time.time() prod = calculate(10) end_time = time.time() print('Took {} to calculate'.format(end_time-start_time))
true
fb455f07ebb00df4a0eff0db3ecd281c60d3278f
poturnak/Python_practice
/3_Machine_learning/1_Numpy/10_choose_take.py
1,297
4.1875
4
#! /library/Frameworks/Python.framework/Versions/3.5/python3.5 # first you specify indices [n, n1, n2] # --number of indices need to be the same as the maximum length of the array # --all arrays are of the same length # --indices are as high as the number of arrays to choose from # choose takes 1st element from array n, 2nd from array n1, 3rd from array 3 etc. # n, n1, n2 needs to be max the number of arrays import numpy as np choices = np.array([[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]) indices = [2, 3, 0, 0] result = np.choose(indices, choices) print(result) # let's take a look at take example # you also pick up the elements, but you flatten the array first # then you pick up the element by the index indices1 = [2, 3, 0, 1, 6] result1 = np.take(choices, indices1) print(result1) # let solve the problem # Generate a 10 x 3 array of random numbers (in range [0,1]). For each row, pick the number closest to 0.5 print('-----------') np.random.seed(11) arr = np.random.rand(3, 2) print(arr) mask = np.argmin(abs(arr - 0.5), axis=1) print(mask) print(arr.T) result = np.choose(mask, arr.T) print('\nThe result is:') print(result) # for i in range(0, 3): # print(arr[i][mask[i]]) index = np.vstack((np.arange(3), mask)) print(arr[np.arange(3), mask])
true
51dfe63a067297775c0e4cb8124b73364fe8512f
DouglasParnoff/learning-python
/src/basic/data_types.py
1,212
4.46875
4
# Integer and Float types print("--- INT AND FLOAT ---") x = 2 # x is an integer y = 3.5 # y is a float print('x: ', + x) print('y: ', + y) print(type(x)) x = float(x) print(type(x)) # you can see more about float here: https://docs.python.org/3/tutorial/floatingpoint.html #NEVER do this: # print(5/0) # Bool type print("--- BOOL ---") bool_variable = x < 1 print(type(bool_variable)) print('bool_variable: ', bool_variable) print('not(bool_variable): ', not(bool_variable)) # Truth Value # We can use non-boolean objects in a boolean expression of an if statement (woooww!) # Here are most of the built-in objects that are considered False in Python: # - constants defined to be false: None and False # - zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1) # - empty sequences and collections: '"", (), [], {}, set(), range(0) errors = 6 if errors: print("Wait: there are {} errors to fix!".format(errors)) else: print("Congratulations: no errors found!") # String type print("--- STRING ---") my_string = 'Let\'s go, baby!' print(type(my_string)) print(my_string) print(len(my_string)) # doesn't work: print(len(132)) print(my_string[0]) print(my_string[1]) print(my_string[2])
true
d56c3cf2bdafa308ec0e4fa971ec377bd43458bf
Yashs744/Python-Workshop-2018
/Lists.py
1,156
4.59375
5
# Lists ''' Resouce: - https://realpython.com/python-lists-tuples/ - https://www.programiz.com/python-programming/methods/list ''' squares = [1, 4, 8, 16, 25, 36, 49] print (squares) for sq in squares: print (sq) # Append Method squares.append(64) squares.append(81) # Insert Method # name_of_list.insert(index, element) squares.insert(9, 100) squares.insert(0, 0) print (squares) # Remove Method # name_of_list.remove(element) squares.remove(25) print (squares) ## Arbitary Objects items = ['apples', 'cake', 10, 3 + 4j, ['Ice Cream'], ['Cold Coffee', 'Ice Tea']] print (items) ## Indexing # Elements are Ordered and can be accessed via index starting from 0 to n-1 print (item[0]) # this would return the 1st elements in the items list print (item[0:3]) # return first, second and third element from the list # List also support negative indexing print (item[-1]) # -1 represents last element in the list # One can traverse in list using negative indexes print (item[-3: -1]) # we can combine both print (items[0:-3]) # stride # Print List in Reverse Order print (items[::-1])
true
d56d29c6f473eddd980fa738f662de0a6dd24087
irimiabianca/calculator
/func.py
1,112
4.125
4
"""simple ex(docstr)""" def add(a,b): """Adds two numbers""" return sub(a, -b) def sub(a, b): return a - b def say_hello(first_name, last_name='', age=0): print(f'Hello {first_name} {last_name}. Your name is {age}') def f(): return 10, 20, 30, 40 def test_say_hello(): say_hello('Paul','Ianas',36) say_hello('Paul') say_hello(last_name = 'Ianas', first_name = 'Paul') params1 = ['Paul', 'Ianas', 36] say_hello(*params1) params2 = {'first_name':'Paul', 'last_name':'Ianas', 'age':36} #dictionar print(params2['first_name']) say_hello(**params2) # ** tine de sintaxa, nu de pointeri a, b, c, d = f() a, b, c, d = d, c, b, a print(a, b, c, d) if __name__ == '__main__': print(__doc__) print(__name__) print(add.__doc__) while True: x = int(input('x=')) y = int(input('y=')) print(f'x + y = {add(x,y)}') print(f'x - y = {sub(x,y)}') if x == 0 and y == 0: break test_say_hello() def sub(a, b): print('Celalalt sub') return a - b print(f'x-y = {sub(x,y)}')
false
44cf5edade16397337809a8023048212ed6f57bd
ebinej97/Luminarpython
/functionalprogramming/mapFliter.py
478
4.15625
4
#map / filter # map is used to apply to all values # filter is used to apply to or filter out particular values lst=[10,20,30,40,50] # def square(num1): # return(num1**2) sqlst=list(map(lambda num1:num1**2,lst)) print(sqlst) cube=list(map(lambda num1:num1**3,lst)) print(cube) #print even no in a lsit lst=[10,11,12,13,14,15,16,17,18,19,20] # def numcheck(num1): lambda function # return(num1%2==0) even=list(filter(lambda num1:num1%2==0,lst)) print(even)
true
1a78eb3ca273b232f3eaa84076f438bfa3d70a48
Samyam412/lab_exercise
/lab exercise 1/question 5.py
1,299
4.25
4
""" A school decided to replace the desks in three classrooms. Each desk sits two students. Given the number of students in each class, print the smallest possible number of desks that can be purchased. The program should read three integers: the number of students in each of the three classes, a, b and c respectively. In the first test there are three groups. The first group has 20 students and thus needs 10 desks. The second group has 21 students, so they can get by with no fewer than 11 desks. 11 desks are also enough for the third group of 22 students. So, we need 32 desks in total.""" students_a = int(input("enter the number of students in class a:")) students_b = int(input("enter the number of students in class b:")) students_c = int(input("enter the number of students in class c:")) def desk(std): desk_needed = std // 2 if std % 2 != 0: desk_needed += 1 return desk_needed desk_a = desk(students_a) desk_b = desk(students_b) desk_c = desk(students_c) total_desk = desk_a + desk_b + desk_c print(f" The desk needed in class 1 with {students_a} students is {desk_a} \n The desk needed in class 2 with {students_b} students is {desk_b} \n The desk needed in class 3 with {students_c} students is {desk_c} \n The total number of desks needed is {total_desk}")
true
a326f714fbb95f48217bcf7a556a9c574f9034db
RakValery/exadel-python-course-2021
/tasks/task02/Area_of_a_triangle.py
2,466
4.40625
4
# main menu import math print("\nWelcome to the triangle area calculation tool.") while True: print("\nMenu:","1. Calculate triangle area by base and height","2. Calculate triangle area by 2 sides and angle between them","3. Exit", sep = "\n") mitem = input("Enter menu item number: ") if mitem == "1": print("\nEnter base and height (space separated): ", end = "") while True: inp = input().split(" ") try: base, height = map(float, inp) print(f"\nbase = {base}, height = {height}") if base > 0 and height > 0: print("Area is: ", base * height / 2) break else: print("The side lengths of the triangle must be positive numbers. Please enter 2 positive numbers: ", end = "") except ValueError: #could not convert string to float or too many/few values to unpack if len(inp) == 2: err = "non-numeric" else: err = len(inp) print("\nYou entered ", err," value(s). Please enter 2 numeric values space separated: ", end = "") elif mitem == "2": print("\nEnter 2 sides and angle(degrees) between them (space separated): ", end = "") while True: inp = input().split(" ") try: side1, side2, angle = map(float, inp) print(f"\nside1 = {side1}, side2 = {side2}, angle = {angle}") if side1 > 0 and side2 > 0 and angle > 0 and angle < 180: print("Area is: ", round((side1 * side2 * math.sin(math.radians(angle)) / 2), 2)) break else: print("The lengths of the sides of the triangle must be positive numbers, the angle between the sides of the triangle is greater than zero and less than 180 degrees. Please enter 3 numbers in valid ranges: ", end = "") except ValueError: #could not convert string to float or too many/few values to unpack if len(inp) == 3: err = "non-numeric" else: err = len(inp) print("\nYou entered ", err," value(s). Please enter 3 numeric values space separated: ", end = "") elif mitem == "3": print("Goodbye!") exit() else: print('\n', "Please enter correct menu item number!")
true
13e42747c2fb0aaa3f2420bca6ba69065f5b9897
Naimul-Islam-Siam/Practice
/Python/1. new.py
630
4.1875
4
name = input("What is your name?") #scanf print("My name is " + name) print(bin(5)) #binary of 5 print(int("0b101", 2)) #first argument is a base 2 number, convert it to an int print(type(str(5))) #5 will be converted to str, then the type will be a string print(2 ** 3) #same as 2^3 a,b,c = 1,2,3 print(a) #1 print(b) #2 print(c) #3 # long string ''' allows string to occupy multiple lines long_string = ''' WOW O O --- ''' print(long_string) #Escape Sequence print("It\'s \"kind of\" funny") # \t = tab # \n = new line #Formatted String age = 55 name = "Johnny" print(f"{name} is {age} years old.") #f must be included
true
0eca9f2b4ba12c1e970ebdf42e360fa056782874
mgupte7/python-examples1
/pyFunctionEx.py
743
4.40625
4
# ----------------------------------------------- # ----------------Python Booleans---------------- # ----------------------------------------------- # ex1 a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a") # ex 2 - can evaluate any value using bool print(bool("Hello")) print(bool(15)) # ex 3 x = "Hello" y = 15 print(bool(x)) print(bool(y)) # ex 4 - values that yield false bool(False) bool(None) bool(0) bool("") bool(()) bool([]) bool({}) # ex 5 - You can execute code based on the Boolean answer of a function: def myFunction() : return True if myFunction(): print("YES!") else: print("NO!") # ex 6 - Check if an object is an integer or not: x = 200 print(isinstance(x, int))
true
1aef76df07e05d6c9b88d9f1a6eba333ecf0a87a
SylphDev/Actividades_Algoritmos
/ejercicios_programateca/c8_funciones/c8e1.py
1,755
4.3125
4
# Ejercicio 1: Escriba una función llamada densidad_de_poblacion que tome dos # argumentos: poblacion y area, y devuelva una densidad de población. # calculada a partir de esos valores. def get_area_population(): ''' El usuario ingresa el area y la poblacion. Returns: area = {float} population = {int} ''' valid = False while not valid: try: area = float(input("Ingrese el area (puede ser con decimales):\n>> ")) if area < 0: print("El area no puede ser negativa") elif area == 0: print("El area no puede ser 0") else: valid = True except ValueError: print("El area solo puede ser numeros (con o sin decimales)") while valid: try: population = float(input("Ingrese la poblacion:\n>> ")) if population < 0: print("La poblacion no puede ser negativa") elif population == 0: print("La poblacion no puede ser 0") else: valid = False except ValueError: print("La poblacion solo puede ser un numero entero") return area, population def calculate_density(area, population): '''Calculo de densidad poblacional Arguments: area = {float} >> area del terreno population = {int} >> residentes en el area Returns: density = {float} >> densidad poblacional ''' density = population / area return density def main(): area, population = get_area_population() density = calculate_density(area, population) print("La densidad poblacional es {:.2f}".format(density)) if __name__ == "__main__": main()
false
f3e80ed42c8d2a56a56475a7113268af47553a96
d80b2t/python
/bootcamp/age.py
764
4.21875
4
""" PYTHON BOOT CAMP BREAKOUT3 SOLUTION; created by Josh Bloom at UC Berkeley, 2012 (ucbpythonclass+bootcamp@gmail.com) """ import datetime born = datetime.datetime(1974,1,1,13,2,2) now = datetime.datetime.now() # note... .utcnow() gives the universal time, .now() # gives the local time. We're ignoring timezone stuff here. diff = now - born # cool! I can subtract two dates print diff # 1. how many days have you been alive? How many hours? print "days alive:", diff.days print "hours alive:", diff.days*24.0 # 2. What will be the date in 1000 days from now? # let's create a timedelta object td = datetime.timedelta(days=1000) print "in 1000 days it will be",now + td # this is a datetime object
true
4f138e5ca75505593c7beed4ff6a64e201899325
ParzivalMarcos/EstudosPython
/Udemy - Curso Python/lambdas.py
1,708
4.8125
5
""" Utilizando Lambdas Conhecidas por Expressões Lambdas, ou simplesmente Lambdas, são funções sem nome, ou seja, funções anonimas. Geralmente aplicadas em filtragem e ordenação de dados # Função em python def soma(a, b): return a + b def funcao(x): return 3 * x + 1 print(funcao(4)) # Exemplo Lambda lambda x: 3 * x + 1 # Utilizando a expressão lambda calc = lambda x: 3 * x + 1 print(calc(4)) # Podemos ter expressões lambdas com multiplas entradas nome_completo = lambda nome, sobrenome: nome.strip().title() + ' ' + sobrenome.strip().title() print(nome_completo(' marcos ', 'MARINHO')) print(nome_completo(nome=' MARCOS', sobrenome=' lima ')) # Funções python, podemos ter nenhuma ou varias entradas. Em Lambdas também teste = lambda: 'Como nao amar Python?' uma = lambda x: 3 * x + 1 duas = lambda x, y: (x * y) ** 0.5 tres = lambda x, y, z: 3 / (1 / x + 1 / y + 1 / z) print(teste()) print(uma(5)) print(duas(2, 6)) print(tres(5, 1, 7)) # Usando a ordenação pelo primeiro nome autores = ['Isaac Asimov', 'J. R. Tolkien', 'Agata Christie', 'Arthur C. Claire', 'Ernest Cline', 'Eduardo Sphor'] autores.sort() print(autores) print() # Ordenando pelo sobrenome usando lambda autores.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower()) print(autores) # Obs.: split() - separa os elementos # -[-1] pega o ultimo elemento, no caso o sobrenome # Função quadratica # f(x) = a * x ** 2 + b * x + c # Definindo a função def gerar_funcao_quadratica(a, b, c): return lambda x: a * x ** 2 + b * x + c # Retorna a função: f(x) = a * x ** 2 + b * x + c teste = gerar_funcao_quadratica(2, 3, -5) print(teste(0)) print(teste(1)) print(teste(2)) print(gerar_funcao_quadratica(3, 0, 1)(2)) """
false
daccc2ee8168191bbde866527da51bd23a535154
brandann/GarbageCode
/PYTHON/Examples/first_class.py
487
4.21875
4
class Point: 'Represents a point in two-dimensional geometric coordinates' def __init__(self, x=1, y=3): '''Initilies the position of...''' self.move(x, y) def move(self, x, y): "Move the point to a new location in 2D space." self.x = x self.y = y def reset(self): """Resets the points to 0,0""" self.move(0, 0) p = Point(3,1) again = True while(again): print(p.x, p.y) p.move(p.x+1, p.y-3) if p.x > 100: again = False a = raw_input("Press Return Key To Exit...")
true
7e7cf2311d1334f7a81ada6dd686b966e2ed484a
nidhinp/Anand-Chapter3
/problem7.py
659
4.28125
4
""" Write a function make_slug that takes a name converts it into a slug. A slug is a string where spaces and special charactes are replaces by a hyphen, typically used to create blog post URL from post title. It should also make sure there are no more than one hyphen in any place and there are no hyphen at the beginning and end of the slug. """ import re def make_slug(word): slug = re.sub(r'[\s!]', '-', word) modified_slug = re.sub(r'-+', '-', slug) space = re.sub(r'-', ' ',modified_slug) print re.sub(r'\s', '-',space.strip()) make_slug("hello world") make_slug("hello world!") make_slug(" --hello- world--")
true
f9791bed2c7d8f1c61c0490161549f113359926e
liugenghao/pythonstudy
/class/inheritPrac.py
2,464
4.1875
4
class School: def __init__(self,name,address): self.name = name self.address = address self.students = [] self.teachers = [] def enroll(self,obj): self.students.append(obj) print("为%s办理入校手续" %obj.name) def hire(self,obj): self.teachers.append(obj) print("为%s办理入校手续" %obj.name) def showTeachers(self): print("Teachers: ",end='') for teacher in self.teachers: print(teacher.name,' ',end='') print("") def showStudents(self): print("Students: ", end='') for student in self.students: print(student.name, ' ', end='') print("") class SchoolMember: members = 0 def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex def tell(self): pass class Teacher(SchoolMember): def __init__(self,name,age,sex,salary,course): super(Teacher,self).__init__(name,age,sex) self.salary = salary self.course = course def tell(self): print(""" -----------info of Teacher: %s------------ Name:%s Age:%d Sex:%s Salary:%d Course:%s """ %(self.name,self.name,self.age,self.sex,self.salary,self.course)) def teach(self): print("%s will teach you %s" %(self.name,self.course)) class Student(SchoolMember): def __init__(self,name,age,sex,stu_id,grade): super(Student,self).__init__(name,age,sex) self.stu_id = stu_id self.grade = grade def tell(self): print(""" -----------info of Student: %s------------ Name:%s Age:%d Sex:%s ID:%s Grade:%d """ %(self.name,self.name,self.age,self.sex,self.stu_id,self.grade)) def pay_tuition(self,amount): print("%s has paid tuition for $%d" %(self.name,amount)) school = School("三峡大学","大学路") t1 = Teacher("Peter",56,"M",200000,"Linux") t2 = Teacher("Tom",36,"M",120000,"Society") school.hire(t1) school.hire(t2) s1 = Student("Jim",20,"M","2017331091",1) s2 = Student("Rose",19,"F","2017331021",1) s3 = Student("Xupeng",18,"M","2016322231",1) school.enroll(s1) school.enroll(s2) school.enroll(s3) school.showTeachers() school.showStudents() for student in school.students: student.pay_tuition(5500) # t1.tell() # s3.tell()
true
6cc30f2f71b11cfb74e224d02263b30616440df4
DaniVasq/holbertonschool-higher_level_programming
/0x06-python-classes/2-square.py
463
4.125
4
#!/usr/bin/python3 class Square: """class Square""" def __init__(self, size=0): """init size as zero, an int""" self.__size = size """assigning size as a private instance attribute""" if not isinstance(size, int): """if not of type int, then...""" raise TypeError("size must be an integer") elif size < 0: raise ValueError("size must be >= 0") """raise exceptions"""
true
75e1875d123f37227aecd398b895d01ecd8a53ac
SlawomirMiszkurka/Zadania-2
/Zad 14.py
329
4.53125
5
##### # Calculation of the area and circumference of a circle ## # determine radius and PI radius= 5 PI= 3.14 # calculate area area=PI*radius**2 # calculate circumference circumference= PI*radius*2 # display results print(f'"When radius is {radius} area equals {area} and circumference equals {circumference}"')
true
f85ab90e37619328b8b65fe3583bf46d42d03f09
chimel3/stormbowl
/fixtures.py
2,666
4.15625
4
import config import random def create_fixture_list(): ''' ABOUT: Uses the circle algorithm to produce a round-robin style fixture list. ''' ''' IDEAS: ''' print("starting create_fixture_list") # Create a new list to hold the clubs. Whilst I could just use the list of clubs held in the game, this wouldn't work where the total number of clubs is an odd number as I then have to create a "DayOff" club. clublist = config.game.clubs if len(clublist) % 2: clublist.append("DayOff") # set the number of fixtures per round classes.game.Game.fixtures_per_round(config.game, int(len(clublist)/2)) # this is cast to an int because otherwise it automatically becomes a float and the for loop in get_fixtures_for_round fails # shuffle clublist to get some randomness in there to the schedule. random.shuffle(clublist) # create the fixture list variables #config.start_fixture_list() for week in range(1, len(clublist)): for i in range(int(len(clublist)/2)): # for the number of matches # attempt to keep a mixture of home and away games if week % 2: #config.fixtures.append((clublist[i], clublist[len(clublist)-1-i])) classes.game.Game.add_fixture(config.game, clublist[i], clublist[len(clublist)-1-i]) #config.returnfixtures.append((clublist[len(clublist)-1-i], clublist[i])) classes.game.Game.add_returnfixture(config.game, clublist[len(clublist)-1-i], clublist[i]) else: #config.fixtures.append((clublist[len(clublist)-1-i], clublist[i])) classes.game.Game.add_fixture(config.game, clublist[len(clublist)-1-i], clublist[i]) #config.returnfixtures.append((clublist[i], clublist[len(clublist)-1-i] )) classes.game.Game.add_returnfixture(config.game, clublist[i], clublist[len(clublist)-1-i]) # move the last club up to the 2nd position in the list clublist.insert(1, clublist.pop()) #return len(clublist-1) # number of rounds is the number of clubs in the draw (includes DayOff) minus 1. ''' # following code is troubleshooting code to show the fixtures in full for fixture in config.fixtures: if isinstance(fixture[0], str): print(fixture[0] + " v " + fixture[1].name) elif isinstance(fixture[1], str): print(fixture[0].name + " v " + fixture[1]) else: print(fixture[0].name + " v " + fixture[1].name) ''' import classes.game
true
21f7bda2d4ba911344f137e0d548234a4a549b1f
nicholsl/PythonProjects
/higher1.py
1,843
4.3125
4
'''higher1.py Jed Yang, 2016-11-10 We have seen how to use map, filter, and functools.reduce to process lists. But these methods do not seem to save a lot of coding, if we have to write a helper function each time to use them. There must be a better way. ''' # Here is the sum-of-ints example using 'reduce' from higher0.py. l = range(10) def summation(x, y): return x + y import functools total = functools.reduce(summation, l) print(total) # Do we really have to write our own addition function? Python obviously has # addition, but neither of these lines works. # functools.reduce(+, range(10)) # functools.reduce('+', range(10)) # Comment the above lines out (since they don't work). # The function you want is add, in the operator module. import operator print( functools.reduce(operator.add, range(10)) ) # You may not know about operator.add. Also, in general, Python might not have # a built-in function for your task. You can use the 'lambda' keyword to make a # function right when you need it, without giving it a name! # # lambda arg1, arg2, ..., argN: return value calculated from arg1...argN # # Here is the reduce example using the lambda keyword. print( functools.reduce(lambda x, y: x + y, range(10)) ) # ^^^^^^^^^^^^^^^^^^ this represent a function that takes # two inputs, x and y, and returns x + y. # Write the lambda expression for the even-numbers filter example from # higher0.py. I've started it for you. You just need to change the ??????. #print( list(filter(lambda n: ???????, range(10))) ) print( list (filter(lambda n: n % 2 == 0, range(10)))) # Adapt our list-of-cubes map example from higher0.py using lambda, in one line. # I didn't quite start it for you this time. print( list (map(lambda x: x**3, range(10))))
true
62eea6ee43e25c53a24e30c12abe1e49a88c36fc
arjuntpant/goldencross
/first.py
1,746
4.125
4
#!/usr/bin/env python3 import os import sys import turtle as a import random scr = a.Screen() scr.bgcolor('dark blue') print ("My name is Arjun") def draw_rectangle(length, width, color, a): a.pensize(1) a.color(color) a.begin_fill() for i in range(1,3): a.forward(length) a.right(90) a.forward(width) a.right(90) a.end_fill() a.goto(0,200) draw_rectangle(525,200,"gold",a) draw_rectangle(200,525,"gold",a) a.goto(-400,200) draw_rectangle(525,200,"gold",a) a.penup() a.goto(200,400) a.pendown() draw_rectangle(200,525,"gold",a) def draw_star(points, size, angle, color,a): a.color(color) a.begin_fill() for i in range (points): a.forward(size) a.right(angle); a.end_fill() a.speed(0) starsize=30 distance = starsize +15; for y in range(1,distance*5,distance): y = y + 111; for x in range(1,distance*10, distance): a.penup() x = x - 666; a.goto(x,y); a.pendown() size=starsize points=5 angle=180- (180 /points) draw_star(points, size, angle, "white", a); for y in range(1,distance*5,distance): y = y + 111; for x in range(200,200+distance*10, distance): a.penup() a.goto(x,y); a.pendown() size=starsize points=5 angle=180- (180 /points) draw_star(points, size, angle, "white", a); for y in range(-290,-290+distance*5,distance): for x in range(200,200+distance*10, distance): a.penup() a.goto(x,y); a.pendown() size=starsize points=5 angle=180- (180 /points) draw_star(points, size, angle, "white", a); for y in range(-290,-290+distance*5,distance): for x in range(-666,-666+distance*10, distance): a.penup() a.goto(x,y); a.pendown() size=starsize points=5 angle=180- (180 /points) draw_star(points, size, angle, "white", a);
false
a7735efc55021db004535bab8898eee7c117fa98
GloryPierceEguare/Python-Programming
/Coding Work (Python)/Palindrome Check.py
414
4.34375
4
print('Enter a string to check if its a palindrome: ') mystring = input() upstring=mystring.upper() #print(upstring) revstring = upstring[::-1] if (revstring == upstring): print("Palindrome") else: print("Not a Palindrome") """for i in range(len(upstring) // 2): if upstring[i] != upstring[- 1 - i]: print('Not Palindrome') break else: print('Palindrome')"""
false
d8b916b65c65277c1da54b68ca2b2090b7cc57e3
2019zding/Python
/queue.py
681
4.21875
4
class Queue(): # initialization def __init__(self): self.items = [] # enqueue, which means adding an item to a queue def enqueue(self, items): return self.items.insert(0, items) # dequeue, which means removing an item from a queue def dequeue(self): return self.items.pop() # showing all of the items in the list def list(self): for x in self.items: print(x) # q is an instance of class Queue # q is a type of Queue q = Queue() # adding to the queue q.enqueue('cat') q.enqueue('rat') # debug, see list before dequeue print("This is popped") print(q.dequeue()) # debug, see list after dequeue q.list()
true
3871b9f00a64fede68646972e686281a0e48d7c5
Anandkumarasamy/Python
/demo_list3.py
218
4.125
4
#Write a Python program to get the difference between the two lists. list1=[1,3,5,7,9] list2=[1,2,4,6,7,8] list3=list(set(list1+list2)) for num in list1: if num in list2: list3.remove(num) print(list3)
true
50a0b77c4ad3ab29283826d2a17de365c18ad5fa
Anandkumarasamy/Python
/demo_list8.py
399
4.125
4
#30 Write a Python program to get the frequency of the elements in a list. list1=[10,10,10,10,20,20,20,20,40,40,50,50,30] dic={} for num in list1: if num in dic: dic[num]=dic[num]+1 else: dic[num]=1 print('the frequency of the elements:',dic) list2=[] for key,value in dic.items(): for iterater in range(value): list2.append(key) print('the normal list:',list2)
true
d411f337f2a7ca50a47c3804d1eb623ef2825d76
xiaobingscuer/lxber-code
/code/python/data_struct_and_algorithm_in_python/datastruct-algorithm.py
1,248
4.40625
4
# data structure and algorithm in python # 有价值的参考源:http://www.madmalls.com/blog/post/finding-the-largest-or-smallest-n-items-in-a-python3-collection/ class Module(): def __init__(self, id, name, path): self.id = id self.name = name self.path = path def __str__(self): return str(self.id)+" "+self.name+" "+self.path if __name__=='__main__': # 排序-自定义对象列表的排序 # 1.借助列表的排序方法list.sort() # 2.使用sorted函数,该函数不改变原始容器的值,而是返回一个新建立的排好序的容器 modules=[] for i in range(10): modules.append( Module(9-i,"xiaobing"+str(i),"D:\lxb\lxb-coder\python")) print("原始modules") for module in modules: print(module) modules.sort(key = lambda x:x.id, reverse = False) print("list.sort()排序后的modules") for module in modules: print(module) modules_new = sorted(modules, key = lambda x:x.id, reverse = True) print("sorted()排序后的modules") for module in modules: print(module) print("sorted()排序后的新的modules") for module in modules_new: print(module)
false
6bd32279df7f26e29fa9aff1e1b784bd8b1f613d
xiaobingscuer/lxber-code
/code/py-code/design-pattern/build-type-pattern/factory.py
1,576
4.15625
4
#!/usr/bin/python # coding=utf-8 """ 工厂方法模式: 1. 主要解决:主要解决接口选择的问题。 2. 何时使用:我们明确地计划可在不同条件下选择(创建)某一抽象类型下不同子类的实例时。 3. 优点:符合开闭原则,对已有代码修改进行关闭,对扩展开放。代码可扩展可维护。 4. 比如新增加一个类型,只需新增加该类型新的子类 """ class Person(object): """ 人 """ def __init__(self, name, sex): self.name = name self.sex = sex @property def get_name(self): return self.name @property def get_sex(self): return self.sex def print_info(self): print('my name is {name}, my sex is {sex}'.format(name=self.name, sex=self.sex)) class Male(Person): """ 男性 """ def __init__(self, name): super().__init__(name, 'Male') print('male, name is {name}'.format(name=self.name)) class Female(Person): """ 女性 """ def __init__(self, name): super().__init__(name, 'Female') print('female, name is {name}'.format(name=self.name)) def person_factory(name, sex_type): """ 工厂 """ if sex_type == 'm': return Male(name) elif sex_type == 'f': return Female(name) else: print('other sex will be supported!') return Person(name, 'Other') if __name__ == '__main__': person = person_factory('lxb', 'm') person.print_info() person = person_factory('xiaoxue', 'f') person.print_info() pass
false
6f8213f2accd85b86e89dda2d72130e65c1b41be
Murthidn/my-python
/Notes/Basic/9-Range.py
273
4.15625
4
r=range(5) for i in r: print(i) #like size, print 0 - 4 #we can specify start point also print('--') r=range(2,6) for i in r: print(i) #prints from 2 - 5, last elem ignored #you can also pass step value print('-------') r=range(2,8,2) for i in r: print(i)
true
9d40d060c1f6fc76f44a3827f3ef95060ade33d5
maggieee/code-challenges
/reverse_keep_order.py
1,237
4.34375
4
"""In this challenge, you need to reverse a string, keeping the word themselves in order, and preserving exact spacing. For example, for the string: " hello_kitty " This should produce: " kitty hello " (Note that we keep the 3 spaces before hello, the two spaces between “hello” and “kitty," and the space after “kitty”.""" # have a string # how would you reverse a string if you were also reversing the letters? # how would you alter your approach to not reverse the words? # reverse by looping # range is where do you want to stop, where do you want to end, and step (exclusive) def reverse_keep_order(str): new_str = "" stop_char_index = None for i in range(len(str)-1, -1, -1): #looping through the indexes of the string backwards if str[i] == " ": if stop_char_index is not None: new_str += str[i+1:stop_char_index+1] stop_char_index = None new_str += str[i] # i is the index elif str[i] != " ": if stop_char_index is None: stop_char_index = i if stop_char_index: new_str += str[0:stop_char_index+1] return new_str print("test ' hi Emily !!! ' --> ' !!! Emily hi '") print(reverse_keep_order(" cat rat bat"))
true
68caebc77b00e0e9bb67cee90754127961f4a52b
RohanMiraje/DSAwithPython
/DSA/string/find_permutation_pattern_in_given_string.py
2,231
4.3125
4
""" find if permutation of given pattern exist in given string text -->use sliding window technique + any algo to check window string and pattern anagram(use xor approach) """ def find_pattern(string, pat): """ this is naive approach it takes O((n-m+)*m) :param string: :param pat: :return: """ str_len = len(string) pat_len = len(pat) start_window = 0 end_window = pat_len for i in range(str_len - pat_len): if are_anagrams(string[start_window:end_window], pat): print(i) start_window += 1 end_window += 1 def find_pattern_2(string, pat): """ This method works in O(n) time Idea is to have count array of pattern and string for given len of pattern which stores frequency of chars of pattern char and other string chars It iterate over string form 0 to n-m n is len of string and m is len of pat Sliding window technique is used to iterate over string :param string: :param pat: :return: """ text_window_count = [0 for _ in range(256)] pat_window_count = [0 for _ in range(256)] text_len = len(string) pat_len = len(pat) for i in range(pat_len): text_window_count[ord(text[i])] += 1 pat_window_count[ord(pat[i])] += 1 for i in range(text_len - pat_len): if is_anagrams(text_window_count, pat_window_count): return True text_window_count[ord(text[i])] -= 1 text_window_count[ord(text[i + pat_len])] += 1 return False def is_anagrams(pat_window_count, text_window_count): for i in range(256): if pat_window_count[i] != text_window_count[i]: return False return True def are_anagrams(str1, str2): str1 = str1.replace(' ', '') str2 = str2.replace(' ', '') n1 = len(str1) n2 = len(str2) if n1 != n2: return False res = ord(str1[0]) for i in range(1, n1, 1): res ^= ord(str1[i]) res2 = ord(str2[0]) for i in range(1, n1, 1): res2 ^= ord(str2[i]) return res ^ res2 == 0 if __name__ == "__main__": text = "geeksforgeeks" pattern = "egek" # "geek" # find_pattern(text, pattern) print(find_pattern_2(text, pattern))
true
8a02fb81626d3dc35b9905c837a9d1d0f41b1652
RohanMiraje/DSAwithPython
/DSA/arrays/find_missing_no.py
1,736
4.40625
4
""" Given two array e.g. arr_1 = [1, 2, 3, 4, 5, 6, 7] arr_2 = [3, 7, 2, 1, 4, 6] Find a missing element second array Method 1: Using sum of elements of two arrays missing_element = sum_of_elements_of_first_array - sum_of_elements_of_second_array TC: O(n) Method 2: Using XOR operation on all elements of both array result = 0 for num in array_1 + array_2: result = result XOR num finally result would be the missing ele from second array Method 3: Using aux dict as look up table add all ele from second array to dict and then travers first array: check if ele is not present in dict then it is missing ele from second array """ def find_missing_number_using_sum(arr, arr2): """ This approach may be problematic in case if arrays are two long or elements are very small """ complete_sum = 0 for val in arr: complete_sum += val missing_sum = 0 for val in arr2: missing_sum += val return complete_sum - missing_sum def finding_missing_using_xor(arr1, arr2): """ XOR of two same no. is zero """ result = 0 for num in arr1 + arr2: result ^= num return result def find_missing_number_using_aux_dict_look_up(arr1, arr2): look_up_dict = {} for val in arr2: look_up_dict[val] = val for val in arr1: if val not in look_up_dict: return val if __name__ == '__main__': arr_1 = [1, 2, 3, 4, 5, 6, 7] arr_2 = [3, 7, 2, 1, 4, 6] print(find_missing_number_using_sum(arr_1, arr_2)) print(finding_missing_using_xor(arr_1, arr_2)) print(find_missing_number_using_aux_dict_look_up(arr_1, arr_2))
true
3329a0079cc277ed5ba8c8924422e273fece5e37
RohanMiraje/DSAwithPython
/DSA/pythonhackerrank/2d_pattern_traversal.py
1,987
4.34375
4
""" Objective Today, we are building on our knowledge of arrays by adding another dimension. Check out the Tutorial tab for learning materials and an instructional video. Context Given a 2D Array, : 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 We define an hourglass in to be a subset of values with indices falling in this pattern in 's graphical representation: a b c d e f g There are hourglasses in , and an hourglass sum is the sum of an hourglass' values. Task Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum. Example In the array shown above, the maximum hourglass sum is for the hourglass in the top left corner. Input Format There are lines of input, where each line contains space-separated integers that describe the 2D Array . Constraints Output Format Print the maximum hourglass sum in . Sample Input 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 2 4 4 0 0 0 0 2 0 0 0 0 1 2 4 0 Sample Output 19 Explanation contains the following hourglasses: 1 1 1 1 1 0 1 0 0 0 0 0 1 0 0 0 1 1 1 1 1 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 2 0 2 4 2 4 4 4 4 0 1 1 1 1 1 0 1 0 0 0 0 0 0 2 4 4 0 0 0 0 0 2 0 2 0 2 0 0 0 0 2 0 2 4 2 4 4 4 4 0 0 0 2 0 0 0 1 0 1 2 1 2 4 2 4 0 The hourglass with the maximum sum () is: 2 4 4 2 1 2 4 """ # !/bin/python3 import math import os import random import re import sys if __name__ == '__main__': arr = [] for _ in range(6): arr.append(list(map(int, input().rstrip().split()))) result = 0 # sample of firts first pattern # sum(arr[0][0:3]) + arr[1][1] + sum(arr[2][0:3]) result = [] for i in range(4): for j in range(4): curr_sum = sum(arr[i][j:j + 3]) + arr[i + 1][j + 1] + sum(arr[i + 2][j:j + 3]) result.append(curr_sum) print(max(result))
true
ab9d08278af39b59e42dd5b1c1eaae3e6700a215
RohanMiraje/DSAwithPython
/DSA/linked_list/single_linked_list/head_tail_linked_list.py
1,153
4.125
4
class Node: def __init__(self, value): self.data = value self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def insert_at_beg(self, value): new_node = Node(value) if not self.head: self.tail = new_node self.head = new_node return new_node.next = self.head self.head = new_node def insert_at_last(self, value): new_node = Node(value) if not self.tail: self.tail = new_node self.head = new_node return self.tail.next = new_node self.tail = new_node def print_list(self): temp = self.head while temp: print(temp.data, end=" ") temp = temp.next print("\n") if __name__ == '__main__': ll = LinkedList() ll.insert_at_last(1) ll.insert_at_last(2) ll.insert_at_last(3) ll.insert_at_last(4) ll.insert_at_last(5) ll.insert_at_beg(11) ll.insert_at_beg(12) ll.insert_at_beg(13) ll.insert_at_beg(14) ll.insert_at_beg(15) ll.print_list()
false
1af3a729f861abcff1571e8e072d4a47192d4950
Baidaly/datacamp-samples
/8 - statistical thinking in python - part 1/quantitative exploratory data analysis/computing the covariance.py
869
4.21875
4
''' The covariance may be computed using the Numpy function np.cov(). For example, we have two sets of data x and y, np.cov(x, y) returns a 2D array where entries [0,1] and [1,0] are the covariances. Entry [0,0] is the variance of the data in x, and entry [1,1] is the variance of the data in y. This 2D output array is called the covariance matrix, since it organizes the self- and covariance. To remind you how the I. versicolor petal length and width are related, we include the scatter plot you generated in a previous exercise. ''' # Compute the covariance matrix: covariance_matrix covariance_matrix = np.cov(versicolor_petal_length, versicolor_petal_width) # Print covariance matrix print(covariance_matrix) # Extract covariance of length and width of petals: petal_cov petal_cov = covariance_matrix[0,1] # Print the length/width covariance print(petal_cov)
true
8639c4b242ad4ca6d530956a7209d1fdc260692e
Baidaly/datacamp-samples
/5 - merging dataframes with pandas/reindexing DataFrame from a list.py
1,256
4.1875
4
''' Sorting methods are not the only way to change DataFrame Indexes. There is also the .reindex() method. In this exercise, you'll reindex a DataFrame of quarterly-sampled mean temperature values to contain monthly samples (this is an example of upsampling or increasing the rate of samples, which you may recall from the pandas Foundations course). The original data has the first month's abbreviation of the quarter (three-month interval) on the Index, namely Apr, Jan, Jul, and Oct. This data has been loaded into a DataFrame called weather1 and has been printed in its entirety in the IPython Shell. Notice it has only four rows (corresponding to the first month of each quarter) and that the rows are not sorted chronologically. You'll initially use a list of all twelve month abbreviations and subsequently apply the .ffill() method to forward-fill the null entries when upsampling. This list of month abbreviations has been pre-loaded as year. ''' # Import pandas import pandas as pd # Reindex weather1 using the list year: weather2 weather2 = weather1.reindex(year) # Print weather2 print(weather2) # Reindex weather1 using the list year with forward-fill: weather3 weather3 = weather1.reindex(year).ffill() # Print weather3 print(weather3)
true
a1b25fdb0d749055443b04c29d4cc229f35b7684
Baidaly/datacamp-samples
/16 - building recommendation engines in python/chapter 1/6 - Making your first movie recommendations.py
1,034
4.5625
5
''' Now that you have found the most commonly paired movies, you can make your first recommendations! While you are not taking in any information about the person watching, and do not even know any details about the movie, valuable recommendations can still be made by examining what groups of movies are watched by the same people. In this exercise, you will examine the movies often watched by the same people that watched Thor, and then use this data to give a recommendation to someone who just watched the movie. The DataFrame you generated in the last lesson, combination_counts_df, that contains counts of how often movies are watched together has been loaded for you. ''' import matplotlib.pyplot as plt # Sort the counts from highest to lowest combination_counts_df.sort_values('size', ascending=False, inplace=True) # Find the movies most frequently watched by people who watched Thor thor_df = combination_counts_df[combination_counts_df['movie_a'] == 'Thor'] # Plot the results thor_df.plot.bar(x="movie_b") plt.show()
true
82056af0d3e8c1088a430db57fa499199ab620e6
Baidaly/datacamp-samples
/8 - statistical thinking in python - part 1/quantitative exploratory data analysis/computing the Pearson correlation coefficient.py
1,130
4.46875
4
''' As mentioned in the video, the Pearson correlation coefficient, also called the Pearson r, is often easier to interpret than the covariance. It is computed using the np.corrcoef() function. Like np.cov(), it takes two arrays as arguments and returns a 2D array. Entries [0,0] and [1,1] are necessarily equal to 1 (can you think about why?), and the value we are after is entry [0,1]. In this exercise, you will write a function, pearson_r(x, y) that takes in two arrays and returns the Pearson correlation coefficient. You will then use this function to compute it for the petal lengths and widths of I. versicolor. Again, we include the scatter plot you generated in a previous exercise to remind you how the petal width and length are related. ''' def pearson_r(x, y): """Compute Pearson correlation coefficient between two arrays.""" # Compute correlation matrix: corr_mat corr_mat = np.corrcoef(x, y); # Return entry [0,1] return corr_mat[0,1] # Compute Pearson correlation coefficient for I. versicolor: r r = pearson_r(versicolor_petal_length, versicolor_petal_width) # Print the result print(r)
true
70698a3667ae95b48d495f3e41fce0161608e3e4
Baidaly/datacamp-samples
/6 - introduction to databases in python/calculating a Difference between Two Columns.py
1,204
4.15625
4
''' Often, you'll need to perform math operations as part of a query, such as if you wanted to calculate the change in population from 2000 to 2008. For math operations on numbers, the operators in SQLAlchemy work the same way as they do in Python. You can use these operators to perform addition (+), subtraction (-), multiplication (*), division (/), and modulus (%) operations. Note: They behave differently when used with non-numeric column types. Let's now find the top 5 states by population growth between 2000 and 2008. ''' # Build query to return state names by population difference from 2008 to 2000: stmt stmt = select([census.columns.state, (census.columns.pop2008-census.columns.pop2000).label('pop_change')]) # Append group by for the state: stmt stmt = stmt.group_by(census.columns.state) # Append order by for pop_change descendingly: stmt stmt = stmt.order_by(desc('pop_change')) # Return only 5 results: stmt stmt = stmt.limit(5) # Use connection to execute the statement and fetch all results results = connection.execute(stmt).fetchall() # Print the state and population change for each record for result in results: print('{}:{}'.format(result.state, result.pop_change))
true
50c2176c301e9e92b5f464c753eecf03bebcff30
Baidaly/datacamp-samples
/5 - merging dataframes with pandas/reindexing using another DataFrame Index.py
1,696
4.4375
4
''' Another common technique is to reindex a DataFrame using the Index of another DataFrame. The DataFrame .reindex() method can accept the Index of a DataFrame or Series as input. You can access the Index of a DataFrame with its .index attribute. The Baby Names Dataset from data.gov summarizes counts of names (with genders) from births registered in the US since 1881. In this exercise, you will start with two baby-names DataFrames names_1981 and names_1881 loaded for you. The DataFrames names_1981 and names_1881 both have a MultiIndex with levels name and gender giving unique labels to counts in each row. If you're interested in seeing how the MultiIndexes were set up, names_1981 and names_1881 were read in using the following commands: names_1981 = pd.read_csv('names1981.csv', header=None, names=['name','gender','count'], index_col=(0,1)) names_1881 = pd.read_csv('names1881.csv', header=None, names=['name','gender','count'], index_col=(0,1)) As you can see by looking at their shapes, which have been printed in the IPython Shell, the DataFrame corresponding to 1981 births is much larger, reflecting the greater diversity of names in 1981 as compared to 1881. Your job here is to use the DataFrame .reindex() and .dropna() methods to make a DataFrame common_names counting names from 1881 that were still popular in 1981. ''' # Import pandas import pandas as pd # Reindex names_1981 with index of names_1881: common_names common_names = names_1981.reindex(names_1881.index) # Print shape of common_names print(common_names.shape) # Drop rows with null counts: common_names common_names = common_names.dropna() # Print shape of new common_names print(common_names.shape)
true
8ed1dda8908d4c11aba7bb38b1465e86546d28b9
Baidaly/datacamp-samples
/3 - pandas foundation/austin case study/8.py
1,070
4.21875
4
''' Sunny or cloudy On average, how much hotter is it when the sun is shining? In this exercise, you will compare temperatures on sunny days against temperatures on overcast days. Your job is to use Boolean selection to filter out sunny and overcast days, and then compute the difference of the mean daily maximum temperatures between each type of day. The DataFrame df_clean from previous exercises has been provided for you. The column 'sky_condition' provides information about whether the day was sunny ('CLR') or overcast ('OVC'). ''' # Select days that are sunny: sunny sunny = df_clean.loc[df_clean['sky_condition'].str.contains('CLR')] # Select days that are overcast: overcast overcast = df_clean.loc[df_clean['sky_condition'].str.contains('OVC')] # Resample sunny and overcast, aggregating by maximum daily temperature sunny_daily_max = sunny.resample('D').max() overcast_daily_max = overcast.resample('D').max() # Print the difference between the mean of sunny_daily_max and overcast_daily_max print(sunny_daily_max.mean() - overcast_daily_max.mean())
true
377045ef9c1b7b105fb1f45bd7a6eea02d2adf7e
Baidaly/datacamp-samples
/9 - statistical thinking in python - part 2/case study/7 - Displaying the linear regression results.py
1,208
4.28125
4
''' Now, you will display your linear regression results on the scatter plot, the code for which is already pre-written for you from your previous exercise. To do this, take the first 100 bootstrap samples (stored in bs_slope_reps_1975, bs_intercept_reps_1975, bs_slope_reps_2012, and bs_intercept_reps_2012) and plot the lines with alpha=0.2 and linewidth=0.5 keyword arguments to plt.plot(). ''' # Make scatter plot of 1975 data _ = plt.plot(bl_1975, bd_1975, marker='.', linestyle='none', color='blue', alpha=0.5) # Make scatter plot of 2012 data _ = plt.plot(bl_2012, bd_2012, marker='.', linestyle='none', color='red', alpha=0.5) # Label axes and make legend _ = plt.xlabel('beak length (mm)') _ = plt.ylabel('beak depth (mm)') _ = plt.legend(('1975', '2012'), loc='upper left') # Generate x-values for bootstrap lines: x x = np.array([10, 17]) # Plot the bootstrap lines for i in range(100): plt.plot(x, bs_slope_reps_1975[i] * x + bs_intercept_reps_1975[i], linewidth=0.5, alpha=0.2, color='blue') plt.plot(x, bs_slope_reps_2012[i] * x + bs_intercept_reps_2012[i], linewidth=0.5, alpha=0.2, color='red') # Draw the plot again plt.show()
true
cbe1c065f7b93dff30bf9f5ecff730b0b53d9582
Baidaly/datacamp-samples
/5 - merging dataframes with pandas/broadcasting in arithmetic formulas.py
1,118
4.3125
4
''' In this exercise, you'll work with weather data pulled from wunderground.com. The DataFrame weather has been pre-loaded along with pandas as pd. It has 365 rows (observed each day of the year 2013 in Pittsburgh, PA) and 22 columns reflecting different weather measurements each day. You'll subset a collection of columns related to temperature measurements in degrees Fahrenheit, convert them to degrees Celsius, and relabel the columns of the new DataFrame to reflect the change of units. Remember, ordinary arithmetic operators (like +, -, *, and /) broadcast scalar values to conforming DataFrames when combining scalars & DataFrames in arithmetic expressions. Broadcasting also works with pandas Series and NumPy arrays. ''' # Extract selected columns from weather as new DataFrame: temps_f temps_f = weather[['Min TemperatureF', 'Mean TemperatureF', 'Max TemperatureF']] # Convert temps_f to celsius: temps_c temps_c = (temps_f - 32) * 5/9 # Rename 'F' in column names with 'C': temps_c.columns temps_c.columns = temps_c.columns.str.replace('F', 'C') # Print first 5 rows of temps_c print(temps_c.head())
true
8fae0fa1a1965830f5ea449962361513e58cd8ac
Baidaly/datacamp-samples
/4 - manipulating dataframes with pandas/Extracting and transforming data/using apply to transform a column.py
907
4.65625
5
''' The .apply() method can be used on a pandas DataFrame to apply an arbitrary Python function to every element. In this exercise you'll take daily weather data in Pittsburgh in 2013 obtained from Weather Underground. A function to convert degrees Fahrenheit to degrees Celsius has been written for you. Your job is to use the .apply() method to perform this conversion on the 'Mean TemperatureF' and 'Mean Dew PointF' columns of the weather DataFrame. ''' # Write a function to convert degrees Fahrenheit to degrees Celsius: to_celsius def to_celsius(F): return 5/9*(F - 32) # Apply the function over 'Mean TemperatureF' and 'Mean Dew PointF': df_celsius df_celsius = weather[['Mean TemperatureF','Mean Dew PointF']].apply(to_celsius) # Reassign the columns df_celsius df_celsius.columns = ['Mean TemperatureC', 'Mean Dew PointC'] # Print the output of df_celsius.head() print(df_celsius.head())
true
c66a3aae3ebb29310a7aa3d92f9a712fde5a1c2f
Baidaly/datacamp-samples
/8 - statistical thinking in python - part 1/thinking probabilistically/will the bank fail.py
782
4.53125
5
''' Plot the number of defaults you got from the previous exercise, in your namespace as n_defaults, as a CDF. The ecdf() function you wrote in the first chapter is available. If interest rates are such that the bank will lose money if 10 or more of its loans are defaulted upon, what is the probability that the bank will lose money? ''' # Compute ECDF: x, y x, y = ecdf(n_defaults) # Plot the ECDF with labeled axes _ = plt.plot(x, y, marker='.', linestyle='none') _ = plt.xlabel('x') _ = plt.ylabel('y') # Show the plot plt.show() # Compute the number of 100-loan simulations with 10 or more defaults: n_lose_money n_lose_money = np.sum(n_defaults >= 10) # Compute and print probability of losing money print('Probability of losing money =', n_lose_money / len(n_defaults))
true
4d8391a0ff32748e16dbb0888595c912930200b9
Baidaly/datacamp-samples
/13 - Supervised Learning with scikit-learn/chapter 1/5 - Train-Test Split + Fit-Predict Accuracy.py
930
4.28125
4
''' Now that you have learned about the importance of splitting your data into training and test sets, it's time to practice doing this on the digits dataset! After creating arrays for the features and target variable, you will split them into training and test sets, fit a k-NN classifier to the training data, and then compute its accuracy using the .score() method. ''' # Import necessary modules from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split # Create feature and target arrays X = digits.data y = digits.target # Split into training and test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=42, stratify=y) # Create a k-NN classifier with 7 neighbors: knn knn = KNeighborsClassifier(n_neighbors=7) # Fit the classifier to the training data knn.fit(X_train, y_train) # Print the accuracy print(knn.score(X_test, y_test))
true
e00dc38228b9dfa2206e9dddaaa3eeda9e6fba61
Baidaly/datacamp-samples
/15 - joining data with pandas/chapter 2/4 - Using outer join to select actors.py
1,134
4.6875
5
''' One cool aspect of using an outer join is that, because it returns all rows from both merged tables and null where they do not match, you can use it to find rows that do not have a match in the other table. To try for yourself, you have been given two tables with a list of actors from two popular movies: Iron Man 1 and Iron Man 2. Most of the actors played in both movies. Use an outer join to find actors who did not act in both movies. The Iron Man 1 table is called iron_1_actors, and Iron Man 2 table is called iron_2_actors. Both tables have been loaded for you and a few rows printed so you can see the structure. ''' # Merge iron_1_actors to iron_2_actors on id with outer join using suffixes iron_1_and_2 = iron_1_actors.merge(iron_2_actors, on='id', how='outer', suffixes=('_1', '_2')) # Create an index that returns true if name_1 or name_2 are null m = ((iron_1_and_2['name_1'].isnull()) | (iron_1_and_2['name_2'].isnull())) # Print the first few rows of iron_1_and_2 print(iron_1_and_2[m].head())
true
54b5f02e53d3efd052db0afc45090a8fe64afeaf
Baidaly/datacamp-samples
/4 - manipulating dataframes with pandas/Advanced indexing/indexing multiple levels of a MultiIndex.py
1,251
4.40625
4
''' Looking up indexed data is fast and efficient. And you have already seen that lookups based on the outermost level of a MultiIndex work just like lookups on DataFrames that have a single-level Index. Looking up data based on inner levels of a MultiIndex can be a bit trickier. In this exercise, you will use your sales DataFrame to do some increasingly complex lookups. The trickiest of all these lookups are when you want to access some inner levels of the index. In this case, you need to use slice(None) in the slicing parameter for the outermost dimension(s) instead of the usual :, or use pd.IndexSlice. You can refer to the pandas documentation for more details. For example, in the video, Dhavide used the following code to extract rows from all Symbols for the dates Oct. 3rd through 4th inclusive: stocks.loc[(slice(None), slice('2016-10-03', '2016-10-04')), :] Pay particular attention to the tuple (slice(None), slice('2016-10-03', '2016-10-04')). ''' # Look up data for NY in month 1: NY_month1 NY_month1 = sales.loc[('NY', 1), :] # Look up data for CA and TX in month 2: CA_TX_month2 CA_TX_month2 = sales.loc[(['CA', 'TX'], 2), :] # Look up data for all states in month 2: all_month2 all_month2 = sales.loc[(slice(None), 2), :]
true
1a38c16fa5871fa4e14d901d5cae75f840d35a42
rbanders/ThinkPython2
/Exercise 5.14.5.py
712
4.34375
4
"""Exercise 5 Read the following function and see if you can figure out what it does (see the examples in Chapter 4). # infinite recursion? Then run it and see if you got it right. def draw(t, length, n): if n == 0: return angle = 50 t.fd(length*n) t.lt(angle) draw(t, length, n-1) t.rt(2*angle) draw(t, length, n-1) t.lt(angle) t.bk(length*n)""" import turtle def draw(t, length, n): if n == 0: return angle = 50 t.fd(length*n) t.lt(angle) draw(t, length, n-1) t.rt(2*angle) draw(t, length, n-1) t.lt(angle) t.bk(length*n) bob = turtle.Turtle() draw(bob, 10, 10) turtle.mainloop() # makes a lung/kidney shaped object
true
44201a93658037168faeeec995f51ef1f99190d1
tony-andreev94/codewars_repo
/22. Rot13 5 kyu.py
697
4.5625
5
# Rot13 # https://www.codewars.com/kata/530e15517bc88ac656000716 # ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it. # If there are numbers or special characters included in the string, they should be returned as they are. def rot13(message): encrypted = "" for each in message: if each.isalpha(): each_ord = ord(each) each_ord += 13 if each.islower() and each_ord > 122 or each.isupper() and each_ord > 90: each_ord -= 26 encrypted += chr(each_ord) else: encrypted += each return encrypted print(rot13('test')) print(rot13('TEST'))
true
5fd89900f1defbfd7538322b050cb2440a7e65a1
Donutellko/PIS
/DZ1.1/Поясняющие мини ДЗ/hometask5.py
2,648
4.375
4
""" В течени практики, мы с вами учились писать такие фигуры: = == === ==== ===== Для этого мы выясняли какие символы в них есть, сколько их и как они изменяются и использовали for Например здесь быд такой код """ for i in range(1, 7): print(i*"=") """ а в таком случае = == === ==== ===== ====== код выглядед так: (сколько-то пробелов + сколько-то '=') """ for i in range(1, 7): print((7-i)*" " + i*"=") ########################################## # TODO задание 1 ########################################## """Напищите код, изображающий фигуру ====== ===== ==== === == = """ print("Результат задания 1") c = 5 for i in range(c): print(i * " " + (c - i) * "=") ########################################## # конец задания ########################################## ########################################## # TODO задание 2 ########################################## """Напищите код, изображающий фигуру = === ===== ======= ========= (подумайте о том, из сокольки частей состоит фигура, например x*" " + y*"=" + z * " ") """ print("Результат задания 2") c = 5 for i in range(c): print((c - i) * " " + (i * 2 + 1) * "=" + (c - i) * " ") ########################################## # конец задания ########################################## ########################################## # TODO задание 3 ########################################## """Напищите код, изображающий фигуру ========= ======= ===== === = """ print("Результат задания 3") c = 5 for i in range(c - 1, -1, -1): print((c - i) * " " + (i * 2 + 1) * "=" + (c - i) * " ") ########################################## # конец задания ########################################## ########################################## # TODO задание 4 дополнительное ########################################## """Напищите код, любую красивую фигуру по вашему желанию """ print("Результат задания 4") for i in range(30): print(i * 'A' + i * '!') ########################################## # конец задания ##########################################
false
5211e6de8bed6e07e67cee03fce7443a464f8059
tarungoyal1/practice-100
/8 - sort words.py
519
4.25
4
# Question 8 # Level 2 # # Question: # Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. # Suppose the following input is supplied to the program: # without,hello,bag,world # Then, the output should be: # bag,hello,without,world def main(wordlist): wordlist.sort() print(','.join(wordlist)) if __name__ == '__main__': words = [w.strip() for w in input("Enter words:").split(',')] main(words)
true
8707c1e9c1b96dc9ddf8742bb947b2c224632821
kush-x7/Python-notes
/for_loops/for_loop.py
660
4.125
4
ruits = ["Apple", "Peach", "Pear"] for fruit in fruits: ->fruit is a new variable which will store particular list item one by one print(fruit) print(fruit + " Pie") print(fruits) for number in range(1, 11): ->range 1-10 print(number, end=' ') print('\n') # Don't change the code below student_scores = input("Input a list of student scores: ").split() for n in range(0, len(student_scores)): student_scores[n] = int(student_scores[n]) # Write your code below this row maximum = -1 for score in student_scores: if score > maximum: maximum = score print(f'The highest score in the class is: {maximum}')
true
6cde8b9df6e948c1b6830e07d1ca0846077d76e0
kush-x7/Python-notes
/creating_function/creating_function.py
640
4.28125
4
def my_function(): ->definning my function print("Hello") print("Bye") sum=2+3 return sum my_function() ->calling my function -------------------------------------------------- def greet_with(name, location): ->definning a function which takes input while calling print(f'Hello {name}') print(f'WHat is it like in {location}?') greet_with("Jack Bauer", "Nowhere") ->sendinfg proper input while calling greet_with("Nowhere", "Jack Bauer") print() greet_with(name="Angela", location="London") ->assigning new variable name with some value greet_with(location="London", name="Angela")
true
c67edae9171d406e4a87459a3a73fd044085025a
biao111/learn_python
/branch/sample2.py
622
4.3125
4
#等值判断 if 1 == 1: print("1等于1") else: print("1不等于1") b = 1 == 1 print(b) print(1 == 1.0)#这里不用区分数值的类型 print("abc" == "Abc")#字符串无法比较 print("abc".lower() == "abc".lower())#将字符串都转移小写,进行判断 print(" abc".strip() == "abc".strip())#将返回无空格的字符串 print(str(1) == "1")#将某一类型转化另一类型,两者保持相同的类型 #数字与布尔表达式的等值比较 #数字0表示False,非0表示True print(0 == False) print(1 == True) if 3-2: print("成立") else: print("不成立")
false
5f27103e2423c71f4f94f867fc71851897964d45
biao111/learn_python
/function/sample2.py
997
4.125
4
#函数的形参与实参 #参数救赎函数的输入的数据,在程序运行时根据参数不同执行代码 def print_verse(verse_name,is_show_title,is_show_dynasty):#形参:约束 #函数体 if verse_name == "悯农":#实参:传值,格式必须按照形参所规定的 if is_show_title == True: print("静夜思-李白") if is_show_dynasty == True: print("唐朝") print("锄禾日当午") print("汗滴禾下土") print("谁之盘中餐") print("粒粒皆辛苦") elif verse_name == "再别康桥": if is_show_title == True: print("再别康桥-徐志摩") if is_show_dynasty == True: print("民国") print("轻轻的我走了") print("正如我轻轻地来") print("挥一挥手") print("不带走一片云彩") print_verse('悯农',True,False) print(",,,") print_verse('再别康桥',True,True)
false
ba8c71be720d66891d7ee93ece372245e80b5e48
calvar122/EXUAGO2021-VPE-L1
/0922/juanl.magana/mes_letra.py
1,233
4.1875
4
#!/usr/bin/env python3 # c-basic-offset: 4; tab-width: 8; indent-tabs-mode: nil # vi: set shiftwidth=4 tabstop=8 expandtab: # :indentSize=4:tabSize=8:noTabs=true: # # SPDX-License-Identifier: GPL-3.0-or-later """ Ejemplo de un modulo """ from ast import literal_eval def main(): """ Funcion main para la conversion de numero de mes a nombre del mes """ #Lectura del numero del mes mes = literal_eval(input("Ingrese el numero del mes\n")) #Impresion en letra del mes if mes == 1: print("el mes es Enero") elif mes == 2: print("el mes es Febrero") elif mes == 3: print("el mes es Marzo") elif mes == 4: print("el mes es Abril") elif mes == 5: print("el mes es Mayo") elif mes == 6: print("el mes es Junio") elif mes == 7: print("el mes es Julio") elif mes == 8: print("el mes es Agosto") elif mes == 9: print("el mes es Septiembre") elif mes == 10: print("el mes es Octubre") elif mes == 11: print("el mes es Noviembre") elif mes == 12: print("el mes es Diciembre") #else: print("Error: Introduce un valor entre 1 y 12") if __name__ == "__main__": main()
false
ae57eec7b6424e0894a3558ca6ebe4f9487d67b0
calvar122/EXUAGO2021-VPE-L1
/0922/gustavo.solorio/mayor_de_dos_numeros.py
516
4.125
4
#!/usr/bin/env python3 # vi: set shiftwidth=4 tabstop=8 expandtab: # Autor Gustavo Alejandro Solorio Ramos} #Descripcion del programa e ingreso de datos print("***Programa para comparar 2 numeros***\n") Numero1 = eval(input("Ingresa el primer numero: ")) Numero2 = eval(input("Ingresa el segundo numero: ")) #Comparacion de ambos numeros para arrojar el resultado print("El numero 1 es mayor que el Numero2") if Numero1 > Numero2 else print ("El Numero2 es mayor que el Numero1") if Numero2 > Numero1 else print("Los numeros son iguales")
false
7a0a7e4d604364966952cf5c3b9b50d751e5b31d
zkhorozianbc/LRU-Cache
/linked_list.py
2,896
4.125
4
from typing import Optional from node import Node class LL: """ Full implementation of doubly linked list """ def __init__(self): self.head = None #type: Optional[Node] self.tail = self.head #type: Optional[Node] self.ref_map = {} #type: Dict[str,Node] def size(self): """ Returns current size of linked list by taking length of ref_map """ return len(self.ref_map) def get(self,key: int) -> Optional[Node]: """ Get but don't pop node in list. Return None if doesn't exist """ if key not in self.ref_map: return None return self.ref_map[key] def push(self,n : Node) -> None: """ Add new Node n to end of list. """ #save reference to tail prev_tail = self.tail n.prev = prev_tail #set tail ref to n self.tail = n #set previous tail next ref to new tail #or set head ref to new tail if prev_tail is not None: prev_tail.next = self.tail else: self.head = self.tail #update ref map with n self.ref_map[n.key] = n def pop(self, key: int) -> Optional[Node]: """ Remove node from list with specified key """ #if key not in ref map, then node is not in list #return None n = self.get(key) if n is None: return None prev_node = n.prev next_node = n.next #set prev_node's next ref to next node #or set head to next_node if n is head (i.e. prev_node is None) if prev_node is None: self.head = next_node else: prev_node.next = next_node #set next_node's prev ref to prev_node #or set tail ref to prev_node if n is tail (i.e. next_node is None) if next_node is None: self.tail = prev_node else: next_node.prev = prev_node #delete n from ref map del self.ref_map[key] n.next = None n.prev = None return n def pop_head(self) -> None: if self.head is not None: self.pop(self.head.key) def __str__(self) -> str: s = "" s += "Linked List:\n" trav = self.head while trav is not None: s += str(trav) trav = trav.next s += "---------" return s def print_forward(self) -> None: print("Linked List:") trav = self.head while trav is not None: print(str(trav)) trav = trav.next print("---------") def print_reverse(self) -> None: print("Linked List in Reverse:") trav = self.tail while trav is not None: print(str(trav)) trav = trav.prev print("---------")
true