blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
405b3a996998adc8c7cd1f6eeb6cd3d1c60ea4fb | green-fox-academy/judashgriff | /Week 3/Day 4/bunnies.py | 368 | 4.1875 | 4 | # We have a number of bunnies and each bunny has two big floppy ears.
# We want to compute the total number of ears across all the bunnies recursively (without loops or multiplication).
def get_bunny_ears(bunnies):
if bunnies == 1:
return 2
else:
return 2 + get_bunny_ears(bunnies-1)
bunnies = 562
ears = get_bunny_ears(bunnies)
print(ears) |
69a13a5414faea8ddb924b4acecc22af914fc1da | ElliottBarbeau/Leetcode | /Problems/2Sum.py | 1,743 | 3.5 | 4 | #Brute force
#Time complexity: O(N^2)
#Space complexity: O(1) -> this is outweighed by awful time complexity
class Solution1:
def twoSum(self, nums, target):
for i, num in enumerate(nums):
for j, num2 in enumerate(nums):
if num + num2 == target and i != j:
return [i, j]
#Two pass dictionary approach
#Time complexity: O(2N) == O(N)
#Space complexity: O(N) -> dictionary is worst case same size as # of integers in nums
class Solution2:
def twoSum(self, nums, target):
d = {}
for i in range(len(nums)):
d[nums[i]] = i
for i in range(len(nums)):
if target - nums[i] in d and d[target-nums[i]] != i:
return [d[target-nums[i]], i]
#One pass dictionary approach
#Time complexity: O(N)
#Space complexity: O(N) -> dictionary is worst case same size as # of integers in nums
class Solution3:
def twoSum(self, nums, target):
d = {}
for i in range(len(nums)):
complement = target - nums[i]
if complement in d:
return [d[complement], i]
else:
d[nums[i]] = i
#Left and right pointer approach
#Time complexity: O(NlogN)
#Space complexity: O(1)
#Trades off logN runtime for constant space
#This algorithm only works for the questions that ask for the numbers rather than the index
class Solution4:
def twoSum(self, nums, target):
nums.sort()
left, right = 0, len(nums) - 1
while left < right:
s = nums[left] + nums[right]
if s < target:
left += 1
elif s > target:
right -= 1
else:
return [nums[left], nums[right]] |
cc52f9c1da3ee39127b1014dabed5ac7c7e64e36 | aiko91/taskpart2 | /Part2task17.py | 901 | 3.609375 | 4 | def receive_complain (x):
with open(f'google_{x}.txt', 'a') as file:
file.write(input('Give your complain here: '))
print('Thank you!')
greetings = input('Say "Hello" ').lower().strip()
if greetings == 'hello':
print("""Hello! Pls, choice your office:
Kazakstan
Paris
UAR
Kyrgyzstan
San-Francisco
Germany
Moscow
Sweden""")
answer = input('').lower().strip()
if answer == 'kazakstan':
receive_complain(answer)
elif answer == 'paris':
receive_complain(answer)
elif answer == 'uar':
receive_complain(answer)
elif answer == 'kyrgyzstan':
receive_complain(answer)
elif answer == 'san-francisco':
receive_complain(answer)
elif answer == 'germany':
receive_complain(answer)
elif answer == 'moscow':
receive_complain(answer)
elif answer == 'sweden':
receive_complain(answer) |
fdb51cee9c0171864734fcc0657b7691f585fb58 | Shubhampy-code/Data_Structure_Codes | /LinkedList_Codes/circular_linkedlist.py | 1,269 | 3.984375 | 4 | class node:
def __init__(self,data):
self.data = data
self.next = None
class circular_linkedlist:
def __init__(self):
self.head = None
def printlist(self):
temp = self.head
if self.head != None:
while(temp):
print(temp.data)
temp = temp.next
if temp == self.head:
break
def push(self,number):
new_node = node(number)
temp = self.head
new_node.next = self.head
if self.head != None:
while temp.next!= self.head:
temp = temp.next
temp.next = new_node
else:
new_node.next = new_node
self.head = new_node
def delete(self,number):
temp = self.head
while (temp):
if self.head.data == number:
self.head = temp.next
break
elif temp.next.data == number:
temp.next = temp.next.next
break
temp = temp.next
cllist = circular_linkedlist()
#cllist.head = node(10)
cllist.push(9)
cllist.push(8)
cllist.push(7)
cllist.push(6)
cllist.delete(6)
cllist.printlist()
|
836f160e3f5872c0da48dae2d5fa76f89dde582f | ofgulban/minimalist_psychopy_examples | /future/csv_related/03_csv_read_organize_data_save_pickle.py | 933 | 3.765625 | 4 | """Basic text read, organize by column, create pickle."""
import csv
import pickle
csv_name = 'Test_01.csv'
pickle_name = 'Test_01.pickle'
# create empty arrays to append elements later
state_ide = []
state_dur = []
# read & display csv
file = open(csv_name)
data = csv.DictReader(file)
# instead of simple prints, append each relevant element to a list, then print
for row in data:
# change data type from string to integers (optional but will be useful)
state_ide.append(int(row['stimulus']))
state_dur.append(int(row['duration']))
file.close()
print 'Stimulus types : ', state_ide
print 'Stimulus durations: ', state_dur
# I prefer dictionary data structures for pickles
dictionary = {'Stimulus': state_ide, 'Duration': state_dur}
print dictionary
# Save the pickle
out = open(pickle_name, 'wb')
pickle.dump(dictionary, out)
out.close()
print 'Saved as: ' + pickle_name
|
38f453d960544b9f7031a86def569b541fa92deb | ezebunandu/Shopify-ds-internship-challenge | /etl.py | 825 | 3.578125 | 4 | import os
import sqlite3
import pandas as pd
from sqlalchemy import create_engine
DATA_PATH = "data/"
def copy_csv_to_table(conn, file, table):
"""Copies data from the file into the table using the insert_query"""
df = pd.read_csv(file, encoding='utf-8', quotechar='|')
engine = create_engine('sqlite:///orders_data.sqlite', echo=False)
df.to_sql(table, con=engine, if_exists="append", index=False)
tables = ["Customers", "Categories", "Employees", "OrderDetails",
"Orders", "Products", "Shippers", "Suppliers"]
files = [os.path.join(DATA_PATH, f"{table}.csv") for table in tables]
def main():
conn = sqlite3.connect("orders_data.sqlite")
for file, table in zip(files, tables):
copy_csv_to_table(conn, file, table)
conn.close()
if __name__ == "__main__":
main()
|
f74fc49767a9a5ca171f5a5fc14a27a651243632 | nikita1610/DSA_in_Python | /Sorting Techniques/Selection_Sort.py | 272 | 3.625 | 4 | def selection_sort(a):
n=len(a)
for i in range(n):
min=i
for j in range(i+1,n):
if a[min]>a[j]:
min=j
a[min],a[i]=a[i],a[min]
return a
l=[5,1,2,7,8,4,9,3,6]
ans=selection_sort(l)
print(*ans)
|
d5d7a7c7d77269533e93b21127ad1087d9265493 | Aasthaengg/IBMdataset | /Python_codes/p03496/s189029857.py | 1,737 | 3.625 | 4 | #!/usr/bin/env python3
import sys
INF = float("inf")
def argmax(a):
index, value = -1, -float("inf")
for i, v in enumerate(a):
if value < v:
index, value = i, v
return index, value
def argmin(a):
index, value = -1, float("inf")
for i, v in enumerate(a):
if value > v:
index, value = i, v
return index, value
def solve(N: int, a: "List[int]"):
# 正のみからなる数列に直す
amin_arg, amin = argmin(a)
amax_arg, amax = argmax(a)
ans = []
if abs(amin) <= abs(amax):
for i in range(N):
if a[i] < 0:
ans.append([amax_arg+1, i+1])
a[i] += amax
# すべて0以上の要素の数列となった
# print(a)
# 累積和の要領
for i in range(N-1):
if a[i] > a[i+1]:
ans.append([i+1, i+2])
a[i+1] += a[i]
# print(a)
else:
for i in range(N):
if a[i] > 0:
ans.append([amin_arg+1, i+1])
a[i] += amin
# すべて0以下の要素の数列となった。
# print(a)
# 累積和の要領
for i in range(N-1, 0, -1):
if a[i-1] > a[i]:
ans.append([i+1, i])
a[i-1] += a[i]
# print(a)
print(len(ans))
for a in ans:
print(*a)
return
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
a = [int(next(tokens)) for _ in range(N)] # type: "List[int]"
solve(N, a)
if __name__ == '__main__':
main()
|
5d93760a59301b1dcf67a694f833a2ac71aa6100 | ThiruMuth/DataScience-Python-Class-Exercises | /answeek2_exercise.py | 1,033 | 4 | 4 | def human2dog(dogageinhumanyr):
"""This function returns dog's age in human years"""
dogageindogyr=0.0
if(dogageinhumanyr)<=2:
dogageindogyr = dogageinhumanyr*10.5
else:
dogageindogyr = 2*10.5 + (dogageinhumanyr-2)*4
return dogageindogyr
def maxof3num(input_number_array):
""" This function returns the maximum of 3 numbers """
max = input_number_array[0]
for i in range(0,3):
if (max < input_number_array[i]):
max = input_number_array[i]
return max
def countupperlower(input_string):
"""This function returns the number of capital and lower in a string"""
capitalletters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
smallletters=capitalletters.lower()
CapitalCount=0
SmallCount=0
for i in range(0,len(input_string)):
if(capitalletters.find(input_string[i]) != -1):
CapitalCount = CapitalCount+1
elif(smallletters.find(input_string[i]) != -1):
SmallCount = SmallCount+1
return [CapitalCount,SmallCount]
|
0f934d221c233e5ebb4c030766600f8263640618 | A-xiaocai/store | /三角形.py | 468 | 3.96875 | 4 | a = int(input("a边为:"))
b = int(input("b边为:"))
c = int(input("c边为:"))
# 不能构成三角形的形成条件
if a+b<=c or a-b>=c :
print("不能构成三角形")
# 等边三角形形成条件
elif a==b==c:
print("等边三角形")
# 等腰三角形形成条件
elif a==b!=c or a==c!=b or b==c!=a:
print("等腰三角形")
elif a^2+b^2==c^2 :
print("直角三角形")
# 普通三角形形成条件
else :
print("普通三角形")
|
28c04385cd908f3562402e821d8f179c1631a102 | PressSergo/AlgoritmsPython | /nonukaz.py | 794 | 3.796875 | 4 | class list:
def __init__(self,i):
self.array = []
for k in range(3):
self.array.append([None for s in range(i)])
self.free = []
self.initFree()
self.current = None
def initFree(self):
for i in range(len(self.array[0])):
if self.array[0][i] == None:
self.free.append(i)
def add(self,s):
self.current = self.free.pop()
self.array[0][self.current] = s[0]
self.array[1][self.current] = s[1]
self.array[2][self.current] = s[2]
self.current = s[0]
self.initFree()
def __str__(self):
return "{}\n{}\n{}\n".format(self.array[0],self.array[1],self.array[2])
s = list(6)
print s
s.add((1,23,None))
s.add((3,56,1))
s.add((1,23,None))
print s |
cbe2bd8c4b1cf7a9fac23ca150c4505d6cb38c51 | yacih/education | /pon/instance.py | 997 | 4.15625 | 4 | # class IO類別名稱(首字英文大寫):
# supportedSrcs=["console","file"]定義封裝的變數
# def read(src):定義封裝的函數
# print("Read from",src)
#Point 實體物件的設計:平面座標上的點
class Point:
def ___init__(self,x,y):
self.x=x
self.y=y
p1=Point(7,8)
print(p1.x,p1.y)
p2=Point(5,6)
print(p2.x,p2.y)
# 實體物件的設計
class FullName:
def __init__(self,first,last):
self.first=first
self.last=last
n1=FullName("Y.C.","Hsieh")
print(n1.first,n1.last)
n2=FullName("B.H.","YA")
print(n2.first,n2.last)
class File:
def ___init__(self,name):
self.name=Name
self.file=None #尚未開啟檔案:初期事None
def open(self):
self.file=open(self.name,mode="r")
def read(self):
return self.file.read()
#讀取第一個檔案
f1=File("data1.txt")
f1.open()
data=f1.read()
print(data)
#讀取第二個檔案
f2=File("data2.txt")
f2.open()
data=f2.read()
print(data) |
3936229d6b6410c7115904ee6d273115d974f667 | jameygronewald/python_challenges | /guessing_game.py | 1,041 | 4.21875 | 4 | import random
random_num = random.randint(1, 9)
attempts = 1
guess_is_correct = False
while guess_is_correct == False:
try:
user_guess_string = input(f"Try to guess the random number from 1-9. Type your response and hit enter or respond with 'exit' to quit the game. ")
if user_guess_string == "exit":
break
user_guess = int(user_guess_string)
if user_guess in range(1, 10):
if user_guess == random_num:
print(f"You guessed it in {attempts} attempts! Good job.")
guess_is_correct = True
elif user_guess > random_num:
print(f"Your guess is too high. That was attempt number {attempts}. Try again.")
attempts += 1
else:
print(f"Your guess is too low. That was attempt number {attempts}. Try again.")
attempts += 1
else:
print('Please enter a valid integer guess.')
except ValueError:
print('Please enter a valid integer guess.') |
5ee901aada1284d912c5cd4e03024d2d8d98e847 | abhishekbunnan/test | /problem1.py | 252 | 3.859375 | 4 | a=int(input("enter the 1st no:"))
b=int(input("enter the 2nd no:"))
c=str(input("enter the type of operation:"))
if(c=="add"):
sum=a+b;
elif(c=="sub"):
sum=a-b;
elif(c=="mul"):
sum=a*b;
elif(c=="div"):
sum=a/b;
print(sum);
|
e1defa04c2165c19ded5ad8b174722cd1123d30a | sixthcodebrewer/PythonForKids | /Class 1/Hangman/Solution.py | 2,683 | 3.96875 | 4 | from turtle import *
import getpass
def turtle(x, y, color):
turtle = Turtle()
turtle.shape("turtle")
turtle.color(color)
turtle.speed(10)
turtle .pu()
turtle.goto(x, y)
turtle.pd()
return turtle
def init(hangman):
screen = Screen()
screen.setup(804, 608)
hangman.fd(50)
hangman.bk(25)
hangman.left(90)
hangman.fd(200)
hangman.right(90)
hangman.fd(70)
hangman.right(90)
hangman.fd(20)
def take_word(turtle):
word_dict = {}
my_word = getpass.getpass(" Enter your word for the other person to guess ")
for char in my_word:
word_dict[turtle.pos()] = char
turtle.pu()
turtle.write("_", True, align="center", font=("Arial", 30, "normal"))
turtle.fd(30)
turtle.pd()
return word_dict
def incorrect(turtle, attempt):
if (attempt == 0):
turtle.pu()
cu = turtle.pos()
turtle.goto(cu[0]-30, cu[1]-30)
turtle.pd()
turtle.circle(30)
turtle.pu()
turtle.goto(cu[0], cu[1]-60)
turtle.pd()
if (attempt == 1):
turtle.fd(80)
if (attempt == 2):
turtle.bk(40)
turtle.right(90)
turtle.fd(25)
if (attempt == 3):
turtle.bk(50)
turtle.pu()
turtle.fd(25)
turtle.left(90)
turtle.fd(40)
turtle.pd()
if (attempt == 4):
turtle.right(45)
turtle.fd(25)
if (attempt == 5):
turtle.bk(25)
turtle.left(90)
turtle.fd(25)
def correct(turtle, word_dict, guess):
total_guessed = 0
for pos, c in word_dict.items():
if (c == guess):
turtle.pu()
turtle.goto(pos[0], pos[1])
turtle.write(c, True, align="center", font=("Arial", 30, "normal"))
total_guessed+=1
return total_guessed
print ("Welcome to Hangman !!")
hangman = turtle(-250, -50, "black")
word = turtle(50, -50, "green")
init(hangman)
word_dict = take_word(word)
incorrect_guesses = 0
correct_guess = 0
guesses = []
while(correct_guess < len(word_dict.keys()) and incorrect_guesses < 6):
print(guesses)
character = input("Enter a character to guess ")
if (len(character) != 1):
print ("Please enter only one character to guess")
continue;
if (character in guesses):
print ("You already guessed that")
continue;
if (character in word_dict.values()):
correct_guess += correct(word, word_dict, character)
else:
incorrect(hangman, incorrect_guesses)
incorrect_guesses += 1
guesses.append(character)
final = turtle(0, -200, "red")
final.pu()
if (correct_guess == len(word_dict.keys())):
final.write("You guessed it !!", True, align="center", font=("Arial", 30, "normal"))
elif (incorrect_guesses == 6):
final.write("Sorry Chances are up !!", True, align="center", font=("Arial", 30, "normal"))
|
fed816d30aaf6a0a193a4761864fddd5488f1d8a | eddyxq/Intro-to-Computer-Science | /Full A5/manager.py | 3,448 | 3.890625 | 4 | # Author: Eddy Qiang
# Student ID: 30058191
# CPSC 231-T01
"""
Patch History:
Date Version Notes
June 16, 2017 Ver. 1.0.0 created the Target and Pursuer class
June 18, 2017 Ver. 1.0.1 defined methods that allows interaction
"""
"""
This program is a dating simulator between two fictional life forms called "The Tims". There are two types of Tims in
this simulation: a "Target" and a "Pursuer". The target is the object of the pursuer's desire. The behaviour of both
types of Tims is purely random. The date consists of a number of social interactions between two Tims broken down into
discrete time units. Each type of Tim will engage in one of two types of interactions: type X-behaviour and type
Y-behaviour. If the two Tims engage in the same type of interaction then that interaction is deemed as successful,
otherwise the interaction is deemed as a failure. A summary report will be generated after each interaction briefly
showing the result of the interaction for that time unit. At the end of the simulation a more detailed report will show
the overall results.
"""
import pursuer as p
import target as t
import random
# gets user input
# accepts integer input
# returns integer
def get_interaction():
try:
num = int(input("Enter the number of interactions (1 or greater): "))
if num > 0:
return num
else:
print("Do not enter non-numeric values")
num = get_interaction()
return num
except ValueError:
print("Do not enter non-numeric values")
num = get_interaction()
return num
# gets user input
# accepts integer input
# returns integer
def get_probability():
try:
num = int(input("Enter the percentage # of 'X' interactions for target (whole numbers from 0 - 100): "))
if num in range(0, 101):
return num
else:
print("Do not enter non-numeric values")
num = get_probability()
return num
except ValueError:
print("Do not enter non-numeric values")
num = get_probability()
return num
# manager function
def main():
X_BEHAVIOUR = "x"
Y_BEHAVIOUR = "y"
# create instances of target and pursuer
pursuer = p.Pursuer()
target = t.Target()
# get user input
num = get_interaction()
target.x_probability = get_probability()
# pursuer and target interacting
for x in range(num):
target_behaviour = target.interact()
pursuer_behaviour = pursuer.interact()
# determine and display result of interaction
result = pursuer.display_interaction_result(target_behaviour, pursuer_behaviour)
if result == True:
pursuer.successful_interaction += 1
elif result == False:
pursuer.fail_interaction += 1
# pursuer learns about the target
if target_behaviour == X_BEHAVIOUR:
pursuer.observed_x_behaviour += 1
elif target_behaviour == Y_BEHAVIOUR:
pursuer.observed_y_behaviour += 1
# pursuer AI adapts to match the target
pursuer.x_probability = pursuer.observed_x_behaviour/(pursuer.observed_x_behaviour + pursuer.observed_y_behaviour)*100
pursuer.y_probability = 100 - pursuer.x_probability
# display final results after all interactions
pursuer.display_simluation_result(target)
main() |
a15134895ba32fd09f79b3bdb09aa979699216a6 | vahidsediqi/Python-basic-codes | /Data-Structures/lists/list-unpacking.py | 299 | 3.9375 | 4 | number1 = list(range(3))
# it unpack out list in save them in sprat variable
first, second, third = number1
print(second)
# if we have so money items we can do like this
number2 = [1,2,5,2,3,5,8,6,5,9,5,7,5,6,5,8,5,6]
# can only stor some of them
a, b, c, *others = number2
print(others)
print(a) |
493d67ed0078e1e4604892ae359dd536882d7162 | JoRoPi/Udacity | /CS253/Pruebas/src/Classes.py | 1,001 | 4.21875 | 4 | # This Python file uses the following encoding: utf-8
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
"""An other comment"""
return 'hello world'
def __init__(self):
"""This is the class init method, similar to a constructor"""
self.data = []
print MyClass.i
print MyClass.f
print MyClass.__doc__
print MyClass.f.__doc__
x = MyClass()
print x.i
print x.f
print x.__doc__
print x.f.__doc__
print x.data
# Añadimos por la cara un atributo, data attribute, a la instancia que al final eliminamos.
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print x.counter
del x.counter
print x.__class__
class BaseClass(object):
def __init__(self):
print "This is the BaseClass"
class DeriveClass(BaseClass):
def __init__(self):
#BaseClass.__init__(self)
super(BaseClass,self).__init__()
print "This is the DeriveClass"
y = DeriveClass()
print y.__class__
print type(y)
|
a1a894a8e5510990006aa78c32cbd591f90b06fc | tangkaiq/uclass | /w3/lc.py | 537 | 4.03125 | 4 | '''
#ex1
lst = [1,2,3,4,5]
[element+5 for element in lst]
'''
'''
#ex2
for pair in (zip([1],[3,4])):
print(pair)
'''
'''
#ex3
x=[1,2]
y=[3,8]
print([a*b for a,b in zip(x,y)])
'''
'''
#ex4
print([(x,y) for x in range(2) for y in range(3)])
'''
'''
#ex5
lst = [1,2,3,4]
less2 = [num for num in lst if (num<2)]
print(less2)
'''
'''
#ex6
def is_even(x):
return x%2==0
print(list(filter(is_even,[1,2,3,4])))
'''
'''
#ex7
def is_even(x):
return x%2==0
print(['even' if is_even(x) else 'odd' for x in [1,2,3,4,5,6]])
'''
|
16618b6cbb02a802756c51c18fdd4b437275e7f9 | qiqimaochiyu/tutorial-python | /leetcode/subsets(回溯).py | 301 | 3.609375 | 4 | class Solution:
"""
@param nums: A set of numbers
@return: A list of lists
"""
def subsets(self, nums):
# write your code here
res = [[]]
nums.sort()
while nums:
a = nums.pop(0)
res += [p+[a] for p in res]
return res
|
19c164445d338f87cebd1577d89d087b4e6f61ce | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day06/demo02.py | 814 | 4.53125 | 5 | """
元组
基础操作
"""
# 1.创建元组
# 空
tuple01 = ()
# 具有默认值
tuple01 = (1, 2, 3)
print(tuple01)
# 列表 --> 元组
tuple01 = tuple(["a", "b"])
print(tuple01)
# 元组 --> 列表
list01 = list(tuple01)
print(list01)
# 如果元组只有一个元素
# tuple02 = 100
# print(type(tuple02)) # int
tuple02 = (100,)
print(type(tuple02)) # tuple
# 不能变化
# tuple02[0] = 10
# 2.获取元素(索引 切片)
tuple03 = ("a", "b", "c", "d")
e01 = tuple03[1]
print(type(e01)) # str
e02 = tuple03[-2:]
print(type(e02)) # tuple
# 可以直接将元组赋值多个变量
tuple04 = (100, 200)
a, b = tuple04
print(a)
print(b)
# 3.遍历元素
# 正向
for item in tuple04:
print(item)
# 反向
# 1 0
for item in range(len(tuple04)-1, -1, -1):
print(tuple04[item])
|
d1a286d32b6fc1782fa9517859585b02f1dd302a | abc123me/nasa_dsn | /cli/ui.py | 3,720 | 3.9375 | 4 | def clearTerm():
print(chr(27) + "[2J" + chr(27) + "[0;0H", end = "")
def doNothing(selection):
pass
'''
Are you sure you would like to continue? [y/N]
The message parameter determines the message
Returns True if yes, False if no
'''
def areYouSure(message = "Are you sure you would like to continue [y/N]? "):
response = input(message)
response = response.strip()
if(response.startswith("y") or response.startswith("Y")):
return True
return False
'''
Menu header goes here:
0 - Option: OptionDesc
1 - Option: OptionDesc
2 - Option: OptionDesc
3 - Option: OptionDesc
Prompt goes here? The MenuEntry selected is returned, or None if the value is invalid
Options are specified by an array of MenuEntry objects:
Description can be None to just print the name
If the name and description are None, then the description is printed without actually being an option
If both the Description and Name are None a newline will be printed
If the event of the menu entry it will be called if that entry is selected
If the customHead is set then it will be used instead of the objHead variable of the menu() function
If the areYouSure variable is True then an "Are you sure" prompt will be shown
repeatOnError: can be set to True to repeat if the user enters an invalid response (default True)
repeatNormally: can be set to True to repeat even if the user enters a valid response (default False)
clear: can be set to True to also clear the terminal (default False)
objHead: can be set to whatever and it will add a prefix to the option (default " ")
onSelect: can be set and will be called with a the selected MenuEntry (default doNothing)
'''
class MenuEntry:
def __init__(self, name, desc = None, event = None, customHead = None, areYouSure = False):
self.name = name
self.desc = desc
self.event = event
self.areYouSure = areYouSure
self.customHead = customHead
#I spent WAY too much time on this
def menu(header, entries, prompt, repeatNormally = False, repeatOnError = True, clear = False, objHead = " ", onSelect = doNothing):
while(True):
#Print the menu
if(clear):
clearTerm()
print(header)
m = type(MenuEntry("menu" , "entry"))
visibleEntries = []
entryId = 0
for e in entries:
if(type(e) != m):
raise TypeError("Invalid type! Must be a MenuEntry object!")
head = objHead
#Custom head
if(e.customHead != None):
head = e.customHead
#Custom sub-headings/newlines
if(e.name == None or (not e.name)):
if(e.desc == None or (not e.desc)):
print()
else:
print(head + e.desc)
continue
#Typical application
head = head + str(entryId) + " - "
if(e.desc == None or (not e.desc)):
print(head + e.name)
else:
print(head + e.name + ": " + e.desc)
visibleEntries.append(e)
entryId = entryId + 1
#User input handling
response = input(prompt)
selection = -1
error = True
try:
selection = int(response)
if(selection < 0 or selection >= len(visibleEntries)):
raise IndexError
error = False
except ValueError:
print("Selection must be a number")
except IndexError:
print("Invalid selection (out of range)")
#Error handling
if(error or selection < 0):
if(not repeatOnError):
return None
else:
continue
#Is the user sure of there decision
if(visibleEntries[selection].areYouSure):
if(not areYouSure()):
return None
#Call the event handlers
if(visibleEntries[selection].event != None):
visibleEntries[selection].event()
onSelect(visibleEntries[selection])
#Repeat or not repeat
if(repeatNormally):
continue
else:
return visibleEntries[selection]
|
1091343454119c08848b559682f0147aae30bfc0 | arthuregood/Ports-Scanner | /scanner.py | 1,085 | 3.59375 | 4 | #! /bin/python3
import sys
import socket
from datetime import datetime
#define target
if len(sys.argv) == 2:
target = socket.gethostbyname(sys.argv[1])
else:
print("Invalid number of elements.")
print("Syntax: python3 scanner.py <ip>")
sys.exit()
#just pretty ok
print("-" * 30)
print(f"scanning {target}")
print(f"Start: {(datetime.now().time().replace(microsecond=0))}")
print("-" * 30)
try:
flag = True
for port in range(50,85):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = s.connect_ex((target, port)) #return an error indicator
if result == 0:
print("Port {} is open".format(port))
flag = False
s.close
if flag:
print("No ports are open")
print(f"Stop: {(datetime.now().time().replace(microsecond=0))}")
except KeyboardInterrupt:
print("\nClosing program.")
sys.exit()
except socket.gaierror:
print("\nHostname was not found.")
sys.exit()
except socket.error:
print("\nIt was not possible to connect to the server.")
sys.exit()
|
3f01a366f95bcf5ce65999da87c719a0eefd7a75 | syedmujahedalih/LeetCode-Submissions | /sortedSquaresarray.py | 272 | 3.859375 | 4 | '''
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
'''
class Solution:
def sortedSquares(self, A):
res = [i**2 for i in A]
return sorted(res) |
ee8031fddd50cce13e9ba7fdef74f96457bf4ef5 | PrakharimaSingh/prakharimasingh | /program1.py | 253 | 3.625 | 4 | name=inpu("enter name:")
gender=("enter gender:")
branch=input("enter branch:")
college=("enter college:")
age=int(input("enter age:")
print("name: ", name)
print("gender: ",gender)
print("branch: ",branch)
print("college: ",college)
print("age: ",age)
|
268302f0d9446252fc016b5461ab45cd35843247 | aats0123/su_python_fundamentals | /E02_lists/p07_remoce_negative_and_reverse.py | 366 | 3.65625 | 4 | if __name__ == '__main__':
nums = [int(value) for value in input().split()]
positive_nums = []
for num in nums:
if num >= 0:
positive_nums.append(num)
if len(positive_nums) > 0:
positive_nums.reverse()
message = ' '.join([str(item) for item in positive_nums])
else:
message = 'empty'
print(message) |
c6c44313c22db6d937d4e5d4fe2aecc34f2eb18b | a865143034/mini-dfs | /ceshi.py | 197 | 3.546875 | 4 | #coding:utf-8
siz=1024*1024*2
def read_bigFile():
f = open("text1",'r')
cont = f.read(1)
while len(cont) >0 :
print(cont)
cont = f.read(1)
f.close()
#read_bigFile() |
4b4e7b3ed7912caea40d038731e23c2068f89551 | MrinmoySonowal/Small-Projects | /Leetcode/OneEditAway.py | 1,215 | 3.59375 | 4 | def oneEditReplace(s1: str, s2: str) -> bool:
found_diff_char = False
for i in range(len(s1)):
if s1[i] != s2[i]:
if found_diff_char:
return False
else:
found_diff_char = True
return True
def oneEditInsert(larger_text: str, smaller_text: str) -> bool:
i = 0
j = 0
found_diff_char = False
while i < len(smaller_text) and j < len(larger_text):
if larger_text[j] != smaller_text[i]:
if i != j:
return False
else:
j += 1
continue
i += 1
j += 1
return True
def is_one_edit_away(s1: str, s2: str) -> bool:
s1_len, s2_len = len(s1), len(s2)
if abs(s1_len - s2_len) > 1:
return False
elif s1_len == s2_len:
return oneEditReplace(s1, s2)
elif s1_len > s2_len:
return oneEditInsert(s1, s2)
else:
return oneEditInsert(s2, s1)
if __name__ == '__main__':
print(is_one_edit_away("paincccccc", "vain"))
print(is_one_edit_away("pain", "vain"))
print(is_one_edit_away("pain", "pin"))
print(is_one_edit_away("pan", "pain"))
print(is_one_edit_away("van", "pain"))
|
56d333b9af01f0e1eeedac863a93e0dc67c14ea2 | TUTElectromechanics/mm-codegen | /modelbase.py | 6,049 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Interface for models.
See splinemodel.py for a real-world usage example.
Created on Thu Nov 9 10:39:51 2017
@author: Juha Jeronen <juha.jeronen@tut.fi>
"""
from abc import ABCMeta, abstractmethod
import sympy as sy
from sympy.core.function import UndefinedFunction
import symutil
class ModelBase:
"""Abstract base class for mathematical models supported by this software."""
__metaclass__ = ABCMeta
@abstractmethod
def define_api(self):
"""Define stage1 functions.
What to define in stage1? For example:
- Quantities which have analytical expressions.
- Quantities that depend on other quantities, in a treelike fashion.
Useful for building a layer cake of auxiliary variables, while
keeping the definitions at each level as simple as possible.
- Quantities that depend on derivatives of other quantities. E.g. if
"∂f/∂x" appears on the RHS of some other quantity, and an LHS "f"
has been defined, then stage1 will automatically derive ∂f/∂x by
differentiating the RHS of "f", and add it to the definitions.
- Chain rule based expressions for the derivatives of a function,
represented as a SymPy applied function (i.e. unspecified function,
but with specified dependencies), in terms of other SymPy applied
functions, and at the final layer, in terms of independent variables.
So we can have a potential ϕ(u, v, w), where the auxiliary variables
u, v, w depend on some other auxiliary variables, and so on, until
(several layers later) the independent variables are reached.
We can then declare the stage1 functions as the derivatives of
this ϕ w.r.t. the **independent** variables. Given the layer cake
definition of ϕ as an applied function, SymPy automatically applies
the chain rule.
The potential ϕ itself can, but does not need to, be declared here.
If you have a custom Fortran code to compute ϕ, ∂ϕ/∂u, ∂ϕ/∂v, etc.,
just tell stage2 about its interface, and those functions will be
considered as stage1 (on equal footing with any generated code).
LHS is a symbol, which is used to generate the name of the API function.
stage1 automatically invokes ``symutil.derivatives_to_names_in()``
and ``util.degreek()`` to make a Fortran-compatible name.
The LHS names are also used for lookup when generating the derivatives.
Use ``keyify()`` to convert something into an LHS key.
RHS is a SymPy expression; applied functions can be used here if needed.
CAUTION:
To reliably make LHS names for derivatives, first use an applied
function (with the desired dependencies), differentiate that,
and finally keyify the result. This is required, because strictly
speaking, for bare symbols ∂x/∂x = 1 and ∂y/∂x = 0 for all y ≠ x.
Example. Given:
from functools import partial # (partial application, not ∂!)
import sympy as sy
D = partial(sy.Derivative, evaluate=False)
Even with evaluate=False, we get:
f, x, y = sy.symbols("f, x, y")
d2fdxdy = D(D(f, x), y) # --> 0
Do this instead:
import symutil
x, y = sy.symbols("x, y")
f = symutil.make_function("f", x, y)
d2fdxdy = D(D(f, x), y) # --> now ok (just D(f, x, y) also ok)
name = ModelBase.keyify(d2fdxdy) # --> "Derivative(f, x, y)"
The same strategy for name generation applies also to layer cakes:
g = symutil.make_function("g", f)
dgdf = D(g, f) # --> ok, Derivative(g(f(x)), f(x))
name = ModelBase.keyify(dgdf) # --> "Derivative(g, f)"
dgdx_name = ModelBase.keyify(D(g, x)) # --> "Derivative(g, x)"
dgdx_expr = (sy.diff(g, x)).doit() # --> Derivative(f(x, y), x)*Derivative(g(f(x, y)), f(x, y))
In the last example, the .doit() changes the format of the result
to standard notation. For more complex expressions which may have
unevaluated substitution objects nested anywhere in them, see
``symutil.apply_substitutions_in()``. See explanation and example
in ``potentialmodelbase.PotentialModelBase.dϕdq()``.
Abstract method, must be overridden in a derived class.
Must return:
dictionary of ``sy.Symbol`` -> ``sy.Expr``
key: LHS, value: RHS
"""
raise NotImplementedError("Abstract method; must be overridden in a derived class")
def simplify(self, expr):
"""Simplify expressions used by this model. Generic fallback.
Derived classes may override this to provide a specific simplifier
that works particularly well with their particular expressions.
"""
return sy.simplify(expr)
@staticmethod
def keyify(expr):
"""Convert expr into a key suitable for the LHS of a definition.
Parameters:
expr: sy.Symbol, sy.Derivative or a SymPy applied function
``symutil.make_function()`` makes applied functions.
Returns:
expr converted to a key.
"""
# the type of an applied function is an instance of UndefinedFunction.
if not isinstance(expr, (sy.Symbol, sy.Derivative)) and \
not isinstance(expr.__class__, UndefinedFunction):
raise TypeError("Expected symbol, derivative or applied function; got {} {}".format(type(expr), expr))
if isinstance(expr, sy.Derivative):
expr = symutil.canonize_derivative(expr) # we assume at least C^k continuity.
return symutil.strip_function_arguments(expr)
|
0c67b1c9f07a7779dd4ec1af65050cffd0286a0d | samhita101/Python-Practice | /User_Age_DOB.py | 305 | 4.03125 | 4 | import datetime
print("Please enter your name after the colon:")
users_name = str(input())
print("Enter the year you were born:")
users_DOB = int(input())
print("Here is the year you will turn 100 in.")
print(users_DOB + 100)
print("You will turn 100 in this many years:")
print(users_DOB + 100 - 2020)
|
ca9b25d13200ee0c4c6dfd8d221dd7b1c16f4b4b | kolavcic/Basic-Python_Code | /Code Academy/4. cas/zadatak10.py | 448 | 3.96875 | 4 | # Napisati program koji za uneti pozitivan ceo broj n, ispisuje zvezdice i tako iscrtava odgovarajuću sliku.
# Slika predstavlja pravougli trougao sastavljen od zvezdica.
# Kateta trougla je dužine n, a prav ugao nalazi se u gornjem desnom uglu slike.
n = int(input("Unesite broj: "))
for red in range(0, n+1):
for kolona in reversed(range(0, red)):
if red == n:
print("*",end="")
red = red - 1
print() |
02401ed3d204d84e9544907b1aac7e1c7efc51e9 | KamalAres/HackerRank | /ProblemSolving/Python/2DArrayDS.py | 827 | 3.75 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'hourglassSum' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def hourglassSum(arr):
# Write your code here
sum = -63
for i in range(4):
for j in range(4):
val = arr[i+0][j+0] + arr[i+0][j+1] + arr[i+0][j+2] + arr[i+1][j+1] + arr[i+2][j+0] + arr[i+2][j+1] + arr[i+2][j+2]
print(val)
if val > sum:
sum = val
return sum
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
result = hourglassSum(arr)
fptr.write(str(result) + '\n')
fptr.close()
|
8f75f61e237432e049a9e925b061ab1e07e656dc | Vincent105/python | /01_Python_Crash_Course/0901_class/favorite_languages.py | 414 | 3.984375 | 4 | from collections import OrderedDict
favorite_languages = OrderedDict() #此Method將創建一個有序字典
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['vincnet'] = 'python'
print(favorite_languages)
for name, language in favorite_languages.items():
print(name.title()+ " 's favorite is " + language.title() + '.')
|
45df217510730605b7d6366944e49a543d506e91 | M4ttoF/Misc. | /HackerRank/Cracking The Coding Interview/Stacks Balanced Brackets.py | 513 | 3.953125 | 4 | def is_matched(expression):
pass
dic1={'}':'{',')':'(',']':'['}
arr=[]
for c in expression:
if c in dic1:
if arr==None or len(arr)==0:
return False
c2=arr.pop(0)
if not c2==dic1[c]:
return False
else:
arr.insert(0,c)
return True
t = int(input().strip())
for a0 in range(t):
expression = input().strip()
if is_matched(expression) == True:
print("YES")
else:
print("NO")
|
76b5bc08efb5632fa13329ad59b4582365f22031 | ManzanasMx/git-prueba | /prueba.py | 279 | 4 | 4 | #Lectura de Datos Flotantes
a=float(input("ingresa valor de A:"))
b=float(input("ingresa valor de B:"))
#Operaciones
c=a+b
c1=a-b
c2=a*b
c3=a/b
#Impresion de resultado5
print("RESULTADO")
print"suma:",c
print"resta:",c1
print"multiplicacion:",c2
print"division:",c3
print"\n"
|
c7355ed714d4c7f28949f2ad15a763a9c3b5b043 | sandyrepswal/MyProject | /Main/Utility/SortingAlgos.py | 2,511 | 3.859375 | 4 | class SortingAlgos:
def bubbleSort(self,inpArr):
for i in range(0,len(inpArr)):
for j in range(0,len(inpArr)-1-i):
if inpArr[j]>inpArr[j+1]:
temp=inpArr[j]
inpArr[j]= inpArr[j+1]
inpArr[j+1]=temp
def printSortArr(self,inpArr):
for i in range(0, len(inpArr) - 1):
print(inpArr[i])
def callmergeSort(self,inpArr):
self.mergeSort(inpArr,0,len(inpArr)-1)
def mergeSort(self, inpArr, start, end):
mid =(start +end)//2
if start< mid:
self.mergeSort(inpArr,start,mid)
if mid+1 <end:
self.mergeSort(inpArr,mid+1,end)
#
# if start == mid:
# print(f'left array is {inpArr[start]}')
# else:
# print(f'left array is {inpArr[start:mid]}')
#
# if mid+1 == end:
# print(f'right array is {inpArr[mid+1]}')
# else:
# print(f'right array is {inpArr[mid + 1:end]}')
print(f'start is {start} , mid is {mid}, end is {end}')
i=start
j=mid+1
tmpArr =[]
while(i<=mid ):
# print(f'left value is {inpArr[i]} and right value is {inpArr[mid+1]}')
# if inpArr[i] >inpArr[mid+1]:
# temp=inpArr[i]
# inpArr[i] = inpArr[mid+1]
# inpArr[mid + 1] = temp
if j <=end and inpArr[i] >inpArr[j] :
tmpArr.append(inpArr[j])
j=j+1
else:
tmpArr.append(inpArr[i])
i = i + 1
while(len(tmpArr)<end-start+1):
tmpArr.append(inpArr[j])
j=j+1
l=start
length = len(tmpArr)
for k in range(0,length):
inpArr[l]=tmpArr[k]
l=l+1
# print(f'after merge temp array is :{tmpArr}')
print(f'after merge array is :{inpArr}')
testVar = SortingAlgos()
inpArray =[ 9,2,32,19,181,-200,0,20,4,6,34,78,95,40,0,0,-32768]
inpArray =[ 0,0,0,0,0,0,-3,0,0,0,00,0,0,0,0,0,0,-2,0,000,]
inpArray =[ 10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
inpArray =[ 110,90,80,70,60,50,40,30,20,100,5000,-12345,1,2,3,4,5,6,7,8,9,10,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
print(type(inpArray))
print(inpArray)
#testVar.bubbleSort(inpArray)
testVar.callmergeSort(inpArray)
print("After sorting")
#print(inpArray)
testVar.printSortArr(inpArray)
print("""current value is:\
testing multi lines""") |
ed6fd54b796032dc241b1abaf0e00c5dceb30b33 | mingyue33/python_base | /09-类和对象2/i上课代码/07-类属性.py | 590 | 3.8125 | 4 | class Cat(object):
#设计一个类
#1. 类名
#2. 属性
#3. 方法
#类属性
num = 0
def __init__(self):
#实例属性
self.age = 1
#如果类属性的名字和实例属性的名字相同,那么
#通过对象去获取num的时候,那么会获取实例属性的值
self.num = 100
#方法
def run(self):
print("-----猫 在跑----")
mao = Cat()
#用对象去访问类属性是可以的
print(mao.num)
#常用的方式是,使用类去访问类属性
print(Cat.num)
Cat.num+=1
print(Cat.num)
|
09c0d3a4db54bd9a0a606087a9315e82bc45ed69 | rodrigobmedeiros/Coursera-Introdution-To-Scientific-Computing-With-Python | /Exercises/ImparPar.py | 146 | 3.890625 | 4 | numero = int(input('Entre com um numero inteiro: '))
RestoDivisao = numero%2
if RestoDivisao ==0:
print('par')
else:
print('impar')
|
a533542a9d211d911386f50e2dbba6e0b87b8731 | gasgit/OOPYTHON | /UniT/my_unit_test.py | 839 | 3.671875 | 4 | #!/usr/bin/python
import unittest
''' funcs to test'''
def square(val):
return val * val
def whatAmI(val):
return val
class MyFirstTest(unittest.TestCase):
''' test func sq pass'''
def test_pass(self):
self.assertEqual(square(2),4)
''' test func sq fail'''
def test_fail(self):
self.assertEqual(square(3),10)
''' test param is alpha'''
def test_val_string(self):
self.assertTrue(whatAmI('iamstring').isalpha())
''' test is upper'''
def test_upper(self):
self.assertTrue(whatAmI('HELLO').isupper())
''' test is ! upper'''
def test_not_upper(self):
self.assertTrue(whatAmI('hello').isupper())
''' test param digit'''
def test_val_num(self):
self.assertTrue(whatAmI('2').isdigit())
if __name__ == '__main__':
unittest.main() |
203a782a278e5966618243ea55f20022b5462133 | a-poorva/testingdemo | /minus.py | 71 | 3.65625 | 4 | def subtract(a, b):
return a - b
a = 4
b = 5
print(subtract(a,b))
|
ed90f21f54e50f01334f2349db540b4f9767f553 | heloisaldanha/PythonExercises | /CursoEmVideo/Mundo_2/Aula #13 - Repetições/aula013_exe#53.py | 170 | 4 | 4 | # saber se o que foi digitado, ao contrário, é a mesma coisa.
phrase = input('Type a phrase: ').strip().upper()
for c in range(len(phrase) - 1, - 1, - 1):
print(c) |
4389ce35b9e5557537a592ed01d6659bdf937be3 | lucthomas/myRepository | /Python/Trading Machine Learning/trade_code5.py | 1,708 | 3.734375 | 4 | '''Build a dataframe in pandas'''
import pandas as pd
def test_run():
#Create dates
start_date = '2010-01-22'
end_date = '2010-01-26'
dates = pd.date_range(start_date,end_date)
print(dates)
print(dates[0])
#Create an empty dataframe
df1 = pd.DataFrame(index=dates)
print(df1)
#Read SPY data into temporary dataframe and change its index to dates rather than 0,1,2,...
#Only use the columns of the csv we're interest in and indicata that nan are not a number
dfSPY = pd.read_csv("data/SPY.csv",index_col="Date",parse_dates=True,usecols=['Date','Adj Close'],na_values=['nan'])
#Rename 'Adj Close' column to 'SPY' to prevent a clash
dfSPY = dfSPY.rename(columns={'Adj Close':'SPY'})
#Join the two dataframes using DataFrame.join()
#df1 = df1.join(dfSPY)
#Drop the NaN values
#df1 = df1.dropna()
#Refactor join and drop of NaN values which happens when you only keep the dates common to both columns (df1 and dfSPY)
df1 = df1.join(dfSPY,how='inner')
print(df1)
#Read in more stocks
symbols = ['GOOG','IBM','GLD']
for symbol in symbols:
df_temp = pd.read_csv("data/{}.csv".format(symbol),index_col="Date",parse_dates=True,usecols=['Date','Adj Close'],na_values=['nan'])
#Rename 'Adj Close' column to symbol to prevent a clash
df_temp = df_temp.rename(columns={'Adj Close': symbol})
df=df1.join(df_temp) #Use default how='left'
print(df)
#Note that we are using a couple of methods a couple of times
#This is not nice programming
#Let's put this into utility functions that we can use afterwards (see trade_code6.py)
if __name__ == "__main__":
test_run()
|
a399ef5d20f8837629e27deec4a7b8d8132021d5 | yandryvilla06/python | /ejercicios_b2/eje3.py | 321 | 3.984375 | 4 | """
Ejercicio 3. Programa que compruebe si una variable esta vacia
y si esta vacia , rrellenarla con texto en minusculas y mostrarlo en mayusculas
"""
valor=""
if not valor:
print("Esta vacia")
rrelleno=input(" Dime algo para rrellenarla ").lower()
print(rrelleno.upper())
else:
print("variable llena") |
77ae35a8cc1edd652192e984161e29692b40a040 | chekhov4/Python-lessons | /ksr-8.py | 574 | 3.984375 | 4 | def find_biggest_in_array(source_array):
all_values = []
def expand(source_array):
for i in range(len(source_array)):
if type(source_array[i]) == list:
expand(source_array[i])
else:
all_values.append(source_array[i])
expand(source_array)
all_values = sorted(all_values, reverse= True)
return all_values[0]
if __name__ == '__main__':
source_array = [[[2,-7,-6],[-9,-5,-1],[-4,-3,-8]],[[-2,3000,-6],[-9,-5,-1],[-4,-3,-8]]]
find_biggest_in_array(source_array)
|
26311bcbdc664f353a75f755b496e94a7e916fe4 | pzp1997/Heschel-CS | /Math/Fibonacci Generator.py | 104 | 3.8125 | 4 | x = 1
y = 1
z = 1
print ("0")
print (x)
print (y)
while True:
print (x+y)
z=x
x=y
y=z+x
|
877168a842feb58575a09c9d1a4aeb3cea0b21be | dukeofdisaster/HackerRank | /Staircase.py | 379 | 4.28125 | 4 | # STAIRCASE---
# Given an integer N, print a staircse of N steps high and N steps wide.
# Ex: Given N = 3
# output: #
# ##
# ###
import sys
n = int(input())
def staircase():
space = " "
tempVal = n
stairSize=1
for i in range(n):
print(space * ((tempVal)-1) + '#'*stairSize)
stairSize += 1
tempVal-= 1
staircase()
|
b1efabac78b858c36868ea2c0f8e292264748a8f | Xvpher/PracticeCodes | /C++/udaan.py | 2,462 | 3.9375 | 4 | '''
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''
import pandas as pd
import numpy as np
df = pd.DataFrame(columns=['name','seats','aisle'])
def addScreen(name, rows, cols, aisle):
dic = {'name':name, 'seats':np.zeros((rows,cols)), 'aisle':(aisle,)}
df.append(dic)
print("success")
return
def reserve(name, row, seat):
df_1 = df.loc[df['name'] == name]
mat = df_1['seats']
for item in seat:
if(mat[row][item-1] == 1):
print("failure")
return
mat[row][item-1] = 1
print("success")
return
def getSeats(name, row):
df_1 = df.loc[df['name'] == name]
mat = df_1['seats']
for pos,item in enumerate(mat[row]):
if(item ==0):
print (pos+1+" ",)
return
def getCont(name, num, row, ch):
flag1=0
flag2=0
df_1 = df.loc[df['name'] == name]
mat = df_1['seats']
aisle = df_1['aisle']
fis = mat[row][ch-num:ch]
sec = mat[row][ch-1:ch+num-1]
x = list(set(aisle) & set(list(range([ch-num+1,ch+1]))))
if(len(x)>2):
flag1=1
if(len(x)==2 and abs(x[1]-x[0])==1):
flag1=1
x = list(set(aisle) & set(list(range([ch,ch+num]))))
if(len(x)>2):
flag2=1
if(len(x)==2 and abs(x[1]-x[0])==1):
flag2=1
if(flag1==1 and flag2==1):
print("none")
elif(1 in fis and 1 in sec):
print("none")
elif(1 in fis and flag2==1):
print("none")
elif(1 in sec and flag1==1):
print("none")
elif(1 in fis):
print(list(range(ch-1,ch+num-1)))
else:
print(list(range(ch-num,ch)))
return
def main():
test = int(input())
while(test>0):
comm = input().split()
if(comm[0] == "add-screen"):
addScreen(str(comm[1]), int(comm[2]), int(comm[3]), [int(x) for x in comm[4:]])
elif(comm[0] == "reserve-seat"):
reserve(str(comm[1]), int(comm[2]), [int(x) for x in comm[3:]])
elif(comm[0] == "get-unreserved-seats"):
getSeats(str(comm[1]), int(comm[2]))
elif(comm[0] == "suggest-contiguous-seats"):
getCont(str(comm[1]), int(comm[2]), int(comm[3]), int(comm[4]))
else:
print("error")
test-=1
if __name__=='__main__':
main()
|
5df383dd0a3677e70c7dbea5c8790e94d50aad90 | MrMyerscough/Coding-Course-Stuff | /python/unit 5/test.py | 2,032 | 4.21875 | 4 | class Dog:
def __init__(self, name, age, color):
self.name = name
self.age = age
self.color = color
self.tricks = []
def introduce(self):
print(f'Hello! My name is {self.name}. I am {self.age} years old. My fur is {self.color}.')
print(f'I know {len(self.tricks)} trick(s):')
for trick in self.tricks:
print(trick)
def learn_trick(self, trick):
self.tricks.append(trick)
class AnimalShelter:
"""Holds found dogs for adoption."""
def __init__(self):
self.dogs = []
def add_dog(self, dog):
"""Add dog to animal shelter."""
self.dogs.append(dog)
def adopt_dog(self, name):
"""Removes dog from animal shelter given name, if dog exists in shelter."""
for dog in self.dogs:
if dog.name == name:
self.dogs.remove(dog)
print(f'Thank you for adopting {name}!')
return
print('Could not find a dog with that name')
def introduce_all_dogs(self):
"""Print a description for all dogs."""
print(f'There are {len(self.dogs)} animals in this shelter:')
for dog in self.dogs:
dog.introduce()
print()
pound = AnimalShelter()
done = False
print('Welcome to the animal shelter!')
while not done:
print('1 - view dogs')
print('2 - adopt a dog')
print('3 - drop off a found dog')
print('4 - exit')
choice = input('Choose an option: ')
if choice == '1':
pound.introduce_all_dogs()
elif choice == '2':
name = input('Which dog would you like to adopt? (name) ')
pound.adopt_dog(name)
elif choice == '3':
name = input("what is the dog's name?")
age = int(input("what is the dog's age?"))
color = input("what is the dog's color?")
dog = Dog(name, age, color)
pound.add_dog(dog)
elif choice == '4':
done = True
else:
print('Not a valid option.') |
e9d6cd060c56f91c5063185d12df06461a1eebb0 | lmc-eu/demo-recommender | /recommender/baseline_recommender.py | 3,091 | 3.796875 | 4 | """A baseline recommender implementation."""
from collections import defaultdict
class User(object):
""" Data class that represents one user in the recommender network.
"""
def __init__(self, user_id):
self.user_id = user_id # String identifier of the user.
self.user_profile = defaultdict(float) # A dict with users interests (interactions), { item_id => interaction weight}
class Item(object):
""" Data class that represents one item in the recommender network.
"""
def __init__(self, item_id):
self.item_id = item_id # String with the item identification.
self.item_profile = defaultdict(float) # {user_id => interaction weight}
class Recommender(object):
"""
A Baseline Recommender.
It allows to add a new interaction into the network.
Recommendations candidates are obtained as all items on the path of the length 3 from the user.
"""
def __init__(self):
self.users = dict() # {user_id => User()}
self.items = dict() # {item_id => Item()}
def put_interaction(self, user_id, item_id, weight):
""" Add a new edge in the network.
"""
# Obtain the user if already exists.
if user_id in self.users:
user = self.users[user_id]
# ...or create a new one.
else:
user = self.users[user_id] = User(user_id)
# Obtain the item if already exists.
if item_id in self.items:
item = self.items[item_id]
# ...or create a new one.
else:
item = self.items[item_id] = Item(item_id)
# Insert a new interest into the user/item profile.
# If there is the same interests, use the higher weight.
# Here you can try different methods how to deal with repeating interactions (e.g. sum them)
user.user_profile[item_id] = max(weight, user.user_profile[item_id])
item.item_profile[user_id] = max(weight, item.item_profile[user_id])
def recommend(self, user_id):
""" Find all items on the path of the length 3 from the given user.
"""
if user_id not in self.users:
return []
# One item could be accessible by more then one path in the network.
# If so, we will sum all these paths into the item's score.
scores = defaultdict(float)
user_node = self.users[user_id]
for user_item_id, user_item_weight in user_node.user_profile.items():
user_item_node = self.items[user_item_id]
for neighbour_id, neighbour_weight in user_item_node.item_profile.items():
neighbour_node = self.users[neighbour_id]
for neighbour_item_id, neighbour_item_weight in neighbour_node.user_profile.items():
# Add the path weight to the item's score.
scores[neighbour_item_id] += user_item_weight * neighbour_weight * neighbour_item_weight
# Return top 10 items with the best score.
return sorted(scores.keys(), key=lambda item_id: scores[item_id], reverse=True)[:10]
|
f0bb31ae46407bb4298851f6792b7193a4adb521 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/3094/codes/1747_1532.py | 202 | 3.75 | 4 | from math import *
x = 0
z = 0
y = 0
k = 0
senh = (x / factorial(1)) * k
x = float
while(senh != k):
x=float(input("x: "))
k = int(input("k: "))
senhx = senh * (x**2 / 1 + 2)
print(round(senh, 9)) |
c459a5bfb6427bb215a67ce6c74b2e6f2cab813f | ljia2/leetcode.py | /solutions/hashtable/244.Shortest.Word.Distance.II.py | 1,603 | 4.09375 | 4 | import collections
class WordDistance:
def __init__(self, words):
"""
Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
:type words: List[str]
Unlimited/Multiple times implies Precompution and store with Hashtable where k = word pair and v = shortest path
"""
self.size = len(words)
self.word_pos = collections.defaultdict(list)
for i, word in enumerate(words):
self.word_pos[word].append(i)
def shortest(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
pos_list1 = self.word_pos[word1]
pos_list2 = self.word_pos[word2]
shortest = self.size
for i in pos_list1:
for j in pos_list2:
if shortest > abs(i-j):
shortest = abs(i-j)
return shortest
# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(words)
# param_1 = obj.shortest(word1,word2) |
6c0642b807005ea45b8fffc55f7161fc3f3fd0a5 | jonsongoffwhite/AlgorithmsCoursework | /Coursework_1/CW1-2 Levenshtein Distance.py | 5,944 | 4.03125 | 4 |
# coding: utf-8
# # Algorithms 202: Coursework 1 Task 2: Levenshtein Distance
# Group-ID: 32
# Group members: Jonathan Muller, Louis de Beaumont, Jonny Goff-White
# # Objectives
# The aim of this coursework is to enhance your algorithmic skills by mastering the divide and conquer and dynamic programming strategies. You are asked to show that you can:
#
# - implement a dynamic programming problem
#
# This notebook *is* the coursework. It contains cells with function definitions that you will need to complete. You will submit this notebook as your coursework.
#
# The comparisons of different algorithms involve textual descriptions and graphical plots. For graphing you will be using [matplotlib](http://matplotlib.org/index.html) to generate plots. [This tutorial](http://matplotlib.org/index.html) will be useful to go through to get you up to speed. For the textual descriptions you may wish to use [LaTeX](http://en.wikipedia.org/wiki/LaTeX) in-line like $\mathcal{O}(n\log{}n)$. Double click this cell to reveal the required markup - and [see here](http://texblog.org/2014/06/24/big-o-and-related-notations-in-latex/) for useful guidance on producing common symbols used in asymptotic run time analysis.
# # Preliminaries: helper functions
# Here we define a collection of functions that will be useful for the rest of the coursework. You'll need to run this cell to get started.
# In[3]:
# so our plots get drawn in the notebook
get_ipython().magic('matplotlib inline')
from matplotlib import pyplot as plt
import numpy as np
from pathlib import Path
from sys import maxsize
from time import clock
from urllib.request import urlretrieve
# a timer - runs the provided function and reports the
# run time in ms
def time_f(f):
before = clock()
f()
after = clock()
return after - before
# we can get a word list from here - we download it once
# to 'wordlist.txt' and then reuse this file.
url = 'http://www.doc.ic.ac.uk/~bglocker/teaching/wordlist.txt'
if not Path('wordlist.txt').exists():
print("downloading word list...")
urlretrieve(url, 'wordlist.txt')
print('acquired word list.')
with open('wordlist.txt') as f:
# here we use a *set* comprehension - just
# like we've done with lists in the past but
# the result is a set so each element is
# guaranteed to be unique.
# https://docs.python.org/3/tutorial/datastructures.html#sets
# note that you can loop over a set just like you would a list
wordlist = {l.strip() for l in f.readlines()}
print("loaded set of words into 'wordlist' variable")
# ## Task 2: Levenshtein Distance
# ### 2a. Implement `levenshtein_distance`
# Complete the below definition for `levenshtein_distance`. Do not change the name of the function or it's arguments.
#
#
# Hints:
#
# - You are given access to numpy (`np`). Numpy is the crown jewel of the scientific Python community - it provides a multidimensional array (`np.array()`) which can be very convenient to solve problems involving matrices.
# In[5]:
def levenshtein_distance(x, y):
m = len(x)
n = len(y)
# Initialise matrix of zeros with lengths of given words
d = np.zeros(shape=[m+1,n+1])
for i in range(1, m+1):
d[i,0] = i
for j in range(n+1):
d[0,j] = j
for j in range(1, n+1):
for i in range(1, m+1):
c = 0 if x[i-1] == y[j-1] else 1
d[i,j] = min(d[i-1,j] + 1, d[i,j-1] + 1, d[i-1,j-1] + c)
return d[m,n]
# Use this test to confirm your implementation is correct.
# In[4]:
print(levenshtein_distance('sunny', 'snowy') == 3)
print(levenshtein_distance('algorithm', 'altruistic') == 6)
print(levenshtein_distance('imperial', 'empirical') == 3)
print(levenshtein_distance('weird', 'wired') == 2)
# ### 2b. Find the minimum levenshtein distance
# Use your `levenshtein_distance` function to find the `closest_match` between a `candidate` word and an iterable of `words`. Note that if multiple words from `words` share the minimal edit distance to the `candidate`, you should return the word which would come first in a dictionary.
#
# As a concrete example, `zark` has an edit distance of 1 with both `ark` and `bark`, but you would return `ark` as it comes lexicographically before `bark`.
#
# Your function should return a tuple of two values - first the closest word match, and secondly the edit distance between this word and the candidate.
#
# ```python
# closest, distance = closest_match('zark', ['ark', 'bark', ...])
# assert closest == 'ark'
# assert distance == 1
# ```
# In[1]:
def closest_match(candidate, words):
closest = ""
# Set sentinel
distance = float("inf")
# Iterate through words list and check if distance is less than max value
for word in words:
d = levenshtein_distance(candidate, word)
if d < distance:
distance = d
closest = word
return closest, distance
# Run the below cell to test your implementation
# In[6]:
# A one liner that queries closest_match and then prints the result
print_closest = lambda w, wl: print('{}: {} ({})'.format(w, *closest_match(w, wl)))
print_closest('zilophone', wordlist)
print_closest('inconsidrable', wordlist)
print_closest('bisamfiguatd', wordlist)
# **Discuss in a few lines the running time of `closest_match`. Can you propose any ideas for making this faster? (Only discuss those in words, no need to do any implementations, unless you want to.)**
# The running time of `closest_match` is $\mathcal{O}(n)$ multiplied by the running time of `levenshtein_distance`, which is $\mathcal{O}(mn)$ - where $m$ and $n$ are the lengths of each of the words passed in. To make this faster, we could implement a divide and conquer approach for `levenshtein_distance` which would reduce the number of operations performed on the matrix and hence reduce the complexity of the `closest_match` function.
|
a82ae2c1d002410f8f1a22e3ead617223e935259 | GuilhermeLaraRusso/python_work | /ch_8_functions/8_2_passing_information_to_a_function.py | 644 | 4.1875 | 4 | # Modified slightly, the function greet_user() can not only tell the user Hello!
# but also greet them by name. For the function to do this, you enter username
# in the parentheses of the function’s definition at def greet_user(). By adding
# username here you allow the function to accept any value of username you
# specify. The function now expects you to provide a value for username each
# time you call it. When you call greet_user(), you can pass it a name, such as
# 'jesse', inside the parentheses:
def greet_user(username):
"""Display a simple greeting."""
print("Hello, " + username.title() + "!")
greet_user('guilherme') |
3f37cef135b11204eec5ee9aab0c17bbdb54f97b | ceparadise/Leecode | /reverseinter.py | 396 | 3.546875 | 4 | class Solution:
#yalin@return an integer
def reverse(self,x):
if x < 0:
sign = -1
elif x >= 0 :
sign = 1
result = sign * int(str(abs(x))[::-1])
if result > 2147483648 or result < -2147483648:
return 0
else:
return result
if __name__ == '__main__':
x = 1534236469
print Solution().reverse(x)
|
e76c609d6b4328adb7223505995041d2534f5dba | Digital-Lc/GUI_learning | /change_labels.py | 836 | 3.796875 | 4 | from tkinter import *
root = Tk()
def set_label1(text):
labeltext.set(text)
labeltext = StringVar()
labeltext.set("")
button1 = Button(root)
button1.config(text="Say hello!", command=lambda: set_label1("hello"), bg="Blue", fg="White", font=("Skia", 50))
button1.grid()
button2 = Button(root)
button2.config(text="Say banana!", command=lambda: set_label1("banana ಠ_ಠ"), bg="Blue", fg="White", font=("Skia", 50))
button2.grid()
button3 = Button(root)
button3.config(text="Clear text", command=lambda: set_label1(""), bg="Blue", fg="White", font=("Skia", 50))
button3.grid()
button4 = Button(root)
button4.config(text="please end me", command=lambda: set_label1("thank you"), bg="Blue", fg="Black", font=("Skia", 9))
button4.grid()
label1 = Label(root)
label1.config(textvariable=labeltext)
label1.grid()
root.mainloop() |
f7189974f9b26f120e43f38cf4d78b37d1ff0fad | dpk3d/HackerRank | /NegativeElement.py | 1,240 | 4.03125 | 4 | """
Move all negative numbers to beginning and positive to end with constant extra space.
An array contains both positive and negative numbers in random order.
Rearrange the array elements so that all negative numbers appear before all positive numbers.
"""
# Complexity O( n * log(n))
def easyWay(arr):
arr.sort()
print("Negative elements in beginning : ", arr)
array = [-3, 4, 60, -5, -8, -1, 10, 4, 5, 6, 6]
easyWay(array)
# Time complexity O(n) , Space - O(1)
def negativeFirst(arr):
x = 0
for y in range(0, len(arr)):
if arr[y] < 0:
temp = arr[y]
arr[y] = arr[x]
arr[x] = temp
x = x + 1
print("Negative elements in beginning :", arr)
array = [-3, 4, 60, -5, -8, -1, 10, 4, 5, 6, 6]
negativeFirst(array)
# Using Dutch National Flag Algorithm.
# Time complexity O(n) , Space - O(1)
def reArrange(arr):
start, end = 0, len(arr) - 1
while start < end:
if arr[start] < 0:
start += 1
elif arr[end] > 0:
end -= 1
else:
arr[start], arr[end] = arr[end], arr[start]
print("Negative elements Two Pointer Approach", arr)
array = [-3, 4, 60, -5, -8, -1, 10, 4, 5, 6, 6]
reArrange(array)
|
7d4a4da31a4949e39c14dde8d5c86e8211075de9 | c4rlos-vieira/exercicios-python | /Exercicio009.py | 187 | 3.921875 | 4 | carteira = float(input('Quanto de dinheir você tem na carteira? '))
dolar = float(3.27)
print('Você tem US$ {:.2f} equivalente aos seus R$ {:.2f}'. format(carteira/dolar, carteira))
|
f9912e387af182f1624ece94da06007a4cc5424c | akhileshgadde/Python-practice | /censor.py | 428 | 4.28125 | 4 | # simple censorship program that replaces the censored 'word' in the string with "****"
def censor(text, word):
words_list = text.split()
result = []
for each in words_list:
if each == word:
result.append('*' * len(word))
print result
else:
result.append(each)
print result
return " ".join (result)
print censor("this hack is wack hack", "hack")
|
08e72c506ad7c81b8295b6e3a2d16ff46cb3236d | sayanm-10/py-modules | /main.py | 3,660 | 3.5 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
__author__ = "Sayan Mukherjee"
__version__ = "0.1.0"
__license__ = "MIT"
import unittest
import os
from datetime import datetime, timedelta
from directory_analyzer import print_dir_summary, analyze_file
def datetime_calculator():
''' A helper to demonstrate the datetime module '''
start_date_1 = 'Feb 27, 2000'
start_date_2 = 'Feb 27, 2017'
start_date_1 = datetime.strptime(start_date_1, '%b %d, %Y')
end_date_1 = start_date_1 + timedelta(days=3)
print("The date three days after Feb 27, 2000 is", end_date_1.strftime('%b %d, %Y'), "\n")
start_date_2 = datetime.strptime(start_date_2, '%b %d, %Y')
end_date_2 = start_date_2 + timedelta(days=3)
print("The date three days after Feb 27, 2017 is", end_date_2.strftime('%b %d, %Y'), "\n")
date_diff_start = datetime.strptime('Jan 1, 2017', '%b %d, %Y')
date_diff_end = datetime.strptime('Oct 31, 2017', '%b %d, %Y')
date_diff = date_diff_end - date_diff_start
print("{} days passed between Jan 1, 2017 and Oct 31, 2017".format(date_diff.days))
def file_reader(path, field_num, sep, header=False):
''' a generator function to read text files and return all of the values on a single line on each call to next() '''
try:
fp = open(path, 'r')
except FileNotFoundError:
print("\n\nError while opening {} for reading".format(os.path.basename(path)))
else:
with fp:
# skip the first line if header is true
if header:
next(fp)
for line_num, line in enumerate(fp):
fields = line.strip().split(sep)
if (len(fields) < field_num):
raise ValueError('\n\n {} has {} fields on line {} but expected {}'.format(os.path.basename(path), len(fields), line_num + 1, field_num))
else:
# return fields from 0:field_num as tuple
yield tuple(fields[:field_num])
class FileOpsTest(unittest.TestCase):
''' Includes all test cases for file operations '''
def test_file_reader(self):
''' test file_reader() '''
# test ValueError is raised if expected number
# of fields exceeds the actual fields
with self.assertRaises(ValueError) as context:
for fields in file_reader('test_file_reader.txt', 6, '|', False):
print(fields)
self.assertTrue('Caught error' in str(context.exception))
# match the first returned tuple
expected_result = ('John ', ' Doe ', ' 102000 ', ' Age: 36 ', ' NJ')
self.assertEqual(next(file_reader('test_file_reader.txt', 5, '|', True)), expected_result)
def test_print_dir_summary(self):
''' test individual o/p of print_dir_summary '''
try:
fp = open('main.py', 'r')
except FileNotFoundError:
print('Unit test needs to run on main.py')
else:
classes, funcs, lines, chars = analyze_file(fp)
self.assertEqual(classes, 1)
self.assertEqual(funcs, 4)
self.assertEqual(lines, 100)
self.assertTrue(chars > 1)
if __name__ == "__main__":
''' This is executed when run from the command line '''
print("\n\n************************* Problem 1 ******************************\n\n")
datetime_calculator()
print("\n\n************************* Problem 3 ******************************\n\n")
print_dir_summary(os.getcwd())
print("\n\n************************* Unit Tests ******************************\n\n")
unittest.main(exit=False, verbosity=2)
|
e126336c16326552771e8544fbfd6205731712c6 | youhusky/Facebook_Prepare | /377. Combination Sum IV.py | 1,073 | 3.90625 | 4 | # Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
# Example:
# nums = [1, 2, 3]
# target = 4
# The possible combination ways are:
# (1, 1, 1, 1)
# (1, 1, 2)
# (1, 2, 1)
# (1, 3)
# (2, 1, 1)
# (2, 2)
# (3, 1)
# Note that different sequences are counted as different combinations.
# Therefore the output is 7.
# Follow up:
# What if negative numbers are allowed in the given array?
# How does it change the problem?
# What limitation we need to add to the question to allow negative numbers?
# Credits:
# Special thanks to @pbrother for adding this problem and creating all test cases.
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [1] + [0] * target
for i in range(1,target+1):
for num in nums:
if i >= num:
dp[i] += dp[i-num]
print dp
return dp[target] |
7201b79d716549a8afe1f06b2d63b10a3f5fa8aa | chrish42/python-profiling | /slow_program.py | 1,169 | 3.890625 | 4 | #!/usr/bin/env python3
"""A slow program... or really, any program that hasn't been profiled yet."""
import time
def fib(n: int) -> int:
"""A recursive implementation of computation of Fibonacci numbers in Python. Will be slow in pretty much all languages, actually."""
# These will be needlessly evaluated on every internal call to fib() also.
if not isinstance(n, int):
raise TypeError("fib() takes an int.")
if n < 0:
raise ValueError("Value for n must be non-negative.")
if n == 0 or n == 1:
return 1
else:
# The same sub-computation for numbers less than n will be redone multiple times!
return fib(n - 1) + fib(n - 2)
def function_that_recurses_too_much():
print(fib(33))
def function_that_busy_loops():
start = time.time()
while time.time() - start < 1:
pass
def function_that_waits():
time.sleep(1)
def function_that_allocates_a_lot():
arr = bytearray(b"\x01") * 10 ** 9
def main():
function_that_busy_loops()
function_that_recurses_too_much()
function_that_allocates_a_lot()
function_that_waits()
if __name__ == "__main__":
main()
|
8e683cea341d0a3fb2633c00817b541aad4e048c | jasonmh999/LeetCode | /add-two-numbers/add-two-numbers.py | 1,252 | 3.640625 | 4 | """
Time: O(max(N,M))
Space: O(max(N,M))
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry=False
returnlist=ListNode(0)
currlist=returnlist
while(True):
digit=0
if carry:
digit=1
carry=False
if l1 is not None:
digit+=l1.val
l1=l1.next
if l2 is not None:
digit+=l2.val
l2=l2.next
#add digit to new list
#1. check if larger than 10
if digit>9:
carry=True
digit-=10
#2 add new digit
currlist.val=digit
if l1 is None and l2 is None:
if carry:
currlist.next=ListNode(None)
currlist=currlist.next
currlist.val=1
break
else:
currlist.next=ListNode(None)
currlist=currlist.next
return returnlist |
3957038560de40849926f31dc45c05eab37ba204 | cosiq/codingChallenges | /Codility/MissingInteger.py | 644 | 3.828125 | 4 | # Write a function that, given an array A of N integers,
# returns the smallest positive integer (greater than 0) that does not occur in A.
# For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
# Given A = [1, 2, 3], the function should return 4.
# Given A = [−1, −3], the function should return 1.
def missingElements(A):
cmp = {}
for item in A:
if item not in cmp and item > 0: cmp[item] = 1
for i in range(1, len(A) + 1):
if i not in cmp: return i
return len(A) + 1
# Time: O(N)
# Space: O(N)
def simpleMissingElements(A):
A, c = set(A), 1
while c in A:
c += 1
return c
# Time: O(N)
# Space: O(N)
|
86235f3224799eb00ea074017b73aa199c9f3ccc | Kimbsy/project-euler | /python/problem_010.py | 379 | 3.859375 | 4 | import math
"""The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
def is_prime(num):
for i in range(2, int(math.sqrt(num)) + 1):
if num % i is 0:
return False
return True
target = 2000000
total = 2
for i in range(3, target, 2):
if is_prime(i):
total = total + i
print(total)
|
2ab339c4a92b1c41bbcb2375e04626ef303f4ad3 | sjsawyer/aoc-2020 | /q1/q1.py | 1,455 | 3.828125 | 4 | def part1(data, target_sum):
'''
Assumes data is sorted.
Runtime (with sorting): n + n*log(n) = n*log(n)
'''
i, j = 0, len(data) - 1
while i < j:
if data[i] + data[j] == target_sum:
return data[i], data[j]
if data[i] + data[j] > target_sum:
j -= 1
else:
i += 1
raise Exception('no two numbers sum to {}'.format(target_sum))
def part2(data):
'''
For each item in data, attempt part1 with the new target sum.
Assumes data is sorted.
Runtime: n*log(n) + n + (n-1) + (n-2) + ... + 1 = O(n^2)
'''
while len(data) > 2:
n3 = data.pop()
try:
# Assume n3 is part of the solution
target_sum = 2020 - n3
n1, n2 = part1(data, target_sum)
return n1, n2, n3
except:
# Didn't work, try next value and continue without current n3
# since n3 won't be part of the solution (we just tried all
# possible solutions including n3 and none worked)
pass
raise Exception('no three numbers sum to 2020')
def main():
with open('input.txt', 'rb') as f:
data = [int(l) for l in f.readlines()]
# critical to success is sorting
data.sort()
n1, n2 = part1(data, 2020)
print('part 1:', (n1, n2), n1*n2)
n1, n2, n3 = part2(data)
print('part 2:', (n1, n2, n3), n1*n2*n3)
if __name__ == '__main__':
main()
|
5ca3c45235cff034329daa64810420b6b39aac49 | daniel-reich/ubiquitous-fiesta | /PCtTk9RRPPKXCxnAx_8.py | 206 | 3.828125 | 4 |
def modulo(x, y):
# Your recursive solution here.
if (y == 0):
return None
if (y < 0):
y = -y
if (x < 0):
return -modulo(-x, y)
if (x < y):
return x
return modulo(x - y, y)
|
4a11d5a75a446f2407383d9b29a9383251269abe | watachan7/ToyBox | /Python_works/normal_code/ifcode.py | 163 | 3.546875 | 4 | def if_test(num):
if num > 100:
print('over 100')
elif num > 50:
print('over 50')
else:
print('elses')
if_test(50)
if_test(101)
if_test(70)
|
182e51cf2f30cdaf4747b531d0b8013660d10563 | ikatar/practice | /Censor_dispenser/censor_dispenser.py | 2,037 | 3.546875 | 4 | import re
def censor(text,words_to_censor,double_occurrences):
#removes words and negative words after 2 occurrences
original_text = text
text = text.lower()
to_remove=[]
for word in words_to_censor:
word = re.compile(rf"\b{word}\b")
for m in word.finditer(text):
to_remove.append([[m.group()],[m.start(),m.end()]])
for word in to_remove:
original_text = original_text[:word[1][0]] + "X"*len(word[0][0]) + original_text[word[1][1]:]
to_remove =[]
for word in double_occurrences:
word = re.compile(rf"\b{word}\b")
for m in word.finditer(text):
to_remove.append([[m.group()],[m.start(),m.end()]])
to_remove.sort(key=lambda x: x[1][1])
for word in to_remove[2:]:
original_text = original_text[:word[1][0]] + "X"*len(word[0][0]) + original_text[word[1][1]:]
return original_text
def censor_plus_next_words(text,list1,list2):
big_list = list1+list2
original_text = text
text = text.lower()
to_remove =[]
for word in big_list:
word = re.compile(rf"\b\w*['-]?\w*\b ?\b{word}\b ?\b\w*['-]?\w*\b")
for m in word.finditer(text):
to_remove.append([[m.group()],[m.start(),m.end()]])
to_remove.sort(key=lambda x: x[1][1])
for word in to_remove:
original_text = original_text[:word[1][0]] +"X"*len(word[0][0])+ original_text[word[1][1]:]
return original_text
email_one = open("email_one.txt", "r").read()
email_two = open("email_two.txt", "r").read()
email_three = open("email_three.txt", "r").read()
email_four = open("email_four.txt", "r").read()
proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithms ", "her", "herself"]
negative_words = ["concerned", "behind", "danger", "dangerous", "alarming", "alarmed", "out of control", "help", "unhappy", "bad", "upset", "awful", "broken", "damage", "damaging", "dismal", "distressing", "distressed", "concerning", "horrible", "horribly", "questionable"]
print(censor(email_three,proprietary_terms,negative_words))
print(censor_plus_next_words(email_four,proprietary_terms,negative_words))
|
196af9daf348dae788eb5f976dd36c3e6bd177a5 | dilekkaplan/Alistirmalar_2 | /soru_4.py | 364 | 3.78125 | 4 | #ilk 30 Fibbonaci sayısını rekülsif olarak yazdıran program
def fibo(x):
if x==1:
return 1
elif x==2:
return 1
else:
return fibo(x-2)+ fibo(x-1)
for i in range(1,31):
print(fibo(i), end=" ")
|
a0d7695cb6be224fea862daf962a2e01823fc1d5 | Jasenpan1987/Python-Rest-Api | /1.python-refresh/list-comparhenson.py | 333 | 3.84375 | 4 | # list comparehenson is a way to build list
list1 = [x for x in range(5)]
print(list1)
list2 = [x**2 for x in range(5)]
print(list2)
list3 = [x for x in range(1, 10) if x % 2 == 0]
print(list3)
name_input = ["Anna ", "Bill", " Josh", "steve"]
normalized_people = [p.lower().strip() for p in name_input]
print(normalized_people)
|
9f6f2a457ec34e70a00ad23011bc8f195380035f | cashmane/Homework12 | /dice.py | 1,303 | 3.84375 | 4 | import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
n = 100000 #number of rolls of d dice
d = 3 #number of dice in each roll
rolls = []
for i in range(n):
indivRoll = []
for j in range(d):
roll = np.random.randint(6) + 1
indivRoll.append(roll)
rolls.append(indivRoll)
sixCount = 0 #counter for number of times that 3 sixes are rolled
elevenCount = 0 #counter for number of times that a sum of 11 is rolled
sumList = []
for i in range(len(rolls)):
total = sum(rolls[i])
if total == 18:
sixCount += 1
sumList.append(total)
elif total == 11:
elevenCount += 1
sumList.append(total)
else:
sumList.append(total)
sixProb = sixCount/len(rolls)
elevenProb = elevenCount/len(rolls)
print("The probability of rolling all sixes is", sixProb)
print('The probability of rolling a total of eleven is', elevenProb)
plt.hist(sumList, bins=16, density=True)
plt.title('Distribution of Sum of Dice Rolls')
plt.xlabel('Sum of Dice')
plt.ylabel('Probability Density of Each Sum')
plt.show()
|
0517046c279c4bfec89274c8e1538b11568dea09 | cirino/python | /CursoGuanabara/ex28_aula10_guanabara.py | 428 | 3.875 | 4 | print("""
Exercício 28 da aula 10 de Python
Curso do Guanabara
Day 7 Code Python - 06/05/2018
""")
from random import randint
from time import sleep
numero = int(input('Adivinhe o número: '))
computador = randint(0, 5)
print('-=-'*30)
sleep(2)
if numero == computador:
print('Acertou, Uhuuu: {}'.format(numero))
else:
print('Pensei no número {} e o computador escolheu {}'.format(numero, computador))
|
caec78489981d610fc19e2f550554390786d6608 | Annika0401/PDF | /for-schleife.py | 141 | 3.5625 | 4 | colors = ["green", "red","blue", "yellow", "black"]
'''for x in colors:
print(x)'''
for x in range(len(colors)):
print(colors[x])
|
8c0e69311f0d25c61f92b95049ae753ab243f87a | CNZedChou/python-web-crawl-learning | /spider/codes/35_thread_count.py | 1,267 | 3.59375 | 4 | # !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author : Zed
@Version : V1.0.0
------------------------------------
@File : 35_thread_count.py
@Description :
@CreateTime : 2020-5-8 13:10
------------------------------------
@ModifyTime :
"""
import threading
import time
import random
def sing():
for i in range(3):
print("正在唱歌。。。。{}".format(i))
time.sleep(random.random())
def dance():
for i in range(3):
print("正在跳舞。。。。{}".format(i))
time.sleep(random.random())
#主线程代码:
if __name__ == '__main__':
#打印晚会开始时间(可读)
print('晚会开始:{}'.format(time.ctime()))
#分别创建执行sing和dance函数的线程
t1 = threading.Thread(target=sing)
t2 = threading.Thread(target=dance)
#主线程
t1.start()
t2.start()
# 主线程不终止
while True:
# 查看线程数量(包括主线程,至少含有一个主线程)
length = len(threading.enumerate())
# 主线程加上两个子线程的线程,一共三个线程
print('当前运行的线程数为:{}'.format(length))
time.sleep(0.1)
if length <= 1:
break
|
7f915f77d29b95d15dba3e56ef542deed43325ea | nisepulvedaa/curso-python | /11-ejercicios/ejercicio2.py | 544 | 3.984375 | 4 | """
Ejercicio 2
Escribir un programa que añada valores a una lista
mientras que su longitud sea menor a 120 y luego mostrar la lista
pluss usar while y for
"""
coleccion = []
for contador in range(0,120):
coleccion.append(("elemento-{}".format(contador)))
print("Mostrando el elemento : {} ".format(contador))
print(coleccion)
coleccion2 = []
indice = 0;
while indice <= 120:
coleccion2.append(("elemento-{}".format(indice)))
print("Mostrando el elemento : {} ".format(indice))
indice += 1
print(coleccion2)
|
e5994139b27f8a6865998a6530914c4a037f969d | CrazyAlan/codingInterview | /cc150/chapter4/4.py | 935 | 3.90625 | 4 | '''
1. For each layer, have a result variable to store all data, then have a list for
each layer, then loop through that list and new a list to store all it's left and right
child, finally check if the list is empty, if it is, then jump out, otherwise loop again
2. Append is wrong, need to append the left or right node
'''
from Classes3 import *
def bfsTraverse(root):
result = []
rstList = []
rstList.append(root)
result.append(rstList)
level = 0
while True :
newList = []
for node in result[level] :
# print "node " + str(node)
if node.left:
#print "left node %d"%node.left
newList.append(node.left)
if node.right:
newList.append(node.right)
if not newList:
break
result.append(newList)
level += 1
return result
if __name__ == '__main__':
testArr = range(0,8)
print testArr
a = AddToTree(testArr, 0, len(testArr)-1)
# print a.right
rst = bfsTraverse(a)
print len(rst)
|
eacd9fbe4f1b5151315dc964ef1218ccca517556 | samirsaravia/Python_101 | /Python_for_beginners_Mdev/error_handling.py | 893 | 4.21875 | 4 | x = 42
y = 0
print()
try:
print(x / y)
except ZeroDivisionError as identifier:
print('Not allowed to divide by zero')
else:
print('Something else went wrong!')
finally:
print('This is our cleanup!')
print()
'''
when an exception occurs in the 'try' suite, a search for an exception handler is started.
This search inspects the except clauses in turn until one is found that matches the exception.
For an except clause with an expression , that expression is evaluated, and the clause matches the exception if the
resulting object is 'compatible' with the exception.
The optional 'else' is executed if the control flow leaves the 'try' suite, no exception was raised, and no 'return',
'continue', or 'break' statement was executed. Exceptions in the 'else clause are not handled by the preceding 'except'
clauses.
If 'finally' is present, it specifies a 'cleanup' handler.
'''
|
c0583550e7db4069442ad77f5561609c6d880e49 | thisguycodez/python-madlibs | /test1.py | 1,353 | 4.4375 | 4 | ''' 1. comments - For python, use with a '#' symbol
or 3 quotes nesting your comment:
-helps explain what the code is doing
-great for jogging your memory if you are editing old code
-helps keep code organized
'''
# this is a comment
''' 2. prints - A function Used to send data to the console/terminal/screen
-Keep track of data in any part of your code
-Great for debugging code
-Needed for terminal/CLI based programs
* print('ThisGuyCodez....*')
* print(24)
***FROM NOW ON WE WILL USE PRINT TO DISPLAY OUR VALUES TO THE CONSOLE
'''
# 3. Strings, Integers , Floats , and Booleans - Data Types
# 3a.) String{a sequence of characters within quotes}
print('This is a String' , "I'm a string 2")
# 3b.) Integer{regular number} solid numbers only(NO COMMAS)
print(24 or 2400)
# 3c.) Float{decimals}
print(5.1 or 33.33)
# 3d.) Boolean{One of the two values - True or False}
print(True or False)
# Try it your self......
# Answer all the questions below, then move on to test2.py
# 1.) print my youtube channel as a string...
'''
2.) print the names of your favorite
coding languages you know or the names
of the ones you want to learn in a string...
'''
# 3.) print a random number/integer...
# 4.) print a random decimal...
# 5.) print a bool...
# 6.) print a string, integer, decimal, and a bool...
|
a5d9e1e0cff85be7691b2e4967cf99d10801e4ec | warsang/CCTCI | /chapter5/5.4/nextNumber.py | 1,098 | 3.59375 | 4 |
def getBit(number,index):
return (number & (1<< index) !=0 )
def flipBit(number,index):
return( number | (1 <<index))
def nextNumber(anumber):
#Flip last bit that is 1
ones_counter = []
for i in range(0,8):
res = getBit(anumber,i)
if res:
ones_counter.append(i)
#Get next largest:
number_of_ones = len(ones_counter)
if len(ones_counter) != 7:
mask = ""
for i in range(number_of_ones):
mask += "1"
nextBig = int(mask,2) << (7 - number_of_ones)
#Get nex smallest
mask = ""
#Get index of smallest one:
smallest = 0
for i in range(number_of_ones):
if i >= smallest:
smallest = i
#Set smallest to 0
flipBit(anumber,smallest)
#Check if next is free:
while True:
smallest -= 1
if getBit(anumber,smallest) == False:
flipbit(anumber,smallest)
return nextBig,anumber
else:
print("No next number!")
return None
|
6d099cedb1760c81594199936a50219dcfbf285d | MrHamdulay/csc3-capstone | /examples/data/Assignment_4/mdlcar002/question2.py | 551 | 3.921875 | 4 | # test program for Ndom calculations
import ndom
option = input ("Choose test:\n")
choice = choice[:1]
print ("calling function")
if choice == 'n' or choice == 'd':
num = int(option[2:])
if choice == 'n':
answer = ndom.ndom_to_decimal (num)
else:
answer = ndom.decimal_to_ndom(num)
elif action == 'a' or action == 'm':
num1, num2 = map (int, choice[2:].split(" "))
if choice == 'a':
answer = ndom.ndom_add (num1, num2)
else:
answer = ndom.ndom_multiply (num1, num2)
print ("called function")
print (answer)
|
8dd5d207c5b08d9a0ec9124b17b08a26d98aacc2 | statham/portfolio | /number_theory.py | 894 | 3.65625 | 4 | #This function should compute a^(b^c) % p where p is a prime.
#runs in polynomial time in log(a), log(b), log(c), and log(p)
#helper function: computes x^n for large x and n
def exp_by_squaring(x, n):
if n == 1:
return x
#if n is even, recurse on squared x and halved n
elif (n%2) == 0:
return exp_by_squaring(x*x, n/2)
#if n is odd, recurse on squared x and (n-1)/2
else:
new_x = exp_by_squaring(x*x, (n-1)/2)
return x*new_x
def exponent_mod(a, b, c, p):
d = 1
#use helper function to compute b^c
b_c = exp_by_squaring(b, c)
#create binary representation of b^c
b_c_binary = bin(b_c)[2:]
#for each digit in b_c_binary, square d and mod p
for i in b_c_binary:
d = (d*d)%p
#for each 1 in b_c_binary, multiply d and a, then mod p
if i == '1':
d = (d*a)%p
return d
|
af0587798c987ace23bf67733d111526429a331b | kbrain41/class | /psevdocod/psevdocod2.py | 114 | 3.8125 | 4 | A = 4
B = 7
if A%2==0:
print ("Число четное")
if A%2==1 and A<4:
print ("Число Простое")
|
2b728a5269149d8104ea4bb64c07249928904c38 | valerii2020/valerii2020 | /starter/lesson 3/Masha Horb/task2.py | 137 | 3.9375 | 4 | import math
p=3.14
x=input("введите число x")
x=int(x)
if -p<=x<=p:
y=math.cos(x*3)
elif x<-p or x>p:
y=x
print(y)
|
250173e6cb9f4a7fb54254b3619fe783ac2a3a6c | JaegerJochimsen/PolySolvy-Version-X-----Bivariate-Interpolation | /graph_bivariate.py | 4,371 | 3.671875 | 4 | import math
import bivariate
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random
%matplotlib notebook
def Graph_Bivariate(vvector: np.array, orig_x: np.array, orig_y:np.array, orig_z: np.array):
"""
A function which plots an original set of (x,y,z) points in a 3D space and overlays that graph with a graph
of the function output by Bivariate() (this is the interpolating function for the original (x,y,z) points).
param: vvector: an np.array of coefficients of the terms of the interpolating polynomial. These coefficients
are of the form:
[c,y,y^2,y^3,...........................y^(n//4), // powers of y increase horizontally, powers of x vertically.
x, xy, xy^2,.........................,xy^(n//4),
x^2,(x^2)y,(x^2)y^2,...........................
x^3,(x^3)y,....................................
................................................
................................................
(x^(n//4)),(x^(n//4))y,..., (x^(n//4))(y^(n//4)]
These coefficients are used by Bivariate() to compute the corresponding z-value for a given (x,y) pair as
specified by the interpolating polynomial.
param: x: an np.array of the original x-coordinates that were interpolated.
param: y: an np.array of the original y-coordinates that were interpolated.
param: z: an np.array of the original z-cooordinates that were interpolated.
return: outputs a graph plotted using Axes3D from mpl_toolkits.mplot3d
libraries/files used:
- bivariate.py
- numpy
- matplotlib.pyplot
- mpl_toolkits.mplot3d
- random
"""
# basic error catching
# input arrays must be of equal size so that they represent viable points
if (len(orig_x) != len(orig_y)) or (len(orig_x) != len(orig_z)):
raise Exception("Input arrays are of unequal length")
# set up the initial graphing space and initialize as a 3d space
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
calculated_z = []
# generate some sample x,y vals to plot, this helps to fill out the curve
# make sure that the range of value for the x and y's are the same length
# take the larger of the two ranges for this purpose
if (orig_x.max() - orig_x.min()) > (orig_y.max() - orig_y.min()):
# if x is the larger range
sample_x = np.arange(orig_x.min(),orig_x.max()+1,.1)
sample_y = np.arange(orig_x.min(), orig_x.max() + 1, .1)
else:
sample_x = np.arange(orig_y.min(),orig_y.max()+1,.1)
sample_y = np.arange(orig_y.min(), orig_y.max() + 1, .1)
# ensure that we include the original points
sample_x = np.append(sample_x, orig_x)
sample_y = np.append(sample_y, orig_y)
# Create the array of z values based off of constants in vmatrix and original x and y vals
for index in range(len(sample_x)):
calculated_z.append(np.double(bivariate.Bivariate(vvector, sample_x[index],sample_y[index])))
# convert to correct data type
calculated_z = np.array(calculated_z, dtype=np.double)
# if an odd num of data points, add one to make even
if len(sample_x) % 2 != 0:
newX = random.randint(orig_x.min(), orig_x.max())
sample_x = np.append(sample_x, newX)
newY = random.randint(orig_y.min(), orig_y.max())
sample_y = np.append(sample_y, newY)
newZ = Bivariate(vmatrix, newX, newY)
calculated_z = np.append(calculated_z, newZ)
# reshape the data for the purpose of surface plotting
reshapedx = sample_x.reshape(2, len(sample_x)//2)
reshapedy = sample_y.reshape(2, len(sample_y)//2)
length = len(calculated_z) // 2
reshapedz = calculated_z.reshape(2, length)
# surface plot
ax.plot_trisurf(sample_x, sample_y, calculated_z)
# plot of original data points
ax.scatter(orig_x, orig_y, orig_z, c='red')
# rotate the axes and update for an interactive graph
for angle in range(0, 360):
ax.view_init(30, angle)
plt.draw()
plt.pause(.001)
|
8c722f918afe8c417ee7d3b830734324b2fe2829 | dipalira/LeetCode | /String/125.py | 466 | 3.765625 | 4 | s= "A man, a plan, a canal: Panama"
a = "ab@a"
def isPalindrome( s):
"""
:type s: str
:rtype: bool
"""
if len(s) <0 : return True
r,l = len(s)-1,0
while l<r:
if s[r] == ' ' or s[r] in '()[].,:;+@-*/&|<>=~$':
r-=1
continue
elif s[l] == ' ' or s[l] in '()[].,:;+-*/&|<>=~$':
l+=1
continue
if s[r].lower() == s[l].lower():
r-= 1
l+= 1
else:
print(s[r],s[l],r,l)
return False
return True
print(isPalindrome(a))
print(len(s)) |
6a5a66972ec8a8e7fb16609bb7dc747e796d4535 | KikiPadoru/PraktikaSaltAndPepper | /1.py | 541 | 4.125 | 4 | import re
def is_palindrome(word):
if (type(word) is not str and type(word) is not int): return False
word = str(word) if type(word) is int else re.sub(r'[^\w]', '', word).lower()
for i in range(len(word) // 2 + 1):
if len(word) < 2: return True
if word[0] != word[-1]: return False
word = word[1:-1]
print(is_palindrome("A man, a plan, a canal -- Panama"))
print(is_palindrome("Madam, I'm Adam!"))
print(is_palindrome(333))
print(is_palindrome(None))
print(is_palindrome("Abracadabra"))
|
d769f566d027c2f25c33b7c8d69787a5cbb86580 | arara90/Python-FastCampusWebPythonBasic | /code04_list_dict/task_삽입정렬/3_insertion.py | 1,181 | 3.671875 | 4 |
#내코드
print("================for=============")
a = [1, 5, 4, 3, 2]
print("시작 : " , a)
for i in range(1,len(a)):
print("pivot index :" , i , "value :" , a[i])
pivot=a[i] #pivot값 저장
for j in range(i,0,-1):
if( pivot < a[j]):
print(" swap[%d , %d] " % ( pivot, a[j] ) )
a[j+1] = a[j]
a[j] = pivot
print(" >> ", a )
print("끝 : ", a )
#while문으로
print("================while=============")
a = [1, 5, 4, 3, 2]
print("시작 : " , a)
for i in range(1,len(a)):
pivot=a[i]
j = i-1
while j >= 0 :
if (a[j] > pivot):
a[j+1] = a[j]
a[j] = pivot
j = j-1
print("끝 : ", a )
#쌤코드
print("================teacher=============")
num_list = [1, 5, 4, 3, 2]
for i in range(1, len(num_list)):
j = i - 1 # 삽입할 요소보다 앞의 인덱스
key = num_list[i] # 삽입할 값 (=pivot)
while num_list[j] > key and j >= 0: # 반복문 조건 비교
num_list[j+1], j = num_list[j], j - 1 # 값을 대입
num_list[j+1] = key # 요소 삽입
for i in num_list:
print(i, end= ' ') # 1, 2, 3, 4, 5
|
88d13f66fdf9c1373d79c07a27bab32dc4fc1593 | anjihye-4301/python | /ch07data/ch07_06dic.py | 1,335 | 3.6875 | 4 | # dictionary -> {key: value[, key: value....]}
# -> js : json 형식
#key 값은 중복이 안되기 때문에 같은 key의 경우 뒤의 데이터로 덮어쓰기가 된다.
dic1 = {1: 'a', 2: 'b', 3: 'c', 3: 'd'}
print(dic1, type(dic1))
# 학생 딕셔너리 생ㄷ성
student ={"학번": 1000, "이름": '홍길동', "학과": "파이썬학과"}
print(student,type(student))
#학생의 이름 데이터 가져오기
print(student["이름"])
print(student.get("이름"))
#모든 키를 출력해보자
keylist = student.keys()
print(keylist)
keylist = list(student.keys())
print(keylist)
valuelist = student.values()
print(valuelist)
# 학생 딕셔너리가 가지고 있는 모든 데이터 출력해보기
for a in keylist:
print(a,":",student[a])
print(student.items())
studentlist = list(student.items())
print(studentlist)
studentlist.append(('연락처', '010-1111-2222'))
print(studentlist)
print(studentlist.pop())
print(studentlist)
# dictionary의 데이터 추가
singer = {}
singer["이름"] = "트와이스"
# js -> singer.구성원수 = 9
singer["구성원수"] = 9
# 같은 키를 사용해서 데이터를 넣으면 수정이 된다
singer["구성원수"] = 10
singer["대표곡"] = "시그널"
print(singer)
# singer dictionary의 대표곡 항목 삭제
del singer["대표곡"]
print(singer)
|
468da1efd2195d81641cb9c313d0330b8ed80a3a | lelencho/Homeworks | /Examples from Slides/Lesson 10 Regular Expression/23_Finditer.py | 172 | 3.671875 | 4 | import re
statement = 'Please contact us at: levon-grigoryan@gmail.com, lgrigor@submarine.com'
addresses = re.finditer(r'[\w\.-]+@[\w\.-]+', statement)
for address in addresses:
print(address)
|
815aea1680d8c32b58e5fbbf7f0a83f3671cfa80 | TPei/jawbone_visualizer | /plotting/Plot.py | 807 | 3.546875 | 4 | __author__ = 'TPei'
from abc import ABCMeta, abstractmethod
import matplotlib.pyplot as plt
class Plot(metaclass=ABCMeta):
"""
abstract plot superclass
"""
def set_ydata(self, ydata):
"""
setter of ydata
:param ydata:
:return:
"""
self.ydata = ydata
def set_xdata(self, xdata):
"""
setter of xdata
:param xdata:
:return:
"""
self.xdata = xdata
@abstractmethod
def get_plot_data(self):
"""
each plot subclass should support
the get plot data action
:return:
"""
pass
@abstractmethod
def plot(self):
"""
each plot subclass should support
the plotting action
:return:
"""
pass |
7d1135c0e34b4214358cb60fcbfc354da9a2ebb2 | roldanj/python | /dictionary_homework.py | 1,258 | 4.53125 | 5 | # Create a variable called student, with a dictionary.
# The dictionary must contain three keys: 'name', 'school', and 'grades'.
# The values for each must be 'Jose', 'Computing', and a tuple with the values 66, 77, and 88.
student = {'name': 'jose', 'school': 'computing', 'grades': (66, 77, 88)}
# Assume the argument, data, is a dictionary.
# Modify the grades variable so it accesses the 'grades' key of the data dictionary.
def average_grade(data):
grades = data['grades']
return sum(grades) / len(grades)
# Implement the function below
# Given a list of students (dictionaries), calculate the average grade received on an exam, for the entire class
# You must add all the grades of all the students together
# You must also count how many grades there are in total in the entire list
def average_grade_all_students(student_list):
total = 0
count = 0
for student in student_list:
# total = total + sum(student['grades'])
# count = count + len(student['grades'])
# or we can write it like this:
total += sum(student['grades'])
count += len(student['grades'])
return total / count
a = (100 + 1.0/3) - 100
b = 1.0/3
print(1.0/3)
print(100 + 1.0/3)
print(a)
print(b)
print(a == b)
|
d697d21b3e25225c7989919d5edc3fecdb6f0ce9 | jeevabalanmadhu/__LearnWithMe__ | /Machine Learning/Data science/DataScienceClass/PythonBasics/SortNumber.py | 1,320 | 3.875 | 4 | #Sorting of ListNumbers
n=int(input("count of ListNumbers: "))
numbers=[]
TypeSorting=input("Accending or Decending: ")
i=0
while(i<n):
numbers.insert(i,input("Enter numbers of {}:".format(i+1)))
i+=1
print(numbers)
def accending(ListNumbers):
n=len(ListNumbers)
i=0
while(i<n):
j=i+1
while(j<n):
if(ListNumbers[i]>ListNumbers[j]):
a=ListNumbers[i]
ListNumbers[i]=ListNumbers[j]
ListNumbers[j]=a
j+=1
i+=1
return ListNumbers
def decending(ListNumbers):
n=len(ListNumbers)
i=0
while(i<n):
j=i+1
while(j<n):
if(ListNumbers[i]<ListNumbers[j]):
a=ListNumbers[i]
ListNumbers[i]=ListNumbers[j]
ListNumbers[j]=a
j+=1
i+=1
return ListNumbers
if(TypeSorting=="Accending"):
accending(numbers)
print("Sorting in accending order:",numbers)
elif(TypeSorting=="Decending"):
decending(numbers)
print("Sorting in decending order:",numbers)
else:
print("incorrect input of sorting type, please run again")
|
87e4318addf2c28a4fd39467c2acd7ea205e4168 | Navesz/python | /Exercícios/ex011.py | 230 | 3.984375 | 4 | print("Coloque os valores em metros!")
largura = float(input("Largura: "))
altura = float(input("Autura: "))
area = largura * altura
tinta = area / 2
print(f"Aréa da parede: {area}m². \nTinta necessária: {tinta} litros.") |
8d2f39771908494dad05b6cf35e6468ba016ae13 | zmj/Euler | /025.py | 167 | 3.59375 | 4 | current = 1
prev = 1
n = 2
digits = 1000
while True:
num = current + prev
prev = current
current = num
n += 1
if len(str(current)) == digits:
break
print n
|
4720c3eb1eb2946626ef8d83030d87f241aabb0b | jbell1991/code-challenges | /challenges/codewars/counting_duplicates/counting_duplicates.py | 797 | 4.34375 | 4 | def duplicate_count(text):
'''Takes in string of text and returns the count of
duplicate characters in the string.
'''
# empty dictionary
dict = {}
# make text lowercase
text = text.lower()
# iterate over each character in the text
for char in text:
# if the character is not in the dictionary
if char not in dict:
# create a key and assign the value to 1
dict[char] = 1
else:
# add 1 to the value
dict[char] += 1
# count how many characters have values > 1
count = 0
# iterate over each value in the dictionary values
for value in dict.values():
# if the value is greater than 1 it counts a duplicate
if value > 1:
count += 1
return count
|
9b588779c7e7eac9bb926a67fd9fce059b686178 | xCrypt0r/Baekjoon | /src/9/9933.py | 437 | 3.90625 | 4 | """
9933. 민균이의 비밀번호
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,380 KB
소요 시간: 68 ms
해결 날짜: 2020년 9월 25일
"""
def main():
N = int(input())
words = [input() for _ in range(N)]
for i in range(N):
for j in range(i, N):
if words[i][::-1] == words[j]:
print(len(words[i]), words[i][len(words[i]) // 2])
if __name__ == '__main__':
main() |
37e3e7aa509433f1d28bd80a129251be3eda8314 | ChezzOr/codeFightsSolves | /makeArrayConsecutive2.py | 303 | 3.515625 | 4 | def makeArrayConsecutive2(statues):
'''Search for max and min, then compare size of array with difference between min and max'''
min = 11
max = -1
for x in statues:
if x > max:
max = x
if x < min:
min = x
return (max - min) - len(statues) + 1
|
fa640b593699c4fc4edb6024799adecd2c3a6c46 | CosmicQubit/type-2 | /gui_txt_text.py | 3,659 | 3.703125 | 4 | txt_help_text = """
This app will predict the probability of you developing type-2 diabetes.
In order to use it, fill in all the fields and press send. To make sure
everything runs smoothly, there are some restrictions:
1) Negative numbers cannot be given.
2) The correct type of information must be entered e.g no words for age.
3) There are limits to prevent extreme values so the app doesn't break
but feel free to play around.
4) Don't leave any fields empty.
Range
-------
Age: 0 - 130
BMI/Glucose/Blood Pressure: Any positive number
Obtaining the data
--------------------
Age: Current year - your birth year
BMI: weight[kg]/Height^2[m]
Glucose: Use a blood glucose meter
Blood Pressure: Use a blood pressure moniter and take the lower number.
Have fun! And remember, this is just an app. Consult a doctor for serious
medical related issues.
"""
txt_about_text = """
Name: Type-2 diabetes predictor
Version: 2.0
Modules used: Numpy, tkinter, SciKit-learn, Pandas
description: Tests the probability of the user developing type-2 diabetes.
Machine Learning Model: Logistic Regression
Dataset used: rb.gy/mrwkvd
"""
txt_info_text = """
Important notice: This is just an app, consult a doctor for serious medical issues.
---------------------------------------------------------------------------------------------------------
This section contains information on type-2 diabetes:
1) What is it?
Type-2 diabetes occurs when your body cannot produce enough insulin or becomes resistant to it.
2)What causes it?
-Being overweight
-Being too inactive
-A family history of the disease.
3)What are the symptoms?
-Peeing a lot
-tiredness
-constantly thiirsty
-losing weight without trying
-cuts take long to heal
-blurred vision
4)How is it diagnosed?
Go to your GP who will do a urine and blood test. If the test comes back positive, they will
call you back and explain the next step.
5)What is the treatment?
-They will give you medicine to help maintain your blood-sugar levels.
-You will be expected to make lifestyle changes such improving your diet and being more active.
-You will be given regular checkups to make sure everything is ok.
Measurements of a healthy person
----------------------------------
Age: n/a
BMI: 18.5 - 25.0
Glucose: 140[mg/dL]/7.8[mmol/L] 90mins after a meal
Blood Pressure: <80[mm Hg] (This is your lower/diastolic one)
---------------------------------------------------------------------------------------------------------
It is important to remember that diabetes (both type-1 and type-2) are serious illnesses and
if you think you have it then you consult a medical professional. It is a lifetime disease
which means once you get it, there is no permenant cure. So make sure to maintain your health
even if the app says your risk is low. Also remember that this is just an app, it does not
replace the opinion of a medical professional at all.
---------------------------------------------------------------------------------------------------------
Source:
1) https://www.nhs.uk/conditions/diabetes/
2) https://www.nhs.uk/conditions/type-2-diabetes/
3) https://www.diabetes.co.uk/diabetes_care/blood-sugar-level-ranges.html
4) https://www.heart.org/en/health-topics/high-blood-pressure/understanding-blood-pressure-readings
5) https://www.nhs.uk/common-health-questions/lifestyle/what-is-the-body-mass-index-bmi/
"""
lbl_result_text = """
Please fill in all the blanks in the entry fields.
Once done press send to get your result.
It will be displayed on this screen.
This app doesn't replace the opinion of doctors
"""
|
74494c92fb4962ee56894be13779be2fe96dd594 | rohanwarange/Python-Tutorials | /Sets/intro_set.py | 501 | 3.984375 | 4 | # Set Data type
# unorder collection of uniqe items
s={1,2,3,4,4}
print(s)
# set uses...............................
# remove duplicate
l=[1,2,3,4,4,3,2,1,1,2,3,4,4,3,2,1,345,22,678,33,5,42,8,5,2,4,5,6,4,3,5,7,4,3,4,5,6,4]
s2=set(l)
# print(s2)
# add element in set
s.add(9)
print(s)
# remove from set
s.remove(4)
print(s)
s.discard(4)
# clere method
s.clear()
print(s)
# copy method()
s5=s.copy()
print(s5)
# store in set
# int,strig,float
# list,array,tuple,dictionary are not stored in set
|
53ff3dcb7ca6d60e7ddb1dcc3136ae89024adb47 | ryhanlon/legendary-invention | /labs_Applied_Python/ari/main.py | 3,656 | 4.03125 | 4 | """
Creating an ARI (automated readability index) to evaluate the reading level of a book for age and grade.
# evaluate the text, compute the ARI score
#4.71 9(characters/words) +.(5 (words/sentences) -21.43)
# ari_scale = {...}, this is used to apply the score to the age and grade
"""
import os
from collections import defaultdict
from collections import Counter
import chalk
import math
from quantify_text import sents_counter
from quantify_text import word_counter
from quantify_text import char_counter
BOOKS = '/Users/MacBookPro/Git/Projects_FSP/labs_Applied_Python/ari/books/'
def score_ari(score: int, text_file: str) -> None:
ari_scale = {
1: {'ages': '5-6', 'grade_level': 'Kindergarten'},
2: {'ages': '6-7', 'grade_level': '1st Grade'},
3: {'ages': '7-8', 'grade_level': '2nd Grade'},
4: {'ages': '8-9', 'grade_level': '3rd Grade'},
5: {'ages': '9-10', 'grade_level': '4th Grade'},
6: {'ages': '10-11', 'grade_level': '5th Grade'},
7: {'ages': '11-12', 'grade_level': '6th Grade'},
8: {'ages': '12-13', 'grade_level': '7th Grade'},
9: {'ages': '13-14', 'grade_level': '8th Grade'},
10: {'ages': '14-15', 'grade_level': '9th Grade'},
11: {'ages': '15-16', 'grade_level': '10th Grade'},
12: {'ages': '16-17', 'grade_level': '11th Grade'},
13: {'ages': '17-18', 'grade_level': '12th Grade'},
14: {'ages': '18-22', 'grade_level': 'College'}
}
score_data = ari_scale.get(score, ari_scale[14])
chalk.magenta(f"""
--------------------------------------------------------
The ARI for the file, {text_file}, is {score}.
This corresponds to a {score_data['grade_level']} level of difficulty
that is suitable for an average person {score_data['ages']} years old.
--------------------------------------------------------
""")
def calculate(text: str) -> int:
"""
Calculate the ari score.
:param text:
:return:
"""
sents = sents_counter(text)
words = word_counter(text)
chars = char_counter(text)
raw_score = 4.71*(chars/words) + .5*(words/sents) - 21.43
score = math.ceil(raw_score)
return score
def pull_text(book_path: str) -> str:
"""
Gets the text to be evaluated (.txt file)
"file handler"
:param path: str
:return: str
"""
with open(book_path, 'r') as file:
text = file.read()
return text
def select_book():
"""
Display the book menu from the file.
:return: int, str
"""
books = [book for book in os.listdir(BOOKS) if '.txt' in book]
book_menu = """To compute the automated readability index,
pick from one of the files below:\n"""
options = {index: item for index, item in enumerate(books, start=1)}
chalk.yellow(book_menu)
for index, book in options.items():
print(index, book)
while True:
book_choice = input("\nEnter the number of your choice or Q/quit. ⇝ ")
try:
book_choice = int(book_choice)
except ValueError:
if book_choice == 'quit' or book_choice == 'q':
chalk.yellow("Good bye.")
break
chalk.red("Please enter the number to the left of the book.")
else:
book_title = options[book_choice]
full_path = BOOKS + book_title
text = pull_text(full_path)
score = calculate(text)
score_ari(score=score, text_file=book_title)
# resul = ari_results # calls the function from quantify_text.py
select_book()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.