blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
296e89f93f80b101088a1e3e89b2d889eb50fa05 | vinceajcs/all-things-python | /algorithms/graph/bfs/valid_tree.py | 1,342 | 4.15625 | 4 | """Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), check whether these edges make up a valid tree.
Example 1:
Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true
Example 2:
Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output: false
Assume that no duplicate edges will appear in edges. Since all edges are undirected, [0,1] is the same as [1,0] and thus will not appear together in edges.
A tree is connected, acyclic, and contains n-1 edges, where n is the number of nodes.
We can use BFS to check if there's a cycle and only one connected component in the graph.
Time: O(m+n)
Space: O(m+n)
"""
def valid_tree(n, edges):
lookup = {i: set() for i in range(n)} # n nodes from 0 to n-1
# create graph
for x, y in edges:
lookup[x].add(y)
lookup[y].add(x)
visited = set()
queue = collections.deque([list(lookup.keys())[0]])
while queue:
node = queue.popleft()
if node in visited: # cycle
return False
visited.add(node)
for neighbour in lookup[node]:
queue.append(neighbour)
lookup[neighbour].remove(node)
lookup.pop(node)
return not lookup # if there are any nodes left, that means there is more than one connected component
| true |
8e6229c7685cf84d2f59e09cdb26349846aadbf9 | cvhs-cs-2017/sem2-exam1-thomasw19 | /Turtle.py | 582 | 4.125 | 4 | """Create a Turtle Program that will draw a 3-dimensional cube"""
import turtle
thomas = turtle.Turtle()
for i in range (4):
thomas.forward(300)
thomas.right(90)
thomas.left(135)
thomas.forward(200)
thomas.right(135)
thomas.forward(300)
thomas.right(45)
thomas.forward(200)
thomas.right(135)
thomas.forward(300)
thomas.left(90)
thomas.forward(300)
thomas.right(135)
thomas.forward.(200)
thomas.right(45)
thomas.forward(300)
"""Import and Call the DrawRectangle(Anyturtle, l, w) function from the
file MyFile.py"""
import DrawRectangle from MyFile
DrawRectangle(thomas, 20, 30)
| false |
ebf403e6382bcfe27c154498c227798f4fb8fe26 | KodeKunstner/grundat | /weeks/week38/oversaet.py | 907 | 4.1875 | 4 | def translate(string):
"""Make a direct translation, by replacing english words with danish words"""
# set of words used in the translation
dict = {
"a": "en",
"another": "endnu",
"hello": "hej",
"is": "er",
"is": "er",
"next": "naeste",
"now": "nu",
"test": "test",
"this": "dette",
"what": "hvad",
"world": "verden" }
# run through the words in the string,
# and replace with known words
result = ""
for word in string.split():
if dict.has_key(word):
result = result + dict[word]
else:
result = result = word
result = result + " "
return result
# Try to run som simple direct translations
print(translate("hello world"))
print(translate("now this is a test"))
print(translate("what is next"))
print(translate("another a test"))
| true |
1d329f78ff1a5cd779a87864d6c959685ae59d28 | youssef-abbih/python_projects | /turtle_race/main.py | 1,106 | 4.125 | 4 | import turtle
from turtle import *
from random import choice
colors =['red', 'blue', 'green', 'black']
y_position = [50, -50 ,-100, 100]
speed = list(range(0,10))
turtles = []
#******Screen****************************
screen = Screen()
screen.setup(width = 500, height = 400)
screen.bgpic("race_road.png")
#******create the turtles****************
for turtle_index in range(0,4):
tortuga= Turtle()
tortuga.color(colors[turtle_index])
tortuga.shape('turtle')
tortuga.penup()
tortuga.goto(-240,y_position[turtle_index])
turtles.append(tortuga)
user_bet = screen.textinput(title = "Make your bet", prompt = "Wich turtle will win the race? ")
if user_bet:
is_race_on = True
while is_race_on:
for turtle in turtles:
if turtle.xcor() > 220:
is_race_on = False
winner = turtle.pencolor()
if winner == user_bet:
print(f"You've won! The {winner} turtle is the winner")
else:
print(f"You've lost! The {winner} turtle is the winner")
turtle.fd(choice(speed))
screen.exitonclick()
| true |
fb7c57de673ac7102b7c7e5927acef368d3d11d1 | IzzyBrand/cs1951c_demos | /pi_basics/blink.py | 834 | 4.40625 | 4 | '''
Demonstrates how to blink an LED using the RPi.GPIO library.
See this tutorial for more details
https://learn.sparkfun.com/tutorials/raspberry-gpio/python-rpigpio-api
Example code for csci1951c Designing Humanity Centered Robots
Brown University
Izzy Brand (2018)
'''
import RPi.GPIO as GPIO # this library enables interfacing with the GPIO (pins)
from time import sleep # this library gives delay functionality
led_pin = 18 # declare a variable to store which pin to blink
# setup the pin
GPIO.setmode(GPIO.BCM) # say how the pins are numbered (this is the most common scheme)
GPIO.setup(led_pin, GPIO.OUT) # set the led_pin as output
# blink in a loop
while True:
GPIO.output(led_pin, GPIO.HIGH)
print "Pin", led_pin, "ON"
sleep(1)
GPIO.output(led_pin, GPIO.LOW)
print "Pin", led_pin, "OFF"
sleep(1)
| true |
82699003d5d51bf9a8d53f5d101078b64ff24acc | MissNaibei/PythonBasics | /Classes_and_Objects.py | 1,600 | 4.25 | 4 | name = "Naibei"
age = 16
# print(type)
# print(type(name))
# print(type(age))
class Person:
#class attribute - shared by all instances
species = "Homo sapien"
#METHOD - Is a function defined inside a class. Self is a default parameter
def walk(self):
print("is walking.")
def sleep(self):
print("{} is sleeping.".format(self.jina))
def __init__(self,name, age):
print("I am the constructor method.")
self.jina = name
self.miaka = age
p6 = Person("Bev", 16)
p7 = Person("Maria", 54)
print(p6.jina)
print(p7.miaka)
p7.sleep()
# p1 = Person()
# p2 = Person()
# p3 = Person()
# p4 = Person()
#
# # print(p1)
# # print(p1.species)
#
#
# #ASSIGN P1 A NAME - instance attributes
#
# p1.name = "Price"
# p2.name = "Soraya"
# p1.age = 67
# print(p1.age)
# p1.race = "African_american"
# p1.nationality = "Rwandese"
# p1.city = "Nairobi"
# p1.spouse = "Alejandro"
#
# # print(p1.race)
# # print(p1.nationality)
# # print(p1.city)
# # print(p1.spouse)
#
# p1.walk()
# p1.sleep()
# p2.sleep()
# class Vehicle:
# #class attribute - shared by all instances
# brand = "Ford"
# # METHOD - Is a function defined inside a class. Self is a default parameter
# def make(self):
# print("is a Mustang.")
# def year(self):
# print("{} was manufactured in 1967.".format(self.owner))
# def breakdown(self):
# print("{} was towed to the garage down town.".format(self.owner))
# car_one = Vehicle()
# car_one.owner = "Miss_Naibei's Machine"
# print(car_one.brand)
# car_one.year()
# car_one.breakdown()
| false |
28cfe665d7b3bcb53c1bb765e69715dad904eb43 | hellowitsme/python | /string_manipulation/main.py | 1,166 | 4.40625 | 4 | # フォーマット
# -------------------------------------
# titleメソッド
# 頭文字を大文字に
print("the walking dead".title())
# formatメソッド
who = input("誰が:")
where = input("どこで:")
what = input("何を:")
do = input("した:")
print("{}が、{}で、{}を、{}したw".format(who, where, what, do))
# splitメソッド
# 引数に渡した文字で分割
print("splitメソッドでは、文章を分割できます。".split("、"))
# joinメソッド
# 全ての文字列の間に新しい文字列を追加
words = ["The", "Walking", "Dead"]
print(" ".join(words))
# stripメソッド
# 空白除去
print(" The ".strip())
# indexメソッド
# 引数に文字を渡す。最初にその文字が現れたインデックス値が帰ってくる
print("animals".index("l"))
# sliceメソッド
# オブジェクトの一部を切り取る
# 終了インデックス値の手前までしか含まない
# 最初の要素から始める場合"0"は省略可能
# 最後の要素まで含める場合終了インデックスは省略可能
list = ["Google", "Apple", "Facebook", "Amazon"]
print(list[:3])
print(list[1:])
| false |
9e3e2ccc89bc10f802eda677a0d12bbd09cc546a | IvetteAb/PythonProjects | /Plotting graphs in Python.py | 2,894 | 4.75 | 5 | # Plotting graphs in Python
# import the relevant modules
import matplotlib.pyplot as plt # named the package plt
# create a very basic plot - we'll want something better
# create a random list
x = [1, 3, 5, 10] # this is what we're plotting
plt.plot(x) # this won't work because you need to say --> plt.show()
plt.show() # v basic, no axis or labels, press red stop button to stop running the graph
# plotting x & y against each other
# both lists need to have the same no of entries
y = [7, 12, 21, 22]
plt.plot(x, y) # +ive correlation as x increases, y increases
plt.show()
# build a better plot
# import the relevant modules
import matplotlib.pyplot as plt # named the package plt
# line 1 - points
x = [3, 9, 14]
y = [2, 7, 30]
# plotting x & y
# now inc info on how you want the graph to look
plt.plot(x, y, c="red", linewidth=2, label="Line 1")
# plt.show() # no legend (i.e key) has popped up, as you have to ask python to recall it
# Line 2 - points
x2 = [1, 15, 18]
y2 = [0, 3, 12]
# plotting x & y
plt.plot(x2, y2, c="green", linewidth=0.5, label="Line 2")
# plt.show()
# label the axis & title
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Table one!")
# show the legend (i.e. key) on the plot --> this will show the labels given to each plot L26, L33
plt.legend()
# get python to show the plot
plt.show()
# other styles to add on a graph
# import the relevant modules
import matplotlib.pyplot as plt # named the package plt
# line 1
a = [3, 9, 14]
b = [2, 7, 30]
# plotting a & b
# now inc info on how you want the graph to look
plt.plot(a, b, c="pink", linewidth=2, label="Line 1")
# Line 2 - points
a2 = [1, 15, 18]
b2 = [0, 3, 12]
# plotting a2 & b2
plt.plot(a2, b2, c="blue", linewidth=0.5, label="Line 2", linestyle="dashed",
marker='o', markerfacecolor="black", markersize=10)
# if marker='s' then the marker will be a square
plt.xlabel("A-axis") # label the axis & title
plt.ylabel("B-axis")
plt.title("Table two!")
# limits of the axis
plt.xlim(0, 30) # limit between 0 & 30
plt.ylim(1, 10) # limit between 1 & 10
plt.legend() # show the legend (i.e. key) on the plot
plt.show()
# Create a graph with two lines
import matplotlib.pyplot as plt
# line 1 points
x = [12, 23, 32, 46, 54, 71, 98]
y = [17, 28, 35, 52, 69, 99, 74]
plt.plot(x, y, c="purple", linewidth=2, label="Line 1", marker='s', markerfacecolor="yellow",
markersize=6)
# line 2 points
x2 = [19, 26, 34, 49, 58, 67, 86]
y2 = [22, 38, 43, 59, 64, 71, 92]
plt.plot(x2, y2, c="orange", linewidth=2, label="Line 2", linestyle="dashed",
marker='o', markerfacecolor="black", markersize=6)
plt.xlabel("X-axis") # label the axis & title
plt.ylabel("Y-axis")
plt.title("A Random Graph")
plt.legend() # show the legend (i.e. key) on the plot
plt.show()
| true |
c5a103a78ecb069d9364ca58103927ec2489a2fd | daviddumas/mcs260fall2020 | /samplecode/redemo_2pm.py | 1,561 | 4.53125 | 5 | """Regular expression demonstrations
MCS 260 Fall 2020 Lecture 28
"""
import re
import sys
def demo1():
"""Minimal example of a regex"""
s = "Avocado is usually considered a vegetable."
print(re.sub("vegetable","fruit",s))
def demo2():
"""dot and repetition controls"""
s = "Do not feed beans to bears"
print(re.sub(r"b.{3}s","?",s))
def demo3():
"""start and end with s"""
s = "Do not feed beans to bears or snakes"
print(re.sub(r"s.+s","?",s))
def demo4():
"""low, low prices"""
s = "A latte costs $18 and a Python textbook costs $599"
print(re.sub(r"\$\d+","$0.99",s))
def demo5():
"""determines whether a string contains digits"""
m = re.search(r"\d+",sys.argv[1])
if m == None:
print("No digits in {}".format(sys.argv[1]))
else:
print("Found this string of digits: {} (at positions {} to {})".format(
m.group(),
m.start(),
m.end()
))
def demo6():
"""Find all contiguous groups of digits in sys.argv[1]"""
L = re.findall(r"\d+",sys.argv[1])
if L:
for s in L:
print("Found number:",s)
else:
print("No digits in",sys.argv[1])
def demo7():
"""Find all contiguous groups of digits in sys.argv[1]"""
for m in re.finditer(r"\d+",sys.argv[1]):
print("Found number {} at positions {} to {}".format(
m.group(),
m.start(),
m.end()
))
if __name__=="__main__":
demo7() | false |
dd34ca54274370c73b5d75147d9b3cd86de3aaea | daviddumas/mcs260fall2020 | /samplecode/sumprod.py | 228 | 4.28125 | 4 | # Read two floats and print their sum and product
# MCS 260 Fall 2020 Lecture 3 - David Dumas
x = float(input("First number: "))
y = float(input("Second number: "))
print("Sum: ",x,"+",y,"=",x+y)
print("Product:",x,"*",y,"=",x*y)
| true |
1ee852b510d92527c5651e5ef3959030608e0f94 | h4r3/PythonFunctions | /[functions] Time_related.py | 665 | 4.25 | 4 | #Time-related functions 2020/12/22
"""Get elapsed time"""#[関数] プログラムの計測時間の表示
def time_elapsed():
import time
print(__doc__)
start = time.time()
print('== Replace the program you want to time here ==') and time.sleep(1)
end = time.time()
_time=end-start
hour,min,sec=_time//3600,_time//60,_time%60
print(f'It takes about {hour:.0f} hours {min:.0f} min {sec:.0f} sec')
return 0
time_elapsed()
"""Get the current time"""
def time_current():
import datetime
print(__doc__)
current=datetime.datetime.today().strftime('%Y%m%d_%H%M%S')
print(current)
time_current() | true |
a043f06288cbc30dda8650601447de6ed6284faf | mirmire/beginner_python_project | /factors.py | 311 | 4.40625 | 4 | #!/usr/bin/python3
# A program to find given number's factors
num = int(input("The number to calculate the factors of: "))
factors = []
def calculate_factors(num):
for i in range(1, num+1):
if num % i == 0:
factors.append(i)
i += 1
calculate_factors(num)
print(factors)
| true |
89329b040f0e579f82588413ebbb5a7dfdd93080 | LuuanOliveira/Snake | /087.py | 1,200 | 4.125 | 4 | matriz = [[0,0,0], [0,0,0], [0,0,0,]] #Uma lista com 3 listas
soma_par = soma_coluna = soma_linha = 0
#Laço para adicionar os valores na matriz
for linha in range(0, 3):
for coluna in range(0, 3):
matriz[linha][coluna] = int(input(f'Digite um valor para [{linha}, {coluna}]: '))
#Adicionando valores atraves de um input na posição 'linha' e 'coluna'
#----------------------------------------------------------
print('=' * 20)
#Laço para mostrar a estrutura na tela
for linha in range(0, 3):
for coluna in range(0, 3):
print(f'[{matriz[linha][coluna]:^5}]', end='')
if matriz[linha][coluna] % 2 == 0: #Calculando a soma de todos os números pares digitados
soma_par += matriz[linha][coluna]
print()
print(f'A soma de todos os pares é {soma_par}')
for linha in range(0, 3): #Calculando os valores da 3 coluna
soma_linha += matriz[linha][2]
print(f'A soma dos valores da 3° coluna é {soma_linha}')
for coluna in range(0, 3): #Pegando o maior valor da 2° Linha
if coluna == 0:
maior = matriz[1][coluna]
elif matriz [1][coluna] > maior:
maior = matriz[1][coluna]
print(f'O maior valor da 2° Linha é {maior}') | false |
960044ee52fc67bb256254724b090f1471a271ac | AlexArango/PythonExercises | /ex19.py | 2,029 | 4.34375 | 4 | # Function that prints out the two number parameters passed in to it
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket. \n"
# A call to the function above
print "We can just give the function numbers directly:"
cheese_and_crackers(19,23)
# Assigning ints to variables to use as parameters for the function above
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 31
# Call to the function with the variables defined above
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# Call to the function with the parameters being summation expressions
print "We can even do math inside, too:"
cheese_and_crackers(17 % 13, 7 - 11)
# Adding numbers to the variables from above and passing these expressions as parameters
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 97, amount_of_crackers + 1001)
# Another way to call the function utilizing user input
print "How many cheeses to you have?"
answer1 = raw_input()
# isdigit() Ensures the input from the user is a number
#print answer1.isdigit()
# Keeps prompting the user for a number and does not move on until user inputs a number
while answer1.isdigit() == False:
print("That's not an int! Please enter a number. We won't move on until you do!")
answer1 = raw_input()
# Turns the user input from a 'string' to an 'int'
val1 = int(answer1)
print "How many crackers to you have?"
answer2 = raw_input()
# Keeps prompting the user for a number and does not move on until user inputs a number
while answer2.isdigit() == False:
print("That's not an int! Please enter a number. We won't move on until you do!")
answer2 = raw_input()
# Turns the user input from a 'string' to an 'int'
val2 = int(answer2)
# Calling the function using the user's input
cheese_and_crackers(val1, val2) | true |
320d2883c5a1fecf87c691878fd82f7716ea5755 | DsDravos-Lnx/DesignPatterns_Strategy | /Exercise_5/invoice.py | 1,399 | 4.125 | 4 | from abc import ABC, abstractmethod
#implementando o metodo abstrado na classe de estrategia
class Strategy(ABC):
@abstractmethod
def tax_calculation(self, number):
pass
#implementando a classe da nota fiscal
class Invoice():
#construtor recebendo uma estrategia inicial do tipo Strategy
def __init__(self, strategy: Strategy):
self._strategy = strategy
#metodo getter
@property
def strategy(self) -> Strategy:
return self._strategy
#metodo setter
@strategy.setter
def strategy(self, strategy: Strategy):
self._strategy = strategy
#metodo para exibir a mensagem com o valor do imposto
def print_tax_calculation(self, value):
print('Calculando o valor de '+str(value)+' reais de acordo com o imposto do estado')
result = self._strategy.tax_calculation(value)
print(result)
####implementanto o metodo abstrato para cada um das classes####
#calculando imposto de São Paulo
class TaxSP(Strategy):
def tax_calculation(self, number):
return 'de São Paulo: '+str((number*0.05))
#calculando imposto do Rio de Janeiro
class TaxRJ(Strategy):
def tax_calculation(self, number):
return 'do Rio de Janeiro: '+str((number*0.08))
#calculando imposto do Ceará
class TaxCE(Strategy):
def tax_calculation(self, number):
return 'do Ceará: '+str((number*0.1)) | false |
5268e6da877b0063a8d6e3d690861698e21e180e | gubenkoved/daily-coding-problem | /python/dcp_324_mices_and_holes.py | 1,142 | 4.375 | 4 | # This problem was asked by Amazon.
# Consider the following scenario: there are N mice and N holes placed at integer points
# along a line. Given this, find a method that maps mice to holes such that the largest
# number of steps any mouse takes is minimized.
# Each move consists of moving one mouse one unit to the left or right, and only one mouse
# can fit inside each hole.
# For example, suppose the mice are positioned at [1, 4, 9, 15], and the holes are located
# at [10, -5, 0, 16]. In this case, the best pairing would require us to send the mouse at
# 1 to the hole at -5, so our function should return 6.
# O(n*logn)
def f(mices, holes) -> int:
# it's obvious from the simple reason to prove that the best way to minimize the biggest
# distance is simple match first mice to the first hole, so that there will be no
# "intersections" if drawn as a bipartite graph as every intersection can be "resolved"
# into a better solution via a unwiding the intersection
mices.sort()
holes.sort()
return max([abs(mices[i] - holes[i]) for i in range(len(mices))])
print(f([1, 4, 9, 15], [10, -5, 0, 16])) | true |
5456219e7caf057c020757f70aa1e7f6bdccee2a | gubenkoved/daily-coding-problem | /python/dcp_401_permutation.py | 992 | 4.125 | 4 | # This problem was asked by Twitter.
#
# A permutation can be specified by an array P, where P[i] represents the location
# of the element at i in the permutation. For example, [2, 1, 0] represents the
# permutation where elements at the index 0 and 2 are swapped.
#
# Given an array and a permutation, apply the permutation to the array. For example,
# given the array ['a', 'b', 'c'] and the permutation [2, 1, 0],
# return ['c', 'b', 'a'].
def permutation(a, p):
if len(a) != len(p):
raise Exception('wrong arguments!')
if len(p) != len(set(p)):
raise Exception('invalid permutation!')
result = [None for _ in a]
for idx in range(len(p)):
result[idx] = a[p[idx]]
return result
assert permutation(['a', 'b', 'c'], [2, 1, 0]) == ['c', 'b', 'a']
assert permutation(['a', 'b', 'c'], [0, 1, 2]) == ['a', 'b', 'c']
assert permutation(['a', 'b', 'c'], [2, 0, 1]) == ['c', 'a', 'b']
assert permutation(['a', 'b', 'c'], [1, 2, 0]) == ['b', 'c', 'a']
| true |
b66cabc4ca81819d90ad2eed53001187ebad091e | gubenkoved/daily-coding-problem | /python/dcp_377_moving_median.py | 1,565 | 4.125 | 4 | # This problem was asked by Microsoft.
#
# Given an array of numbers arr and a window of size k, print out the median of each
# window of size k starting from the left and moving right by one position each time.
#
# For example, given the following array and k = 3:
#
# [-1, 5, 13, 8, 2, 3, 3, 1]
# Your function should print out the following:
#
# 5 <- median of [-1, 5, 13]
# 8 <- median of [5, 13, 8]
# 8 <- median of [13, 8, 2]
# 3 <- median of [8, 2, 3]
# 3 <- median of [2, 3, 3]
# 3 <- median of [3, 3, 1]
#
# Recall that the median of an even-sized list is the average of the two middle
# numbers.
import bisect
# O(n * k)
def moving_median(a, k):
result = []
window = []
for idx in range(len(a)):
x = a[idx]
bisect.insort(window, x)
# populate the k elements for the window
if len(window) < k:
continue
if len(window) > k:
# evict the element that went out of the window
victim = a[idx - k]
victim_idx = bisect.bisect_left(window, victim)
del window[victim_idx] # O(k)
if len(window) == k:
if k % 2 == 1:
median = window[k // 2]
else:
median = (window[k // 2] + window[k // 2 - 1]) / 2
# add the median
result.append(median)
return result
assert moving_median([-1, 5, 13, 8, 2, 3, 3, 1], k=3) == [5, 8, 8, 3, 3, 3]
assert moving_median([1, 2, 3, 4, 5], k=3) == [2, 3, 4]
assert moving_median([1, 2, 3, 2, 5, 2, 6], k=3) == [2, 2, 3, 2, 5]
| true |
18b6747cbd7c12f8909f015cccb3e83dac083cdb | gubenkoved/daily-coding-problem | /python/dcp_337_shuffle_linked_list.py | 2,535 | 4.15625 | 4 | # This problem was asked by Apple.
# Given a linked list, uniformly shuffle the nodes. What if we want to prioritize space over time?
import itertools
from random import randint
class Node(object):
def __init__(self, val, next=None) -> None:
self.value = val
self.next = next
def insert(root: Node, index: int, value) -> Node:
node = Node(value)
cur_idx = 0
cur = root
prev = None
while True:
if cur_idx == index:
# insert BEFORE current
node.next = cur
if prev is not None:
prev.next = node
else: # head is changed
root = node
break # over!
if cur is None:
raise Exception(f'unable to insert item at {index} as we only found {cur_idx} items')
prev = cur
cur = cur.next
cur_idx += 1
return root
def shuffle(root: Node) -> Node:
# iterate over the source list and maintain a new linked list
# and every time we randomly choose the position of the new node
source_ptr: Node = root.next
target_head: Node = Node(root.value)
target_len = 1
while source_ptr is not None:
new_index = randint(0, target_len)
target_head = insert(target_head, new_index, source_ptr.value) # head can change
source_ptr = source_ptr.next
target_len += 1
return target_head
def generate(n: int) -> Node:
root = None
prev = None
for i in range(n):
# node = Node(randint(0, 1000))
node = Node(i)
if prev:
prev.next = node
else:
root = node
prev = node
prev = node
return root
def list_values(root: Node):
cur = root
values = []
while cur is not None:
values.append(cur.value)
cur = cur.next
return values
def print_list(root):
print(' -> '.join(map(str, list_values(root))))
def check_distributions(n, times):
freq_map = {} # map NUMBER -> positions list
for _ in range(times):
vals = list_values(shuffle(generate(n)))
for val_idx in range(len(vals)):
val = vals[val_idx]
if val not in freq_map:
freq_map[val] = []
freq_map[val].append(val_idx)
for source in sorted(freq_map.keys()):
groupped = itertools.groupby(sorted(freq_map[source]))
print([len(list(group[1])) for group in groupped])
print_list(shuffle(generate(30)))
check_distributions(10, 10000)
| true |
139d3b1da44b0e53666cfac9d23c106abc204a98 | gubenkoved/daily-coding-problem | /python/dcp_315_toeplitz_matrix.py | 1,643 | 4.3125 | 4 | # This problem was asked by Google.
# In linear algebra, a Toeplitz matrix is one in which the
# elements on any given diagonal from top left to bottom right are identical.
# Here is an example:
# 1 2 3 4 8
# 5 1 2 3 4
# 4 5 1 2 3
# 7 4 5 1 2
# Write a program to determine whether a given input is a Toeplitz matrix.
from typing import List
def is_toeplitz(matrix: List[List[int]]):
# there are two classes of diagonals -- ones that start from
# left-most items, and ones that start from top-most items
# go thought left most ones first
rows = len(matrix)
cols = len(matrix[0])
# left most ones
for row in range(rows):
el = matrix[row][0]
dist = 1
while row + dist < rows and dist < cols:
if matrix[row + dist][dist] != el:
return False
dist += 1
# top most ones (skip the first -- already covered)
for col in range(1, cols):
el = matrix[0][col]
dist = 1
while dist < rows and col + dist < cols:
if matrix[dist][col + dist] != el:
return False
dist += 1
return True
assert(is_toeplitz([[1, 2, 3, 4, 8],
[5, 1, 2, 3, 4],
[4, 5, 1, 2, 3],
[7, 4, 5, 1, 2]]))
assert(is_toeplitz([[2, 2, 3, 4, 8],
[5, 1, 2, 3, 4],
[4, 5, 1, 2, 3],
[7, 4, 5, 1, 2]]) is False)
assert(is_toeplitz([[1, 1],
[1, 1]]))
assert(is_toeplitz([[1, 2]]))
assert(is_toeplitz([[1]]))
assert(is_toeplitz([[1, 1],
[1, 2]]) is False) | true |
2acf399ff7534ef83aad7f5a4ad5aa9d771d04e0 | gokou00/python_programming_challenges | /coderbyte/Camel_Case.py | 487 | 4.15625 | 4 | def CamelCase(string):
finalStr = ""
toCap = False
if string[0].isalpha():
finalStr += string[0].lower()
for x in string[1:]:
if x.isalpha() == False:
toCap = True
continue
if toCap:
toCap = False
finalStr += x.upper()
continue
finalStr += x.lower()
#print(finalStr)
return finalStr
print(CamelCase("BOB loves-coding"))
| true |
2b5234a2677b8fdfdc5f87fb48b50d4ed1adf21e | chars32/edx_python | /Weeks/Week7/Dictionaries/Excercise6.py | 719 | 4.375 | 4 | #Write a function that takes a string as input argument and returns a dictionary of vowel counts i.e. the keys of this dictionary
#should be individual vowels and the values should be the total count of those vowels. You should ignore white spaces and they
#should not be counted as a character. Also note that a small letter vowel is equal to a capital letter vowel.
argument = "Murciealgooo ataca"
def dictionary_vowel_count(argument):
vowels = ['a','e','i','o','u']
dictionary = {}
copy_argument = argument.replace(" ","")
copy_argument = copy_argument.lower()
for x in vowels:
if x in copy_argument:
dictionary[x] = argument.count(x)
return dictionary
print(dictionary_vowel_count(argument))
| true |
dac5f35f618cf20a6197c1883ee608349e857fca | chars32/edx_python | /Weeks/Week7/Dictionaries/Excercise8.py | 768 | 4.125 | 4 | #Write a function that takes an integer as input argument and returns the integer using words.
#For example if the input is 4721 then the function should return the string "four seven two one".
#Note that there should be only one space between the words and they should be all lowercased in the string that you return.
number = 4722
def number_to_words(number):
word_numbers = ["zero","one", "two", "three", "four", "five", "six", "seve", "eight", "nine"]
number = str(number)
list_words = []
final_list = ""
count = 0
for x in number:
list_words.append(word_numbers[int(x)])
for y in list_words:
if count == len(list_words)-1:
final_list += y
else:
final_list += y + " "
count += 1
return final_list
print(number_to_words(number)) | true |
5ffc5e02425c991b076a58483c583ff0a7ed52f8 | chars32/edx_python | /Weeks/Week9/5. Nested.py | 516 | 4.21875 | 4 | #Write a function named nested_list_sum that receives a nested list of integers as parameter and calculates
#and returns the total sum of the integers in the list using recursion. Keep in mind that the inner elements
#may be integers or other nested lists themselves.
def nested_list_sum(list_nested):
sum = 0
for elements in list_nested:
if type(elements) != type([]):
sum += elements
else:
sum += nested_list_sum(elements)
return sum
print(nested_list_sum([1, -1, [2, -2], [3, -3, [4, -4], 10]])) | true |
969bf5055bb8e265bdc829f6464782244f6acd16 | chars32/edx_python | /Quizes/Quiz5/one_to_2D.py | 1,198 | 4.125 | 4 | #Write a function named one_to_2D which receives an input list and two integers r and c as parameters and returns a
#new two-dimensional list having r rows and c columns.
#Note that if the number of elements in the input list is larger than r*c then ignore the extra elements.
#If the number of elements in the input list is less than r*c then fill the two dimensional list with the keyword None.
def one_to_2D(some_list, r, c):
mult_rc = r*c
some_list_aux = []
list_aux = []
final_list = []
#------------------------------------
#first we compare is the leng of the list is greather or equal than the multiplication
#of r*c if yes we split the list to fix it.
if len(some_list) >= mult_rc:
some_list_aux = some_list[:mult_rc]
#if the len of the list is less thant the multiplication r*c then we fill the spaces
#with None string
else:
some_list_aux = some_list
for x in range(len(some_list_aux), mult_rc):
some_list_aux.append(None)
print(some_list_aux)
#-------------------------------------
for x in some_list_aux:
list_aux.append(x)
if len(list_aux) == c:
final_list.append(list_aux)
list_aux = []
return final_list
print(one_to_2D([1, 2, 3, 4], 3, 4)) | true |
4ab97b49e6ff1ea031aaf66ba7da59681ae158ff | chars32/edx_python | /Weeks/Week6/string_practices9.py | 549 | 4.25 | 4 | #Write a function that accepts a string of words separated by spaces consisting of alphabetic characters and returns a string such that each
#word in the input string is reversed while the order of the words in the input string is preserved.
def preserve_and_reverse(line):
line_split = line.split()
final = ""
count = 0
for x in line_split:
if line_split[count] != line_split[-1]:
for i in range(len(x)-1, -1, -1):
final += x[i]
final += " "
count += 1
else:
for i in range(len(x)-1, -1, -1):
final += x[i] | true |
9009a923d906e59077eafaa7004a088570231fbd | msberi/coding_practice | /rock_paper_scissor.py | 2,935 | 4.15625 | 4 | import random
class Computer(object):
def choose(self):
return random.randrange(1,3)
class Player(object):
def __init__(self, name):
self.name = name;
def choose(self):
print """Enter:
- 1 FOR ROCK;
- 2 FOR PAPER;
- 3 FOR SCISSOR."""
Choice = int(raw_input('>'))
while(Choice<1 or Choice>3):
print "Wrong!!! Enter 1 for rock, 2 for paper, or 3 for scissor."
Choice = int(raw_input('>'))
return Choice
def main():
print "Let's play Rock Paper Scissor"
print "You choose and I tell you if you win!"
print "Let's start: what is your name?"
name = raw_input(">>>")
again = 'y'
while(again == 'y'):
tPlayer = Player(name)
tComputer = Computer()
printWinner(tPlayer.choose() , tComputer.choose())
again = raw_input("Do you want to play again? y or n: ")
print "Bye Bye {name}!".format(name=tPlayer.name)
#actual choice from the number
def getChoice(choiceNumber):
choices = {1: "ROCK.", 2: "PAPER.", 3: "SCISSOR."}
return choices[choiceNumber]
# if ( choiceNumber == 1 ):
# return "ROCK."
# elif ( choiceNumber == 2 ):
# return "PAPER."
# elif ( choiceNumber == 3 ):
# return "SCISSOR."
#check and prints the winner
draw = "It's a draw."
winner = "You won :)"
loser = "You lose :("
def checkWinner(P, C):
if ( P == C ):
return draw
elif ( (P-C)%3 == 1 ):
return winner
elif ( (C-P)%3 == 1 ):
return loser
def printWinner(P,C):
print "You chose", getChoice(P)
print "Computer chose", getChoice(C)
print checkWinner(P, C)
# return checkWinner(P, C)
#start the game
main()
# -------------------------------------------------------------
# def printWinner(P,C):
# if ( P == C ): #Rock, Paper, or Scissor for both
# print "You chose", getChoice(P)
# print "Computer chose", getChoice(C)
# print "It is a draw."
# elif ( P == 1 and C == 2 ): #Player is Rock and Computer is Paper
# print "You chose", getChoice(P)
# print "Computer chose", getChoice(C)
# print "You lose :("
# elif ( P == 1 and C == 3 ): #Player is Rock and Computer is Scissor
# print "You chose", getChoice(P)
# print "Computer chose", getChoice(C)
# print "You won :)"
# elif ( P == 2 and C == 1 ): #Player is Paper and Computer is Rock
# print "You chose", getChoice(P)
# print "Computer chose", getChoice(C)
# print "You won :)"
# elif ( P == 2 and C == 3 ): #Player is Paper and Computer is Scissor
# print "You chose", getChoice(P)
# print "Computer chose", getChoice(C)
# print "You lose :("
# elif ( P == 3 and C == 1 ): #Player is Scissor and Computer is Rock
# print "You chose", getChoice(P)
# print "Computer chose", getChoice(C)
# print "You lose :("
# elif ( P == 3 and C == 2 ): #Player is Scissor and Computer is Paper
# print "You chose", getChoice(P)
# print "Computer chose", getChoice(C)
# print "You won :)"
| true |
52f49102910b46f6f9371c485e8aa484a6df67cc | nochemargarita/coding-challenges | /recursion.py | 1,075 | 4.125 | 4 | def count_recursively(lst):
"""Return number of items in a list, using recursion."""
if lst:
return 1 + count_recursively(lst[1:])
return 0
# print count_recursively([])
# print count_recursively([5, 6, 7])
def print_recursively(lst):
"""Print items in the list, using recursion."""
if lst:
print lst[0]
return print_recursively(lst[1:])
# print_recursively([6, 2, 3])
def recursive_index(word, lst):
"""Given list (haystack), return index (0-based) of needle in the list.
Return None if needle is not in haystack.
Do this with recursion. You MAY NOT USE A `for` OR `while` LOOP.
"""
index = 0
def inner(word, lst, index):
if index < len(lst):
if lst[index] == word:
return index
index += 1
return inner(word, lst, index)
return inner(word, lst, index)
lst = ["hey", "there", "you"]
# print recursive_index('hey', lst)
# print recursive_index('there', lst)
# print recursive_index('you', lst)
# print recursive_index('how', [])
| true |
b2a49c31909ab49962d507e95188e28bbd089ef0 | nochemargarita/coding-challenges | /Hackerrank/30-Day-Challenge-Hackerrank/day16_exceptions.py | 518 | 4.40625 | 4 | """Task
Read a string, S, and print its integer value; if S cannot be converted to an
integer, print Bad String.
Note:
You must use the String-to-Integer and exception handling constructs built into
your submission language. If you attempt to use loops/conditional statements,
you will get a 0 score.
Input Format
A single string, S."""
S = raw_input().strip()
try:
print int(S)
except:
print 'Bad String'
# Sample Input 0
# 3
# Sample Output 0
# 3
# Sample Input 1
# za
# Sample Output 1
# Bad String | true |
60f77bc714f7bf3acdb1396306396b564eca8daf | nochemargarita/coding-challenges | /Technical-Challenge/strobogrammatic.py | 2,644 | 4.5625 | 5 | '''
-------------------
Long-form question
-------------------
A "Strobogrammatic Number" is a number that looks the same
when rotated 180 degrees (upside down) on an LED screen.
E.g.
11 -> 11, Strobogrammatic
252 -> 252, Strobogrammatic
37 -> LE, Not!
Write a function to determine whether a number is strobogrammatic.
#### #### ####
# # #
#### #### ####
# # #
#### #### ####
'''
# 0, 1, 2, 5, 8 True
# 3, 4, 6, 7, 9 False
# First test: are all the digits in strobogrammatic_numbers?
# Second test: does each digit match it's opposite?
# FIRST SOLUTION:
# def is_strobogrammatic(number):
# # TODO: Implement me
# result = False
# strobogrammatic_numbers = {0, 1, 2, 5, 8}
# numbers = str(number)
# # First test: are all the digits in strobogrammatic_numbers?
# # Second test: does each digit match it's opposite?
# for num in numbers:
# if int(num) in strobogrammatic_numbers:
# result = True
# # print result
# # return result
# if (result == True) and (numbers == numbers[::-1]):
# return True
# else:
# return False
def is_strobogrammatic(number):
# TODO: Implement me
strobogrammatic = {'0': '0',
'1': '1',
'2': '2',
'5': '5',
'8': '8',
'6': '9',
'9': '6'} # O(1) space since I know that the number of items will be constant or will remain the same, no adding or deleting.
to_str = str(number) # O(1) space
length = len(to_str) # O(1) space
for indx in xrange((length + 1) / 2): # O(n) time
last_to_mid = to_str[length-1-indx] # O(1) space
if last_to_mid not in strobogrammatic or \
to_str[indx] != strobogrammatic[last_to_mid]: # O(1) time
return False
return True
# O(n) time complexity
# O(1) space complexity
# '180/81' --> 3
# 1) 1 and 1 == 1 --> True
# 2) 8 and 8 == 8 -- > True
# 3) 0 and 0 == 0 --> True
def test_strobo():
test_cases = [
(0, True),
(2, True),
(3, False),
(6, False),
(10, False),
(13, False),
(11, True),
(16, False),
(69, True), # 96 -> tanslate -> 69
(101, True),
(131, False),
(161, False),
(18081, True),
]
for test, result in test_cases:
my_result = is_strobogrammatic(test)
print(test, result, my_result)
assert my_result == result, (
'Error for value: ' + str(test))
test_strobo() | true |
077122e2903858f716b3d384730d9450405d3d0e | nochemargarita/coding-challenges | /Hackerrank/30-Day-Challenge-Hackerrank/day20_sorting.py | 1,822 | 4.21875 | 4 | """Task:
Given an array, a, of size n distinct elements, sort the array in ascending
order using the Bubble Sort algorithm above. Once sorted, print the following 3
lines:
Array is sorted in numSwaps swaps.
where numSwaps is the number of swaps that took place.
First Element: firstElement
where firstElement is the first element in the sorted array.
Last Element: lastElement
where lastElement is the last element in the sorted array.
Hint: To complete this challenge, you will need to add a variable that keeps a
running tally of all swaps that occur during execution.
Input Format
The first line contains an integer, n, denoting the number of elements in array a.
The second line contains n space-separated integers describing the respective
values of a[0], a[1]....a[n-1].
Constraints
2 <= n <= 600
1 <= a[i] <= 2 * 10^6, where 0 <= i < n.
Output Format
Print the following three lines of output:
Array is sorted in numSwaps swaps.
where numSwaps is the number of swaps that took place.
First Element: firstElement
where firstElement is the first element in the sorted array.
Last Element: lastElement
where lastElement is the last element in the sorted array.
"""
#!/bin/python
import sys
n = int(raw_input().strip())
a = map(int, raw_input().strip().split(' '))
# Write Your Code Here
swap_count = 0
for i in xrange(n):
for j in xrange(n-1):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
swap_count += 1
print 'Array is sorted in {} swaps.'.format(swap_count)
print 'First Element: {}'.format(a[0])
print 'Last Element: {}'.format(a[-1])
# Sample Input 0
# 3
# 1 2 3
# Sample Output 0
# Array is sorted in 0 swaps.
# First Element: 1
# Last Element: 3
# Sample Input 1
# 3
# 3 2 1
# Sample Output 1
# Array is sorted in 3 swaps.
# First Element: 1
# Last Element: 3
| true |
7416ca6c9c0f44ba0b9712c8a6b28de0ef307b04 | dmitry-izmerov/Udacity-Intro-to-computer-science | /Lesson04/Converting Seconds.py | 1,662 | 4.3125 | 4 | __author__ = 'demi'
# Write a procedure, convert_seconds, which takes as input a non-negative
# number of seconds and returns a string of the form
# '<integer> hours, <integer> minutes, <number> seconds' but
# where if <integer> is 1 for the number of hours or minutes,
# then it should be hour/minute. Further, <number> may be an integer
# or decimal, and if it is 1, then it should be followed by second.
# You might need to use int() to turn a decimal into a float depending
# on how you code this. int(3.0) gives 3
#
# Note that English uses the plural when talking about 0 items, so
# it should be "0 minutes".
#
def convert_seconds(seconds):
res = ''
mins = 0
hours = 0
if(seconds > 0):
mins = int(seconds/60)
seconds = seconds - (mins*60)
hours = int(mins/60)
mins = mins - (hours*60)
if hours == 1:
res += '%d hour' % hours
else:
res += '%d hours' % hours
if mins == 1:
res += ', '
res += '%d minute' % mins
else:
res += ', '
res += '%d minutes' % mins
if seconds == 1:
res += ', '
if isinstance(seconds, int):
res += '%d second' % seconds
else:
res += '%.1f second' % seconds
else:
res += ', '
if isinstance(seconds, int):
res += '%d seconds' % seconds
else:
res += '%.1f seconds' % seconds
return res
print(convert_seconds(3600))
print(convert_seconds(3661))
#>>> 1 hour, 1 minute, 1 second
print(convert_seconds(7325))
#>>> 2 hours, 2 minutes, 5 seconds
print(convert_seconds(7261.7))
#>>> 2 hours, 1 minute, 1.7 seconds | true |
922bfd0a81850b411ffcb0ebe8397add059b9924 | maolasirzul/COMP1819ADS | /Lab_01/02_while loop with checking condition.py | 549 | 4.34375 | 4 | def staircase(data):
current = 0
if data > 0 and data <= 20:
while current <= data: # While the 'current' counter variable is less or equal to the input value 'data' the loop will continue to execute
print('#' * current) # This line will print the hash symbol by the current value of the 'current' counter
current = current + 1 # This increment will ensure on each line a different number of hash symbols will be printed and will also casue the loop to end when it is equal to 'data'
staircase(10) | true |
44ccabdc35767928022e0400ffc6799bf7aee320 | samwilliamsjebaraj/networkautomation | /PythonCode/function_operations.py | 707 | 4.15625 | 4 | """
File:function_operations.py
Mapping, Filtering & Reducing
map(),filter(),reduce()
"""
def check_even(x):
return x%2==0
def check_odd(x):
return x%2!=0
def add_numbers(x1,x2):
"""
add's the numbers and returns the value
"""
return x1+x2
def product(x1,x2):
'''
returns the product of the args(x1,x2)
'''
return x1*x2
#checking the map() function
my_number_list=range(1,101)
print map(check_even,my_number_list)
print map(check_odd,my_number_list)
#checking the filter() function
print filter(check_even,my_number_list)
print filter(check_odd,my_number_list)
#check reduce() function
print reduce(add_numbers,my_number_list)
print reduce(product,my_number_list)
| true |
5e561e78ee3b8adfb2e2002bfb9db0e851f467cb | kssim/efp | /making_decisions/python/multistate_sales_tax_calculator.py | 2,107 | 4.125 | 4 | # Pratice 20. Multistate sales tax calculator
# Output:
# What is the order amount? 10
# What state do you live in? Wisconsin
# What county do you live in? Eau Claire
# The state tax is $0.55.
# The county tax is $0.05.
# The total tax is $0.60.
# The total is $10.60.
# Or
# What is the order amount? 10
# What state do you live in? Illinois
# The total tax is $0.80.
# The total is $10.80.
# Standard:
# State
# Illinois : 0.08
# County (If state is Wisconsin)
# - Eau Claire : 0.005
# - Dunn : 0.004
# Constraint:
# - Ensure that all money is rounded up to the nearest cent.
# - Use a single output statement at the end of the program to display the program results.
#!/usr/bin/env python
import sys
def input_process(in_question):
return input(in_question) if sys.version_info >= (3,0) else raw_input(in_question)
if __name__ == '__main__':
try:
amount = int(input_process('What is the order amount? '))
state = str(input_process('What state do you live in? '))
exists_county = False
if state.upper() == 'WISCONSIN':
county = str(input_process('What county do you live in? '))
exists_county = True
except:
print ('You must input only numbers.')
else:
county_tax = 0
if state.upper() == 'WISCONSIN':
if county.replace(' ','').upper() == 'EAUCLAIRE':
county_tax = amount * 0.005
elif county.replace(' ','').upper() == 'DUNN':
county_tax = amount * 0.004
else:
county_tax = 0
tax = amount * 0.055
elif state.upper() == 'ILLINOIS':
tax = amount * 0.08
else:
tax = 0
print_str = 'The state tax is $%s\n' % round(tax, 2)
if exists_county == True:
print_str += 'The county tax is $%s\n' % round(county_tax, 2)
print_str += 'The total tax is $%s\n' % round((tax + county_tax), 2)
print_str += 'The total is $%s' % round((amount + tax + county_tax), 2)
print (print_str)
| true |
aad75d82beb1ad4241514e8b5acf4c776912d531 | kssim/efp | /working_with_files/python/parsing_a_data_file.py | 2,045 | 4.15625 | 4 | # Pratice 41. Parsing a Data File
# Input:
# File name : parsing_a_data_file_input
# Output:
# Last First Salary
# ------------------------
# Ling Mai 55900
# Johnson Jim 56500
# Jones Aaron 46000
# Jones Chris 34500
# Swift Geoffrey 14200
# Xiong Fong 65000
# Zarnecki Sabrina 51500
# Constraint:
# - Write your own code to parse the data.
# Don'y use a CSV parser.
# - Use spaces to align the columns.
# - Make each column one space longer than the longest value in the column.
#!/usr/bin/env python
import sys
FILE_NAME = 'parsing_a_data_file_input'
LAST_NAME_IDX = 0
FIRST_NAME_IDX = 1
SALARY_IDX = 2
def read_file():
data_list = []
try:
with open(FILE_NAME, 'r') as f:
for line in f.readlines():
data_list.append(line.strip().split(','))
except:
print ('File does not exist.')
exit()
return data_list
def get_data_length(in_data_list):
last_name_len = 0
first_name_len = 0
salary_len = 0
for data in in_data_list:
last_name_len = last_name_len if last_name_len > len(data[LAST_NAME_IDX]) else len(data[LAST_NAME_IDX])
first_name_len = first_name_len if first_name_len > len(data[FIRST_NAME_IDX]) else len(data[FIRST_NAME_IDX])
salary_len = salary_len if salary_len > len(data[SALARY_IDX]) else len(data[SALARY_IDX])
return (last_name_len + 1, first_name_len + 1, salary_len + 1)
def print_names(in_data_list):
(last_name_len, first_name_len, salary_len) = get_data_length(in_data_list)
print('{:' '<{}}{:' '<{}}{:' '<{}}'.format('Last', last_name_len, 'First', first_name_len, 'Salary', salary_len))
print ('-------------------------')
for data in in_data_list:
print('{:' '<{}}{:' '<{}}{:' '<{}}'.format(data[LAST_NAME_IDX], last_name_len, \
data[FIRST_NAME_IDX], first_name_len, data[SALARY_IDX], salary_len))
if __name__ == '__main__':
data_list = read_file()
print_names(data_list)
| true |
db430d632e618f25d79d588df2538cd0e72fe1dc | kssim/efp | /making_decisions/python/legal_driving_age.py | 949 | 4.25 | 4 | # Pratice 16. Legal driving age
# Output:
# What is your age? 13
# You are not old enough to legally drive.
# Or
# What is your age? 25
# You are old enough to legally drive.
# Standard:
# 20 years old.
# Constraint:
# - Use a single output statement.
# - Use a ternary operator to write this program.
# If your language doesn't support a ternary operator,
# use a regular 'if/else' statement, and still use a single output
# statement to display the message.
#!/usr/bin/env python
import sys
def input_process(in_question):
return input(in_question) if sys.version_info >= (3,0) else raw_input(in_question)
if __name__ == '__main__':
try:
age = int(input_process('What is your age? '))
except:
print ('You must input only numbers.')
else:
print_str = 'You are old enough to legally drive' if age >= 20 else 'You are not old enough to legally drive'
print (print_str)
| true |
0fa7b929eaadf462dbf8d0d106f4e0e91af01e30 | Sofista23/Aula1_Python | /Aulas/Exercícios-Mundo1/Aula010/Ex033.py | 879 | 4.1875 | 4 | n1=int(input("Digite um número:"))
n2=int(input("Digite outro um número:"))
n3=int(input("Digite mais um número:"))
if n1>n2 and n1>n3 and n2>n3:
print("{0} é o maior número.".format(n1))
print("{0} é o menor número.".format(n3))
if n1>n2 and n1>n3 and n2<n3:
print("{0} é o maior número.".format(n1))
print("{0} é o menor número.".format(n2))
if n2>n1 and n2>n3 and n1>n3:
print("{0} é o maior número.".format(n2))
print("{0} é o menor número.".format(n3))
if n2>n1 and n2>n3 and n1<n3:
print("{0} é o maior número.".format(n2))
print("{0} é o menor número.".format(n1))
if n3>n1 and n3>n2 and n1>n2:
print("{0} é o maior número.".format(n3))
print("{0} é o menor número.".format(n2))
if n3>n1 and n3>n2 and n1<n2:
print("{0} é o maior número.".format(n3))
print("{0} é o menor número.".format(n1)) | false |
4c1939145029d1d52e5fefc5a13f26fd7b6640a3 | Coders222/Shared | /Comp Sci Gr 10/Selection/Bonus Question.py | 646 | 4.40625 | 4 | # this program takes in the year of input and tells you when is easter
year = input("What is the year? ")
year = int(year[-2:]) # takes last 2 digits of the year and parses into integer
x = year // 19
y = year // 4
r = (19 * year - x) % 30
s = (6 * year - y - r) % 7
# formulas ^^^^
# conditions to check when is Easter
if r == 28 and r == s + 6:
print("Easter is on the 18th of April")
elif year == 57:
print("Easter is on the 21st of April")
elif r + s <= 9:
print("Easter is on day " + str(r + s + 22), "of March")
else:
print("Easter is on day " + str(r + s - 9), "of April")
| false |
b51bc6f916c8c16aeb2aa0a780aee969769fd087 | Dave0512/py_oop | /dir_Database/database.py | 2,913 | 4.125 | 4 |
## VORLAGE DATENBANK KLASSE
import pyodbc
class Database:
"""
Class to connect, and interact with several types of relational dbms
like ms sql server, mySQL, PostgreSQL, SQLite
Documentation:
Database Handler Class
1) Open Database (Using "with" to easy handle db_connection)
2) Set a cursor
3) Commit data
"Each SQL command is in a transaction and the transaction
must be committed to write the transaction
to the SQL Server so that it can be read by other SQL commands.
Under MS SQL Server Management Studio the default is to allow
auto-commit which means each SQL command immediately
works and you cannot rollback."
Example:
with Database("...") as db:
# do stuff
"""
def __init__(self,driver, server, database,tr_conn):
"""
Method recieves compulsory parameter
to create a connection to a database.
MS SQL Server, for instance:
"DRIVER={SQL Server Native Client 11.0};"
"SERVER=192.168.16.124;"
"DATABASE=Vorlauf_DB;"
"Trusted_Connection=yes;
"""
self._db_conn = pyodbc.connect(r"DRIVER={0};"
"SERVER={1};"
"DATABASE={2};"
"Trusted_Connection={3};".format(driver, server, database,tr_conn))
self._cursor = self._db_conn.cursor()
def __enter__(self):
"""
Magic method to let the class use the with statement.
"""
return self
def __exit__(self,exc_type,exc_val,exc_tb):
"""
Magic method to let the class use the with statement
"""
self.close()
@property
def connection(self):
"""
built-in function property
"""
return self._db_conn
@property
def cursor(self):
"""
built-in function property
"""
return self._cursor
def commit(self):
"""
Commit SQL command as a transaction.
"""
self.connection.commit()
def close(self,commit=True):
"""
Close the connection to db
"""
if commit:
self.commit()
self._db_conn.close()
def execute(self,sql): # evtl params=None
"""
Handle sql querys
"""
self._cursor.execute(sql) # evtl params or ()
def fetchall(self):
"""
Retrieve all rows
"""
return self._cursor.fetchall()
def fetchone(self):
"""
Retrieve one row
"""
return self._cursor.fetchone()
def query(self,sql): # evtl params=None
"""
Handle sql querys
"""
self._cursor.execute(sql) # evtl params or ()
return self.fetchall()
| true |
5bc79659163519e172cfed17f106ae1e9af8fa9b | Shashank001122/Linked-List-2 | /ReorderList.py | 1,448 | 4.1875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
mid=self.calculateMid(head)
newpointer=mid.next
mid.next=None
newlist=self.reverse(newpointer)
one=head
two=newlist
three=head.next
while(three!=None):
one.next=two
two.next=three
two=two.next
one=three
three=three.next
return head
def calculateMid(self,head):
fast=head
slow=head
while(fast!=None and fast.next!=None):
slow=slow.next
fast=fast.next.next
return slow
def reverse(self,newpointer):
prev=None
curr=newpointer
fast=curr.next
while(fast!=None):
curr.next=prev
prev=curr
curr=fast
fast=fast.next
curr.next=prev
return curr
#Time complexity is O(n)
sample 1->2->3->4-->5
#i am confused for space complexity, I am making a new Linkedlist for this so 1->-3->Null is pointed by head and
and there is one new newlist which points to 4->5->null, then I am merging them, so will this newlist will make the solution O(n)?
| true |
46d985ce758d64b9743b1baab9eac5c27b3b95ea | jdaeira/Udemy-Python | /Data-Types/strings.py | 630 | 4.15625 | 4 |
x = "Hello World!"
print(x.lower())
print(x.upper())
print(x.split())
my_name = "John"
my_age = 50
print("Hello " + my_name)
text = "Hello {}, you are {} years old!".format(my_name, my_age)
print(text)
print("The {2} {1} {0}!".format("fox", "brown", "quick"))
# You can choose which index you want to use
print("The {q} {b} {f}!".format(f = "fox", b = "brown", q = "quick"))
result = 100/777
print("The result is {r:1.3f}".format(r = result))
# r is value:width.precision(how many places) f
print(f"The result is {result:1.3f}")
# f-strings()formatted string literals
print(f"Hello {my_name}, you are {my_age} years old!") | true |
7ea90ab04f978ae19d4294fa14dcefa94cc7c801 | jdaeira/Udemy-Python | /Python-Statements/comprehensions.py | 654 | 4.1875 | 4 |
mystring = "hello"
mylist = []
for letter in mystring:
mylist.append(letter)
print(mylist)
mylist = [letter for letter in mystring] # this creates a list of the letters in mystring (list comprehensions)
print(mylist)
mylist = [char for char in "word"]
print(mylist)
mylist = [num for num in range(0,11)]
print(mylist)
mylist = [num**2 for num in range(0,11)]
print(mylist)
mylist = [num for num in range(0,11) if num%2 == 0]
print(mylist)
celcius = [0,10,20,34.5]
fahrenheit = [( (9/5)*temp + 32 ) for temp in celcius]
print(fahrenheit)
mylist = []
for x in [2,4,6]:
for y in [1,10,1000]:
mylist.append(x*y)
print(mylist) | false |
e082b4185da9587d3d7e5c9f1a078241708b8b72 | jdaeira/Udemy-Python | /Python-Statements/ifelse.py | 336 | 4.1875 | 4 |
number = 11
if number > 12:
print("Your number is greater than 12")
else:
print("Your number is less than 12")
loc = "Bank"
if loc == "Auto Shop":
print("I love Cars!")
elif loc == "Bank":
print("I'm at the Bank!")
elif loc == "Store":
print("Welcome to the Store!")
else:
print("I don't know where I am!")
| true |
00b65c069fef5460d4fa9364383d397bcfd045af | marciorela/python-cursos | /luizotavio/aula020/aula032 - desafios.py | 1,174 | 4.28125 | 4 | """
1 - Crie uma função que exibe uma saudação com os parâmetros saudacao e nome.
"""
def saudacao(saud, nome):
print(f"{saud}, {nome}")
saudacao("Olá", "Joaquim")
"""
2 - Crie uma função que recebe 3 números como parâmetros e exiba a soma entre
eles.
"""
def soma(n1, n2, n3):
print(n1 + n2 + n3)
soma(10, 20, 30)
"""
3 - Crie uma função que receba 2 números. O primeiro é um valor e o segundo um
percentual (ex. 10%). Retorne (return) o valor do primeiro número somado
do aumento do percentual do mesmo.
"""
def percent(valor, porc):
return valor * ((porc/100) + 1)
print(percent(100, 20))
print(percent(50, 10))
"""
4 - Fizz Buzz - Se o parâmetro da função for divisível por 3, retorne fizz,
se o parâmetro da função for divisível por 5, retorne buzz. Se o parâmetro da
função for divisível por 5 e por 3, retorne FizzBuzz, caso contrário, retorne o
número enviado.
"""
def fizzbuzz(n1):
retorno = ""
if n1 % 3 == 0:
retorno += "Fizz"
if n1 % 5 == 0:
retorno += "Buzz"
return n1 if retorno == "" else retorno
print(fizzbuzz(9))
print(fizzbuzz(5))
print(fizzbuzz(15))
print(fizzbuzz(14))
| false |
98e168e73f9559d81e17c23bfc0b2ef75194d7d6 | fatemebaghi/into_python | /ex2/prog2.py | 592 | 4.28125 | 4 | def prog2(a,b):
""" (int,int)-> list
You can use this function to find even numbers between two numbers.
In this function, it does not matter which a or b is bigger .
>>> prog1(12,26)
[14, 16, 18, 20, 22, 24]
>>> prog1(26,12)
[14, 16, 18, 20, 22, 24]
"""
if b>a :
num=[]
for m in range(a,b):
if (m%2)==0 and m!=a and m!=b :
num.append(m)
print(num)
if a>b :
print(prog2(b,a))
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
print(prog2(a,b))
| true |
746094a4a00af0117ebbbf02761fb10409a58a0b | Edwinl777/contest-questions | /ProjectEuler/Project Euler #1 Multiples of 3 and 5.py | 271 | 4.15625 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
s = 0
for i in range(3, 1000):
if not i % 3 or not i % 5: s += i
print(s)
| true |
8755fdee63904f0de6c757f8153fbee065a57ee7 | Temp-Nerd/All-d-Porgrams-in-d-wurld | /palindrome.py | 247 | 4.125 | 4 | def reverse(a):
rev=''
for i in range (len(a)-1,-1,-1) :
rev+=a[i]
return(rev)
a=(input('enter :'))
b=reverse(a)
if b==a :
fill=''
else :
fill='not '
print(f'The string is {fill}a palindrome')
| true |
31e5750e79937eefd9f9b803dcb5843546380866 | bishop527/MIT_OCW-6.00 | /ProblemSets/PS1/PS1b.py | 1,414 | 4.28125 | 4 | # MIT OpenCourseWare Introduction to 6.00
# Problem Set 1
# 10 March 2014
#Problem 2
min_monthly_payment = 0.0
cur_balance = 0.0
month = 0
total_interest = 0.0
total_paid = 0.0
success = False
start_balance = float(raw_input("What is the starting balance? "))
cur_balance = start_balance
annual_interest_rate = float(raw_input("What is the annual interest rate? "))
monthly_interest_rate = annual_interest_rate/12.0
while success == False:
min_monthly_payment += 10.0
month = 0
cur_balance = start_balance
while month < 12 and success == False:
month += 1
interest_paid = round(monthly_interest_rate / 12 * cur_balance, 2)
total_interest += interest_paid
principle_paid = round(min_monthly_payment - interest_paid, 2)
cur_balance = cur_balance*(1+monthly_interest_rate) - min_monthly_payment
print "Month ", month
print " Min Monthly Payment = %.2f" % min_monthly_payment
# print " Interest Paid = ", interest_paid
print " Principle Paid = %.2f" % principle_paid
print " Remaining Balance = %.2f" % cur_balance
if cur_balance <= 0:
success = True
if cur_balance <= 0:
success = True
print "RESULT"
print "Monthly payment to pay off debt in 1 year: ", min_monthly_payment
print "Number of months needed: ", month
print "Remaining balance: %.2f" % cur_balance
| true |
19bf2f59ee20094e7b2fe0ddfb570f810450c2e6 | itzketan/7th-day | /7th day.py | 1,712 | 4.21875 | 4 | """
1. Create a function getting two integer inputs from user. & print the following:
Addition of two numbers is +value
Subtraction of two numbers is +value
Division of two numbers is +value
Multiplication of two numbers is +value
"""
def add(a, b) :
return a + b
def sub(a, b) :
return a - b
def mul(a, b) :
return a * b
def div(a, b) :
return a / b
print("Enter Two Integer Numbers : ")
nOne = int(input())
nTwo = int(input())
print("\n""Enter the Operator (+,-,*,/):")
ch = input()
if ch == '+':
print("\n" "Addition of two numbers is : " + str(nOne) + " + " + str(nTwo) + " = " + str(add(nOne, nTwo)))
elif ch == '-':
print("\n" "Subtraction of two numbers is : " + str(nOne) + " - " + str(nTwo) + " = " + str(sub(nOne, nTwo)))
elif ch == '*':
print("\n" "Multiplication of two numbers is : " + str(nOne) + " * " + str(nTwo) + " = " + str(mul(nOne, nTwo)))
elif ch == '/':
print("\n" "Division of two numbers is : " + str(nOne) + " / " + str(nTwo)+ " = " + str(div(nOne, nTwo)))
else:
print("\nInvalid Operator!")
print("\n -------------------------------------------- 2 -------------------------------------------------------------")
"""
Create a function covid( ) & it should accept patient name, and body temperature,
by default the body temperature should be 98 degree
"""
def covid(n,t):
return (n,t)
def d(T = 98):
return d(T = 98)
n = str(input("Enter Patient Name : "))
t = str(input("Enter Patient Body Temperature In Degree : "))
print("Patient Name : " + n)
if t != 98 :
print("Patient Body Temperature : " + t + " Degree")
else:
print("Default Temperature : " + d(T = 98) + " Degree")
| true |
91e029f13f5797575827b33620826c9bb2cd52fa | mwflickner/code-library | /merge-sort/python/merge_sort.py | 1,040 | 4.28125 | 4 | def merge_sort(the_list):
if len(the_list) < 2:
return the_list
left_side, right_side = split_list(the_list)
left_side = merge_sort(left_side)
right_side = merge_sort(right_side)
return merge(left_side, right_side)
def merge(left, right):
left_index = right_index = 0
sorted_list = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
sorted_list.append(left[left_index])
left_index += 1
else:
sorted_list.append(right[right_index])
right_index += 1
while left_index < len(left):
sorted_list.append(left[left_index])
left_index += 1
while right_index < len(right):
sorted_list.append(right[right_index])
right_index += 1
return sorted_list
def split_list(the_list):
middle = len(the_list) // 2
return the_list[:middle], the_list[middle:]
a_list = [5, 2, 4, 3, 8]
print(a_list)
sorted_list = merge_sort(a_list)
print(sorted_list)
| true |
4f1b61e589e878bdfe4088fc50e7202ba601c325 | jinkyukim-me/Learn-Python-Programming | /exercises/ex44d.py | 1,441 | 4.1875 | 4 | class Parent(object):
"""A simple example class""" # 클래스 정의 시작부분에 """...""" 도큐먼트 스트링
def __init__(self): # 컨스트럭터 (생성자)
self.name = "Kim"
def override(self): # override() 메소드
print("PARENT override()")
def implicit(self): # implicit() 메소드
print("PARENT implicit()")
def altered(self): # altered() 메소드
print("PARENT altered()")
class Child(Parent):
def __init__(self): # 자식클래스 생성자
super().__init__() # 부모클래스 생성자
self.blood = "O" # blood 추가
def override(self):
print("CHILD override()") # override() 메소드
def altered(self): # altered() 메소드
print("CHILD, BEFORE PARENT altered()")
super(Child, self).altered() # super(자식클래스, self)로 부모클래스의 메서드 호출
print("CHILD, AFTER PARENT altered()")
dad = Parent() # 클래스의 인스턴스 생성
son = Child() # 클래스의 인스턴스 생성
dad.implicit()
son.implicit()
dad.override()
son.override()
dad.altered()
son.altered()
| false |
559b5681b0c301958f4e6ecc2c0618cc5a1171c3 | jinkyukim-me/Learn-Python-Programming | /exercises/ex6.py | 861 | 4.28125 | 4 | # Exercise 6. Strings and Text
types_of_people = 10
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
print(f"I said: {x}")
print(f"I also said: '{y}'")
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
joke_evaluation1 = "Isn't that {} so {}?! {}"
# a variety of expressions
print(joke_evaluation.format(hilarious))
print("Isn't that joke so funny?! {}".format(hilarious))
print("Isn't that joke so funny?! {}".format("False"))
print("Isn't that {} so {}?! {}".format('joke', 'funny', 'False'))
print("Isn't that {2} so {0}?! {1}".format('funny', 'False', 'joke'))
i = 'joke'
j = 'funny'
z = 'True'
print(joke_evaluation1.format(i, j, z))
w = "This is the left side of..."
e = "a string with a right side."
print(w + e)
| false |
cc324b58ba872cd52137c1898bb9fef8b96e8dd8 | uolter/SortingAndSearch | /python/bubblesort.py | 1,458 | 4.34375 | 4 | #!/usr/bin/env
# -*- coding: utf-8 -*-
import unittest
def bubble_sort( seq ):
"""
Time Complexity of Solution:
Best O(n^2); Average O(n^2); Worst O(n^2).
Approach:
Bubblesort is an elementary sorting algorithm. The idea is to
imagine bubbling the smallest elements of a (vertical) array to the
top; then bubble the next smallest; then so on until the entire
array is sorted. Bubble sort is worse than both insertion sort and
selection sort. It moves elements as many times as insertion sort
(bad) and it takes as long as selection sort (bad). On the positive
side, bubble sort is easy to understand. Also there are highly
improved variants of bubble sort.
"""
for i in range(len(seq)):
for k in range(len(seq) - 1, i, -1 ):
if ( seq[k] < seq[k - 1] ):
swap( seq, k, k - 1 )
return seq
def swap( seq, x, y ):
tmp = seq[x]
seq[x] = seq[y]
seq[y] = tmp
class TestBubbleSort(unittest.TestCase):
def test_sort_empty(self):
self.assertEqual([], bubble_sort([]))
def test_sort_one(self):
self.assertEqual([1], bubble_sort([1]))
def test_sort_numbers(self):
self.assertEqual([1,2,3,4], bubble_sort([4, 3,2,1]))
def test_sort_string(self):
self.assertEqual(['e', 's', 't', 't'], bubble_sort(list("test")))
if __name__ == '__main__':
unittest.main()
| true |
6c11c446f1ad859cf4c1c4e531633ced03bdc6a1 | cort-robinson/holbertonschool-web_back_end | /0x04-pagination/0-simple_helper_function.py | 591 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Write a function named index_range that takes two integer arguments: page and
page_size.
The function should return a tuple of size two containing a start index and an
end index corresponding to the range of indexes to return in a list for those
particular pagination parameters.
Page numbers are 1-indexed, i.e. the first page is page 1.
"""
def index_range(page: int, page_size: int) -> tuple:
"""Return a tuple of size two containing a start index and an end index"""
start = (page - 1) * page_size
end = start + page_size
return start, end
| true |
68eb5ec8fccafd6c2bd4abb94818b3a3a4ba38af | dastagg/bitesofpy | /68/clean.py | 298 | 4.34375 | 4 | import string
def remove_punctuation(input_string):
"""Return a str with punctuation chars stripped out"""
new_string = ""
for letter in input_string:
if letter in string.punctuation:
continue
else:
new_string += letter
return new_string
| true |
36820a394332863c004e35683353c86d581fab55 | faizalazman/UTArlingtonX--CSE1309x-Introduction-to-Programming-Using-Python | /Final Exam/Final Exam Part 3 (N letter dictionary).py | 2,657 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 1 13:33:45 2018
@author: Parmenides
"""
# =============================================================================
# Final Exam, Part 3 (N letter dictionary)
# 20.0/20.0 points (graded)
# Write a function named n_letter_dictionary that receives a string (words separated by spaces) as parameter and returns a dictionary whose keys are numbers and whose values are lists that contain unique words that have the number of letters equal to the keys.
#
# For example, when your function is called as:
#
# n_letter_dictionary("The way you see people is the way you treat them and the Way you treat them is what they become")
# Then, your function should return a dictionary such as
# {2: ['is'], 3: ['and', 'see', 'the', 'way', 'you'], 4: ['them', 'they', 'what'], 5: ['treat'], 6: ['become', 'people']}
# Notes:
# Each list of words with the same number of letters should be sorted in ascending order
# The words in a list should be unique. For example, even though the word "them" is repeated twice in the above sentence, it is only considered once in the list of four letter words.
# Capitalization does not matter, this means that all the words should be converted to lower case. For example the words "The" and "the" appear in the sentence but they are both considered as lower case "the".
# =============================================================================
# Type your code here
def n_letter_dictionary(my_string):
strings = my_string.lower().split()
count_string = []
for string in strings:
length = len(string)
count_string.append(length)
strings = sorted(list(set(strings)))
count_string = list(set(count_string))
l1 = []
l2 = []
l3 = []
l4 = []
l5 = []
l6 = []
l7 = []
l8 = []
l9 = []
l10 = []
for word in strings:
if len(word) == 1:
l1.append(word)
elif len(word) == 2:
l2.append(word)
elif len(word) == 3:
l3.append(word)
elif len(word) == 4:
l4.append(word)
elif len(word) == 5:
l5.append(word)
elif len(word) == 6:
l6.append(word)
elif len(word) == 7:
l7.append(word)
elif len(word) == 8:
l8.append(word)
elif len(word) == 9:
l9.append(word)
else:
l10.append(word)
full = list((l1,l2,l3,l4,l5,l6,l7,l8,l9,l10))
full_total = []
for li in full:
if len(li) == 0:
continue
else:
full_total.append(li)
return dict(zip(count_string, full_total)) | true |
070e48f8fcfb0722069f6c56c6fc1baaef4a079e | rwatsh/python | /codeacademy_proj/codeacademy/list_comprehension.py | 509 | 4.25 | 4 | __author__ = 'rushil'
doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0]
print doubles_by_3
# Complete the following line. Use the line above for help.
even_squares = [x**2 for x in range(1,11) if x % 2 == 0]
print even_squares
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print evens_to_50
cubes_by_four = [x**3 for x in range(1,11) if (x**3) % 4 == 0]
print cubes_by_four
threes_and_fives = [i for i in range(1,16) if (i % 3 == 0) or (i % 5 == 0)]
print threes_and_fives | true |
2ccd980f63f90ec665ba214438aa90db57c736d6 | dayanandghelaro/practice_for_arbisoft | /basicPython.py | 2,453 | 4.40625 | 4 | """
VARIABLES:
variableName = value
"""
integer = 123
decimal = 12.3
string = "string"
boolean = True
# assignment
variableName = 12
# assignment with expression
variableName = otherVariableName operator someValue
"""
OPERATORS:
Addition: +
Subtraction: -
Multiplication: *
Division: /
Modulus (Remainder): %
Power(Exponentiation): **
Interger Division: //
Operator Precedence:
Parenthesis: (), {}, []
Power: a**b or a^b
Multiplication: Division(/), Multiplication (*), Remainder (%)
Addition: Addition(+), Subtraction (-)
Left to Right: a - c + d
Comparision Operators:
Less than: <
Less than or equal: <=
Greater than: >
Greater than or equal: >=
Equal: ==
Not equal: !=
"""
type(variableName) # gives type of variable (int, str, float, bool, object, etc)
"""
CONVERTING TYPE (suitable conversion):
str(variableName): converts to string
int(variableName): converts to integer
float(variableName): converts to float/decimal
"""
"""
CONDITIONAL STATEMENTS
if condition:
# code goes here
pass
else:
# code goes here
pass
More conditions
if condition1:
# code goes here
pass
elif condition2:
# code goes here
pass
...
...
...
elif conditionN:
# code goes here
pass
else:
# code goes here
pass
TRY - EXCEPT
try:
# put dangerous / critical code which will probably cause exception
pass
except:
# if exception encountered..
pass
FUNCTIONS:
Built-in functions:
(int(), float(), str(), print(), etc.)
def functionName():
# function code goes here
pass
def functionName(argument[s]):
# function code goes here
pass
def functionName(arguments[s]):
# function code goes here
return someValue
LOOPS:
# indefinite loop
while condition[s]:
# loop code goes here
if condition:
continue # skip following line go to next iteration
if condition:
break: # stop loop
# definite loop
for item in itemsList:
# process item
STRINGS:
"""
| true |
aba7804090bdaa8d017dd1cf8592885eb86aa15e | helenle/Python | /fibonacci.py | 382 | 4.21875 | 4 | import math
# fibonacci
def fibonacci(n):
if not isinstance(n, int):
print "fibonacci is only defined for integers."
return -1
elif n < 0:
print "fibonacci is only defined for positive integers."
return -1
elif 0 <= n <= 1: # or if n == 0 or n == 1:
return 1
else:
return fibonacci(n -1) + fibonacci(n -2)
print 'fibonacci =', fibonacci(5)
| false |
3138940ce195de5ef13bfe7b7f6a297a117051fd | SarahLizDettloff/Mathematics | /Physics/bigfour.py | 2,590 | 4.34375 | 4 | def displacement_with_acceleration():
initial_velocity = float(raw_input("Enter the inital velocity of the object in m/s: \n"))
time = float(raw_input("Enter the time in seconds: \n"))
acceleration = float(raw_input("Enter the acceleration in m/s^2:\n"))
result = (float(initial_velocity) * float(time) + float(0.5) * float(acceleration) * float(time**2))
print("The displacement with acceleration is: " + str(result) + "m \n")
another()
def final_velocity():
initial_velocity = float(raw_input("Enter the inital velocity of the object in m/s: \n"))
time = float(raw_input("Enter the time in seconds: \n"))
acceleration = float(raw_input("Enter the acceleration in m/s^2:\n"))
result = (float(initial_velocity) + (float(time) * float(acceleration)))
print("The final velocity is: " + str(result) + "m \n")
another()
def displacement_without_acceleration():
initial_velocity = float(raw_input("Enter the inital velocity of the object in m/s: \n"))
time = float(raw_input("Enter the time in seconds: \n"))
final_velocity = float(raw_input("Enter the final velocity of the object in m/s: \n"))
result = (((float(initial_velocity) * float(final_velocity)) / 2) * float(time))
print("The displacement is: " + str(result) + "m \n")
another()
def final_velocity_squared():
acceleration = float(raw_input("Enter the acceleration in m/s^2:\n"))
initial_velocity = float(raw_input("Enter the inital velocity of the object in m/s: \n"))
displacement = float(raw_input("Enter the displacement in m:\n"))
result = float(float(initial_velocity * 2) + (2 * float(acceleration) * float(displacement)))
print("The final velocity squared is: " + str(result) + "m \n")
another()
def another():
answer = raw_input("Would you like to solve another equation? Enter Y for yes or N for no\n")
if answer == "Y":
which_equation()
else:
exit()
def which_equation():
answer = raw_input("Enter the number of the kinematic equation you want to solve:\n1.Displacement with known acceleration.\n2.Displacement without known acceleration.\n3.Final Velocity.\n4.Final Velocity Squared.\n")
if answer == "1":
displacement_with_acceleration()
elif answer == "2":
displacement_without_acceleration()
elif answer == "3":
final_velocity()
elif answer == "4":
final_velocity_squared()
else:
print("This will only accept an input of 1, 2, 3, or 4.")
which_equation()
if __name__ == "__main__":
which_equation()
| true |
3c6640ad9baad02e2a098269a9cb0fd2f0abc2dd | dpancho/leetcode_stuffs | /LeetcodeChallenges/easy/palindrome_num.py | 713 | 4.15625 | 4 | # To check if number inputed is the same forwards as it is backwards AKA palindrome
# x = 121
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
# similar to reverse an int, just compare at the end.
# take x and store into separate array
# reverse that number
# is num in array == x?
# if its a negative number, will always be false
if x < 0:
return False
else:
store = str(x)
reversed_num = int(store[::-1])
if x == reversed_num:
return True
else:
return False
# print(isPalindrome(121))
| true |
7a59269681a3dd7d314575e7da273ff75e0218c6 | vish35/algorithms | /Level-3/cycle_in_graph.py | 1,780 | 4.28125 | 4 | #!/usr/bin/python
# Date: 2017-12-29
#
# Description:
# Program to check if there exists a cycle in a graph or not.
#
# Approach:
# - Graph has cycle if it contains a back edge(there is some other path which
# reaches to the same vertex from a source vertex).
# - This uses DFS approach to find back edge.
# - This is implemented for directed graph, for undirected graph we just have
# to add an edge corresponding to each edge(for each edge u to v there should
# be an edge from v to u)
#
# Reference:
# https://www.geeksforgeeks.org/detect-cycle-in-a-graph/
#
# Complexity:
# O(V + E)
# V = number of vertexes/nodes
# E = number of edges
import collections
class Graph(object):
"""Implements graph and performs DFS."""
def __init__(self):
"""Initializes empty graph having no vertexes/edges."""
self.graph = collections.defaultdict(list)
def add_edge(self, start, end):
"""Adds an edge to graph"""
self.graph[start].append(end)
def cycle_wrt_vertex(self, current_vertex, visited):
"""Uses DFS to check if cycle exists with respect to current vertex."""
visited[current_vertex] = True
for x in self.graph[current_vertex]:
if visited.has_key(x):
if not visited[x]:
return self.cycle_wrt_vertex(x, visited)
else:
return True
def check_cycle(self):
"""Checks if cycle is present in a graph."""
for k in self.graph:
visited = {k: False for k in self.graph}
has_cycle = self.cycle_wrt_vertex(k, visited)
if has_cycle:
print('Graph has cycle!')
print('Has a back edge with ancestor node - {0}'.format(k))
break
g = Graph()
g.add_edge(10, 11)
g.add_edge(10, 12)
g.add_edge(11, 13)
g.add_edge(13, 14)
g.add_edge(15, 15)
g.check_cycle()
| true |
a60b914cda1997cb8e7d1e7a015d3dc60d19b993 | Joes-BitGit/Leetcode | /leetcode/valid_paren.py | 1,519 | 4.25 | 4 | # DESCRIPTION
# Given a string containing only three types of characters: '(', ')' and '*',
# write a function to check whether this string is valid.
# We define the validity of a string by these rules:
# Any left parenthesis '(' must have a corresponding right parenthesis ')'.
# Any right parenthesis ')' must have a corresponding left parenthesis '('.
# Left parenthesis '(' must go before the corresponding right parenthesis ')'.
# '*' could be treated as a single right parenthesis ')'
# or a single left parenthesis '(' or an empty string.
# An empty string is also valid.
# EXAMPLE 1:
# Input: "()"
# Output: True
# EXAMPLE 2:
# Input: "(*))"
# Output: True
class Solution:
def checkValidString(self, s: str) -> bool:
'''
Time: O(N), where N is the length of the string
Space: O(1), constant space no aux space used
'''
# Greedy Algorithm
# increments at '(' dec for ')'
cmin = 0
# incs '(' and '*' decs for ')'
cmax = 0
for i in s:
if i == '(':
cmax += 1
cmin += 1
if i == ')':
cmax -= 1
# not including itself find the max between cmin-1 and 0
# this makes sure cmin is not negative
cmin = max(cmin - 1, 0)
if i == '*':
cmax += 1
cmin = max(cmin - 1, 0)
if cmax < 0:
return False
return cmin == 0
| true |
f31d566f815b4a3f79d4b00ee2a42f077b477756 | Joes-BitGit/Leetcode | /leetcode/longest_common_subseq.py | 1,613 | 4.15625 | 4 | # DESCRIPTION
# Given two strings text1 and text2, return the length of their longest common subsequence.
# A subsequence of a string is a new string generated from the original string
# with some characters(can be none) deleted without changing the relative order of the remaining characters.
# (eg, "ace" is a subsequence of "abcde" while "aec" is not).
# A common subsequence of two strings is a subsequence that is common to both strings.
# If there is no common subsequence, return 0.
# EXAMPLE 1:
# Input: text1 = "abcde", text2 = "ace"
# Output: 3
# Explanation: The longest common subsequence is "ace" and its length is 3.
# EXAMPLE 2:
# Input: text1 = "abc", text2 = "abc"
# Output: 3
# Explanation: The longest common subsequence is "abc" and its length is 3.
# EXAMPLE 3:
# Input: text1 = "abc", text2 = "def"
# Output: 0
# Explanation: There is no such common subsequence, so the result is 0.
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
'''
Time: O(N*M), where N is length of text1, M is the length of text2
Space: O(N*M), 2D array needed of rows N and columns M
'''
# Dynamic Programming
n = len(text1)
m = len(text2)
# includes empty string
lcs = [[0 for i in range(m+1)] for j in range(n+1)]
# fill table
for i in range(n):
for j in range(m):
if text1[i] == text2[j]:
lcs[i+1][j+1] = 1 + lcs[i][j]
else:
lcs[i+1][j+1] = max(lcs[i+1][j], lcs[i][j+1])
return lcs[-1][-1]
| true |
00db7034e92382db740054511b875d31a4b20869 | Anton-K-NN/Python-prakticum-Stepic | /ceasar crypt for dif alphabet.py | 1,780 | 4.1875 | 4 | '''
Реализуйте функцию caesar(text, key), возвращающую зашифрованный текст, работающую только с латинским алфавитом.
text - исходных текст, который надо зашифровать (или расшифровать)
key - ключ (сдвиг)
Ключ может быть отрицательным или больше 26
Из преобразуемого текста удаляются все пробелы и знаки препинания. Зашифрованный текст пишется в верхнем регистре 1 строкой.
'''
def caesar(text, key, alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
t=text.upper().split()
tr=''.join(t)
#print(tr)
ntr=''
if len(alphabet)==0:
return tr
else:
for i in range(len(tr)):
if alphabet.find(tr[i]) != -1:
# print('tr',tr[i])
if (key > 0 and key < len(alphabet)) or (key > -len(alphabet) and key < 0):
ntr = ntr + alphabet[(alphabet.index(tr[i]) + key) % (len(alphabet))]
elif key > len(alphabet):
newkey = (key) % len(alphabet)
ntr = ntr + alphabet[(alphabet.index(tr[i]) + newkey)]
elif key < -len(alphabet):
newkey = -(abs(key) % len(alphabet))
ntr = ntr + alphabet[(alphabet.index(tr[i]) + newkey)]
elif key == 0 or key == len(alphabet):
ntr = ntr + alphabet[alphabet.index(tr[i])]
else:
continue
# print(ntr)
return ntr
tex=input()
k=int(input())
print(caesar(tex, k)) | false |
5354f3c09a7ea0dc4815745bdbfa77975843dcd0 | Anton-K-NN/Python-prakticum-Stepic | /Practicum Numpy/Геометрическая прогр - вектор чисел.py | 570 | 4.21875 | 4 | '''
На вход подаются 3 числа (каждое с новой строки):
start
stop
n
Составьте список из n точек на отрезке [start, stop] в геометрической прогрессии, включая start и stop.
Округлите значения точек до 3 знака после запятой.
Результат сохраните в переменную Z.
'''
import numpy as np
start=int(input())
stop=int(input())
n=int(input())
Z=np.geomspace(start,stop, num=n)
print(Z)
| false |
eb401e973c5fd01437ce19511b48dda51ed195de | anjaandric/Midterm-Exam | /task2.py | 970 | 4.3125 | 4 | """
=================== TASK 2 ====================
* Name: Product Of Digits
*
* Write a script that will take an input from user
* as integer number and display product of digits
* for a given number. Consider that user will always
* provide integer number.
*
* Note: Please describe in details possible cases
* in which your solution might not work.
===================================================
"""
# Write your code here
def product_digits(number):
# Provjeravamo da li je intiger
if not isinstance(number, int):
return False
# Initialize product value
product_sum = 1
# NOTE: Napravimo je da radi za negativne brojeve
number = abs(number)
while number > 0:
digit = number % 10
number = number // 10
product_sum *= digit
return product_sum
def main():
int_number = 1234
product_sum = product_digits(int_number)
print("Proizvod cifara je : ", product_sum)
main()
| true |
b379d7433da0d408c5e56a8bd2c9051cee61fe2b | Sunno/interviewcake | /bracket_validator.py | 1,891 | 4.21875 | 4 | # Bracket Validator
# Just a bracket validator, this is the link https://www.interviewcake.com/question/python3/bracket-validator
import unittest
def is_valid(code):
# Determine if the input code is valid
# We'll use a list as a stack, it's the simpler way
stack = []
# Here we have our openers and their pair
openers = {
'(': ')',
'{': '}',
'[': ']'
}
for c in code:
if c in openers:
# In case the char we are evaluating is opening a pair, we add it to stack
stack.append(c)
elif len(stack) > 0 and c == openers[stack[-1]]:
# if the current character is closing the opener in the stack we just remove that
# opener from stack
stack.pop()
else:
# This is the case we find a char that is not closing anything
# It makes no sense to keep iterating
return False
# And last, in case there are still brackets without closing, we return False
return len(stack) == 0
# Tests
class Test(unittest.TestCase):
def test_valid_short_code(self):
result = is_valid('()')
self.assertTrue(result)
def test_valid_longer_code(self):
result = is_valid('([]{[]})[]{{}()}')
self.assertTrue(result)
def test_interleaved_openers_and_closers(self):
result = is_valid('([)]')
self.assertFalse(result)
def test_mismatched_opener_and_closer(self):
result = is_valid('([][]}')
self.assertFalse(result)
def test_missing_closer(self):
result = is_valid('[[]()')
self.assertFalse(result)
def test_extra_closer(self):
result = is_valid('[[]]())')
self.assertFalse(result)
def test_empty_string(self):
result = is_valid('')
self.assertTrue(result)
unittest.main(verbosity=2)
| true |
c392a5acbdc590ed92e4b9ae022b5b775ef152e3 | jodebane/PythonCode | /BostonTripPlanner | 2,557 | 4.25 | 4 | #!/usr/bin/python
print("You will be asked to rate your desire to see various tourist sights, by ranking types of sights on a scale of 1 to 4, 4 being the type of sight you most want to see, 4 being the type of sight you least want to see. You will also be asked how many days you are staying in this city")
artlist=["MFA", "ICA", "Isabella Steward Gardner Museum"]
artnum=len(artlist)
historylist=["freedom trail", "North End", "Navy Yard", "JFK House", "Black Heritage Trail", "Boston Common",]
historynum=len(historylist)
modernlist=["Cambridge","Museum of Science", "MIT Museum", "Prudential Center"]
modernnum=len(modernlist)
days=input("How many days will you be in Boston?" )
if days == "1":
d = 1
print("you will be in Boston for 1 day")
if days == "2":
d = 2
print("you will be in Boston for 2 day")
if days == "3":
d = 3
print("you will be in Boston for 3 days")
artrank=input("how important are art-related sights to you? Rank on a scale of 1 to 3, 1 being most important, 3 being least important. You may not use this number ranking again.")
if artrank == "1":
artrankvar = 1
print ("art rank is 1")
if artrank == "2":
artrankvar = 2
print ("art rank is 2")
if artrank == "3":
artrankvar = 3
print ("art rank is 3")
artmax = round((artnum*d*d)/(3*d*artrankvar))
historyrank=input("how important are history-related sights to you? Rank on a scale of 1 to 3, 1 being most important, 3 being least important. You may not use this number ranking again.")
if historyrank == "1":
historyrankvar = 1
print ("history rank is 1")
if historyrank == "2":
historyrankvar = 2
print ("history rank is 2")
if historyrank == "3":
historyrankvar = 3
print ("History rank is 3")
if historyrank == artrank:
sys.exit()
historymax = round((historynum*d*d)/(3*d*historyrankvar))
modernrank=input("how important are modern day sights to you? Rank on a scale of 1 to 3, 1 being most important, 3 being least important. You may not use this number ranking again.")
if modernrank == "1":
modernrankvar = 1
print ("modern rank is 1")
if modernrank == "2":
modernrankvar = 2
print ("modern rank is 2")
if modernrank == "3":
modernrankvar = 3
print ("modern rank is 3")
if modernrank == historyrank:
sys.exit()
if modernrank == artrank:
sys.exit()
modernmax = round((modernnum*d*d)/(3*d*modernrankvar))
print("Visit these sights as your priority")
print(artlist[0:artmax])
print(historylist[0:historymax])
print(modernlist[0:modernmax])
| true |
865f5bfc1a9660ea8de54d2a0a9c37c0a97f2693 | aifulislam/Python_Demo_Third_Part | /lesson5.py | 1,627 | 4.1875 | 4 | #05/11/2020-------
#Function----------
def add(n1,n2):
return n1 + n2
n = 10
m = 20
result = add(n,m)
print(result)
#Function----------
x = 30
y = 40
result = add(x,y)
print(result)
print(add(2.50,6.50))
#Function----------
def sub(s1,s2):
return s1 - s2
x = 100
y = 50
sum = sub(x,y)
print(sum)
#Function----------
def mul(m1,m2):
return m1 * m2
p = 10
q = 20
multiplaction = mul(p,q)
print(multiplaction)
#Function----------
def myfnc(x):
print("inside myfnc", x)
x = 10
print("inside myfnc", x)
x = 20
print(x)
myfnc(x)
#Function----------
def myfnc(y):
print("y = ",y)
print("x = ",x)
x = 20
myfnc(x)
print("y = ",x)
# Function----------
def myfnc(y=10):
print("y = ", y)
x = 20
myfnc(x)
myfnc()
#Function----------
def myfunc(x, y , z = 10):
print("x = ",x, "y = ",y, "z = ",z)
myfunc(x = 1, y = 2, z = 5)
a = 5
b = 6
myfunc(x = a, y = b)
a = 1
b = 2
c = 3
myfunc(y = a, z = b, x = c)
#Function----------
def add_numbers(numbers):
result = 0
for number in numbers:
result+= number
return result
result = add_numbers([5,10,20,30,40,50])
print("Sum of result = ",result)
sum = add_numbers([5,8,5,4,6,7])
print("Sum of result = ",sum)
#Function----------
def test_fnc(li):
li[0] = 10
my_list = [1,2,3,4,5]
print("before function call [",my_list)
test_fnc(my_list)
print("After function call [",my_list)
#Function----------
list1 = [1,2,3,4,5]
list2 = list1
print(list1)
print(list2)
list2[0] = 100
print(list2)
print(list1)
| false |
053e5e0d77941ea0d13a7f12fcd9d9ddfe307a32 | armasog/Project_Euler_Solutions | /1.py | 524 | 4.1875 | 4 | import unittest
'''
Challenge:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
class testSuite(unittest.TestCase):
def test_solution(self):
assert solution(10) == 23
def solution(upper_bound):
result = 0
for i in range(upper_bound):
if i % 3 == 0 or i % 5 == 0:
result += i
return result
answer = solution(1000) # Answer is 233168
| true |
c8e905f7778a713f88da949f0af1a9d39471e01f | RafaelPerezMatos/VotingSystem | /Madlibs.py | 704 | 4.40625 | 4 | #string Connection (aka how to put strings toguether)
#suppose we want to create a string that says "subscribe to ____"
#youtuber = "Kylie Ying" #some string variable
# a few ways to do this
#print("subscribe to " + youtuber)
#print("subscribe to {}".format(youtuber))
#print(f"subscribe to {youtuber}")
"""---------------------------------------"""
adj = input("Adjective: ")
verb1 = input("Verb: ")
verv2 = input("Verb: ")
famous_person = input("Famous person: ")
madlib = f"Computer programming is so {adj}¡ It makes me so excited all the time because \
I love to {verb1}. Stay hydrated and {verv2} like you are {famous_person}!"
print(madlib)
"___________________________________________________" | true |
ee06139ffcd88f79b7c9a0bc7126088f61b3f1af | abhiiitcse/HackerRank | /Python/Functional/mapandlambda.py | 403 | 4.125 | 4 | cube = lambda x: x**3
def fibonacci(n):
ret_list = list()
if n>0:
ret_list.append(0)
if n>1:
ret_list.append(1)
if n >= 3:
a = 0
b = 1
for i in range(2,n):
ret_list.append(a+b)
temp = a + b
a = b
b = temp
return ret_list
if __name__=='__main__':
n = input()
print map(cube,fibonacci(n))
| false |
c8661b2aa80b2ac32cee09aa0c30bc5e327006a5 | munnamn/01-IntroductionToPython | /src/m6_your_turtles.py | 1,935 | 4.5 | 4 | """
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Aaron Wilkin, their colleagues, and Nihaar Munnamgi.
"""
########################################################################
# DONE:
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
########################################################################
import rosegraphics as rg
window = rg.TurtleWindow()
red_turtle = rg.SimpleTurtle('turtle')
red_turtle.pen = rg.Pen('red', 10)
red_turtle.speed = 10
size = 100
for k in range(5):
red_turtle.draw_circle(size)
red_turtle.pen_up()
red_turtle.right(45)
red_turtle.forward(100)
red_turtle.left(45)
red_turtle.pen_down()
size = size - 10
window.tracer(50)
black_turtle = rg.SimpleTurtle('square')
black_turtle.pen = rg.Pen('black', 20)
red_turtle.speed = 20
size = 200
for k in range (10):
black_turtle.draw_square(size)
black_turtle.pen_up()
black_turtle.left(50)
black_turtle.backward(200)
black_turtle.right(90)
black_turtle.pen_down()
size = size - 20
########################################################################
#DONE:.
# You should have RUN the m5e_loopy_turtles module and READ its code.
# (Do so now if you have not already done so.)
#
# Below this comment, add ANY CODE THAT YOU WANT, as long as:
# 1. You construct at least 2 rg.SimpleTurtle objects.
# 2. Each rg.SimpleTurtle object draws something
# (by moving, using its rg.Pen). ANYTHING is fine!
# 3. Each rg.SimpleTurtle moves inside a LOOP.
#
# Be creative! Strive for way-cool pictures! Abstract pictures rule!
#
# If you make syntax (notational) errors, no worries -- get help
# fixing them at either this session OR at the NEXT session.
#
# Don't forget to COMMIT-and-PUSH when you are done with this module.
#
########################################################################
| false |
2c465c4d4f5c7e04806bef753dff033d12c208ff | hubrigant/python_exercises | /ex4/ex4.py | 266 | 4.3125 | 4 | #!/usr/bin/env python3
"""
W3Schools Python Exercises
Exercise 4
24 July 2020
Jon Williams
"""
from math import pi
r = float(input("Input the radius of the circle: "))
print("The area of the circle with radius {} is {}".format(str(r), str(pi * r**2)))
| true |
323a510fa8e250cbd3f7fbe753938c8d1478dd0d | Susanna501/Homework | /Homework28.py | 898 | 4.4375 | 4 | '''1. Create a python function factorial and import this
file in another file and print factorial.'''
from Susik import factorial2 as f
print(f(7))
'''2. Write a Python function tocalculate surface volume and area of
a cylinder(Գլան). V=πr^2h and A=2πrh+2πr^2 :'''
from Susik import cylinder_volume_and_area as cyl
print(cyl(6,4))
'''3. Write a Python function to calculate surface volume
and area of a sphere(Գունդ). V = 4/3*π*r3 and A = 4*π*r2'''
from Susik import sphere_volume_and_area as sph
print(sph(6))
'''4. Write a Python function to convert degree to radian.
one radian = pi/180: 90 radian = 1.57...'''
from Susik import degree_to_radian as dr
print(dr(90))
'''5. Write a Python function to print all primes smaller than or equal to a
specified number. Call function: numbers(9) Output: (2, 3, 5, 7)'''
from Susik import allprimes
print(allprimes(9))
| true |
06ba5bb820f895d67b0370b59846f1ca1436f34f | szostiPL/kolo | /draw_methods.py | 538 | 4.3125 | 4 | def create_line(x, y):
"""
Returns list of tuples which are coordinates
of a line created in cartesian coordinate system
"""
return [(1,1),(2,2),(3,3)(4,4)]
def create_square():
"""
Returns list of tuples which are coordinates
of a square created in cartesian coordinate system
"""
return [(0,0),(4,0),(0,4),(4,4)]
def measure_angle(line, wall):
"""
Returns angle between given line and given wall
line -- formula of a line
wall -- formula of a wall line
"""
return 43
| true |
b51fdc7a0edab37a8b720a9b3a8e192ab569a23c | jlaufmann/python-fundamentals | /01_python_fundamentals/01_01_run_it.py | 1,139 | 4.59375 | 5 | '''
1 - Write and execute a script that prints "hello world" to the console.
2 - Using the interpreter, print "hello world!" to the console.
3 - Explore the interpreter.
- Execute lines with syntax error and see what the response is.
* What happens if you leave out a quotation or parentheses?
* How helpful are the error messages?
- Use the help() function to explore what you can do with the interpreter.
For example execute help('print').
press q to exit.
- Use the interpreter to perform simple math.
- Calculate how many seconds are in a year.
'''
#1
# see file hello.py
#2
'''
$ python3
>>> print("hello world!")
'''
#3
'''
print("no 2nd quotation mark)
print("no 2nd paranthesis"
we get syntax errors
the error messages are good, in these examples they tell us where to look to correct the error
'''
'''
$ python3
>>> help(print)
'''
'''
$ python3
>>> 2 + 2
>>> days_in_year = 365
>>> hours_in_day = 24
>>> minutes_in_hour = 60
>>> seconds_in_minute = 60
>>> seconds_in_year = days_in_year * hours_in_day * minutes_in_hour * seconds_in_minute
>>> print(seconds_in_year)
31536000
'''
| true |
d6ee384ea6541eee98b5fcfef8772c504f9c13a6 | jlaufmann/python-fundamentals | /04_conditionals_loops/04_07_search.py | 1,137 | 4.25 | 4 | '''
Receive a number between 0 and 1,000,000,000 from the user.
Use while loop to find the number - when the number is found exit the loop and print the number to the console.
'''
magic_no = int(input("Enter an integer number between 0 and 1,000,000,000: "))
method = 'simple'
# method = 'fast'
guess_low = 0
guess_high = 1E+9
if magic_no < guess_low or magic_no > guess_high:
print("That number is out of range!")
quit()
guess = 0
########### SIMPLE METHOD ##########
if method == 'simple':
while guess != magic_no:
guess += 1
##############################################
# that is the simplest method, but on my computer can take up to 80 seconds to find the magic_no
# using if loops to implement upper and lower bounds each time is much quicker.
########## FAST METHOD #############
if method == 'fast':
while guess != magic_no:
guess = int(((guess_high - guess_low) // 2) + guess_low)
if magic_no < guess:
guess_high = guess
elif magic_no > guess:
guess_low = guess
##############################################
print(f"Your number is: {guess}")
| true |
34b9eb3a422d22dec6e0f585195aa47ca0e0b3f6 | jlaufmann/python-fundamentals | /03_more_datatypes/2_lists/03_10_unique.py | 1,284 | 4.34375 | 4 | '''
Write a script that creates a list of all unique values in a list. For example:
list_ = [1, 2, 6, 55, 2, 'hi', 4, 6, 1, 13]
unique_list = [55, 'hi', 4, 13]
'''
# Example list:
list_ = [1, 2, 6, 55, 2, 'hi', 4, 6, 1, 13]
'''
All this stuff is commented out because it is just too difficult to get a string from user input without knowing
in advance exactly what may be in the list. And in any case it is more likely that a string would be passed to a
function rather than getting the user to input a string in string format.
# get list from input:
print("Example list: [1, 2, 6, 55, 2, 'hi', 4, 6, 1, 13]")
string_in = input("Enter your list: ")
string_in1 = string_in.replace(" ","") # removing whitespace from string
# this assumes there is no whitespace within a string in the list
#print(f"string without white space: {string_in1}")
list_in = string_in1.strip('][').split(',') # splitting string into list
#print(f"string split into list: {list_in}")
#print(type(list_in))
# Because the list may contain integers, floats or strings, all items will just be treated as general items
list_ = list_in
'''
print(f"list_ = {list_}")
unique_list = []
for item in list_:
if list_.count(item) == 1:
unique_list.append(item)
print(f"unique_list = {unique_list}")
| true |
3e6059d11c6e02ce24cdfbeb5e6753f07d8917dd | jlaufmann/python-fundamentals | /03_more_datatypes/4_dictionaries/03_18_occurrence.py | 1,002 | 4.15625 | 4 | '''
Write a script that takes a string from the user and creates a dictionary of letter that exist
in the string and the number of times they occur. For example:
user_input = "hello"
result = {"h": 1, "e": 1, "l": 2, "o": 1}
'''
string_in = input("Enter your string: ")
# so that A and a are the same, convert string to lower case.
string_l = string_in.lower()
keys = []
for char in string_l:
if char.isalpha() and (char not in keys):
keys.append(char)
# it could be nice to sort the letters alphabetically
keys.sort()
'''
strings are immutable, lists are mutable.
string.lower() needs to be assigned to new_string - because strings are immutable
string.sort() does not work
list.lower() does not work
list.sort() does not need an assignment. An assignment in the statement will not work!!
list2 = sorted(list) leaves list unsorted, and assigns the sorted list to list2.
'''
my_dict = {}
for letter in keys:
my_dict[letter] = string_l.count(letter)
print(f"result = {my_dict}")
| true |
5998c9696b4ad3dd93cdae238e8f6516e55f4ad8 | jlaufmann/python-fundamentals | /02_basic_datatypes/1_numbers/02_04_temp.py | 447 | 4.4375 | 4 | '''
Fahrenheit to Celsius:
Write the necessary code to read a degree in Fahrenheit from the console
then convert it to Celsius and print it to the console.
C = (F - 32) * (5 / 9)
Output should read like - "81.32 degrees fahrenheit = 27.4 degrees celsius"
'''
deg_F = float(input("Please enter temperature in degrees Fahrenheit: "))
deg_C = (deg_F - 32) * (5 / 9)
print(str(deg_F), 'degrees fahrenheit = ', str(deg_C), 'degrees celsius') | true |
f3b7818632d13f3ab51f9a1020ccf2382a82e9c5 | ivo-douglas/OlaMundo | /URI Programas/Age in Days.py | 807 | 4.4375 | 4 | # coding: utf-8
"""
Read an integer value corresponding to a person's age (in days) and print it in years, months and days,
followed by its respective message “ano(s)”, “mes(es)”, “dia(s)”.
Note: only to facilitate the calculation, consider the whole year with 365 days and 30 days every month.
In the cases of test there will never be a situation that allows 12 months and some days, like 360, 363 or 364.
This is just an exercise for the purpose of testing simple mathematical reasoning.
Input
The input file contains 1 integer value.
Output
Print the output, like the following example.
"""
age = int(input())
age_to_years = age // 365
age_to_month = (age%365)//30
age_to_days = (age%365)%30
print(age_to_years, "ano(s)")
print(age_to_month, "mes(es)")
print(age_to_days, "dia(s)") | true |
675e2203367e209bdebc621a313cbc46e67f8a69 | bigorangedad/hogwarts | /main.py | 1,907 | 4.375 | 4 | """
list.append(x): 在列表的末尾添加一个元素。相当于a[len(a):] = [x]。
list.insert(i,x):在给定的位置插入一个元素。第一个参数是要插入的元素的索引,以a.insert(0,x)插入列表头部,a.insert(len(a),x)等同于a.append
list.remove(x):移除列表中第一个值为x的元素。如果没有这样的元素,则抛出ValueError 异常。
list.pop([i]):删除列表中给定位置的元素并返回它。如果没有给定位置,a.pop()将会删除并返回列表中的最后一个元素。
list.sort(key=None,reverse=False):对列表中的元素进行排序(参数可用于自定义排序,解释请参见 sorted())。
list.reverse():反转列表中的元素。
"""
#
# list_hogwarts=[1,2,3,]
# list_hogwarts.append(0)
# list_hogwarts.insert(1,5)
# list_hogwarts.insert(4,5)
# list_hogwarts.pop(1)
# list_hogwarts.sort()
# list_hogwarts.sort(reverse=True)
# list_hogwarts.reverse()
# list_hogwarts.remove(1)
# list_hogwarts.append(2)
# list_hogwarts.append(4)
# list_hogwarts.append(6)
# print(list_hogwarts.pop(1))
# print(list_hogwarts)
# list_hogwarts.append(2)
# list_hogwarts.append(4)
# print(list_hogwarts)
"""
列表推导式:
如果我们想生成一个平方列表,比如[1,4,9...],使用for循环应该怎么写,使用列表生成式又应该怎么写呢?
"""
# list_square=[]
# for i in range(3,8):
# list_square.append(i**2)
# print(list_square)
# list_square=[i**2 for i in range(3,8)]
# print(list_square)
# list_square=[]
# for i in range(2,6):
# if i !=3:
# list_square.append(i**2)
# print(list_square)
# list_square=[i**2 for i in range(2,6) if i !=3]
# print(list_square)
# list_square=[]
# for i in range(2,6):
# for j in range(1,4):
# if i!=j:
# list_square.append(i*j)
# print(list_square)
# list_square=[i*j for i in range(2,6) for j in range(1,4) if i!=j]
# print(list_square)
| false |
fc776359ce8fd44b0e2bdd58dab97a1603f5703a | sachinlohith/leetcode | /String/strobogrammaticNumber.py | 848 | 4.125 | 4 | """
https://leetcode.com/problems/strobogrammatic-number/description/
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
"""
class Solution(object):
def isStrobogrammatic(self, num):
"""
:type num: str
:rtype: bool
"""
nMap = {'1':'1', '6':'9', '9':'6', '8':'8', '0':'0'}
res = ''
for n in str(num):
if n not in nMap:
return False
res += nMap[n]
return res[::-1] == num
def isStrobogrammaticOneLiner(self, num):
return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num) / 2 + 1)) | true |
5fa2cea6a51c8a631c135040734d6b8fc1abd07a | vignesan-siva/python-project | /day5-time convertion problem.py | 1,755 | 4.21875 | 4 | #only enter valid number otherwise not properly respond
#hours to second
print("==========1) hours to second==========")
hr=int(input("enter no of hours:"))
def convert(hr):
hour=hr*60
return hour
print("second:",convert(hr))
#minutes to hour
print("=============2) minutes to hour==================")
minute=int(input("enter no of minutes:"))
a=minute//60
print(a,"hours")
# #second to hour
print("==============3) second to hour==================")
second=int(input("enter no of second:"))
b=second//3600
print(b,"hour")
#hours to second
print("===================4) hour to second============")
d=int(input("enter no of hours:"))
def second(s):
hd=3600*s
return hd
print(second(d),"second")
#day to year
print("===============5)day to year=============")
day=int(input("enter no of day:"))
day_to_year=day/365
print("%.2f"%day_to_year,"year")
#year to date
print("===========6)year to date============")
year=int(input("enter no of year:"))
year_to_date=year*365
print("%.0f"%year_to_date,"date")
#month to day
print("===========7)month to day================")
hello=int(input("enter no of month:"))
year=hello*30+5
print("%.0f"%year,"days")
#day-to month
print("==============8)day to month==============")
hi=int(input("enter no of days:"))
month_of=hi//30
print("%.0f"%month_of,"month")
#month to year
print("==============9)month to year==============")
g=int(input("enter no of month:"))
month_of_f=g//12
print("%.0f"%month_of_f,"year")
#year to month
print("==============10)year to month==============")
gu=int(input("enter no of years:"))
month_of_h=gu*12
print("%.0f"%month_of_h,"month")
| true |
39e5ac0aaf7d255b7fad05047377e5aeae703108 | Shahidayatar/PythonLearn | /Constructors___15.py | 1,412 | 4.375 | 4 | #https://www.youtube.com/watch?v=ic6wdPxcHc0&list=PLsyeobzWxl7poL9JTVyndKe62ieoN-MZ3&index=55
class computer : # if you want to keep the class empty then use 'pass'
def __init__(self):
self.name= 'shahid' # we are making variables
self.age= 19
print(self.name, self.age)
def update(self):
self.age=27
def compare(self,c2): # compare take two parameter compare(who is calling, whom to compare )
if self.age==c2.age:
return True
else:
return False
c1=computer() # constructor calculates size of the memory
#c1.update() if you put this age will refer to update function
c2=computer()
if c1.compare (c2):# compare is not inbuild function # this is the way you compare
print("the age is same ")
else:
print("the age is different")
c1.update()# because of this c1.age refers to 27
print('name is ',c1.name,'and age is ',c1.age)
# another example of compre
class person:
def __init__(self):
self.age=92
def info(self):
self.age=23
def comparing(self,p2):
if p1.age==p2.age:
print("its correct")
else:
print("not correct")
p1=person()
#p1.info() # this will change the value of age remove comment to see
p2=person()
if p1.comparing(p2):
print("this is an compare example")
else:
print(" you get it !")
| true |
bdf8e6c6532ba8a06fc556c3a2fcb6048d55e67f | enterpriseih/Python100days | /day01_15/day09/triangle.py | 839 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 实例方法和类方法的应用
# @Date : 2019-07-13 22:41:54
# @Author : yaolh (yaolihui129@sina.com)
# @Link : https://github.com/yaolihui129
# @Version : 0.1
from math import sqrt
class Triangle(object):
"""docstring for Triangle"""
def __init__(self, a,b,c):
self._a = a
self._b = b
self._c = c
@staticmethod
def is_valid(a,b,c):
return a+b>c and b+c>a and c+a>b
def perimeter(self):
return self._a + self._b + self._c
def area(self):
p = self.perimeter()/2
return sqrt(p*(p -self._a)*(p - self._b)*(p-self.b)*(p - self._c)
if __name__ == '__main__':
a,b,c =map(float,input('请输入三条边:').sqrt())
if Triangle(a,b,c):
tri Triangle(a,b,c)
print('周长:',tri.perimeter())
print('面积:',tri.area())
else:
print('不能构成三角。')
| false |
681fb2c333226985bcaa14db397687e6e12351a9 | izzyevermore/test-average-calculator | /main2.py | 796 | 4.15625 | 4 | # task 2
# Calculate a learners average mark
student_name = input("Please enter your name: ")
student_surname = input("Please enter your surname: ")
test1 = float(input("Please your mark for the first test: "))
test2 = float(input("Please enter your mark for the second test: "))
test3 = float(input("Please enter your mark for the third test: "))
def average_mark():
average_mark = ((test1 + test2 + test3) / 3)
if average_mark >= 50:
print("You have passed!")
if average_mark < 50:
print("you have failed!")
print("Your mark is " + str(average_mark) + "%")
average_mark()
from datetime import datetime, timedelta
now = datetime.now
for d in range(10):
ten_date = now + timedelta(days=14)
now = ten_date
print(ten_date.strftime("%Y-%m-%d")) | true |
e1f5c724c7c5faa4c01d3ead8029a89191f3ce67 | Rammurthy5/random-topic-learnings | /composite_method.py | 1,399 | 4.375 | 4 | """
To understand & demonstrate composition. its an alternate approach to inheritance. to use only one or two methods
from a class, we can avoid inheritance, and go with composition
..date.. march 25 2020
..additional .. Understand the importance of total_ordering from functools module
"""
class A:
persist = ['get', 'hey', 'cha']
aa = 2
def __init__(self, instance):
print("init")
self._instance = instance
def __enter__(self):
print("enter")
def __getattr__(self, item):
print("searching")
if item in self.persist:
return getattr(self._instance, item)
def get(self):
print("inner get")
from functools import total_ordering
@total_ordering # this will make sure we implement at least one ordering dunder operation: < > <= >=
class B:
aa = 1
def get(self):
print("composite get")
def hey(self):
print("composite get")
def cha(self):
print("composite get")
def set(self):
print("composite get")
def __eq__(self, other):
print("in here")
return self.aa == other.aa
def __lt__(self, other):
return self.aa < other.aa
b = B()
a = A(b) # passing class B's instance 'b' here rather inheriting it. this will invoke __getattr__ &
# do the needful
print(a == b)
a.hey()
a.set() | true |
d110080b0a3bb72270852dbd6092e641864d8b22 | Rammurthy5/random-topic-learnings | /duck_typing.py | 1,771 | 4.46875 | 4 | """
Duck Typing is helpful in returning some value nonetheless the type / class of the object. Objective is to get something
work based on behaviour rather having dependency on type of the object.
..date.. March 25 2020
..real-time eg.. we have a len() method in Python, which can return length of string, dict, list only. what if we
need to return something when we do it for a class? can be doable with the help of dunders!
OR
class A dont want to have concrete dependency, & it just wanna call method B from different class /
interface.
Can be implemented with the help of duck typing / dependency injection.
https://hackernoon.com/python-duck-typing-or-automatic-interfaces-73988ec9037f
"""
class Hello:
def __len__(self):
"""By declaring this we are making sure that len() works not based on TYPE, but based on behaviour."""
return 1234
h = Hello()
print(len(h)) # prints 1234
# Example 2
a = 'stroiae'
l = ['ared', 'louis', 'tariq', 'ram', 'jona', 'nick']
t = ('arse', 'myarse', 'nipper', 'jeopardy')
d = {'ch':'chet'}
s = {'chet', 'chetchet', 'see', 'oral'}
# we have all the above different data types. Now we gonna write a method below to demonstrate duck-typing
def find_vowels(iterable):
res = list()
for i in iterable: # this would work for any object if it behaves like an iterable. this duck-typing
# for i in range(len(iterable)):
# i = iterable[i] # Had we included the above 2 lines, it would be SPECIFIC to type list / tuple. wont
# work for dict / set.
if i[0] in 'aeiou':
res.append(i)
return res
| true |
5632e4f6a793e5660a1ca666530c033777686e16 | felipemaion/studying_python | /MaiQuete20220417.py | 1,613 | 4.125 | 4 | # Escreva um programa que calcule o preço a pagar pelo fornecimento
# de energia elétrica. Pergunte a quantidade de kWh consumida e o tipo de insta-
# lação: R para residências, I para indústrias e C para comércios. Calcule o preço a
# pagar de acordo com a tabela a seguir.
# Preço por tipo e faixa de consumo
# Tipo Faixa (kWh) Preço
# Residencial Até 500 R$ 0,40
# Acima de 500 R$ 0,65
# Comercial
# Até 1000 R$ 0,55
# Acima de 1000 R$ 0,60
# Industrial
# Até 5000 R$ 0,55
# Acima de 5000 R$ 0,60
def input_usuario():
try:
kWh = float(input("Informe a quantidade de kWh consumida: "))
tipo = input("Informe o tipo de instalação: R para residências, I para indústrias e C para comércios: ")[0].upper()
if tipo not in 'RIC':
raise ValueError
return kWh, tipo
except ValueError:
print("ERRO:\n\tCONSUMO: Números apenas (kWh)\n\tTIPO: R, I ou C a instalação.")
return input_usuario()
def calcular_consumo(kWh, tipo):
if tipo == 'R':
if kWh <= 500:
return kWh*0.4
else:
return kWh*0.65
elif tipo == 'C':
if kWh <= 1000:
return kWh*0.55
else:
return kWh*0.6
elif tipo == 'I':
if kWh <= 5000:
return kWh*0.55
else:
return kWh*0.6
else:
print("Tipo de instalação inválida")
return 0
def main():
kWh, tipo = input_usuario()
print(f"O valor a pagar é R${calcular_consumo(kWh, tipo):.2f}")
if __name__ == '__main__':
main() | false |
5819146d616965a9e209615769bd33f7755d6c05 | tnakagaw22/Introduction-to-Computer-Science | /factorial.py | 491 | 4.125 | 4 | number = 5
def factorial(number):
if number == 1:
return 1
else:
return number * factorial(number -1)
result = factorial(5)
print(result)
def iterPower(base, exp):
result = 0
while exp > 0:
if result == 0:
result = base * base
else:
result = result * base
exp = exp - 1
if exp == 0:
return 1
else:
return base * iterPower(base, exp - 1)
result = iterPower(3,5)
print(result)
| true |
09823770fe971ca2c6505750ca422201c5110a20 | jswoodburn/Ex14 | /rps_functions.py | 1,361 | 4.28125 | 4 | import random
# get user input
def get_user_choice(question_string="\nEnter your choice (r, p, or s): ", acceptable_answer=['R', 'P', 'S']):
while True: # fails after 3 attempts?
user_choice = input(question_string)
if user_choice.upper() in acceptable_answer:
return user_choice.upper()
print(f"Your choice must be one of the letters: {', '.join(acceptable_answer)}.\n")
# convert user choice to word
def convert_user_choice(user_choice):
full_words = {'R': 'rock',
'P': 'paper',
'S': 'scissors'
}
return full_words[user_choice]
# generate random number
def generate_comp_choice():
comp_choice = random.randint(0, 2)
# convert number to computer choice
if comp_choice == 0:
return 'rock'
elif comp_choice == 1:
return 'scissors'
else:
return 'paper'
# ------------ compared with Michaela & Dolapo and realised a list would have been more optimal above.
win_condition = {
'rock': 'scissors',
'scissors': 'paper',
'paper': 'rock'
}
# compare choices/decide winner
def get_winner(user_choice, comp_choice):
if user_choice == comp_choice:
return [0, "It's a draw!"]
elif win_condition[user_choice] == comp_choice:
return [1, "You win!"]
else:
return [-1, "You lose..."]
| true |
9205e997af7767698016b14cfcd9fdd949f439a3 | manuel-garcia-yuste/ICS3UR-Assignmentb-Python | /assigment2b.py | 393 | 4.4375 | 4 | #!/usr/bin/env python3
# Created by: Manuel Garcia
# Created on: September 2019
# This program calculates the surface area of the cube
def main():
length = int(input("Enter the length of the cube: "))
# process
surface_area = 6*length**2
# output
print("")
print("The surface area of the cube is {:.2f} cm^2".format(surface_area))
if __name__ == "__main__":
main()
| true |
35dd6500c70a59c8b655acbfe2e2d8667fb51700 | ashar-sarwar/python-works | /python_practice/filing2.py | 720 | 4.125 | 4 | filename='pi.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi=''
for line in lines:
pi+=line.rstrip()
print(pi)
print(len(pi))
filename='pi.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi=''
for line in lines:
pi+=line.strip()
print(pi)
print(len(pi))
print(pi[:20])
#is your birthday in pi?
filename='pi.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi=''
for line in lines:
pi+=line.rstrip()
print(len(pi))
birthday=input("Enter your birthday, in the form ddmmyy: ")
if birthday in pi:
print("exists in 1st million digits of pi")
else:
print("Does'nt exists in 1st million digits of pi")
| true |
a1bb86465b14c847ce05c7e22eb87f123bed4d74 | youngminpark2559/prac_ml | /flearning/003_001_numpy_array.py | 2,739 | 4.25 | 4 | # 003_001_numpy_array
# ======================================================================
# Numpy manages data as array and performs operations in array
# At this moment, array can be considered as vector or matrix mathematically
# ======================================================================
import numpy as np
# np.array() can have list or other numpy array as arguments
# c data1: created list
data1=[5,5.4,9,0,1]
# c arr1: created numpy array using list
arr1=np.array(data1)
print(arr1)
# array([5. , 5.4, 9. , 0. , 1. ])
# c arr1: 1D array in Numpy or list perspectives, 5D vector mathematically
print(arr1.shape)
# (5,)
# 2D list
data2=[[5,5.4,9,0,1],
[3,5.2,5,2,0]]
arr2=np.array(data2)
print(arr2)
# array([[5. , 5.4, 9. , 0. , 1. ],
# [3. , 5.2, 5. , 2. , 0. ]])
# c arr2: 2D array in Numpy or list perspectives, (2,5) matrix mathematically
print(arr2.shape)
# (2, 5)
# ======================================================================
# (3,6) 2D array or (3,6) matrix filled with all 0s
print(np.zeros((3,6)))
# array([[0., 0., 0., 0., 0., 0.],
# [0., 0., 0., 0., 0., 0.],
# [0., 0., 0., 0., 0., 0.]])
# 10 length 1D array or 10 dimensional vector
print(np.ones(10))
# array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
# 15 length 1D array or 15 dimensional vector
print(np.arange(15))
# array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
# ======================================================================
# Numpy automatically sets datatype of elements in np array by using most wide datatype
print(arr1.dtype)
# dtype('float64')
print(arr2.dtype)
# dtype('float64')
# arr1 and arr2 has same wide datatype
# --------------------------------------------------
# You also can manually set datatype
# 64 means size of bit which each element in np array will use in memory
# When you need use larger datatype, you can use larger number
arr=np.array([1,2,3,4,5],dtype=np.int64)
print(arr)
# array([1, 2, 3, 4, 5])
print(arr.dtype)
# dtype('int64')
# ======================================================================
# You can change datatype which was already determined
# c float_arr: float datatype np array
float_arr=arr.astype(np.float64)
print(float_arr)
# [1. 2. 3. 4. 5.]
print(float_arr.dtype)
# float64
# ======================================================================
# Let's talk about operation in numpy
arr1=np.array(
[[1,2,3],
[4,5,6]],
dtype=np.float64)
arr2=np.array(
[[7,8,9],
[10,11,12]],
dtype=np.float64)
# Try these calculations
arr1+arr2
arr1-arr2
# Note that this performs element-wise multiplication,
# not matrix multiplication
arr1*arr2
arr1/arr2
arr1*2
arr1**0.5
1/arr1
| true |
1120102a7bd5bb2239193623ec7d0cbf2a06decd | andysain/_Project-Euler | /Problems/Problem019.py | 1,544 | 4.1875 | 4 | """You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?"""
def leap(year):
if year%4 != 0: return False
elif year%100 ==0 and year%400 != 0: return False
else: return True
def yearDays(year):
if leap(year): return 366
else: return 365
def monthDays(year):
days = [range(1,noMonthDays[M]+1) for M,month in enumerate(noMonthDays)]
if leap(year):
days[1].append(29)
return reduce(list.__add__,days)
def days(yearStart,yearEnd):
daysInYear = [monthDays(year) for year in range(yearStart,yearEnd+1)]
#print [range(1,day+1) for day in daysInYear]
list_ = reduce(list.__add__,daysInYear)
monthStart = startOfMonth(list_)
return dayName(monthStart)
def startOfMonth(daysList):
return [d for d,day in enumerate(daysList) if day ==1]
def dayName(monthStart):
return sum([1 for d in monthStart if daysofWeek[d] == 'Sun'])
noMonthDays = [31,28,31,30,31,30,31,31,30,31,30,31]
daysofWeek = ['Wed', 'Thu','Fri','Sat','Sun','Mon','Tue',]*5300
def First1901():
days1900 = yearDays(1900)
print daysofWeek[days1900]
#print First1901()
print days(1901,2000)
#print monthDays(1901) | true |
3dfb5ef5513de1172b741a69b154fde21d2ab84a | Aivrie/ping-pong | /pong.py | 2,893 | 4.1875 | 4 | # Procedural version of my ping pong game
'''
Ping Pong - A simple ping pong game built with procedural oriented programming coding style
'''
# Game 1 - Pong Game
import turtle
win = turtle.Screen()
win.title("Pong Game by Ivory")
win.bgcolor("white")
win.setup(width=800, height=600)
win.tracer(0)
# Score
score_a = 0
score_b = 0
# Game objects
# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("black")
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.penup()
paddle_a.goto(-350, 0)
# Paddle B
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("black")
paddle_b.shapesize(stretch_wid=5, stretch_len=1)
paddle_b.penup()
paddle_b.goto(350, 0)
# Pong Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("circle")
ball.color("black")
ball.penup()
ball.goto(0, 0)
ball.dx = 0.4
ball.dy = -0.4
# Pen
pen = turtle.Turtle()
pen.speed(0)
pen.color("black")
pen.penup()
pen.hideturtle()
pen.goto(0, 240)
pen.write("Player A:0 Player B:0", align="center", font=("Courier", 20, "normal"))
# Functions
# Paddle_a_up
def paddle_a_up():
y = paddle_a.ycor()
y += 20
paddle_a.sety(y)
# Paddle_a_down
def paddle_a_down():
y = paddle_a.ycor()
y -= 20
paddle_a.sety(y)
# Paddle_b_up
def paddle_b_up():
y = paddle_b.ycor()
y += 20
paddle_b.sety(y)
# Paddle_b_down
def paddle_b_down():
y = paddle_b.ycor()
y -= 20
paddle_b.sety(y)
# Calling the function on event
win.listen()
win.onkeypress(paddle_a_up, 'w')
win.onkeypress(paddle_a_down, 's')
win.onkeypress(paddle_b_up, 'Up')
win.onkeypress(paddle_b_down, 'Down')
# Main game loop
while True:
win.update()
# Move the ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Border blocking
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
if ball.ycor() < -290:
ball.sety(-290)
ball.dy *= -1
if ball.xcor() > 390:
ball.goto(0, 0)
ball.dx *= -1
score_a += 1
pen.clear()
pen.write("Player A:{} Player B:{}".format(score_a, score_b), align="center", font=("Courier", 20, "normal"))
if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1
score_b += 1
pen.clear()
pen.write("Player A:{} Player B:{}".format(score_a, score_b), align="center", font=("Courier", 20, "normal"))
# Paddle and Ball Collision
if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor() + 50 and ball.ycor() > paddle_b.ycor() - 50):
ball.setx(340)
ball.dx *= -1
if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle_a.ycor() + 50 and ball.ycor() > paddle_a.ycor() - 50):
ball.setx(-340)
ball.dx *= -1 | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.