blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
279b97085dbd7235566c62bde9c4761ef6e87e0e | abhishekthukaram/Course-python | /Strings/longestpalindromesubstring.py | 612 | 4.21875 | 4 | """
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
"""
def longestPalindrome(s):
result = ""
if len(s) ==1:
result+=s
elif len(s) ==2:
if s == s[::-1]:
result+=s
return result
for i in range(len(s)+1):
for j in range(i, len(s)+1):
print s[i:j]
if s[i:j] == (s[i:j][::-1]) and len(s[i:j])>len(result):
result = s[i:j]
return result
print longestPalindrome("c") | true |
d162088f28ae906eac9636790590bf971e5ad407 | rileytaylor/csc110 | /4/ex1.py | 1,737 | 4.3125 | 4 | # Allison Obourn and Janalee O'Bagy
# CSc 110, Spring 2017
# Lecture 9
# This program prompts two people for their CS1 and CS2 grades
# computes their CS GPA and whether or not that GPA is
# high enough (so far) to be a CS major.
def main():
intro()
gpa1 = get_person_info()
gpa2 = get_person_info()
results(gpa1, 1)
results(gpa2, 2)
# prints out an introduction explaining what the program does
def intro():
print("This program reads data for two students and")
print("computes their Computer Science GPAs")
print()
# Takes a GPA (float) and person number (int) as parameters
# and outputs the person's GPA as well as whether or not the
# GPA is high enough to potentially be a CS major
def results(gpa, person):
print("Person " + str(person) + " GPA = " + str(gpa))
if(gpa >= 2.5):
print("accepted")
else:
print("not accepted")
# prompts the user for a 110 grade and a 120 grade.
# Assumes those grades will be capital single letters
# Returns the average GPA of those two grades as a float
def get_person_info():
print("Enter next person's information:")
grade110 = input("CS 110 grade? ")
grade120 = input("CS 120 grade? ")
print()
gpa110 = grade_to_gpa(grade110)
gpa120 = grade_to_gpa(grade120)
return (gpa110 + gpa120) / 2
# takes a string letter grade as a parameter and returns
# that grade converted to a GPA value (float). Assumes grade
# will be an uppercase letter.
def grade_to_gpa(grade110):
gpa = "A"
if(grade110 == "A"):
gpa = 4.0
elif(grade110 == "B"):
gpa = 3.0
elif(grade110 == "C"):
gpa = 2.0
elif(grade110 == "D"):
gpa = 1.0
else:
gpa = 0.0
return gpa
main()
| true |
439a0a5b91b1d2cd7d758904ae1af7487a4871e3 | hanaahwrub/python | /areavolume.py | 802 | 4.125 | 4 | import math
def areaCircle():
pi = math.pi
r = float(input("Input the radius of the circle : "))
area = pi * r * r
print ("Area of the circle is : %.2f" %area)
areaCircle()
def areaSquare():
s = float(input("Input one side of the square : "))
area = s * s
print("Area of the square is : %.2f" %area)
areaSquare()
def volumeSphere():
pi = math.pi
r = float(input("Input the radius of the sphere : "))
volume = 4/3 * pi * r ** 3
print("Volume of the sphere is : %.2f " %volume)
volumeSphere()
def volumeCylinder():
pi = math.pi
r = float(input("Input the radius of the cylinder : "))
h = float(input("Input the height of the cylinder : "))
volume = pi * r * r * h
print("Volume of the cylinder is : %.2f " %volume)
volumeCylinder() | false |
18980bb11e026549b19880a48575fa1190617ccd | dinhhuyminh03/C4T21 | /session10/dict_delete.py | 303 | 4.1875 | 4 | chracter = {
"name": "Minh",
"age": 19,
}
if "name" in chracter:
print("True")
else:
print("False")
if "nationality" in chracter:
print("True")
else:
print("False")
# print(chracter)
# del chracter[input("Enter what you which key value you want to delete: ")]
# print(chracter) | false |
2dc1750c44de3d1d1f90d02bc706d7f72e81d9d4 | drbubbles40-school/cse210-tc04 | /hilo/game/dealer.py | 2,645 | 4.15625 | 4 | from game.player import Player
class Dealer:
"""A class for the bot who directs the game. The responsibility of
this class of objects is to keep track of the score and control the
sequence of play.
Attributes:
keep_playing (boolean): Whether or not the player wants to keep playing.
score (number): The total number of points earned.
player (Player): An instance of the class of objects known as Player.
"""
def __init__(self):
"""The class constructor.
Args:
self (Dealer): an instance of Dealer.
"""
self.keep_playing = True
self.score = 0
self.player = Player()
def start_game(self):
"""Starts the game loop to control the sequence of play.
Args:
self (Dealer): an instance of Dealer.
"""
while self.keep_playing:
self.get_inputs()
self.do_updates()
self.can_draw()
self.do_outputs()
def get_inputs(self):
"""Gets the inputs at the beginning of each round of play. In this case,
that means taking the guess.
Args:
self (Dealer): An instance of Dealer.
"""
self.player.draw_card()
print(f"\nThe selected card is: {self.player.current_card}")
self.player.get_guess()
def do_updates(self):
"""Updates the important game information for each round of play. In
this case, that means updating the score.
Args:
self (Dealer): An instance of Dealer.
"""
points = self.player.get_points()
self.score += points
def can_draw(self):
"""Checks if score is 0 or below or if all cards have been used.
This method will set the keep_playing attribute to false, Ending the loop
Args:
self (Dealer): An instance of Dealer."""
if self.score <= 0:
return False
if len(self.player.cards) == 0:
return False
else:
return True
def do_outputs(self):
"""Outputs the important game information for each round of play. In
this case, that means the dice that were rolled and the score.
Args:
self (Dealer): An instance of Dealer.
"""
print(f"\nThe card is: {self.player.new_card}")
print(f"Your score is: {self.score}")
if self.can_draw():
choice = input("Keep Playing? [y/n] ")
self.keep_playing = (choice == "y")
else:
self.keep_playing = False
| true |
1c5880aa60cf19eba8e59b1ff23e9a3cd7a021d2 | Raphaelshoty/Python-Studies | /exercicio.py | 1,742 | 4.125 | 4 | ##class Employee:
## pass
##
## def __init__(self, firstName, lastName, age):
## self.__firstName = firstName
## self.__lastName = lastName
## self.__age = age
##
## def getFirstName(self):
## return self.__firstName
##
## def getLastName(self):
## return self.__lastName
##
## def getAge(self):
## return self.__age
##
##
##
##def main():
## pessoa = Employee("Candango","Qualquer",22)
##
## print("Employee First Name: {}".format(pessoa.getFirstName()))
## print("Employee Last Name: {}".format(pessoa.getLastName()))
## print("Employee Age: {}".format(pessoa.getAge()))
##
##main()
class Pessoa:
pass
firstName = None
lastName = None
age = None
def __init__(self, firstName , lastName , age ):
self.firstName = firstName
self.lastName = lastName
self.age = age
def getAge(self):
return self.age
def getLastName(self):
return self.lastName
def getFirstName(self):
return self.firstName
def setAge(self,age):
self.age = age
def setLastName(self, lastName):
self.lastName = lastName
def setFirstName(self, firstName):
self.firstName = firstName
def main():
print("First name: ",Pessoa.firstName)#class attr
print("Last name: ",Pessoa.lastName)#class attr
print("Age: ",Pessoa.age)#class attr
print("-------- changes------------")
pelego = Pessoa("","", 0)
pelego.setFirstName("Pelego")
pelego.setLastName("Doidão")
pelego.setAge(20)
print("Pelego's age : ",pelego.getAge())
print("Pelego's First Name: ",pelego.getFirstName())
print("Pelego's Last Name: ", pelego.getLastName())
main()
| false |
200cc7227829f8868537bc3fcdcdd2cca6adcdb6 | oGabrielF/DocumentationPython | /Python/Basic/Dictionary/dictionary.py | 733 | 4.28125 | 4 | # DICIONÁRIOS
# Dicionários são listas de associações composta por:
# -Uma chave
# -Um valor correspondente
# dicionario = {'CHAVE':'VALOR'}
my_dictionary = {"A":"AMEIXA", "B":"BANANA", "C":"CEREJA"}
# Para localizar os valores você não ira utilizar [0],[1],[2]...
# Você utiliza a chave que você colocou exemplro:
print(my_dictionary["A"])
# Navegar pelo meu dicionário
for key in my_dictionary:
print(key+"-"+my_dictionary[key])
for i in my_dictionary.items(): # Converte o dicionário em uma dupla.
print(i)
for i1 in my_dictionary.values(): # Irá retornar somente os valores do meu dicionário
print(i1)
for i2 in my_dictionary.keys(): # Retorna somente as chaves do meu dicionário
print(i2) | false |
f0e492c49673f2163e44af8436aef5a714f92cd9 | oGabrielF/DocumentationPython | /Python/Basic/ConditionalCommands/ConditionalCommands.py | 1,593 | 4.25 | 4 | # COMANDO IF
# Realiza testes condicionais.
# Executa um bloco se uma determinada condição for atendida.
# Avalia-se condição é verdadeira ou não.
# IF significa SE ou seja:
# A linha de baixo se lê: (Se x for igual a y:)
# if x == y:
# print("x é maior que y")
# Sintaxe:
# if condição:
# Executa_O_Code_Que_Tiver_Aqui
x = 1
y = 2
# Essa linha de baixo não foi exibida no console pois x não é maior que y então o comando ira parar pois não possui um else
if x > y: # Essa linha se lê: (Se x for maior que y:)
print("x é maior que y")
if y > x: # Essa linha se lê: (Se y for maior que x:)
print("y é maior que x")
# COMANDO ELSE
# O comando ELSE significa SE NÃO ou seja:
# x = 1 / y = 2
# if x > y:
# print("x é maior que y")
# else:
# print("x não é maior que y")
# O comando acima se lê: (Se x for maior que y: [executa uma linha de codigo] Se não: [Executa outra linha de codigo])
a = 1
b = 2
if a > b:
print("a é maior que b")
else:
print("a não é maior que b")
# COMANDO ELIF
# Caso haja necessidade de mais condições entre o if e o else
# ELIF siginifa SE NÃO SE ou seja:
if x == y: # Fazendo uma verificação
print("x é igual a y")
elif x == a: # Caso a verificação de cima der false ira começar essa verificação
print("x é igual a c")
else: # Caso as duas verificações de cima der falso irá passar essa linha de code
print("Todos os resultados estão errados.")
c = 1
d = 2
if x == y:
print("Números Iguais")
elif y > x:
print("y maior que x")
else:
print("Número Diferentes") | false |
ef04a36dea40a41df248e95bef86dd3ff9027b12 | oGabrielF/DocumentationPython | /Python/Basic/Repetition/for.py | 635 | 4.28125 | 4 | # LAÇO DE REPETIÇÃO FOR
# For significa para
lista1 = [1,2,3,4,5]
lista2 = ["Hello","World"]
lista3 = [0,"Hello","World",9.99,True]
for coloca_o_nome_que_quiser in lista3: # Para cada elemento da minha lista1 o valor i será atribuido a cada elementos da minha lista.
print(coloca_o_nome_que_quiser)
# LAÇO DE REPETIÇÃO FUNÇÃO RANGE
for i in range(10): # Irá exibir uma lista de 0 até 9 pois na computação começa pelo 0.
print(i)
for i1 in range(10,20): # Irá exibir uma contagem de 10 até 19
print(i1)
for i2 in range(10,20,2): # Irá exibir uma contagem de 10 até 19 contando de 2 em 2
print(i2) | false |
2518577f4aaf1f00d75367b7b9f0f703e8a91d2a | shaheen19/dsp | /python/q8_parsing.py | 1,137 | 4.34375 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
import csv
def read_data(filename):
with open(filename, 'r') as file:
reader = csv.reader(file)
premier_list = [record for record in reader]
return premier_list
def get_index_score_diff(goals):
i = 1
old_diff = 100000000
for records in goals[1:]:
diff = abs(int(records[5]) - int(records[6]))
if diff < old_diff:
index = i
old_diff = diff
i += 1
return index
def get_team(index_value, parsed_data):
return parsed_data[index_value][0]
footballTable = read_data('football.csv')
minRow = get_index_score_diff(footballTable)
print(str(get_team(minRow, footballTable))) | true |
2b8c30b145a4301c641aff2d95339fba817678e3 | imsoumya18/py_workbook_solution | /2. If Statement/55. Frequency to Name/Frequency to Name.py | 488 | 4.25 | 4 | f = float(input('Enter the frequency:'))
if (f < 3 * 10 ** 9):
print('Radio waves.')
elif (3 * 10 ** 9 <= f < 3 * 10 ** 12):
print('Microwaves.')
elif (3 * 10 ** 12 <= f < 4.3 * 10 ** 14):
print('Infrared light.')
elif (4.3 * 10 ** 14 <= f < 7.5 * 10 ** 14):
print('Visible light.')
elif (7.5 * 10 ** 14 <= f < 3 * 10 ** 17):
print('Ultraviolet light.')
elif (3 * 10 ** 17 <= f < 3 * 10 ** 19):
print('X rays.')
elif (f >= 3 * 10 ** 19):
print('Gamma rays.')
| false |
6efc3e4dc99ce316f2be4176a80ac0af71f84c2e | imsoumya18/py_workbook_solution | /1. Introduction to Programming/22. Area of a Triangle(again)/area.py | 255 | 4.3125 | 4 | from math import sqrt
s1 = float(input('Enter length of first side:'))
s2 = float(input('Enter length of second side:'))
s3 = float(input('Enter length of third side:'))
s = (s1+s2+s3)/2
a = sqrt(s*(s-s1)*(s-s2)*(s-s3))
print('Area of the triangle=',a) | false |
ec40833892ee68a3cd7f0a8bdc0f63f0e57644e4 | zouwen198317/TensorflowPY36CPU | /_1_PythonBasic/Dictionary.py | 1,196 | 4.125 | 4 | # Dictionary iterm are in brackets {} in key: values pairs
print("Data")
cars = {'factory': 'bmw',
'model': '550i',
'year': '2016'}
print(cars)
print("#" * 40)
print("Access by keys")
print(cars['model'])
print("#" * 40)
print("Nested Dictionary")
nestedcars = {'bmw': {'factory': 'bmw', 'model': '550i', 'year': '2016'},
'benz': {'factory': 'benz', 'model': 'benz 50i', 'year': '2017'}}
print(nestedcars['bmw']['year'])
print("#" * 40)
print("The keys in the nested Cars")
print(nestedcars.keys())
print("The values in the nested cars")
print(nestedcars.values())
print("The items in dict")
print(nestedcars.items())
print("#" * 40)
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3, 'B': 10}
mcase_frequency = {
k.lower():
mcase.get(k.lower(), 0) +
mcase.get(k.upper(), 0)
for k in mcase.keys()
}
frquence = {
b.lower(): # this is a function
mcase.get(b.upper(), 0) +
mcase.get(b.lower(), 0)
for b in mcase.keys()
}
print(frquence)
print(mcase_frequency)
# mcase_frequency == {'a': 17, 'z': 3, 'b': 34}
print({v: k for k, v in mcase.items()})
print("Here is the line "+ str([x ** 2 for x in range(10)]))
| false |
2ea511816f931fc9c0d4ac58f317b7fa8390ef51 | zouwen198317/TensorflowPY36CPU | /_1_PythonBasic/Tuples.py | 499 | 4.125 | 4 | #tuples are like list but
#they are immutavle
print("List of Numbers")
print("#" * 40)
listOfNumbers = [1,2,3]
print(listOfNumbers)
print("#" * 40)
print("Orgini al Tuples")
tupleOfNumnbers = (1,2,3)
print(tupleOfNumnbers)
print("Tuples access by index")
print(tupleOfNumnbers[0])
print("Tuples skip 1 by [:1]")
print(tupleOfNumnbers[1:])
print("Count how many match in tupl")
print(tupleOfNumnbers.count(3))
print("Ask where is the index of the values is ")
print(tupleOfNumnbers.index(2))
| false |
372f0404e35f6394e2b72618a423a20ef74b92ef | wayne676/Python_Concurrency_Notes | /page55_thread_modulepy.py | 1,441 | 4.125 | 4 | import _thread as thread
from math import sqrt
def is_prime(x):
if x < 2:
print('%i is not a prime number.' % x)
elif x == 2:
print('%i is a prime number.' % x)
elif x % 2 == 0:
print('%i is not a prime number.' % x)
else:
limit = int(sqrt(x)) + 1
for i in range(3, limit, 2):
if x % i == 0:
print('%i is not a prime number.' % x)
return
print('%i is a prime number.' % x)
my_input = [2, 193, 323, 1327, 433785907]
for x in my_input:
thread.start_new_thread(is_prime, (x,)) # start_new_thread(function, args_tuple, kwargs_dict)
a = input('Type something to quit: \n')
print('Finished')
"""
import _thread, it is very low level API, not recommanded to use
If comment out the a=input(''), then program may terminate without printing out any input, in other words, the program
terminates before the threads can finish executing.
$ python example2.py
Type something to quit: <--------------------
2 is a prime number.
193 is a prime number.
323 is not a prime number.
1327 is a prime number.
433785907 is a prime number.
$ python example2.py
323 is not a prime number.
2 is a prime number.
Type something to quit: <--------------------
193 is a prime number.
433785907 is a prime number.
1327 is a prime number.
so the last line of code is a workaround for the thread module finish all the threads before exit the program
""" | true |
86002343dff37e4b3165263a4205593915751614 | jieunyu0623/3522_A00998343 | /Assignments/Assignment1/userType.py | 944 | 4.15625 | 4 | import abc
from Assignments.Assignment1.users import Users
class UserType(abc.ABC):
"""
UserType abstract class for three different user types.
"""
def __init__(self):
"""
constructs an user type object.
"""
pass
@abc.abstractmethod
def lock_account(self, user: Users):
"""
locks the budget category if the user exceeds a specified amount.
:param user: Users
:return: None
"""
pass
@abc.abstractmethod
def warning_message(self, user: Users):
"""
gives the user warning message if the user exceeds a stated amount.
:param user: Users
:return: None
"""
pass
@abc.abstractmethod
def notification(self, user: Users):
"""
gives the user notification if the user exceeds a set amount.
:param user: Users
:return: None
"""
pass
| true |
4790a6d2a36efc60b01acf00688dbe7ea27c8719 | ethan5771/Ethans-Programming-Programs | /EthanMadLib.py | 761 | 4.125 | 4 | print ("Welcome to the mad lib project.")
name = input("What is your name?")
place = input("Name a place.")
verb = input("Name a verb.")
place_two = input("Name a different place.")
noun = input("Name a noun.")
name_two = input("What is another name?")
print("%s went to %s to %s. The next day %s went to %s to get %s for %s. They became friends and lived happily ever after. Until they got mauled by a bear and died." %(name, place, verb, name, place_two, noun, name_two))
text_file = open("Output.txt", "w")
text_file.write("%s went to %s to %s. The next day %s went to %s to get %s for %s. They became friends and lived happily ever after. Until they got mauled by a bear and died." %(name, place, verb, name, place_two, noun, name_two))
text_file.close()
| true |
bfa5b716adaadf7c02118e1811a3546af71e0242 | llpj/coding_the_matrix | /WORK_DPB/matrix/The_Function.py | 1,553 | 4.15625 | 4 | # version code 778a5ea1ddbc+
# Please fill out this stencil and submit using the provided submission script.
## 1: Problem 0.8.3Tuple Sum
def tuple_sum(A, B):
'''
Input:
-A: a list of tuples
-B: a list of tuples
Output:
-list of pairs (x,y) in which the first element of the
ith pair is the sum of the first element of the ith pair in
A and the first element of the ith pair in B
Examples:
>>> tumple_sum([(1,2), (10,20)],[(3,4), (30,40)])
[(4,6), (40,60)]
'''
return [(a[0] + b[0], a[1] + b[1]) for a, b in zip(A, B)]
## 2: Problem 0.8.4Inverse Dictionary
def inv_dict(d):
'''
Input:
-d: dictionary representing an invertible function f
Output:
-dictionary representing the inverse of f, the returned dictionary's
keys are the values of d and its values are the keys of d
Examples:
>>> inv_dict({'thank you': 'merci', 'goodbye': 'au revoir'})
{'merci':'thank you', 'au revoir':'goodbye'}]
'''
return {d[k]:k for k in d}
## 3: Problem 0.8.5Nested Comprehension
def row(p, n):
'''
Input:
-p: a number
-n: a number
Output:
- n-element list such that element i is p+i
Examples:
>>>row(10,4)
[10, 11, 12, 13]
'''
return [p + i for i in range(n)]
comprehension_with_row = [row(i, 20) for i in range(15)]
comprehension_without_row = [[i + j for j in range(20)] for i in range(15)]
## 4: Problem 0.8.10Probability_1
Pr_f_is_even = 0.7
Pr_f_is_odd = 1 - 0.7
## 5: Problem 0.8.11Probability_2
#Please give your solution as a fraction
Pr_g_is_1 = "4/10"
Pr_g_is_0or2 = "6/10"
| true |
46d0eb250ee3ba2d29035d7ff0b34a75ec20febc | lounotlew/CS-61A-Spring-2015 | /notes/trees.py | 2,373 | 4.25 | 4 | """Trees"""
"""Slicing: creates a new list."""
lst = [1, 2, 3, 4, 5]
sliced = lst[1:3]
# includes index 1, excludes index 3.
"""
>>> sliced
[2, 3]
"""
"""Tree Functions"""
def tree(root, branches=[]):
for branch in branches:
assert is_tree(branch), 'branches must be trees.'
return [root] + list(branches)
def root(tree):
return tree[0]
def branches(tree):
return tree[1:]
def is_tree(tree):
if type(tree) != list or len(tree) < 1:
return False
for branch in branches(tree):
if not is_tree(branch):
return False
return True
def is_leaf(tree):
return not branches(tree)
def fib_tree(n):
if n == 0 or n == 1:
return tree(n)
else:
left, right = fib_tree(n-2), fib_tree(n-1)
r = root(left) + root(right)
return tree(r, [left, right])
def count_leaves(n):
if is_leaf(n):
return 1
else:
counts = [count_leaves(b) for b in branches(tree)]
return sum(counts)
def leaves(tree):
"""Return a list containing the leaves of tree.
>>>leaves(fib_tree(5))
[1, 0, 1, 0, 1, 1, 0, 1]
"""
if is_leaf(tree):
return [root(tree)]
else:
return sum([leaves(b) for b in branches(tree)], [])
def partition_tree(n, m):
if n == 0:
return tree(True)
elif n < 0:
return tree(False)
elif m == 0:
return tree(False)
else:
left = partition_tree(n-m, m)
right = partition_tree(n, m-1)
return tree(m, [left, right])
def print_parts(tree, partition=[]):
if is_leaf(tree):
if root(tree):
print(partition)
else:
left, right = branches(tree)
print_parts(left, partition+[root(tree)])
print_parts(right, partition)
"""Tree Class"""
class Tree:
def __init__(self, entry, branches=()):
self.entry = entry
for branch in branches:
assert isinstance(branch, Tree)
self.branches = branches
def __repr__(self):
if self.branches:
return 'Tree({0}, {1})'.format(self.entry, repr(self.branches))
else:
return 'Tree({0})'.format(repr(self.entry))
def is_leaf(self):
return not self.branches
"""Binary Tree Class"""
class BinaryTree(Tree):
empty = Tree(None)
empty.is_empty = True
def __init__(self, entry, left=empty, right=empty):
for branch in (left, right):
assert isinstance(branch, BinaryTree) or branch.is_empty
Tree.__init__(self, entry, (left, right))
self.is_empty = False
@property
def left(self):
return self.branches[0]
@property
def right(self):
return self.branches[1]
| true |
07dc3932efe8a630417374bb410f9581643e1829 | lounotlew/CS-61A-Spring-2015 | /notes/mutable_values.py | 1,833 | 4.46875 | 4 | """Mutable Values"""
"""
Lists:
Mutable values that can change in the course
of a program.
Only lists and dictionaries can change.
"""
"""
Operations:
- lst.pop(): removes the last element of a list and returns it.
**add argument n to lst.pop() to remove nth index.**
- lst.append(x): adds x to the end of a list.
- lst.extend([a, b, c...]): adds [a, b, c...] to the
end of a list.
"""
suits = ['coin', 'string', 'myriad']
original_suits = suits
suits.pop() # removes and returns the final element.
suits.remove('string') # removes the first element that equals the argument.
suits.append('cup') # add an element to the end.
suits.extend(['sword', 'club']) # add all elements of a list to the end.
suits[2] = 'spade' # replace an element.
suits[0:2] # replace a slice.
[suit.upper() for suit in suits] # list comprehension.
[suit[1:4] for suit in suits if len(suit) == 5] # list comprehension with a condition.
"""Dictionaries"""
numerals = {'I': 1, 'V': 5, 'X': 10}
original_numerals = numerals
numerals['X'] = 11 # the value for key 'X' changes from 10 to 11.
numerals['L'] = 50 # adds key 'L' and corresponding value 50 to numerals.
numerals.pop('X') #removes the key 'X' and corresponding value 11 from numerals; returns 11.
"""
Dictionary Restrictions:
Dictionaries are unordered collection of key-value pairs.
A key cannot be a list or a dictionary (or any mutable type).
Two keys cannot be equal.
"""
def mystery(s):
s.pop()
s.pop()
def mystery2(s):
s[2:] = []
# mystery and mystery2 do the same thing for four = [1, 2, 3, 4].
"""
Tuples:
Protects immutable values from mutation.
Stored in parenthesis, not brackets.
Tuples can be used as keys for dictionaries.
"""
a = {tuple([1, 2]): 3}
b = tuple(x+1 for x in range(5)) #Tuple comprehension.
###Try not to use mutable values as arguments.###
| true |
9f6ebe67bc4ffff12763624aaec64f6098b6a697 | ro-mak/GeekbrainsPython | /lesson2/task3_2.py | 554 | 4.1875 | 4 | time_of_the_year_list = {(1, 2, 12): "winter", (3, 4, 5): "spring", (6, 7, 8): "summer", (9, 10, 11): "autumn"}
while True:
try:
month = int(input("Input a month: "))
if month not in range(1, 13):
raise Exception("Your number is out of range (1-12)")
for el in time_of_the_year_list.keys():
if month in el:
print(time_of_the_year_list[el])
break
break
except Exception as e:
print(f"There was an input error({e}). Please, type an int from 1 to 12.")
| true |
d6b3efe5a222ff24c0362f4e433a2a9db5712d63 | PacktPublishing/IPython-7-Cookbook | /Chapter04/code/heapsort.py | 761 | 4.28125 | 4 | #thanks to https://rosettacode.org/wiki/Sorting_algorithms/Heapsort#Python
def heapsort(lst):
''' Heapsort. Note: this function sorts in-place (it mutates the list). '''
# in pseudo-code, heapify only called once, so inline it here
for start in range(int((len(lst)-2)/2), -1, -1):
siftdown(lst, start, len(lst)-1)
for end in range(len(lst)-1, 0, -1):
lst[end], lst[0] = lst[0], lst[end]
siftdown(lst, 0, end - 1)
return lst
def siftdown(lst, start, end):
root = start
while True:
child = root * 2 + 1
if child > end: break
if child + 1 <= end and lst[child] < lst[child + 1]:
child += 1
if lst[root] < lst[child]:
lst[root], lst[child] = lst[child], lst[root]
root = child
else:
break
| true |
b69ecb102c3671c26b469df894b4433ec2ba119e | gokulvenkats/python-exercise | /scripts/list.py | 2,147 | 4.1875 | 4 | # Basic list exercises
# Fill in the definitions for the required functions. The main functions and the testing
# has been handled, so when you run a program, you will get an output of how many testcases
# passed and how many didn't.
# A. alphanum Score
def alphanum_score(words):
"""
The function takes a list of words as its argument.
Returns a score generated as follows,
> Start with a net score of 0
> If the element is a alpha-string, +1
> If the element is a number-string, -1
"""
# Add your code here
return
# B. Occurences
def occurences(words):
"""
The function takes a list of words as its argument.
Returns a list sorted by the number of times the letter 'a' occurs.
"""
# Add your code here
return
# C. Tuple Merge
def tuple_merge(tuples):
"""
The functions takes a list of 2-tuples as its argument.
Returns a list of the form -
[tuples sorted by first element, tuples sorted by second element]
"""
# Add your code here
return
def test(function, input, expected):
print('\nCASE :', input )
try:
assert function(input) == expected
print('TEST CASE PASSED ! EXPECTED : %s \nOBTAINED : %s' % (expected, function(input)))
except AssertionError:
print('TEST CASE FAILED ! EXPECTED : %s \nOBTAINED : %s' % (expected, function(input)))
def main():
print('\nA. alphanum Score')
test(alphanum_score, ['abc', '11', 'cde', 'rt', '2', 'word'], 2)
test(alphanum_score, ['1', '2', 'a', '3', 'b'], -1)
test(alphanum_score, [], 0)
print('\nB. Occurences')
test(occurences, ['apple', 'aardvark', 'empty'], ['empty', 'apple', 'aardvark'])
test(occurences, ['pple', 'rdvrk', 'empty'], ['pple', 'rdvrk', 'empty'])
print('\nC. Tuple Merge')
test(tuple_merge, [(1, 2), (3, 1), (2, 0), (2, 1)], [(1, 2), (2, 0), (2, 1), (3, 1), (2, 0), (3, 1), (2, 1), (1, 2)])
test(tuple_merge, [(7, 5), (5, 5), (7, 7), (3, 2), (1, 4)], [(1, 4), (3, 2), (5, 5), (7, 5), (7, 7), (3, 2), (1, 4), (7, 5), (5, 5), (7, 7)])
test(tuple_merge, [(14, 6), (3, 13), (8, 1), (15, 2), (5, 13)], [(3, 13), (5, 13), (8, 1), (14, 6), (15, 2), (8, 1), (15, 2), (14, 6), (3, 13), (5, 13)])
if __name__ == '__main__':
main()
| true |
ac8cbad6497bcf36a62f01c801d80920203e39dc | lphdev/python | /rps.py | 2,679 | 4.40625 | 4 | # Rock Paper Scissors
from random import randint
name = input("What is your name? ")
print("\nHello %s! Welcome to the Rock, Paper, Scissors's game. \nRemember the rules: rock beats scissors; paper beats rock; scissors beats paper. \nYou have to accumulate three points to win the game. Let's play!" % (name))
player_score = 0
comp_score = 0
while True:
list_choise = ["rock", "paper", "scissors"]
player_choise = input("\n%s, do you want to choose rock, paper or scissors? " % (name)).lower()
comp_choise = list_choise[randint(0,2)]
if player_choise == comp_choise:
print(" It's a tie! \n Score: %s %s : %s Computer" % (name, player_score, comp_score))
elif player_choise == "rock":
if comp_choise == "scissors":
player_score += 1
print(" Your rock beats computer's scissors! \n Score: %s %s : %s Computer" % (name, player_score, comp_score))
else:
comp_score += 1
print(" Computer´s paper beats your rock! \n Score: %s %s : %s Computer" % (name, player_score, comp_score))
elif player_choise == "scissors":
if comp_choise == "paper":
player_score += 1
print(" Your scissors beats computer's paper! \n Score: %s %s : %s Computer" % (name, player_score, comp_score))
else:
comp_score += 1
print(" Computer´s rock beats your scissors! \n Score: %s %s : %s Computer" % (name, player_score, comp_score))
elif player_choise == "paper":
if comp_choise == "rock":
player_score += 1
print(" Your paper beats computer's rock! \n Score: %s %s : %s Computer" % (name, player_score, comp_score))
else:
comp_score += 1
print(" Computer´s scissors beats your paper! \n Score: %s %s : %s Computer" % (name, player_score, comp_score))
else:
print(" Invalid input! You have not entered rock, paper or scissors, try again. \n Score: %s %s : %s Computer" % (name, player_score, comp_score))
if player_score == 3 or comp_score == 3:
print("\nTotal score: %s %s : %s Computer" % (name, player_score, comp_score))
if player_score > comp_score:
print("Congratulations %s! You win!" % (name))
else:
print("You lose %s, don't worry, try it again." % (name))
if input("\nRepeat the program? (Y/N)").strip().upper() != 'Y':
break
else:
player_score = 0
comp_score = 0
print("Let's get started again, %s!" % (name))
continue
| true |
edda3c531a2366d2815d5716aaf7f5b7b9ce5760 | 1987617587/lsh_py | /basics/day8/day8_class_test.py | 2,644 | 4.375 | 4 | """
# author Liu shi hao
# date: 2019/11/14 15:44
# file_name: day8_class_test
"""
# 示例:
# 自行车:
# 数据(属性或者状态): 车架尺寸、 车轮尺寸、 牌子、 材料名称…
# 操作(方法或者功能): 变速、移动、 修理…
#
import math
class Bike:
def __init__(self, carriage_geometry, vehicle_geometry, plate, materials) -> None:
super().__init__()
self.carriage_geometry = carriage_geometry
self.vehicle_geometry = vehicle_geometry
self.plate = plate
self.materials = materials
def shifting(self):
print("变速")
def move(self):
print("移动")
def repair(self):
print("修理")
# Windows窗口:
# 数据(属性或者状态): 颜色、 样式、 标题、 位置…
# 操作(方法或者功能): 打开窗口、 改变大小、 移动位置…
class Windows:
def __init__(self, color, style, title, location) -> None:
super().__init__()
self.color = color
self.style = style
self.title = title
self.location = location
def open_windows(self):
print("打开窗口")
def change_size(self):
print("改变尺寸大小")
def move_location(self):
print("移动位置")
# 鱼:
# 数据:年龄、大小、颜色、名字
# 操作:游泳、捕食、睡觉...
#
class Fish:
def __init__(self, age, size, color, name) -> None:
super().__init__()
self.age = age
self.size = size
self.color = color
self.name = name
def swim(self):
print("游泳")
def eat(self):
print("捕食")
def sleep(self):
print("睡觉")
# 编写圆类:
# 数据:半径、坐标
# 操作:求面积、求周长
class Circle:
def __init__(self, r, pos_x,pos_y) -> None:
super().__init__()
self.r = r
self.pos_x = pos_x
self.pos_y = pos_y
def find_area(self):
s = math.pi * self.r ** 2
print(s)
return s
def find_girth(self):
girth = math.pi * self.r * 2
print(girth)
return girth
# find_girth(1)
c1 = Circle(2, 3,3)
c3 = Circle(3, 5,5)
c2 = Circle(8, 0,0)
Circle.find_girth(c1)
print(f"在({c1.pos_x},{c1.pos_y})点画半径为{c1.r}的圆,他的周长是{c1.find_girth()},面积是{c1.find_area()}")
print(f"在({c2.pos_x},{c2.pos_y})点画半径为{c2.r}的圆,他的周长是{c2.find_girth()},面积是{c2.find_area()}")
print(f"在({c3.pos_x},{c3.pos_y})点画半径为{c3.r}的圆,他的周长是{c3.find_girth()},面积是{c3.find_area()}") | false |
1496b75d73de827d2f21b20176f0f6e0d43d7a93 | qademo2015/CodeSamples | /Python/013_find_second_least_common_in_array.py | 1,010 | 4.125 | 4 | ######################################################################
# this file contains function to find second least common element in
# array of integers
######################################################################
# this function uses some standard built-in Python methods
def find_second_common(list_of_int):
res_dict = {}
count_dict = {}
for elem in set(list_of_int):
count_dict[elem] = list_of_int.count(elem)
for key in count_dict.keys():
if count_dict[key] == list(set(count_dict.values()))[1]:
res_dict[key] = list(set(count_dict.values()))[1]
return res_dict
def main():
data_list = [5, 5, 4, 5, 4, 6, 6, 6, 1, 3, 3, 4, 4, 5, 4]
print(find_second_common(data_list))
data_list = [5, 5, 4, 5, 4, 6, 6, 6, 1, 3, 3, 4, 4, 5, 4, 8, 8]
print(find_second_common(data_list))
data_list = [5, 5, 4, 5, 4, 6, 6, 6, 1, 3, 3, 4, 4, 5, 4, 8, 8, 0]
print(find_second_common(data_list))
if __name__ == '__main__':
main() | false |
48175bfb53a63c722ae5d167a2027a8f8bd49ed0 | qademo2015/CodeSamples | /Python/010_substring_occurrence.py | 1,390 | 4.3125 | 4 | ######################################################################
# this file contains different implementations of finding index of
# first sub-string occurrence within given string and returning -1
# in case if nothing found
######################################################################
# this function uses built-in 'find' method
def get_index_1(string, substring):
return string.find(substring)
# this function uses built-in 'index' method
# which raises an exception if nothing found
def get_index_2(string, substring):
try:
return string.index(substring)
except ValueError:
return -1
# this function does not use built-in methods
def get_index_3(string, substring):
index = 0
if substring in string:
c = substring[0]
for char in string:
if char == c:
if string[index:index+len(substring)] == substring:
return index
index += 1
return -1
def main():
string = 'Stringwithmultiplecharacters'
substring_1 = 'multi'
substring_2 = 'abc'
print(get_index_1(string, substring_1))
print(get_index_1(string, substring_2))
print(get_index_2(string, substring_1))
print(get_index_2(string, substring_2))
print(get_index_3(string, substring_1))
print(get_index_3(string, substring_2))
if __name__ == '__main__':
main() | true |
8ff7db5bb4e257a52984ee1c63976299b8927123 | Michael-Wisniewski/algorithms-unlocked | /chapter 3/3_select_sort.py | 1,323 | 4.1875 | 4 | def sort(numbers, numbers_count):
"""Time complexity - Θ(n**2), memory consumption - O(n), replacements O(n).
>>> numbers = [8, 6, 7, 4, 5, 2, 3, 1]
>>> numbers_count = 8
>>> sort(numbers, numbers_count)
[1, 2, 3, 4, 5, 6, 7, 8]
"""
for i in range(0, numbers_count - 1):
index_of_min = i
for j in range(i + 1, numbers_count):
if numbers[j] < numbers[index_of_min]:
index_of_min = j
temp = numbers[index_of_min]
numbers[index_of_min] = numbers[i]
numbers[i] = temp
return numbers
def sort_with_swap_check(numbers, numbers_count):
"""If table is mostly sorted or replacement cost is high, we can add
elements swap check. Replacements - min Θ(1), max Θ(numbers_count - 1)
>>> numbers = [8, 6, 7, 4, 5, 2, 3, 1]
>>> numbers_count = 8
>>> sort(numbers, numbers_count)
[1, 2, 3, 4, 5, 6, 7, 8]
"""
for i in range(0, numbers_count - 1):
index_of_min = i
for j in range(i + 1, numbers_count):
if numbers[j] < numbers[index_of_min]:
index_of_min = j
if index_of_min != i:
temp = numbers[index_of_min]
numbers[index_of_min] = numbers[i]
numbers[i] = temp
return numbers
| true |
0de917ca9e6bd4b8d3f76bf24fec06eb3ec5eb93 | Michael-Wisniewski/algorithms-unlocked | /chapter 4/2_count_equal_keys.py | 1,046 | 4.21875 | 4 | def count_equal_keys(A, n, m):
"""Time complexity: Θ(n) if m is constant, memory consumption - Θ(n).
>>> numbers = [1, 0, 4, 2, 3, 0, 2, 0, 1]
>>> numbers_count = 9
>>> max_number = 4
>>> count_equal_keys(numbers, numbers_count, max_number)
[3, 2, 2, 1, 1]
"""
equal_keys = [0] * (m + 1)
for i in range(0, n):
index = A[i]
equal_keys[index] += 1
return equal_keys
def sort_by_counting_equal_keys(A, n, m):
"""Time complexity: Θ(n) if m is constant, memory consumption - Θ(n).
Works only for natural numbers without metadata.
>>> numbers = [1, 0, 4, 2, 3, 0, 2, 0, 1]
>>> numbers_count = 9
>>> max_number = 4
>>> sort_by_counting_equal_keys(numbers, numbers_count, max_number)
[0, 0, 0, 1, 1, 2, 2, 3, 4]
"""
equal_keys = [0] * (m + 1)
for i in range(0, n):
index = A[i]
equal_keys[index] += 1
sorted_list = []
for i in range(0, m + 1):
sorted_list += [i] * equal_keys[i]
return sorted_list
| true |
80e38eaa81b52f0db759fb2fd862f65a14b24fe3 | rexfordcode/codefights | /python/pressureGauges.py | 574 | 4.15625 | 4 | """
https://app.codesignal.com/arcade/python-arcade/drilling-the-lists/SkTfc263CQbGNMtoj
Given the pressures Harry wrote down for each pipe, return two lists: the first one containing the minimum, and the second one containing the maximum pressure of each pipe during the day.
Example
For morning = [3, 5, 2, 6] and evening = [1, 6, 6, 6],
the output should be
pressureGauges(morning, evening) = [[1, 5, 2, 6], [3, 6, 6, 6]]
"""
def pressureGauges(morning, evening):
return [[min(a, b) for a, b in zip(morning,evening)], [max(a, b) for a, b in zip(morning,evening)]]
| true |
31ca138ab4f6cd87443dd26e1b25e46bcb48dadb | sahadatsays/pythonStore | /PythonBasic/conditions.py | 457 | 4.3125 | 4 | age = 20
if age < 18:
print("You are Teenager. Because Your age is under 18")
else :
print("You are Adult. Because Your age is upto 18 Years")
#login and, or
if age < 1:
print("Under 1 years called Babby !")
elif (age == 2) or (age > 18):
print("Upto 2 years and Under 18 years, called teenage")
elif (age == 18) or (age > 40):
print('upto 18 and under or equal 40 its called adult')
else:
print('Upto 40 years called old man !') | true |
de2f3d2d43d0ece3158754e9a71648be6a9119b2 | jonathanthen/INFO1110-and-DATA1002-CodeDump | /xprime.py | 1,276 | 4.21875 | 4 | def modulus(num,divisor):
if type(num) != int or type(divisor) != int:
raise TypeError("Input(s) are not integers.")
else:
# Handle divisor equals to 0 case
if (divisor == 0):
return False
n = num
# Handle negative values
if n < 0:
count = 0
while n < 0:
n += divisor
count += 1
return n
else:
count = -1
while n > 0:
n -= divisor
count += 1
if n == 0:
return 0
else:
return num - (count * divisor)
import sys
try:
number = int(sys.argv[1])
except ValueError:
print("Invalid input")
if number > 1:
i = 2
if number == 2:
print("Prime")
else:
while i < number:
if number == 3:
print("Prime")
break
elif modulus(number,i) == 0:
print("Not Prime")
break
else:
i += 1
if i == number-1 and modulus(number,i+1) == 0:
print("Prime")
else:
print("Not Prime")
| true |
d4374f5d35f227735e3bebac6212115a60d6d259 | tashachin/coding-challenges | /lemur.py | 1,574 | 4.28125 | 4 | def lemur(branches):
"""Return number of jumps needed."""
assert branches[0] == 0, "First branch must be alive"
assert branches[-1] == 0, "Last branch must be alive"
# given a bunch of 0s and 1s, i have to return the num of jumps it takes the lemur
# to reach the last branch (last 0)
# she can only hop a distance of two branches max
# 0 - 0 - 1 - 0 - 0 - 1 - 0
# >>> 4
# in a simpler problem, if there were ONLY 0s, the max num is half the 0s
# 0 - 0 - 0 - 0
# >>> 2
# if i add the 1s, how does the logic change?
# 0 - 1 - 0 - 1 - 0 - 1 - 0
# >>> 3
# HINT: there will never be two 1s in a row
# one-to-three dead branches have the impact of one additional hop
# every three dead branches should add one hop
# 0 - 1 - 0 - 0 - 1 - 0 - 0 - 1 - 0 - 1 - 0
# >>> 6
# 0 - 0 - 0 - 0 - 0 - 0 - 0
# >>> 3
# in this case, though, the 1s doubled the hops BECAUSE of their placement
# the lemur can't hop two at a time because it has to scoot over one and then bound over the branch
# if the pattern goes 0, 1, 0, 1 the dead branches add one hop
# if the pattern goes 0, 1, 0, 0, 1, the dead branches double the hops
# How do I check for both cases?
# HINT: Involves loops and lists.
if len(branches) < 2: # If she's already where she needs to be, return zero jumps
return 0
# Let's handle our simplest case where no dead branches are involved
if 1 not in set(branches): # I'm looking in a set because that's O(1)
return len(branches) / 2 | true |
44853bce4f2b354c083129ada61b9505eeabdf9a | tashachin/coding-challenges | /reverse-string-in-place.py | 427 | 4.15625 | 4 | def reverse(characters):
"""Reverses a list of characters in place.
>>> "hello"
"olleh"
>>> "How are you?"
"?uoy era woH"
"""
left_index = 0
right_index = len(characters) - 1
while left_index < right_index:
characters[left_index], characters[right_index] = characters[right_index], characters[left_index]
left_index += 1
right_index -= 1
return characters
| true |
093d482a93abbeab61e942dddf11d970eb2c90f9 | tashachin/coding-challenges | /euler3.py | 1,421 | 4.28125 | 4 | """
1. factor is a thingy that a num can be evenly divided by
2. a prime num is a num that can only be divided by 1 and itself!!!!
3. a prime factor is a thingy that a num can be evenly divided by,
and that can only be divided by 1 and itself
"""
import math
def find_prime_factors(num):
"""Returns a list of all the factors for a given num that are prime.
>>> find_prime_factors(25)
5
>>> find_prime_factors(20)
5
>>> find_prime_factors(37)
37
"""
# range params exclude 1 and num. check for empty list later.
# factors = [i for i in range(2, num) if num % i == 0]
factors = []
if num % 2 == 0:
factors.append(2)
num = num / 2
# print factors, "after 2 logic"
def alter_range():
pass
# i all odd nums after 1, typecast to avoid floats
# range is stop exclusive
# step by 2 to avoid evens
for i in range(3, num + 1, 2):
# print i, "in for loop"
while num % i == 0:
factors.append(i)
num = num / i
# print factors
return max(factors)
# print find_prime_factors(600851475143)
# def is_prime(num):
# """
# >>> is_prime(7)
# True
# >>> is_prime(25)
# False
# """
# if find_factors(num):
# return False
# return True
# print find_prime_factors(600851475143)
if __name__ == "__main__":
import doctest
doctest.testmod() | true |
d5995bb6a91d04400240586530ceed2fd7baea9a | aaku1234/gittest | /practice.py | 2,387 | 4.15625 | 4 | #first assignment
'''print("hello my name is akash ")
a= ("äcad")
b= ("view")
print(a+b)
name= str(input("what is your name?"))
print(name)
age= int(input("what is your age?"))
print(age)
print("let's get started",end=".\n")
s= ("acadview")
course= ("python")
fee= (5000)
print('%s %s %d '%(s,course,fee))
pi= (3.14)
radius= int(input("what is the radius of circle "))
answer= pi*radius*radius
print("area of circle is ", answer)
'''
#date 23 assignment
#1.
'''year= int(input("year = "))
if year%4==0:
print("it is a leap year")
else:
print("it is not a leap year")
'''
#2.
'''length= int(input("length = "))
breadth = int(input("breadth = "))
if length==breadth:
print("it is a square")
else:
print("it is a rectangle")
'''
#3.
'''age1= int(input("age of first person= "))
age2= int(input("age of second person= "))
age3= int(input("age of third person= "))
if age1>age2 and age1>age3:
print("age1 is oldest")
elif(age2>age3):
print("age2 is oldest")
else:
print("age3 is oldest")'''
#4.
'''age = int(input("what is your age? = "))
sex = str(input("m of f? = "))
marital_status = str(input("marital status yes or no? = "))
if sex.upper()=="f":
print("work only in urban areas.")
elif((sex=="m" or sex=="M") and (age>=20 and age<=40)):
print("he may work in anywhere.")
elif((sex=="m" or sex=="M") and (age>=40 and age<=60)):
print("he will work in urban areas only.")
else:
print("error")
'''
#5.
'''print("cost of item is Rs 100/-")
print("Shop will give discount of 10% if the cost of purchased quantity is more than 1000")
quantity = int(input("quantity = "))
price = 100
if(quantity>10):
amount = ((quantity*price)/100)*10
print("discount: ",amount)
print("your bill: ",quantity*price-amount)
else:
print("your amount is :", quantity*price)'''
#loop
#1
'''a= 0
while a<=9:
b= int(input("enter the number"))
a=a+1
print(a)
'''
#2
'''while True:
print("hello")
'''
#3.
'''list = [ ]
while True:
number= int(input("type number = "))
list.append(number)
if number==0:
break
else:
print(number*number)'''
#4.
#5.
'''for number in range(1,101):
if number>1:
for i in range(2,number):
if(number%i)==0:
break
else:
print(number)
'''
#6.
'''a= []
while True:
a.append('*')
print(a)
'''
#7.
| false |
06e2b44f31d4b647be868d03b11a69421ae9f9cd | kevin-ss-kim/coding-problems | /linked_list/xor_linked_list.py | 2,137 | 4.1875 | 4 | '''
An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at index.
If using a language that has no pointers (such as Python), you can assume you have access to get_pointer and dereference_pointer functions that converts between nodes and memory addresses.
'''
# TODO: store size of the linked list to make get operation faster
class XORLinkedList:
class XORLinkedListNode:
def __init__(self, value):
self.both = 0 # XOR of prev and next node memory address
self.value = value
def __init__(self):
self.head = None # head XORLinkedListNode object
self.tail = None # tail XORLinkedListNode object
def get_pointer(self, node):
# Given a node, returns the memory address of the node
# Assumes that this method works correctly
return None
def dereference_pointer(self, address):
# Given an address, returns the node at the address
# Assumes that this method works correctly
return None
def add(self, element):
node = self.XORLinkedListNode(element)
if self.tail is None:
self.head, self.tail = node, node
else:
self.tail.both ^= self.get_pointer(node)
node.both = self.get_pointer(self.tail)
self.tail = node
def get(self, index):
if index == 0 or self.head == None:
return self.head
node = self.head
nextNode = self.dereference_pointer(node.both)
while (index > 0):
# store nextNode address before jumping
nextNodeAddress = self.get_pointer(nextNode)
# jump nextNode to next
nextNode = self.dereference_pointer(nextNode.both ^ self.get_pointer(node))
# jump node to next
node = self.dereference_pointer(nextNodeAddress)
return node | true |
7f0f48293a12c585764878909d063725f71931c7 | kevin-ss-kim/coding-problems | /string/remove_white_spaces.py | 447 | 4.125 | 4 | def remove_white_spaces(string):
# O(n) runtime, O(1) space
read_index = 0
write_index = 0
while read_index < len(string):
if string[read_index] != ' ':
string[write_index] = string[read_index]
write_index += 1
read_index += 1
return "'" + ''.join(string[:write_index]) + "'"
if __name__ == '__main__':
string = input("Enter a string: ")
print(remove_white_spaces(list(string))) | false |
20897ae3b12e197c1b51fed79dee0ac9afbfd5e7 | Kushendra1/csci127-assignments | /ClassworkNotes/Python/hw_05Solu.py | 1,155 | 4.15625 | 4 | #Mapping- showing the relationship between two functions or lists and maps it onto
#another
def mapsq(l):
result = []
for item in l:
result = result + [item*item]
return result
l = [1,2,3,4,3,2,1]
print(mapsq(l))
def filter_odd(l):
result = []
for item in l:
if item %2 !=0 :
result.append(item)
return result
print(filter_odd(l))
def filter_even(l):
result = []
for item in l:
if item %2 ==0 :
result.append(item)
return result
print(filter_even(l))
def is_odd(n): #This is a predicate function, same for odd and big.
return n%2==1
def is_even(n):
return n%2==0
def is_big(n):
return n>5
def myfilter(predicate,l):
result=[]
for item in l:
if predicate(item):
result.append(item)
return result
print(myfilter(is_odd, l))
def make_upper(w):
return w[0].upper()+w[1:]
def mymap(f,l):
result = []
for item in l:
result.append(f(item))
return result
sentence = "when shall we meet again"
print(sentence.split())
print(sentence.split("e"))
wl = sentence.split()
print(" ".join(wl)) | false |
b6b123f794048e613ec2787b5272fb856f04db69 | sleepyheead/Numpy-Tensorflow-ScikitLearn_Exercises | /Numpy/generate-random-matrix-of-array-and-dot-product.py | 967 | 4.3125 | 4 | import numpy as np
# For example, to create an array filled with random values between 0 and 1, use random function.
# This is particularly useful for problems where you need a random state to get started.
# But here the elements will be decimals
A = np.random.rand(2,3)
print(A)
""" Output of above
[[0.62857547 0.14598864 0.93991874]
[0.65560569 0.29442998 0.3354452 ]] """
A = np.random.random([2,3]) # Or this is also equivalent
print(A)
'''
numpy.random.random like many of the other numpy.random methods accept shapes, i.e. N-tuples. So really the outside parenthesis represent calling the method numpy.random.random(), and the inside parenthesis are syntactic sugar for instantiating the tuple (3, 3) that is passed into the function.
'''
# Create Matrix (2,3) with random between 0 and 1 and INTEGER (i.e. NOT decimal)
B = np.random.randint(10, size=(3,2))
# print(B)
print(B.T)
# Dot product
print(np.dot(A, B))
# transpose
# print(np.dot(A, B).T)
| true |
da4d9a0e13beb9c912813b2c612aa0829038b9c0 | vtsenin/geekbrains-python | /lesson-03-task/task-03-01.py | 1,170 | 4.34375 | 4 | '''
Урок 3. Задание 1.
Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
'''
def division_func(var_1, var_2):
"""
Функция, принимающая два числа (позиционные аргументы) и выполняющую их деление
:param var_1: Первое число
:param var_2: Второе число
:return:
"""
try:
return var_1 / var_2
except ZeroDivisionError:
return f"Деление на ноль!!!"
def user_input():
"""
Запрос числа у пользователя
:return:
:rtype int
"""
user_input = input(f"Введите число >>>")
if not user_input.isdigit():
print("Неверный формат ввода")
exit()
return int(user_input)
num_1 = user_input()
num_2 = user_input()
print(division_func(num_1, num_2))
| false |
32ea85ab9db1390a418066a5dd81211a152cee64 | truckson/playtime | /lesson4playtime.py | 1,457 | 4.25 | 4 | # Challenge level: Beginner
# Scenario: You have two files containing a list of email addresses of people who attended your events.
# File 1: People who attended your Film Screening event
# https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/film_screening_attendees.txt
#
# File 2: People who attended your Happy hour
# https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/happy_hour_attendees.txt
# Note: You should create functions to accomplish your goals.
# Goal 1: You want to get a de-duplicated list of all of the people who have come to your events.
# Goal 2: Who came to *both* your Film Screening and your Happy hour?
with open('happy_hour_attendees.txt','r') as hh_file:
hh_list=hh_file.read().split("\n")
with open('film_screening_attendees.txt','r') as fs_file:
fs_list=fs_file.read().split("\n")
def de_duplicate(list1,list2):
full_list=list1+list2
unique_attendees=list(set(full_list))
return unique_attendees
#print de_duplicate(hh_list,fs_list)
#GOAL 1 BABY!!!
def find_overlap(list1,list2):
matches=[]
match=[]
for index, email in enumerate(list1):
list1[index]=email
if email in list2:
match=email
if match!=[]:
matches.append(match)
for index, email in enumerate(list2):
list2[index]=email
if email in list1:
match=email
if match!=[]:
matches.append(match)
matches =list(set(matches))
print matches
find_overlap(fs_list,hh_list)
| true |
edaee72925a72c34765b387091201a7ba6db956e | awilkinson88/SoftwareDesign | /chap12/anagram_sets.py | 1,103 | 4.21875 | 4 | def letters(s):
"""Returns the string with the letters of string
s in alphabetical order.
"""
t = list(s)
t.sort()
t = ''.join(t)
return t
def make_dict():
"""Creates a dictionary from a text file and then
returns sets of anagrams"""
d = {}
fin = open ('words.txt')
for line in fin:
word = line.strip().lower()
t = letters(word)
if t not in d:
d[t] = [word]
else:
d[t].append(word)
return d
def show_anagrams():
"""Prints all words with at least one anagram."""
d = make_dict()
final = []
for t in d:
if len(d[t]) > 1:
final.append(d[t])
return final
def sort_anagrams():
"""Sorts the anagrams by the sets with the most
words, and prints 10 lines of anagrams. Modified to only
print anagrams of 8 letters"""
t = []
anagrams = show_anagrams()
for anagram in anagrams:
t.append((len(anagram),anagram))
t.sort(reverse=True)
res = []
count = 0
for length, anagramlist in t:
res.append(anagramlist)
for i in range(len(res)-1):
if len(res[i][0]) == 8:
print res[i]
count +=1
if count == 10:
return
sort_anagrams()
| true |
037df5fe7d41b196c14ae8e7c7a20019c245ce67 | awilkinson88/SoftwareDesign | /chap16/chap16ex.py | 1,007 | 4.5 | 4 | class Time(object):
"""Represents the time of day.
attributes: hour, minute, second"""
#We can create a new Time object
#and assign attributes for hours, minutes, and seconds:
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
#from datetime import *
current = Time()
current.year = 2013
current.month = 11
current.day = 3
current.hour = 15
current.minutes = 23
current.seconds = 9
birthday = Time()
birthday.year = 1994
birthday.month = 5
birthday.day = 25
birthday.hour = 0
birthday.minutes = 0
birthday.seconds = 0
def time_to_bday(current,birthday):
age = current.year-birthday.year
print age
print 12-current.month+birthday.month
print birthday.day-current.day
print
time_to_bday(current,birthday)
# # def print_time(time_obj):
# print time.hour
# print time.minute
# print time.second
# print_time(time)
# print time
# def is_after(time1,time2):
# return (time1.hour,time1.minute,time1.second) < (time2.hour,time2.minute,time2.second)
# print is_after(time,time2) | true |
5c6cd78b9bbb66ed67e6eac3f75592996bce684c | propersam/Grokking-Algorithm-Practice | /selection_sort.py | 916 | 4.3125 | 4 |
def findSmallest(arr):
"""
Fucntion to find smallest element from array
and return it's index location
>> findSmallest([4,7,1,9,6,0])
2
"""
smallest = arr[0] # assign the element in array as smallest
smallest_index = 0 # assign first index of array as index with smallest value
for i in range(1,len(arr)):# loop through the array_list
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selectionSort(arr):
"""
Function to Sort an array
from smallest to Largest
>> selectionSort([5,7,4,2,3,1,9,0])
[0,1,2,3,4,5,7,9]
"""
newArr = []
for i in range(len(arr)):
smallest = findSmallest(arr)
newArr.append(arr.pop(smallest))
return newArr
print(selectionSort([5, 3, 6, 2, 10, 78, 0]))
| true |
ac387ee9a61aea324424563c87f1b3e1ee349586 | hritik1228/Python | /String Formatting.py | 2,457 | 4.71875 | 5 | # F-Strings & String Formatting In Python
"""
1 String Formatting (% Operator)
Python has a built-in operation that we can access with the % operator.
This will help us to do simple positional formatting. If anyone knows a
little bit about C programming, then they have worked with printf statement,
which is used to print the output. This statement uses the % operator. Similarly,
in Python, we can perform string formatting using the % operator. For Example:
"""
name="Jack"
print("My name is %s" %name)
"""
2 Using Tuple ()
The string formatting syntax, which uses % operator changes slightly if we want to
make multiple substitutions in a single string. The % operator takes only one argument,
to mention more than one argument, use tuples. Tuples are better than using the old
formatting string method. However, it is not an ideal way to deal with large strings.
For Example:
"""
name="Jack"
c=5
print("%s is in class %d" %(name,c))
"""
3 String Formatting (str.format)
Python 3 introduced a new way to do string formatting. format() string formatting method
eliminates the %-operator special syntax and makes the syntax for string formatting more regular.
str.format() allows multiple substitutions and value formatting. We can use format() to do simple
positional formatting, just like you could with old-style formatting:
In str.format(), we put one or more replacement fields and placeholders defined by a pair
of curly braces { } into a string.
Syntax: {}.format(values)
"""
str = "This article is written in {} "
print (str.format("Python"))
"""
4 Using f-Strings ( f ):
Python added a new string formatting approach called formatted string literals or "f-strings."
This is a new way of formatting strings. A much more simple and intuitive solution is the use of
Formatted string literals.f-string has an easy syntax as compared to previous string formatting
techniques of Python. They are indicated by an "f" before the first quotation mark of a string.
Put the expression inside { } to evaluate the result. Here is a simple example
"""
## declaring variables
str1="Python"
str2="Programming"
print(f"Welcome to our {str1} {str2} tutorial")
# F strings
import math
me = "Harry"
a1 =3
# a = "this is %s %s"%(me, a1)
# a = "This is {1} {0}"
# b = a.format(me, a1)
# print(b)
a = f"this is {me} {a1} {math.cos(65)}"
# time
print(a)
| true |
d3077b4b36594a4c3f2ee5973ec9bd6cb15c9ce0 | fotisk07/Visualising-Gradient-Descend | /futils.py | 2,623 | 4.1875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import math
def derivative(x):
'''This function computes the numerical value of the derivative of the cost function.
Args:
X (float) : Derivative function input value
Returns:
yhat (float) : The value of the derivative function
'''
yhat = 2 * x #Change this to use other functions
return yhat
def cost_function(x):
'''
This function computes the value of the cost function y=x^2
Args:
x (float): the input of the function
Returns:
y (float): the output of the function
'''
y= x**2 # Change this to use other functions
return y
def plot_function(weight,window,step):
'''This function plots the function along with the steps from the Gradient Descend Algoritmh
Args:
weight (numpy array): The different weights for plotting
windows (int): The window's size
step(float): The graph's step
Returns:
NaN
'''
x = np.arange(-window,window,step)
y = np.square(x) # change this to use other function
fig, ax = plt.subplots()
for i in range(len(weight)):
ax.cla()
plt.plot(weight[i],cost_function(weight[i]),'ro')
plt.plot(x,y)
ax.set_title("frame {}".format(i))
plt.pause(0.001)
def do_GD(epochs,lr,window):
'''This function used a basic Gradient Descend algoritmh to find a minimum
Args:
epochs (int): The number of steps the algorithm performs
lr (float): The learning rate for the GD
windows (int): The window's size
Returns:
weight (numpy array): An array containg the consecutive weights the algorithm came up to
'''
weight=[]
weight.append(np.random.randint(-window-100,window+100))
for i in range(0,epochs):
weight.append(weight[i] - lr *derivative(weight[i]))
return weight
def do_GD_momentum(epochs,lr,gamma,window):
'''This function used a basic Gradient Descend with momentum algoritmh to find a minimum
Args:
epochs (int): The number of steps the algorithm performs
lr (float): The learning rate for the GD
gamma (float): The gamma parameter
windows (int): The window's size
Returns:
weight (numpy array): An array containg the consecutive weights the algorithm came up to
'''
weight=[]
v=[1]
weight.append(np.random.randint(-window+50,window-50))
for i in range(0,epochs):
v.append(gamma*v[i] + lr *derivative(int(weight[i])))
weight.append(weight[i] - v[i])
return weight
| true |
ca225b4ade3ef5031882eaac82407b823a65fe5d | quanyuexie/pythonProject8 | /sorts_count.py | 1,421 | 4.3125 | 4 | # Author: Quanyue Xie
# Date: 10/21/2020
# Description: count the number of change and compare in
#bubble sort and insertion sort, and think the difference between
#different kind of list
#if the numbers in the list are almost sequential
#the change number will be smaller, but the compare number will be the same
a_list = [1,6,5,3,8,4]
def bubble_count(a_list):
"""
Sorts a_list in ascending order
"""
compare_num= 0
change_num = 0
for pass_num in range(len(a_list) - 1):
for index in range(len(a_list) - 1 - pass_num):
if a_list[index] > a_list[index + 1]:
temp = a_list[index]
a_list[index] = a_list[index + 1]
a_list[index + 1] = temp
#everytime if num changed, there should be add 1
change_num += 1
#everytime if there is a comparison, add 1
compare_num += 1
#return a tuple of the two values
return (compare_num,change_num)
def insertion_count(a_list):
change_number = 0
compare_number = 0
for index in range(1, len(a_list)):
value = a_list[index]
pos = index - 1
while pos >= 0 and a_list[pos] > value:
a_list[pos + 1] = a_list[pos]
pos -= 1
# everytime if num changed, there should be add 1
change_number += 1
# everytime if there is a comparison, add 1
compare_number += 1
a_list[pos + 1] = value
# return a tuple of the two values
return (compare_number, change_number)
| true |
9adec7548d08c0d0697e357cb905ff24ccaf011c | DanieledG/ETH_Subjects | /MaturaArbeit/Decrypter.py | 1,262 | 4.3125 | 4 | #our password
password = input("Choose a password, use only letters: ")
#the text we want to decrypt
cipherText = input("Enter the text you want to decrypt: ")
#the alphabet we are going to use
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
#an empty list
plainText = []
#function that sorts the alphabet using a given character as the first element
def sortAlphabet (char):
#tells you at wich position of the alphabet is our charachter
i = alphabet.index (char)
#moves the characters from the end of the alphabet to the beginning
for x in range (0, i):
alphabet.append (alphabet[0])
alphabet.remove (alphabet[0])
def decrypt (password, cipherText):
i = 0
cipherText = cipherText.lower()
#transforms all letters in the password to lowercase
password = password.lower()
for l in cipherText:
if l in alphabet:
c = i%len(password)
d = password[c]
sortAlphabet (d)
b = alphabet.index(l)
sortAlphabet ("a")
plainText.insert(i, alphabet[b])
i += 1
return plainText
decrypt (password, cipherText)
plainText = ''.join(plainText)
print ("plaintext: ", plainText)
| true |
7eb6fbd0616136a7446b7e0fb3e91c0cee84f3e4 | mnishiguchi/python_notebook | /MIT6001x/week3/iterativePower_1.py | 715 | 4.40625 | 4 | # -*- coding: utf-8 -*-
# calculates the exponential baseexp by simply using successive multiplication.
# should compute base**exp by multiplying base times itself exp times
# Your code must be iterative - use of the ** operator is not allowed.
# take in two values - base can be a float or an integer;
# exp will be an integer ≥ 0. return one numerical value.
def iterPower(base, exp) :
if exp == 0:
return 1
result = base
while exp > 1 :
result = result * base
exp = exp - 1
return result
def test():
for i in range(10):
print '2**', i, ':', iterPower(4,i), ' ', 4**i
test()
| true |
7768db3184fcb6e2253aa8da21bd8f919109c957 | mnishiguchi/python_notebook | /MIT6001x/week2/pset1_longestSubstring.py | 742 | 4.25 | 4 | '''
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order.
For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
'''
s = raw_input('Type a string of lower case characters: ')
longest = ''
for i in range(len(s)) :
probe = s[i:]
prev = ''
candidate = ''
for char in probe :
if char >= prev :
candidate = candidate + char
prev = char
else :
break
if len(candidate) > len(longest) :
longest = candidate
print longest
| true |
bd7a0fb7e0aea394b6d72abecb976ff53e8ec15e | mnishiguchi/python_notebook | /MIT6001x/week5/swapSort.py | 1,444 | 4.15625 | 4 | import random
def swapSort(L):
""" L is a list on integers """
print "Original L: ", L
ctr = 0
# iterate L[0] through L[-1]
for i in range( len(L) ):
# prove the sub-list for the smaller int
for j in range( i+1, len(L) ):
# everytime smaller int is found,
# put it in the leftmost position of unsorted sub-list
if L[j] < L[i]:
# a short form for swap L[i] and L[j]
L[j], L[i] = L[i], L[j]
ctr += 1
print 'ctr',ctr,L
print "Final L: ", L
#### this sorting algorithm is NOT efficient ####
def modSwapSort(L):
""" L is a list on integers """
ctr = 0
print "Original L: ", L
for i in range( len(L) ):
for j in range( len(L) ):
# ensure L[i] is the greatest int,
# everytime greater int is found, swap it
if L[j] < L[i]:
# swap
L[j], L[i] = L[i], L[j]
ctr += 1
print 'ctr',ctr,L
print "Final L: ", L
## test
##----------------------------------------------
# generate a list of ramdom numbers
L = [5,4,3,2,1]
#for i in range(5):
# L.append( random.randint(0, 100) )
L1=L[:]
L2=L[:]
# execute functions
print
swapSort(L1)
print
modSwapSort(L2)
| true |
7897e59325cda32b890fd19f430c0753fb4f4305 | mnishiguchi/python_notebook | /MIT6001x/week2/pset2-2_ok.py | 1,814 | 4.21875 | 4 | # -*- coding: utf-8 -*-
'''
Pset2
PROBLEM 2: PAYING DEBT OFF IN A YEAR (15 points possible)
calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months.
By a fixed monthly payment, we mean a single number which does not change each month,
but instead is a constant amount that will be paid each month.
monthly payment: must be a multiple of $10 and is the same for all months.
'''
# balance - the outstanding balance on the credit card
# annualInterestRate - annual interest rate as a decimal
### Test Case 1:
balance = 819
annualInterestRate = 0.18
# initial guess (multiple of 10)
lowestMonthlyPayment = balance / 12
lowestMonthlyPayment = lowestMonthlyPayment - (lowestMonthlyPayment % 10)
def balanceOneYearLater(balance, monthlyPayment) :
'''
calculate balance of one year later based on passed monthly payment(fixed)
return balance
'''
for i in range(1, 12+1) :
# Update the outstanding balance by removing the payment, then charging interest on the result.
balance = (balance - monthlyPayment) + (balance - monthlyPayment) * annualInterestRate / 12.0
balance = round(balance, 2)
return balance
# test
while True :
# balance 1 year later
remainingBalance = balanceOneYearLater(balance, lowestMonthlyPayment)
# if finish paying
if remainingBalance <= 0 :
break
else :
lowestMonthlyPayment += 10
# the lowest monthly payment that will pay off all debt in under 1 year
print 'Lowest Payment:', lowestMonthlyPayment
| true |
24307b45111157f390a27b6a9d13b3dbd2792645 | mnishiguchi/python_notebook | /MIT6001x/week6/PSet6/applyCoder_test.py | 1,436 | 4.25 | 4 | import string
#
# Problem 1: Encryption
#
def buildCoder(shift):
"""
Returns a dict that can apply a Caesar cipher to a letter.
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation, numbers and spaces.
shift: 0 <= int < 26
returns: dict
"""
# get all the alphabetical characters
lower = string.ascii_lowercase
upper = string.ascii_uppercase
# create a dict
coder = dict()
for i in range(26):
# The cipher is defined by the shift value.
coder[ lower[i] ] = lower[ (i + shift) % 26 ]
coder[ upper[i] ] = upper[ (i + shift) % 26 ]
# Returns a dict that can apply a Caesar cipher to a letter.
return coder
def applyCoder(text, coder):
"""
Applies the coder to the text. Returns the encoded text.
text: string
coder: dict with mappings of characters to shifted characters
returns: text after mapping coder chars to original text
"""
encodedLetters = []
for letter in text:
if letter.isalpha():
encodedLetters.append( coder[letter] )
else:
encodedLetters.append( letter )
# Returns the encoded text.
return ''.join( encodedLetters )
print applyCoder("Hello, world!", buildCoder(3))
#'Khoor, zruog!'
print applyCoder("Khoor, zruog!", buildCoder(23))
#'Hello, world!' | true |
adcdfd298b99f77ea5dbfc5d13d9c9126fd5c3ed | mnishiguchi/python_notebook | /MIT6001x/week2/bineryConverter.py | 529 | 4.15625 | 4 | # binaryConverter.py
n = int(raw_input('Enter an integer: '))
# remember positive or negative
if n < 0:
isNeg = True
n = abs(n)
else:
isNeg = False
# storage of result, initialize as empty str
result = ''
# if 0, binary is 0 also
if n == 0:
result = '0'
# calculate binary from 2**0 to left
while n > 0:
result = str(n % 2) + result # each bit's value : modulo 2
n = n / 2 # shift left
if isNeg:
result = '-' + result
print result
| true |
8d736b54c1af8058461e4a4abb4aed821b9971b6 | Hisquare/Database-user-input | /userDbInput.py | 2,711 | 4.40625 | 4 | # TO ALLOW A USER ENTER DATA INTO A DATABASE WHILE THE CODE IS RUNNING.
print('DATABASE TO RECIEVE WEEKLY TEMPERATURE DATA AND COMPUTE THEIR AVERAGE! ')
a1 = input("enter date: ")
a = int(input("enter temperature on day 1: "))
b1 = input("enter date: ")
b = int(input("enter temperature on day 2: "))
c1 = input("enter date: ")
c = int(input("enter temperature on day 3: "))
d1 = input("enter date: ")
d = int(input("enter temperature on day 4: "))
e1 = input("enter date: ")
e = int(input("enter temperature on day 5: "))
f1 = input("enter date: ")
f = int(input("enter temperature on day 6: "))
g1 = input("enter date: ")
g = int(input("enter temperature on day 7: "))
# DATABASE PROGRAMMING
import sqlite3 as db
# CREATE DATABASE
kat = db.connect('TempTracker1.db') #creates database
cursor = kat.cursor() # to create a cursor
cursor.execute("drop table if exists tempdata") # checks if the table already exists and deletes it if true
# CREATE TABLE
cursor.execute("create table tempdata (serialNumber text, date text, temp int)") # creates the table
# UPDATE
cursor.execute("insert into tempdata values ('1.', '{}', '{}')".format(a1,a)) # inserts data into the table
cursor.execute("insert into tempdata values ('2.', '{}', '{}')".format(b1,b))
cursor.execute("insert into tempdata values ('3.', '{}', '{}')".format(c1,c))
cursor.execute("insert into tempdata values ('4.', '{}', '{}')".format(d1,d))
cursor.execute("insert into tempdata values ('5.', '{}', '{}')".format(e1,e))
cursor.execute("insert into tempdata values ('6.', '{}', '{}')".format(f1,f))
cursor.execute("insert into tempdata values ('7.', '{}', '{}')".format(g1,g))
# RETRIEVE
kat.row_factory = db.Row # to be able to select any column from table or all
cursor.execute('select * from tempdata') # to select from the table
rows = cursor.fetchall() # to display every result
for row in rows:
print("%s %s %s" % (row[0], row[1], row[2])) # to print
cursor.execute("select avg(temp) from tempdata") # TO COMPUTE AVARAGE
row = cursor.fetchone() # to display all data
print("the average temperature for the week was %s" % row[0]) # to print
# DELETE
h = int(input("the temperature to delete from the table: "))
cursor.execute("delete from tempdata where temp = {}".format(h)) # to delete from table
cursor.execute('select * from tempdata')
rows = cursor.fetchall()
for row in rows:
print("%s %s %s" % (row[0], row[1], row[2]))
cursor.execute("select avg(temp) from tempdata") # TO COMPUTE AVARAGE
row = cursor.fetchone() # to displace just one result
print("the average temperature for the week was %s" % row[0]) # to print
kat.commit() # to return to the database the updated data. | true |
ffd3816df64c6f672693ebcb3199dc88f769415c | ChairOfStructuralMechanicsTUM/Mechanics_Apps | /Base_excited_oscillator/beo_coord.py | 2,199 | 4.1875 | 4 | from math import sqrt
class Coord(object):
# initialise class
def __init__(self,x,y):
self.x=x
self.y=y
# define Coord+Coord
def __add__(self,A):
return Coord(self.x+A.x,self.y+A.y)
# define Coord+=Coord
def __iadd__(self,A):
self.x+=A.x
self.y+=A.y
return self
# define Coord-Coord
def __sub__(self,A):
return Coord(self.x-A.x,self.y-A.y)
# define Coord-=Coord
def __isub__(self,A):
self.x-=A.x
self.y-=A.y
return self
# define Coord*num
def __mul__(self,a):
return Coord(self.x*a,self.y*a)
# define num*Coord
def __rmul__(self,a):
return Coord(self.x*a,self.y*a)
# define Coord*=num
def __imul__(self,a):
self.x*=a
self.y*=a
return self
# define Coord/num
def __div__(self,a):
return Coord(self.x/a,self.y/a)
# define Coord/=num
def __idiv__(self,a):
self.x/=a
self.y/=a
return self
# define -Coord
def __neg__(self):
return Coord(-self.x,-self.y)
# define Coord==Coord
def __eq__ (self,A):
# leave room for rounding errors
return (abs(self.x-A.x)<1e-10 and abs(self.y-A.y)<1e-10)
# define Coord!=Coord
def __neq__(self,A):
return (not (self==A))
# define what is printed by print
def __str__(self):
return "("+str(self.x)+", "+str(self.y)+")"
# define what is printed by print in a list
def __repr__(self):
return "("+str(self.x)+", "+str(self.y)+")"
# function returning the norm
def norm(self):
return sqrt(self.x**2+self.y**2)
# function returning the direction
def direction(self):
abx=self.x/self.norm()
aby=self.y/self.norm()
return Coord(abx,aby)
# function returning the perpendicular direction
def perp(self):
abx=self.x/self.norm()
aby=self.y/self.norm()
return Coord(aby,-abx)
def copy(self):
return Coord(self.x,self.y)
def prod_scal(self,A):
return self.x*A.x+self.y*A.y
| false |
135a0840a43ca56a6a077792285d2fe39ec0ce83 | shirwani/WebDevelopment | /Python/Section_1_Basic/Ex2_strings.py | 701 | 4.5 | 4 | #!/usr/bin/python
print "Hello World"
print "Hello " + "World"
world = "World"
print "Hello " + world
print "Hello %s" % world
name = "Bob"
print "Hello " + world + ". My name is " + name + ". Hello " + name + "!"
print "Hello %s. My name is %s. Hello %s!" % (world, name, name)
str = 'Hello World!'
print "############################"
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
print "############################"
| true |
be7c7ac9ee9fd436bb143ed7ad5ae738ac5c054b | zosman1/learnpython | /p10.py | 327 | 4.1875 | 4 | #Welcome to Problem 10
#lines with a # in front of it are comments, they will be ignored by python
#What does the following code output / what does it print?
# With this problem we begin with the concept of loops
# Lets start with the while loop
counter = 0
while counter < 10:
print(counter)
counter = counter + 1
| true |
c86f43ce872258bea4b4a86b9815b15bf752927d | The-Anonymous-pro/projects | /week 1 assignment/Assingment.py | 1,027 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## ASSIGNMENT
#
# **Tomiwa Emmanuel O. Am a python programmer and this script will be solving quadratic equations**. A quadratic equation form is: **(ax² + bx + c = 0)** which is solved using a quadratic formular: **(-b +- √(b²-4ac))/2a** where a, b, c are numbers and **a** is not equals to 0.
#
# In[2]:
#First we import cmath module
import math
#Then we allow three(3) float inputs (a,b,c) for the quadratic equation
a= float(input("Enter a: "))
b= float(input("Enter b: "))
c= float(input("enter c: "))
#using the quadratic formular -b +- √(b² - 4ac)/2a we calculate x is (b²-4ac)
x= b**2 - 4*a*c
#since we have x ,we can now find the two solutions to the equation
first_sol = (-b - math.sqrt(x)) / (2*a)
second_sol = (-b + math.sqrt(x)) / (2*a)
#note that we already calculated for x, therefore the first and second solution need only to apply the quardratic formular.
print ( first_sol, second_sol )
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
| true |
654c01c44d8a543dc60431ba09e723a3f5ae72e8 | angamndiyata/Data-Science- | /compTask1.py | 1,950 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
# In[13]:
#Why doesn’t
#np.array((1, 0, 0), (0, 1, 0), (0, 0, 1,dtype=float)
#create a two dimensional array? Write it the correct way.
#Answer : The list for each row array is missing, matrix [] brackets mising for matrix array and the datatype uses wrong syntax.
#correct way to represent the array.
np.array([[(1, 0, 0)], [(0, 1, 0)], [(0, 0, 1)]], dtype=float)
# In[10]:
#What is the difference between
a = np.array([0, 0, 0])
print(a)
#and
a =np.array([[0, 0, 0]])
print(a)
#?
#Answer : 1. array of single item where a[0] = 0 and 2. array of a row array where a[0] = [0,0,0]
# In[110]:
# A 3 by 4 by 4 is created with
arr = np.linspace(1, 48,48).reshape(3, 4, 4)
print("Array")
print(arr)
#Index or slice this array to obtain the following
print("1st")
print(arr[1][0,3])
print("2nd")
print(arr[0][2])
print("3rd")
print(arr[2])
print("4rd")
print(np.array([arr[0][1,[0,1]],arr[1][1,[0,1]],arr[2][1,[0,1]]]))
print("5th")
print(np.array([arr[2][0,[2,3]][::-1],arr[2][1,[2,3]][::-1],arr[2][2,[2,3]][::-1],arr[2][3,[2,3]][::-1]]))
print("6th")
print(np.array([arr[0][:,0][::-1], arr[1][:,0][::-1] , arr[2][:,0][::-1]]))
print("7th")
print(np.array([[arr[0][0,0],arr[0][0,3]],[arr[2][3,0],arr[2][3,3]]]))
print("8th")
print(np.array([arr[1][2,:],arr[1][3,:],arr[2][0,:],arr[2][1,:]]))
# In[ ]:
■ 20.0
■ [ 9. 10. 11. 12.]
■ [[33. 34. 35. 36.] [37. 38. 39. 40.] [41. 42. 43. 44.] [45. 46. 47. 48.]]
■ [[5. 6.], [21. 22.] [37. 38.]]
■ [[36. 35.] [40. 39.] [44. 43.] [48. 47.]]
■ [[13. 9. 5. 1.] [29. 25. 21. 17.] [45. 41. 37. 33.]]
■ [[1. 4.] [45. 48.]]
■ [[25. 26. 27. 28.], [29. 30. 31. 32.], [33. 34. 35. 36.], [37. 38. 39. 40.]]
Hint: use flatten (help here) and reshape.
# In[97]:
print("5th")
print([arr[2][0,[2,3]][::-1],[arr[2][1,[2,3]][::-1],[arr[2][2,[2,3]][::-1],[arr[2][3,[2,3]][::-1]]
# In[ ]:
| true |
79a4539019cb728195ad92b030fc3dbe6335cacf | xavrb/numericalmethods | /Newton R/nr.py | 1,309 | 4.21875 | 4 | # Newton-Raphson method, a simple implementation
import math
from random import randint
#f(x) - the function of the polynomial
def f(x):
function = (x*x) - (2*x) - 1
return function
def derivative(x): #function to find the derivative of the polynomial
h = 0.000001
derivative = (f(x + h) - f(x)) / h
return derivative
def newton_raphson(x):
return (x - (f(x) / derivative(x)))
# p - the initial point i.e. a value closer to the root
# n - number of iterations
def iterate(p, n): #
x = 0
for i in range(n):
if i == 0: #calculate first approximation
x = newton_raphson(p)
else:
x = newton_raphson(iterate(x, n)) #iterate the first and subsequent approximations
n=n-1
return x
g = 2
resultados = []
for res in range(0,g):
print randint(-1, 1)
if res ==0:
resultados.append(iterate(1, 5)) #print the root of the polynomial x^3 - 2x - 1 using 3 iterations and taking initial point as 1
else:
if randint(1, 100)%2 == 0:
sign = -1
else:
sign = 1
resultados.append(iterate(resultados[(res-1)]+(sign*randint(-10, 10)), 5)) #print the root of the polynomial x^3 - 2x - 1 using 3 iterations and taking initial point as 1
print resultados
| true |
9a68453b55f78475271344d7638e171c91e69e78 | ORodrigoFerreira/ExerciciosCursoemvideo | /ex033.py | 420 | 4.125 | 4 | a = int(input('Um número'))
b = int(input('Outro número'))
c = int(input('Mais um número'))
if a > b and a > c:
print(a, 'é o maior número')
if a < b and a < c:
print(a, 'é menor número')
if b > a and b > c:
print(b, 'é o maior número')
if b < a and b < c:
print(b, 'é menor número')
if c > b and c > a:
print(c, 'é o maior número')
if c < b and c < a:
print(c, 'é menor número')
| false |
c98216a3cb68e5168db5420596da044ad8080a81 | Jwatt229/program-arcade-games | /Lab 01 - Calculator/lab_01_part_c.py | 321 | 4.53125 | 5 | #
#!/usr/bin/env python3
+#Circle Area
+#Jordan Watt
+#11-2-17
+
+"""Using the radius to find the Area of a circle"""
+
+#import math
+
+from math import pi
+
+#user input for radius
+
+radius = int(input('Enter the radius: '))
+
+#Equation
+
+area = pi*radius**2
+
+#print
+
+print('The area is:', area)
| false |
51a86765d26f71463fce2ee6e805d3ff2d491008 | Narvienn/MyPythonSandbox | /PracticePythonEx8_new.py | 2,132 | 4.125 | 4 | """Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out
a message of congratulations to the winner, and ask if the players want to start a new game)
Remember the rules:
- Rock beats scissors
- Scissors beats paper
- Paper beats rock"""
import sys
print("Welcome to a game of Rock, Paper, Scissors. If at any point you'd like to quit, simply type 'quit'.")
options = ["rock", "paper", "scissors"]
user1 = input("What's your name, Player 1?\n")
user2 = input("What's your name, Player 2?\n")
def rps(input_user1, input_user2):
if (input_user1 == "rock" and input_user2 == "scissors") or (input_user1 == "scissors" and input_user2 == "paper") or (input_user1 == "paper" and input_user2 == "rock"):
return input_user1
elif (input_user2 == "rock" and input_user1 == "scissors") or (input_user2 == "scissors" and input_user1 == "paper") or (input_user2 == "paper" and input_user1 == "rock"):
return input_user2
def exit_check(user_input):
if user_input == "quit":
print("Thanks for playing!")
sys.exit()
game_on = "yes"
while game_on != "no":
user1_choice = input("What's your choice, " + user1 + "? \n").lower()
# .lower() method turns all characters into lowercase regardless of user's spelling
exit_check(user1_choice)
user2_choice = input("What's your choice, " + user2 + "? \n").lower()
exit_check(user1_choice)
if user1_choice == user2_choice:
print("It's a tie.")
else:
result = rps(user1_choice, user2_choice)
if user1_choice == result:
print("You won, " + user1 + "!")
else:
print("You won, " + user2 + "!")
game_on = input("Do you want to play another game? yes/no \n")
# fix this:
"""What's your choice, z?
quit
You won, z!"""
# for future reference, when attempting a different flavour of the game
"""import random
print("Welcome to a game of 'Rock, Paper, Scissors' against a bot")
user1 = input("Name your choice (rock, paper, scissors)")
choiceList = ["rock", "paper", "scissors"]
bot = random.choice(choiceList)"""
| true |
829984ff431b046fa6a5a152d53cb68f0bf1a734 | santosh449/Rock-Paper-Scissors-cod | /ROCK-PAPER+SCISSORS.py | 2,910 | 4.28125 | 4 | import random # Random Package from the library
# Combinations of Inputs
user_input = input("Enter either 'Rock', 'Paper', 'Scissor', 'Lizard', or 'Spock': ")
print("You entered : ", user_input)
possible_options = ['Rock', 'Paper', 'scissor', 'Lizard', 'Spock']
# Enter the code for Computer Input
computer_input = random.choice(possible_options)
print("System entered :", computer_input)
# Try all the possible combinations between user & computer
if (user_input == computer_input):
print("This Match is a Tye")
elif user_input == 'Rock':
if computer_input == 'Scissor':
print("You are the Winner!")
else:
print("Computer is the Winner!")
elif user_input == 'Paper':
if computer_input == 'Scissor':
print("Computer is the Winner!")
else:
print("You are the Winner!")
elif user_input == 'Scissor':
if computer_input == 'Rock':
print("Computer is the Winner!")
else:
print("You are the Winner!")
elif user_input == 'Scissor':
if computer_input == 'Paper':
print("You are the Winner!")
else:
print("Computer is the Winner!")
elif user_input == 'Rock':
if computer_input == 'Paper':
print("Computer is the Winner!")
else:
print("You are the Winner!")
elif user_input == 'Paper':
if computer_input == 'Rock':
print("You are the Winner!")
else:
print("Computer is the Winner!")
elif user_input == 'Lizard':
if computer_input == 'Rock':
print("Computer is the Winner!")
else:
print("You are the Winner!")
elif user_input == 'Spock':
if computer_input == 'Rock':
print("You are the Winner!")
else:
print("Computer is the Winner!")
elif user_input == 'Lizard':
if computer_input == 'Spock':
print("You are the Winner!")
else:
print("Computer is the Winner!")
elif user_input == 'Spock':
if computer_input == 'Lizard':
print("Computer is the Winner!")
else:
print("You are the Winner!")
elif user_input == 'Spock':
if computer_input == 'Paper':
print("Computer is the Winner!")
else:
print("You are the Winner!")
elif user_input == 'Spock':
if computer_input == 'Scissors':
print("You are the Winner!")
else:
print("Computer is the Winner!")
elif user_input == 'Scissors':
if computer_input == 'Spock':
print("Computer is the Winner!")
else:
print("You are the Winner!")
elif user_input == 'Lizard':
if computer_input == 'Scissors':
print("Computer is the Winner!")
else:
print("You are the Winner!")
elif user_input == 'Scissors':
if computer_input == 'Lizard':
print("You are the Winner!")
else:
print("Computer is the Winner!")
| true |
ff5afe4fe43d05cae0344e159391b2e84a90ef7b | conradylx/Python_Course | /Hackaton - 01/Phone book/phone_book.py | 1,552 | 4.28125 | 4 | # Program przechowujący danę kontaktowe znajomych/klientów.
#
# Program wyświetla menu wypisujące komendy jakie należy wpisać, aby program wykonał dane zadanie. Zadania to:
# Wyświetlenie wszystkich wpisów
# Stworzenie nowego wpisu (dane wczytywane z klawiatury)
# Usunięcie wpisu
# Zakończenie pracy programu
# Program powinien na starcie mieć już wprowadzone kilka wpisów.
def show_all_records(list):
for key, value in list.items():
print("Name:", key, "Phone no:", value)
def add_new_record(list):
new_new = input("Please enter name of new record ")
new_phone_no = int(input("Please enter new phone number of new record "))
list[new_new] = new_phone_no
print("Your new contact has been added")
return list
def remove_record_from_contact(list):
user_input = input("Please enter name of your contact to remove from dictionary ")
if user_input in list:
del list[user_input]
else:
print(f'{user_input} is not in your contacts')
return list
data_list = {"Jan": 433122345, "Kamil": 333222111, "Anna": 999333884}
print("Type /show to show all the records, /add to add new record, /remove to remove contact")
user_input = ""
while user_input != "/end":
user_input = input("Your input: ")
if user_input == "/show":
show_all_records(data_list)
elif user_input == "/add":
data_list = add_new_record(data_list)
elif user_input == "/remove":
data_list = remove_record_from_contact(data_list) | false |
c94c16d92e34a5df69180200f5c35a9a8f4e2d8b | conradylx/Python_Course | /07.04.2021/exc2.py | 541 | 4.21875 | 4 | # Utwórz dowolną krotkę zawierającą kilka wartości np. 10.
# Pozwól użytkownikowi podać dowolny index oraz wartość.
# Spróbuj w krotce podmienić wartość na zadanym indeksie. Obsłuż błąd.
example_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
user_index = int(input("Enter index in tuple: "))
tuple_value = input("Enter value to replace: ")
try:
example_tuple[user_index] = tuple_value
except TypeError:
print('Cannot replace value in tuple.')
except ValueError:
print('Given index is string. Should be an integer.') | false |
ff3496fef2a28cc981192ac559deb663c39ecfa3 | mccornet/leetcode_challenges | /Python/0088.py | 1,909 | 4.125 | 4 | """
# 88. Merge Sorted Array
- https://leetcode.com/problems/merge-sorted-array/
- Classification: Array, Two Pointers
## Challenge
You are given two integer arrays nums1 and nums2,
sorted in non-decreasing order, and two integers m and n,
representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function,
but instead be stored inside the array nums1.
To accommodate this, nums1 has a length of m + n,
where the first m elements denote the elements that should be merged,
and the last n elements are set to 0 and should be ignored. nums2 has a length of n
## Solution
Start at the end with k = m+n-1 and add only the largest values
If the first while loop runs out then only elements remaining in
The second array need to be transferred still
"""
class Solution:
def merge(self, nums1: list[int], m: int, nums2: list[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
k = m+n-1
while m and n:
if nums1[m-1] > nums2[n-1]:
nums1[k] = nums1[m-1]
m -= 1
else:
nums1[k] = nums2[n-1]
n -= 1
k -= 1
while n:
nums1[k] = nums2[n-1]
n -= 1
k -= 1
if __name__ == "__main__":
s = Solution()
# Example 1
nums1 = [1,2,3,0,0,0]
m = 3
nums2 = [2,5,6]
n = 3
s.merge(nums1, m, nums2, n)
print(nums1)
# Example 2
nums1 = [1]
m = 1
nums2 = []
n = 0
s.merge(nums1, m, nums2, n)
print(nums1)
# Example 3
nums1 = [0]
m = 0
nums2 = [1]
n = 1
s.merge(nums1, m, nums2, n)
print(nums1)
| true |
5c8ca94b9e88708641dd92ed4a905e88f00204ea | mertys/PyhtonApp | /Depo/Files/friends.py | 670 | 4.25 | 4 | import sqlite3
connection = sqlite3.connect('friend.db')
cursor = connection.cursor()
# cursor.execute("CREATE TABLE friends(first_name TEXT , last_name TEXT , age INTEGER)")
# cursor.execute("INSERT INTO friends VALUES ('Mert' , 'Yurtseven' , '29')")
# cursor.execute("SELECT * FROM friends WHERE first_name = 'Mahmut' ")
first_name = input('Adınız: ')
last_name = input('Soyadınız: ')
age = input('Yaşınız: ')
# cursor.execute(f"INSERT INTO friends VALUES('{first_name}', '{last_name}' , {age})")
cursor.execute(f"INSERT INTO friends VALUES(? , ? , ?)" , (first_name , last_name , age))
# print(cursor.fetchall())
connection.commit()
connection.close()
| false |
c1923c752618cea37d83ae0795396c7b0d4d26d3 | mikaav/Learn-Python | /Case1.py | 518 | 4.375 | 4 | # Дано целое число в диапазоне 1–7. Вывести строку — название дня недели,
# соответствующее данному числу (1 — «понедельник», 2 — «вторник» и т. д.)
d = int(input())
if d == 1:
print("Monday")
elif d == 2:
print("Tuesday")
elif d == 3:
print("Wednesday")
elif d == 4:
print("Thursday")
elif d == 5:
print("Friday")
elif d == 6:
print("Saturday")
elif d == 7:
print("Sunday")
| false |
007b1267119578812e8589c587c9a891c38edaa2 | constancedongg/Analysis_of_Algorithm | /graph/bfs_shortest_path.py | 1,220 | 4.21875 | 4 |
'''
Application:
- Find people at a given distance from a person in social networks.
- Identify all neighbour locations in GPS systems.
- Search whether there is a path between two nodes of a graph and shortest path.
Time complexity: exponential
Space complexity: even worse, needs high memory
'''
def bfs_shortest_path(graph , start , goal):
explored = []
queue = [[start]]
if start == goal:
return 'You find it instantly!'
while queue:
path = queue.pop(0)
node = path[-1]
if node not in explored:
neighbors = graph[node]
for neighbor in neighbors:
new_path = list(path)
new_path.append(neighbor)
queue.append(new_path)
print(queue)
if neighbor == goal:
return new_path
explored.append(node)
return 'There is no path between {} and {}'.format(start, goal)
graph = {'A': ['B', 'C', 'E'],
'B': ['A','D', 'E'],
'C': ['A', 'F', 'G'],
'D': ['B', 'E'],
'E': ['A', 'B','D'],
'F': ['C'],
'G': ['C'],
'H': []}
print(bfs_shortest_path(graph , 'A' , 'G'))
| true |
90269575ecef57a9e5d6c82365231487340977d5 | LiYChristopher/chris_rmotr | /week2_solo/dict_comphrension.py | 898 | 4.15625 | 4 | """
Write a function that receives a list and
returns a dictionary with the elements initialized with the value 0.
You MUST use dict comprehensions.
Example:
init_dict(['a', 'b', 'c']) # {'a': 0, 'b': 0, 'c': 0}
"""
def init_dict(a_list):
return { i : 0 for i in a_list }
if __name__ == '__main__':
import unittest
class InitDictTestCase(unittest.TestCase):
def test_two_keys(self):
self.assertEqual(
init_dict(['a', 'b']),
{'a': 0, 'b': 0}
)
def test_three_keys(self):
self.assertEqual(
init_dict(['a', 'b', 'c']),
{'a': 0, 'b': 0, 'c': 0}
)
def test_integer_keys(self):
self.assertEqual(
init_dict([1, 2, 3]),
{1: 0, 2: 0, 3: 0}
)
def test_empty_list(self):
self.assertEqual(init_dict([]), {})
unittest.main() | true |
47076c7b44e9302ac98eb36e60100e185650d623 | lbedoyas/Python | /listas.py | 618 | 4.25 | 4 | #listas
#Las listas son los mismo que un arrays pero en python son list
UnaLista = ["apple", "banana", "cherry"]
print(UnaLista)
#Cambiar valores
UnaLista[1] = "Manzana"
print UnaLista
print(len(UnaLista))
#Metodo para anexar un item
UnaLista.append("Mandarina")
print UnaLista
#Comprobar si un objeto se encuentra en una lista
print "Comprobar si un objeto(apple) se encuentra en una lista"
print("apple" in UnaLista)
#Metodo para anexar un item
UnaLista.append("Mandarina")
print UnaLista
#Elimina un campo especifico
del UnaLista[1]
print UnaLista
#Imprimir en un for
for x in UnaLista:
print x
| false |
34a4686e520dfa72d21901a042965fcc9d18b9ab | amirarfan/INF200-2019-Exercises | /src/amir_arfan_ex/ex01/tidy_code.py | 1,622 | 4.28125 | 4 | from random import randint
__author__ = "Amir Arfan"
__email__ = "amar@nmbu.no"
def randomnumgen():
"""
A function which generates a random number with the sum of two numbers between 1 and 6
"""
return randint(1, 6) + randint(
1, 6
) # Used randint for clarity, as randint refers to random integer.
def guessanumber(): # Guess a number function
""" Guess a number function. As long as the guessed number is below 1, the function will continue to sk for a number
"""
num_guess = 0
while num_guess < 1:
num_guess = int(input("Guess a number greater than one. Your guess: "))
return num_guess
def checkguessrandom(rand_num, guess_num):
"""
Checks if the random number is equal to the guessed number. Returns a True or False value (BOOL)
"""
return rand_num == guess_num
if __name__ == "__main__":
bool_test = (
False
) # Variable is set as false from the beginning, to be changed to True if user is able to guess
# the random number
points = 3 # The user begins with 3 points
num_to_guess = randomnumgen()
while (
not bool_test and points > 0
): # While loop which runs until user is able to guess the random number or has
# lost all points
your_guess = guessanumber()
check = checkguessrandom(num_to_guess, your_guess)
if check:
bool_test = True
else:
print("Wrong, try again!")
points -= 1
if points > 0:
print(f"You won {points} points.")
else:
print(f"You lost. Correct answer: {num_to_guess}.")
| true |
f46a293c33623f82720d92d209eae7a238ebf3d7 | IsaacColney/Leap-Year-Calculator | /leap_year.py | 605 | 4.15625 | 4 | #Leap_Year
cont = "y"
while cont.lower() == 'y':
year = int(input("Enter the year :"))
def is_leap(year):
pass
a = "The entered year is Leap Year"
b = "The entered year is not leap year"
if year % 4 == 0:
if year % 100 == 0:
if year % 100 == 0 and year % 400 == 0:
return a
return b
return a
else:
return b
print(is_leap(year))
cont = input("Do you want to check another Year? y/n:")
if cont == "n":
break
| false |
8b30aa13655f35efc8e9a7275f335f086263f080 | Gmiller290488/Programming-challenges | /Plus Minus or zero.py | 556 | 4.15625 | 4 | # Given an array of integers, calculate which fraction of its elements are positive,
# which fraction of its elements are negative, and which fraction of its elements are zeroes,
# respectively.
# Print the decimal value of each fraction on a new line.
positive = negative = zero = 0
n = int(input().strip())
arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]
for num in arr:
if num > 0:
positive += 1
elif num < 0:
negative += 1
elif num == 0:
zero += 1
print(positive/n)
print(negative/n)
print(zero/n) | true |
92a277a2281f82bf696d4b58ec5855409affb505 | Divine11/InterviewBit | /Tree data structure/Valid_BST.py | 1,269 | 4.3125 | 4 | # Given a binary tree, determine if it is a valid binary search tree (BST).
# Assume a BST is defined as follows:
# The left subtree of a node contains only nodes with keys less than the node’s key.
# The right subtree of a node contains only nodes with keys greater than the node’s key.
# Both the left and right subtrees must also be binary search trees.
# Example :
# Input :
# 1
# / \
# 2 3
# Output : 0 or False
# Input :
# 2
# / \
# 1 3
# Output : 1 or True
# Return 0 / 1 ( 0 for false, 1 for true ) for this problem
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isValidBstUtil(A,maxi,mini):
if A==None:
return 1
if A.val<mini:
return 0
elif A.val>maxi:
return 0
return isValidBstUtil(A.left,A.val,mini) and isValidBstUtil(A.right,maxi,A.val)
def isValidBST(self, A):
import sys
return isValidBstUtil(A,sys.maxsize,-sys.maxsize)
def createTree():
root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(5)
root.left.left = TreeNode(1)
root.left.right = TreeNode(5)
root.left.left.right = TreeNode(97)
return root
root = createTree()
print(isValidBST("",root))
| true |
ceacd4c8afdcc1de7a3062fadce42346fe2b962a | Divine11/InterviewBit | /Tree data structure/Flatten_Binary_Tree_To_Linked_List.py | 1,926 | 4.125 | 4 | # Given a binary tree, flatten it to a linked list in-place.
# Example :
# Given
# 1
# / \
# 2 5
# / \ \
# 3 4 6
# The flattened tree should look like:
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# \
# 6
# Note that the left child of all nodes should be NULL.
def flatten(A):
if A is None:
return None
left = flatten(A.left)
right = flatten(A.right)
if not left and not right:
return A
elif not left and right:
return A
elif left and not right:
A.right = left
A.left = None
return A
else:
A.right = left
cur = A
while cur.right:
cur = cur.right
cur.right = right
A.left = None
return A
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __str__(self):
res = str(self.val)
return res
def __repr__(self):
return self.__str__()
def createTree():
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(5)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.right = TreeNode(6)
return root
def zigzagLevelOrder(A):
print("yolo")
queue = []
res = []
cur = []
if A is None:
return res
queue.append(A)
queue.append(None)
flag = 0
while queue:
temp = queue.pop(0)
if temp:
cur.append(temp)
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
else:
if len(queue)>0:
queue.append(None)
res.append(cur+[])
cur = []
return res
root = flatten(createTree())
print(zigzagLevelOrder(root))
| true |
aa0d85a5f743e69c34531ca22ce93ef424e1e612 | Divine11/InterviewBit | /Stacks And Queues/Generate_All_Parentheses.py | 841 | 4.125 | 4 | # Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
# The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
# Return 0 / 1 ( 0 for false, 1 for true ) for this problem
def isValid(A):
opening = ['(','{','[']
closing = [')','}',']']
res = []
if A==None:
return 1
if len(A)==1:
return 0
for i in A:
if i in opening:
res.append(i)
elif i in closing:
ind = closing.index(i)
if len(res)<1:
return 0
if res[-1]==opening[ind]:
res.pop()
else:
return 0
else:
return 0
if len(res)!=0:
return 0
return 1
print(isValid("{{"))
| true |
36b5f7278ccda2936222a1d8468ce02bde0f3e1e | it-learning-diary/pystudy | /python十万字入门/加入列表.py | 342 | 4.25 | 4 | # coding=gbk
"""
ߣ
ʱ䣺2021/8/23
Ⱥ970353786
"""
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1) | false |
45e05755de29803965fb1016c87325961ec9c9c3 | it-learning-diary/pystudy | /python十万字入门/继承.py | 2,507 | 4.125 | 4 | # coding=gbk
"""
ߣ
ʱ䣺2021/8/24
Ⱥ970353786
"""
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("", "")
x.printname()
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
pass
x = Student("", "")
x.printname()
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
x = Student("", "")
x.printname()
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
x = Student("", "")
x.printname()
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2021
x = Student("", "")
print(x.graduationyear)
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("", "", 2021)
print(x.graduationyear)
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
x = Student("", "", 2021)
x.welcome() | false |
98fddce213b302c16acf32500065cbf5770ac820 | jangui/archive | /Python-Scripts/circle.py | 361 | 4.375 | 4 | import math
import turtle
def drawCircle(x, y, r):
""""Draws a cirlce using the turtle module"""
#move to start of circle
turtle.up()
turtle.setpos(x + r, y)
turtle.down()
#draw the circle
for i in range(0, 365, 5):
a = math.radians(i)
turtle.setpos(x + r*math.cos(a), y + r*math.sin(a))
drawCircle(100, 100, 200)
turtle.mainloop() | true |
a82c70a453682d9d8ed3aee73ed7b42fa042cb8b | fanbyprinciple/pymaths | /doing_math_with_python/chapter2/gravitational_formula.py | 830 | 4.125 | 4 | '''
The relationship between gravitational force and
distance between two bodies
'''
import matplotlib.pyplot as plt
from pylab import savefig
# Draw the graph
def draw_graph(x,y):
plt.plot(x, y, marker='o')
plt.xlabel('Distance in meters.')
plt.ylabel('Gravitational force in Newton.')
plt.title('Gravitational force and distance')
plt.show()
savefig('gravity.png')
def generate_F_r():
# generate values for r
r = range(100, 1001, 50)
# Empty list
F = []
# Constant, G
G = 6.674 * (10 **-11)
# two masses
m1 = 0.5
m2 = 1.5
# Calculate force andadd it to the list, F
for dist in r:
force = G* (m1 * m2)/ (dist ** 2)
F.append(force)
# call the draw_graph function
draw_graph(r, F)
if __name__ == '__main__':
generate_F_r() | true |
1731d8cdfed7335e7387e48ff9e4a64eb24b61f8 | MiguelBalderrama/lab10 | /70-100pt.py | 1,483 | 4.4375 | 4 | ##########################################
# #
# Draw a house! #
# #
##########################################
# Use create_line(), create_rectangle() and create_oval() to make a
# drawing of a house using the tKinter Canvas widget.
# 70pt: House outline (roof and the house)
# 80pt: Square windows and a door
# 90pt: A door handle plus a chimney!
# 100pt: Green grass on the ground and a red house!
# Minus 5pts if your code has no comments
# Minus 10pts if you only commit once to github
from Tkinter import *
root = Tk()
# Create the canvas widget
drawpad = Canvas(root, background='white')
drawpad.grid(row=0, column=1)
# create_oval(x,y,width,height,fill color)
#create_square(top left x,top left y, bottom right x, bottom right y, fill color)
square = drawpad.create_rectangle(120,90,130,50, fill='red')
square = drawpad.create_rectangle(50,200,150,100, fill='red')
square = drawpad.create_rectangle(110,110,140,140, fill='white')
square = drawpad.create_rectangle(60,110,90,140, fill='white')
square = drawpad.create_rectangle(80,160,110,200, fill='white')
oval = drawpad.create_oval(100, 170, 105, 180, fill='blue')
square = drawpad.create_rectangle(40,200,180,220, fill='green')
#create_line(top left x,top left y, bottom right x, bottom right y, fill color)
line = drawpad.create_line(150, 100, 100, 50)
line = drawpad.create_line(50, 100, 100, 50)
root.mainloop() | true |
69605eded459aa40bfdc8648549ba030fd809184 | shahidcaan/AnimatedMovies | /src/Task2.py | 803 | 4.3125 | 4 | """
Task 2a
Write a modified version of function readAllRecords()
to read all the records from the file and return the
records as a Python list.
"""
def readAllRecords():
file = open("MoviesData.txt", "r")
allMovies = file.readlines()
file.close()
return allMovies
"""
Task 2b
Write another function displayAllNames() that uses
or calls the method in part a to get the list, iterate
through the it and display ONLY the titles (movies name) of
all the movies.
"""
def displayAllNames():
movies = readAllRecords()
for movie in movies:
allFields = movie.split("%")
#Task 2c Adding movie release year to part b part of program.
print(allFields[1] +" - "+allFields[2])
# Calling the defined function to execute it
displayAllNames()
| true |
7771b3a895ed8272bebe233aa9a7259d0a55d585 | loingo95/leetcode | /symmetric-tree/symmetric-tree.py | 942 | 4.125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
return self.compare(root.left, root.right)
def compare(self, node_1, node_2):
# if code can reach the leave the it's true
if (node_1 is None) and (node_2 is None):
return True
# if either of node is none and other one is a leaf then it's false
if (node_1 is None) or (node_2 is None):
return False
# if current nodes is not equal return immediately
if node_1.val != node_2.val:
return False
# All sub compare must be true to return a true value
return self.compare(node_1.left, node_2.right) and self.compare(node_1.right, node_2.left)
| true |
18a2e2f92dd71889063d89bf7913577c9ebc85dd | MachineLearningIsEasy/python_lesson_4 | /functions.py | 1,307 | 4.375 | 4 | #Простейшая функция и описание
def add(x,y):
'''
:param x:
:param y:
:return:
'''
return x+y
help(add) # просмотр описания функции
# Вызов функции
print(add(100,101))
print(add('Dima','+Kate'))
# Функция возвращает функцию
def f1(n):
def f2(m):
return n+m
return f2
new_f = f1(100)
print(type(new_f))
new_f = f1(100)
print(new_f(250))
#Даже без return функция вернет None
def f():
pass
print(f())
#Аргументы функций-------------
-------------------------------
# Обязательные аргументы и не обязательные
def add(x,y, z = 10):
'''
:param x:
:param y:
:return:
'''
return x+y+z
print(add(1,2))
print(add(1,2,3))
# args
def func(*args):
print(type(args), args)
return args
func(1,2,3,'Volvo')
# kwargs
def func(**kwargs):
print(type(kwargs), kwargs)
return kwargs
func(a = 1, b = 2, c = 'Volvo', d = 1.5)
# Все вместе
def func_difficult(x, y = 2, *args, **kwargs):
print(type(x), x)
print(type(y), y)
print(type(args), args)
print(type(kwargs), kwargs)
return kwargs
func_difficult(1,3, (1,2,3), temp = 12, temp_1 = 13) | false |
9bdbcd076778f3763ba80572ce2bf228e315f837 | Koro6ok/CURSOR_HW | /HW2/1+1a.py | 2,220 | 4.125 | 4 | # 1. Create a class hierarchy of animals with at least 5 animals that have additional methods each,
# create an instance for each of the animal and call the unique method for it.
# Determine if each of the animal is an instance of the Animals class
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f'{self.name} like eating delicious food')
def sleep(self):
print(f'{self.name} need to sleep a little bit')
class Frog (Animal):
def frog_skill (self):
print(f'{self.name} can jump')
class Zebra(Animal):
def zebra_skill (self):
print(f'{self.name} can run')
class Bird(Animal):
def bird_skill (self):
print(f'{self.name} can fly')
class Elephant(Animal):
def elephant_skill (self):
print(f'{self.name} have a trunk')
class Lemur(Animal):
def lemur_skill (self):
print(f'{self.name} can climb trees')
frog = Frog('Frog')
zebra = Zebra('Zebra')
bird = Bird('Bird')
elephant = Elephant('Elephant')
lemur = Lemur('Lemur')
frog.frog_skill()
zebra.zebra_skill()
bird.bird_skill()
elephant.elephant_skill()
lemur.lemur_skill()
frog.eat()
frog.sleep()
for item in (frog,zebra,bird,elephant,lemur):
instance = f'{isinstance(item,Animal)}'
print(str(item.name) + ' is an instance of the Animals class: ' + instance)
# 1.a. Create a new class Human and use multiple inheritance to create Centaur class,
# create an instance of Centaur class and call the common method of these classes and unique.
class Human:
def __init__(self, name):
self.name = name
def eat(self):
print(f'{self.name} like eating something special')
def sleep(self):
print(f'{self.name} need to sleep, sometimes')
def study(self):
print(f'{self.name} need studying everyday')
def work(self):
print(f'{self.name} need to work, if she want to earn some money')
class Centaur (Human, Animal):
def home (self):
print(f'{self.name} usually live in forest')
def sleep(self):
Human.sleep(self)
centaur = Centaur('Centaur')
print('---------------------------------------------------')
centaur.home()
centaur.sleep() | true |
f101db7fe9fd9e8fde69ec4d1878d6a0676e24d3 | pbeens/Challenges | /_in progress/Reddit Wandering Fingers/Wandering Fingers.py | 2,240 | 4.28125 | 4 | '''
From https://goo.gl/s3VJAN
Description
Software like Swype and SwiftKey lets smartphone users enter text by dragging their finger over the on-screen keyboard, rather than tapping on each letter.
Example image of Swype: http://www.swype.com/content/uploads/2014/09/swype_path.png
You'll be given a string of characters representing the letters the user has dragged their finger over.
For example, if the user wants "rest", the string of input characters might be "resdft" or "resert".
Input
Given the following input strings, find all possible output words 5 characters or longer.
qwertyuytresdftyuioknn
gijakjthoijerjidsdfnokg
Output
Your program should find all possible words (5+ characters) that can be derived from the strings supplied.
Use http://norvig.com/ngrams/enable1.txt as your search dictionary.
The order of the output words doesn't matter.
queen question
gaeing garring gathering gating geeing gieing going goring
Notes/Hints
Assumptions about the input strings:
QWERTY keyboard
Lowercase a-z only, no whitespace or punctuation
The first and last characters of the input string will always match the first and last characters of the desired output word
Don't assume users take the most efficient path between letters
Every letter of the output word will appear in the input string
Bonus
Double letters in the output word might appear only once in the input string, e.g. "polkjuy" could yield "polly".
Make your program handle this possibility.
'''
'''
NOT WORKING YET...
'''
import urllib.request
words = []
possible_words = []
url = 'https://raw.githubusercontent.com/pbeens/challenges/master/cleandict.txt'
response = urllib.request.urlopen(url)
data = response.readlines()
# create list of words
for line in data:
words.append(line.strip().decode('UTF-8'))
# find possible words
swype = 'qwertyuytresdftyuioknn'
for word in words:
if len(word) > 4 and word[0] == swype[0] and word[-1:] == swype[-1:]:
possible_words.append(word)
print (possible_words)
for word in possible_words:
possible = True
for c in word:
if c not in swype:
print (c)
possible = False
if possible == False:
possible_words.remove(word)
print (possible_words)
| true |
3598b3a190968675d0ad57934d75d2a60bf40d53 | Steelex/CSE | /Hangman - Steelex Garcia Period 3.py | 1,552 | 4.21875 | 4 | import random
import string
# Steelex Garcia
# Period 3
"""
A general guide for Hangman
1. Make a word bank - 10 items
2. Pick a random word from the item from the list
3. Add a guess to the list of letters guessed
4. Reveal letters already guessed
5. Create the win condition
"""
word_bank = ["monster", "metal", "fear", "deceiving",
"science", "unmatched", "power", "perfection",
"cataclysm", "pokemon", "charizard", "blastoise",
"scizor", "luffy", "bleach", "ichigo", "orihime",
"inhuman", "saitama", "naruto", "genos", "scare",
"lonely", "amazing"]
guesses = 11
alphabet = list(string.ascii_lowercase)
random_word = random.choice(word_bank)
correct = list(random_word)
print("Choose a letter. They are comepletely random You have ten tries")
letters_guessed = []
while guesses > 0:
output = []
for letter in random_word:
if letter in letters_guessed:
output.append(letter)
else:
output.append("*")
guesses -= 1
print(guesses)
join = " ".join(output)
print(join)
if output == correct:
print("You Win! You successfuly guessed the right word!")
exit(0)
print("These are your letters you can guess :), %s" % alphabet)
ask_for_letter = input("Name a letter")
lowercase_guess = ask_for_letter.lower()
letters_guessed.append(lowercase_guess)
if lowercase_guess in alphabet:
alphabet.remove(lowercase_guess)
if guesses == 0:
print("You Lose The Word Was %s" % random_word)
| true |
1ad3b19b27a9c0fc0a2b71475fe98afdc08638d1 | moogzy/learnpythonthehardway | /ex3.py | 1,038 | 4.5 | 4 | #!/usr/bin/python
# Prints statement for counting chickens
print "I will now count my chickens:"
# Addition then divisions for hens
print "Hens", 25.0 + 30.0 / 6.0
# Subtractions then multiplication then modulus(remainder)
print "Roosters", 100.0 - 25.0 * 3.0 % 4.0
# Prints statement for counting eggs
print "Now I will count the eggs:"
# Addition, substraction, modulus(remainder), subtraction, divisions, addition
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0
# Prints statements then provides true\false comparison between arithmetic statements
print "Is it true that 3 + 2 < 5 - 7?"
print 3.0 + 2.0 < 5.0 - 7.0
# Prints value of each arithmetic statement.
print "What is 3 + 2?", 3.0 + 2.0
print "what is 5 - 7?", 5.0 -7.0
# Prints statement
print "Oh, that's why it's False."
# Prints statement
print "How about some more."
# Provides true\false comparison between arithmetic statements
print "Is it greater?", 5.0 > -2.0
print "Is it greater or equal?", 5.0 >= -2.0
print "Is it less or equal?", 5.0 <= -2.0
| true |
0049cee9fdc9de28fcd4e39bdfadb1b38f3402c4 | vardaan-raj/The-Layman-Machine-Learning-dictionary | /examples/linearRegression.py | 1,279 | 4.15625 | 4 | # Linear Regression
import numpy as np
# Cost Function For Linear Regression
def costFunction(X,y,theta):
J = 0
m = np.size(y)
grad = 0
for i in range(0,m):
h = X[i]*theta.T
grad += (h-y[i])*X[i]
J *= 1/m
grad *= (alpha/m)
return J,grad
# Dataset
x = np.matrix('1 0;1 100;1 200;1 300;1 400;1 500')
y = np.matrix('0;1;2;3;4;5')
'''
X Y
--------
0 0
100 1
200 2
300 3
400 4
500 5
'''
# Learning rate
alpha = .3
# Optimization algorithm
def gradientDescent(iterations,x,y):
# Initial Value for theta
theta = np.matrix('0.0 0.0')
# Initializing new Cost and Old Cost
cost = costFunction(x,y,theta)[0]
oldCost = 10000
# Use the gradient while the threshold is not reached
for iteration in range(0,iterations):
gradient = costFunction(x,y,theta)[1]
print(f"Iteration {iteration} :",theta,oldCost,cost)
theta -= gradient
oldCost = cost
cost = costFunction(x,y,theta)[0]
return theta
# Predicting function
def predict(x,theta):
X = np.matrix(f'1 {x}')
return round(float(X*theta.T))
#================================================#
print("Getting ready to train model")
input("Press [ENTER] to continue")
theta = gradientDescent(1000,x,y)
#================================================#
| false |
34993d094b41a5a4fc249b610a563561576d93c3 | codymalick/practice | /python/sorting/merge_sort.py | 1,669 | 4.1875 | 4 | """Merge sort is a divide and conquor algorithm that breaks an array into subarrays to sort.
Runtime Complexity:
Best: O(nlogn)
Worst: O(nlogn)
Average: O(nlogn)
Space Complexity: O(n)
"""
import random
def generate_array():
return [random.randint(0, 100) for x in range(50)]
def merge_sort(array):
# if one, the array sorted
if len(array) == 1:
return array
# In an even length array, pick middle
length = len(array) # len() returns non-zero indexed value
if length % 2 == 0:
middle = int(length / 2)
else:
middle = int((length - .5) / 2)
# Python slice notation is end exclusive
# Ex: arr[0:10] takes elements 0 - 9
# To resolve this issue we simply don't subtract 1 from the length
left = merge_sort(array[:middle])
right = merge_sort(array[middle:])
# build return array
result = []
while len(left) != 0 or len(right) != 0:
# If the right array is empty, keep popping the left
if len(right) == 0:
result.append(left.pop(0))
continue
# If the left array is empty, keeping popping the right
if len(left) == 0:
result.append(right.pop(0))
continue
# Normal case
if left[0] < right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
return result
def main():
unsorted_array = generate_array()
print(unsorted_array)
sorted_array = merge_sort(unsorted_array)
print(sorted_array)
if __name__ == "__main__":
main() | true |
d1396f03cd112f90bdd2fdc374a0d7bd8ea235cd | rozifa/mystuff | /ex21.py | 1,354 | 4.34375 | 4 | #Defines four basic functions that each take two arguments: a, b.
#Each function prints a string formatted with each of the input arguments
#Then returns a value. This returned value can be stored in variables
#IT IS NOT PRINTED, it simply tells the function what its final output should
#be. This has to be stored or printed to be viewed.
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
#prints a string
print "Let's do some math with just functions"
#Assigns the values of each of the functions with some differing arguments
#to four different variables.
age = add(30, 5)
height = multiply(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
#Prints string formatted with the values of the four variables. These values
#are obtained by applying the defined functions tot heir respective arguments.
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
#Puzzle for extra credit
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
#This is just a chain of functions that use returned values as arguments in
#other functions.
print "That becomes", what, "Can you do it by hand?"
| true |
b42e2047f24f03c2a0a8af664c85fb2dbf0b2ae4 | charan2108/pythonprojectsNew | /lists/numericallists/range.py | 690 | 4.125 | 4 | #range
for value in range(1, 10):
print(value)
#using number as variable
numbers = list(range(1, 100))
print(numbers)
#evennumber
evennumber = list(range(2,20,2))
print(evennumber)
#oddnumber
oddnumber = list(range(1,25,2))
print(oddnumber)
# Squarenumber
squares = []
for value in range(1,14):
square = value ** 2
squares.append(square)
print(squares)
squares = [value ** 2 for value in range(1, 14)]
print(squares)
# cubenumber
cubes = []
for value in range(1,14):
cube = value ** 3
cubes.append(cube)
print(cubes)
cubes = [value ** 3 for value in range(1, 14)]
print(cubes)
powerfour = [value ** 4 for value in range(1, 14)]
print(powerfour) | true |
c64cee9be624e7234096eb01fc7056671c0eb05e | nikhilagopathi/sample | /app.py | 2,016 | 4.375 | 4 | #print("Hello world")
# taking inputs from terminal
#Patient_name = input('What is your name')
#Age= input('what is your age')
#status= input('status')
#print ( "Hello " + Patient_name + " is" +Age + " years old and " + status)
#birth_year = input('what is your birth year')
#Age = 2021 - int(birth_year)
#print(Age)
#calculator program
#first= float(input('enter first number:'))
#second = float(input('Enter second number:'))
#sum = first + second
#print("sum is:" + str(sum))
#for checking
#course = "Python for beginners"
#print(course.upper())
#print(course)
#print(course.find('n'))
#print(course.replace('for', '4'))
#print('Python' in course)
#basicmath operations
#print(10/3) #returnwith decimal
#print(10//3) #returns only number
#print(10%3) #remiander
#print(10 ** 3) #exponent (10 to the power of 3 here)
#x= 10+3*2
#print (x) #precesion
#y=(10+3)*2
#print(y)
#comparision operators
#x = 3>2
#print(x)
#x = 2<1
#print(x)
#logical operators
#price =25
#print(price > 10 and price <30)
#price = 5
#print(price > 10 or price <30)
#if statements
#temp = 5
#if temp > 30:
# print("It's a hot day")
# print('Drink pleanty of water')
#elif temp>20:
# print("it's a nice day")
#elif temp>10:
# print("it's a bit cold")
#else:
# print("it's cold")
#print ('done')
#
a= [5,3,2,4,6,13]
b= [2,3,4,5,6,8]
c=[]
for n in range (0, len(a)):
c.append(a[n] + b[n])
print("the sum list is ", c)
for m in c:
if m%3== 0 and m%7==0:
print("Fizzbuzz")
elif m % 3 == 0:
print("fizz")
else:
print("Buzz")
# weight function
weight = int(input("weight:"))
unit = input("(K)g or (L)bd: ")
if unit.upper() == "K":
converted = weight/0.45
print("weight in pounds is : " + str(converted))
else:
converted = weight *0.45
print("Weight in kg is " + str(converted))
#while loops - to repeat block of coade multiple time
i=1
while i<=5:
print(i)
i=i+1
#functions with while
i=1
while i<=10:
print(i * '*')
i=i+1
#Lists
a= 7**2
print(a) | true |
cf7a4a97ac0024dc0801ff38eadfce286614c85f | raygolden/leetcode-python | /src/groupAnagram.py | 855 | 4.15625 | 4 | #!/usr/bin/env python
# given a list of words, write a function which
# takes in the list, and groups the words together
# according to which ones are anagrams of eachother
# e.g.
# input = ["art", "rat", "bats", "banana", "stab", "tar"]
# output = [["art", "rat", "tar], ["bats", "stab"], ["banana"]]
def groupAnagrams(input):
new_input = [(elm, sorted(elm)) for elm in input]
new_input = sorted(new_input, key=lambda x:x[1])
output = []
cur_ana = new_input[0][1]
group = []
for elm, ana in new_input:
if ana == cur_ana:
group.append(elm)
else:
output.append(group)
cur_ana = ana
group = [elm]
output.append(group)
return output
if __name__ == '__main__':
print groupAnagrams(["art", "rat", "bats", "banana", "stab", "tar"]) | true |
180a462489d2ab4d66a7af27f1aba5bd7e09ccbf | anushreesaha/python_training | /source/comments.py | 1,766 | 4.25 | 4 | """ This module is used to practice comments """
import argparse
from util.logger import get_logger
#logger = get_logger()
c = """this module is used
to"""
#logger.info(c)
d = "this is module is used " \
"to"
#logger.info(d)
# ====================== Block comment Example =====================
# The main function will parse arguments via the parser variable. These
# arguments will be defined by the user on the console. This will pass
# the word argument the user wants to parse along with the filename the
# user wants to use, and also provide help text if the user does not
# correctly pass the arguments.
#
# Add extra comment
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-w","--word",dest="word",
help="the word to be written to a text file."
)
parser.add_argument(
"-f","--filename",dest="filename",
help="the path to the text file to be searched through"
)
cmd_options = parser.parse_args()
print(cmd_options)
fp = open(cmd_options.filename, "w") # open a file in write mode
fp.write(cmd_options.word)
fp.close()
# ================== Documentation string Example=================== #
def get_db_conn(host_name, db, user, db_pass):
"""
Get a db connection with given host.
if no connection exist, thrown an exception
:param host_name: hostname
:param db: database name
:param user: database user
:param db_pass: database password
:return:
"""
pass
def get_conn(a, b):
"""
:param a:
:param b:
:return:
"""
# main()
#__main__(private). other modules cant access that function
#_main
#__main
# __variable__ # Inbuilt variable
# _variable # Private variable
# __variable # Protected variable
| true |
881526253537ceceeed4a343f3897a9284e5eb67 | fercibin/Python | /Loop-FOR.py | 1,875 | 4.21875 | 4 | """
Loop FOR
--------
- C ou C++
----------
for (int i=0, 1< 10, i++) {
// bloco de instruções
}
Python
------
for x in iterável:
// bloco de instrução
Utilizamos loops para iterar sobre sequências ou sobre valores iteráveis.
Exemplos de iteráveis:
- String
- Lista
- Range
"""
string = 'Curso Python'
lista = [1, 3, 5, 7, 9]
index = range(0, 10)
# Iterando em uma String
for letra in string:
print(letra)
for letra in string:
print(letra, end='')
print("\n----------------------------------------")
# Iterando em uma lista
for numero in lista:
print(numero)
print("----------------------------------------")
# Iterando sobre um range - Vai de zero até 10-1 (9)
for index in range(0, 10):
print(index)
print("----------------------------------------")
asteristico = '*'
for x in range(1, 16): # rodar 15 vezes, de 1 a 15
print(asteristico * x)
"""
Tabela de emoji unicode: https://apps.timwhitlock.info/emoji/tables/unicode
Exemplo de um emoji convertido (trocar o sinal de '+' por '000' (3 zeros)
Original : U+1F60D
Convertido: U0001F60D
"""
for _ in range(3): # Vai executar esse loop 3 vezes
for num in range(1, 4):
print('\U0001F61D' * num)
qtd = int(input("Quantas vezes rodar o loop?"))
for num in range(1, qtd + 1):
print('\U0001F60D' * num)
var = 'Python'
for x in var:
print(x)
print("**********************************************")
frutas = ['laranja', 'morango', 'guarana', 'melancia', 'mamao']
for y in frutas:
print("Fruta: %s" % y)
print("**********************************************")
'''
Loop FOR com contador
--------
- Funcao range() - Gera uma lista contendo uma progressao aritmetica
- Sintaxe
range(inicio, fim, salto)
- Inicio e salto sao opcionais
'''
for x in range(1, 11):
print(x)
for w in range(0, 51, 5):
print(w)
for w in range(1, 51, 5):
print(w)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.