blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
1b788ed26371d117fb008e34947901a28423aebd
leilalu/algorithm
/剑指offer/第二遍/08.二叉树的下一个节点.py
1,115
4.15625
4
""" 题目: 给定一棵二叉树和其中的一个节点,如何找【中序遍历】序列的下一个结点? 树中的结点除了有两个分别指向左、右子结点的指针,还有一个指向父结点的指针。 """ def FindNextNode(pNode): """" 如果是根结点:如果有右结点,返回右结点 如果没有右结点,是否有父结点: 如果有父结点: 它是左子结点:返回父结点 它是右子结点:返回父结点的父结点,直到某个父结点是左子结点 ...
false
78e05511a05b0ab901e8772cc04b86aa29a26a40
leilalu/algorithm
/剑指offer/第五遍/59-2.队列的最大值.py
1,219
4.125
4
""" 请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。 若队列为空,pop_front 和 max_value 需要返回 -1 示例 1: 输入: ["MaxQueue","push_back","push_back","max_value","pop_front","max_value"] [[],[1],[2],[],[],[]] 输出: [null,null,null,2,1,2] 示例 2: 输入: ["MaxQueue","pop_front","max_value"] [[],[],[]] 输...
false
3500394cc1da77913ec3752c8bb2d29b11b1f29b
justien/CourseraPython
/ch6_Test0.py
1,106
4.15625
4
# -*- coding: utf8 -*- # justine lera 2016 # Python Specialisation - Coursera # 234567890123456789012345678901234567890123456789012345678901234567890123456789 print "==================================================" print "Chapter 6: Strings Assignment" print print # Comment comment print """ 6.5 Write code usin...
true
ce3c4a0371a029dbd273360dbc52835b11c2cb33
shaoda06/python_work
/Part_I_Basics/exercises/exercise_9_4_number_served.py
1,650
4.4375
4
# 9-4. Number Served: Start with your program from Exercise 9-1 (page 166). # Add an attribute called number_served with a default value of 0. Create an # instance called restaurant from this class. Print the number of customers the # restaurant has served, and then change this value and print it again. # Add a method ...
true
888a1e66add51623a4a7ca61c432ffaf2e7306ac
shaoda06/python_work
/Part_I_Basics/examples/example_2_3_Strings.py
1,245
4.625
5
# 2.3.1 Changing Case in a String with Methods name = "ada lovelace" print(name.title()) print(name.upper()) print(name.lower()) # 2.3.2 Combining or Concatenating Strings first_name = "ada" last_name = "lovelace" full_name = first_name + " " + last_name print(full_name) print("Hello, " + full_name.title() + "!") mes...
true
05e07093f6d271ffc57bebbf4fd0c857e58be4a1
shaoda06/python_work
/Part_I_Basics/exercises/exercise_5_10_checking_usernames.py
1,310
4.28125
4
# 5-10. Checking Usernames: Do the following to create a program that simulates # how websites ensure that everyone has a unique username. # • Make a list of five or more usernames called current_users. # • Make another list of five usernames called new_users. Make sure one or # two of the new usernames are also in the...
true
1525ef3a80fe96f54fd4fb09b7491abaf15f3118
shaoda06/python_work
/Part_I_Basics/exercises/exercise_5_7_favorite_fruit.py
597
4.40625
4
# 5-7. Favorite Fruit: Make a list of your favorite fruits, and then write a series of # independent if statements that check for certain fruits in your list. # • Make a list of your three favorite fruits and call it favorite_fruits. # • Write five if statements. Each should check whether a certain kind of fruit # is ...
true
c90cafde1b6aaa92f509d27efb3e77f47151ad0d
shaoda06/python_work
/Part_I_Basics/exercises/exercise_6_4_glossary_2.py
668
4.5
4
# 6-4. Glossary 2: Now that you know how to loop through a dictionary, clean # up the code from Exercise 6-3 (page 102) by replacing your series of print # statements with a loop that runs through the dictionary’s keys and values. # When you’re sure that your loop works, add five more Python terms to your # glossary. W...
true
9334659921bff17abfd27f4ee846e4266df22a80
shaoda06/python_work
/Part_I_Basics/examples/example_7_1_1_greeter.py
691
4.375
4
# Writing Clear Prompts # Each time you use the input() function, you should include a clear, # easy-to follow prompt that tells the user exactly what kind of information # you’re looking for. Any statement that tells the user what to enter should # work. For example: prompt = "If you tell us who you are, we can perso...
true
3896dfec904e99bf3baa8f8bbb62a60a5a5f9fc8
shaoda06/python_work
/Part_I_Basics/exercises/exercise_3_5_changing_guest_list.py
930
4.15625
4
# 3-5. Changing Guest List: You just heard that one of your guests can’t make the # dinner, so you need to send out a new set of invitations. You’ll have to think of # someone else to invite. # • Start with your program from Exercise 3-4. Add a print statement at the # end of your program stating the name of the guest ...
true
826d693bb54c1320ddea28370ceb07e0696dc487
shaoda06/python_work
/Part_I_Basics/exercises/exercise_6_2_favorite_numbers.py
676
4.25
4
# 6-2. Favorite Numbers: Use a dictionary to store people’s favorite numbers. # Think of five names, and use them as keys in your dictionary. Think of a # favorite number for each person, and store each as a value in your # dictionary. Print each person’s name and their favorite number. For even # more fun, poll a few ...
true
fe792070d524789aa7b9759fbe1be9a394c1e379
shaoda06/python_work
/Part_I_Basics/exercises/exercise_10_7_addition_Calculator.py
847
4.125
4
# 10-7. Addition Calculator: Wrap your code from Exercise 10-6 in a while loop # so the user can continue entering numbers even if they make a mistake and # enter text instead of a number. prompts = "Please enter two numbers, and I will add them together.\n" \ "Enter 'quit' to stop." while True: first_nu...
true
fb894772decf3dd8681a1bb67a4a97514f9a70f4
shaoda06/python_work
/part_II_projects/exercises/exercise_13_3_raindrops.py
1,947
4.21875
4
# 13-3. Raindrops: Find an image of a raindrop and create a grid of raindrops. # Make the raindrops fall toward the bottom of the screen until they disappear. import sys import pygame from pygame.sprite import Sprite class Screen: def __init__(self): self.screen_width = 1200 self.screen_height = ...
true
399056e76c322c0401c5e7e41fe7817fd7f20ac3
shaoda06/python_work
/Part_I_Basics/examples/example_10_3_7_word_count.py
1,369
4.375
4
# 10.3.7 Working with Multiple Files def count_words(file_name): """Count the approximate number of words in a file.""" try: with open(file_name) as file_object: contents = file_object.read() except FileNotFoundError: msg = "Sorry, the file " + file_name + " dose not exist." ...
true
c6a008188c768f9d5266406123eb5f1c3497b389
shaoda06/python_work
/Part_I_Basics/exercises/exercise_3_6_more_guests.py
1,250
4.59375
5
# 3-6. More Guests: You just found a bigger dinner table, so now more space is # available. Think of three more guests to invite to dinner. # • Start with your program from Exercise 3-4 or Exercise 3-5. Add a print # statement to the end of your program informing people that you found a # bigger dinner table. # • Use i...
true
13241be97d33f44f265445186c56be2048e9a1e9
shaoda06/python_work
/Part_I_Basics/examples/example_9_2_1_car.py
2,058
4.6875
5
# 9.2.1 The Car Class # Let’s write a new class representing a car. Our class will store information # about the kind of car we’re working with, and it will have a method that # summarizes this information: # 9.2.2 Setting default value for an attribute # Line #24 is to initialize attribute with a default value 0 # Li...
true
691552139e74d957439f164a1315dddced1b9414
TheVibration/pythonprocedures
/findelement.py
606
4.15625
4
# find_element takes two inputs # lst and v. lst is a list of # any type and v is a value of any # type. find_element will go through # lst and find the index at which # v exists. If v isn't in lst, -1 # will be returned. def find_element(lst,v): counter = 0 for i in lst: pos = i.find(v) if p...
true
db2ef3de811092b4553f42147f277492ec2c3c80
G0nov4/Programacion
/Python/Algoritmia/Metodo_de_Seleccio.py
642
4.15625
4
''' Ordenamiento por seleccion Es un algoritmo que consisite en ordenar los elementos de manera ascendente o desendente Funcionamiento: -Buscar eldato mas pequeño de la lista - Intercambiarlo por el actual - Seguir buscando el mas pequeño de la lista - Intercambiarlo por el actual - Esto se repite sucesivamente ''...
false
5b8cf851dff26a603f872f81058b0846e8582fa4
Dhruvin1/covid19
/random_walk.py
1,299
4.1875
4
from random import choice import settings class Randomwalk(): """ A class to generate random walks.""" def __init__(self, x=0, y=0): """Initiate attributes of a walk""" # All walks start at (x,y) self.is_infected = False self.x_values = [] self.y_values = [] s...
true
d22d27eddc509404b4e15a97edee44d2eaac8330
Shiven004/learnpython
/Numbers/fibonacci_value.py
585
4.46875
4
#!/usr/bin/env python3 # Fibonacci Value # Have the user enter a number # and calculate that number's # fibonacci value. def fib(x): """ Assumes x an integer >= 0 Returns Fibonacci value of x """ assert isinstance(x, int) and x >= 0 n_1, n_2, i = 1, 1, 2 while i <= x: n_new = n...
true
04b8789692ce0274401697ceb7a5ecc2a44ce030
JakeTheLion89/portfolio
/Python/word_scram.py
2,507
4.125
4
# July 23 # Learning python # Excercise in "random" module import random def wordScram(): print """Welcome to Word Scram. Choose a difficulty and unscramble 10 words! """ ## Game Dictionaies and Variables game = { "EASY" : ["night", "quill" ,"book", "wine", "grass", "fill","quilt","kind","public"...
true
5d6afa46a2c08a8462aa5f63ad54e2ee53e5e784
YHGui/CS61ASp18
/Lab/lab01/falling.py
331
4.15625
4
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 0) 1 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 """ sum = 1 while k > 0: sum = sum * n k = k - 1 n = n - 1 ...
false
ccdebc7b2dc593443b32343663ade9efe2bc5956
AntonioRoye/Beginner_Python_Projects
/madlibs.py
1,085
4.15625
4
adjective1 = str(input("Enter an adjective: ")) noun1 = str(input("Enter a noun: ")) verb1 = str(input("Enter a verb (past tense): ")) adverb1 = str(input("Enter an adverb: ")) noun2 = str(input("Enter a noun: ")) noun3 = str(input("Enter a noun: ")) adjective2 = str(input("Enter an adjective: ")) verb2 = str(input("En...
true
c235ad0774ff10ece5f1f7e0c90f3c03a89a0d66
JessicaReay/compound_interest_app
/calc.py
541
4.25
4
# App: compound interest calculator # Fuction: calculates monthly compound interest for custom user inputs # Author: Dan & Jess def monthly_compounding(initial, monthly, years, annual_rate): sum = initial months = years *12 #iterate through months for month in range(int(months)): # apply annua...
true
95ba9c78de1f6d7be74bba0ece2ec0d2710d70da
stellakaniaru/bootcamp
/day_3/data_types.py
765
4.3125
4
def data_type(x): ''' takes in an argument, x: -for an integer, return x ** 2 -for a float, return x/2 -for a string, return "hello" + x -for a boolean, return "boolean" -for a long, return squareroot(x) ''' #cheking for integers if type(x) == int: return x ** 2 #checking for float elif type(x) == float: ...
true
82c3aafc7d1790b02b4f3dd7bbabce51df708820
MesutCevik/adventcalendarPython
/impl/CompetitorsList.py
1,334
4.15625
4
from typing import List from impl import Competitor class CompetitorsList: competitors: List['Competitor'] = [] def add_competitor(self, competitor: Competitor): self.competitors.append(competitor) def __str__(self) -> str: competitors_in_string: str = "" for competitor in self....
true
ab0a9bc482e0034a83e008318732b818c757aa0b
smreferee/Lame-Game
/Lab2_Richard_Nolan.py
823
4.34375
4
################################################ #This is Lab 2 for COSC 1336 by Richard Nolan # #The program will display program information, # #ask and display the user name, display a menu,# #and finally confirm the menu choice. # ################################################ #Introduction to...
true
16c862609f2b52921d214facaba3e87ef050dae7
Nextc3/aulas-de-mainart
/Listas/Lista 6/q2.py
1,682
4.15625
4
''' Faça um Programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 6 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00 ou em galões de 3,6 litros, que custam R$ 25,00. • In...
false
deac9d6024ce82f36c08b88799eafbf4173ba236
Nextc3/aulas-de-mainart
/Listas/Lista 5/q4.py
202
4.125
4
numero1 = int(input("Entre com o numero1: ")) numero2 = int(input("Entre com o numero2: ")) dict_decisao = {True:numero1, False:numero2} print("Maior numero: {}".format(dict_decisao[numero1 > numero2]))
false
86ca90fd31a09060144e0a06bf68b5423967344f
rootrUW/Python210-W19
/students/KevinCavanaugh/session3/list_lab.py
1,668
4.1875
4
#!/usr/bin/env python3 # ----------------------------------------------------------------------- # # Title: List_Lab # Author: Kevin Cavanaugh # Change Log: (Who,What,When) # kcavanau, created document & completed assignment, 01/29/2019 # ----------------------------------------------------------------------- # impor...
false
aed4d6aa3e9256d4f0e43b879b23bc36a4dcab4a
JBW1997/hello-world
/数字类型.py
640
4.625
5
""" #分类:整数、浮点数、复数 #整数:python可以处理任意大小的整数 """ #交互式复赋值定义变量 num1, num2 =1, 2 print(num1,num2) #连续定义多个变量 num3 =1 num5 =num4 =num3 print(num3, num4, num5) """ 浮点数:由整数和小数组成,浮点数可能会有四舍五入的误差 """ f1 = 1.1 f2 = 2.2 print(f1 + f2) """ 复数:由实部和虚部组成,a+bj """ #数字类型转换 print(int(1.11)) print(float(1)) print(int("12...
false
ce619542d41fd7f2465eea7f4974e3c9d3c050d6
wilfort/python
/example/typles.py
717
4.375
4
# thistuple = ("apple", "banana", "cherry") print(thistuple) # thistuple = ("apple", "banana", "cherry") print(thistuple[1]) # thistuple = ("apple", "banana", "cherry") thistuple[1] = "blackcurrant" # the value is stille the same: print(thistuple) ################################################### ###############...
false
9bf185e97b1c81a0ac4fe3dd7166db777cb7a032
MatthewKosloski/starting-out-with-python
/chapters/07/03.py
371
4.59375
5
# Program 7-3 # Demonstrates how the append # method can be used to add # items to a list. def main(): name_list = [] again = 'y' while again.lower() == 'y': name = input('Enter a name: ') name_list.append(name) again = input('Add another name? (y/n): ') print() print('Here are the names you entered...
true
3ae72ab5b4b40599ca663c2e1c1eadbdc34904dc
MatthewKosloski/starting-out-with-python
/chapters/03/06.py
539
4.34375
4
# Program 3-6 # This program gets a numeric test score from the # user and displays the corresponding letter grade. # Variables to represent the grade thresholds A_score = 90 B_score = 80 C_score = 70 D_score = 60 # Get a test score from the user. score = int(input('Enter your test score: ')) # Determine the grade....
true
ef3fca65a2e5701628ad968b9be7c358dbb95325
MatthewKosloski/starting-out-with-python
/chapters/06/13.py
710
4.125
4
# Program 6-13 # Gets employee data from the user and # saves it as records in the employee.txt file. def main(): number_of_employees = int(input('How many employee records' + 'do you want to create? ')) employee_file = open('employees.txt', 'w') # Get each employee's data and # write it to employees.txt ...
true
519ce83fed6f9df3bc17c810db2c6ffacd79d397
MatthewKosloski/starting-out-with-python
/homework/factorial.py
415
4.1875
4
# Matthew Kosloski # Exercise 4-11 # CPSC 3310-01 SP2018 num = int(input('Enter a number >= 0 for factorial: ')) while num != -1: # Calculate and display factorial if number is >= 0 if num >= 0: factorial = 1 for i in range(1, num + 1): factorial *= i print('Factorial of', num, 'is', factorial) prin...
true
5bee66cb2090e4b9dba3669b3aae497b9a42227d
MatthewKosloski/starting-out-with-python
/chapters/06/23.py
375
4.125
4
# Program 6-23 # Handles a ValueError exception. def main(): try: hours = int(input('How many hours did you work? ')) pay_rate = float(input('Enter your hourly pay rate: ')) gross_pay = hours * pay_rate print(f"Gross pay: ${format(gross_pay, ',.2f')}") except ValueError: print('ERROR: Hours worked and h...
true
d43e8b23538cf42f944943865fa14593c29b8071
MatthewKosloski/starting-out-with-python
/chapters/04/12.py
446
4.4375
4
# Program 4-12 # This program calculates the sum of a series # of numbers entered by the user. # The maximum number max = 5 # Initialize the accumulator total = 0 # Explain the purpose of the program print('This program calculates the\nsum of', max, 'numbers you will enter.\n') # Get the numbers and accumulate them...
true
30bd227c3394fc4f470e851c54f9a2740e4068ed
MatthewKosloski/starting-out-with-python
/chapters/07/07.py
508
4.15625
4
# Program 7-7 # Calculates the gross pay for each # barista. NUM_EMPLOYEES = 6 def main(): hours = [0] * NUM_EMPLOYEES for index in range(NUM_EMPLOYEES): print('Enter the hours worked by employee ', \ index + 1, ': ', sep='', end='') hours[index] = float(input()) pay_rate = float(input('Enter the hourly p...
true
441bee12976cb345a05b93a4d6f7e212352e9217
MatthewKosloski/starting-out-with-python
/chapters/04/01.py
632
4.15625
4
# Program 4-1 # This program calculates sales commissions. # Create a variable to control the loop keep_going = 'y' # Calculate a series of commissions while keep_going == 'y': # Get a salesperson's sales and commission rate. sales = float(input('Enter the amount of sales: ')) comm_rate = float(input('Enter the co...
true
623305636b6eabf818bdc6e4ad67cf45d15d2208
AnthonySDi/python-fizzbuzz
/main.py
758
4.34375
4
def fizzBuzz(num): ''' Receives num from main and determines if it is divisable by 3, 5, or both and prints the int with fizz, buzz, or fizzbuzz respectfully. helper function to main() keyword arguments: num: int ''' if(num % 3 == 0 and num % 5 == 0): #num is divisable by both 3 and 5 print(s...
true
05f0578d150f7fc9eb4ce6ae57fe85694657b098
SahilBastola/lab_exercise
/question no 8.py
242
4.375
4
#write a python program which accepts the radius of a circle from the user and compute the area (area of circle = pier**2 radius=float(input("Enter the value of radius:")) pie= 22/7 area = pie*radius**2 print(f"the area of circle is {area}")
true
307e4ca82c543e16d29d03cf9631961218c409ab
johnkirch123/python
/udemy-mega-course/exercises/forIteration.py
303
4.21875
4
def celsius_to_farenheit(c): if c > -273.15: return c * 9/5 + 32 else: return "Impossible temperature." #print(celsius_to_farenheit(float(input("Enter Celsius for conversion: ")))) temperatures=[10, -20, -289, 100] for temp in temperatures: print(celsius_to_farenheit(temp))
false
be1bcbb2118d393a7d7a6cfc86fe2562dc1db529
dfds/python-for-absolute-beginners
/doc_examples.py
1,123
4.3125
4
#!/usr/bin/env python3 class Person: """ This class defines a person ;) """ def __init__(self, name: str, age: int) -> None: """ This is the class constructur. :param name: The person's name. :param age: The person's age. :type name: str :type age: int ...
true
7e776d80ade377fa2bbf3ee0236be71e35966043
MarceloDL-A/Python
/10-Introduction_to_Pandas/Select_Rows_with_Logic_I_equal.py
704
4.375
4
import codecademylib import pandas as pd df = pd.DataFrame([ ['January', 100, 100, 23, 100], ['February', 51, 45, 145, 45], ['March', 81, 96, 65, 96], ['April', 80, 80, 54, 180], ['May', 51, 54, 54, 154], ['June', 112, 109, 79, 129]], columns=['month', 'clinic_east', 'clinic_north', 'clinic_so...
true
3b74a5f0b532198a85d79480fbc2fc06a4fbd896
MarceloDL-A/Python
/15-Statistics_with_NumPy/Statistics_in_NumPy/Mean_and_Logical_Operations.py
2,192
4.5
4
""" INTRODUCTION TO STATISTICS WITH NUMPY Mean and Logical Operations We can also use np.mean to calculate the percent of array elements that have a certain property. As we know, a logical operator will evaluate each item in an array to see if it matches the specified condition. If the item matches the given condition...
true
db96f54eb8dab41492a4e9fbb4d3072e96eec934
MarceloDL-A/Python
/13-Data_Visualization/Introduction_to_Seaborn/Understanding_Aggregates.py
943
4.28125
4
import codecademylib3_seaborn import pandas as pd from matplotlib import pyplot as plt import numpy as np gradebook = pd.read_csv("gradebook.csv") #Next, take a minute to understand the data youll analyze. The DataFrame gradebook contains the complete gradebook for a hypothetical classroom. Use print to examine gradeb...
true
801604eed56381f44cf18f885ac7f3a9ea8eba39
MarceloDL-A/Python
/14-Statistics_with_Python/Quatiles,_Quantiles,_and_Interquartile_Range/Quartiles_Interquartile.py
1,597
4.71875
5
""" Quartiles The interquartile range is the difference between the third quartile (Q3) and the first quartile (Q1). For now, all you need to know is that the first quartile is the value that separates the first 25% of the data from the remaining 75%. The third quartile is the opposite it separates the first 75% of...
true
cf2293fa6dc26162ce73a2c33cbc8bdd6c580d22
MarceloDL-A/Python
/14-Statistics_with_Python/Histograms/Bins_and_Count I.py
2,238
4.28125
4
""" Bins and Count I In the previous exercise, you found that the earliest transaction time is close to 0, and the latest transaction is close to 24, making your range nearly 24 hours. Now, we have the information we need to start building our histogram. The two key features of a histogram are bins and counts. Bins A...
true
04c97880d4fee65117627e674f1323fd109c2854
MarceloDL-A/Python
/14-Statistics_with_Python/Histograms/Range.py
2,173
4.59375
5
""" HISTOGRAMS Range Histograms are helpful for understanding how your data is distributed. While the average time a customer may arrive at the grocery store is 3 pm, the manager knows 3 pm is not the busiest time of day. Before identifying the busiest times of the day, its important to understand the extremes of your...
true
80b1669509b72ce5219a27ab27d7af53c0887503
MarceloDL-A/Python
/13-Data_Visualization/Introduction_to_Matplotlib/Modify_Ticks.py
870
4.125
4
import codecademylib from matplotlib import pyplot as plt month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep","Oct", "Nov", "Dec"] months = range(12) conversion = [0.05, 0.08, 0.18, 0.28, 0.4, 0.66, 0.74, 0.78, 0.8, 0.81, 0.85, 0.85] plt.xlabel("Months") plt.ylabel("Conversion") plt.plot(m...
true
d6c07151daabf0c745ea0b53d3309a2a5408d995
MarceloDL-A/Python
/19-Beautiful_Soup/10_of_11_Reading_Text.py
2,953
4.53125
5
""" WEB SCRAPING WITH BEAUTIFUL SOUP Reading Text When we use BeautifulSoup to select HTML elements, we often want to grab the text inside of the element, so that we can analyze it. We can use .get_text() to retrieve the text inside of whatever tag we want to call it on. <h1 class="results">Search Results for: <span c...
true
8e8c22f5ae1f42fafdeea4aaa32af32a85fc434e
MarceloDL-A/Python
/20-Machine_Learning_-_Supervised_Learning/5-K_Nearest_Neighbor_Regression/01_of_04_Regression.py
2,121
4.46875
4
from movies import movie_dataset, movie_ratings def distance(movie1, movie2): squared_difference = 0 for i in range(len(movie1)): squared_difference += (movie1[i] - movie2[i]) ** 2 final_distance = squared_difference ** 0.5 return final_distance def predict(unknown, dataset, movie_ratings, k): distances...
true
1118eca63a9f6b4d06db8d7abef1851fc16bde02
MarceloDL-A/Python
/19-Beautiful_Soup/05_of_11_Object_Types.py
1,433
4.28125
4
""" WEB SCRAPING WITH BEAUTIFUL SOUP Object Types BeautifulSoup breaks the HTML page into several types of objects. Tags A Tag corresponds to an HTML Tag in the original document. These lines of code: soup = BeautifulSoup('<div id="example">An example div</div><p>An example p tag</p>') print(soup.div) Would produce o...
true
2be072ab38c419634143e9f2cc8bba6513b1368d
MarceloDL-A/Python
/14-Statistics_with_Python/Quatiles,_Quantiles,_and_Interquartile_Range/Q1_and_Q3.py
2,292
4.71875
5
""" QUARTILES Q1 and Q3 Now that weve found Q2, we can use that value to help us find Q1 and Q3. Recall our demo dataset: [-108, 4, 8, 15, 16, 23, 42][-108,4,8,15,16,23,42] In this example, Q2 is 15. To find Q1, we take all of the data points smaller than Q2 and find the median of those points. In this case, the point...
true
a4181a44e4275296d819894ef81abec72d61ac10
MarceloDL-A/Python
/14-Statistics_with_Python/Quatiles,_Quantiles,_and_Interquartile_Range/Quantiles.py
2,260
4.5
4
""" QUANTILES Quantiles Quantiles are points that split a dataset into groups of equal size. For example, lets say you just took a test and wanted to know whether youre in the top 10% of the class. One way to determine this would be to split the data into ten groups with an equal number of datapoints in each group and ...
true
ec29f3e59f81646bf22b6fefb780636964429175
MarceloDL-A/Python
/14-Statistics_with_Python/Histograms/Histograms.py
2,291
4.34375
4
""" Histograms While counting the number of values in a bin is straightforward, it is also time-consuming. How long do you think it would take you to count the number of values in each bin for: an exercise class of 50 people? a grocery store with 300 loaves of bread? Most of the data you will analyze with histograms i...
true
44774e0e6115992fe42608c6da39b77fbeb94f58
MarceloDL-A/Python
/17-Data_Cleaning_with_Pandas/Part II/08_de_12_-_Looking_at_Types.py
1,679
4.375
4
""" DATA CLEANING WITH PANDAS Looking at Types Each column of a DataFrame can hold items of the same data type or dtype. The dtypes that pandas uses are: float, int, bool, datetime, timedelta, category and object. Often, we want to convert between types so that we can do better analysis. If a numerical category like "n...
true
557043185e919883ce22896537949df1cb4552e5
MarceloDL-A/Python
/15-Statistics_with_NumPy/Statistics_in_NumPy/Percentiles,_Part_II.py
1,940
4.5625
5
""" INTRODUCTION TO STATISTICS WITH NUMPY Percentiles, Part II Some percentiles have specific names: The 25th percentile is called the first quartile The 50th percentile is called the median The 75th percentile is called the third quartile The minimum, first quartile, median, third quartile, and maximum of a dataset a...
true
1d7378dc2e5fadcb2bbc7149bd3f92c1d5f0028c
MarceloDL-A/Python
/20-Machine_Learning_-_Supervised_Learning/7-Logistic_Regression/Logistic_Regression/10_of_11_-_Feature Importance.py
1,542
4.25
4
import codecademylib3_seaborn import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from exam import exam_features_scaled, passed_exam_2 # Train a sklearn logistic regression model on the normalized exam data model_2 = LogisticRegression() model_2.fit(exam_features_scal...
true
07097ec4eebec7c04984fe26835e8c868976f17c
manika1511/interview_prep
/linked_list/palindrome.py
2,717
4.40625
4
"""Implement a function to check if a linked list is a palindrome.""" # Node class to define linked list nodes class Node(object): # constructor to initialise node def __init__(self, data=None, next=None): self.data = data self.next = next # Linkedlist class class LinkedList(object): #met...
true
336f51c6456087da98c1e508fec295c019f2484c
manika1511/interview_prep
/array_and_strings/is_unique.py
1,703
4.34375
4
"""The complexity of converting a string to a set is O(n) as time to traverse a string of 'n' characters is O(n) and the time to add it to the hash map is O(1) and the is else loop is again O(1). Assumption: the lowercase and uppercase letters are considered same""" def all_unique(s): s = s.lower() #conv...
true
f5fe31c9f62de93f9a22a16080f37fb8d37e9e8b
manika1511/interview_prep
/linked_list/partition.py
2,083
4.1875
4
"""Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partitio...
true
901a0be5cbea7c9f0ee6294e5950ab2550e392d5
nathan5280/ndl-tools
/src/ndl_tools/list_sorter.py
2,910
4.21875
4
""" ListSorters used to control if and how Lists are sorted. Really there are only two choices. Sort or don't sort. The sorter can be applied to the List elements by the Selector that is associated with the sorter. """ from abc import abstractmethod from pathlib import Path from typing import List, Optional, Union ...
true
c472563f3f05f70fa12cbf772f3d8deacf2f2424
Fiinall/UdemyPythonCourse
/Embaded Functions/zipFunction.py
997
4.21875
4
""" Combining lists into one list. """ liste1 = [1, 2, 3, 4, 5] liste2 = [6, 7, 8, 9, 10, 11] liste3 = ["Python","Php","Java"] # sonucu [(1,6),(2,7),(3,8),(4,9),(5,10)] yapmaya çalışalım. #-------without zip funciton----- i = 0 sonuç = list() while (i < len(liste1) and i < len(liste2)): sonuç.append((liste1[i], ...
false
b14de33186c8d3f6d2f3b07602d41e34d40633cd
Fiinall/UdemyPythonCourse
/Conditional Statement/Hesap Makinesi.py
1,023
4.3125
4
print("""Welcome to Calculator Here are the operations that you can do 1. Summation 2. Extraction 3. Multiplication 4. Division Please Selecet the Operatiıon with + , - , * or / """) First_Number = float(input("What is your first number")) Operation = input("What...
false
c2aa28ef1639e050fe92756f1a7c6834d69b75f5
Fiinall/UdemyPythonCourse
/Advanced Data Structures and Object/AdvancedListsAndItsMethods.py
2,397
4.625
5
# extend() method is like append method but this help you for add whole list into another list; print("extend method; \n") list1 = [1,2,3,4] list2 = [45,6893,245,667,"asd"] list1.extend(list2) print(list1) print("---------") # insert(index,element) method inserts an element into specified index print("insert method; \n...
true
3ae1a7a089d9054ca47a6412d6834d35be1448de
EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions
/Chapter1/1.9.py
582
4.4375
4
#String Rotation; Assume you have a method i s S u b s t r i n g which checks if one word is a substring of another. #Given two strings, si and s2, write code to check if s2 is a rotation of si using only one call to isSubstring # [e.g., "waterbottle" is a rotation oP'erbottlewat"), def string_rotation(s1, s2): i...
false
037c3372719b206f9694da97f36e528b366a037a
EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions
/Chapter5/5.1.py
881
4.28125
4
#5.1 #Insertion: You are given two 32-bit numbers, N and M, and two bit positions, i and j. #Write a method to insert M into N such that M starts at bit j and ends at bit i. #You can assume that the bits j through i have enough space to fit all of M. That is, if M = 10011, # you can assume that there are at least 5 bit...
true
cf3fb2b8852de85b47b3aa67a3ae8e48b2607e76
EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions
/Chapter4/4.3.py
2,560
4.125
4
#List of Depths: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth #(e.g., if you have a tree with depth 0, you'll have 0 linked lists). from SinglyLinkedList import SinglyLinkedList class Node(): def __init__(self,value): self.right = None self.lef...
true
16c9d17f9c4cfd8f8002434d9b810182f4128b1f
EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions
/Chapter1/1.4.py
1,477
4.34375
4
#Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. #A palindrome is a word or phrase that is the same forwards and backwards. #A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words. #First I need to prep...
true
6fd6268052ce61de5d97fcf138e7ff611fadc1ad
mattfisc/python
/quicksort.py
1,383
4.125
4
# This function takes first element as pivot, places # the pivot element at its correct position in sorted # array, and places all smaller (smaller than pivot) # to left of pivot and all greater elements to right # of pivot import random def partition(lst, a ,b): random_index = random.randint(a,b) # pick ra...
true
99d7bceef1cd86093a076d4eba62beb240b06c6b
mihawkeyes/practice-pro
/python/sieveofsundaram.py
1,101
4.625
5
# Python3 program to print # primes smaller than n using # Sieve of Sundaram. # Prints all prime numbers smaller def SieveOfSundaram(n): # In general Sieve of Sundaram, # produces primes smaller # than (2*x + 2) for a number # given number x. Since we want # primes smaller than n, we # reduce n to ha...
true
826550ee62029fff7f61bf987598ee0125413a49
tsamridh86/RSA
/decryptor.py
1,387
4.375
4
# this code converts cipher text into msg & displays it to the user # this functions converts the cipherText into number format plainText def decrypt( cipherText, publicKey, divisorKey , blockSize): i = 0 lenCipherText = len(cipherText) plainText = [] while i < lenCipherText: copyBlockSize = blockSize numArr =...
true
b733170325793d63b2db089bb0a4a31dd5d36c55
dimaape/GeekBrains_Python_Course
/Lesson_1/GB_Py_HW_1_1.py
1,252
4.34375
4
# Задание 1.1 # Поработайте с переменными, создайте несколько, выведите на экран print("Поработайте с переменными, создайте несколько, выведите на экран.\n") var_a = 0 var_b = "some text" var_c = 10 var_d = "some text again" print(var_a, var_b, var_c, var_d, sep='\n') # Запросите у пользователя несколько ...
false
e6fd95ce117cb9035049aac5bc970dbf7a08f9e3
icadev/Python-Projects
/ex2.py
691
4.46875
4
print "I will now count my chickens:" print "Hens", 2.5 + 3.0 / 6.0 #make the operation print "Roosters", 10.0 - 2.5 * 3.0 % 4.0 #make the operation print "Now I will count the eggs:" print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 -1.0 / 4.0 + 6.0 #make the operation print "Is it true that 3.0 + 2.0 < 5.0 - 7.0?...
true
b1437f271f59cca4f92fb6e111a96f2579bdb93a
icadev/Python-Projects
/my_game.py
1,628
4.40625
4
class Person: """Represents a robot, with a name.""" # A class variable, counting the number of robots population = 0 def __init__(self, name, age, job): """Initializes the data.""" self.name = name self.age = age self.job = job print("(Presenting you...
true
47b5e7d992beeeae927c07f8ddfcdbdbefa6d345
SudheshSolomon1992/Hackerrank_30_days_Coding_Challenge
/Day_7_Arrays.py
360
4.34375
4
#!/bin/python3 def main(): number_of_elements = int(input()) element = [int(n) for n in input().split()[:number_of_elements]] reverse(element) def reverse(array): # reversed function is used to reverse an array in python3 for element in reversed(array): print (element, end=" ")...
true
0b5051386fd85a67cf88c88cabb2d63d1f954bbe
Tbeck202/PythonCourse
/VariablesAndStrings/converter.py
207
4.34375
4
print("Enter a distance in Kilometers, and I'll convert it to miles!") kms = input() miles = float(kms)/1.60934 round_miles = round(miles, 2) print(f"Ok, {kms} kilometers are equal to {round_miles} miles!")
true
22c960b54ebe64b8083645821782ad6852c4436c
Tbeck202/PythonCourse
/Tuples_and_sets/sets.py
1,202
4.15625
4
# cities = ['Los Angeles', 'Boulder', 'Kyoto', 'Florence', 'Santiago', # 'Los Angeles', 'Shanghai', 'Boulder', 'San Francisco', 'Oslo', 'Tokyo'] # no_duplicates = set(cities) # # print(no_duplicates) # no_duplicates.add('Portland') # print(no_duplicates) # no_duplicates.remove('Shanghai') # print(no_dupli...
false
cc0cc27653fcbe55bc65ecca72da02037956b473
DharmilShahJBSPL/DharmilShah
/python/dictionary_ex.py
620
4.5
4
print('using Dictionary example') print('') di={'abc':'1','x':'2','jkl':'3'} print (di) print(di.keys()) print(di.values()) print('to print particaular value of key then use this ') print(di['abc']) print(di['jkl']) print('') print('') print('to print more than 1 key value then use this ') print((di['abc']),(di['jkl']...
true
a8674b4146e7fb058d70e0e1900a14d2b4f0042e
DiegoC386/Algoritmos_Diego
/Taller Estructuras de Control Selectivas/Ejercicio_9.py
2,123
4.3125
4
""" En una tienda efectúan un descuento a los clientes dependiendo del monto de la compra. El descuento se efectúa con base en el siguiente criterio: a. Si el monto es inferior a $50.000 COP, no hay descuento. b. Si está comprendido entre $50.000 COP y $100.000 COP inclusive, se hace un descuento del 5%. c. Si está com...
false
5b4841a57f777204f1a4a2235901b6c0ce723858
tlofreso/adventofcode2020
/01/expense_report.py
1,284
4.1875
4
def values(): """Reads input, and returns all values as a sorted list of integers""" with open('input.txt') as f: lines = f.read().splitlines() my_input = [int(i) for i in lines] my_input.sort() return my_input def computer(): result = 2020 n1_possible = [] n2_pos...
true
00f75399b13208b8b2c648c978fb08065306f427
OffensiveCyber/Learn_Python_the_practical_way
/T2_List.py
1,063
4.5625
5
cars = ['nissan', 'ford', 'honda','tesla', 'Volkswagen'] #print all cars name from the list print cars[0] print cars[1] print cars[2] print (cars[3].title()) #title() method displays word with first letter in caps print "Hello " + cars[0] + ", What is your milage?" #concetation demonstrated print "Hello " + cars...
true
36d59d8a1a2efc18dba383797d90efbbf4bed1ee
thecoderarnav/C-98
/counting.py
340
4.28125
4
def countingwords(): fileName = input("ENTER FILE NAME") numberofcharacters = 0 file= open(fileName,"r") for line in file: data = file.read() #words = line.split() numberofcharacters = len(data) print ("Number of Characters") print(numberofcharacters) countingw...
true
bcd2e33743c0415435f74f87b1c32ba9f3450e72
chyidl/leetcode
/0098-validate-binary-search-tree/validate-binary-search-tree.py
1,442
4.21875
4
# Given the root of a binary tree, determine if it is a valid binary search tree (BST). # # A valid BST is defined as follows: # # # The left subtree of a node contains only nodes with keys less than the node's key. # The right subtree of a node contains only nodes with keys greater than the node's key. # Both the l...
true
e7df3aa457b5bdcfa8b0e8c35b431f31313c886e
septos/learnpython
/sets.py
705
4.21875
4
''' Sets 1.Unordered 2.Unindexed 3.newset = {orange,banana,fig} ''' new_fruits = {"lemon","fig","cherry"} print(new_fruits) print("-------------------------------------------------------------------------------") #for loop for x in new_fruits: print(x) print("------------------------------------------------------...
true
81a03cfdb9a4d88e8ad179c7b7d357a34a08e02d
learning-laboratory/cursos
/python/open-source-it/pratice/exercise_03.py
370
4.125
4
age = int(input('Age: ')) gender = input('Genger[M/F]: ') gender = gender.upper() if age < 18: if gender == 'M': print('son') else: print('daughter') elif 18 <= age < 65: if gender == 'M': print('father') else: print('mother') else: if gender == 'M': print('gr...
false
e926d5b9a9f8e73cf5e0277853d7414fee12a5dc
navaneeth2324/256637_DailyCommits
/secondsmallest.py
245
4.1875
4
# Write a Python program to find the second smallest number in a list list=[] n=int(input("Size of list : ")) for i in range(0,n): item=int(input()) list.append(item) print("List : ",list) list.sort() print("Second Smallest :",list[1])
true
2c7f55a161747f33675e72d3d60d4464640521a2
Michal-Kok/WAR2021
/python tasks/chris.py
813
4.25
4
def name_in_str(sentence, name): return """ Simple as that, your task is to find name within given sentence, like in the example: Across the rivers. --- chris c h ri s Make it case sensitive. Letters must appear in the right order. """ assert name_in_str("Across the rivers", "chris") is True assert n...
true
b237e9da29896ffa0fee894b8d81d2cbb20bbec9
AndresNunezG/ejercicios_python_udemy
/ejercicio_16.py
570
4.34375
4
""" Ejericio 16. - Solicitar al usuario un texto o cadena de caracteres - Devolver en pantalla el texto de entrada al revés: Ej: Entrada: 'hola' Salida: 'aloh' """ #Solicitar texto al usuario print('Ingrese el texto a ser invertido!') texto = input('') #Invertir el texto #Método 1. texto_inv = te...
false
cf37e6f4fd508e8ff33efd07e80e64fcf84af3ee
shaheryarshaikh1011/tcs_prep
/prime.py
565
4.125
4
lower = int(input("Enter Lower bound of the range")) upper = int(input("enter Upperbound of the range")) print("Prime numbers between", lower, "and", upper, "are:") #initialize variable to store sum of prime numbers sum=0; for num in range(lower + 1, upper ): # all prime numbers are greater than 1 if num == 1: ...
true
d557718e840f2b0e9e3e7dd7fe350649122e02a3
leosantosx/exercicios-em-python
/exercicios/ex87.py
1,057
4.1875
4
""" EXERCÍCIO 087: Mais Sobre Matriz em Python Aprimore o desafio anterior, mostrando no final: A) A soma de todos os valores pares digitados. B) A soma dos valores da terceira coluna. C) O maior valor da segunda linha. 0 [_][_][_] 1 [_][_][_] 2 [_][_][_] 0 1 2 """ line = int(input('Quantas linhas tem a Matriz? '...
false
8fa3df7a5aea16aaf2b22007b378947ca0868977
leosantosx/exercicios-em-python
/exercicios/ex77.py
562
4.125
4
""" EXERCÍCIO 077: Contando Vogais em Tupla Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são as suas vogais. """ palavras = ('Mercado','morango', 'banana', 'Notebook', 'carro', 'celular') for palavra in palavras: ...
false
e0b2da770c4f6765119b599ea4812323b8598f00
leosantosx/exercicios-em-python
/exercicios/ex74.py
532
4.1875
4
""" EXERCÍCIO 074: Maior e Menor Valores em Tupla Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla. """ from random import randint numeros = (randint(0,9),randint(0,9),randint(0...
false
1ff8f127e7d8de6397cfab3db966ec1967b8f6f2
leosantosx/exercicios-em-python
/exercicios/ex36.py
699
4.15625
4
""" DESAFIO 036: Aprovando Empréstimo Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário, ou então o empréstimo será negado. """ casa = float(input('Qual o...
false
a65b1ff98ba3df1b73a3c854fb04278ac804ff2f
chrishendrick/Python-Bible
/cinema.py
1,113
4.25
4
# cinema ticketing # working with dictionaries, while loops, if/elif/else # "name":[age,tickets] films = { "The Big Lebowski":[17,5], "Bourne Identity":[18,5], "Tarzan":[15,3], "Ghost Busters":[12,5] } while True: choice = input("Which film would you like to watch?: ").strip().title() if...
true
bf44413ec101466043c14961e255cd0dc1ab5af7
dimitrisgiannak/Python-Private_School-Part_B
/files/PV_methods2.py
1,081
4.1875
4
from datetime import date ''' For details check README ''' error_message3 = 'You must input an integer' def getdate(datetime_ , statement , empty): while True: date1 = 0 try: print_message = f'Please write the {datetime_} of the {statement} ' date = input(print_message +...
true
f2dc16e373f8c6e18f30bb0f7ffa3c0985b16355
modukurusrikanth/python-inventateq
/dictinory_ex1.py
286
4.3125
4
#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 d = {'KA':'BLR','MH':'mum','AP':'AMR','noodles':['yippeee','maggi']} for k,v in d.items(): print(" the capital of {} is: {}".format(k,v)) for k in d.values(): print("All the values of dictionary is:{}".format(k))
false
a5b2fdd0a9f78f160f40d7975cab2c57cea2590f
modukurusrikanth/python-inventateq
/biggest_and_smallest_number_from_list.py
405
4.15625
4
#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 list_1 = [9, 8, 1, 6, 3, 2, 10, 12, 11, 201, 209, 99, 203,4,-5] max_num = list_1[0] min_num = list_1[0] print("The list is:", list_1) for i in xrange(len(list_1)): if list_1[i] > max_num: max_num = list_1[i] elif list_1[i] < min_num: ...
false