blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
8444720849db0c2171c094f46c8593e96f4f3542 | EugenKuzin/math-for-fedor-r | /teo/addition.py | 801 | 4.125 | 4 | #!/usr/bin/env python3
def successor(x: int) -> int:
'''Return the next integer.'''
return x + 1
def predecessor(x: int) -> int:
'''Return the previous integer.'''
return x - 1
def sum(a, b: int) -> int:
'''Return the sum of given non-negative integers using recursion.'''
return a if b == 0 e... | false |
d43109a47056775be354e96ff28de941555ba6a5 | sghwan28/PythonSelf-Learning | /Data Structure/Linked List/Q_Reversal.py | 912 | 4.15625 | 4 | from linked_list import Node
'''
Question: Define a function to reverse a linked list
The function will take in the head of the list as input and return the new head of the list
'''
def reverse(head:Node):
current = head
previous = None
next = None
while current:
# assign the next according... | true |
af0f883c0b23d83f653309ebc7285c26ab5a198b | Andre-Williams22/SPD-1.4 | /technical_interview_problems/most_frequent.py | 828 | 4.25 | 4 | # Most Frequently Occuring Item in Array
#Example: list1 = [1, 3, 1, 2, 3, 1]
# Output: => 1
def most_frequent(given_list):
hashtable = {} # O(n) Space Complexity
max_num = 0 # O(1) space => tracks the most occuring number
max_count = 0 # O(1) space => tracks num of times number appears
for i in g... | true |
e788d3bf4f1da7321d9a3d4e96d8f96b719a5982 | Tianchi1998/Massey-Assignments | /159.171 1A Question 1.py | 565 | 4.15625 | 4 | # The function below caculates the amount of money that should be repaid each week.
def weekly_pay_back(loan_amount,number_of_weeks):
result=loan_amount/number_of_weeks
return result
# The 7 and 8 lines ask the user to enter his information.
loan_amount=int(input("Enter an amount: "))
number_of_weeks=int(input... | true |
493c73b4d9ac741382161a6239138923f7a76eab | Tokeshy/EpamPythonTraining | /01_DataTypes/Task 1.4.py | 335 | 4.375 | 4 | ### Task 1.4
#Write a Python program to sort a dictionary by key.
DefDict = {1: 2, 3: 4, 2: 9, 4:8} # as ex
SortedDict = {}
KeyList = []
for key, value in DefDict.items() :
if key not in KeyList:
KeyList.append(key)
for SortedKey in sorted(KeyList):
SortedDict[SortedKey] = DefDict[SortedKey]
print(Sorte... | true |
3cd9f4d176b7843ac085568d13ebad1525da4828 | Tokeshy/EpamPythonTraining | /02_Functions/Task 4.1.py | 362 | 4.3125 | 4 | ### Task 4.1
# Implement a function which receives a string and replaces all `"` symbols
# with `'` and vise versa.
def Replacer (in_str):
out_str = ''
for ch in in_str:
if ch == '"' :
ch = "'"
elif ch == "'":
ch = '"'
out_str = out_str + ch
return out_str
... | true |
f43250a00288e6849c76dca071c8a84d218974ea | fahrettincakir/IZU-datacamp | /ornek6.py | 740 | 4.125 | 4 | ########################
# 6.1
soyisim = input("Soyisminiz nedir? ")
if soyisim[0] < "K":
print("Sınava gireceğiniz sınıf EK 101.")
elif soyisim[0] >= "K":
print("Sınava gireceğiniz sınıf EK 201.")
########################
########################
# 6.2
sayı = int(input("3 ile başlayan üç basamaklı bir pozi... | false |
0f0e826c7e1d490b3636644cee05cf21e0168c18 | rootthirtytwo/sandbox | /data_structure/queue.py | 834 | 4.21875 | 4 | class Queue:
def __init__(self):
self.queue = list()
def add_item(self, item):
if item not in self.queue:
self.queue.insert(0, item)
# self.queue.insert(len(self.queue), item)
def delete_item(self):
if len(self.queue) > 0:
self.queue.pop()
... | false |
ad89ae728159df741e30231ddb9527c5718ea69f | Bochkarev90/python2019 | /turtle/task_9.py | 759 | 4.375 | 4 | import turtle
import math
turtle.shape('turtle')
def draw_rectangle(n, radius):
""" Draws a rectangle
n - number of sides
radius - circle's radius
"""
side_length = math.radians(360/(2*n)) * 2 * radius
angle = 360 / n
turtle.penup()
turtle.goto(side_length, 0)
turtle.pend... | false |
eef06c93d884a33eabb2ccb7acd2ab0d71b1182b | Bochkarev90/python2019 | /turtle/task_14.py | 278 | 4.25 | 4 | import turtle
turtle.shape('turtle')
def draw_star(n, size):
""" Draws a star with n vertices.
size - length of the star's side
"""
angle = 180 - 180 / n
for _ in range(n):
turtle.forward(size)
turtle.left(angle)
draw_star(15, 150)
| true |
2346e66a526ad1773ab916166bcc69f2d77b0b9a | belug23/Belug-s-Project-Euler-python-answers-in-TDD | /pe_001/pe_001.py | 938 | 4.3125 | 4 | # Problem 1
# If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
def sum_of_multiple_of_3_and_5_under(limit: int) -> int:
if limit < 0:
raise ValueError("Minimum num... | true |
450a73aaf4e3e7ac0d71cc015d784e87d69394a1 | LynnaOrm/PythonFundamentals | /String_and_List.py | 838 | 4.25 | 4 | #Find and Replace, replace day with month.
words = "it's thanksgiving day. It's my birthday, too!"
print words.find('day')
newWord = words.replace('day','month')
print newWord
#Min and Max, print the min and max in a list.
x = [2,54,-2,7,12,98]
print min(x)
print max(x)
#First and Last, print the first and last value... | true |
eca2a834d3860d5a5d2ed7d3bdd6bdff19ed0b1f | LynnaOrm/PythonFundamentals | /FindCharacters.py | 490 | 4.125 | 4 | #Write a program that takes a list of strings and a string containing a single character, and prints a new list of all the strings containing that character.
#hint every word containing the letter "o"
word_list = ['Hello','world','my','name','is','Lynna']
char = 'o'
def characters(word_list, char):
new_list= []
... | true |
246dfe73de2381ef10f837d60fbab0ffbc573306 | code-drops/hackerrank | /Data structures/01. Arrays/04. Left Rotation.py | 652 | 4.25 | 4 | '''
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array , then the array [1,2,3,4,5] would become [3,4,5,1,2].
Given an array of n integers and a number,d , perform d left rotations on the array. Then print the u... | true |
31e655bd56214fd451d7b7a3650f99df06f843b4 | code-drops/hackerrank | /contest/Hack The Interview IV(Asia Pacific)/arrange students.py | 1,819 | 4.28125 | 4 | /*
A classroom has several students, half of whom are boys and half of whom are girls. You need to arrange all of them in a line for the morning assembly such that the following conditions are satisfied:
The students must be in order of non-decreasing height.
Two boys or two girls must not be adjacent to each other.
... | true |
1421ac4a6580bdc60fdc0e05106f0828be93b937 | code-drops/hackerrank | /Algorithms/01. Warmup/07. Staircase.py | 419 | 4.375 | 4 | '''
Consider a staircase of size n=4:
#
##
###
####
Observe that its base and height are both equal to n, and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces.
Write a program that prints a staircase of size n.
'''
n = int(input())
for i in range(n):
for tab in rang... | true |
8f222e213fd69c171b553e1a6006b98fea65b34a | iamsiva11/Codingbat-Solutions | /string1/left2.py | 324 | 4.21875 | 4 | """
Given a string, return a "rotated left 2"
version where the first 2 chars are moved to the end.
The string length will be at least 2.
"""
def left2(str):
if len(str)<2:
return str
else:
return str[2:]+str[:2]
print left2('Hello') # 'lloHe'
print left2('java') # 'vaja'
print left2('Hi') # 'Hi'
... | true |
bef196da12fbfa1af31ecb3c51ecf14e643a69a1 | iamsiva11/Codingbat-Solutions | /list2/big_diff.py | 1,151 | 4.15625 | 4 |
"""
Given an array length 1 or more of ints,
return the difference between the largest
and smallest values in the array. Note:
the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values.
"""
def big_diff(nums):
#Edge Cases
if(len(nums)<1):
return []
if(len(nums)<2):
retur... | true |
a6e77d06f5b4ba618a8c06343dc132f179cb2890 | iamsiva11/Codingbat-Solutions | /string1/first_two.py | 452 | 4.1875 | 4 | # Given a string, return the string made of its first two chars,
# so the String "Hello" yields "He". If the string is shorter than length 2,
# return whatever there is, so "X" yields "X", and the empty string
# "" yields the empty string "".
def first_two(str):
first2=str[:2]
if len(str)<2:
return str
return ... | true |
40a8dd0eb042c746ccf292335555be50c545cbbc | Enfioz/pands-problems | /squareroot.py | 316 | 4.21875 | 4 | # Enter positive floating-point number as input
# Output an approximation of its square root
from math import sqrt
def squareroot(x):
return(sqrt(x))
x = float(input("Please enter a positive number: "))
ans = (sqrt(x))
y = format(ans, ".1f")
print("The square root of %s is approx." % x, y)
# push to github | true |
b723e7816fe7a6a70df9dde60283c319009dfa26 | viruskingkk/PyMiscellaneous | /AI_guess_number.py | 549 | 4.1875 | 4 | while True:
try:
num = int(input('Enter a number: '))
except ValueError:
print ("The input must be a integer!")
continue
break
guess = num / 1.3
middle = num / 2
step = 0
while guess != num:
if num > guess:
guess += middle
print (("I guess: "), guess)
el... | true |
ea95b3d2b93b3c8ecc05cf6c5d2bbf75858f7b87 | Yihu4/Python_study | /2018_after_vacation/how_to_have_infinite_power/fibonacci_counting.py | 436 | 4.15625 | 4 | def fibonacci_counting(n):
current = 0
after = 1
for i in range(n):
current, after = after, current + after
return current
# 迭代
print(fibonacci_counting(36))
print(fibonacci_counting(5))
mass_of_earth = 5.9722 * 10**24 # kilograms
print(2**10)
mass_of_rabbit = 2 # 2 kilograms per rabbit
... | true |
975a6b351292c23f64415f1eb6d0dce5c037dce0 | hxtruong6/Python-bootcamp | /Generator/homework.py | 970 | 4.5 | 4 | # 1.Create a generator that generates the squares of numbers up to some number N
def generates(N):
for i in range(N):
yield i**2
# 2.Create a generator that yields "n" random numbers between a low and high number (that are inputs).
import random
def rand_num(low,high, n):
for x in range(n):
... | true |
21bdc00a5ac1049c82f844e61e8f291fde8b5181 | arianafm/Python | /Básico/Ejercicios/menu.py | 1,581 | 4.25 | 4 | #Ejercicio de hacer un menú:
# -Ingresa opción
# -Sumar dos números
# -Elevar un número a la potencia n
# -Imprime los números pares del 1 al 100
# -Salir
Calculadora = True
bandera = True
while Calculadora:
print("Menú")
print("1.- Suma dos números.")
print("2.- Elevar número a la potencia n.")
print("3.- Mostr... | false |
74e2ecd9ce622b5b82790f503058b6e5f3491f59 | arianafm/Python | /Tareas/Tarea1/matrices.py | 1,061 | 4.3125 | 4 | #Elabora un programa que me permita realizar la suma de dos matrices de 3x3. Cada uno de los elementos de la matriz deberá ser ingresado por el usuario. Una matriz en Python puede implementarse con listas dentro de listas.
def elementos():
#Listas por comprensión
matriz =[[[] for i in range(3)] for i in range(3)]
... | false |
97e1ba546f035f1f6891fdec5e681003f244936f | kavyatham/In-a-list-sum-of-numbers | /sum of the list of numbers.py | 209 | 4.3125 | 4 | Dict1 = {"name1":"50","name2":"60","name3":"70"}
itemMaxValue = max(Dict1.items(), key=lambda x : x[1])
print('Max value in Dict: ', itemMaxValue[1])
print('Key With Max value in Dict: ', itemMaxValue[0]) | false |
11a11960a90ed8c7998f4bbf71dd8e90265b1442 | nczapla/PHYS400 | /Exercise.5.2.py | 418 | 4.25 | 4 | def is_triangle(a,b,c):
if a>=b+c:
print 'Not today junior!'
else:
if b>=a+c:
print 'Not today junior!'
else:
if c>=a+b:
print 'Not today junior!'
else:
print 'Houston we have lift off!'
def is_triangle1():
print 'Pick three numbers greater than 0 to see if they can form a triangle'
a=float... | false |
659a6a1d5a2daea427240d774f144919606e51d7 | gurgalex/pythonmathbook | /ch2/golden_fib.py | 944 | 4.15625 | 4 | """Compares the fibonacci sequence to the golden ratio using a graph"""
from matplotlib import pyplot as plt
def fiblist(n):
"""Returns a list of n fibonacci numbers"""
sequence = [i for i in fibseq(n)]
return sequence
def fibseq(n):
"""Yields the next fibonacci number"""
# Set values for fib 1 ... | true |
b7163fc8ddc4386c6f98665b327c7073c513ab73 | TulebaevTemirlan/ICT_labs | /Task1/ex33.py | 390 | 4.15625 | 4 | number_of_breads = float(input("Enter the number of breads you want to buy: "))
discount = 60
price = 3.49
answer = number_of_breads * price * ((100 - discount) / 100)
print("\nThe regular price is -- $ " + "{0:.2f}".format(int(number_of_breads * price)))
print("The discount is -- " + str(discount) + " %")
print("Th... | true |
fcad3fef0a680c9d900642c9ff2556a9f5ea95ee | TulebaevTemirlan/ICT_labs | /Task1/ex16.py | 295 | 4.4375 | 4 | # Hint: The area of a circle is area = πr2.
# The volume of a sphere is volume= 4 3πr3.
import math
r = float(input("Enter the radius: "))
area = math.pi * (r**2)
volume = math.pi * (r ** 3)
print("\nThe area of a circle is " + str(area))
print("The volume of a sphere is " + str(volume))
| true |
362f8adc6335ea128392a3c2460f7fdfe8b15f7d | TulebaevTemirlan/ICT_labs | /Task1/ex28.py | 321 | 4.15625 | 4 | import math
temperature = float(input("Enter the temperature of a wind in Celcius: "))
wind_speed = float(input("Enter the speed of a wind kilometers/hour: "))
WCI = 13.12+ 0.6215 * temperature - 11.37 * wind_speed**0.16 + 0.3965 * temperature * wind_speed**0.16
print("\nThe Wind Chill Index is: " + str(round(WCI))... | true |
9a12ff9ff84c6c9e99035d19544678af1d77eab0 | BrianCUNY/IS211_Assignment1 | /assignment1_part2 | 459 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Coding assignment 1, P2"""
class Book(object):
author = " "
title = " "
def __init__(self, author, title):
self.author = author
self.title = title
def display(self):
bookinfo = '"{}, written by {}"'.format(self.title, self.author)
print bo... | true |
eb984ce3396e00273e331804620635d70dde108e | AdegokeFawaz/header | /Numbers.py | 521 | 4.15625 | 4 | #this code adds the first number and the second number
first_number=4
second_number=4
print(first_number+second_number)
#This code divides the first number and the second number
first_number=16
second_number=2
print(first_number/second_number)
#This code multiplies the first number and the second number
first_number=4
... | true |
e1431f0ee27aa1b590a1cbd0039563baaa65cdef | wahabshaikh/problems-vs-algorithms | /problem_1.py | 897 | 4.40625 | 4 | def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
try:
if number == 0 or number == 1:
return number
start = 1
end = number
while (start <= ... | true |
f0cf672dad43443e587e08e37a2250f01312fa9c | shardul-shah/Project-Euler | /p4efficient.py | 726 | 4.15625 | 4 | """
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
from itertools import combinations_with_replacement
def main():
domain = []
for i in range(100, 100... | true |
579b9ce5760116e18c8c367d116540f3196b74ec | mariahabiba078/python-code | /.github/workflows/fizzbuzz prb method1.py | 530 | 4.28125 | 4 | #So the problem is basically to give you the numbers 1 to 100, if the number is divisible by 3, print
# 'Fizz', if divisible by 5, print 'Buzz', if divisible by 3 and 5, print 'FizzBuzz'. For other numbers
# just print out the number itself."
for fizzbuzz in range(100):
if fizzbuzz % 3 == 0 and fizzbuzz % 5 == ... | true |
deeb87115360c28bf4ea428c637edfac3295040b | shenny88/python_casestudies | /cs4/7_factorial.py | 282 | 4.21875 | 4 | # 7. program which can compute the factorial of a given numbers. Use recursion
# to find it.
import sys
def factorial(mynum):
if mynum == 1:
return 1
else:
mynum = mynum * factorial(mynum -1)
return(mynum)
num = int(sys.argv[1])
print(factorial(num))
| true |
f01ff5ab3a092509e90471f44840c90a6fe0d257 | mhayes2019/100-Days-of-Codeing-udemy | /day-3-1 Odd or Even.py | 551 | 4.34375 | 4 | # 🚨 Don't change the code below 👇
number = int(input("Which number do you want to check? "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
#need to figure out if the number the user chose will come out zero after doing the modulous of 2, because any even number is divided by 2. if the numb... | true |
47a78750a51d0fae96288905cac4f1a42212cc39 | wgdcs/learnpython | /lec5/task_1.py | 1,382 | 4.34375 | 4 | print ("введите два числа, одно из которых четное, а другое - нечетное")
number_1 = int (input ("введите первое число: "))
number_2 = int (input ("введите второе число: "))
# проверяем, является ли нечетным первое число
is_number_1_odd = bool (number_1 % 2 == 1)
# проверяем, является ли нечентным второе число
is_number... | false |
7cfa9f704cd0090ce2252a10815b2493097db4d3 | wgdcs/learnpython | /lec5/task_6.py | 1,342 | 4.375 | 4 | # По длинам трех отрезков, введенных пользователем,
# определить возможность существования треугольника,
# составленного из этих отрезков.
# Если такой треугольник существует, то определить,
# является ли он разносторонним, равнобедренным или равносторонним.
a = float (input ("Введите первую сторону треугольника: "))
b... | false |
5166c517b1686250fb957848922e64352a8c0e96 | assafZaritskyLab/Intro_to_CS_SISE_2021-2022 | /week_4/example_12.py | 827 | 4.15625 | 4 | ### Question 3 - Students and grades
students = [["yael", 87], ["yuval", 88], ["amir", 100]]
print(students)
# students = ("yael" : 87, "yuval": 88, "amir": 100)
# students = ["yael": 87, "yuval": 88, "amir": 100]
students = {"yael": 87, "yuval": 88, "amir": 100}
# students = {("yael" : 87), ("yuval" : 88), ("amir" : ... | false |
bfdb276cd9717bc16c4b9de6ed6bd486c153f3d7 | assafZaritskyLab/Intro_to_CS_SISE_2021-2022 | /week_2/Example_12.py | 577 | 4.21875 | 4 | # # determine whether a number is prime or not
# number = int(input("Enter a number larger than 1: "))
# is_prime = True # assuming the number is prime
# # i in range(2, number)
# i = 2
# while i < number: # check from 2 to number - 1
# if number % i == 0:
# is_prime = False
# i += 1 # i = i +1
#
#... | true |
c9b513abc057ff84ffd6d97bcca99b07d9d1849b | assafZaritskyLab/Intro_to_CS_SISE_2021-2022 | /week_2/Example_13.py | 391 | 4.25 | 4 |
# determine whether a number is prime or not
number = int(input("Enter a number larger than 1: "))
is_prime = True # assuming the number is prime
i = 2
while i < number and is_prime: # check from 2 to number - 1
if number % i == 0:
is_prime = False
i += 1 # i = i + 1
if is_prime:
print("The cho... | true |
3c794c0ee8fc7308acae66fdd6006b50ee531bbb | tenguterror/personal-growth | /messingWithStrings.py | 367 | 4.40625 | 4 | # This will ask for the user name and print it out last then first.
# This was done using string formatting(f strings) and string methods so is the user inputs in lower it will titlecase it
print('Hello, what is you first name?')
firstName = input().title()
print('What is you last name?')
lastName = input().titl... | true |
11fba9c4267e533ad849a9dc2458d88eb1c5e288 | tejaswiniR161/fewLeetCodeSolutions | /Concepts/Sorting/Merge.py | 1,311 | 4.375 | 4 | #Merge sort uses the divide and conquer technique
#time complexity is O(nlogn)
#space however is
array=input("Enter the numbers to sort them, enter space sepearted integers")
array=array.split(" ")
#for some reason remember this so, if you use list(array) it'll split even the spaces so spaces will also be in the res... | true |
e748bfaff2149bcc6a08e7d7c47089efc08a0894 | sanjipmehta/prime_number | /prime.py | 237 | 4.21875 | 4 | num=int(input("Enter the number:"))
for x in range(2,num):
if (x==2 or x==3 or x==5 or x==7):
print(x,"is a prime number")
elif(x%2!=0 and x%3!=0 and x%5!=0 and x%7!=0):
print(x,"is a prime number")
else:
print(x,"is not prime") | true |
1108bf3ed45627f8d1b0799300053a18337485aa | LeviMorningstar/Ex.-Estrutura-de-decisao | /Ex. 5(OK).py | 1,318 | 4.1875 | 4 | #Faça um programa para a leitura de duas notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e apresentar:
#A mensagem "Aprovado", se a média alcançada for maior ou igual a sete;
#A mensagem "Reprovado", se a média for menor do que sete;
#A mensagem "Aprovado com Distinção", se a média f... | false |
bfb76e52a351bf9204af296325bca82da26cb5a0 | adowdell18/HowMuchDoesItCostToPaintaTurtle | /paint-a-turtle.py | 1,794 | 4.46875 | 4 |
#Computing area of shell
import math
diameter_shell = eval(input("Enter the diameter of the turtle's shell (in inches): "))
radius_inches_shell = diameter_shell/2
radius_feet_shell= radius_inches_shell/12
area_shell = (3.14* (radius_feet_shell)**2)/2
print("The area of the turtle's shell is ",area_... | true |
16ebd39c87c1a35e69c7074700a0d4908580c556 | suareasy/project_euler-python | /solutions/001.py | 404 | 4.3125 | 4 |
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we
get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def run() -> int:
res = 0
n = 1000
for i in range( n ):
if i%3 == 0 or i%5 == 0:
... | true |
32e49bff29d0eda5af5608ead6c78bd440fd7c2f | sunny0910/Data-Structures-Algorithms | /stacks & queue/next_greater_element.py | 1,860 | 4.375 | 4 | def next_greater_element(array):
"""
This approach uses two for loops, one to iterate over every element and second to iterate over subsequent elements
to find the next greater element.
The time complexity for this approach is O(n^2)
:param array: List
:return: None
"""
for i in range(le... | true |
71497189bfae4f11e908d988842ec3adec70c55a | sunny0910/Data-Structures-Algorithms | /binary_trees/distance_between_nodes.py | 1,269 | 4.28125 | 4 | from binary_trees.path_to_node import path_to_node
from binary_trees.binary_search_tree import BinarySearchTree
def distance_between_nodes(root, a, b):
"""
Function to calculate the distance between two target nodes.
Distance is the number of lines covered in the traversal till that node.
:param root:... | true |
21386b540c4d1a0bcc0e97a2e9f546ed7efeb34c | sunny0910/Data-Structures-Algorithms | /binary_trees/width_of_tree.py | 1,324 | 4.4375 | 4 | from binary_trees.binary_search_tree import BinarySearchTree
def max_width(root):
"""
Function to calculate width of a binary tree.
Width is the maximum number of nodes at any level in a binary tree.
This approach uses level order traversal and return maximum length of levels in a tree.
:param roo... | true |
dca3ffd56ae472f37a3b3d73b1c84790d24d3c9c | sunny0910/Data-Structures-Algorithms | /binary_trees/zigzak_traversal.py | 2,066 | 4.4375 | 4 | from binary_trees.binary_search_tree import BinarySearchTree
from binary_trees.print_level import print_level
from binary_trees.height_of_btree import height
def zigzak(root, clockwise):
"""
Function to print the zig-zak traversal of a binary tree.
This function prints new levels by traversing the tree ag... | true |
f843b65dec038a2c8db23ebb0200dd9503651273 | sunny0910/Data-Structures-Algorithms | /matrix/matrix_path.py | 1,681 | 4.28125 | 4 | def path_exits(a):
"""
Function to check if a matrix path exists from top to bottom
:param a: List # Matrix
:return: String
"""
if 1 not in a[0]:
return 'safe'
q = [[] for i in range(len(a))]
for i in range(len(a)):
for j in range(len(a[0])):
if a[i][j] == 1:
... | true |
fc63aaa4ee0d2fb7da70c8046653fd67393f541e | dlfosterii/python-105 | /exercise1.py | 399 | 4.25 | 4 | #prompt user for a single grocery item
# -append it toa the 'grocieres' list
#in an infinate loop, prompt the user, prompt the user for an item
# -append the item to the list
# -print()the list after you add the item
#to exit out of the loopm oress Ctrl-C
groceries = []
while True:
item = input(f'Enter an i... | true |
1d774247fe076f3c0648b0c1505ce9462de0822f | emord/project-euler | /python/prob51-60/prob55.py | 1,692 | 4.25 | 4 | #!/usr/bin/python3
"""
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is tho... | true |
d213e7854b1fa806a55c1dad42715b3501929252 | emord/project-euler | /python/prob1-10/prob2.py | 961 | 4.21875 | 4 | #!/usr/bin/python3
"""
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the ... | true |
a0a3edd8c43a194f367fad6e177673bdda541666 | adrielleAm/ListaPython | /ClasseTV.py | 1,577 | 4.4375 | 4 | '''
2) Classe TV: Faça um programa que simule um televisor criando-o como um objeto.
O usuário deve ser capaz de informar o número do canal e aumentar ou diminuir o volume.
Certifique-se de que o número do canal e o nível do volume permanecem dentro de faixas válidas.
'''
class tv:
def __init__(self, canal, volum... | false |
2073778e6dbd3912e543ac5f464be40e81ca5f4f | adrielleAm/ListaPython | /EstruturaRepeticao_3.py | 394 | 4.21875 | 4 | '''
Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao
nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.
'''
user = input("Nome de usuario: ")
senha = input("Senha: ")
while senha == user:
senha = input("Digite uma senha diferente do nom... | false |
739ae13d86f18ce54b47007fc31abb8bab8e6ac2 | adefowoke/coffee-machine | /task/machine/coffee_machine.py | 2,928 | 4.125 | 4 | # create inputs for the machine materials
# initialize machine resources
water, milk, coffee_beans, cups, money = 400, 540, 120, 9, 550
def remaining():
global water, milk, coffee_beans, cups, money
# water += 0
# milk += 0
# coffee_beans += 0
# cups += 0
# money += 0
# if money >= 1:
... | true |
9bad3f9582f4a8a85af82d0e0e6b3a7be9ca02ca | thhuynh91/Python_Practice | /Even_Fibonacci_numbers.py | 478 | 4.46875 | 4 | #The Fibonacci number is generated by adding the previous two terms.
#For example: below is list of Fibonacci numbers:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#Find the sum of the even-valued terms by considering the terms in Fibonacci sequence whose value do not exceed a given "n"
def Fibo(n):
total = 0
f1 =... | true |
4451f145fdc6ae45deb38c1eefb6756e569ec56e | barnybug/aoc2020 | /day12.py | 1,660 | 4.1875 | 4 | #!/usr/bin/env python
from typing import NamedTuple
class Coordinate(NamedTuple):
x: int = 0
y: int = 0
def __add__(self, d):
return Coordinate(self.x + d.x, self.y + d.y)
def __mul__(self, n):
return Coordinate(self.x * n, self.y * n)
def turn(self, sign):
return Coordi... | false |
762b19a44435df63dcf0f404c5e16d3013e2efd3 | xxiang13/Courses | /MITx_Intro_to_CS_Programming/Lec6_prob10_numValue_inDict.py | 391 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 16
@author: Xiang Li
"""
def howMany(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
sumValue = 0
for i in aDict.keys():
sumValue = sumValue + len(aDict[i])
re... | false |
47e8ec41897b4d624f36816d17ed35ae7e2c4a0d | lisahachmann/SoftDesSp15 | /toolbox/word_frequency_analysis/frequency.py | 2,452 | 4.5625 | 5 | """ Analyzes the word frequencies in a book downloaded from
Project Gutenberg """
import string
def get_word_list(file_name):
""" Reads the specified project Gutenberg book. Header comments,
punctuation, and whitespace are stripped away. The function
returns a list of the words used in the b... | true |
8c60e30f5fcc54b61ba1fdba88413a84f0871bcf | gabrielfern/concurrent-programming | /pythonic-way/async-gen.py | 1,079 | 4.15625 | 4 | #!/usr/bin/python3
# simples execucao assincrona usando python generators
# Gabriel Fernandes
# gera a quantidade desejada de numeros pares
# tam :: tamanho da sequencia desejada
def pares(tam):
n = 0
while n < tam:
yield 2*n
n += 1
# gera a quantidade desejada de numeros impares
# tam :: ta... | false |
462dbe269a345d5bd7b08bf70c1375304a5c0b66 | sajeendragavi/Learn-Python-Programming-Masterclass | /9_/dictionary_2.py | 2,048 | 4.125 | 4 | # fruit = {"orange" : "a sweet, orange, citrus fruit",
# "apple" : "good for making cider",
# "lemon" : "a sour, yellow citrus fruit",
# "grape" : "a small, sweet fruit growing in bunches",
# "lime" : "a sour, green citrus fruit",
# "apple" : "round and crunchy"}
... | true |
11733fa8741a2aef2b526bcbd370dafb0e89d468 | esizemore/Homework-1 | /Sizemore_hw1_prob2 | 521 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 29 16:39:13 2017
@author: elizabethsizemore
"""
#Elizabeth Sizemore
#HW 1 prob 2
from math import pi,pow
#Newton's Gravitational constant (m^3/kg*s^2)
G=6.67E-11
#Mass of the Earth (kg)
M=5.97E24
#Radius of Earth (m)
R=6371000
t=int(input("... | false |
a56c6317f6cc132023f3eb645b7b580b0d67afaf | Dpoudel18/Data-Structures-in-Python | /distinct_elements.py | 344 | 4.1875 | 4 | # A python function to print all the distinct elements of the array.
def distinct_elements(my_array):
for i in range(len(my_array)):
repeat = 1
for j in range(0, i):
if (my_array[i] == my_array[j]):
repeat = 2
break
if (repeat == 1):
... | true |
f777d76072a405e156c3c9fd7041eeb3dc068764 | jwhitish/learning-python | /strong-pw-detection.py | 863 | 4.15625 | 4 | #simple password strength checker
import re
userPW = str(input("Enter a password: "))
if len(userPW) < 8:
print('Password is not long enough')
else:
lowerTest = re.compile(r'[a-z]+')
test1 = lowerTest.findall(userPW)
if len(test1) > 0:
print('has lower alpha')
upperTest = re.compile... | true |
635c389c37e5d467b4fce7ff7b41ee9831a7394c | mragipaltuncu/hogwarts | /player.py | 1,591 | 4.25 | 4 | def choose_character():
"""Choose your character"""
name = input("What is your name student ?: ")
print("")
print("It is our choices {0}, that show us who we truly are,\nfar more than our abilities -- Albus Dumbledore".format(name))
print("")
while True:
print("Which Hogwarts House do you want to choose?")
pr... | false |
6e83c0ca10ad51d8347fe4398ed02b3590937ac9 | kgisl/pythonFDP | /code/mergesort.py | 1,184 | 4.1875 | 4 | import itertools
# http://j.mp/zipLongest
def mergesort(series):
'''iterative mergesort implementation
@author kgashok
@param series is a sequence of unsorted elements
@returns a list containing sorted elements
Testable docstring? https://docs.python.org/2/library/doctest.html
>>> mergeso... | true |
b7baef09673eec4a7b58cd57df5722a796cea33d | dmathews98/NumRec | /Unit3/bisecttest.py | 1,235 | 4.125 | 4 | '''
Test class for Unit 3 - Exercise 1: The Bisection Method
'''
from functions import Functions
from bisectclass import Bisect
def main():
initx = -4
finalx = 4
numpoints = 500
error = 0.00001
rootsf = []
rootsg = []
rootsh = []
run = Functions(initx, finalx, numpoints)
run.plo... | false |
654a1a70c8d49597f2e74c1ff4ea1b3c7e4ba05a | erjimrio/Curso-CPP | /Comparativa Python/Ejercicio9-Condicionales.py | 531 | 4.3125 | 4 | """8. Escribe un programa que lea de la entrada estándar tres números. Después
debe leer un cuarto número e indicar si el número coincide con alguno de los
introducidos con anterioridad."""
num1 = int(input('Digite num1: '))
num2 = int(input('Digite num2: '))
num3 = int(input('Digite num3: '))
num4 = int(input('Digite... | false |
c645f9a710fe8622e644a3c73a93481f00b85bac | erjimrio/Curso-CPP | /Comparativa Python/Ejercicio2-Tablas.py | 382 | 4.3125 | 4 | """2. Realiza un programa que defina una matriz de 3x3 y escriba un ciclo para
que muestre la diagonal principal de la matriz.
1 2 3 1
4 5 6 -> 5
7 8 9 9
"""
numeros = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# imprime diagonal principal
for r in range(0, 3):
for c in range(0, 3):
... | false |
6d04801541acf2d7423ab05be1624ed5fd2bd639 | kt3k/codesprint5 | /special-multiple/solution.py | 541 | 4.125 | 4 | #! /usr/bin/env python
def main():
T = input()
for i in range(T):
N = input()
print special_multiple(N)
# generate sequence of positive integers of only 9 and 0 digits
def gen():
i = 1
while True:
# transform binary representation to special 0,9-sequence
# ex. 9... | false |
961b618935e47a24fff62e37ada5bebba1308de8 | ShiyuCheng2018/ISTA130-Intro-To-Programming | /assignments/assignment_3/try.py | 482 | 4.34375 | 4 | '''
pseudocode:
1. define the function name and the argument: String
1.1 assign an empty string to a variable name called result
1.2 loop through the string that passed in as a local variable cha
1.21 assign double times cha to the result
1.3 print result to check if its expected
1.4 return the ... | true |
056c6013e5b051a8a890117c4ccebbebcf0ac49d | weiwenliang666/learning | /传递参数.py | 1,442 | 4.34375 | 4 | '''
值传递:传递的不可变类型
string、tuple、number是不可变的
'''
'''
引用传递:传递的可变类型
list、dict、set是可变的
'''
'''关键字参数
概念:允许函数调用时参数的顺序与定义时不一致
'''
#使用关键字参数
def myPrint(str,age):
print (str,age)
myPrint(age = 18, str = 'Today is good day')
'''默认参数
概念:调用函数时,如果没有传递参数,则使用默认参数
'''
'''不定长参数
概念:能处理比定义时更多的参数
加了星号*的变量... | false |
fa76b3b7e329162fafea995c657b5b7517c80155 | SherazKhan/DS-rep | /Utils/Visualization/box_plot.py | 2,041 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
This file contains function(s) for creating box plots.
Created on Thu Aug 10 09:05:23 2017
@author: imazeh
"""
import numpy as np
import matplotlib.pyplot as plt
def create_box_plot(df, x_discrete_variable, y_cont_variable, with_outliers=True, all_possible_x_vals=None,
... | true |
839642c0f8764508a721f7a6a5a4dadb94a26a01 | M-Usman-Tahir/PythonPrograms | /Problem Set 2 Task 4.py | 1,764 | 4.125 | 4 | # Programming Fundamentals
# Problem Set 2
# Submitted By: Sundas Noreen
# Task 4
# Using Tuples to test our program on a variety of choices of Package Sizes.
print("\nProblem Set 2, Task 4")
bestSoFar = 0 # Keeping track of largest number of McNuggets that cannot be bought in exact quantity.
Combination_1 = ... | true |
a10496cbfb02d3aec8cb034bb2b4f121a541b45e | M-Usman-Tahir/PythonPrograms | /Tuples and Lists Assignment.py | 842 | 4.5625 | 5 | #Tuples and List by Sundas Noreen
#Writing a function that emulates the builtin zip function.
#It will take iterables and return a list of tuples.
#Each tuple will contain one element from each of the iterables passed to the function.
def My_Function(x,y): # Defining the Function with two Input Paramete... | true |
43fcedf50771bf61bfc70072c53ca04c1580662d | prajapati123476/clean-code-challenge | /challenge-7/largest_element.py | 462 | 4.625 | 5 | # Python3 program to print the largest element
# in a list
# Input Constraint: array_size >= 5
list_size = 0
# Input until Constraint satisfied
while list_size < 5:
list_size = int(input("Input size: "))
# Declare empty list
elements = list()
# Read list from user
for i in range(list_size):
num = int(input('Input... | true |
454e460f003c75ec9c5fa4123d428afb1370a5d2 | prajapati123476/clean-code-challenge | /challenge-9/count_vowel_words.py | 904 | 4.40625 | 4 | # Python3 program to count the number of words
# in input string that start with a vowel
# Input Constraint: max_string_size = 500
import sys
# Count num of words starting with vowel in param
def count_vowel_words(check_string):
count = 0
# Generate list of words, on basis of ' '
list_of_words = check_string.spl... | true |
acf3c0030603d0f6ccadada5af951d738fb47134 | BW1ll/Projects | /Python/python_crash_course/Chapter 4/4.3-4.9.py | 425 | 4.125 | 4 | for i in range(1, 21):
print(i)
nums = [value for value in range(1,1_000_000)]
print(nums)
print(min(nums))
print(max(nums))
print(sum(nums))
odd_nums = list(range(1, 21, 2))
for num in odd_nums:
print(num)
multiple3 = list(range(3, 31, 3))
for num in multiple3:
print(num)
cubes1 = list(range(1, 11))
f... | true |
0ab2aed573e8d75fcd62f649574e971c382bb224 | SubhadeepSen/Python-Core-Basics | /4_Methods/3_Map_Filter.py | 668 | 4.1875 | 4 | def square(num):
return num**2;
numbers = [1,2,3,4,5,6,7,8];
#Using for loop
for n in numbers:
print("Square of {} is {}".format(n, square(n)));
#Using map() function we can map a function to a list of elements
#map(functionNeedsToBeExecuted, listOfElemetns)
#returns map object
print(map(square, numbers));... | true |
33bb208d1b854e9c01ea723f1831fb473f252783 | SubhadeepSen/Python-Core-Basics | /1_DataTypes/String_operation.py | 1,430 | 4.53125 | 5 | name = "Subhadeep Sen";
print("Name: ", name);
#Length of a given string
length = len(name);
print("Length: ", length);
#Character at particular index
name_0 = name[0];
print("Name[0]: ", name_0);
name_5 = name[5];
print("Name[5]: ", name_5);
#Substring
# str[startIndex:lastIndex]
firstName = name[0:9];
print("Firs... | true |
8f98824fdc04655806e918583498749abb515bcf | rzhao04/wave-2 | /month name to number of days.py | 290 | 4.1875 | 4 | month = str
month = raw_input ("what is month: ")
if (month in ["january", "march", "may", "july", "august", "october", "december"]):
print ("31 days")
if (month in ["april", "june", "september", "november"]):
print ("30 days")
if (month == "february"):
print ("28 or 29 days") | true |
d5e5fb6e29e682d8e21f55bef8c16171768a4d44 | fixitcode/Hello-python | /Fifo.py | 1,102 | 4.25 | 4 |
# coding: utf-8
# In[16]:
'''A queue follows FIFO (first-in, first-out).
FIFO is the case where the first element added is the first element that can be retrieved.
Consider a list with values [1,2,3]. Create functions queueadd and queueretrieve to add and
pop elements from the list in FIFO order respectively. Aft... | true |
0240ac7b4e98d5bf5a77247acd82bd4845b05638 | lordzizzy/leet_code | /04_daily_challenge/2021/01-jan/week3/longest_palindromic_substring.py | 2,376 | 4.28125 | 4 | # https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3609/
# Longest Palindromic Substring
# Given a string s, return the longest palindromic substring in s.
# Example 1:
# Input: s = "babad"
# Output: "bab"
# Note: "aba" is also a valid answer.
# Examp... | true |
2c66d493db17934dd11fcb234879c2973389c5e6 | lordzizzy/leet_code | /04_daily_challenge/2021/01-jan/week3/count_sorted_vowel_strings.py | 2,456 | 4.21875 | 4 |
# https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3607/
# Count Sorted Vowel Strings
# Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.
# A string s is lexicog... | true |
c3ddb3bf94ebf1718c478cc0f1dbf22e6f36c684 | lordzizzy/leet_code | /04_daily_challenge/2021/04-apr/week4/power_of_three.py | 2,113 | 4.40625 | 4 | # # https://leetcode.com/explore/challenge/card/april-leetcoding-challenge-2021/596/week-4-april-22nd-april-28th/3722/
# Power of Three
# Given an integer n, return true if it is a power of three. Otherwise, return
# false.
# An integer n is a power of three, if there exists an integer x such that n ==
# 3x.
# Examp... | true |
705f19655e764983cd30ec9cc85fa1c1b71d058d | lordzizzy/leet_code | /04_daily_challenge/2021/07-july/week4/beautiful_array.py | 2,660 | 4.1875 | 4 | # https://leetcode.com/explore/challenge/card/july-leetcoding-challenge-2021/611/week-4-july-22nd-july-28th/3829/
# Beautiful Array
# An array nums of length n is beautiful if:
# nums is a permutation of the integers in the range [1, n].
# For every 0 <= i < j < n, there is no index k with i < k < j where 2 *
# nums... | true |
8eed14a8dec53b19bc3f644868f4646c1cda8935 | JudoboyAlex/python_fundamentals1 | /exercise6.2.py | 1,667 | 4.4375 | 4 | # You started the day with energy, but you are going to get tired as you travel! Keep track of your energy.
# If you walk, your energy should increase. If you run, it should decrease. Moreover, you should not be able to run if your energy is zero.
# ...then, go crazy with it! Allow the user to rest and eat. Do whatever... | true |
15de37c13d5b459e5cd75ec427a4345ec6d2294f | Lukas-N/Projects | /L5.py | 429 | 4.15625 | 4 | Bottles = int(input("How many green bottles are there: "))
while Bottles > 1:
print(Bottles, "green bottles hanging on the wall, and if one green bottle were to accidently fall, there would be", (Bottles -1), "green bottle(s) hanging on the wall")
Bottles = Bottles -1
print("1 green bottle hanging on the wa... | true |
4d1ca25ab9bd4f77a4a415fdd9dd14db66f2e4c5 | Rishik999/BSc_IT_Python | /pracs/unit_1/prac_1c_fibonacci.py | 311 | 4.1875 | 4 | # PYTHON PROGRAM TO GENERATE FIBONACCI SERIES
# user input
num = int(input("Enter a number: "))
# initializing variables
old = 0
new = 1
count = 0
# while loop to run until counter reaches the given number
while count <= num:
next = old + new
print(old)
old = new
new = next
count += 1
| true |
5f91500b1d550a84eb01f20e8af063f2273e8192 | Rishik999/BSc_IT_Python | /pracs/unit_1/prac_1b_odd_even.py | 313 | 4.4375 | 4 | # PYTHON PROGRAM TO CHECK IF THE NUMBER IS EVEN OR ODD
# user input
num = input("Please enter a number: ")
# using modulus operator to check if the remainder is 0 i.e. if it is divisible by 2
if int(num) % 2 == 0:
print("Entered number is an even number")
else:
print("Entered number is an odd number")
| true |
6c14e816e6bd5251daec42c8d71c3fd00c474981 | Rishik999/BSc_IT_Python | /pracs/unit_4/prac_4c_clone_list.py | 344 | 4.4375 | 4 | # PYTHON PROGRAM TO CLONE A LIST
# initializing lists
list_1 = [44, 54, 22, 71, 67, 89, 20, 99]
list_2 = [] # empty list to store elements from list_1
# for loop to iterate list_1
for x in list_1:
list_2.append(x) # append each element (x) from list_1 to list_2
# output
print("Original list: ", list_1)
print("Cl... | true |
59270649836a6f75ba96305618e67b36535a7af8 | Rishik999/BSc_IT_Python | /pracs/unit_7/prac_7a_class_student.py | 851 | 4.3125 | 4 | # CLASS STUDENT TO STORE AND DISPLAY INFORMATION
class Student:
# The __init__ is a special method used to initialise any class
# The parameters passed in the init method are necessary to create an instance of that class
def __init__(self, first, last, score):
self.first = first
self.last ... | true |
469f876e7eb620c0875414d8444c3e246977dec9 | Ghroznak/python_practice | /hangman.py | 1,608 | 4.1875 | 4 | # Hangman
import random
def make_a_word(strng): #create a def or remove it again? revert strng to secret_word if removed.
word_File_path = '/Users/RogerMBA/PycharmProjects/Hangman/english3.txt'
f = open('english3.txt', 'r')
lines = f.readlines()
for index, line in enumerate(lines):
lines[index] = line.strip('\n'... | true |
026bb3b7be0ea9e4d0577e90096a3edd68b8015b | sunny-g/ud036 | /lesson2/lesson2a.py | 2,399 | 4.4375 | 4 | ''' lesson 2 - building a movie website
build a site that hosts movie trailers and their info
steps:
1. we need:
title
synopsis
release date
ratings
this means we need a template for this data,
ex: avatar.show_info(), toyStory.show_trailer()
but we dont want to use s... | true |
7a305cdf89b311875b172dc6c4e74188ab6b0355 | greenfox-zerda-lasers/bereczb | /week-04/day-3/09.py | 504 | 4.15625 | 4 | # create a 300x300 canvas.
# create a square drawing function that takes 1 parameter:
# the square size
# and draws a square of that size to the center of the canvas.
# draw 3 squares with that function.
from tkinter import *
def draw_square(a):
canvas.create_rectangle(150 - a / 2, 150 - a / 2, 150 + a / 2, 150 +... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.