blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
59d4865c48cf12bac99b751cec480b1aa52b59c5 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/simplify-path.py | 2,163 | 4.5 | 4 | """
# SIMPLIFY PATH
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period '.' refers to the current directory. Furthermore, a double period '..' moves the directory up a level.
Note that the returned canonical path mus... | true |
7028074d72039afc722149007fbae5fda2bba392 | SPARSHAGGARWAL17/DSA | /Linked List/linked_ques_4.py | 1,325 | 4.28125 | 4 | # reverse of a linked list
class Node():
def __init__(self,data):
self.data = data
self.nextNode = None
class LinkedList():
def __init__(self):
self.head = None
self.size = 0
def insertAtStart(self,data):
self.size += 1
node = Node(data)
... | true |
d9402c751d352b002fff94a55c3d4f322e231e8d | Unknown-Flyin-Wayfarer/pycodes | /9/testFor.py | 307 | 4.15625 | 4 | # i starts from 0, will increment by +1 stop at the range
for i in range(3):
print("My name is Amit, value of i = ",i)
for j in range(6,10):
print ("Value of j = ",j)
for z in range(10,50,5):
print("Value of z = ",z)
for y in range(100,10,-10):
print("value of y = ",y)
| false |
50dfd4b377425832e0a75179c16433e00d68ffda | Unknown-Flyin-Wayfarer/pycodes | /7/test_if4.py | 658 | 4.25 | 4 | a = int(input("enter first number"))
b = int(input("Enter second number"))
if a > b:
print("a is larger")
if a > 100:
print("a is also greater than 100")
if a > 1000:
print ("a is greater than 1000 also")
print("a is only greater than and not 1000")
p... | true |
7bfc463f05d5555ea2df2b2ca7d36a5a3e5d1d64 | aaroncymor/python-data-structures-and-algorithms | /Search and Sort/sort_implementation.py | 1,094 | 4.125 | 4 | # Hello World program in Python
def bubblesort(arr):
for i in range(len(arr)-1,0,-1):
for j in range(i):
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr
def insertionsort(arr):
for i in range(1... | false |
e0622163402f580a65518211eb3378994a15bec2 | rajeshpillai/learnpythonhardway | /ex9.py | 717 | 4.1875 | 4 | # Exercise 9: Printing, Printing, Printing
# By now you should realize the pattern for this book is to use more than one
# exercise to teach you something new. I start with code that you might not
# understand, then more exercises explain the concept. If you don't understand something now,
# you will later as you co... | true |
e4288c0c6d4b3d2decad9a22a96a79fe8b9502b7 | rajeshpillai/learnpythonhardway | /ex31.py | 2,038 | 4.59375 | 5 | # Exercise 32: Loops and Lists
# You should now be able to do some programs that are much more interesting. If you have been keeping up, you should realize that now you can combine all the other things you have learned with if-statements and boolean expressions to make your programs do smart things.
# However, program... | true |
b6350d9fb8134ecb5fa0d840315140af1c905978 | mauriceLC92/LeetCode-solutions | /Arrays/Selection-sort.py | 607 | 4.125 | 4 | def find_smallest(arr):
smallestIndex = 0
smallestValue = arr[smallestIndex]
index = 1
while index < len(arr):
if arr[index] < smallestValue:
smallestValue = arr[index]
smallestIndex = index
index += 1
return smallestIndex
def selection_sort(arr):
so... | true |
a11dae4297dd98f1a75943a3a4e5143e8d716922 | prathamesh-collab/python_tutorials-pratham- | /inheritance.py | 603 | 4.21875 | 4 | #!/usr/bin/env python3.7
#for inheritance
class person:
def __init__(myo,fname,lname):
myo.fname=fname
myo.lname=lname
def printname(myo):
print("hello,my name is " + myo.fname,myo.lname)
#child class ,parent is person class
class student(person):
def __init__(self,fname,lname,y... | false |
6f5e1666083599d3d40180ba5a488f7dc4512c24 | prathamesh-collab/python_tutorials-pratham- | /practice.py/cal_2020-14.py | 961 | 4.125 | 4 | #!/usr/bin/env python3.7
def menu():
print("welcome")
print(" " )
print("1:- addition")
print("2: subtraction")
print("3:- multiplication")
print("4:- division")
print("5:- quit")
print(" " )
return int(input("chose your option "))
def add():
a = int(input("enter 1st value : "... | false |
c6fb497553306801c5ee4c71ef33e19a832dd6f0 | has-g/HR | /fb_1_TestQuestions.py | 1,551 | 4.1875 | 4 | '''
In order to win the prize for most cookies sold, my friend Alice and
I are going to merge our Girl Scout Cookies orders and enter as one unit.
Each order is represented by an "order id" (an integer).
We have our lists of orders sorted numerically already, in lists.
Write a function to merge our lists of orders into... | true |
77d6e6cd9187f8c0b5dc63059a37a717873f3717 | OSUrobotics/me499 | /plotting/basic.py | 1,617 | 4.5 | 4 | #!/usr/bin/env python3
# Import the basic plotting package
# plt has all of the plotting commands - all of your plotting will begin with ply.[blah]
# To have this behave more like MatLab, do
# import matplotlib.pyplot
# in which case the plt scoping isn't needed
import matplotlib.pyplot as plt
# Get some thin... | true |
744b7479288431296863e7d8d2254c0cd58c1ea4 | OSUrobotics/me499 | /files/basics.py | 760 | 4.40625 | 4 | #!/usr/bin/env python3
if __name__ == '__main__':
# Open a file. The second argument means we're opening the file to write to it.
f = open('example_file', 'w')
# Write something to the file. You have to explicitly add the end of lines.
f.write('This is a string\n')
f.write('So is this\n')
... | true |
84eb498c2dc5b63eb5942e3bd057b1d2602c0348 | OSUrobotics/me499 | /control/while_loops.py | 613 | 4.3125 | 4 | #!/usr/bin/env python3
if __name__ == '__main__':
# This is the basic form a while statement. This particular example is better suited to a for loop, though, since
# you know how many times round the loop you're going to go.
n = 0
while n < 5:
print(n)
n += 1
# This is a better e... | true |
23b5df5c6836f5759b1b820eb7d57fc51d9d70ff | OSUrobotics/me499 | /containers/list_comprehensions.py | 870 | 4.3125 | 4 | #!/usr/bin/env python3
from random import random
if __name__ == '__main__':
# Instead of enumerating all of the items in a list, you can use a for loop to build one. Start with an empty
# list.
a = []
# This will build a list of the first 10 even numbers.
for i in range(10):
a.append(i... | true |
7730f652b4b1bb37f4e2b33533317aca526af6c0 | Mksourav/Python-Data-Structures | /stringlibraryfunction.py | 819 | 4.15625 | 4 | greet=input("Enter the string on which you want to perform the operation::")
# zap=greet.lower()
# print("lower case of the inputted value:",zap)
#
# search=input("Enter the substring you want the find:")
# pos=greet.find(search)
# if pos=='-1':
# print("substring not found!")
# else:
# print("substring spotted... | true |
78345b42e8ff3dc48545a9d4d3bd1aeac5b74eef | HighPriestJonko/Anger-Bird | /Task1.py | 1,366 | 4.15625 | 4 | import math
v = int(input('Enter a velocity in m/s:')) # With which bird was flung
a = int(input('Enter an angle in degrees:')) # With respect to the horizontal
d = int(input('Enter distance to structure in m:'))
h = int(input('Enter a height in m:')) # Height of structure
g = -9.8 # m/s^2
degC = math.pi / 180
ar = a... | true |
8b11e8566191510812c33c50c77a9c4610904130 | ajakaiye33/pythonic_daily_capsules | /apythonicworkout_book/pig_latin.py | 1,814 | 4.21875 | 4 |
def pig_latin():
"""
The program should asks the user to enter an english word. your program should
then print the word, translated into Pig Latin.
If the word begins with a vowel(a,e,i,o,u), then add way to the end of the word e.g
so "air" becomes "airway" eat becomes "eatway"
if the word begi... | true |
25223ab1874f7cf1e492040faba073faba3881a4 | ajakaiye33/pythonic_daily_capsules | /make_car_drive.py | 469 | 4.125 | 4 |
class Car(object):
"""
make a car that drive
"""
def __init__(self, electric):
"""
receives a madatory argument: electric
"""
self. electric = electric
def drive(self):
if not self.electric:
return "VROOOOM"
else:
return "WH... | true |
44be8c3c7f6920bdb8329af683afa045634d682e | ajakaiye33/pythonic_daily_capsules | /concatenate_string.py | 602 | 4.34375 | 4 |
def concatenate_string(stringy1, stringy2):
"""
A function that receives two strings and returns a new one containing both
strings cocatenated
"""
return "{} {}".format(stringy1, stringy2)
print(concatenate_string("Hello", "World"))
print(concatenate_string("Hello", ""))
# some other way...
d... | true |
7ba818effcd4db9905ca6814f4679184224e9d27 | ajakaiye33/pythonic_daily_capsules | /color_mixer.py | 970 | 4.25 | 4 |
def color_mixer(color1, color2):
"""
Receives two colors and returns the color resulting from mixing them in
EITHER ORDER. The colors received are either "red", "blue", or "yellow" and
should return:
"Magenta" if the colors mixed are "red" and "blue"
"Green" if the colors mixed are "blue" and "... | true |
195b3d1288769e60d0aa6d0023f308a6e0675523 | ajakaiye33/pythonic_daily_capsules | /make_number_odd.py | 288 | 4.25 | 4 |
def make_number_odd(num):
"""
Receives a number, adds 1 to that number if it's even and returns the number
if the original number passed is odd, just return it
"""
if num % 2 == 0:
num += 1
return num
print(make_number_odd(2))
print(make_number_odd(5))
| true |
d46bd897ee359b69d2f3fc29d7d6803883590c23 | rhydermike/PythonPrimes | /primes.py | 1,641 | 4.40625 | 4 | #Prime number sieve in Python
MAXNUMBER = 1000 #Total number of numbers to test
results = [] #Create list to store the results
for x in range (1,MAXNUMBER): #Begin outer for loop to test all numbers between 1 and MAXNUMBER
isprime = True #Set boolean variable ispri... | true |
4221e1c6df47872d910c462da5e3aff516755f86 | doctor-blue/python-series | /Intermediate/strings.py | 503 | 4.15625 | 4 | # a = "Hello\nWorld"
# a = '''Lorem ipsum dolor sit amet,
# consectetur adipiscing elit,
# sed do eiusmod tempor incididunt
# ut labore et dolore magna aliqua.'''
# print(a)
# a = 'Hello'
# print(a[-5])
# print(len("banana"))
# for x in "banana":
# print(len(x))
# print("ca" not in "banana")
a = "Hello, ... | false |
3b25e59cd8ef2f769e36aca0497e4dd7b9db38ad | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise04_39.py | 744 | 4.21875 | 4 | import turtle
x1, y1, r1 = eval(input("Enter circle1's center x-, y-coordinates, and radius: "))
x2, y2, r2 = eval(input("Enter circle2's center x-, y-coordinates, and radius: "))
# Draw circle 1
turtle.penup()
turtle.goto(x1, y1 - r1)
turtle.pendown()
turtle.circle(r1)
# Draw circle 2
turtle.penup()
turtle.goto(x2,... | false |
7a02905d8b244c6e96eb871ff8099d6c0db26e03 | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise04_11.py | 1,309 | 4.125 | 4 | # Prompt the user to enter input
month = eval(input("Enter a month in the year (e.g., 1 for Jan): "))
year = eval(input("Enter a year: "))
numberOfDaysInMonth = 0;
if month == 1:
print("January", year, end = "")
numberOfDaysInMonth = 31;
elif month == 2:
print("February", year, end = "")
if year % 40... | true |
8eed6f99e34f720e1b6a2c0e7d406e938fbc11ff | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise11_27.py | 738 | 4.1875 | 4 | def main():
SIZE = 3
print("Enter a 3 by 3 matrix row by row: ")
m = []
for i in range(SIZE):
line = input().split()
m.append([eval(x) for x in line])
print("The column-sorted list is ")
printMatrix(sortColumns(m))
def reverse(m):
for i in range(len(m)):
for j ... | false |
be6bed1c6c15377c1bd5d78c321d8413fcb85bf5 | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise06_17.py | 643 | 4.28125 | 4 | import math
def main():
edge1, edge2, edge3 = eval(input("Enter three sides in double: "))
if isValid(edge1, edge2, edge3):
print("The area of the triangle is", area(edge1, edge2, edge3))
else:
print("Input is invalid")
# Returns true if the sum of any two sides is
# greater than the th... | true |
2608df1e9d7d7a7dabfc23600cc0ab47b70883a3 | EvgenyTyurin/Dictionary-demo | /dict.py | 571 | 4.34375 | 4 | # Bill Lubanovich "Introducing Python"
# Chapter 3, Exercises 10-14: Dictionary demo
# English/French dictionary
e2f = {
"dog": "chien",
"cat": "chat",
"walrus": "morse"}
print("English/French dictionary: " + str(e2f))
# Walrus in french?
print("walrus in french = " + e2f["walrus"])
# Ma... | false |
0a685439e88369e8b563d1960fa8fc846e9fe2d5 | Renatabfv/T-cnicas-de-Programa-o | /projeto_2.py | 1,332 | 4.15625 | 4 | #cadastrar novos usuários pelo seu nome completo e e-mail
#exibir todos os usuários cadastrados, listando-os por ordem de cadastro.
#exibir todos os usuários cadastros, listando-os por ordem alfabética.
#um usuário faz parte da lista de participantes, buscando-o pelo seu nome.
#remover um usuário cadastrado, buscando-o... | false |
5a326e8c133c4fb3fc2d0581f1c8d6c7feb72376 | Ayman-M-Ali/Mastering-Python | /Assignment_015.py | 2,725 | 4.15625 | 4 | #--------------------------------------------------------
# Assignment (1):
# Write the following code to test yourself and do not run it
# After the last line in the code write a comment containing the Output that will come out from your point of view
# Then run Run to see your result sound or not
# Make a com... | true |
073cb8b4c68463b903c6b033228e849ca8a1136f | Athithya6/Python-Programs | /trial4.py | 901 | 4.25 | 4 | # List comprehensions and while loop
# Celsius to fahrenheit using ordinary for loop
'''
celsius = [12.5, 36.6, 37, 43, 49]
fahrenheit = []
for i in celsius:
caltemp = (((9 / 5) * i) + 32)
fahrenheit.append(caltemp)
print("Input Celsius tempertures in fahrenheit: ", fahrenheit)
'''
'''
# Celsiu... | false |
694a06ab8f7ca681fb5b16f273cb2be1f725abbd | Lydia-Li725/python-basic-code | /排序.py | 369 | 4.1875 | 4 | def insertion_sort(array):
for index in range(1,len(array)):
position = index
temp_value = array[index]
while position > 0 and array[position - 1] > temp_value:
array[position] = array[position-1]
position -= 1
array[position] = temp_value
return a... | true |
027ddb1b8268b0d843d0c987d8c31eda833b9bbf | mxmaria/coursera_python_course | /week5/Ближайшее число.py | 562 | 4.125 | 4 | # Напишите программу, которая находит в массиве элемент, самый близкий по величине к данному числу.
n = int(input())
mass_elems = list(map(int, input().split()))
diff_from_number = int(input())
min_diff_elem = mass_elems[0]
min_diff = abs(min_diff_elem - diff_from_number)
for elem in mass_elems:
curr... | false |
b1f37d0a9a5d003672c1c3d17a2c72b0a9094b57 | mxmaria/coursera_python_course | /week4/Быстрое возведение в степень.py | 709 | 4.375 | 4 | # Возводить в степень можно гораздо быстрее, чем за n умножений!
# Для этого нужно воспользоваться следующими рекуррентными соотношениями: aⁿ = (a²)ⁿ/² при четном n, aⁿ=a⋅aⁿ⁻¹ при нечетном n.
# Реализуйте алгоритм быстрого возведения в степень.
def power(a, n):
if n == 0:
return 1
elif n == 1:
... | false |
b79fe6a6d388f0bc02d2ac304582ad39a54811c5 | mxmaria/coursera_python_course | /week3/Цена товара.py | 745 | 4.125 | 4 | # Цена товара обозначена в рублях с точностью до копеек, то есть действительным числом с двумя цифрами после десятичной точки.
# Запишите в две целочисленные переменные стоимость товара в виде целого числа рублей и целого числа копеек и выведите их на экран.
# При решении этой задачи нельзя пользоваться условными инс... | false |
26dafe823f7870dd47096c8e4bb4cb809cb95a0b | mxmaria/coursera_python_course | /week2/Узник замка Иф.py | 985 | 4.1875 | 4 | # За многие годы заточения узник замка Иф проделал в стене прямоугольное отверстие размером D×E.
# Замок Иф сложен из кирпичей, размером A×B×C. Определите, сможет ли узник выбрасывать кирпичи в море через это отверстие (очевидно, стороны кирпича должны быть параллельны сторонам отверстия).
# Программа получает на вхо... | false |
acbf854d06bfa1e458cf65cca8af844fb40cd094 | swavaldez/python_basic | /01_type_and_statements/04_loops.py | 620 | 4.21875 | 4 | # student_names = []
student_names = ["Mark", "Katarina", "Jessica", "Sherwin"]
print(len(student_names))
# for loops
for name in student_names:
print("Student name is {0}".format(name))
# for range
x = 0
for index in range(10):
x += 10
print("The value of x is {0}".format(x))
# start in 5 and ends in 9
... | true |
214f5b112c81efed5de997dd92b72e35383da87d | eMUQI/Python-study | /python_book/basics/chapter03_list/03-08.py | 352 | 4.125 | 4 | list_of_place = ['hangzhou','shanghai','meizhou','xian','beijing']
#1
print(list_of_place)
print(sorted(list_of_place))
print(list_of_place)
print(sorted(list_of_place,reverse = True))
print(list_of_place)
list_of_place.reverse()
print(list_of_place)
list_of_place.sort()
print(list_of_place)
list_of_place.sort(reve... | false |
a1ba2026687b109cdd7c72113cc222d4cffdd804 | cassandraingram/PythonBasics | /calculator.py | 1,427 | 4.1875 | 4 | # calculator.py
# Cassie Ingram (cji3)
# Jan 22, 2020
# add function adds two inputs
def add(x, y):
z = x + y
return z
#subtract function subtracts two inputs
def subtract(x, y):
z = x - y
return z
# multiply function multiplies two inputs
def multiply(x, y):
z = x * y
return z
# divide function divides two ... | true |
9527efcef31dba3ca25ec33f2115ebfc5ec1d53a | snowpuppy/linux_201 | /python_examples/example1/guessnum.py | 855 | 4.21875 | 4 | #!/usr/bin/env python
#Here we import the modules we need.
import random
random.seed() #We need to seed the randomizer
number = random.randint(0,100) #and pull a number from it.
trys = 10 #We're only giving them 10 tries.
guess = -1 #And we need a base guess.
while guess != number and trys != 0: #So, we need to let... | true |
26f06216b4cf66c2bb236dccb89ae7cf0d7b2713 | rchristopfel/IntroToProg-Python-Mod07 | /Assignment07.py | 2,304 | 4.125 | 4 | # ------------------------------------------------------------------------ #
# Title: Assignment 07
# Description: using exception handling and Python’s pickling module
# ChangeLog (Who,When,What):
# Rebecca Christopfel, 11-18-19, test pickle module
# Rebecca CHristopfel, 11-20-19, create try/except block for scri... | true |
919d4323cdb5dd99e5aff75710d00fe279bbf712 | XavierKoen/lecture_practice_code | /guessing_game.py | 254 | 4.125 | 4 | question = input("I'm thinking of a number between 1 and 10, what is it? ")
ANSWER = '7'
print(question)
while question != ANSWER:
question = input("Oh no, please try again. ")
print (question)
print("Congrtulations! You were correct, it was 7!") | true |
1a8f986972d5f0ec326aaeb3f901cc259bf47ecd | XavierKoen/lecture_practice_code | /name_vowel_reader.py | 786 | 4.125 | 4 | """
Asks user to input a name and checks the number of vowels and letters in the name.
"""
def main():
name = input("Name: ")
number_vowels = count_vowels(name)
number_letters = count_letters(name)
print("Out of {} letters, {}\nhas {} vowels".format(number_letters, name, number_vowels))
def count_vo... | true |
04cb412cecc6d49bd15ebde03cc729f51d1e19aa | milanvarghese/Python-Programming | /Internshala/Internshala Assignments/W5 Assignment - Connecting to SQLite Database/insert_data.py | 1,124 | 4.28125 | 4 | #Importing Necessary Modules
import sqlite3
#Establishing a Connection
shelf=sqlite3.connect("bookshelf.db")
curshelf=shelf.cursor()
#Creating a table with error check
try:
curshelf.execute('''CREATE TABLE shelf(number INT PRIMARY KEY NOT NULL ,title TEXT NOT NULL, author TEXT STRING, price FLOAT NOT NULL);''')
... | true |
76f3fe078aebe4ede0b70767e19ba901e4a7d7b7 | CamiloBallen24/Python-PildorasInformaticas | /Script's/00 - Otros/Metodos de Cadenas.py | 1,029 | 4.4375 | 4 | #TEMA: METODOS DE CADENA
################################################################
print("Ejemplo #1")
miCadena = "Hola"
print(miCadena.upper()) #Pasa a mayusculas tooo
print()
print()
print()
################################################################
####################################################... | false |
dc73601bced9a16c9b52abdb42a53b04df5da287 | Ktheara/learn-python-oop | /advaced-review/2.tuple.py | 959 | 4.5625 | 5 | # A tuple is a collection of objects which is ordered and immutable(unchangeable).
# https://www.python-engineer.com/courses/advancedpython/02-tuples/
# So similar to list but elements are protected
mytuple = ('a', 'p', 'p', 'l', 'e') #create a tuple
print(mytuple)
# number of elements
print(len(mytuple))
# number ... | true |
d7948b4af779d68ed87af1d832c4cf6c558ec274 | cuongv/LeetCode-python | /BinaryTree/PopulatingNextRightPointersInEachNode.py | 2,802 | 4.21875 | 4 | #https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
"""
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate ea... | true |
1dfcc2fe5bcac12d235391d073b5991fca58960b | sudhamshu091/Daily-Dose-of-Python-Coding | /Qsn_21/string_punctuation.py | 232 | 4.25 | 4 | from string import punctuation
string = "/{Python @ is actually an > interesting //language@ "
replace = '#'
for char in punctuation:
string = string.replace(char, replace)
print("String after replacement is: ", string)
| true |
88fa596a897959b76862605be56a153b606f4555 | devil-cyber/Data-Structure-Algorithm | /tree/count_node_complete_tree.py | 643 | 4.125 | 4 | from tree import Tree
def height_left(root):
hgt = 0
node = root
while node:
hgt += 1
node = node.left
return hgt
def height_right(root):
hgt = 0
node = root
while node:
hgt += 1
node = node.right
return hgt
def count_node(root):
if root is None:
... | true |
9179d31d9eeda1d0767924c0714b62e22875fb34 | MeeSeongIm/trees | /breadth_first_search_02.py | 611 | 4.1875 | 4 | # find the shortest path from 1 to 14.
# graph in list adjacent representation
graph = {
"1": ["2", "3"],
"2": ["4", "5"],
"4": ["8", "9"],
"9": ["12"],
"3": ["6", "7"],
"6": ["10", "11"],
"10": ["13", "14"]
}
def breadth_first_search(graph, start, end):
next_start = [(node, pat... | true |
21ef42736c7ef317b189da0dc033ad75615d3523 | LiloD/Algorithms_Described_by_Python | /insertion_sort.py | 1,505 | 4.1875 | 4 | import cProfile
import random
'''
this is the insertion sort Algorithm implemented by Python
Pay attention to the break condition of inner loop
if you've met the condition(the key value find a place to insert)
you must jump out of the loop right then
Quick Sort is Moderately fast for small input-size(<=30)
but weak for... | true |
bedf86dafe10f5dc96b2ebd355040ab2fdfbd469 | jpacsai/MIT_IntroToCS | /Week5/ProblemSet_5/Problem1.py | 1,832 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 6 16:04:29 2018
@author: jpacsai
"""
def build_shift_dict(self, shift):
'''
Creates a dictionary that can be used to apply a cipher to a letter.
The dictionary maps every uppercase and lowercase letter to a
character shifted down the a... | true |
5902f17e71a3630344ab79f9c22ee2985cb80d3e | GorTIm/DailyCoding | /2020-01-17-Medium-Google-DONE.py | 987 | 4.21875 | 4 | """
This problem was asked by Google.
You are given an array of nonnegative integers. Let's say you start at the beginning of the array
and are trying to advance to the end. You can advance at most, the number of steps that you're currently on.
Determine whether you can get to the end of the array.
For example, giv... | true |
8e0f519ea8d1c1fb701a718929fb35e1319c2faf | pemburukoding/belajar_python | /part002.py | 2,128 | 4.40625 | 4 | # Get input from console
# inputString = input("Enter the sentence : ")
# print("The inputted string is :", inputString)
# Implicit Type
# num_int = 123
# num_flo = 1.23
# num_new = num_int + num_flo
# print("Value of num_new : ", num_new)
# print("datatype of num_new : ", type(num_new))
# num_int = 123
# num_str ... | true |
639934c70afa23f042371ce06b3ed89fdd6245ca | baluneboy/pims | /recipes/recipes_map_filter_reduce.py | 1,824 | 4.53125 | 5 | #!/usr/bin/env python
"""Consider map and filter methodology."""
import numpy as np
def area(r):
"""return area of circle with radius r"""
return np.pi * (r ** 2)
def demo_1(radii):
"""method 1 does not use map, it fully populates in a loop NOT AS GOOD FOR LARGER DATA SETS"""
areas = []
for r... | true |
1e6201d2f6f6df652f7ca66b1347c59c3121d067 | ThoPhD/vt | /question_1.py | 918 | 4.25 | 4 | # Question 1. Given an array of integer numbers, which are already sorted.
# E.g., A = [1,2,3,3,3,4,4,5,5,6]
# • Find the mode of the array
# • Provide the time complexity and space complexity of the array, and your reasoning
# • Note: write your own function using the basic data structure of your language,
# please av... | true |
dc76d98797c421cf3ff6ca5de691aeec5ad29aa6 | VersionBeathon/Python_learning | /chapter_8/catch_exception.py | 1,648 | 4.28125 | 4 | # _*_ coding:utf-8 _*_
# 处理异常可以使用try/except语句来实现
try:
x = input('Enter the first number: ')
y = input("Enter the second number: ")
print x / y
except ZeroDivisionError:
print "The second number can`t be zero!"
# 不止一个except字句
try:
x = input('Enter the first number: ')
y = input("Enter the second... | false |
604be482da6a2aea20bf660763b23019eea9571f | cloudzfy/euler | /src/88.py | 1,356 | 4.1875 | 4 | # A natural number, N, that can be written as the sum and
# product of a given set of at least two natural numbers,
# {a1, a2, ... , ak} is called a product-sum number:
# N = a_1 + a_2 + ... + a_k = a_1 x a_2 x ... x a_k.
# For example, 6 = 1 + 2 + 3 = 1 x 2 x 3.
# For a given set of size, k, we shall call the smalle... | true |
03f028686704d0b223621546b04893a844ef9148 | NathanJiangCS/Exploring-Python | /Higher Level Python Concepts/Closures.py | 2,029 | 4.6875 | 5 | #Closures
'''
Closures are a record storing a function together with an environment: a mapping
associating each free variable of the function with the value or storage location
to which the name was bound when the closure was created. A closure, unlike a plain
function, allows the function to access those captured var... | true |
d3ea582ed28b3eaa9f7a0376c649bab202c94ffa | NathanJiangCS/Exploring-Python | /Higher Level Python Concepts/String Formatting.py | 2,862 | 4.125 | 4 | #String formatting
#Advanced operations for Dicts, Lists, and numbers
person = {'name':'Nathan', 'age':100}
#######################
#Sentence using string concatenation
sentence = "My name is " + person['name'] + ' and I am ' + str(person['age']) + ' years old.'
print sentence
#This is not readable as you have to ope... | true |
616e0af829a12d78b50fdf016704bb179d2a721c | RonakNandanwar26/Python_Programs | /zip_enumerate.py | 2,367 | 4.40625 | 4 | # zip
# zip returns iterator that combines multiple iterables into
# one sequence of tuples
# ('a',1),('b',2),('c',3)
# letters = ['a','b','c']
# nums = [1,2,3]
# lst = [4,5,6]
# print(zip(nums,letters,lst))
# # #
# for letters,nums,lst in zip(letters,nums,lst):
# print(letters,nums,lst)
# # unzip
... | true |
39c6cf72d27d1444e7fcb21d611ee5673a32b9f1 | fsicardir/sorting-algorithms | /mergeSort.py | 624 | 4.125 | 4 |
# Time complexity: O(n*log(n))
# Space complexity: O(n)
# Stable
def merge_sort(arr):
def merge(list1, list2):
i, j = 0, 0
merge = []
while i < len(list1) and j < len(list2):
if list1[i] > list2[j]:
merge.append(list2[j])
j += 1
else:... | false |
baa648fbc217616042bccd431787c762b2e8fc47 | wxhheian/lpthw | /ex41e.py | 2,047 | 4.59375 | 5 | ###继承####
#继承是一种创建新类的方式,在python中,新建的类可以继承一个或多个父类,父类又称为基类 或超类,新建的类称为派生类或子类
#继承分为单继承和多继承
# class ParentClass1: #定义父类
# pass
#
# class ParentClass2: #定义父类
# pass
#
# class SubClass1(ParentClass1): #单继承,基类是ParentClass1 派生类是SubClass1
# pass
#
# class SubClass2(ParentClass1,ParentClass2): #多继承
# pa... | false |
a7d494c37a77ff4aec474502cff553348d9e5c17 | alexander-zou/pycheats | /pyps/use_random.py | 1,548 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@File : use_random.py
@Author : alexander.here@gmail.com
@Date : 2020-07-10 16:55 CST(+0800)
@Brief : https://docs.python.org/zh-cn/3/library/random.html
'''
from __future__ import print_function
import random
print( 'random.random() generates 0 <= X < 1... | false |
9a84af3077b599c11231def2af09cb8ccf40141c | stavernatalia95/Lesson-5.3-Assignment | /Exercise #1.py | 448 | 4.5 | 4 | #Create a function that asks the user to enter 3 numbers and then prints on the screen their summary and average.
numbers=[]
for i in range(3):
numbers.append(int(input("Please enter a number:")))
def print_sum_avg(my_numbers):
result=0
for x in my_numbers:
result +=x
avg=result/le... | true |
bcacc85fdc2fde42a3f3636cedd1666adaa24378 | Chia-Network/chia-blockchain | /chia/util/significant_bits.py | 991 | 4.125 | 4 | from __future__ import annotations
def truncate_to_significant_bits(input_x: int, num_significant_bits: int) -> int:
"""
Truncates the number such that only the top num_significant_bits contain 1s.
and the rest of the number is 0s (in binary). Ignores decimals and leading
zeroes. For example, -0b01111... | true |
f3d569ebc4192a0e60d95944b91ac33bac1f17aa | chimaihueze/The-Python-Workbook | /Chapter 2/44_faces_on_money.py | 1,118 | 4.1875 | 4 | """
Individual Amount
George Washington $1
Thomas Jefferson $2
Abraham Lincoln $5
Alexander Hamilton $10
Andrew Jackson $20
Ulysses S. Grant ... | true |
87a475ae20b4dde09bc00f7ca8f0258ead316aa4 | chimaihueze/The-Python-Workbook | /Chapter 1/exercise24_units_of_time.py | 670 | 4.4375 | 4 | """
Create a program that reads a duration from the user as a number of days, hours,
minutes, and seconds. Compute and display the total number of seconds represented
by this duration.
"""
secs_per_day = 60 * 60 * 24
secs_per_hour = 60 * 60
secs_per_minute = 60
days = int(input("Enter the number of days: "))
hours =... | true |
621e85bdd3efd63d3d3fccd18e6d77d83ef9d6f3 | chimaihueze/The-Python-Workbook | /Chapter 1/exercise29_wind_mill.py | 1,266 | 4.4375 | 4 | """
When the wind blows in cold weather, the air feels even colder than it actually is
because the movement of the air increases the rate of cooling for warm objects, like
people. This effect is known as wind chill.
In 2001, Canada, the United Kingdom and the United States adopted the following formula for computing ... | true |
420c2501440b97e647d1eff05559561e5c5b3869 | chimaihueze/The-Python-Workbook | /Chapter 1/exercise23_area_of_a_regular-polygon.py | 531 | 4.46875 | 4 | """
Polygon is regular if its sides are all the same length and the angles between all of
the adjacent sides are equal.
Write a program that reads s and n from the user and then displays the area of a
regular polygon constructed from these values.
"""
# s is the length of a side and n is the number of sides:
import... | true |
61628dc6e1c6d4ba2c8bdc112d25aa1b2d334f96 | cheikhtourad/MLND_TechnicalPractice | /question2.py | 1,628 | 4.125 | 4 | # Question 2
# Given a string a, find the longest palindromic substring contained in a.
# Your function definition should look like question2(a), and return a string.
# NOTE: For quetions 1 and 2 it might be useful to have a function that returns all substrings...
def question2(a):
longest_pal = ''
# Base Case: The... | true |
3c6a3ffb396896360f45c373f871e4e15fafc181 | vivekinfo1986/PythonLearning | /Oops-Polymorphism_AbstractClass_Overwrite.py | 530 | 4.46875 | 4 | #Define a base class with abstract method and using inheritence overwrite it.
class Animal():
def __init__(self,name):
self.name = name
#Testing abstract class
def speak(self):
raise NotImplementedError('Subclass must implement this abstract method')
class Dog(Animal):
def speak(self)... | true |
649554a6af19f4c16562158e17a24a630a116fcd | arctan5x/jhu | /algorithms/sorting/insertion_sort.py | 609 | 4.1875 | 4 | def insertion_sort(lst):
if not lst:
return []
for i in range(1, len(lst)):
pivot_key = lst[i]
position = i - 1
while position > -1 and pivot_key < lst[position]:
lst[position + 1] = lst[position]
position -= 1
lst[position + 1] = pivot_key
return lst
if __name__ == "__main__":
# some tests
lst1... | false |
9dd09c27fa88d56e88778df9bee7ddf4edaa98ca | ShiekhRazia29/Dictionary | /samp7.py | 542 | 4.5 | 4 | #To check whether a key exists in a dictiory or not
#For that we use a key word called "in"
key_word_exists={'name':"Razia",'Age':22,'Course':"Software Engineering",
'present':"Navgurkul Campus"}
if 'name' in key_word_exists:
print("Yes the keyword name exists:",key_word_exists['name'])
else:
print("No t... | false |
3efc0fc73ac41af9ac77e905c7cf68b82a71a2d5 | brayan-mendoza/ejercicios_examen | /L-2.py | 357 | 4.21875 | 4 | # utlizando ciclos (loops) dinujar un triangulo de asteriscos
def triangulo(altura):
for numero_linea in range(altura):
espacios = altura - numero_linea - 1
print("", espacios)
asteriscos = 1 + numero_linea * 2
print (" " * espacios + "*" * asteriscos)
alt = int(input("int... | false |
cd4f7ca00ff3f3336e8899c75f10fc5d69fedc7e | AndyWheeler/project-euler-python | /project-euler/5 Smallest multiple/smallestMultiple.py | 1,105 | 4.15625 | 4 | import primeFactors
#primePower(num) returns True if num is a prime power, False otherwise
def primePower(num):
factors = primeFactors.primeFactorsOf(num)
#print "prime factors of " + str(num) + ": " + str(factors)
isPrimePower = not factors or factors.count(factors[0]) == len(factors)
return isPrimePo... | true |
4ca1429fa78294b81f05a18f22f23a5bad106c73 | jammilet/PycharmProjects | /Notes/Notes.py | 2,014 | 4.1875 | 4 | import random # imports should be at the top
print(random.randint(0, 6))
print('Hello World')
# jamilet
print(3 + 5)
print(5 - 3)
print(5 * 3)
print(6 / 2)
print(3 ** 2)
print() # creates a blank line
print('see if you can figure this out')
print(5 % 3)
# taking input
name = input('What is your name?')
print('... | true |
976d7a598201141e0a1b4ae033be763da80fd5b2 | Genyu-Song/LeetCode | /Algorithm/BinarySearch/Sqrt(x).py | 1,003 | 4.15625 | 4 | # -*- coding: UTF-8 -*-
'''
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
'''
class Solution(object):
def mySqrt(se... | true |
d188291d13c688c3fd3404e49c785336f160a075 | Genyu-Song/LeetCode | /Algorithm/Sorting/SortColors.py | 1,598 | 4.15625 | 4 | # -*- coding: UTF-8 -*-
'''
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are... | true |
f13838e403245f0e5e00dd3db6d7cdd4a3425631 | driscollis/Python-101-Russian | /code/Chapter 2 - Strings/string_slicing.py | 248 | 4.25 | 4 | # string slicing
my_string = "I like Python!"
my_string[0:1]
my_string[:1]
my_string[0:12]
my_string[0:13]
my_string[0:14]
my_string[0:-5]
my_string[:]
my_string[2:]
# string indexing
print(my_string[0]) # prints the first character of the string | true |
b7bdff3a5a9043d42ec3dd26c63c67c239f1b3cf | traj1593/LINEAR-PREDICTION-PROGRAM | /linearPrediction-tRaj-00.py | 1,173 | 4.25 | 4 | '''
Program: LINEAR PREDICTION
Filename: linearPrediction-tRaj-00.py
Author: Tushar Raj
Description: The program accepts two integers from a user at the console and uses them to predict the next number in the linear sequence.
Revisions: No revisions made
'''
### Step 1: Announce, prompt and get response
#Anno... | true |
42fd723316a51442c22fb676a3ec9f12ae82056b | HeimerR/holbertonschool-higher_level_programming | /0x0B-python-input_output/7-save_to_json_file.py | 302 | 4.125 | 4 | #!/usr/bin/python3
"""module
writes an Object to a text file
"""
import json
def save_to_json_file(my_obj, filename):
""" writes an Object to a text file, using a JSON representation"""
with open(filename, encoding="utf-8", mode="w") as json_file:
json_file.write(json.dumps(my_obj))
| true |
e5666f5f6d68cc0fbc6d57012f6b9c3e740a09a8 | bmihovski/PythonFundamentials | /count_odd_numbers_list.py | 429 | 4.15625 | 4 | """
Write a program to read a list of integers and find how many odd items it holds.
Hints:
You can check if a number is odd if you divide it by 2 and check whether you get a remainder of 1.
Odd numbers, which are negative, have a remainder of -1.
"""
nums_odd = list()
nums_stdin = list(map(int, input().split('... | true |
d03229593c9e605f31320e0200b0b258e191acee | bmihovski/PythonFundamentials | /sign_of_int_number.py | 581 | 4.25 | 4 | """
Create a function that prints the sign of an integer number n.
"""
number_stdin = int(input())
def check_int_type(int_to_check):
"""
Check the type of input integer and notify the user
:param int_to_check: Int
:return: message_to_user: Str
"""
if int_to_check > 0:
msg_to_user = f'T... | true |
f6a011b92ee7858403ea5676b01610ff962e1c0d | bmihovski/PythonFundamentials | /wardrobe.py | 2,079 | 4.21875 | 4 | """
On the first line of the input, you will receive n - the number of lines of clothes,
which came prepackaged for the wardrobe.
On the next n lines, you will receive the clothes for each color in the format:
" "{color} -> {item1},{item2},{item3}…"
If a color is added a second time, add all items from it and count th... | true |
d92a918b6cfb2f15386e235fdd3f2f2f3c7d8291 | heldaolima/MiniCursoIC | /PROVA/1) A.py | 584 | 4.15625 | 4 | print('''Questão1- Fazer um programa que peça uma quantidade de números e em seguida separar os números
que forem pares e colocar em um vetor e os que forem impares e colocar em outro vetor. Ao final printar
os vetores.''')
print('----------------')
pares = []
ímpares = []
quant = int(input('Quantos números deseja ins... | false |
fa8b2f12b38257a7111d00aca216f0251c8238b4 | juso40/ALDA_SS2019 | /sheet1/sieve.py | 861 | 4.125 | 4 | from math import sqrt
def sieve(sieve_up_to):
sieve_up_to=int(sieve_up_to)
is_prime = [True] * sieve_up_to #jede zahl ist eine potentielle primzahl
is_prime[0],is_prime[1]=False,False #0 und 1 sind keine Primzahlen
for n in range(2, int(sqrt(sieve_up_to)+1)): #bei 2(der erstenprimzahl) fängt man an
... | false |
b80cb0d8e3d127c6f859b761403cce0f9a9fcc0e | g423221138/chebei | /bs4_study.py | 1,766 | 4.21875 | 4 | #bs4官方文档学习
#例子文档
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http:/... | true |
c1279076e019dd32f1e2fd30c52d1831b9ffe504 | NicsonMartinez/The-Tech-Academy-Basic-Python-Projects | /For and while loop statements test code.py | 2,469 | 4.46875 | 4 |
mySentence = 'loves the color'
color_list = ['red','blue','green','pink','teal','black']
def color_function(name):
lst = []
for i in color_list:
msg = "{0} {1} {2}".format(name,mySentence,i)
lst.append(msg)
return lst
def get_name():
go = True
while go:
name = input('What... | true |
6b42b0ca8302c2642bf2becbacf273c22f9281d2 | lufe089/lfrincon | /material/IntroProg/Ejercicios/6. Diccionarios/Nivel0- ejemploLLenarDiccionario.py | 1,586 | 4.3125 | 4 | # Escriba un programa en Python que le solicite al usuario por pantalla un listado de números (para finalizar debe ingresar 0). Cree un diccionario en donde se almacene la siguiente información a partir de los números ingresados:
# Cantidad de números pares
# Cantidad de números impares
# Número mayor
# Número menor
# ... | false |
a59a8a3825c2b2d1c790e24f3fd2e7738b7b999d | veterinarian-5300/Genious-Python-Code-Generator | /Py_lab/Lab 1,2/plotting_a_line.py | 345 | 4.375 | 4 | # importing the module
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3,4,5]
# corresponding y axis values
y = [2,4,1,3,5]
# plotting the points
plt.plot(x, y)
# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# Title to plot
plt.title('Plot')
# function to ... | true |
41da6593087fa6ce2e17fff89aa8179832563cfb | prmkbr/misc | /python/fizz_buzz.py | 536 | 4.125 | 4 | #!/usr/local/bin/python
"""
Prints the numbers from 1 to 100. But for multiples of three print 'Fizz'
instead of the number and for the multiples of five print 'Buzz'.
For numbers which are multiples of both three and five print 'FizzBuzz'.
"""
def main():
"""
Main body of the script.
"""
for i in xra... | true |
69936d76f0ecd2b3f640c6015389fbcbe8d14821 | yodifm/Hacktoberfest2020 | /round.py | 705 | 4.1875 | 4 | import turtle
print("1. Draw circle")
print("2. Draw Tangent Circles in Python Turtle")
print("3. Draw Spiral Circles in Python Turtle")
print("4. Draw Concentric Circles in Python Turtle")
num = int(input("Enter a number: "))
if num == 0:
t = turtle.Turtle()
t.circle(100)
print(num)
elif ... | false |
5782fa59d65af071e8fb004f42c8321f17fb6fd3 | mljarman/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,383 | 4.25 | 4 | # TO-DO: Complete the selection_sort() function below
arr = [5, 2, 1, 6, 8, 10]
def selection_sort(arr):
# loop through n-1 elements
for i in range(len(arr)-1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
# iterat... | true |
de2c80883264b731c748c09d2a20c8c27995d03e | bjucps/cps110scope | /Lesson 2-3 String Processing/greeter.py | 481 | 4.21875 | 4 | # Demonstrates string processing
full_name = input('Enter your first and last name:')
if full_name == '':
print('You did not enter a name!')
else:
space_pos = full_name.find(' ')
if space_pos == -1:
print('You did not enter your first and last name!')
else:
first_name = full_name[0:spa... | true |
3d9018bea5f64544cb6abc8c06a27385262d73c3 | bjucps/cps110scope | /Lesson 2-4 Unit Testing/addnums.py | 409 | 4.1875 | 4 | def addNums(num: str) -> int:
"""Adds up all digits in `num`
Preconditions: `num` contains only digits
Postconditions: returns sum of digits in `num`
"""
sum = 0
for digit in num:
sum += int(digit)
return sum
def test_addNums():
assert addNums('123') == 6
if __name__ == "__ma... | true |
25d71f955e65b7fd8bd67850c5cc694e8eb5b2ba | meera-ramesh19/sololearn-python | /displaycalenderofthemonth.py | 1,511 | 4.25 | 4 | # input from the user the month and the year of the calendar and displaythe
#calendar for the month or the year
yearuser=int(input("Enter the year:"))
print(yearuser)
#monthuser=int(input("\nEnter the month : "))
#print(monthuser)
startday=input("Enter the day of the week:")
print(startday)
calendar=[('January',range... | false |
a8d363524dc77a216dbf6b331181ac9f05c7b4d8 | nong2013/Apple-to-Raspberry-Pi | /Early Lessons/python_strings_demo.py | 852 | 4.28125 | 4 | #python_Strings_demo
my_string ="and now for SOMEthing completely different"
my_silly_string ="silly walks"
pi_value= 3.1415926
integer_value = 123
print (my_string + ' -- The Ministry of ' + my_silly_string )
print (len(my_string))
print (my_string.capitalize())
print (my_string.upper())
print (my_string.lower())
p... | false |
09dcca918dee39291a7de4a3e15cbe89e3e7dfd6 | vinayakentc/BridgeLabz | /AlgorithmProg/VendingMachine.py | 1,042 | 4.3125 | 4 | # 10. Find the Fewest Notes to be returned for Vending Machine
# a. Desc > There is 1, 2, 5, 10, 50, 100, 500 and 1000 Rs Notes which can be
# returned by Vending Machine. Write a Program to calculate the minimum number
# of Notes as well as the Notes to be returned by the Vending Machine as a
# Change
# b. I/P > rea... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.