blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
54a10d41ef8a3bc55c624d1115bff0d731dff64f | androidSec/SecurityInterviews | /docs/custom_linked_list.py | 837 | 4.15625 | 4 | '''
Create a linked list that supported add and remove.
Numbers are added in ascending order, so if the list
was 1,3,5 and 4 was added it would look like 1,3,4,5.
'''
class custom_linked_list:
def __init__(self):
self.custom_list = []
def add(self, number):
if len(self.custom_list) == 0:
self.custom_list.app... | true |
51fce45bb405ab2fc62e3f0cdfd92759b9e4f515 | vijayb5hyd/class_notes | /turtle_race.py | 2,138 | 4.28125 | 4 | import turtle # Import every object(*) from module 'turtle'
from turtle import *
speed(100)
penup()
# The following code is for writing 0 to 13 numbers on the sheet
# By default, the turtle arrow starts at the middle of the page. goto(x,y) will take it to (x,y).
goto(-120,120)
for step in range... | true |
fdc37d4b6119ef863393cc36eec3fe8cbeafa09f | ramchinthamsetty/learning | /Python3/Advanced/decorators2.py | 2,605 | 4.65625 | 5 |
"""
1. Demystifying Decorators for Simple Use.
2. Helps in Building Libraries and Frameworks.
3. Encapuslating details and providing simple interface.
"""
def simple_func1(x):
'''
@return - Square of given values
'''
return x*x
# Passing the reference to a varibaale
# dec_func is stored ... | true |
bf5a57816608353f402c38cbb0f0294fbad96731 | cintax/dap_2019 | /areas_of_shapes.py | 944 | 4.21875 | 4 | #!/usr/bin/env python3
import math
def circle():
radius = int(input("Give radius of the circle: "))
print(f"The area is {math.pi*(radius**2):6f}")
def rectangle():
width = int(input("Give width of the rectangle: "))
height = int(input("Give height of the rectangle: "))
print(f"The area is {heigh... | true |
b6d75f871bb2a85f93d87234fd97c73cd7350ecf | hiSh1n/learning_Python3 | /Day_02.py | 1,249 | 4.3125 | 4 | #This is day 2
#some variable converters int(),str(), bool(), input(), type(), print(), float(), by default everything is string.
#Exercise 03-
#age finder
birth_year = input("what's your Birth Year:")
age = (2021 - int(birth_year))
print("your are " + str( age) + " years old !")
print(" ")
... | true |
b6ec7850d06b74c6009467c3dc860bde78298164 | DanielHabib/HowManyBalloons | /HowManyBalloonsAlg.py | 514 | 4.125 | 4 | """How Many Balloons Alghorithm"""
import math
class BalloonCount(object):
grams = 453.593
liters_in_balloon = 14
def __init__(self, weight):
self.weight = weight
def how_many_balloons(self):
balloons = self.weight * self.grams / self.liters_in_balloon
return ("It would take %... | false |
a61941a1d02f0fe26da9dfb3586341bcaa5cb419 | joshuaabhi1802/JPython | /class2.py | 793 | 4.125 | 4 | class mensuration:
def __init__(self,radius):
self.radius=radius
self.pi= 22/7
def area_circle(self):
area = self.pi*self.radius**2
return area
def perimeter_circle(self):
perimeter = 2*self.pi*self.radius
return perimeter
def volume_sphere(self):
... | true |
abd5cb0421cd452bdb1405cca6a680f7f7f2ead3 | mthompson36/newstuff | /codeacademypractice.py | 856 | 4.1875 | 4 |
my_dict = {"bike":1300, "car":23000, "boat":75000}
"""for number in range(5):
print(number, end=',')"""
d = {"name":"Eric", "age":26}
for key in d:
print(d.items()) #list for each key and value in dictionary
for key in d:
print(key, d[key]) #list each key and value in dictionary just once(not like above exampl... | true |
d416f36e048c95fd1d331c0e9b5d4dd64c16c7ca | rafaelsaidbc/Exercicios_python | /ex093.py | 1,246 | 4.125 | 4 | '''Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos durante o campeonato.'''
from ti... | false |
59a3f75b4cfc0851b9478a998b94262fdccdbece | rafaelsaidbc/Exercicios_python | /ex080.py | 783 | 4.25 | 4 | '''Crie um programa que o usuário possa digitar cinco valores numéricos e cadastre-os em uma lista, já na posição correta de inserção (sem usar o sort()). No final , mostre a lista ordenada na tela.'''
lista = []
for elemento in range(0, 5):
numero = int(input('Adicione um número na lista: '))
if elemento == 0 ... | false |
37277bbd39ba1a73e04a4d28d8e41a0eb04da7ad | rafaelsaidbc/Exercicios_python | /ex042.py | 947 | 4.34375 | 4 | '''Verificar se 3 retas podem formar um triângulo e qual tipo de triângulo elas formarão
- equilátero: todos os lados são iguais
- isósceles: dois lados iguais
- escaleno: nenhum lado igual'''
lado1 = float(input('Dê a medida de uma reta: '))
lado2 = float(input('Dê a medida de outra reta: '))
lado3 = float(input('Dê a... | false |
b3b88fe8ea17fd2a5d32e6ca796633d9855c7aa4 | Izaya-Shizuo/lpthw_solutions | /ex9.py | 911 | 4.5 | 4 | # Here's some new strange stuff, remember type it exactly
# Assigning the days variable with a string containing the name of all the 7 days in their short form
days = "Mon Tue Wed Thu Fri Sat Sun"
# Assigning the month variable with the name of the months from Jan to Aug in their short forms. After ech month's name the... | true |
41925bae39b1ab9472d933a9f9a87e11f076fa0a | entropy-dj/word2vec | /key_lambda_test.py | 612 | 4.28125 | 4 | """
在排序的时候,接使用sorted方法,返回一个列表就是排序好的
测试一下
啧啧啧
"""
a = [4, 2, 6, 1, 8, 3, 6, 3]
b = ["d", "a", "x", "w", "v", "c"]
print(sorted(a))
print(sorted(b))
print(sorted(a, reverse=True))
print(sorted(b, reverse=True))
"""
x[0]表示元组里的第一个元素,x[1]当然就是第二个元素;
"""
a = [("d", 4), ("a", 1), ("c", 9), ("b", 5), ("e", 2),... | false |
198144fb410628ec9afe4457204c78cb7df7d12e | priscilalobo/Python_Studies | /aulas/aula9.py | 1,052 | 4.125 | 4 | # Manipulando textos
'''frase = curso em video python
frase.split() = dividir uma string em uma lista
'-'.joint(frase) = junta as frases e separa pelo -
frase.count('o') - contar quantas strings especificas
len(frase) - contar quantas caracteres tem
frase.found('deo') - procurar na frase
a lista sempre começa a contar... | false |
9224069954e9e321b596b41d93630454b4b016ba | priscilalobo/Python_Studies | /Exercicios/exercicio59.py | 2,250 | 4.15625 | 4 | #Crie um programa que leia dois valores e mostre um menu na tela:
#[ 1 ] somar
#[ 2 ] multiplicar
#[ 3 ] maior
#[ 4 ] novos números
#[ 5 ] sair do programa
#Seu programa deverá realizar a operação solicitada em cada caso.
"""n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo numero: '))
esc... | false |
8df83445e494e7137b3ba2721433d7d63ba88244 | tudormihaieugen/DataScientistCourse | /Courses/Course1.py | 1,530 | 4.21875 | 4 | # # Type of variables
# a = 5
# print(type(a))
#
# # Power: ** (double * operator)
# print(2 ** 3) # =8
#
# # Area of circle
# pi = 3.14159
# radius = 2.2
# area = pi * (radius ** 2)
#
# # string concat
# hi = "Hello there"
# name = "Ana"
# greet = hi + " " + name
# print(greet)
#
# three_times = name * 3
# print(thre... | false |
d1608587d280fd2ed388aaa71241f856421f7648 | todaatsushi/python-data-structures-and-algorithms | /algorithms/sort/insertion_sort.py | 1,025 | 4.40625 | 4 | """
Insertion sort.
Sort list/array arr of ints and sort it by iterating through and placing each element
where it should be.
"""
def insertion_sort(arr, asc=True):
"""
Inputs:
- Arr - list of ints to be sorted. Assumes arr
is longer than 1 element long.
- asc - True for ascending, False for desce... | true |
453fc0baf0163d84d4b0b26ffa2164826bec58cf | fslichen/Python | /Python/src/main/java/Set.py | 207 | 4.34375 | 4 | # A set is enclosed by a pair of curly braces.
# Set automatically removes duplicate elements.
set = {'apple', 'pear', 'banana', 'apple'}
print(set)
if 'apple' in set:
print('Apple is in the set.') | true |
41bac5b84ed3e03a44faaf6a3cdcb39649e8ba0d | shubhamjain31/demorepo | /Python_practice/Practice_10.py | 330 | 4.125 | 4 | from collections import Counter
str = 'In the example below, a string is passed to Counter. It returns dictionary format, with key/value pair where the key is the element and value is the count. It also considers space as an element and gives the count of spaces in the string.'
count = Counter(str).most_common(10)
pr... | true |
6ad58d5245bad903ce16648f61d2a31508fe8b51 | Siddardha21/NUMERICAL-METHODS | /Differentiation_3_Formula.py | 2,974 | 4.15625 | 4 | from sympy import Symbol, Derivative
import sympy as sym
import math
x = Symbol('x')
# Given the Initial Conditions.
fx = x**3 - 6*x**2 + 11*x - 6
x_gvn = 0.5
h = 0.5
# ----------------------------------------------
x_plus_h = x_gvn + h
x_minus_h = x_gvn - h
# ------------------------------------... | false |
d39fd6e5e119959aa925225efd01b46abce8243f | tt-n-walters/uria-python | /adv_dictionaries/adv_dictionaries.py | 696 | 4.125 | 4 |
hair_colours = {
"Arthur": "ginger",
"Bill": "ginger",
"Charlie": "ginger",
"Draco": "blond",
"Errol": "feathers",
"Fred": "ginger",
"George": "ginger",
"Harry": "black"
}
# Accessing items that may not exist
print(hair_colours.get("Lucius", "Hair colour not found."))
# keys, values, ... | false |
ad947590ffed3dcfe73337bea8ffe8e68b6910ef | sky-bot/Interview_Preparation | /Educative/Permutation_in_a_String_hard/sol.py | 1,806 | 4.40625 | 4 | # Given a string and a pattern, find out if the string contains any permutation of the pattern.
# Permutation is defined as the re-arranging of the characters of the string. For example, “abc” has the following six permutations:
# abc
# acb
# bac
# bca
# cab
# cba
# If a string has ‘n’ distinct characters it will hav... | true |
a1ff9c00543721443a49cee0b3c9ecbe1741f740 | sky-bot/Interview_Preparation | /Educative/LinkedList/Palindrome_LinkedList.py | 1,343 | 4.125 | 4 | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def is_palindromic_linked_list(head):
slow = head
fast = head
tail = None
count = 1
middle = None
while(fast.next and fast.next.next):
slow = slow.next
fast = fast.next.n... | true |
179576de0a97a3a2957d7cdcedf93d53e203869e | Switters37/helloworld | /lists.py | 758 | 4.25 | 4 |
#print range(10)
#for x in range (3):
# print 'x=',x
#names = [['dave',23,True],['jeff',24,False],['mark',21,True]]
#for x in names:
# print x
#print names [1][1]
#numbers in square brackets above will index over in the list. So in this case, the list will index over 1 list, and then 1 space in th... | true |
1260a7849253566d81c9d5c8d0836f3c20b71bac | NihalSayyad/python_learnigs | /51DaysOfCode/017/Enumerator_in_py.py | 221 | 4.15625 | 4 | '''
In we are interested in an index of a list, we use enumerate.
'''
countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
for index, i in enumerate(countries):
print(f"country {i} is at index {index}") | true |
465380ce5b174a59245d0691e8394672def2d779 | devanbenz/PythonStuff | /MIT OCW/LectureSix/lectureSix.py | 2,618 | 4.40625 | 4 | ## Recursion -
# **Process of repeating items in a self-similar way
# '''Droste effect''' - picture within a picture
# Divide and conquer
# Decrease and conquer
# Algorithmically we reduce a problem into smaller parts in
#order to solve problems
# Semantically it is a function that is called within the body
#o... | true |
bb17f15513d9e77d524d9396beabff0470adab0e | sejalg1019/project-97 | /guessingGame.py | 559 | 4.3125 | 4 | import random
print("Number guessing game!")
number = random.randint(1,9)
chances = 0
print("Guess a number between 1-9 (You only have 5 chances to guess correctly)")
while chances < 5:
guess = int(input("Enter your guess:"))
if guess == number:
print("Congratulations, you won!")
break
... | true |
4158ddec48858494fea09623a6b935450fd87f4b | afatihirkli/data_science_practice | /physics-class.py | 1,139 | 4.15625 | 4 | # Codecademy Data Science Python Exercise : Getting Ready for Physics Class #
train_mass = 22680
train_acceleration = 10
train_distance = 100
impact_mass = 1
## Q1 ##
def f_to_c(f_temp):
c_temp = (f_temp - 32) * 5 / 9
return c_temp
## Q2 ##
f100_in_celsius = f_to_c(100)
print(f100_in_celsius)
## Q3 ##
def c_to_f... | false |
80be44b952612926061985837d905e02fea488ac | binoytv9/Think-Python-by-Allen-B-Downey--Exercises | /8th-chapter/12.py | 529 | 4.15625 | 4 | def rotate_word(word,num):
new=''
for letter in word:
if letter.isupper():
ordr=ord(letter)+num
if ordr > 90:
new+=chr(ordr-26)
elif ordr < 65:
new+=chr(ordr+26)
else:
new+=chr(ordr)
elif letter.islower():
ordr=ord(letter)+num
if ordr > 122:
new+=chr(ordr-26)
elif ordr < 97:
... | false |
1442cba523d9be466df5c0b11c09430da9ee2fde | sudhamshu091/Sorting-Techniques | /tim_sort.py | 1,606 | 4.125 | 4 | #sorting technique used by python in sorted()
#fastest sorting technique
#hybrid technique
#based on insertion sort and bubble sort
RUN = 32
""" insertion_sort function"""
def insertionSort(arr,left,right):
for i in range(left+1, right,1):
temp = arr[i]
j = i-1
while(arr[j]>t... | false |
19bc00052a6249859a29cbd57b55e1ac2821c175 | Nsk8012/TKinter | /1.py | 426 | 4.34375 | 4 | from tkinter import * #import Tkinter lib
window = Tk() #Creating window
window.title("Print") #Giving name of the window
l1 = Label(window, text="Hello World!",font=('Arial Bold',50)) #label is used to print line of text on window gui
l1.grid(column=0,row=0) #grid set the position of label on window
window.geometr... | true |
83119fa61c4da7286fba5de1586d2df40a5bcb7f | SW1992/100-Days-Of-Code | /Forty-third-day.py | 1,271 | 4.625 | 5 | # Day Forty Three
# Python Range & Enumerate
# range() function
# the python range function can be thought of as a form of loop
# it loops through & produces list of integer values
# it takes three parameters, start, end & step
# if you specify only an end value, it will loop up to the number (exclusive)
#... | true |
c3a81e455e13111e4f3d39301727e1b8a20ae464 | codingandcommunity/intro-to-python | /beginner/lesson7/caesar.py | 494 | 4.15625 | 4 | '''
Your task is to create a funcion that takes a string and turns it into a caesar cipher.
If you do not know what a caesar cipher is, here's a link to a good description:
https://learncryptography.com/classical-encryption/caesar-cipher
'''
def makeCipher(string, offset):
# Your code here
return string
s = i... | true |
b530e63e5290ca037d25b0d547fee2f963b91a26 | codingandcommunity/intro-to-python | /beginner/lesson7/piglatin.py | 655 | 4.28125 | 4 | '''
Write a function translate that translates a list of words to piglatin
ex) input = ['hello', 'world']
output = ['ellohay', 'orldway']
remember, you can concactenate strings using +
ex) 'hello' + ' ' + 'world' = 'hello world'
'''
def translate( ):
# Your code here
phrase = (input("Enter a phrase -> ")... | true |
6f5b4a260426de11c79686367fc4d854d3d2c10a | carlosarli/Learning-python | /old/str_methods.py | 458 | 4.21875 | 4 | name = 'lorenzo' #this is a string object
if name.startswith('lo'):
print('yes')
if name.find('lo') != -1: #.find finds the position of a string in a string, and returns -1 if it's not succesfull in finding the string in the string
print('yes')
delimiter = '.'
namelist = ['l', 'o', 'r', 'e', 'n', 'z', 'o']
pri... | true |
e7ce661b78ca1fb34ee44f025de804f0fc4cec29 | AkshayGulhane46/hackerRank | /15_string_split_and_join.py | 512 | 4.28125 | 4 | # Task
# You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen.
#
# Input Format
# The first line contains a string consisting of space separated words.
#
# Output Format
# Print the formatted string as explained above.
def split_and_join(line):
a = line.split(" ") # a is ... | true |
625abfb54078aa303cfc1e7d9f358a0fc1b6528d | kolodziejp/Learning-Part-1 | /Smallest_Value.py | 343 | 4.28125 | 4 | # Finding the smallest value in a range
small = None
print ("Let us look for the smallest value")
for number in [21, 42, 13, 53, -5, 2, 56, 119, -23, 99, 2, 3, 9, 87]:
if small is None:
small = number
elif number < small:
small = number
print (small, number)
print ("The smalle... | true |
c5f22e3b607f0af078e1506feb80d6d81041862c | kolodziejp/Learning-Part-1 | /Ex_5_1.py | 480 | 4.1875 | 4 | # entered numbers are added, counted and average computed
count = 0
total = 0
while True:
num = input ("Enter a number: ")
if num == "done":
break
try:
fnum = float(num) #convert to floating number
except:
print ("Invalid Data!")
continue # should... | true |
eb94db21432787349ffa87f4d1c7ea2da625a8c4 | Savirman/Python_lesson01 | /example04.py | 1,065 | 4.25 | 4 | # Программе нахождения наибольщей цифры в числе
# Пользователь вводит целое число произвольной длины
while True:
number = int(input("Введите целое положительное число: "))
# Проверяем введенное число. Если оно отрицательное, то выдаем сообщение об этом и просим ввести положительное число
if number < 0:
... | false |
e925e128a91016a06b95f1c88d3c9a7f8c1628f8 | ApurvaW18/python | /Day 3/Q2.py | 377 | 4.25 | 4 | '''
2.From a list containing ints, strings and floats,make three lists to store
them separately.
'''
l=['aa','bb','cc',1,2,3,1.45,14.51,2.3]
ints=[]
strings=[]
floats=[]
for i in l:
if (type(i))==int:
ints.append(i)
elif (type(i))==float:
floats.append(i)
else:
string... | true |
0ccd24589fd5833bd9dd205fe3bf34a315f533eb | ApurvaW18/python | /Day 6/Q2.py | 678 | 4.125 | 4 | '''
2.Write program to implement Selection sort.
'''
a = [16, 19, 11, 15, 10, 12, 14]
i = 0
while i<len(a):
s=min(a[i:])
print(s)
j=a.index(s)
a[i],a[j] = a[j],a[i]
i=i+1
print(a)
def selectionSort(array, size):
for step in range(size):
min_idx = step
for i... | true |
09e8a1f3816fcdbeba2632c33b93a7dbfc46d46d | JulietaCaro/Programacion-I | /Trabajo Practico 2/Ejercicio 11.py | 830 | 4.40625 | 4 | #11. Intercalar los elementos de una lista entre los elementos de otra. La intercalación
#deberá realizarse exclusivamente mediante la técnica de rebanadas y no se creará
#una lista nueva sino que se modificará la primera. Por ejemplo, si lista1 = [8, 1, 3]
#y lista2 = [5, 9, 7], lista1 deberá quedar como [8, 5, 1, ... | false |
2b957856684056fdad48fc84aa6edafa70598df9 | JulietaCaro/Programacion-I | /Trabajo Practico 4/Ejercicio 13.py | 1,539 | 4.1875 | 4 | # 13.Escribir un programa que cuente cuántas veces se encuentra una subcadena dentro de otra cadena, sin diferenciar
# mayúsculas y minúsculas. Tener en cuenta que los caracteres de la subcadena no necesariamente deben estar en forma
# consecutiva dentro de la cadena, pero sí respetando el orden de los mismos.
# F... | false |
9fef6a6753a7fc3f577a737d811d5179fe0d1435 | oski89/udemy | /complete-python-3-bootcamp/my-files/advanced_lists.py | 398 | 4.25 | 4 | l = [1, 2, 3, 3, 4]
l.append([5, 6]) # appends the list as an item
print(l)
l = [1, 4, 3, 3, 2]
l.extend([5, 6]) # extends the list
print(l)
print(l.index(3)) # returns the index of the first occurance of the item
l.insert(2, 'inserted') # insertes at index
print(l)
l.remove(3) # removes the first occurance
pr... | true |
800319d01235504239ac6011970662a0b9dc7a76 | Tduncan14/PythonCode | /pythonGuessGame.py | 834 | 4.21875 | 4 | #Guess my number
##
#The computer picks a random number between 1 and 100
#The player tries to guess it and the computer lets
#The player on guessing the numner is too high, too low
# or right on the money
import random
print("\tWelcome to 'Guess My Number'!")
print("\n I'm thinking of a number between 1 and 100.")
... | true |
78aa63ab11d675859c5f683cb02bbb1541bfbd18 | Arlisha2019/Calculator-EvenOdd-FizzBuzz | /EvenOdd.py | 215 | 4.28125 | 4 | user_number = int(input("Enter a number: "))
def even_or_odd():
if(user_number % 2 == 0):
print("You entered an even number!")
else:
print("You have entered an odd number!")
even_or_odd()
| false |
4741931113c64c098b5d06449bceafc4949bab1f | seen2/Python | /workshop2019/secondSession/function.py | 415 | 4.1875 | 4 | # without parameter
def func():
a, b = 10, 20
c = a+b
print(c)
# func()
def funcP(a, b):
'''
takes two integer and print its sum
'''
c = a+b
print(c)
# default argument comes last in parameter sequence.
def funcDefaultP(a, b=1, c=1):
'''
takes three integer and print its su... | true |
e90d7ae10791ac7dd407d940ed3e444770d087c1 | seen2/Python | /bitwiseOperators/bitwiseLogicalOperators.py | 406 | 4.125 | 4 | def main():
a=2 # 2=ob00000010
b=3 # 3=ob00000011
# logical operations
print(f"{a} AND {b}={a&b}")
print(f"{a} OR {b}={a|b}")
# takes binary of a and flips its bits and add 1 to it.
# whilch is 2 's complement of a
print(f"2's complement of {a} ={~a}")
# exclusive OR (... | true |
78c62c8944c81c10e80cc64673aab404ff0f4bd5 | GeorgeMohammad/Time2ToLoseWeightCalculator | /WeightLossCalculator.py | 1,081 | 4.3125 | 4 | ####outputs the amount of time required to lose the inputted amount of weight.
#computes and returns the amount of weight you should lose in a week.
def WeeklylbLoss(currentWeight):
return (currentWeight / 100)
#Performs error checking on a float.
def NumTypeTest(testFloat):
errorFlag = True
while(err... | true |
ff05aa7d85f2d7a414accb8daaebe64663c4606a | clementin-bonneau-riera/mathsPythonLycee | /pythagore/pythagoreCheck.py | 677 | 4.15625 | 4 | print("Vérifier la réciproque de Pythagore.")
print("Ne marche qu'avec des nombres entiers.")
a = input("longueur du côté A: ")
b = input("Longueur du côté B: ")
hyp = input("Longueur du côté C (hypoténuse): ")
a_b_lenght_square = pow(int(a), 2) + pow(int(b), 2) # additionne les carrés des côtés A et B
if a_b_lenght... | false |
24115f34af7e2162c885ffc7f22ec1f76550fc56 | Goku0858756/rzzzwilson | /talks/recursion_1/code/fibonacci.py | 1,228 | 4.21875 | 4 | #!/usr/bin/env python
"""
Recursive solution for the Fibonacci function.
With and without memoisation.
Usage: fibonacci <integer>
"""
import time
def fibonacci(n):
"""Return the 'n'th Fibonacci number."""
if n == 0:
return 0
if n == 1:
return 1
return fibonacci(n-1) + fibonacci(n-... | false |
de97d0426ab25ac5d7ff658ba6903b8770ab4382 | Goku0858756/rzzzwilson | /talks/recursion_1/code/hanoi.py | 1,132 | 4.21875 | 4 | #!/usr/bin/env python
"""
Recursive solution to the "Tower of Hanoi" puzzle.
[http://en.wikipedia.org/wiki/Tower_of_Hanoi]
Usage: hanoi <number_of_disks>
"""
def hanoi_original(n, src, dst, tmp):
"""Move 'n' disks from 'src' to 'dst' using temporary 'tmp'."""
if n == 1:
print('move %s to %s' % (src... | false |
b7df58e4d45c16fc5fe35e2ba028378c9cf227d8 | rcreagh/network_software_modelling | /vertex.py | 606 | 4.125 | 4 | #! usr/bin/python
"""This script creates an object of class vertex."""
class Vertex(object):
def __init__(self, name, parent, depth):
"""Initialize vertex.
Args:
name: Arbitrary name of the node
parent: Parent vertex of the vertex in a tree.
depth: Number of edges between the vertex itself ... | true |
b722454a775c2345a4ee44f318e38341872cb479 | gittangxh/python_learning | /ds_seq.py | 330 | 4.21875 | 4 | shoplist=['apple', 'mango','carrot','banana']
name = 'swaroop'
print('item -1 is', shoplist[-1])
print('character 0 is', name[0])
print('item 0 to 2 are:', shoplist[0:2])
print('item 1 to -1 are:', shoplist[1:-1])
print('reverse all items:', shoplist[-1::-1])
print('reverse the string:', name[-1::-1])
print(shopli... | false |
8c2e4e8110aa53f0b5ecffce8b2b80ba2bbeb1aa | gittangxh/python_learning | /io_input.py | 364 | 4.3125 | 4 | def reverse(text):
return text[::-1]
def is_palindrome(text):
newtext=''
for ch in text:
if ch.isalpha() and ch.isnumeric():
newtext+=ch.lower()
return newtext == reverse(newtext)
something = input('Enter text:')
if is_palindrome(something):
print('yes, it is palindrome')
el... | true |
6a6468dc982e95af935fbd3a353794d55da10dc2 | emiliobort/python | /Practica1/Programas/Ejercicio2.py | 1,118 | 4.125 | 4 | # Visualizar un cuadrado con su vértice inferior izquierdo en el origen
from turtle import *
#Inicializamos la pantalla
pantalla = Screen()
pantalla.setup(425,225)
pantalla.screensize(400,200)
#Asignamos las variables x e y, y pedimos al usuario valores del lado
x = 0
y = 0
lado = int(input("Dame el tamaño del lado... | false |
20c13fa236de48a3a418bbac633f32554381c7c1 | 8589/codes | /python/my_test/interview/generator.py | 504 | 4.125 | 4 | '''
show how to use generator, every generator is iteration, but not vice verse.
'''
def yrange(n):
# print n
i = 0
# print i
while i < n:
# print i
yield i
i = i + 1
y_iter = yrange(10)
# print y_iter.next()
# print y_iter.next()
for i in y_iter:
print i
# if __name__... | false |
a5eaf5cc98c6aa37fbeb170cd98631833be34eaa | RavinduTharaka/COHDSE182F-001.repo | /01_ceaser.py | 997 | 4.1875 | 4 | def encrypt(string, shift):
a = ''
for char in string:
if char.isalpha():
if char == ' ':
a = a + char
elif char.isupper():
a = a + chr((ord(char) + shift - 65) % 26 + 65)
else:
a = a + chr((ord(char) + shift - 97) % 26 + 97)
else:
print("Please enter... | false |
b54ece015da6564cd0c5c839f67149774f0e0888 | niteshsrivats/IEEE | /Python SIG/Classes/Class 6/regularexp.py | 2,377 | 4.375 | 4 | # Regular expressions: Sequence of characters that used for
# searching and parsing strings
# The regular expression library 're' should be imported before you use it
import re
# Metacharacters: characters with special meaning
# '.' : Any character "b..d"
# '*' : Zero or m... | true |
77f86f9689a16c3a8d9438a24b5d13b67bd6c6f0 | alanvenneman/Practice | /Final/pricelist.py | 614 | 4.125 | 4 | items = ["pen", "notebook", "charge", "scissors", "eraser", "backpack", "cap", "wallet"]
price = [1.99, .5, 4.99, 2.99, .45, 9.99, 7.99, 12.99]
pricelist = zip(items, price)
for k, v in pricelist:
print(k, v)
cart = []
purchase = input("Enter the first item you would like to buy: ")
cart.append(purchase)
second =... | true |
4e7693939c6098c938fce30f8915f19b80dc2ecd | SteveWalsh1989/Coding_Problems | /Trees/bst_branch_sums.py | 2,265 | 4.15625 | 4 | """
Given a Trees, create function that returns a list of it’s branch sums
ordered from leftmost branch sums to the rightmost branch sums
__________________________________________________________________
0 1
/ \
1 2 3
/ \ / \
2 4 5 6 7
/ \ ... | true |
a21b1e8a04826d5391cfa5eac83e0d4b12d22859 | SteveWalsh1989/Coding_Problems | /Arrays/sock_merchant.py | 634 | 4.3125 | 4 |
def check_socks(arr, length):
""" checks for number of pairs of values within an array"""
pairs = 0
# sort list
arr.sort()
i = 0
# iterate
while i < (length - 1):
# set values
current = arr[i]
next = arr[i + 1]
# check if the same sock or different
... | true |
70ed3e204149399b43259d4fa675d705cc4d9121 | yueranwu/CP1404_prac06 | /programming_language.py | 946 | 4.125 | 4 | """CP1404/CP5632 Practical define ProgrammingLanguage class"""
class ProgrammingLanguage:
"""represent a programming language"""
def __init__(self, name, typing, reflection, year):
"""Initiate a programming language instance
name: string, the name of programming language
typi... | true |
7804095933cc582dbff88b5369ed5d35f45e8c57 | JosephZYU/Python-2-Intermediate | /27.Python Tutorial for Beginners 8: Functions.py | 1,082 | 4.3125 | 4 | # https://youtu.be/9Os0o3wzS_I
def hello_func(name, host_name='Alexa'):
return (f'How are you {name}! This is your host {host_name} speaking\nHow may I help you today?')
# return (f'How are you! {name}\nHow are you twice! {name}')
# return (f'How are you! {name} ' * 3)
print(hello_func)
print()
print(he... | false |
e5cd322b04d126d2283dd2be8caed59f1985ef17 | Xuehong-pdx/python-code-challenge | /caesar.py | 667 | 4.1875 | 4 | from string import ascii_lowercase as lower
from string import ascii_uppercase as upper
size = len(lower)
message = 'Myxqbkdevkdsyxc, iye mbkmuon dro myno'
def caesar(message, shift):
""" This function returns a caesar (substitution) cipher for a given string where numbers,
punctuation, and other non-alphabe... | true |
cde0d233f7e9d53bd8e501fae8365584dadb402b | VitBomm/Algorithm_Book | /1.12/1_1_is_multiple.py | 355 | 4.3125 | 4 | # Write a short Python function, is_multiple(n, m), that takes two integer values and returns True if n
# is a multiple of m, n = mi for some integer i, and False otherwise
#
def is_multiple(n, m):
if n/m % 1 == 0:
return True
return False
n = eval(input("Input your n: "))
m = eval(input("Input your ... | true |
e1fb035396c96114dbc2b78f81f28faec0d812f0 | GustavoBonet/pythonexercicios | /ex.038.py | 270 | 4.15625 | 4 | um = int(input('Primeiro número:'))
dois = int(input('Segundo número:'))
if um == dois:
print('Os dois valores são IGUAIS')
elif um > dois:
print('O primeiro é maior')
elif dois > um:
print('O segundo é maior')
else:
print('Erro, tente novamente.')
| false |
45f2179deaa14abbb287fd2d956e12ce6bd3733e | Liam876/USEFUL_STUFF | /repos/factory.py | 1,877 | 4.15625 | 4 | from abc import ABC, abstractmethod
import math
from itertools import accumulate
import random
class Shape(ABC):
@abstractmethod
def perimeter ():
pass
@abstractmethod
def area():
pass
def __str__(self):
return "This is a shape"
class Triangle (S... | false |
ce4a2f26dff9b7aae290e08ea4e02a6054f4e650 | SBCV/Blender-Addon-Photogrammetry-Importer | /photogrammetry_importer/utility/type_utility.py | 385 | 4.15625 | 4 | def is_int(some_str):
""" Return True, if the given string represents an integer value. """
try:
int(some_str)
return True
except ValueError:
return False
def is_float(some_str):
""" Return True, if the given string represents a float value. """
try:
float(some_str)... | true |
52ae20a0eadb2ac4e684ef4920f6c105d6187a6d | jeffsnguyen/Python | /Level 1/Homework/Section_1_3_Functions/Exercise 5/variance_dof.py | 1,003 | 4.40625 | 4 | '''
Type: Homework
Level: 1
Section: 1.3: Functions
Exercise: 4
Description: Create a function that calculates the variance of a passed-in list.
This function should delegate to the mean function
(this means that it calls the mean function instead of containing logic
to calculate ... | true |
55568741e62e8f4da5189d2582f58916995cd8a3 | jeffsnguyen/Python | /Level_3/Homework/Section_3_2_Generators_101/Exercise_1/num_iterable.py | 883 | 4.46875 | 4 | # Type: Homework
# Level: 3
# Section: 3.2: Generators 101
# Exercise: 1
# Description: Contains the tests to iterate through a list of numbers
# Create a list of 1000 numbers. Convert the list to an iterable and iterate through it.
#######################
# Importing necessary packages
from random import random, se... | true |
a6948de57520137916bd17f153148e83f51d3f35 | jeffsnguyen/Python | /Level 1/Homework/Section_1_5_Dicts_and_Sets/Exercise 2/name_usuk.py | 2,581 | 4.21875 | 4 | '''
Type: Homework
Level: 1
Section: 1.5 Dicts and Sets
Exercise: 2
Description: Create two sets:
Set 1 should contain the twenty most common male first names in the United States and
Set 2 should contain the twenty most common male first names in Britain (Google it).
Perform the... | true |
92209793e197de9c33c0d3f6c219455620de4282 | jeffsnguyen/Python | /Level 1/Homework/Section_1_6_Packages/Exercise 2/anything_program/hello_world_take_input/take_input_triangle/take_input/take_input.py | 332 | 4.25 | 4 | '''
Type: Homework
Level: 1
Section: 1.1 Variables/ Conditionals
Exercise: 4
Description: Create a program that takes input from the user
(using the input function), and stores it in a variable.
'''
def take_input():
var = input('Input anything: ') # Take user's input and store in variable var
... | true |
c0f0fbf101b3a648ef5dfd24d760fdcca394c260 | jeffsnguyen/Python | /Level_3/Homework/Section_3_3_Exception_Handling/Exercise_2/divbyzero.py | 1,719 | 4.4375 | 4 | # Type: Homework
# Level: 3
# Section: 3.3: Exception Handling
# Exercise: 2
# Description: Contains the tests for handling div/0 exception
# Extend exercise 1) to handle the situation when the user inputs something other than a number,
# using exception handling. If the user does not enter a number, the code s... | true |
a1f40e6da78edd81dadd58f19b78490f33aeb4ea | jeffsnguyen/Python | /Level_4/Lecture/string_manipulation_lecture.py | 1,778 | 4.46875 | 4 | # string manipulation lecture
def main():
s = 'This is my sample string'
# indexing
print(s[0])
print(s[-1])
print()
# slicing
print(s[0:2:3])
print(s[:3])
print()
# upper: create a new string, all uppercase
print(s.upper())
print()
# lower: create a new string, ... | true |
5afb09b8eb3c629211076857bfc6b1f859d28f46 | jeffsnguyen/Python | /Level_4/Lecture/string_formatting_lecture.py | 1,421 | 4.21875 | 4 | # string formatting lecture
def main():
age = 5
print('Ying is %i years old'%age) # format flag i = integer
print('Ying is %f years old'%age) # format flag f = float
print('Ying is %.1f years old' % age) # format flag f = floag, truncate it 1 decimal place
print('Ying is %e years old' % age) # ... | true |
8251f87063be621d270c55e3c3849c758ae2f28b | jeffsnguyen/Python | /Level 1/Homework/Section_1_3_Functions/Exercise 1/day_of_week.py | 1,320 | 4.3125 | 4 | '''
Type: Homework
Level: 1
Section: 1.3: Functions
Exercise: 1
Description: Write a function that can print out the day of the week for a given number.
I.e. Sunday is 1, Monday is 2, etc.
It should return a tuple of the original number and the corresponding name of the day.
'''
import sys
#... | true |
0e7639bd5f7fc3b37bfa0cdbcd091fd94121e827 | jeffsnguyen/Python | /Level_3/Homework/Section_3_2_Generators_101/Exercise_4/fibonacci.py | 2,283 | 4.46875 | 4 | # Type: Homework
# Level: 3
# Section: 3.2: Generators 101
# Exercise: 4
# Description: Contains the tests to modified fn() method to generate Fibonacci sequence
# Modify the Fibonacci function from Exercise 1.3.2 to be a generator function. Note that the function
# should no longer have any input parameter sin... | true |
5792af4a3d9edc774bba3c6cf4bb7cba31ef6b0d | jeffsnguyen/Python | /Level_3/Homework/Section_3_1_Advanced_Functions/Exercise_1/test_hypotenuse.py | 1,140 | 4.375 | 4 | # Type: Homework
# Level: 3
# Section: 3.1: Advanced Functions
# Exercise: 1
# Description: This contains the method to test the hypotenus of a right triangle
# Create a stored lambda function that calculates the hypotenuse of a right triangle; it should take
# base and height as its parameter. Invoke (test) this lam... | true |
4f999f411dc875269cba559dcdfdcc478f3bdd7b | BrandonOdiwuor/Problem-Solving-With-Algorithms-and-Data-Structures | /queue/queue.py | 691 | 4.125 | 4 | class Queue:
def __init__(self):
self.queue_list = []
def is_empty(self):
'''
Returns a boolean indicating if the Queue is empty
Wost Case Complexity O(1)
'''
return self.queue_list == []
def size(self):
'''
Returns the size of the Queue
Worst Case Complexity ... | true |
61ee1f89ea4b3f3e0862c729f4bce4f91d96148a | BrandonOdiwuor/Problem-Solving-With-Algorithms-and-Data-Structures | /sorting-and-searching/sorting/insertion_sort.py | 575 | 4.375 | 4 | def insertion_sort(lst):
'''
Sorts a list in ascending order according to Insertion Sort algorithm
Time Complexity O(N^2)
'''
for index in range(1, len(lst)):
item = lst[index]
i = index
while i > 0 and item < lst[i - 1]:
lst[i] = lst[i - 1]
i = i - 1
lst[i] = item
return lst... | false |
5def4ffc1d4aa1f09363d0a3d3e86661085c23b0 | damingus/CMPUT174 | /weather1.py | 407 | 4.4375 | 4 | #This program sees whether 2 inputted temperatures are equal or not
#assign 'a' to the first temperature we ask for and 'b' for the next
a = input("What is the first temperature? ")
b = input("What is the second temperature? ")
#we convert 'a' into a string from an integer
a = str(a)
b = str(b)
if a == b:
print... | true |
3bb05110f4e61837f3033087526ee6f96e418f8d | andrew1236/python | /organism population calculator.py | 864 | 4.1875 | 4 | #ask user for number of intital organisms, the average increases of organisms, and how many days to calcualte
def calculate_organism_population():
organisms=int(input('Enter number of organisms:'))
average_increase =int(input('Enter average daily increase:'))
days=int(input('Enter number of days to multiply... | true |
e03234ead130d80f81f623ad279e8a1987578390 | Muhammadtawil/Python-Lessons | /set-part1.py | 822 | 4.3125 | 4 | # -----------------------------
# -- Set --
# ---------
# [1] Set Items Are Enclosed in Curly Braces
# [2] Set Items Are Not Ordered And Not Indexed
# [3] Set Indexing and Slicing Cant Be Done
# [4] Set Has Only Immutable Data Types (Numbers, Strings, Tuples) List and Dict Are Not
# [5] Set Items Is Unique
# --... | true |
2f9b3ee9e458ca2e53599ca5a3a1befd90d04268 | dshipman/devtest | /part_2_6.py | 621 | 4.25 | 4 | """
Write a short docstring for the function below,
so that other people reading this code can quickly understand what this function does.
You may also rename the functions if you can think of clearer names.
"""
def create_step_function(start_time, end_time, value):
"""
Create a step function that takes a si... | true |
d91fc95f364e491f76c5c341aa5d777caa2c1911 | AmirMoshfeghi/university_python_programming | /Functions/wine_house.py | 1,549 | 4.46875 | 4 | # Working with Functions
# Making a house wine project
# Wine Temperature must be closely controlled at least most of the time.
# The program reads the temperature measurements of the wine container
# during the fermentation process and tells whether the wine is ruined or not.
def main():
# Get number of measure... | true |
f6e66580b128af7d4d0f757ec2a1062eb40001c0 | baha312/chapter4_task7 | /task7.py | 735 | 4.1875 | 4 | # Implement Students room using OOP:
# Steve = Student("Steven Schultz", 23, "English")
# Johnny = Student("Jonathan Rosenberg", 24, "Biology")
# Penny = Student("Penelope Meramveliotakis", 21, "Physics")
# print(Steve)
# <name: Steven Schultz, age: 23, major: English>
# print(Johnny)
# <name: Jonathan Rosenberg, age... | false |
7fd2ed27b7956cf58308ab4832b503f4668fc8f3 | brunopurper/Python-Curso-em-Video | /ex022.py | 728 | 4.125 | 4 | #Exercício Python 22: Crie um programa que leia o nome completo de uma pessoa e mostre:
# – O nome com todas as letras maiúsculas e minúsculas.
#
# – Quantas letras ao todo (sem considerar espaços).
#
# – Quantas letras tem o primeiro nome.
nome = str(input("Digite seu nome: ")).strip()
nomeup= nome.upper()
nomelow= ... | false |
ae430661d281a65275da7d7230c35096d68c593e | Jayu8/Python3 | /assert.py | 636 | 4.125 | 4 | """
It tests the invariants in a code
The goal of using assertions is to let developers find the likely root cause of a bug more quickly.
An assertion error should never be raised unless there’s a bug in your program.
assert is equivalent to:
if __debug__:
if not <expression>: raise AssertionError
"""
# Asserts
a... | true |
b2d675b96a26428a9bd8695a2425a1d0f09dfe59 | netteNz/Python-Programming-A-Concise-Introduction | /problem2_5.py | 1,296 | 4.21875 | 4 | '''Problem 2_5:
Let's do a small simulation. Suppose that you rolled a die repeatedly. Each
time that you roll the die you get a integer from 1 to 6, the number of pips
on the die. Use random.randint(a,b) to simulate rolling a die 10 times and
printout the 10 outcomes. The function random.randint(a,b) will
generate an ... | true |
f3db3ba1af9a34c6b223dd1d4d0e55c99e1319fe | prudhvireddym/CS5590-Python | /Source/Python/ICP 2/Stack Queue.py | 852 | 4.15625 | 4 | print("Enter Elements of stack: ")
stack = [int(x) for x in input().split()]
con ="yes"
while con[0]=="y":
ans = input("Enter 0 for push\n1 for pop\n2 to print stack\n3 for Top most element : ")
while ans == "0":
a = int(input("Enter the element to append"))
stack.append(a)
print(stack)
... | true |
2853c45cb2b7883d73a62a288916aa026c6db2be | aligol1/beetroot111 | /lesson37.py | 1,421 | 4.59375 | 5 | """Task 1
Create a table
Create a table of your choice inside the sample
SQLite database, rename it,
and add a new column. Insert a couple rows inside
your table. Also, perform UPDATE and DELETE statements
on inserted rows.
As a solution to this task, create a file named: task1.sql,
with all the SQL statements you h... | true |
69eaa079f4ad20db8c19efa7af08adcdcf174e1a | aligol1/beetroot111 | /lesson14.py | 2,240 | 4.65625 | 5 | """Lesson 14 Task 1
Write a decorator that prints a function with arguments passed to it.
NOTE! It should print the function, not the result of its execution!
For example:
"add called with 4, 5"
def logger(func):
pass
@logger
def add(x, y):
return x + y
@logger
def square_all(*args):
return [arg ** 2 fo... | true |
7a85e32340f82247a32ce4f234a38b3b30c9ffc9 | Gwinew/To-Lern-Python-Beginner | /Tutorial_from_Flynerd/Lesson_4_typesandvariables/Task2.py | 817 | 4.21875 | 4 | # Make a list with serial movie
#
# Every serial movie should have assigned rate in scale 1-10.
# Asking users what they serial movie want to see.
# In answer give they rate value.
# Asking user if they want to add another serial movie and rate.
# Add new serial movie to the list.
# -*- coding: utf-8 -*-
dictserial={... | true |
b1077695d8b814286c878c7d809eed423b224f72 | Gwinew/To-Lern-Python-Beginner | /Tutorial_from_Flynerd/Lesson_3_formattingsubtitles/Task2.py | 886 | 4.125 | 4 | # -*- coding: utf-8 -*-
#
# Create a investment script which will have information about:
# -Inital account status
# -Annual interest rate
# -The number of years in the deposit
#
# Result show using any formatting text.
#
enter=input("Hi! This is Investment script.\nI want to help you to count your money impact at the ... | true |
931c283cfe56acb0b02c9e26205980a3fda9f4ff | Gwinew/To-Lern-Python-Beginner | /Pluralsight/Intermediate/Unit_Testing_with_Python/1_Unit_Testing_Fundamentals/2_First_Test/test_phonebook.py | 1,405 | 4.1875 | 4 | """Given a list of names and phone numbers.
Make a Phonebook
Determine if it is consistent:
- no number is a prefix of another
- e.g. Bob 91125426, Anna 97625992
- Emergency 911
- Bob and Emergency are inconsistent
"""
import unittest
#class PhoneBook: # Right-cli... | true |
3816745c2b680faf5ed5b87fb6a9cc7503a5a818 | 351116682/Test | /20.py | 572 | 4.25 | 4 | #coding=utf-8
'''
交换两个数的值
其实原理都是一样的,只不过Python可以借助于tuple,元组的形式来一次性的返回多个值
相对于其他编程语言而言,这真的很方便
'''
def change(a,b):
temp = a
a = b
b = temp
return a,b
def exchange(a,b):
a,b = b,a
return a,b
if __name__ == "__main__":
a ,b = 1,2
print '原来的值:%d---%d'%(a,b)
a,b = exchange(a,b)
pri... | false |
ee0eb65582ce9db9cc635038101221a257bbc5f6 | Aa-yush/Learning-Python | /BMICalc.py | 331 | 4.28125 | 4 | weight = float(input("Enter your weight in kg : "))
height = float(input("Enter your height in meters : "))
BMI = weight / (height**2)
if(BMI <= 18.5):
print("Underweight")
elif(BMI >18.5 and BMI <= 24.9):
print("Normal weight")
elif(BMI>24.9 and BMI<=29.9):
print("Overweight")
else:
print("... | true |
8a2edf5d14180fefe7c387a81465edb89c12eca0 | rohit98077/python_wrldc_training | /24_read_write_text_files.py | 816 | 4.375 | 4 | '''
Lesson 2 - Day 4 - read or write text files in python
'''
# %%
# read a text file
# open the file for reading
with open("dumps/test.txt", mode='r') as f:
# read all the file content
fStr = f.read()
# please note that once again calling f.read() will return empty string
print(fStr)
# this will... | true |
b096fbd435e5058f59aa46d546a0a4ade727fa69 | rohit98077/python_wrldc_training | /13_pandas_dataframe_loc.py | 574 | 4.125 | 4 | '''
Lesson 2 - Day 3 - Pandas DataFrame loc function
loc function is used to access dataframe data by specifying the row index values or column values
'''
#%%
import pandas as pd
# create a dataframe
df = pd.DataFrame([[2, 3], [5, 6], [8, 9]],
index=['cobra', 'viper', 'sidewinder'],
columns=['max_speed', 's... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.