blob_id
stringlengths 40
40
| repo_name
stringlengths 5
119
| path
stringlengths 2
424
| length_bytes
int64 36
888k
| score
float64 3.5
5.22
| int_score
int64 4
5
| text
stringlengths 27
888k
|
---|---|---|---|---|---|---|
70c2390aa2840df0fd6bd54fdf3b225b47156288 | ThompsonHe/LeetCode-Python | /Leetcode0088.py | 733 | 4.1875 | 4 | """
88. 合并两个有序数组
给你两个有序整数数组nums1 和 nums2,请你将 nums2 合并到nums1中,使 nums1 成为一个有序数组。
说明:
初始化nums1 和 nums2 的元素数量分别为m 和 n 。
你可以假设nums1有足够的空间(空间大小大于或等于m + n)来保存 nums2 中的元素。
示例:
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出:[1,2,2,3,5,6]
"""
class Solution:
def merge(self, nums1, m, nums2, n):
"""
Do not return anything, modify nums1 in-place instead.
:param nums1: List[int]
:param m: int
:param nums2: List[int]
:param n: int
:return: None
"""
if m
|
68685b3dca14bf22fa3e8d8812b6bbf19b0fdb70 | snulion-study/algorithm-adv | /jenny/sorting/[필수]단어정렬.py | 602 | 4 | 4 | """
[정렬] 백준 1181번
sort의 기준이 정해져 있을 때,
python 내장 함수의 sorted와
lambda로 sort 기준의 우선순위를 정해준다.
: sorted(iterable, key= lambda x: [기준])
내장함수 말고 직접 구현하는게 핵심인 것 같은데 난 귀찮으니 생략.
"""
def solution(word_list):
word_list = sorted(set(word_list), key=lambda x: [len(x), x])
for w in word_list:
print(w)
return 0
# Driver Code
if __name__ == "__main__":
word_list = []
for _ in range(int(input())):
word_list.append(input())
solution(word_list)
|
64d20b6eaa4d2e27e2de96eb0605545e31388771 | maxbergmark/misc-scripts | /codereview/find_repeating.py | 1,622 | 3.625 | 4 | import time
import numpy as np
def find_repeating(lst, count=2):
ret = []
counts = [None] * len(lst)
for i in lst:
if counts[i] is None:
counts[i] = i
elif i == counts[i]:
ret += [i]
if len(ret) == count:
return ret
def find_repeating_fast(lst):
n = len(lst)-2
num_sum = -n*(n+1)//2 + np.sum(lst)
sq_sum = -n*(n+1)*(2*n+1)//6 + np.dot(lst, lst)
root = (sq_sum/2 - num_sum*num_sum/4)**.5
base = num_sum / 2
a = int(base - root)
b = int(base + root)
return a, b
tests = int(input())
print("Comparison to Ludisposed's solution (best case):")
for k in range(tests):
inp = input()
iterations = 1
t0 = time.clock()
for _ in range(iterations):
test = [int(i) for i in inp.split()]
find_repeating(test)
test_np = np.fromstring(inp, dtype=np.int64, sep=' ')
t1 = time.clock()
for _ in range(iterations):
find_repeating_fast(test_np)
t2 = time.clock()
print("Time per iteration (10^%d): %9.2fµs /%9.2fµs, speedup: %5.2f" % (
k+1,
(t1-t0)/iterations*1e6,
(t2-t1)/iterations*1e6,
(t1-t0)/(t2-t1))
)
"""
for k in range(1, 7):
size = 10**k
iterations = 1000000//size*0+1
# test = [i+1 for i in range(size)] + [1, size-1] # worst case
# test = [1, 2] + [i+1 for i in range(size)] # best case
t0 = time.clock()
for i in range(iterations):
find_repeating(test)
t1 = time.clock()
for i in range(iterations):
test_np = np.array(test, dtype=np.int64)
find_repeating_fast(test_np)
t2 = time.clock()
print("Time per iteration (10^%d): %8.2fµs /%8.2fµs, speedup: %5.2f" % (
k,
(t1-t0)/iterations*1e6,
(t2-t1)/iterations*1e6,
(t1-t0)/(t2-t1))
)
""" |
3e3be3fa5c1327be35a6d33c27793733ddc86e60 | CoreyPrachniak/Van-Eck-Sequence | /main.py | 810 | 3.53125 | 4 | print("Please input a tuple, (M, p). The output is the probability that for a random index, n < M, the nth member of the Van Eck sequence is zero or within p percent of n.")
tuple = input()
M, p = map(int, tuple[1: len(tuple) - 1].split(", "))
#STEP 1: Fill an array called dontknow with the first M entries of the Van Eck sequence.
dontknow = [0]*M
seen = []
for i in range(1, M):
if dontknow[i - 1] not in seen:
dontknow[i] = 0
seen.append(dontknow[i - 1])
else:
for j in range(1, i):
if dontknow[i - 1] == dontknow[(i - 1) - j]:
dontknow[i] = j
break
#STEP 2: Do a favorable divided by total calculation.
counter = 0
for i in range(M):
if dontknow[i] == 0 or (100 - p)*i < 100*dontknow[i] < (100 + p)*i:
counter += 1
print("The desired probability is " + str(counter/M) + ".")
|
60547004e6c76cffce141ef6f13e4c4248bccd67 | lapa19/wcmentor16 | /flow.py | 2,291 | 3.765625 | 4 | # variables
a=5 #integers
print(a)
pi = 3.14 #float
my_name='aparna' #strings
var = True #boolean
my_var = 5 #integer
my_var = 'tree' #string
#strings:
#immutable
#string concatenation
x='ap'
y='arna'
x+y
#Indexing:strings are indexed
x[0] #gives 'a'
#negative indexing:
x[-1] #gives 'p'
#slicing:
y[0:2] #gives 'ar'
len(x) #gives 2
#lists
mylist = [1, 4, 9, 16, 25]
diff = [2,'ap',True]
#indexing,slicing same as strings
a=[1,3,5]
b=[7,9,9]
c=a+b
c=[1,3,5,7,9]
len(c) #gives 5
c.append(7) #append 7 at the end
c.pop(3) #pop from position 3, pops 7
#tuples
#immutable
t = ("harry","potter",15,5)
#dictionaries
runs = {"virat":103,"vijay":"30", "yadav":"26"}
runs["virat"] #gives 103
#sets
s = {3,1,4,2,3}
s #removes duplicates
a=1
#control flow statements:
if a<5:
#do something
print("hi")
elif a<10:
#do something
print("hello")
else:
#do something
print("bye")
#for
for i in c:
print(i)
#range
for i in range(5):
print(i)
for i in range(len(c)):
print (c[i])
#while
i=1
while i<5:
print (i)
i=i+1
#break
#continue
#2 lists
names=['virat','vijay','yadav']
runs = [103,30,26]
for n,r in zip(names,runs):
print (n, r)
#Functions:
def odd(num):
if num%2:
return True
else:
return False
#function call
odd(5)
#Modules
#file1.py
def odd(num):
if num%2:
return True
else:
return False
def prime(n):
for i in range(2,int(math.ceil(math.sqrt(n)))):
if n%i == 0:
return False
return True
#importing
import file1.py
file1.odd(5)
from file1 import odd
odd(5)
from file1 import *
odd(5)
prime(5)
#reading and writing files
f = open('workfile', 'w')
f.read(1)
f.seek(5)
f.readline()
s = "myname"
f.write(s)
#HTML
#urllib
import urllib2
url = urllib2.urlopen("http://www.imdb.com/chart/top")
content = url.read()
#beautifulsoup
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("index.html"))
soup = BeautifulSoup("<html>data</html>")
soup.p
soup.p['class']
soup.find_all('a')
soup.get_text()
tag = soup.b
tag.name
tag.name = "strong"
#<head><title>Harry potter</title></head>
head_tag = soup.head
head_tag.contents
title_tag = soup.title
title_tag
# <title>Harry Potter/title>
title_tag.parent
# <head><title>Harry Potter</title></head>
|
6d6ed9b2e5717b040a2339f22cf21166c0dc2919 | fwzlyma/OpenCV-in-3h | /7_face_detection.py | 1,267 | 3.5625 | 4 | # 项目 : Python学习
# 姓名 : 武浩东
# 开发时间 : 2021/7/12 12:27
import cv2
import numpy as np
def useCam():
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# how to import a webcam
cap = cv2.VideoCapture(0) # 0 mean webcam object
cap.set(3, 640) # the width ID is 3
cap.set(4, 480) # the height ID is 4
cap.set(10, 100) # the brightness ID is 10
while True:
success, img = cap.read()
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(imgGray, 1.1, 4)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow("Result", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
def useImg():
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img = cv2.imread('lena.png')
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(imgGray, 1.1, 4)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('Result', img)
cv2.waitKey(0)
if __name__ == '__main__':
useImg()
|
fb3641017158cbb1d4596a9ec532733d6d7b6645 | Jagadish2019/The_Valley_Boot_Camp | /3Mar19/dynamicfib.py | 215 | 3.578125 | 4 | def fib_efficient(n,d):
if n in d:
return d[n]
else:
ans = fib_efficient(n-1, d) + fib_efficient(n-2, d)
d[n] = ans
return ans
d = {1:1,2:1}
a = int(input("enter a number\t"))
print(fib_efficient(a,d))
|
a65c3967e2a92b7a3d8fdbd45b446118e59abe6c | i386net/python_crash | /the begining/others/5-8_hello_admin.py | 853 | 3.828125 | 4 | users = ['sponge bob', 'patrick', 'sandy', 'admin']
new_users = ['john', 'Patrick', 'michael', 'rose', 'sara']
if len(users) == 0:
print('We need to find some users!')
else:
for user in users:
if user == 'admin':
print('Hello admin, would you like to see a status report?')
else:
print('Hello ' + user.title() + ', thank you for logging in again.')
# 5-10 checking new_users in users list:
for new_user in new_users:
if new_user.lower() in users:
print(new_user.title() + ', you should choose another name!')
else:
print('Hello ' + new_user.title())
#5-11
for num in list(range(1,10)):
if num == 1:
print(str(num) + 'st')
elif num == 2:
print(str(num) + 'nd')
elif num == 3:
print(str(num) + 'rd')
else:
print(str(num) + 'th')
|
a82f52439bdec84adc211792bb23cae313e93915 | preboe/stapik | /stepik_2/stepik_1.1.py | 1,944 | 4.34375 | 4 | # Задача 1. Напишите программу, которая считывает одну строку. Если это строка «Python»,
# программа выводит «ДА», в противном случае программа выводит «НЕТ».
#
# Решение. Программа, решающая поставленную задачу, может иметь вид:
word = input()
if word == 'Python':
print('ДА')
else:
print('НЕТ')
# Задача 2. Напишите программу, которая определяет, состоит ли двузначное число,
# введенное с клавиатуры, из одинаковых цифр. Если состоит, то программа выводит «ДА»,
# в противном случае программа выводит «НЕТ».
#
# Решение. Программа, решающая поставленную задачу, может иметь вид:
num = int(input())
last_digit = num % 10 # Последняя цифра числа
first_digit = num // 10 # Первая цифра числа
if last_digit == first_digit:
print('ДА')
else:
print('НЕТ')
# Задача 3. Напишите программу, которая считывает три числа и подсчитывает количество чётных чисел.
#
# Решение. Программа, решающая поставленную задачу, может иметь вид:
num1, num2, num3 = int(input()), int(input()), int(input())
counter = 0 # Переменная счетчик
if num1 % 2 == 0:
counter = counter + 1 # Увеличеваем счетчик на 1
if num2 % 2 == 0:
counter = counter + 1 # Увеличеваем счетчик на 1
if num3 % 2 == 0:
counter = counter + 1 # Увеличеваем счетчик на 1
print(counter)
|
3180b33c49d1c819ffe2dbd3f579046ed6abcd78 | jpmolinamatute/labs | /server/Python/pass.py | 1,900 | 3.734375 | 4 | #! /home/juanpa/Projects/labs/server/Python/.venv/bin/python
import random
import time
import string
import argparse
import pyperclip
def generate(length, alphanu):
if not isinstance(length, int):
raise TypeError("length must be an integer")
if length < 8:
raise ValueError("length must be greater than 8")
if alphanu:
all_char = list(f"{string.digits}{string.ascii_letters}")
opt_num = 4
else:
all_char = list(f"{string.digits}{string.punctuation}{string.ascii_letters}")
opt_num = 5
limit1 = int(time.time())
random.seed()
rand1 = random.randint(0, limit1)
random.seed(rand1)
sub_length = int(length / opt_num)
ext_length = (length % opt_num) + sub_length
random.shuffle(all_char)
result = random.choices(string.ascii_uppercase, k=sub_length)
result += random.choices(string.ascii_lowercase, k=ext_length)
result += random.choices(string.digits, k=sub_length)
if not alphanu:
result += random.choices(string.punctuation, k=sub_length)
result += random.choices(all_char, k=sub_length)
random.shuffle(result)
random.shuffle(result)
password = "".join(result)
print(f"Your new Password is {password} and it was copied to your clipboard")
pyperclip.copy(password)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Generate random password")
parser.add_argument(
"--length",
dest="length",
type=int,
choices=range(8, 40),
required=True,
default=10,
help="Length of password to be generated. Default: 10",
)
parser.add_argument(
"--onlyalphanum",
action="store_true",
dest="alphanu",
help="Create password using onlu upper/lower character and numbers",
)
args = parser.parse_args()
generate(args.length, args.alphanu)
|
c040f6ef4acf04f243de67e2c10f8b7260ded1b8 | AlekssandraMurzyn/pythonKurs | /zestaw2.py | 3,873 | 3.765625 | 4 | # zadanie 2.1
print("##################### zadanie 2.1 ##################### ")
longInt = 92835893724000
a = str(longInt)
b = a.count("0")
print(b)
# zadanie 2.2
print("##################### zadanie 2.2 ##################### ")
x = 5
print(x == 5 and 3) # 3 is not 0 and x is indeed 5 so its True. print(x == 5 and 0) would be false
print(x == 4 and 3) # False because x is 5, not 4
print(3 and x == 5) # 3 is not 0 and x is indeed 5 so its True. print(x == 5 and 0) would be false
print(3 and x == 4) # False because x is 5, not 4. And have to be True on both sides of logical opperand
isinstance(True, int) # False, because int != bool
isinstance(True, bool) # True is a bool so isinstance(True, bool) will also be True
# zadanie 2.3
print("##################### zadanie 2.3 ##################### ")
listaNowychWartosci = []
for numer in range(1, 2023, 2):
listaNowychWartosci.append(numer ** 2)
print(sum(listaNowychWartosci))
# inna metoda
print(sum([x ** 2 for x in range(1, 2023, 2)]))
# zadanie 2.4
print("##################### zadanie 2.4 ##################### ")
listapierwiastkow = [(1, "hydrogen", "H", 1), (2, "helium", "He", 4), (3, "Lithium", "Li", 7)]
print(listapierwiastkow)
print("+----+--------------------+-------+-------+")
print("|No. | Name (en) |Symbol |Waga(u)|")
print("+----+--------------------+-------+-------+")
for pierwiastek in listapierwiastkow:
print("|{}|{}|{}|{}|".format(str(pierwiastek[0]) + " " * (4 - len(str(pierwiastek[0]))),
pierwiastek[1] + " " * (20 - len(pierwiastek[1])),
pierwiastek[2] + " " * (7 - len(pierwiastek[2])),
str(pierwiastek[3]) + " " * (7 - len(str(pierwiastek[3])))))
print("+----+--------------------+-------+-------+")
# zadanie 2.5
print("##################### zadanie 2.5 ##################### ")
# Let S be a long string (many lines).
wierszyk = '''Stoi na stacji lokomotywa,
Ciężka, ogromna i pot z niej spływa:
Tłusta oliwa.
Stoi i sapie, dyszy i dmucha,
Żar z rozgrzanego jej brzucha bucha:
Uch - jak gorąco!
Puff - jak gorąco!
Uff - jak gorąco!
Już ledwo sapie, już ledwo zipie,
A jeszcze palacz węgiel w nią sypie.
Wagony do niej podoczepiali
'''
# Find the number of words in S.
print("Liczba słów gorąco w wierszu: ", wierszyk.count("gorąco"))
# Find the number of black characters in S.
print("Liczba nie-białych znaków: ", len(wierszyk.replace(" ", "").replace("\n", "")))
# Find the longest word in S.
tablicaSlow = []
tablicaSlowMalymiLiterami = []
for slowo in wierszyk.split(" "):
for element in slowo.split("\n"):
tablicaSlow.append(element)
tablicaSlowMalymiLiterami.append(element.lower())
najdluzszeSlowo = ""
for slowo in tablicaSlow:
if len(slowo)>len(najdluzszeSlowo):
najdluzszeSlowo = slowo
else:
continue
print("Najdluzsze slowo w wierszu: ", najdluzszeSlowo)
# Sort words from S according to (1) the lexicographic order, (2) the length.
tablicaSlowMalymiLiterami.sort()
print("alfabetycznie: ", tablicaSlowMalymiLiterami)
print("wg dlugosci: ", sorted(tablicaSlow, key=len))
# Find the number of zeros in a long number [hint: change to a string].
longInt = 92835893724000
a = str(longInt)
b = a.count("0")
print(b)
print("##################### zadanie 2.6 ##################### ")
# Find and explain the results.
t = (2, 4)
#print(t[2]) #arrays, touples etc are 0- based. [2] is out of range
#t.append(6) #appened is a touple not list so can;t be modified that way
#a, b = t ; print(a, b) ; means a new line so its assigment touple to the 2 vars, and then normal print od 2 values
print("##################### zadanie 2.7 ##################### ")
konwersjaDoArabskich = {
"M" : 1000,
"D" : 500,
"C" : 100,
"L" : 50,
"X" : 10,
"V" : 5,
"I" : 1
}
|
83b70ea5bcb07921616114ff1c59f9ae858745e1 | tganesan70/epai3-session6-tganesan70 | /test_part1.py | 11,286 | 4 | 4 | #'''
#Python code for poker game
#'''
import random
import itertools
import part1
## Globals
# Card values
vals = [ '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '10' , 'jack' , 'queen' , 'king' , 'ace' ]
# card suits
suits = [ 'spades' , 'clubs' , 'hearts' , 'diamonds' ]
# Question 1: Create the complete deck of 52 cards using map, filter and/or zip
def test_session6_part1_create_card_deck():
deck_new= part1.create_card_deck()
deck_normal = part1.create_card_deck_normal()
assert sorted(deck_new) == sorted(deck_normal), "Error card deck generation - Normal method and map method do not match"
assert len(deck_new) == 52, "Error card deck generation - number of cards in new method is less than 52"
assert len(deck_normal) == 52, "Error card deck generation - number of cards in normal method is less than 52"
# Question 2: Create the complete deck of 52 cards without using map, filter or zip
#print("Deck created by wo using map, filter, zip: \n ",deck_normal) #--> it is working correctly
# Question 3: From the complete deck of 52 cards, create two hands with 5 cards each
def test_session6_part1_create_poker_hand():
deck_normal = part1.create_card_deck_normal()
hand1 = part1.deal_cards(deck_normal, 5)
hand2 = part1.deal_cards(deck_normal, 3)
assert len(hand1) == 5, "Error in poker hand generation - number of cards is incorrect"
assert len(hand2) == 3, "Error in poker hand generation - number of cards is incorrect"
# Question 4: check for the winner of the game
def test_session6_part1_poker_game1():
# Test 1: Flush for hand1
hand1 = [('hearts','ace'),('hearts','king'),('hearts','queen'),('hearts','jack'),('hearts','2')]
hand2 = [('spade','ace'),('hearts','10'),('diamond','queen'),('hearts','3'),('diamond','2')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 1, "Game is over!!! You lost "
def test_session6_part1_poker_game2():
# Test 2: Royal Flush for hand1
print("############# test 1 ############")
hand1 = [('hearts', 'ace'), ('hearts', 'king'), ('hearts', 'queen'), ('hearts', 'jack'), ('hearts', '10')]
hand2 = [('spades', 'ace'), ('hearts', '10'), ('diamonds', 'queen'), ('hearts', '3'), ('diamonds', '2')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 1, "Game is over!!! You lost "
def test_session6_part1_poker_game3():
# Test 3: Royal Flush for hand2
hand2 = [('spades', 'ace'), ('spades', 'king'), ('spades', 'queen'), ('spades', 'jack'), ('spades', '10')]
hand1 = [('spades', 'ace'), ('hearts', '10'), ('diamonds', 'queen'), ('hearts', '3'), ('diamonds', '2')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 2, "Game is over!!! You lost "
def test_session6_part1_poker_game4():
# Test 4: Straight Flush for hand2
hand1 = [('clubs', '9'), ('spades', '10'), ('spades', 'queen'), ('spades', '3'), ('spades', '2')]
hand2 = [('hearts', '9'), ('hearts', 'king'), ('hearts', '8'), ('hearts', 'jack'), ('hearts', '10')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 2, "Game is over!!! You lost "
def test_session6_part1_poker_game5():
# Test 5: Straight Flush for hand1
hand2 = [('spades', '9'), ('clubs', '10'), ('spades', 'queen'), ('spades', '3'), ('spades', '2')]
hand1 = [('diamonds', '9'), ('diamonds', 'king'), ('diamonds', 'queen'), ('diamonds', 'jack'), ('diamonds', '10')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 1, "Game is over!!! You lost "
def test_session6_part1_poker_game6():
# Test 6: The Quad hand1
hand2 = [('spades', '9'), ('clubs', '10'), ('spades', 'queen'), ('spades', '3'), ('spades', '2')]
hand1 = [('clubs', 'king'), ('diamonds', 'king'), ('spades', 'king'), ('hearts', 'king'), ('diamonds', '10')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 1, "Game is over!!! You lost "
def test_session6_part1_poker_game7():
# Test 7: The Quad hand2
hand1 = [('spades', '9'), ('clubs', '10'), ('spades', 'queen'), ('spades', '3'), ('spades', '2')]
hand2 = [('clubs', 'queen'), ('diamonds', 'queen'), ('spades', 'queen'), ('hearts', 'queen'), ('spades', '10')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 2, "Game is over!!! You lost "
def test_session6_part1_poker_game8():
# Test 8: The Quad hand2
hand1 = [('spades', '9'), ('clubs', '10'), ('spades', 'queen'), ('spades', '3'), ('spades', '2')]
hand2 = [('clubs', 'queen'), ('diamonds', 'queen'), ('spades', 'queen'), ('hearts', 'queen'), ('spades', '10')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 2, "Game is over!!! You lost "
def test_session6_part1_poker_game9():
# Test 9: The full house in hand2
hand1 = [('spades', '9'), ('clubs', '10'), ('spades', 'queen'), ('spades', '3'), ('spades', '2')]
hand2 = [('clubs', 'queen'), ('diamonds', 'queen'), ('spades', 'queen'), ('hearts', 'ace'), ('spades', 'ace')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 2, "Game is over!!! You lost "
def test_session6_part1_poker_game10():
# Test 10: The full house in hand1
hand2 = [('spades', '9'), ('clubs', '10'), ('spades', 'queen'), ('spades', '3'), ('spades', '2')]
hand1 = [('clubs', 'king'), ('diamonds', 'king'), ('spades', 'king'), ('hearts', 'jack'), ('spades', 'jack')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 1, "Game is over!!! You lost "
def test_session6_part1_poker_game11():
# Test 11: The flush in hand1
hand1 = [('hearts', '2'), ('clubs', '3'), ('diamonds', 'ace'), ('spades', '5'), ('spades', '8')]
hand2 = [('diamonds', '3'), ('diamonds', '5'), ('diamonds', '7'), ('diamonds', '9'), ('diamonds', 'queen')]
#hand2 = [('spades', '2'), ('spades', '4'), ('spades', '6'), ('spades', '8'), ('spades', 'king')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 1, "Game is over!!! You lost "
def test_session6_part1_poker_game12():
# Test 12: The flush in hand1
hand2 = [('spades', '9'), ('clubs', '10'), ('spades', 'queen'), ('spades', '3'), ('spades', '2')]
hand1 = [('diamonds', '3'), ('diamonds', '5'), ('diamonds', '7'), ('diamonds', '9'), ('diamonds', 'queen')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 1, "Game is over!!! You lost "
def test_session6_part1_poker_game13():
# Test 13: The straight in hand2
hand1 = [('hearts', '2'), ('clubs', '3'), ('diamonds', 'ace'), ('spades', '5'), ('spades', '8')]
hand2 = [('diamonds', '3'), ('clubs', '4'), ('spades', '5'), ('hearts', '6'), ('diamonds', '7')]
#hand2 = [('spades', '2'), ('spades', '4'), ('spades', '6'), ('spades', '8'), ('spades', 'king')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 2, "Game is over!!! You lost "
def test_session6_part1_poker_game14():
# Test 14: The straight in hand1
hand2 = [('spades', '9'), ('clubs', '10'), ('spades', 'queen'), ('spades', '3'), ('spades', '2')]
hand1 = [('diamonds', '6'), ('clubs', '7'), ('spades', '8'), ('hearts', '9'), ('diamonds', '10')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 1, "Game is over!!! You lost "
def test_session6_part1_poker_game15():
# Test 15: The triplets in hand2
hand1 = [('hearts', '2'), ('clubs', '3'), ('diamonds', 'ace'), ('spades', '5'), ('spades', '8')]
hand2 = [('diamonds', 'queen'), ('clubs', 'queen'), ('spades', 'queen'), ('hearts', '6'), ('diamonds', '7')]
#hand2 = [('spades', '2'), ('spades', '4'), ('spades', '6'), ('spades', '8'), ('spades', 'king')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 2, "Game is over!!! You lost "
def test_session6_part1_poker_game16():
# Test 16: The triplets in hand1
hand2 = [('spades', '9'), ('clubs', '10'), ('spades', 'queen'), ('spades', '3'), ('spades', '2')]
hand1 = [('diamonds', 'king'), ('clubs', 'king'), ('spades', 'king'), ('hearts', 'ace'), ('diamonds', '9')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 1, "Game is over!!! You lost "
def test_session6_part1_poker_game17():
# Test 15: The pairs in hand2
hand1 = [('hearts', '2'), ('clubs', '3'), ('diamonds', 'ace'), ('spades', '5'), ('spades', '8')]
hand2 = [('diamonds', 'queen'), ('clubs', 'queen'), ('spades', 'king'), ('hearts', '6'), ('diamonds', '7')]
#hand2 = [('spades', '2'), ('spades', '4'), ('spades', '6'), ('spades', '8'), ('spades', 'king')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 2, "Game is over!!! You lost "
def test_session6_part1_poker_game18():
# Test 16: The pairs in hand1
hand2 = [('spades', '9'), ('clubs', '10'), ('spades', 'queen'), ('spades', '3'), ('spades', '2')]
hand1 = [('diamonds', 'king'), ('clubs', 'king'), ('spades', '2'), ('hearts', 'ace'), ('diamonds', '9')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 1, "Game is over!!! You lost "
def test_session6_part1_poker_game19():
# Test 17: One pairs in hand2
hand1 = [('hearts', '2'), ('clubs', '3'), ('diamonds', 'ace'), ('spades', '5'), ('spades', '8')]
hand2 = [('diamonds', 'queen'), ('clubs', 'queen'), ('spades', 'king'), ('hearts', '6'), ('diamonds', '7')]
#hand2 = [('spades', '2'), ('spades', '4'), ('spades', '6'), ('spades', '8'), ('spades', 'king')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 2, "Game is over!!! You lost "
def test_session6_part1_poker_game20():
# Test 18: One pairs in hand1
hand2 = [('spades', '9'), ('clubs', '10'), ('spades', 'queen'), ('spades', '3'), ('spades', '2')]
hand1 = [('diamonds', 'king'), ('clubs', 'king'), ('spades', '2'), ('hearts', 'ace'), ('diamonds', '9')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 1, "Game is over!!! You lost "
def test_session6_part1_poker_game21():
# Test 17: two pairs in hand2
hand1 = [('hearts', '2'), ('clubs', '3'), ('diamonds', 'ace'), ('spades', '5'), ('spades', '8')]
hand2 = [('diamonds', 'queen'), ('clubs', 'queen'), ('spades', 'king'), ('hearts', 'king'), ('diamonds', '7')]
#hand2 = [('spades', '2'), ('spades', '4'), ('spades', '6'), ('spades', '8'), ('spades', 'king')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 2, "Game is over!!! You lost "
def test_session6_part1_poker_game22():
# Test 18: two pairs in hand1
hand2 = [('spades', '9'), ('clubs', '10'), ('spades', 'queen'), ('spades', '3'), ('spades', '2')]
hand1 = [('diamonds', 'king'), ('clubs', 'king'), ('spades', '2'), ('hearts', '2'), ('diamonds', '9')]
winner = part1.poker_winner(hand1, hand2)
assert winner == 1, "Game is over!!! You lost "
def test_session6_part1_poker_game23():
# Test 17: Random hands - test 1
deck_new = part1.create_card_deck()
hand1 = part1.deal_cards(deck_new, 5)
hand2 = part1.deal_cards(deck_new, 5)
winner = part1.poker_winner(hand1, hand2)
assert winner != 0, "Game is over!!! You lost "
def test_session6_part1_poker_game24():
# Test 18: Random hands - test 2
deck_new = part1.create_card_deck()
hand2 = part1.deal_cards(deck_new, 5)
hand1 = part1.deal_cards(deck_new, 5)
winner = part1.poker_winner(hand1, hand2)
assert winner != 0, "Game is over!!! You lost "
|
558315a7d9bb3a2a64c673b7c38d1bd39fb0c934 | nikhilcusc/HRP-1 | /ProbSol/magicSquare2.py | 1,137 | 3.734375 | 4 | '''
You will be given a 3x3 matrix s of integers in the inclusive range 1-9. We can convert any digit a to any other digit b in the range 1-9 at cost of |a-b|. Given s, convert it into a magic square at minimal cost. Print this cost on a new line.
'''
def getAllSquares():
allMagicSquares=[
[[2, 7, 6],
[9, 5, 1],
[4, 3, 8]],
[[2, 9, 4],
[7, 5, 3],
[6, 1, 8]],
[[4, 3, 8],
[9, 5, 1],
[2, 7, 6]],
[[4, 9, 2],
[3, 5, 7],
[8, 1, 6]],
[[6, 1, 8],
[7, 5, 3],
[2, 9, 4]],
[[6, 7, 2],
[1, 5, 9],
[8, 3, 4]],
[[8, 1, 6],
[3, 5, 7],
[4, 9, 2]],
[[8, 3, 4],
[1, 5, 9],
[6, 7, 2]]]
return allMagicSquares
def formingMagicSquare(s):
magicSquares=getAllSquares()
minDiff=[]
for magicSquare in magicSquares:
tempDiff=0
for ind1 in range( len(s)):
for ind2 in range(len(s)):
tempDiff+=abs(magicSquare[ind1][ind2] - s[ind1][ind2])
minDiff.append(tempDiff)
return min(minDiff)
s= [[4,8,2],
[4,5,7],
[6,1,6]]
s2=[[4,9,2],
[3,5,7],
[8,1,5]]
print(formingMagicSquare(s2))
|
41d106be54c4e9991ecbf67047ba74aaeecb527a | NakulK48/Project-Euler-Solutions | /52.py | 928 | 3.53125 | 4 | #PROBLEM 52
#Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
import time
start = time.clock()
i = 1
truths = []
while True:
truths = []
a = str(i)
f = str(6*i)
if len(f) == len(a):
A, B, C, D, E, F = [], [], [], [], [], [],
for j in a:
A.append(j)
for j in str(2*i):
B.append(j)
for j in str(3*i):
C.append(j)
for j in str(4*i):
D.append(j)
for j in str(5*i):
E.append(j)
for j in f:
F.append(j)
A.sort()
B.sort()
C.sort()
D.sort()
E.sort()
F.sort()
if A == B == C == D == E == F:
print ("The answer is", a, "whose multiples are:",str(2*i),str(3*i),str(4*i),str(5*i),f)
print ("That took",time.clock()-start,"seconds")
break
i += 1
|
704c9c2259021c2d53443dcb82480e3aefa65a90 | DenisEke/BSC_Artificial_Intelligence | /Computational Thinking/Assignment 3/Corona_Proof.py | 838 | 3.890625 | 4 | #Ask for number of friend in a friendly way
print("Hey I am here to check whether your party is corona proof. How many friends are you planning to invite? ")
numberFriends=int(input())
#If less than or equal to 6 friends
if numberFriends<=6:
#ask for friends name
print("This should work out fine. Tell me their names and I will invite them. Just enter the names with spaces between: (Casy Mendel Lister)")
#split is used to divide a string by a certain char (default is sapce)
#creates an array of the entered friends.
friends=input().split()
#for every of the friends we print that he/she/it was invited!
for friend in friends:
print(friend +" has been invited!")
#If more than 6 friends
else:
#inform user that he can't throw this party
print("You can't throw this party. It is not Corona proven.") |
8febba19c20a2ed2caf560f0dc7bbf16e88e7485 | arnava2001/Python-Code | /Anagram Game/anagram.py | 2,106 | 3.5625 | 4 | import threading
import time
import enchant
import random
from collections import Counter
score = 0
def genLetterPool():
vowels = ['a', 'e', 'i', 'o', 'u']
letters = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p','r', 's', 't', 'v', 'w', 'x', 'y']
s = ''
for n in range(2):
s+=random.choice(vowels)
for n in range(4):
s+=random.choice(letters)
return s
def isWord(str):
d = enchant.Dict('en_US')
return d.check(str)
def isFrom(guess, ana):
for n in range(len(guess)):
if guess[n] not in ana:
return False
guessCt = Counter(guess)
anaCt = Counter(ana)
anaCt.subtract(guessCt)
for n in range(len(guess)):
if anaCt[guess[n]] < 0:
return False
return True
def play():
global score
ana = genLetterPool()
anaList = list(ana)
printedList = " ".join(anaList)
guesses = []
print('Welcome to Anagrams: You have 60 seconds to try to make words out of the letters in the bank (2-6 Letter words only)')
while True:
print("Bank: ",printedList)
guess = input("Guess (Min. 2 Letters): ").strip()
if len(guess) < 2 or len(guess) > 6:
print("Sorry, guesses must be between 2 and 6 letters\n")
continue
if isWord(guess) == False:
print("Sorry, this is not a real word\n")
continue
if isFrom(guess, ana) == False:
print("This guess is not valid given the bank\n")
continue
if guess in guesses:
print("Sorry, you've already guessed this!\n")
continue
guesses.append(guess)
leng = len(guess)
if(leng == 2):
score += 100
print("Good job! Current Score: ",score,'\n')
if(leng == 3):
score += 200
print("Great job! Current Score: ",score,'\n')
if(leng == 4):
score += 400
print("Wow! Current Score: ",score,'\n')
if(leng == 5):
score += 1000
print("Sweet! Current Score: ",score,'\n')
if(leng == 6):
score += 2000
print("Perfect! Current Score: ",score,'\n')
t = threading.Thread(target = play)
t.daemon = True
t.start()
time.sleep(60)
print("Out of time! Final Score: ",score)
|
97e5e4247df8709ddddd41fbd6495ba900a89b40 | taxijjang/algorithm | /연속된 수의 합.py | 228 | 3.703125 | 4 | import math
def solution(num, total):
center_value = math.sqrt(total)
for start in range(1, num + 1):
pass
return 1
if __name__=="__main__":
num = 3
total = 12
print(solution(num, total))
|
104feeeb1f402f6807ff950524d6faa1789d649e | kimjeonghyon/Algorithms | /Python/MovingAverage.py | 523 | 3.671875 | 4 | def movingAverage(data,num) :
ret = []
for i in range(num-1,len(data)):
sum = 0
for j in range(0,num) :
sum += data[i-j]
ret.append(sum/num)
return ret
def movingAverage2(data,num) :
ret = []
sum = 0
for i in range(0,num):
sum += data[i]
for i in range(num,len(data)) :
ret.append(sum/num)
sum = sum + data[i]-data[i-num]
return ret
data = [2,2,3,4,5,6,7,9,9]
result = movingAverage2(data,3)
print (result)
|
4f6dd237004237ab01ce4a5b5b59fa85f93e805e | ravi7501/computer-graphics | /dda_algo.py | 832 | 3.828125 | 4 | import matplotlib.pyplot as ravi
def round(n):
return int(n+0.5)
def drawDDA(x1, y1, x2, y2):
x = [x1]
y = [y1]
steps = abs((x2 - x1) if abs(x2 - x1) > abs(y2 - y2) else (y2 - y1))
dx = (x2 - x1) / float(steps)
dy = (y2 - y1) / float(steps)
print(((round(x[0]), round(y[0]))))
i = 1
for i in range(steps):
l = round(x[i] + dx)
m = round(y[i] + dy)
x.append(l)
y.append(m)
i = i + 1
print((((x[i]), y[i])))
ravi.plot(x, y, 'o-', linewidth='1.5')
ravi.show()
ravi.grid()
ravi.xlim(0,100)
ravi.xlim(0,100)
a = int(input("Enter x1: "))
b = int(input("Enter y1: "))
c = int(input("Enter x2: "))
d = int(input("Enter y2: "))
drawDDA(a,b,c,d)
|
f16bebd9f409ee6f6ae0941303328c3c57bed054 | AlakiraRaven/ProjectEuler | /Problem3_LargestPrimeFactor.py | 566 | 4.375 | 4 | '''
the code works for smaller numbers, does not scale well
'''
import math
if __name__ == "__main__":
x = 0
x = int(input('Please input a positive integer X: '))
while x < 0:
print('Your number is negative, please input a positive value.')
x = int(input('Please input a positive integer X: '))
print('Nice \n')
BiggestValue = 0
for i in range(2, int((math.sqrt(x))+1)):
if x % i == 0:
BiggestValue = i
x = x/i
print('The largest prime factor is: ', end='')
print(BiggestValue) |
5f755ffc052eab58dc4c2ca9a41f5f5f2f5be3e8 | vikask1640/Demogit | /calculator.py | 1,571 | 4.09375 | 4 | #..............CALCULATOR................
import math
def calculator():
print("Enter the values of a")
a=float(input())
print("Enter the vaues of b")
b=float(input())
print()
print("Addition of numbers")
def adds(a,b):
add=a+b
print(add)
adds(a,b)
print()
print("Subtraction of numbers")
def subs(a,b):
sub=a-b
print(sub)
subs(a,b)
print()
print("Multiply of numbers")
def muls(a,b):
mul=a*b
print(mul)
muls(a,b)
print()
print("Divisions of numbers")
def divs(a,b):
div=a/b
print(div)
divs(a,b)
print()
print("Modulas of numbers")
def mods(a,b):
mod=a%b
print(mod)
mods(a,b)
print()
print("Sqrt of the numbers")
def sqrts(a,b):
sq=math.sqrt(a)
sqs=math.sqrt(b)
print(sq)
print(sqs)
sqrts(a,b)
print()
print("Powers of numbers")
def powr(a,b):
pwr=math.pow(a,b)
print(pwr)
powr(a,b)
def powrs(b,a):
pwrs=math.pow(b,a)
print(pwrs)
powrs(a,b)
print()
print("floor values of numbers")
def flr(a,b):
flrs=math.floor(a)
flrss=math.floor(b)
print(flrs)
print(flrss)
flr(a,b)
print()
print("Ceils values of the numbers")
def cel(a,b):
cles=math.ceil(a)
celss=math.ceil(b)
print(cles)
print(celss)
cel(a,b)
calculator()
|
589a92512421b75379dbc3f7547fdd0736ff68ca | leekyunghun/bit_seoul | /ML/m32_outlier.py | 1,750 | 3.515625 | 4 |
############################### 데이터 안에 있는 이상치 확인 ################################
import numpy as np
# def outliers(data_out):
# quartile_1, quartile_3 = np.percentile(data_out, [25, 75])
# print("1사분위 : ", quartile_1) # 3.25
# print("3사분위 : ", quartile_3) # 97.5
# iqr = quartile_3 - quartile_1
# lower_bound = quartile_1 - (iqr * 1.5)
# upper_bound = quartile_3 + (iqr * 1.5)
# return np.where((data_out > upper_bound) | (data_out < lower_bound))
# a = np.array([1, 2, 3, 4, 10000, 6, 7, 5000, 90, 100])
# b = outliers(a)
# print("이상치의 위치 : ", b)
# # 과제 2차원 배열 이상이 input일때를 생각해서 2차원 배열일때 outliers가 기능 할 수 있도록 수정
a = np.array([[1,2,3,4,10000,6,7,5000,90,100],
[10000,20000,3,40000,50000,60000,70000,8,90000,100000]])
a = a.transpose()
print(a)
def outliers(data_out):
result = []
for i in range(data_out.shape[1]):
quartile_1, quartile_3 = np.percentile(data_out[:, i], [25, 75])
print("==========", i+1, "열==========")
print("1사분위 : ", quartile_1)
print("3사분위 : ", quartile_3, "\n")
iqr = quartile_3 - quartile_1
lower_bound = quartile_1 - (iqr * 1.5)
upper_bound = quartile_3 + (iqr * 1.5)
print("upper_bound : ", upper_bound , "lower_bound : ", lower_bound)
a = np.where((data_out[:, i] > upper_bound) | (data_out[:, i] < lower_bound))
a = np.array(a)
if a.shape[1] == 0:
a = np.append(a, 0)
a = a.reshape(1, a.shape[0])
result.append(a)
return result
b = outliers(a)
print("열 마다 이상치의 위치 : ", b)
|
c12083e8cbc0301457e00b4fdbc979d807035dfe | vincent-vega/adventofcode | /2017/day_03/3.py | 1,577 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def _square_coord(square: int) -> (int, int):
max_steps, step_cnt = 1, 1
direction = 0 # 0: RIGHT, 1: UP, 2: LEFT, 3: DOWN
x, y = 0, 0
for _ in range(2, square + 1):
step_cnt -= 1
x += 1 if direction == 0 else -1 if direction == 2 else 0
y += 1 if direction == 1 else -1 if direction == 3 else 0
if step_cnt == 0:
direction = (direction + 1) % 4
if direction == 2 or direction == 0:
max_steps += 1
step_cnt = max_steps
return x, y
def part1(square: int) -> int:
return sum(map(abs, _square_coord(square)))
def _adj(x: int, y: int) -> list:
return [ (x + dx, y + dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1) if (dx, dy) != (0, 0) ]
def part2(square: int) -> int:
max_steps, step_cnt = 1, 1
direction = 0 # 0: RIGHT, 1: UP, 2: LEFT, 3: DOWN
x, y = 0, 0
mem = { (0, 0): 1 }
for _ in range(2, square + 1):
step_cnt -= 1
x += 1 if direction == 0 else -1 if direction == 2 else 0
y += 1 if direction == 1 else -1 if direction == 3 else 0
S = sum(mem.get(c, 0) for c in _adj(x, y))
if S > square:
return S
mem[(x, y)] = S
if step_cnt == 0:
direction = (direction + 1) % 4
if direction == 2 or direction == 0:
max_steps += 1
step_cnt = max_steps
raise Exception('Not found')
if __name__ == '__main__':
print(part1(368078)) # 371
print(part2(368078)) # 369601
|
883100fd6e40f554397b5a4b47fb44823b1801a0 | kushagrapatidar/Newton-School-Code-Contests | /September 2021 Code Contest/Que_01.py | 246 | 3.59375 | 4 | nums=input()
nums=nums.split()
for i in range(len(nums)):
nums[i]=int(nums[i])
lst=[0,1,2]
lst[2]=max(max(nums[0],nums[1]),nums[2])
lst[0]=min(min(nums[0],nums[1]),nums[2])
for _ in nums:
if _ not in lst:
lst[1]=_
print(lst[1])
|
5b57068b8e06fbc23bc498cd1ee0750c46f8563f | MrCsabaToth/IK | /2019Nov/practice4/critical_connections_dfs_recursive.py | 829 | 3.5 | 4 | def findCriticalConnections(noOfServers, noOfConnections, connections):
critical = []
visited = [False] * noOfServers
def dfs(source):
visited[source] = True
for neighbor in adj_list[source]:
if not visited[neighbor]:
dfs(neighbor)
for connection in connections:
adj_list = [None] * noOfServers
visited = [False] * noOfServers
edges = connections[:]
edges.remove(connection)
for vertex in range(noOfServers):
adj_list[vertex] = list()
for edge in edges:
adj_list[edge[0]].append(edge[1])
adj_list[edge[1]].append(edge[0])
dfs(0)
if any(v is False for v in visited):
critical.append(connection)
return critical if critical else [(-1, -1)]
|
8930c19930bd1649d78e55e03c4f5e95add89727 | TulasiGupta/master | /python/sqllite/user.py | 1,138 | 3.65625 | 4 | import sqlite3
class User(object):
def __init__(self, _id, username, password):
self.id = _id
self.username = username
self.password = password
@classmethod
def find_by_username(cls, username):
print("username "+username)
connection = sqlite3.connect("data.db")
cursor = connection.cursor()
selectquery = "select * from users where username = ?"
result = cursor.execute(selectquery, (username,))
print("result %r", result)
row = result.fetchone()
print(row)
user = None
if row:
user = cls(row[0], row[1], row[2])
connection.close()
print(user)
return user
@classmethod
def find_by_id(cls, id):
connection = sqlite3.connect("data.db")
cursor = connection.cursor()
selectquery = "select * from users where id = ?"
result = cursor.execute(selectquery, (id,))
row = result.fetchone()
user = None
if row:
user = cls(row[0], row[1], row[2])
connection.close()
print(user)
return user |
113f54d89baebe043e68e9ade756d880eb9d9a01 | ElvinChen1994/PythonPlan | /Chapter1/test_loop.py | 1,044 | 3.875 | 4 | # -*- coding:utf-8 -*-
# @Time: 2021/7/26 12:26 下午
# @Author: Elvin
'''for in '''
sum = 0
for x in range(100):
sum += x
print(sum)
'''增加歩长'''
sum = 0
for x in range(1,100,2):
sum += x
print(sum)
'''while 循环'''
import random
answer = random.randint(1,100)
counter = 0
while True:
counter += 1
number = int(input('请输入:'))
if number < answer:
print('大一点')
elif number > answer:
print('小一点')
else:
print('答对了')
break
print('你猜对的次数%d次'%counter)
'''循环嵌套'''
for i in range(1,10):
for n in range(1, i+1):
print('%d*%d=%d'%(i,n+1,i*n),end='\t')
print()
'''判断一个整数是不是素数'''
from math import sqrt #需要平方根的值
num = int(input('请输入一个正整数:'))
end = int(sqrt(num))
is_prime = True
for x in range(2, end + 1):
if num % x == 0:
is_prime = False
break
if is_prime and num != 1:
print('%d是素数'% num)
else:
print('%d不是素数'% num) |
1221e5fb34a0eb201bad210deea12039a50660c1 | hieugomeister/ASU | /CST100/sobeledge.py | 2,647 | 3.5 | 4 | import image
import math
import sys
# Code adapted from http://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/image-processing/edge_detection.html
# Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
# this algorithm takes some time for larger images - this increases the amount of time
# the program is allowed to run before it times out
sys.setExecutionLimit(20000)
img = image.Image("luther.jpg")
newimg = image.EmptyImage(img.getWidth(),img.getHeight())
win = image.ImageWin()
for x in range(1, img.getWidth()-1): # ignore the edge pixels for simplicity (1 to width-1)
for y in range(1, img.getHeight()-1): # ignore edge pixels for simplicity (1 to height-1)
# initialise Gx to 0 and Gy to 0 for every pixel
Gx = 0
Gy = 0
# top left pixel
p = img.getPixel(x-1, y-1)
r = p.getRed()
g = p.getGreen()
b = p.getBlue()
# intensity ranges from 0 to 765 (255 * 3)
intensity = r + g + b
# accumulate the value into Gx, and Gy
Gx += -intensity
Gy += -intensity
# remaining left column
p = img.getPixel(x-1, y)
r = p.getRed()
g = p.getGreen()
b = p.getBlue()
Gx += -2 * (r + g + b)
p = img.getPixel(x-1, y+1)
r = p.getRed()
g = p.getGreen()
b = p.getBlue()
Gx += -(r + g + b)
Gy += (r + g + b)
# middle pixels
p = img.getPixel(x, y-1)
r = p.getRed()
g = p.getGreen()
b = p.getBlue()
Gy += -2 * (r + g + b)
p = img.getPixel(x, y+1)
r = p.getRed()
g = p.getGreen()
b = p.getBlue()
Gy += 2 * (r + g + b)
# right column
p = img.getPixel(x+1, y-1)
r = p.getRed()
g = p.getGreen()
b = p.getBlue()
Gx += (r + g + b)
Gy += -(r + g + b)
p = img.getPixel(x+1, y)
r = p.getRed()
g = p.getGreen()
b = p.getBlue()
Gx += 2 * (r + g + b)
p = img.getPixel(x+1, y+1)
r = p.getRed()
g = p.getGreen()
b = p.getBlue()
Gx += (r + g + b)
Gy += (r + g + b)
# calculate the length of the gradient (Pythagorean theorem)
length = math.sqrt((Gx * Gx) + (Gy * Gy))
# normalise the length of gradient to the range 0 to 255
length = length / 4328 * 255
length = int(length)
# draw the length in the edge image
newpixel = image.Pixel(length, length, length)
newimg.setPixel(x, y, newpixel)
newimg.draw(win)
win.exitonclick()
|
5a8b9bbb1f68ee455845b89775352d003b19c369 | bokveizen/leetcode | /836_Rectangle Overlap.py | 330 | 3.734375 | 4 | # https://leetcode-cn.com/problems/rectangle-overlap/
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
x1 = max(rec1[0], rec2[0])
y1 = max(rec1[1], rec2[1])
x2 = min(rec1[2], rec2[2])
y2 = min(rec1[3], rec2[3])
return x2 - x1 > 0 and y2 - y1 > 0
|
4b223a623f3e5fc16b658c35d192758c8f1a746c | rose317/network_program | /demo_正则表达式.py | 239 | 3.671875 | 4 | import re
names = ["name","_name","2_name","__name__","name#name"]
for i in names:
ret = re.match(r"[a-zA-Z_][a-zA-Z0-9_]*$",i)
if ret:
print("变量名%s符合要求" % i)
else:
print("变量名%s非法" % i) |
8a514cffbc1a232db2a9b4b9a5c68df84d9597d2 | sinhasaroj/Python_programs | /properties_use_cases/property_method_for_type_checking.py | 626 | 3.71875 | 4 | class Person:
def __init__(self,first_name):
self._first_name = first_name
# Getter Function
@property
def first_name(self):
return self._first_name
# Setter Function
@first_name.setter
def first_name(self,value):
if not isinstance(value,str):
raise ValueError(f'Expected a string,{value} given.')
else:
self._first_name = value
# Deleter Function(optional)
@first_name.deleter
def first_name(self):
raise AttributeError("Can't delete Attribute.")
# Creating Instance
p1 = Person('John')
print(p1.first_name)
|
bc745644f3ffbfc7e64a751c38dc87397ec09f35 | pidddgy/competitive-programming | /dmoj/modefinding2.py | 97 | 3.515625 | 4 | #!python3
N = int(input())
nums = input().split()
nums2 = [int(x) for x in nums]
# print(nums) |
e991eb8dad2e62bf377d3c3bd96a5c73920f7691 | Timur597/First6team | /6/Tema6(Dict,Set)/14.d_100.py | 159 | 3.5 | 4 | 14 Задание
farm_2 = {"cow", "horse", "donkey", "cat", "dog"}
farm_1 = {"dog", "cat", "mouse", "sheep"}
farm_2.difference_update (farm_1)
print (farm_2)
|
4bbd1023acd3458bb63ecac6a6e8738bb9d10c9b | WeAreAVP/avp-tools | /otter-txt-to-vtt-script/otter-txt-to-vtt.py | 4,681 | 3.671875 | 4 | '''
Purpose: Converts TXT files to WebVTT files.
Usage: 'python [path to otter-txt-to-vtt.py]' or 'python3 [path to otter-txt-to-vtt.py]' depending on your environment config.
'''
import os
import re
from datetime import datetime
from datetime import timedelta
use = input('Would you like to convert a single TXT or all the TXTs in a folder? Type "file" or "folder": ').strip().lower()
while use != 'file' and use != 'folder':
print('Looks like you didn\'t type "file" or "folder". Please try running the script again')
use = input('Would you like to convert a single TXT or all the TXTs in a folder? Type "file" or "folder": ').strip().lower()
print()
if use == 'file':
input_path = input('What is the full path of the TXT file?: ').strip()
elif use == 'folder':
input_path = input('What is the full path of the folder containing the TXT?: ').strip()
if os.name == 'posix':
input_path = input_path.replace('\\','')
else:
input_path = input_path.replace('\\','/')
path = input_path.strip().strip('"')
if use == 'file':
file = '/'.join(path.split('/')[-1:])
path = '/'.join(path.split('/')[:-1])
output_folder = path + '/vtts'
try:
if not os.path.exists(output_folder):
os.makedirs(output_folder)
except:
print()
print('Sorry,', path, 'is not a valid directory.')
print()
exit()
def process_file(file):
f = open(output_folder + '/' + file[:-4] + '.vtt', 'w')
first_line = True
with open(path + '/' + file, 'r') as txt:
saved_speaker = None
speaker_bool = False
storage = ''
start_time = None
end_time = None
new_start_time = None
for line in txt:
if line.strip() == 'Transcribed by https://otter.ai':
continue
if first_line:
f.write('WEBVTT' + '\n')
f.write('\n')
first_line = False
times = re.findall(r'\d{1,2}:\d{2}', line)
if times:
start_time = new_start_time
time = times[0]
time_len = len(time)
speaker = line.strip()[:-time_len].strip()
speaker_bool = False
split_time = time.split(':')
if len(split_time) == 1:
time = '00:00:' + time
elif len(split_time) == 2:
if len(split_time[0]) == 0:
time = '00:00' + time
elif len(split_time[0]) == 1:
time = '00:0' + time
elif len(split_time[0]) == 2:
time = '00:' + time
else:
print('The time format is strange. Please contact AVP.')
exit()
elif len(split_time) == 3:
if len(split_time[0]) == 0:
time = '00' + time
elif len(split_time[0]) == 1:
time = '0' + time
elif len(split_time[0]) > 2:
print('The time format is strange. Please contact AVP.')
exit()
elif len(split_time) > 3:
print('The time format is strange. Please contact AVP.')
exit()
new_start_time = time + '.000'
if start_time :
end_time = datetime.time(datetime.strptime(new_start_time, '%H:%M:%S.%f') - timedelta(milliseconds=1))
f.write(str(start_time) + ' --> ' + str(end_time)[:-3] + '\n')
f.write(storage)
storage = ''
if speaker:
saved_speaker = speaker.upper()
speaker_bool = True
else:
if speaker_bool:
line = saved_speaker + ': ' + line
speaker_bool = False
storage = storage + line
end_time = datetime.time(datetime.strptime(new_start_time, '%H:%M:%S.%f') + timedelta(milliseconds=2000))
f.write(str(new_start_time) + ' --> ' + str(end_time) + '.000\n')
f.write(storage)
f.close()
if use == 'file':
if file[-4:] != '.txt':
print('Sorry, file is not a .txt')
exit()
process_file(file)
elif use == 'folder':
for file in os.listdir(path):
if file[-4:] != '.txt':
continue
if file == '.DS_Store':
continue
if os.path.isdir(path + '/' + file):
continue
process_file(file)
print()
print('Finished converting TXTs to VTTs.')
|
73f196e0f76d888b5f88db7f8795f7df39021317 | gitprouser/LeetCode-3 | /interleave.py | 801 | 3.921875 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def interleave(p, q):
dummy = ListNode(0)
cur = dummy
while p is not None and q is not None:
cur.next = p
cur = cur.next
p = p.next
cur.next = q
cur = cur.next
q = q.next
if p is not None:
cur.next = p
elif q is not None:
cur.next = q
return dummy.next
def print_list(head):
path = ''
while head:
path += (str(head.val) + '->')
head = head.next
return path
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node6 = ListNode(6)
node1.next = node2
node2.next = node3
node3.next = node4
node5.next = node6
print print_list(interleave(node1, node5))
|
7317cd586606f98c6459206d78b6860c59b05e73 | rocketII/project-chiphers-old | /playfair.py | 8,436 | 3.53125 | 4 | def playfair_encrypt(secret, key, junkChar):
'''
Encrypt using playfair, enter secret followed by key. Notice we handle only lists foo['h','e','l','p']
English letters only lowercase.
:param secret: text string of english letters only,
:param key: string of english letters only, thanks.
:param junkChar: junkchar fill out betwwen two copies of letters.
:return: encrypted text.
'''
ciphertxt= []
clearTxt = secret
junk = junkChar
nyckel = key
nyckelLen = len(nyckel)
#Create 2D list. Enter key with censored duplicate letters, row by row across columns
col1=[None] *5
col2=[None] *5
col3=[None] *5
col4=[None] *5
col5=[None] *5
tmp = [col1,col2,col3,col4,col5] # currently good enough without list copies in main list.
row=0
col=0
for read in nyckel:
# count(read) make sure no copies are in the column lists.
if tmp[0].count(read) + tmp[1].count(read) + tmp[2].count(read) + tmp[3].count(read) + tmp[4].count(read) == 0:
tmp[col][row]= read
col = (col + 1) % 5
if col == 0:
row = (row + 1) % 5
#append the rest of the letters in chronologically order
english = ['a','b','c','d','e','f','g','h','i','k','l','m','n','o','p','q','r','s','t','u','v','w','x','z','y']
for read in english:
if tmp[0].count(read) + tmp[1].count(read) + tmp[2].count(read) + tmp[3].count(read) + tmp[4].count(read) == 0:
tmp[col][row] = read
col = (col + 1) % 5
if col == 0:
row = (row + 1) % 5
#print "Table: ",tmp
# create bigrams of clear text. no bigram using samme letter allowed insert junk letter 'n' between
length = len(clearTxt)
previous = None; insertAt = 0
for read in clearTxt:
if previous == read:
clearTxt.insert(insertAt, junk)
insertAt +=1
previous=junk
continue
previous = read
insertAt += 1
length = len(clearTxt)
if length % 2 == 1:
clearTxt.append(junk)
# Find 'i' so that we can replace 'j' with 'i' coordinates
rowFor_i = 0; colFor_i = 0
for row in range(5):
for col in range(5):
if tmp[col][row] == 'i':
rowFor_i = row
colFor_i = col
#print tmp[col][row]," discovered at col: ",col," row: ",row
# print "Bigram Source: ",clearTxt
# read two letters from cleartext, use 2D list applie rules. Append result in ouput list
listlength = len(clearTxt)
A = 0; rowFor0 = 0; colFor0 = 0; rowFor1 = 0; colFor1 = 0
temp = ['.','.']
while A < listlength:
if (clearTxt[A] == 'j'):
temp[0] = 'i'
else:
temp[0] = clearTxt[A]
A += 1
if A < listlength:
if (clearTxt[A] == 'j'):
temp[1] = 'i'
else:
temp[1] = clearTxt[A]
A += 1
#print "Current bigram: ", temp
for row in range(5):
for col in range(5):
if tmp[col][row] == temp[0]:
rowFor0 = row
colFor0 = col
#print "round:",A,"row: ",row, "col: ", col," char: ", tmp[col][row]
elif tmp[col][row] == temp[1]:
rowFor1 = row
colFor1 = col
#print "round:",A,"row: ", row, "col: ", col, " char: ", tmp[col][row]
if rowFor0 == rowFor1:
#read in order, row/col index 0 goes first
ciphertxt.insert(0, tmp[(colFor0 + 1)%5][rowFor0])
ciphertxt.insert(0, tmp[(colFor1 + 1)%5][rowFor1])
#print ' '
elif colFor1 == colFor0:
# read in order, row/col index 0 goes first
ciphertxt.insert(0, tmp[colFor0][(rowFor0 + 1)%5])
ciphertxt.insert(0, tmp[colFor1][(rowFor1 + 1)%5])
#print ' '
else:
if colFor0 > colFor1:
# read in order, row/col index 0 goes first
colDiff = abs(colFor0 - colFor1)
#print "Difference: ", colDiff
ciphertxt.insert(0, tmp[(colFor0 - colDiff ) % 5][rowFor0])
#print "Inserted: ",tmp[(colFor0 - colDiff ) % 5][rowFor0]
ciphertxt.insert(0, tmp[(colFor1 + colDiff) % 5][rowFor1])
#print "Inserted: ",tmp[(colFor1 + colDiff) % 5][rowFor1]
#print ' '
elif colFor0 < colFor1:
# read in order, row/col index 0 goes first
colDiff = abs(colFor0 - colFor1)
#print "Difference: ", colDiff
ciphertxt.insert(0, tmp[(colFor0 + colDiff) % 5][rowFor0])
#print "Inserted: ",tmp[(colFor0 + colDiff) % 5][rowFor0]
ciphertxt.insert(0, tmp[(colFor1 - colDiff) % 5][rowFor1])
#print "Inserted: ",tmp[(colFor1 - colDiff) % 5][rowFor1]
#print ' '
ciphertxt.reverse()
return ciphertxt
def playfair_decryption(encryptedList, key, junkChar):
'''
Playfair changes the order of letters according to rules and sometimes add junk to your secret string. But here we reverse the order.
:param encryptedList: list with chars
:param key: word based on the english letter system
:junkChar: fill out secret in order to create bigrams
:return: clear text as list used with print
'''
crypto = encryptedList
keyWord = key
# create 2D list
col1 = [None] * 5
col2 = [None] * 5
col3 = [None] * 5
col4 = [None] * 5
col5 = [None] * 5
tmp = [col1, col2, col3, col4, col5] # currently good enough without list copies in main list.
row = 0
col = 0
for read in keyWord:
if tmp[0].count(read) + tmp[1].count(read) + tmp[2].count(read) + tmp[3].count(read) + tmp[4].count(read) == 0:
tmp[col][row] = read
col = (col + 1) % 5
if col == 0:
row = (row + 1) % 5
# append the rest of the letters in chronologically order
english = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'z', 'y']
for read in english:
if tmp[0].count(read) + tmp[1].count(read) + tmp[2].count(read) + tmp[3].count(read) + tmp[4].count(read) == 0:
tmp[col][row] = read
col = (col + 1) % 5
if col == 0:
row = (row + 1) % 5
# stuff above works ------------------------------------------------------------------------------------------------
# read bigrams and apply reverse order
secret = []
listlength = len(crypto)
A = 0;
rowFor0 = 0;
colFor0 = 0;
rowFor1 = 0;
colFor1 = 0
temp = ['.', '.']
while A < listlength:
temp[0] = crypto[A]
A += 1
if A < listlength:
temp[1] = crypto[A]
A += 1
for row in range(5):
for col in range(5):
if tmp[col][row] == temp[0]:
rowFor0 = row
colFor0 = col
elif tmp[col][row] == temp[1]:
rowFor1 = row
colFor1 = col
if rowFor0 == rowFor1:
# read in order, row/col index 0 goeas first
secret.insert(0, tmp[(colFor0 - 1) % 5][rowFor0])
secret.insert(0, tmp[(colFor1 - 1) % 5][rowFor1])
elif colFor1 == colFor0:
# read in order, row/col index 0 goeas first
secret.insert(0, tmp[colFor0][(rowFor0 - 1) % 5])
secret.insert(0, tmp[colFor1][(rowFor1 - 1) % 5])
else:
if colFor0 > colFor1:
#read in order, row/col index 0 goeas first
colDiff = abs(colFor0 - colFor1)
secret.insert(0, tmp[(colFor0 - colDiff) % 5][rowFor0])
secret.insert(0, tmp[(colFor1 + colDiff) % 5][rowFor1])
elif colFor0 < colFor1:
# read in order, row/col index 0 goes first
colDiff = abs(colFor0 - colFor1)
secret.insert(0, tmp[(colFor0 + colDiff) % 5][rowFor0])
secret.insert(0, tmp[(colFor1 - colDiff) % 5][rowFor1])
secret.reverse()
for junk in range(secret.count(junkChar)):
secret.remove(junkChar)
return secret
|
087e1a8d7ff4eb6c3b626089053ce6c53b6e3965 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/word-count/8ab446165df2444eb0982eedf5eddad9.py | 166 | 3.765625 | 4 | import re
def word_count(input):
words = re.split(r"\s+", input)
distinct_words = set(words)
return {word: words.count(word) for word in distinct_words}
|
95a8e1125977a42a52a86becdc1d37687c2e28df | Illugi317/forritun | /aefingarprof/student.py | 1,060 | 4.125 | 4 | from collections import defaultdict
NUMBER_OF_PEOPLE = 4
NUMBER_OF_GRADES = 3
MAX_DECIMALS = 2
def get_names_and_values(name_dict):
counter = 0
while counter != NUMBER_OF_PEOPLE:
name = input("Student name: ")
for x in range(0,NUMBER_OF_GRADES):
grade = input(f"Input grade number {x+1}: ")
name_dict[name].append(float(grade))
counter += 1
def show_student_list(name_dict):
for key,value in name_dict.items():
print(f"{key}: {value}")
def get_highest_student(name_dict):
print("Student with highest average grade:")
highest_student = ""
current_avg = 0
for key,value in name_dict.items():
avg = sum(value)/len(value)
if current_avg < avg:
current_avg = avg
highest_student = key
print(f"{highest_student} has an average grade of {round(current_avg,MAX_DECIMALS)}")
def main():
name_dict = defaultdict(list)
get_names_and_values(name_dict)
show_student_list(name_dict)
get_highest_student(name_dict)
main() |
ae8f0acc4a2a41d0f57285042ca789c393abf409 | lyk4411/untitled | /pythonWebCrawler/student.py | 1,958 | 3.890625 | 4 | class Student():
def __init__(self, name):
print("Student init")
super(Student, self).__init__()
if __name__ == "__main__":
s1 = Student("XIAOMIN")
s1.english =90
class Person(object):
__slots__ = ('_name', '_age', '_sex') ##限制基类变量只能有这三个属性,实例对象无法增加新的属性,这就防止了用户误输入
def __init__(self, name):
self._name = name
print("Person init")
class Student(Person):
__slots__ = ('_grade', '_english', '_chinese') ##限制基类变量只能有这三个属性,实例对象无法增加新的属性,这就防止了用户误输入
def __init__(self, name):
print("Student init")
# Person.__init__(self, name)
super(Student, self).__init__(name)
@property ##property 方法访问变量
def english(self):
return self._english
@english.setter ##property 方法设置变量,这里面对参数进行了校验
def english(self, value):
if not isinstance(value, int):
raise ValueError('分数必须是整数才行呐')
if value < 0 or value > 100:
raise ValueError('分数必须0-100之间')
self._english = value
if __name__ == "__main__":
s1 = Student("XIAOMIN")
p1 = Person("lll")
# p1.aaa = 1
class anmon(object):
'''
this is doc.
'''
def __init__(self, name):
self._name = name
print("anmon init")
def anon_a(self):
self.anon_a = 'aaaa'
if __name__ == "__main__":
print(anmon.__dict__)
a2 = anmon('xiaoli')
print(a2.__dict__)
a2.anon_a()
print(a2.__dict__)
class anmon(object):
'''
this is doc.
'''
def __init__(self, name):
self._name = name
print("anmon init")
def anon_a(self):
self.anon_a = 'aaaa'
if __name__ == "__main__":
a2 = anmon('xiaoli')
print(dir(anmon))
print(dir(a2))
|
722467ce4d1de29c49aae9180694de36832e763f | riteshbisht/dsprograms | /arrays/searching/problem1.py | 572 | 3.765625 | 4 | """
Given an array A[] and a number x, check for pair in A[] with sum as x
Write a program that, given an array A[] of n numbers and another number x,
determines whether or not there exist two elements in S whose sum is exactly x.
"""
arr = [1, 2, 3, 4, 5, 6, 7, 8]
if __name__ == '__main__':
k = 7
myset = set()
for i in arr:
if k-i not in myset:
myset.add(i)
else:
print((i, (k-i)))
# k = {}
# sum1 = 7
# for i in arr:
# if (sum1-i) in k:
# print(sum1-i, i)
# break
# else:
# k[i] = 1
|
940877bf3e62ccc8ab6fadc39d04ab950a6a7b63 | Keshpatel/Python-Basics | /OOP Python/Classes and Instance.py | 630 | 4 | 4 | # Python Object-Oriented Programming
class Employee:
def __init__(self, first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + "." + last + '@company.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('Keshini', 'Patel', 70000)
emp_2 = Employee('Tom','Corey',60000)
print(emp_1.email)
print(emp_2.email)
# using class name and passing Instance of the class
print(Employee.fullname(emp_1))
print(Employee.fullname(emp_2))
# Using instance and no need to pass anything
emp_1.fullname()
emp_2.fullname()
|
780b3b7b03917782f8392c5caf6ba9059048b9d4 | sameerktiwari/PythonTraining | /Basics/Addition.py | 115 | 3.921875 | 4 | num1=input("Enter first number")
num2=input("Enter second number")
print "Addition of two numbers is ",num1+num2
|
17c7731acd7af27d3604acaa9ef49729e8630830 | jixinfeng/leetcode-soln | /python/405_conver_a_number_to_hexadecimal.py | 1,360 | 4.40625 | 4 | """
Given an integer, write an algorithm to convert it to hexadecimal. For negative
integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra leading 0s. If the number is
zero, it is represented by a single zero character '0'; otherwise, the first
character in the hexadecimal string will not be the zero character.
The given number is guaranteed to fit within the range of a 32-bit signed
integer.
You must not use any method provided by the library which converts/formats
the number to hex directly.
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff"
"""
class Solution(object):
hexChar = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f']
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return '0'
while num < 0:
num += 2 ** 32
if num > 2 ** 32 - 1:
num = 2 ** 32 - 1
soln = ''
while num > 0:
soln += self.hexChar[num % 16]
num //= 16
return soln[::-1]
a = Solution()
print(a.toHex(26) == "1a")
print(a.toHex(-1) == "ffffffff")
|
e54ae04f65762d6827ac9e7ab9d9d6c15ae4317a | Rahonam/algorithm-syllabus | /array/contains_range.py | 708 | 3.890625 | 4 |
def contains_range(arr:list, start:int, end:int):
"""
Check if given array contains all elements of some given range
using: iteration, time O(n) space O(1)
Args:
arr: array of integers
start: first element of range
end: last element of range
Returns:
boolean: True, if array contains all elements of the range
boolean: False, otherwise
"""
for i in range(0, len(arr)):
if start <= arr[i] and arr[i] <= end:
arr[arr[i] - start] *= -1
for i in range(0, end - start + 1):
if arr[i] > 0:
return False
return True
print(contains_range([11, 17, 13, 19, 15, 16, 12, 14], 12, 15)) |
f50dbbea23a9a84011a3bd85b7e587861ee2207a | mariusv/robofinder | /v2.0/search.py | 20,294 | 3.703125 | 4 | #!/usr/bin/python
from numpy import *
#################################### SEARCH ###################################
class Search:
"""A superclass of search algorithms on grid.
"""
def __init__(self, search_grid):
self.search_grid = search_grid # 2-dimensional search grid
self.node_parent_list = [] # list of (node, parent) tuples
self.fringe = [] # list of nodes to expand
self.visited = [] # list of visited nodes (visited
# nodes are not expanded)
self.expanded = [] # list of nodes already expanded
self.path = [] # path from start to goal
def set_path(self, goal):
"""Find path travelled by backtracking from goal
Each node's parent is looked up in node_parent_list.
Parameter: goal - the goal node
"""
current = goal;
self.path.insert(0, current); # start from goal node
for tup in reversed(self.node_parent_list):
if tup[0] == current:
current = tup[1] # push parent to path
self.path.insert(0, current)
############################# BREADTH-FIRST SEARCH ############################
class BreadthFirstSearch(Search):
"""An implementation of breadth-first search on grid.
"""
def search(self):
"""Initiate breadth-first search from start to goal.
Returns: True if path is found, False otherwise
"""
"initialise start and goal nodes"
start = self.search_grid.grid[self.search_grid.start_pos[0], \
self.search_grid.start_pos[1]]
goal = self.search_grid.grid[self.search_grid.goal_pos[0], \
self.search_grid.goal_pos[1]]
self.fringe.append(start) # append start node to fringe
while True:
"if fringe is empty, no solution is found"
if len(self.fringe) == 0:
return False
"expand the first node in fringe"
current = self.fringe.pop(0)
"cycle check if fringe is already expanded"
if self.visited.count(current) == 0:
self.expanded.append(current) # expand node
self.visited.append(current) # mark node as visited
else:
continue # continue loop if cycle is detected
"once goal is reached, find path and stop search"
if current == goal:
self.set_path(goal)
return True
self.__expand(current) # expand current node
def __expand(self, current):
"""Find children of current node in the order: up, left, right, down.
All children nodes are appended to the end of the fringe.
Parameter: current - value of current node
"""
pos = self.search_grid.position(current) # get coordinates (row,col) of node
current_fringe = []
"do not go up if already at top of grid"
if pos[0] > 0:
current_fringe.append(self.search_grid.grid[pos[0] - 1, pos[1]])
"do not go left if already at leftmost of grid"
if pos[1] > 0:
current_fringe.append(self.search_grid.grid[pos[0], pos[1] - 1])
"do not go right if already at rightmost of grid"
if pos[1] < (self.search_grid.grid.shape[1] - 1):
current_fringe.append(self.search_grid.grid[pos[0], pos[1] + 1])
"do not go down if already at bottom of grid"
if pos[0] < (self.search_grid.grid.shape[0] - 1):
current_fringe.append(self.search_grid.grid[pos[0] + 1, pos[1]])
for value in current_fringe:
"only add nodes if not forbidden"
if value != -1:
self.fringe.append(value)
self.node_parent_list.append((value, current)) # add current as parent
############################# DEPTH-FIRST SEARCH #############################
class DepthFirstSearch(Search):
"""An implementation of depth-first search on grid.
"""
def search(self):
"""Initiate depth-first search from start to goal.
Returns: True if path is found, False otherwise
"""
"initialize start and goal nodes"
start = self.search_grid.grid[self.search_grid.start_pos[0], \
self.search_grid.start_pos[1]]
goal = self.search_grid.grid[self.search_grid.goal_pos[0], \
self.search_grid.goal_pos[1]]
self.fringe.append(start) # append start node to fringe
while True:
"if fringe is empty, no solution is found"
if len(self.fringe) == 0:
return False
"expand the first node in fringe"
current = self.fringe.pop(0)
"cycle check if fringe was already expanded"
if self.visited.count(current) == 0:
self.expanded.append(current) # expand node
self.visited.append(current) # mark node as visited
else:
continue # continue loop if cycle is detected
"once goal is reached, find path and stop search"
if current == goal:
self.set_path(goal)
return True
self.__expand(current) # expand current node
def __expand(self, current):
"""Find children of current node in the order: up, left, right, down.
All children nodes are pushed into the start of the fringe.
Parameter: current - value of current node
"""
pos = self.search_grid.position(current) # get coordinates (row,col) of node
current_fringe = []
"do not go up if already at top of grid"
if pos[0] > 0:
current_fringe.insert(0, self.search_grid.grid[pos[0] - 1, pos[1]])
"do not go left if already at leftmost of grid"
if pos[1] > 0:
current_fringe.insert(0, self.search_grid.grid[pos[0], pos[1] - 1])
"do not go right if already at rightmost of grid"
if pos[1] < (self.search_grid.grid.shape[1] - 1):
current_fringe.insert(0, self.search_grid.grid[pos[0], pos[1] + 1])
"do not go down if already at bottom of grid"
if pos[0] < (self.search_grid.grid.shape[0] - 1):
current_fringe.insert(0, self.search_grid.grid[pos[0] + 1, pos[1]])
for value in current_fringe:
"only add nodes if not forbidden"
if value != -1:
self.fringe.insert(0, value)
self.node_parent_list.append((value, current)) # add current as parent
################################ GREEDY SEARCH ################################
class GreedySearch(Search):
"""An implementation of greedy search on grid.
"""
def search(self):
"""Initiate greedy best-first search from start to goal.
Greedy search expands the node which appears to be closest to goal.
The heuristic is the step cost as the sum of the differences
between the coordinates of the node and the goal.
For example, if node is located at (4,3) and goal is located at (7,4),
the heuristic will compute the step cost as (7 - 4) + (4 - 3) = 4.
The variables 'fringe' and 'expanded' in the superclass are used to
contain (node, cost) tuples.
"""
"initialise start and goal nodes"
start = self.search_grid.grid[self.search_grid.start_pos[0], \
self.search_grid.start_pos[1]]
goal = self.search_grid.grid[self.search_grid.goal_pos[0], \
self.search_grid.goal_pos[1]]
self.fringe.append((start, 0)) # append start node to fringe
while True:
"if fringe is empty, no solution is found"
if len(self.fringe) == 0:
return False
"expand the least cost to goal node in fringe"
lowest_index = self.__least_cost_node_index(self.fringe)
current = self.fringe.pop(lowest_index)
"cycle check if fringe is already expanded"
if self.visited.count(current[0]) == 0:
self.expanded.append(current) # expand node
self.visited.append(current[0]) # mark node as visited
else:
continue # continue loop if cycle is detected
"once goal is reached, find path and stop search"
if current[0] == goal:
self.set_path(goal)
return True
self.__expand(current[0]) # expand current node
def __least_cost_node_index(self, fringe):
"""Returns the index of the node with the least cost to goal in fringe.
If there are several least cost nodes in the fringe, the last added is returned.
Parameter: fringe - the list of available fringe nodes
Returns: the index of the node with the least cost
"""
lowest_value = float("inf")
lowest_index = 0
current_position = 0
for node in fringe:
if node[1] <= lowest_value:
lowest_value = node[1]
lowest_index = current_position
current_position += 1
return lowest_index
def __expand(self, current):
"""Find children of current node in the order: up, left, right, down.
All children nodes are appended to the end of the fringe.
Parameter: current - value of current node
"""
pos = self.search_grid.position(current) # get coordinates (row,col) of node
current_fringe = []
"do not go up if already at top of grid"
if pos[0] > 0:
current_fringe.append(self.search_grid.grid[pos[0] - 1, pos[1]])
"do not go left if already at leftmost of grid"
if pos[1] > 0:
current_fringe.append(self.search_grid.grid[pos[0], pos[1] - 1])
"do not go right if already at rightmost of grid"
if pos[1] < (self.search_grid.grid.shape[1] - 1):
current_fringe.append(self.search_grid.grid[pos[0], pos[1] + 1])
"do not go down if already at bottom of grid"
if pos[0] < (self.search_grid.grid.shape[0] - 1):
current_fringe.append(self.search_grid.grid[pos[0] + 1, pos[1]])
for value in current_fringe:
"only add nodes if not forbidden"
if value != -1:
self.fringe.append((value, self.search_grid.heuristic(value)))
self.node_parent_list.append((value, current)) # add current as parent
################################## A* SEARCH ##################################
class AStarSearch(Search):
"""An implementation of A* search on grid.
"""
def search(self):
"""Initiate A* search from start to goal.
A* search improves on greedy. Instead of just considering the heuristic,
it takes the path cost and cost-so-far into account.
In A*, the cost will be heuristic + cost from start to node.
As in greedy search, the variables 'fringe' and 'expanded' will be used
to contain (node, cost) tuples.
"""
"initialise start and goal nodes"
start = self.search_grid.grid[self.search_grid.start_pos[0], \
self.search_grid.start_pos[1]]
goal = self.search_grid.grid[self.search_grid.goal_pos[0], \
self.search_grid.goal_pos[1]]
self.fringe.append((start, self.search_grid.heuristic(start)))
while True:
"if fringe is empty, no solution is found"
if len(self.fringe) == 0:
return False
"expand the least cost to goal node in fringe"
lowest_index = self.__least_cost_node_index(self.fringe)
current = self.fringe.pop(lowest_index)
"cycle check if fringe is already expanded"
if self.visited.count(current[0]) == 0:
self.expanded.append(current) # expand node
self.visited.append(current[0]) # mark node as visited
else:
continue # continue loop if cycle is detected
"once goal is reached, find path and stop search"
if current[0] == goal:
self.set_path(goal)
return True
self.__expand(current[0]) # expand current node
def __least_cost_node_index(self, fringe):
"""Returns the index of the node with the least cost to goal in fringe.
If there are several least cost nodes in the fringe, the last added is
returned.
Parameter: fringe - the list of available fringe nodes
Returns: the index of the node with the least cost
"""
lowest_value = float("inf")
lowest_index = 0
current_position = 0
for node in fringe:
if node[1] <= lowest_value:
lowest_value = node[1]
lowest_index = current_position
current_position += 1
return lowest_index
def __expand(self, current):
"""Find children of current node in the order: up, left, right, down.
All children nodes are appended to the end of the fringe.
Parameter: current - value of current node
"""
pos = self.search_grid.position(current) # get coordinates (row,col) of node
current_fringe = []
path_cost = 1
"calculate the cost so far"
if len(self.node_parent_list) != 0:
path_cost = self.__path_cost(current)
"do not go up if already at top of grid"
if pos[0] > 0:
current_fringe.append(self.search_grid.grid[pos[0] - 1, pos[1]])
"do not go left if already at leftmost of grid"
if pos[1] > 0:
current_fringe.append(self.search_grid.grid[pos[0], pos[1] - 1])
"do not go right if already at rightmost of grid"
if pos[1] < (self.search_grid.grid.shape[1] - 1):
current_fringe.append(self.search_grid.grid[pos[0], pos[1] + 1])
"do not go down if already at bottom of grid"
if pos[0] < (self.search_grid.grid.shape[0] - 1):
current_fringe.append(self.search_grid.grid[pos[0] + 1, pos[1]])
for value in current_fringe:
"only add nodes if not forbidden"
if value != -1:
total_cost = path_cost + self.search_grid.heuristic(value)
self.fringe.append((value, total_cost))
self.node_parent_list.append((value, current, path_cost)) # add current as parent
def __path_cost(self, value):
"""Find the path cost from start node to current node.
Parameter: value - value of current node
Returns: the path cost from start node to current node
"""
for node in self.node_parent_list:
if node[0] == value:
return node[2] + 1
############################# HILL-CLIMBING SEARCH ############################
class HillClimbingSearch(Search):
"""An implementation of hill-climbing search on grid.
"""
def search(self):
"""Initiate hill-climbing search from start to goal.
Hill-Climbing Search is a search algorithm that only takes into account
the neighbouring nodes. It traverses by simply moving into the node
with the least v-value, assuming its v-value is lower than the current
v-value of the node. The v-value can be determined from a heuristic
evaluation function.
"""
"initialise start and goal nodes"
start = self.search_grid.grid[self.search_grid.start_pos[0], \
self.search_grid.start_pos[1]]
goal = self.search_grid.grid[self.search_grid.goal_pos[0], \
self.search_grid.goal_pos[1]]
previous = (0, 0)
current = (start, self.__evaluate(start))
while True:
if current[0] == goal:
self.expanded.append(current)
self.set_path(goal)
return True
self.expanded.append(current)
self.__expand(current[0], previous[0])
next = (0, float("inf"))
"find the neighbour with lowest v-value"
for node in self.fringe:
if node[1] <= next[1]:
next = node
"if no better neighbours exist, end search"
if next[1] >= current[1]:
return False
previous = current
current = next
def __evaluate(self, node):
"""Heuristic evaluation function.
The v-value is simply the heuristic value of the node. However, if
the node is on special rows/columns in the grid, special modifier values
will be added. This is done to ensure the hill-climbing algorithm
to find the goal node.
Parameter: value - value of current node
Returns: the v-value for the given node
"""
modifier = 0
node_position = self.search_grid.position(node)
"find the rows and columns of forbidden nodes"
grid_width = len(self.search_grid.grid)
blocked_row = grid_width / 2
"the formula for finding blocked_column is based on linear\
observation of forbidden nodes of grid size 8 and 16"
blocked_column = (grid_width - 8) / 2 + 1
"higher modifier if node is surrounded by forbidden nodes"
if node_position[1] > blocked_column:
if node_position[0] == blocked_row:
modifier += 4
elif node_position[0] == blocked_row + 1:
modifier += 2
"higher modifier to nodes that stray farther from goal"
if node_position[0] >= blocked_row:
if node_position[1] == blocked_column:
modifier += 2
elif node_position[1] == (blocked_column + 1):
modifier += 4
elif node_position[1] > (blocked_column + 1):
modifier += 6
return self.search_grid.heuristic(node) + modifier
def __expand(self, current, previous):
"""Find children of current node in the order: up, left, right, down.
All children nodes are appended to the end of the fringe.
Parent node is not added to prevent backtracking.
Parameters:
- current: value of current node
- previous: previous node, to prevent backtracking
"""
self.fringe = [] # clears current fringe
pos = self.search_grid.position(current) # get coordinates (row,col) of node
current_fringe = []
"do not go up if already at top of grid"
if pos[0] > 0:
current_fringe.append(self.search_grid.grid[pos[0] - 1, pos[1]])
"do not go left if already at leftmost of grid"
if pos[1] > 0:
current_fringe.append(self.search_grid.grid[pos[0], pos[1] - 1])
"do not go right if already at rightmost of grid"
if pos[1] < (self.search_grid.grid.shape[1] - 1):
current_fringe.append(self.search_grid.grid[pos[0], pos[1] + 1])
"do not go down if already at bottom of grid"
if pos[0] < (self.search_grid.grid.shape[0] - 1):
current_fringe.append(self.search_grid.grid[pos[0] + 1, pos[1]])
for value in current_fringe:
"only add nodes if not forbidden"
if value != -1 and value != previous:
self.fringe.append((value, self.__evaluate(value)))
self.node_parent_list.append((value, current)) # add current as parent
|
5d8694886e104882e15b28cc89e9876295d50349 | ro-mak/PythonAlgs | /lesson8/task1.py | 873 | 3.671875 | 4 | from collections import deque
# 1. На улице встретились N друзей. Каждый пожал руку всем остальным друзьям (по одному разу).
# Сколько рукопожатий было?
# Примечание. Решите задачу при помощи построения графа.
n = int(input("Number of friends: "))
graph = []
for i in range(0, n):
graph.append([1 if j != i else 0 for j in range(0, n)])
for i in graph:
print(i)
handshakes = 0
iter = 0
for i in range(len(graph)):
for j in range(i + 1, len(graph[i])):
item1 = graph[i][j]
item2 = graph[j][i]
print(f"Checking item1[{i},{j}] and item2[{j},{i}]")
iter += 1
if item1 == item2 and item1 == 1:
handshakes += 1
print(f"Handshakes = {handshakes}")
print(f"Iter = {iter}")
|
e156cf688a2b96cda8f6b18c1146592d7269aac7 | Jason30102212/python_basics_refresher | /10.ListFunctions.py | 964 | 4.1875 | 4 | # 10.ListFunctions
numbers = [4, 8, 15, 16, 23, 42]
strings = ["One", "Two", "Three", "Four", ]
#strings.extend(numbers) # Append to end of list
strings.extend("Five") # Append each character as a value to list
strings.append("Five") # Append as string to list
strings.insert(2, "Two and a half") # First arg is indedx of list, second is value
strings.remove("Three") # Remove a specific string
print(strings)
strings.clear() # Clears a list
print(strings)
strings = ["One", "Two", "Three", "Four", ]
strings.index("Three") # Index of specified value
# strings.index("QQQ") # ERROR
strings = ["One", "Two", "Three", "Four", "Four", "Four" ]
print(strings.count("Four")) # Counts number of appearances
print(strings.sort()) # Sort in desending order
print(strings.reverse())
#stringsTwo = strings #This sets a reference to strings and
#print(strings)
#stringsTwo.clear()
#print(strings)
stringsTwo = strings.copy() # Creats a new list, not a reference
|
f70de42a669e899fcb229d87f22c09bdc0dd734d | Edyta68/Akademia-programowania | /test2.py | 1,604 | 3.703125 | 4 | def dic():
thisdict = ({
"apple": 1,
"banana": 2,
"cherry": 3
})
thisdict["orange"] = 4
thisdict.pop("apple", None)
print(thisdict)
dic()
def word_counter(sentence):
from collections import Counter
list1 = sentence.split(" ")
counts = Counter(list1)
return counts
def word_counter2(sentence):
from collections import Counter
list1 = sentence.split(" ")
for ind, word in enumerate(list1):
if len(word) == 1:
continue
if not word[-1].isalnum():
list1.append(word[-1])
list1[ind] = word[:-1]
counts = Counter(list1)
return counts
answer = {"Ala": 2, "ma": 2, "kota.": 1, "psa.": 1}
assert word_counter("Ala ma kota. Ala ma psa.") == answer
answer = {"Ala": 2, "ma": 2, "kota": 1, "psa": 1, ".": 2}
assert word_counter2("Ala ma kota. Ala ma psa.") == answer
import re
def validatePIN(PIN):
return bool(re.fullmatch("\d{4}", PIN))
assert validatePIN("1234") == True, "Wrong validation!"
assert validatePIN("12345") == False, "Wrong validation!"
assert validatePIN("a234") == False, "Wrong validation!"
def validate_input(word):
return bool(re.fullmatch ("[a-z 0-9_]{5,20}", word))
assert validate_input("Summer Academmy") == False, "Bad validation!"
assert validate_input("Summer_Academmy") == False, "Bad validation!"
assert validate_input("summer_academmy") == True, "Bad validation!"
import omdb
client = omdb.OMDBClient(apikey="1ecdeb9a")
res = client.request(t='Grease', y='1978')
xml_content = res.content
print(xml_content)
|
a824ea3d688d429867b446e7f6d1e5c50575d624 | Junaid388/Advanced-Python | /Object Internals and Custom Attributes/ex_attrstorage.py | 704 | 3.78125 | 4 | from vector import *
cv = ColoredVector(red = 23, green = 44, blue = 238, p= 9, q= 14)
cv.red # stored in a list at __dict__['color']
#cv.p # stored directly in __dict__
print(dir(cv))
print(cv) # look for color variable
# Method storage
v = Vector(x= 3, y=7)
print(v.__class__)
print(v.__class__.__dict__)
print(v.__class__.__dict__['__repr__'](v))
#The __class__.__dict__ doesn't support item assignment as normal __dict__ so here how to assign a attribute
# Its like adding the attribute to class dictionary
setattr(v.__class__, 'a_vector_class_attribute', 5)
print(v.a_vector_class_attribute)
print(v.__class__.__dict__['__repr__'](v))
print(Vector.a_vector_class_attribute)
print(v)
|
be164b11af232139ab8bdef69c5c86e5ca148752 | Zazzerpoof/DONOTUSE-Code | /Junk/Yeet.py | 1,157 | 3.84375 | 4 | class person:
def __init__(self,first_name,last_name,middle_name,favorite_color,fart,eyes,hair,height,weight,age):
self.first_name = first_name
self.last_name = last_name
self.middle_name = middle_name
self.favorite_color = favorite_color
self.fart = fart
self.eyes = eyes
self.hair = hair
self.height = height
self.weight = weight
self.age = age
def list(self):
return "First Name: {}\nMiddle Name: {}\nLast Name: {}\nAge: {}\nEye Color: {}\nHair Color: {}\nHeight: {}\nWeight: {}\nFavorite Color: {}\nFart Smell: {}".format(self.first_name,self.middle_name,self.last_name,self.age,self.eyes,self.hair,self.height,self.weight,self.favorite_color,self.fart)
p1 = person("Geoff","Stevenson","Cliff","Blue","Yeet","Blue","Brown","5' 11","179 lbs", "23")
p2 = person("Steve","Robertson","Cliff","Green","Really Awful","Purple","Grey","1' 11","307 lbs","26")
x = p1.list()
y = p2.list()
t = input("Who do you want to check?\n")
while t != "p1" and t != "p2":
t = input("Invalid Dood triy ugen\n")
if t == "p1":
print(x)
else:
print(y)
|
df4c79769257929216023a0cc55ecbfa4ede83d0 | iliachigogidze/Python | /Cormen/Chapter2/day5/take2/recursion_insertion_sort.py | 487 | 4.09375 | 4 | def main(numbers:list) -> list:
print(f'Sort numbers {numbers}')
return insertion(numbers)
def insertion(numbers):
if len(numbers) == 1:
return numbers[0]
def insertion_sort(numbers):
for i in range(len(numbers)-1):
key = numbers[i]
j = i - 1
while key < numbers[j] and j >= 0:
numbers[j+1] = numbers[j]
j -= 1
numbers[j+1] = key
return numbers
print('Answer is: ', main([5,12,-4,-4,23,-5,1,2,2])) |
7553b5ecc6cf1b2061d1da56c1e8cd2037f4b09f | AleksandrVladimirovichNaumov/Python | /Lesson9/Naumov_alexander_dz_lesson9_task2.py | 1,228 | 3.9375 | 4 | # Реализовать класс Road (дорога).
# определить атрибуты: length (длина), width (ширина);
# значения атрибутов должны передаваться при создании экземпляра класса;
# атрибуты сделать защищёнными;
# определить метод расчёта массы асфальта, необходимого для покрытия всей дороги;
# использовать формулу: длина*ширина*масса асфальта для покрытия одного кв. метра дороги асфальтом,
# толщиной в 1 см*число см толщины полотна;
# проверить работу метода.
#
# Например: 20 м*5000 м*25 кг*5 см = 12500 т.
class Road:
# attributes:
def __init__(self, l, w):
self._length = l
self._width = w
# methods
def mass(self, thickness, density):
try:
mass = self._width * self._length * thickness * density
return mass
except Exception as e:
print(e)
road_1 = Road(10000, 10)
print(road_1.mass(0.1, 25)) |
8130f96043cc320e7d5c122a813c146f3cf121be | JEBatta/agent_with_habits | /test1-streamplot.py | 1,108 | 3.84375 | 4 | """
==========
Streamplot
==========
A stream plot, or streamline plot, is used to display 2D vector fields. This
example shows a few features of the :meth:`~.axes.Axes.streamplot` function:
* Varying the line width along a streamline.
This code is a modification from:
https://matplotlib.org/gallery/images_contours_and_fields/plot_streamplot.html
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import csv
Y, X = np.mgrid[0.35:0.65:31j, 0.35:0.65:31j]
U, V = np.mgrid[0.0:0.0:31j, 0.0:0.0:31j]
with open('influence_single_node.csv','rb') as f:
reader = csv.reader(f)
next(reader)
i = 0
for row in reader:
U[i/31][i%31],V[i/31][i%31] = float(row[2]),float(row[3])
i += 1
speed = np.sqrt(U*U + V*V)
fig = plt.figure(figsize=(5, 5))
gs = gridspec.GridSpec(nrows=1, ncols=1, height_ratios=[1])
# Varying line width along a streamline
ax2 = fig.add_subplot(gs[0, 0])
lw = speed / speed.max()
ax2.streamplot(X, Y, U, V, density=0.7, color='k', linewidth=lw)
ax2.set_title('Influence of medium with a single node')
plt.tight_layout()
plt.show()
|
36caaf6d42d93e1d25139c88d2df5edef5e91a41 | aritro999/apy | /10_pallindrome.py | 345 | 4.09375 | 4 | def f1(num):
temp = num
reverse = 0
while num > 0:
last_dig = num % 10
reverse = reverse * 10 + last_dig
num = num // 10
if temp == reverse:
print("The number is palindrome!")
else:
print("The number is not a palindrome!")
num = int(input("Enter a number: "))
f1(num) |
8a1cebee66d077306785c071223a3ab73701f1a1 | jake3991/Stanford_algo | /count_inversions.py | 1,412 | 4.09375 | 4 | def count_inversions(input):
#define a single element list to keep track of inversions
count=[0]
def merge(left,right):
#init some varibles
output=[]
i,j=0,0
#loop while the indexes i and j are less than the length of left and right
while i < len(left) and j < len(right):
#if the left is bigger than the right append the left an increase the step i by 1
if left[i] <= right[j]:
output.append(left[i])
i+=1
#else the right must be smaller, append the right and increase the step j by 1
else:
output.append(right[j])
j+=1
count[0]+=(len(left)-i)
#lists are exausted so add the rest to the ouput
output += left[i:]
output += right[j:]
#return the output
return output
def merge_sort(input):
#if the len of the input is less than 2 just return the input
if len(input) < 2:
return input
#find the middle of the input
middle = int(len(input) / 2)
#make recursive calls
left = merge_sort(input[:middle])
right = merge_sort(input[middle:])
#merge
D=merge(left, right)
return D
#call the merge_sort on the input
merge_sort(input)
#return the count
return count[0] |
9338572155a771a07431ad67d9b4baabe62007eb | ThompsonBethany01/Python_Practice_Problems | /HackerRank/Introduction.py | 2,340 | 4.21875 | 4 | # Python If-Else
'''
Task
Given an integer, n, perform the following conditional actions:
If is odd, print Weird
If is even and in the inclusive range of to , print Not Weird
If is even and in the inclusive range of to , print Weird
If is even and greater than , print Not Weird
'''
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if n % 2 != 0:
print('Weird')
elif n % 2 == 0:
if n > 1 and n < 6:
print('Not Weird')
elif n > 5 and n < 21:
print('Weird')
elif n > 20:
print('Not Weird')
# Arithmetic Operators
'''
Task
The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where:
The first line contains the sum of the two numbers.
The second line contains the difference of the two numbers (first - second).
The third line contains the product of the two numbers.
'''
if __name__ == '__main__':
a = int(input())
b = int(input())
print(a+b)
print(a-b)
print(a*b)
# Python Division
'''
The provided code stub reads two integers, a and b, from STDIN.
Add logic to print two lines. The first line should contain the result of integer division, a // b. The second line should contain the result of float division, a / b.
No rounding or formatting is necessary.
'''
if __name__ == '__main__':
a = int(input())
b = int(input())
print(a//b)
print(a/b)
# Loops
'''
Print the square of each number on a separate line.
'''
if __name__ == '__main__':
n = int(input())
for x in range(0, n):
print(x**2)
# Write a function
'''
Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False.
'''
def is_leap(year):
leap = False
if (year % 4 == 0) and (year % 100 == 0) and (year % 400 == 0):
leap = True
elif (year % 4 == 0) and (year % 100 != 0):
leap = True
return leap
year = int(input())
# Print Function
'''
Print the list of integers from 1 through n as a string, without spaces.
'''
if __name__ == '__main__':
n = int(input())
number = ''
for i in range(1, n+1):
number = number + str(i)
print(number) |
d55cfeb3b2a05c46053627797100d1d3450971ac | rnetuka/adventofcode2020 | /src/day11.py | 3,702 | 3.859375 | 4 | # --- Day 11: Seating System ---
from src.matrix import Matrix
import itertools
class Seats(Matrix):
def __init__(self, width, height):
super().__init__(width, height)
def adjacent_occupied_seats(self, row, col) -> int:
c = [coords for coords in itertools.product((-1, 0, 1), repeat=2)]
c.remove((0, 0))
result = 0
for i, j in c:
if 0 <= row + i < self.height and 0 <= col + j < self.width:
if self[row + i][col + j] == '#':
result += 1
return result
def visible_occupied_seats(self, row, col) -> int:
"Counts visible occupied seats from specified coordinates"
def occupied_seat_in_direction(row, col, di=0, dj=0) -> bool:
row += di
col += dj
while 0 <= row < self.height and 0 <= col < self.width:
if self[row][col] == 'L':
return False
if self[row][col] == '#':
return True
row += di
col += dj
return False
count = 0
count += occupied_seat_in_direction(row, col, di=-1)
count += occupied_seat_in_direction(row, col, di=1)
count += occupied_seat_in_direction(row, col, dj=-1)
count += occupied_seat_in_direction(row, col, dj=1)
count += occupied_seat_in_direction(row, col, di=-1, dj=-1)
count += occupied_seat_in_direction(row, col, di=-1, dj=1)
count += occupied_seat_in_direction(row, col, di=1, dj=-1)
count += occupied_seat_in_direction(row, col, di=1, dj=1)
return count
def __eq__(self, other):
return repr(self) == repr(other)
def occupied(self) -> int:
count = 0
for row in range(self.height):
for col in range(self.width):
if self[row][col] == '#':
count += 1
return count
class SeatingSystem:
def __init__(self, seats, strategy=Seats.adjacent_occupied_seats, treshold=4):
self.seats = seats
self.strategy = strategy
self.treshold = treshold
def __next__(self):
result = Seats(self.seats.width, self.seats.height)
for row in range(self.seats.height):
for col in range(self.seats.width):
seat = self.seats[row][col]
if seat == 'L':
if self.strategy(self.seats, row, col) == 0:
result[row][col] = '#'
else:
result[row][col] = 'L'
if seat == '#':
if self.strategy(self.seats, row, col) >= self.treshold:
result[row][col] = 'L'
else:
result[row][col] = '#'
if seat == '.':
result[row][col] = '.'
self.seats = result
return result
if __name__ == '__main__':
print('Day 11: Seating System')
print('----------------------')
with open('../res/day11.txt') as file:
seats = Seats.parse(file.read().splitlines())
system = SeatingSystem(seats)
previous_state = seats
while True:
next_state = next(system)
if next_state == previous_state:
break
else:
previous_state = next_state
print(system.seats.occupied())
system = SeatingSystem(seats, strategy=Seats.visible_occupied_seats, treshold=5)
previous_state = seats
while True:
next_state = next(system)
if next_state == previous_state:
break
else:
previous_state = next_state
print(system.seats.occupied())
|
665e177d6c8f5c41a0f45d180802f57133f1a1ed | vemanand/pythonprograms | /matplotexamples/twoplots.py | 290 | 3.796875 | 4 | import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,10,1)
y1 = 2*x+5
y2 = 3*x+7
#Use subplot to create two or more plots
plt.subplot(1,2,1) #rows,cols,position
plt.plot(x,y1)
plt.title("First graph")
plt.subplot(1,2,2)
plt.plot(x,y2)
plt.title("Second graph")
plt.show() |
e29fc7b7cb6f2bcc101e3b2367c4513bfedbbee4 | 16GordonA/Essay-Writer | /fileparse.py | 458 | 4.125 | 4 | '''
Reads through files and parses out paragraphs (denoted by newline characters)
'''
def parse():
f = open('input.txt', 'r')
text = []
line = f.readline()
while(line is not ""):
if line is not "\n":
text += [line[:len(line)-1]] #-2 is to remove \n from line end
line = f.readline()
while('' in text):
text.remove('')
print(text)
return text
|
227a0118d502be79d6de5c111e1718037a12b7cd | G00364756/Project_Euler | /euler7.py | 849 | 3.890625 | 4 | # Project Euler - Problem 7
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
import math
def Primenumbers(number):
"""This function returns the factors of any number"""
primes = []
factors = []
j = 1
while len(primes) < 10002:
for a in range(1,(int(math.sqrt(j))+1)):
if j % a == 0:
factors.append(a)
factors.append(j//a)
else:
continue
if len(factors) == 2:
primes.append(j)
factors = []
else:
factors = []
j = j + 1
i = primes[-1]
return(i)
ans = Primenumbers(1)
print(ans)
|
c6243b3b8c420a27e10ea6a0282b3ef1947999d6 | asdra1v/python_homework | /homework03/Exercise06.py | 1,245 | 4.15625 | 4 | """
6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
Каждое слово состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки, но каждое слово должно
начинаться с заглавной буквы. Необходимо использовать написанную ранее функцию int_func().
"""
def int_func(text):
my_list = []
for i in range(len(text)):
my_list.append(text[i][0:1].title() + text[i][1:])
return ' '.join(my_list)
def in_out():
print(int_func(input('Введите строку из слов, состоящих из букв '
'в нижнем регистре, разделенных пробелом: ').split()))
in_out()
|
a559d566ffc9e0d737b7272e79784fddef93df46 | Gscsd8527/python | /正则表达式/lx_2.py | 334 | 3.828125 | 4 | import re
mystr='tanzhenhuatan'
test=re.match('tan',mystr)
print(test.group())
# 返回匹配的所有字符串,并生成一个列表
print(re.findall('tan',mystr))
# 匹配末尾的字符串的下标
print(test.end())
# 匹配第一个字符串的下标
print(test.start())
# 定位匹配字符串的第一个位置
print(test.pos) |
9c008adcb53f5bf97b7bdb08f404f86de41077f8 | msano20/Sequence-analysis | /gccontent.py | 1,647 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 2 13:35:20 2021
Essentially this script reads and parses multiple fasta files
before calculating GC percentage and assigning those values and
associated fasta IDs into a new dictionary. It will return the
ID with the highest GC content.
"""
file = "string.fasta"
def GCcount():
#parsing the fasta
with open(file,'r') as string:
headers = {} #header & sequence inserted into dict
key = ''
line_seq = ''
#this line-by-line loop sets the header name as the key
#sequences are then appended to a list before added as a dict value
for line in string.readlines():
if line.startswith('>'):
key = line.strip('>\n')
line_seq = ''
elif line == '\n':
pass
else:
line_seq+=str(line.strip())
headers[key] = line_seq
gc_list= {}
for item, value in headers.items():
gc_dict = {} #overwritten with every loop
total = len(value)
gc_count = ((value.count("G")) + value.count("C")) / float(total)
gc_percent = float(gc_count * 100)
rounded = (round(gc_percent, 6))
gc_dict[item] = rounded
gc_list.update(gc_dict)
desc_list = (dict(sorted(gc_list.items(), key = lambda item: item[1], reverse = True)))
return desc_list
#print(max(gc_list, key = gc_list.get)) #if you want the highest gc% only
headers.clear()
gc_list.clear()
def main():
desc_list = GCcount()
print(desc_list)
if __name__ == "__main__":
main()
|
66c9daed3d05553a55e95224cd6cc94a33418bb0 | jwyx3/practices | /leetcode/binary-search-tree/construct-binary-search-tree-from-preorder-traversal.py | 1,802 | 3.875 | 4 | # https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/
# Time: O(NlogN)
# Space: O(1)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def bstFromPreorder(self, preorder):
"""
:type preorder: List[int]
:rtype: TreeNode
"""
# [lo, hi)
def helper(lo, hi):
if lo >= hi:
return None
target = preorder[lo]
root = TreeNode(target)
mid = lo + 1
while mid < hi and preorder[mid] < target:
mid += 1
root.left = helper(lo + 1, mid)
root.right = helper(mid, hi)
return root
return helper(0, len(preorder))
# https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/252232/JavaC%2B%2BPython-O(N)
# because len(A) <= 100.
# Time: O(100).
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def bstFromPreorder(self, preorder):
"""
:type preorder: List[int]
:rtype: TreeNode
"""
self.idx = 0
n = len(preorder)
# [lo, hi]
def helper(lo, hi):
if self.idx == n or preorder[self.idx] < lo or preorder[self.idx] > hi:
return None
root = TreeNode(preorder[self.idx])
self.idx += 1
root.left = helper(lo, root.val)
root.right = helper(root.val, hi)
return root
return helper(1, 100)
|
c5403336fd9befacfa20b2de8fdd28c9703c2a6b | linkem97/holbertonschool-machine_learning | /math/0x04-convolutions_and_pooling/2-convolve_grayscale_padding.py | 1,122 | 3.59375 | 4 | #!/usr/bin/env python3
""" This module has the method
convolve_grayscale_padding(images, kernel, padding):
"""
import numpy as np
def convolve_grayscale_padding(images, kernel, padding):
"""This method performs a convolution on grayscale
images with custom padding
"""
images = np.pad(images, ((0, 0), (padding[0], padding[0]),
(padding[1], padding[1])),
'constant', constant_values=0)
rows_im = images.shape[1]
cols_im = images.shape[2]
rows_k = kernel.shape[0]
cols_k = kernel.shape[1]
new_rows = rows_im - rows_k + 1
new_cols = cols_im - cols_k + 1
# print(new_cols, new_rows)
new = np.ones((images.shape[0], new_rows, new_cols))
# print(new.shape)
# print(new)
for i in range(new.shape[1]):
for j in range(new.shape[2]):
ans = images[:, i:rows_k + i, j:cols_k + j] * kernel
# print(ans.shape)
# print(ans.T.shape)
# print(np.sum(ans, axis=2).shape)
mat = np.sum(np.sum(ans.T, axis=1), axis=0)
new[:, i, j] = mat
return new
|
4c647bc2bf5fdc2f8eb12e7d351a48f34448b257 | aallalxndr/cscc11 | /linearRegression.py | 806 | 3.609375 | 4 | import math
def mean(values):
mean = sum(values) / float(len(values))
return mean
def covariance(x, meanX, meanY):
covariance = 0.0
for i in range(len(x)):
covariance +=(x[i] - meanX)* (y[i] - meanY)
return covariance
def variance(values, mean):
variance = sum([(x-mean)**2 for x in values])
return variance
def coefficients(data):
x = [row[0] for row in data]
y = [row[1] for row in data]
x_mean, y_mean = mean(x), mean(y)
b1 = covariance(x , x_mean, y, y_mean) / variance(x, x_mean)
b0 = y_mean - b1 * x_mean
return [b0,b1]
def regress(train,test):
predictions = list()
b0, b1 = coefficients(train)
for row in test:
y = b0 + b1 * row[0]
predictions.append(y)
return predictions |
c2b13e1895ed846a54c41f5659b2b2cfcc5b8723 | xanderyzwich/Playground | /python/puzzles/encoder.py | 953 | 3.71875 | 4 | """
Given a string, Encode any stretch of characters to an encoding of <char><count>.
This should account for any character, and should encode upper and lower case differently.
"""
from unittest import TestCase
from tools.decorators import function_details
@function_details
def encode(plaintext):
ciphertext = ''
current, count = '', 0
for p in plaintext:
if p == current:
count += 1
else:
ciphertext += f'{current}{count}'if len(current)>0 else ''
current, count = p, 1
ciphertext += f'{current}{count}'
return ciphertext
class TestEncode(TestCase):
def test_one(self):
assert encode('AABBAACCDaaTTttcc') == 'A2B2A2C2D1a2T2t2c2'
def test_two(self):
assert encode('ABCAAA') == 'A1B1C1A3'
def test_three(self):
assert encode('TTGGCCGTCGT') == 'T2G2C2G1T1C1G1T1'
def test_four(self):
assert encode('!!..??%%..') == '!2.2?2%2.2'
|
ac0e1ebf2448e20a448f135827cd746d5c0e34d0 | LaurentLabine/fcc_demographic_data_analyzer | /demographic_data_analyzer.py | 4,802 | 4.1875 | 4 | import pandas as pd
data_url = 'https://raw.githubusercontent.com/LaurentLabine/fcc_data_analysis_python/main/demographic.csv'
def calculate_demographic_data(print_data=True):
# Read data from file
df = pd.read_csv(data_url)
df.info()
# How many of each race are represented in this dataset? This should be a Pandas series with race names as the index labels.
race_count = df['race'].value_counts()
# What is the average age of men?
average_age_men = round(df.loc[df['sex'] == "Male","age"].mean(),1)
# What is the percentage of people who have a Bachelor's degree?
percentage_bachelors = round(len(df.loc[df['education'] == "Bachelors"].value_counts())/len(df.index)*100,1)
# What percentage of people with advanced education (`Bachelors`, `Masters`, or `Doctorate`) make more than 50K?
education_list = ["Bachelors","Masters","Doctorate"]
# with and without `Bachelors`, `Masters`, or `Doctorate`
higher_education = df.loc[(df['education'].isin(education_list))]
lower_education = lower_education = df.loc[~(df['education'].isin(education_list))]
# percentage with salary >50K
higher_education_rich = round((len(higher_education.loc[higher_education["salary"] == ">50K"])/len(higher_education))*100,1)
# What percentage of people without advanced education make more than 50K?
lower_education_rich = round(len(lower_education.loc[lower_education["salary"] == ">50K"])/len(lower_education)*100,1)
# What is the minimum number of hours a person works per week (hours-per-week feature)?
min_work_hours = df["hours-per-week"].min()
# What percentage of the people who work the minimum number of hours per week have a salary of >50K?
min_hours = df.loc[df["hours-per-week"] == df["hours-per-week"].min()]
rich_percentage = round(len(min_hours.loc[min_hours["salary"] == ">50K"])/len(min_hours)*100,1)
# What country has the highest percentage of people that earn >50K?
dfsal = df[["salary", "native-country"]]
dfsal.loc[dfsal["salary"] == ">50K"].value_counts(normalize=True).max()
dfref = dfsal["native-country"].value_counts().reset_index()
dfref.columns = ["native-country","nb"]
total_data_per_countries = dfref.set_index('native-country').T.to_dict("records")[0]
df_over_50k = dfsal.loc[dfsal["salary"] == ">50K"].value_counts().reset_index()
del df_over_50k['salary']
df_over_50k.columns = ["native-country","nb"]
over_50k = df_over_50k.set_index('native-country').T.to_dict("records")[0]
res = {}
for country in total_data_per_countries:
if(country in over_50k):
res[country] = over_50k[country]/total_data_per_countries[country]
new = pd.DataFrame.from_dict(res, orient ='index').reset_index()
new.columns=["country","wealth-%"]
highest_earning_country_percentage = round(new.loc[new['wealth-%'].idxmax()].to_dict()["wealth-%"]*100,1)
highest_earning_country = new.loc[new['wealth-%'].idxmax()].to_dict()["country"]
# Identify the most popular occupation for those who earn >50K in India.
india_oc = df.loc[df['native-country'] == "India"]
india_over_50k = india_oc.loc[india_oc["salary"] == ">50K"]
india_over_50k_values = india_over_50k["occupation"].value_counts().reset_index()
top_IN_occupation = india_over_50k_values.loc[india_over_50k_values['occupation'].idxmax(),["index"]].to_dict()["index"]
# DO NOT MODIFY BELOW THIS LINE
if print_data:
print("Number of each race:\n", race_count)
print("Average age of men:", average_age_men)
print(f"Percentage with Bachelors degrees: {percentage_bachelors}%")
print(f"Percentage with higher education that earn >50K: {higher_education_rich}%")
print(f"Percentage without higher education that earn >50K: {lower_education_rich}%")
print(f"Min work time: {min_work_hours} hours/week")
print(f"Percentage of rich among those who work fewest hours: {rich_percentage}%")
print("Country with highest percentage of rich:", highest_earning_country)
print(f"Highest percentage of rich people in country: {highest_earning_country_percentage}%")
print("Top occupations in India:", top_IN_occupation)
return {
'race_count': race_count,
'average_age_men': average_age_men,
'percentage_bachelors': percentage_bachelors,
'higher_education_rich': higher_education_rich,
'lower_education_rich': lower_education_rich,
'min_work_hours': min_work_hours,
'rich_percentage': rich_percentage,
'highest_earning_country': highest_earning_country,
'highest_earning_country_percentage':
highest_earning_country_percentage,
'top_IN_occupation': top_IN_occupation
} |
4c9e4357ce6bb2beff94e8a110c29ed51dbb82c9 | nararodriguess/programacaoempython1 | /ex034.py | 219 | 3.6875 | 4 | salario = float(input('Digite o seu salário: '))
if salario > 1250:
novo = salario * (1 + 0.1)
else:
novo = salario * (1 + 0.15)
print(f'Seu salário era R${salario:.2f} reais, agora será R${novo:.2f} reais')
|
8e078af22b22ac81eb324de255de0c10bada7876 | TenederoGerard/PANDAS_2 | /cars1.py | 592 | 3.6875 | 4 | import pandas as pd
#Corresponding .csv file into a data frame named cars using pandas
cars = pd.read_csv('cars.csv')
#Display the first five rows with odd-numbered columns.
B= cars.iloc [:5, 0::2]
#Display the row contains the ‘Model’ of Mazda RX4’
C= cars.iloc [:1]
#Displays the cylinders (‘cyl’) of the car model ‘Camaro Z28’
D= cars.loc [[23], ['Model', 'cyl']]
#Displays cylinders (‘cyl’) gear type (‘gear’) of the car models
#‘Mazda RX4 Wag’, ‘Ford Pantera L’ and ‘Honda Civic’.
E = cars.loc [[1,18,28], ['Model','cyl','gear']]
|
c75c080569ec591e78489cdf1f2600a82509dc9e | DoubleS-Lee/python_practice | /practice_02_01.py | 3,873 | 3.765625 | 4 | # 파이썬으로 배우는 알고리즘 트레이딩
# https://wikidocs.net/2843
#%%
# 2-1
daum_price = 89000
naver_price = 751000
daum = 100
naver = 20
total = daum_price * daum + naver_price * naver
print(total)
# 2-2
daum_per = 0.05
naver_per = 0.1
total = daum_price * daum * daum_per + naver_price * naver * naver_per
print(total)
#%%
# 2-3
F=50
C = (F-32)/1.8
#%%
# 2-4
print('pizza\n'*10)
#%%
# 2-5
naver = 1000000
days = 3
for i in range(days):
naver *= 0.7
print(naver)
#%%
# 2-6
print("이름: 파이썬 생년월일: 2014년 12월 12일 주민등록번호: 20141212-1623210")
#%%
# 2-7
s = 'Daum KaKao'
s = s[-5:] + " " + s[:4]
print(s)
#%%
# 2-8
a = 'hello world'
a = 'hi' + ' ' + a[-5:]
print(a)
#%%
# 2-9
x = 'abcdef'
x = x[1:5] + x[-1] + x[0]
print(x)
#%%
# 3-1
naver_closing_price = [474500, 461500, 501000, 500500, 488500]
# 3-2
print(max(naver_closing_price))
# 3-3
print(min(naver_closing_price))
# 3-4
print(max(naver_closing_price)-min(naver_closing_price))
# 3-5
print(naver_closing_price[2])
# 3-6
naver_closing_price1 = ['09/07','09/08','09/09','09/10','09/11']
naver_closing_price2 = dict(zip(naver_closing_price1,naver_closing_price))
print(naver_closing_price2)
# 3-7
naver_closing_price2['09/09']
#%%
# 4-1
for i in range(5):
print('*',end='')
#%%
# 4-2
for i in range(4):
for k in range(5):
print('*', end='')
print('')
#%%
# 4-3
for i in range(6):
print('*'*i)
#%%
# 4-4
for i in range(6):
print('*'*(5-i))
#%%
# ! 4-5 for문을 가지고 만들면 된다
#%%
# 4-9
apart = [[101, 102, 103, 104],[201, 202, 203, 204],[301, 302, 303, 304], [401, 402, 403, 404]]
arrears = [101, 203, 301, 404]
for i in apart:
for k in i:
if k not in arrears:
print(k)
#%%
# 5-1
def myaverage(a, b):
result = (a+b)/2
return result
print(myaverage(3,4))
#%%
# 5-2
def get_max_min(data_list):
data_max = max(data_list)
data_min = min(data_list)
return data_max, data_min
a = [5,6,7,8,9,10]
print(get_max_min(a))
#%%
# ! 5-3 os.listdir(path) : path 디렉토리에 있는 모든 파일들을 보여준다
import os
def get_txt_list(path):
get_txt_list('c:/')
#%%
# 5-4
def bmi_func(weight, height):
bmi = float(weight)/((float(height)*0.01)*(float(height)*0.01))
print(bmi)
if bmi < 18.5:
result = '마른체형'
elif 18.5 <= bmi < 25.0:
result = '표준'
elif 25.0 <= bmi < 30.0:
result = '비만'
else:
result = '고도비만'
return print(result)
weight = input('몸무게를 입력하세요 (kg) : ')
height = input('키를 입력하세요 (cm) : ')
print(bmi_func(weight, height))
#%%
# 5-6
def get_triangle_area(width, height):
area = width * height * 0.5
return print(area)
get_triangle_area(3,3)
#%%
# 5-7
def add_start_to_end(start, end):
list_num = range(int(start),int(end)+1)
return sum(list_num)
a = input('시작값을 입력하세요 : ')
b = input('마지막 값을 입력하세요 : ')
c = add_start_to_end(a,b)
print(c)
#%%
# 5-8
def string_3(list_str):
list_after = []
for i in list_str:
list_after.append(i[:3])
return list_after
list_str = ['Seoul', 'Daegu', 'Kwangju', 'Jeju']
k = string_3(list_str)
print(k)
#%%
# 6-1
class point():
def __init__(self, x, y):
self.x = x
self.y = y
def setx(self,x):
self.x = x
return self.x
def sety(self,y):
self.y = y
return self.y
def get(self):
return (self.x, self.y)
def move(self, dx, dy):
self.x = self.x + dx
self.y = self.y + dy
return self.x, self.y
# 6-2
a = point(1,2)
print(a.setx(3))
print(a.sety(3))
print(a.get())
print(a.move(1,2))
#%%
# 6-3
class Stock():
market = 'kospi'
a = Stock()
b = Stock()
|
1b400aa72c54b93a88e12ec9994d08bc7b87688d | hygnic/Gispot | /gispot/test/md/详解pack.py | 793 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# ---------------------------------------------------------------------------
# Author: LiaoChenchen
# Created on: 2021/1/10 16:36
# Reference:
"""
Description:
Usage:
"""
# ---------------------------------------------------------------------------
import Tkinter as tk
# py2.7 tk8.5
if __name__ == '__main__':
class ScrollWidge(object):
def __init__(self):
self.master = tk.Tk()
self.frame = tk.Frame(self.master)
# self.frame.pack(expand=True, fill="both") # 示例1.2
self.frame.pack() # 示例1.1
self.canvas = tk.Canvas(self.frame,bg="blue")
self.canvas.pack(expand=True, fill="both")
ScrollWidge().master.mainloop()
|
b0cc59677678fa06c24d25e25c390e47907e1e84 | VladCincean/homework | /Graph Algorithms/L2/utils.py | 782 | 3.6875 | 4 | class Queue:
def __init__(self):
self.__q = []
def enqueue(self, x):
self.__q.append(x)
def dequeue(self):
if len(self.__q) == 0:
return None
x = self.__q[0]
self.__q = self.__q[1:]
return x
def isEmpty(self):
return len(self.__q) == 0
def __len__(self):
return len(self.__q)
class Stack:
def __init__(self):
self.__s = []
def push(self, x):
self.__s.append(x)
def pop(self):
if len(self.__s) == 0:
return None
x = self.__s.pop()
return x
def isEmpty(self):
return len(self.__s) == 0
def __len__(self):
return len(self.__s)
|
0d814843ba4a5f49ff7f452fd9abd4d7d6b26e6c | cnpena/Coding-Practice | /Chapter1/1.6_stringCompression.py | 1,874 | 4.1875 | 4 | #Chapter 1: Arrays and Strings
#1.6 String Compression, page 91
#Performs a basic string compression using the counts
#of repeated characters.
#Example: aabcccccaaa becomes a2b1c5a3
#Iterates through the given string, checking the current
#letter against the next letter. If they're equivalent, keep moving.
#If not, add current letter/count to compressedString and reset currentCount
import unittest
def compress(string):
currentCount = 0
compressedString = ''
for i in range(len(string)):
currentCount +=1
if((i+1 >= len(string)) or string[i] != string[i+1]):
compressedString = compressedString + string[i] + str(currentCount)
currentCount = 0
if(len(compressedString) < len(string)):
return compressedString
else:
return string
#If we only care about number of occurrences, not order:
#Utilizes hash table to keep track of number of occurences of each letter.
#Iterates through hash table to build a string
def compress2(string):
table = createHashTable(string)
compressedString = ''
for key in table:
compressedString = compressedString + key + str(table[key])
if(len(compressedString) < len(string)):
return compressedString
else:
return string
def createHashTable(string):
table = {}
for letter in string:
if(letter in table):
table[letter] +=1
else:
table[letter] = 1
return table
class Test(unittest.TestCase):
data1 = [ ('aabcccccaaa', 'a2b1c5a3'),
('abcd', 'abcd'),
('aaabbbcccddd', 'a3b3c3d3') ]
data2 = [ ('aabcccccaaa', 'a5b1c5'),
('abcd', 'abcd'),
('aaabbbcccddd', 'a3b3c3d3') ]
def testCompression(self):
for [string, expected] in self.data1:
self.assertEqual(compress(string), expected)
for [string, expected] in self.data2:
self.assertEqual(compress2(string), expected)
if __name__ == "__main__":
unittest.main() |
ce366f1a34aa029740a8d3dc887fea61b6f525a4 | aichaitanya/Python-Programs | /factorial.py | 247 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 16 21:45:44 2019
@author: Patil
"""
n=int(input('Enter Number : '))
def fact(n):
if n==1:
return 1
else :
return n*fact(n-1)
print("Factorial is %d" % fact(n)) |
cf9fabd9ffb6e2704e381aa09271bd5b0bdda6e5 | Spaceunit/calculation_methods_2016 | /fixed-point_iteration_matrix0.py | 2,758 | 3.71875 | 4 | import math
import matrix
class FPIM:
def __init__(self):
self.am = matrix.Matrix([],"Initial matrix")
self.commands = {
"none": 0,
"exit": 1,
"test": 2,
"clear": 3,
"help": 4,
"new": 5,
"show slist": 6,
"show scount": 7,
"makei": 8,
"showi": 9,
"start": 10,
"old": 11
}
pass
def inputnewdata(self):
task = 0
self.am = matrix.Matrix([], "Initial matrix")
while (task != 1):
print('')
print("Enter matrix dimension:")
while (task != 1):
num = int(input("-> "))
print("Input is correct? (enter - yes/n - no)")
command = input("-> ")
if (command != "n"):
self.am = self.inputmatrix(num)
task = 1
task = 0
self.am.rename("Initial matrix")
self.am.showmatrix()
print("Matrix is correct? (enter - yes/n - no)")
command = input("-> ")
if (command != "n"):
task = 1
def inputmatrix(self, num):
print('')
i = 0
task = 0
nm = matrix.Matrix([], "new matrix")
while (i < num):
print("Enter matrix row (use spaces)")
print("Row ", i + 1)
while (task != 1):
row = list(map(float, input("-> ").split()))
print("Input is correct? (enter - yes/n - no)")
command = input("-> ")
if (command != "n" and len(row) == num):
task = 1
nm.appendnraw(row)
elif (len(row) != num):
print('')
print("Incorrect input: count of items.")
task = 0
i += 1
return nm
def resolve(self):
pass
def dostaff(self):
task = 0
while (task != 1):
print('')
print("LU factorization v0.0002 betta")
print('')
task = self.enterCommand()
if (task == 2):
#self.dostaff()
elif (task == 3):
pass
elif (task == 4):
self.showHelp()
elif (task == 5):
self.inputnewdata()
pass
elif (task == 6):
self.am.showmatrix()
pass
elif (task == 10):
self.resolve()
print("Result:")
print("result")
pass
elif (task == 11):
self.inputnewdata()
pass |
1f6394627645122b6f8cd0ff8127a3c4b2e37401 | rrr5458/python102 | /exercises_multiply.py | 138 | 3.78125 | 4 | numbers = [-13, -4, 7, 11, -666, 23, -1134]
multiply_list = []
for num in numbers:
multiply_list.append(num * 3)
print(multiply_list) |
632bed19e32e98318b29215d147edd4c1a116867 | billkd24/python | /conditions2.py | 260 | 4.15625 | 4 | age = int (input("Please enter your age:"))
if age >= 3 and age <= 5:
print ("Join Pre-School")
elif age >= 6 and age <= 7:
print ("Join Grade School")
elif age >= 8:
print ("Join High School")
else:
print ("Not elgible to join")
|
10757d2fdfdca0ebcbd918122694d4ba8d0f3b20 | Nchuijangzelie/zenia | /team_chooser/main.py | 1,604 | 4.15625 | 4 | #!/bin/python3
from random import choice
#this code below creats a list from player.txt file
#players = ['Zelie','Ashley','Rodrigue','Sebastien','Kcenia','Susan','Julius','Amin']
players = []
file = open('players.txt', 'r')
players = file.read().splitlines()
print(players)
#this code creates three empty list
teamA = []
teamB = []
teamC = []
#this code shows that while loop is added to keep choosing players until the lengh of the player list is zero
while len(players) > 0:
playerA = choice(players)
#print(playerA)
teamA.append(playerA)
players.remove(playerA)
#print('Players left:', players)
#this code shows that ifall players are chosen then stop
if players == []:
break
#this code is to chose playerB.
playerB = choice(players)
#print (playerB)
teamB.append(playerB)
players.remove(playerB)
#this code shows that ifall players are chosen then stop
if players == []:
break
#this code is to chose playerC.
playerC = choice(players)
#print (playerC)
teamC.append(playerC)
players.remove(playerC)
#print('players left:',players)
#this code below creats a list from Zelie.txt file
teamNames = []
file = open('Zelie.txt', 'r')
teamNames = file.read().splitlines()
#the code below give your teams random names for the three teams
teamNamesA = choice(teamNames)
teamNames.remove(teamNamesA)
teamNamesB = choice(teamNames)
teamNames.remove(teamNamesB)
teamNamesC = choice(teamNames)
teamNames.remove(teamNamesC)
#the code below print team names
print('This are your teams')
print(teamNamesA ,teamA)
print(teamNamesB ,teamB)
print(teamNamesC ,teamC)
|
e9774bd92a37c6fddebb8f0fc694ea016e966c86 | samcrohub/Exercici2 | /Exercici2-YolandaAlonso.py | 562 | 4.0625 | 4 | #! /usr/bin/env python
# encoding: utf-8
print "per sortir de la aplicació escriu 'fi' quan et pregunti pel teu nom"
salir=0
while salir !="fi":
"""declaramos aquí la variable para que el while nos vuelva a preguntar"""
salir= raw_input ("Escriu el teu nom: ")
"""ponemos una condición para que nos deje salir"""
if salir == "fi":
print "Adeu"
break
"""ponemos aquí el break porque sino no nos dejaba salir"""
numero= int (raw_input ("Escriu un numero: "))
for i in range(numero):
print salir,"\t","\t"
if salir == "fi":
print "Adeu"
|
77309cf8ab11a92f47804ba66e7f58abd705544e | lscosta90br/scripts | /virtualbox-cmd.py | 4,667 | 3.515625 | 4 | """Programa para interagir com o VirtualBox."""
from os import popen
from argparse import ArgumentParser
parser = ArgumentParser(prog='virtualbox-cmd cli',
description='VirtualBox commandline - programa para manipular hosts virtuais', # NOQA
fromfile_prefix_chars='@')
parser.add_argument('operacao', choices=['liga', 'desliga', 'lista', 'lista_todos', 'ativo', 'existe'],
help='''
liga: Liga a(s) VM passada no parâmetro;
desliga: Desliga a(s) VM passada no parâmetro;
lista: Lista as VMs ativas;
lista_todos: Lista as VMs ligadas;
ativo: Verifica quais VMs estão ativas
existe: Verifica se VM existe;
''')
parser.add_argument('--host', action='store',
help='VM a ser manipulada no VirtualBox')
parser.add_argument('-v', '--verbose', action='count',
help='Entenda o que estamos fazendo', default=0)
args = parser.parse_args()
def verbose(func):
"""Decorador para verificar a verbosidade (-v)."""
def _inner(*verb):
if args.verbose == 1:
print(f'Estamos operando com {args.operacao} {args.host}')
if args.verbose == 2:
print(f'{func.__name__}({args.host})')
if args.verbose >= 10:
print('Vá se danar com tanta verbosidade')
exit()
return func(*verb)
return _inner
# windows
cmd_vboxmanage = '\"C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe\"'
#linux
# cmd_vboxmanage = '/usr/bin/vboxmanage'
@verbose
def host_existe(host_vm):
"""
Verifica se a maquina virtual existe.
args:
host_vms - Nome da máquina virtual
"""
cmd = cmd_vboxmanage + ' list vms'
cmd = popen(cmd).read()
cmd_lista = cmd.split('\"')
if host_vm in cmd_lista:
# print(f'Host virtual {host_vm} existe!')
return True
else:
print(f'Host virtual {host_vm} não existe!')
return False
@verbose
def host_is_ativo(host_vm):
"""
Verifica se a maquina virtual está ativa.
args:
host_vms - Nome da máquina virtual
"""
cmd = cmd_vboxmanage + ' list runningvms'
cmd = popen(cmd).read()
cmd_lista = cmd.split('\"')
if host_vm in cmd_lista:
print(f'Host virtual {host_vm} está ligado!!')
return True
elif host_existe(host_vm):
print(f'Host {host_vm} está desligado')
return False
else:
print('Host nao existe')
return False
@verbose
def lista_host_ativos():
"""Lista máquinas virtuais ativas."""
cmd = cmd_vboxmanage +' list runningvms'
cmd = popen(cmd).read()
print('Lista de Hosts Virtuais Ativos:')
return cmd
@verbose
def lista_todos_host():
"""Lista máquinas virtuais ativas."""
cmd = cmd_vboxmanage +' list vms'
cmd = popen(cmd).read()
print('Lista de todos os Hosts Virtuais:')
return cmd
@verbose
def liga_host(*hosts_vms):
"""
Liga a maquina virtual.
args:
host_vms - Nome da máquina virtual
"""
# print(type(hosts_vms))
# host
for host_vm in hosts_vms:
if host_existe(host_vm):
if not host_is_ativo(host_vm):
cmd = cmd_vboxmanage + 'startvm' + host_vm + ' --type headless'
popen(cmd).read()
print(f'Host virtual {host_vm} está sendo ligado...')
# return f'Host virtual {host_vm} está sendo ligado...'
@verbose
def desliga_host(*host_vms):
"""
Desliga a maquina virtual.
args:
host_vms - Nome da máquina virtual
"""
print(type(host_vms))
print(host_vms)
for host_vm in host_vms:
if host_existe(host_vm) and host_is_ativo(host_vm):
print(f'Host virtual {host_vm} está sendo preparado para o desligamento...!!')
cmd = cmd_vboxmanage + ' controlvm ' + host_vm + ' poweroff'
print(f'desliga: {cmd}')
popen(cmd).read()
print(f'Host virtual {host_vm} foi desligado com sucesso!')
# return f'Host virtual {host_vm} foi desligado com sucesso!'
if __name__ == '__main__':
if args.operacao == 'liga':
liga_host(args.host)
if args.operacao == 'desliga':
desliga_host(args.host)
if args.operacao == 'lista' and args.host is None:
lista_host_ativos()
if args.operacao == 'ativo':
host_is_ativo(args.host)
if args.operacao == 'existe':
host_existe(args.host)
if args.operacao == 'lista_todos':
host_existe(args.host)
|
2ed2ddb66b5e37169394ff408784c0082b44bb00 | ZhengZixiang/interview_algorithm_python | /jianzhi/22.链表中环的入口结点.py | 1,113 | 3.875 | 4 | # 给定一个链表,若其中包含环,则输出环的入口节点。
#
# 若其中不包含环,则输出null。
#
# 样例
# QQ截图20181202023846.png
#
# 给定如上所示的链表:
# [1, 2, 3, 4, 5, 6]
# 2
# 注意,这里的2表示编号是2的节点,节点编号从0开始。所以编号是2的节点就是val等于3的节点。
#
# 则输出环的入口节点3.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def entryNodeOfLoop(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
if fast == slow:
slow = head
while fast != slow:
fast = fast.next
slow = slow.next
return slow
else:
return None
|
4294cc2a7c61efd483d79140c96d2fc51f04dc0f | confar/python_challenges | /difference_of_times.py | 1,160 | 4.21875 | 4 | """
Difference of times
Given the values of the two moments in time in the same day: hours, minutes and seconds for each of the time moments.
It is known that the second moment in time happened not earlier than the first one.
Find how many seconds passed between these two moments of time.
Input data format
The program gets the input of the three integers: hours, minutes, seconds, defining the first moment of time and
three integers that define the second moment time.
Output data format
Output the number of seconds between these two moments of time.
"""
import io
inp1 = io.StringIO('''1
1
1
2
2
2''')
inp2 = io.StringIO('''1
2
30
1
3
20''')
def main(str_buffer):
first = get_time(str_buffer)
second = get_time(str_buffer)
return second - first
def get_time(str_buffer):
seconds = 0
for index in range(3):
if index == 0:
seconds += int(next(str_buffer)) * 3600
elif index == 1:
seconds += int(next(str_buffer)) * 60
else:
seconds += int(next(str_buffer))
return seconds
if __name__ == '__main__':
assert main(inp1) == 3661
assert main(inp2) == 50
|
f737ac2b369b2897222989993371ec11a5e7ec46 | KelineBalieiro/Python | /sorveteria.py | 855 | 3.765625 | 4 | class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(self.restaurant_name.title())
print(self.cuisine_type.title())
def open_restaurante(self):
print("O " + self.restaurant_name.title() + " está aberto")
restaurante = Restaurant('Chimarrão', 'Churrasco')
print("O nome do restaurante é " + restaurante.restaurant_name.title())
print("O tipo de comida servida é " + restaurante.cuisine_type.title())
restaurante.open_restaurante()
class IceCreamStand(Restaurant):
def __init__(self, flavors):
self.flavors = flavors
list_flavors = IceCreamStand (['Morango', 'Creme', 'Chocolate', 'Framboesa'])
print("Sabores disponíveis: " + str(list_flavors.flavors))
|
9cd123c6fec21d0f1fa0dbde511d254046bcde06 | aurel1212/Sp2018-Online | /students/ssankura/lesson06/Activity/calculator/calculator.py | 1,672 | 3.921875 | 4 | """
Lesson06 - Activity 1
Author: Sireesha Sankuratripati
Implementation of Calculator
"""
from .exceptions import InsufficientOperands
class Calculator(object):
""" Implementation of the Calculator Class """
def __init__(self, adder, subtracter, multiplier, divider):
"""Constructor for Calculator"""
self.adder = adder
self.subtracter = subtracter
self.multiplier = multiplier
self.divider = divider
self.stack = []
def enter_number(self, number):
""" enter the number on which an operation needs to be performed
the number will get inserted into the stack"""
self.stack.insert(0, number)
def _do_calc(self, operator):
""" Perform the calculation based on the mathemarical operation
specified in the operator argument"""
try:
result = operator.calc(self.stack[1], self.stack[0])
except IndexError:
raise InsufficientOperands
self.stack = [result]
return result
def add(self):
""" Add method which calls the calc method
on the adder object """
return self._do_calc(self.adder)
def subtract(self):
""" Subtract method which calls the calc method
on the subtracter object """
return self._do_calc(self.subtracter)
def multiply(self):
""" Multiply method which calls the calc method
on the multiplier object """
return self._do_calc(self.multiplier)
def divide(self):
""" Divide method which calls the calc method
on the divider object """
return self._do_calc(self.divider)
|
a5e8035ed68a1c8e95fffab02a5b2ade7fab905a | d-ariel/addhealth | /data_analysis.py | 5,004 | 3.71875 | 4 | import pandas
import numpy
#read in data set
my_addHealth = pandas.read_csv('addhealth_pds.csv', low_memory=False)
#upper-case all My Health dataframe column names
my_addHealth.columns = map(str.upper, my_addHealth.columns)
pandas.set_option('display.float_format', lambda x:'%f'%x)
#convert relevant output objects to numeric
my_addHealth["H1PR1"] = pandas.to_numeric(my_addHealth["H1PR1"])
my_addHealth["H1PR2"] = pandas.to_numeric(my_addHealth["H1PR2"])
my_addHealth["H1PR3"] = pandas.to_numeric(my_addHealth["H1PR3"])
my_addHealth["H1EE1"] = pandas.to_numeric(my_addHealth["H1EE1"])
my_addHealth["H1EE2"] = pandas.to_numeric(my_addHealth["H1EE2"])
print("The following data is compromised of the whole dataset.")
#frequency distributions for 3 variables related to perceived care from adults, teachers, and parents
print("[whole set] distribution for variable H1PR1 - How much do you feel that adults care about you?")
adults_care_c = my_addHealth["H1PR1"].value_counts(sort=True)
print(adults_care_c)
print("[whole set] percentage for variable H1PR1: adult support")
adults_care_p = my_addHealth["H1PR1"].value_counts(sort=True, normalize=True)
print(adults_care_p)
print("[whole set] distribution for variable H1PR2 - How much do you feel that your teachers care about you?")
teachers_care_c = my_addHealth["H1PR2"].value_counts(sort=True)
print(teachers_care_c)
print("[whole set] percentage for variable H1PR2: teacher support")
teachers_care_p= my_addHealth["H1PR2"].value_counts(sort=True, normalize=True)
print(teachers_care_p)
print("[whole set] distribution for variable H1PR3 - How much do you feel that your parents care about you?")
parents_care_c = my_addHealth["H1PR3"].value_counts(sort=True)
print(parents_care_c)
print("[whole set] percentage for variable H1PR3: parent support")
parents_care_p = my_addHealth["H1PR3"].value_counts(sort=True, normalize=True)
print(parents_care_p)
#to see how many H1EE1 non-responses exist in full dataset
print("[whole set] distribution for variable H1EE1")
desire_for_college_c = my_addHealth["H1EE1"].value_counts(sort=True)
print(desire_for_college_c)
print("[whole set] percentage for variable H1EE1: desire for college")
desire_for_college_p = my_addHealth["H1EE1"].value_counts(sort=True, normalize=True)
print(desire_for_college_p)
#to see how many H1EE2 non-responses exist in full dataset
print("[whole set] distribution for variable H1EE2")
likelihood_of_college_c = my_addHealth["H1EE2"].value_counts(sort=True)
print(likelihood_of_college_c)
print("[whole set] percentage for variable H1EE2: likelihood of college")
likelihood_of_college_p = my_addHealth["H1EE2"].value_counts(sort=True, normalize=True)
print(likelihood_of_college_p)
# var H1EE1 represents adolescents' self-reported desires to go to college (measured on a scale of 1-5).
# var H1EE2 represents adolescents' self-reported likelihood of attending college (measured on a scale of 1-5).
# this creates a subset of the initial dataframe that is limited to
# responses with H1EE1 = 5 (very likely) and H1EE2 = 5 (very likely).
my_addHealth_subset = my_addHealth[(my_addHealth["H1EE1"] == 5) & (my_addHealth["H1EE2"] == 5)] #subset
my_addHealth_subset_copy = my_addHealth_subset.copy() #copy of subset
print("The following data is compromised of my subset.")
# to demonstrate that my subset is populated correctly:
print("The number of observations in H1EE1 should be equivalent to the number of observations in H1EE2.")
print(my_addHealth_subset_copy["H1EE1"].value_counts(sort=True)) #contains only entries containing H1EE1 = 5
print(my_addHealth_subset_copy["H1EE2"].value_counts(sort=True)) #contains only entries containing H1EE2 = 5
#frequency distributions for 3 variables related to perceived care from adults, teachers, and parents
print("[subset] distribution for variable H1PR1 - How much do you feel that adults care about you?")
adults_care_count = my_addHealth_subset_copy["H1PR1"].value_counts(sort=True)
print(adults_care_count)
print("[subset] percentage for variable H1PR1: adult support")
adults_care_percentage = my_addHealth_subset_copy["H1PR1"].value_counts(sort=True, normalize=True)
print(adults_care_percentage)
print("[subset] distribution for variable H1PR2 - How much do you feel that your teachers care about you?")
teachers_care_count = my_addHealth_subset_copy["H1PR2"].value_counts(sort=True)
print(teachers_care_count)
print("[subset] percentage for variable H1PR2: teacher support")
teachers_care_percentage = my_addHealth_subset_copy["H1PR2"].value_counts(sort=True, normalize=True)
print(teachers_care_percentage)
print("[subset] distribution for variable H1PR3 - How much do you feel that your parents care about you?")
parents_care_count = my_addHealth_subset_copy["H1PR3"].value_counts(sort=True)
print(parents_care_count)
print("[subset] percentage for variable H1PR3: parent support")
parents_care_percentage = my_addHealth_subset_copy["H1PR3"].value_counts(sort=True, normalize=True)
print(parents_care_percentage)
|
1571e8e0e397d0449fd6c8f689460aa2df8b1c05 | jbeaulieu/MIT-ES.S70 | /lecture_4/group_4.py | 1,522 | 3.515625 | 4 | #################################
# Title: Lecture 4 Group Script #
# Lesson: Gauss' Law #
# Filename: group_4.py #
# Original Author: Joe Griffin #
# Most Recent Edit: 1/23/2015 #
# Last Editor: Joe Griffin #
#################################
# We will calculate the electric field due to a non-uniformly charged rod in space.
# We use direct integration and use symmetry to reduce it to a 1D scalar integral.
from math import sqrt, pi, cos
from const import E0
k = 1.0 / (4 * pi * E0)
def lamda(x):
return 1e-5 * cos(x)
# here dE_list is the y-component of the electric field because we relized that the other
# components are zero
def E(yp):
rod = ((-4.0, 0.0, 0.0), (4.0, 0.0, 0.0)) # Endpoint 1, endpoint 2
L = sqrt((rod[1][0] - rod[0][0])**2) # Length of rod
dx = 1.0e-3 # Integral increment length
dE_list = [] # differential contributions
for i in xrange(int(L / dx)): # Create our integration iterable
dq = lamda((i * dx) - (L / 2)) * dx
pos = rod[0][0] + ( i * dx) # Pos is x-coord of dq
r = sqrt(yp**2+ (pos)**2) # r is distance from pos to P=(0,yp,0)
dE = k * dq / (r**2) #magnitude if the E-field vector due to dq at point P
dE_list.append(dE * yp / r)
E = sum(dE_list) # Total E
return E
|
d5120c08f627237137611e7dfee5fb88d458c1ca | marytaylor/LearnPythonTheHardWay | /ex4.py | 1,124 | 4.59375 | 5 | #Here I am declaring how many cars there are
cars = 100
# This is how many seats in each car
space_in_a_car = 4
#This is how many drivers there are and there can only be 1 driver per a car.
drivers = 30
#This is how many people that can ride in a car and this does not count the drivers
passengers = 90
#There are not enough drivers for all of the cars so I need to find out how many cars will not be driven with this
cars_not_driven = cars - drivers
#It looks like 30 of the cars are driveable
cars_driven = drivers
#This is how many seats are avaliable in the cars that can be driven
carpool_capacity = cars_driven * space_in_a_car
#If we were to put everyone in a car, 1 by 1 per each car. Only 3 people would be in each car.
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available."
print "There are only", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
|
acc29cebf91324c592457aeb90ba36c5b3f3d9fa | joker-Infinite/python | /day_01/function.py | 890 | 3.8125 | 4 | #!/usr/bin/python3
if __name__ == '__main__':
def MAX(a, b):
if a > b:
return a
else:
return b
print(MAX(3, 4))
def address(a):
print(id(a))
a = 20
print(id(a))
a = 1
print(id(a))
address(a)
print(id(a))
def changeList(ls):
ls.append([1, 2, 3])
print('函数内:', ls)
return
ls = [0, 4, 5, 6]
print('函数外-前:', ls)
changeList(ls)
print('函数外-后:', ls)
def defaultData(name, age=90):
print('名字:', name)
print('年龄:', age)
defaultData('小明', 30)
defaultData(name='小李')
def moreData(a, *arr):
print(a)
print(arr)
moreData(1, 2, 3, 5, 6)
def dict(d, **dic):
print('字典:')
print(d)
print(dic)
dict(1, a=2, b=3)
|
63e320de4f806fa0741ba46cfa79e91265365813 | drewhoener/CS220 | /Project 2/src/player.py | 1,903 | 3.546875 | 4 | import random
class Player:
def make_bet(self, par1_bal):
"""
:param par1_bal: The balance of the player
:return: The bet placed
"""
pass
def want_card(self, par1_hand, par2_bank, par3_list, par4_list):
"""
:param par1_hand: The player's hand from the dealer
:param par2_bank: The player's bank from the dealer
:param par3_list: The one card that the dealer has placed face-down
:param par4_list: The cards that have already been revealed
:return: True if the player wants a card, False otherwise
"""
pass
def use_ace_hi(self, par1_hand):
pass
class DealerPlayer(Player):
def make_bet(self, par1_bal):
return 0
def use_ace_hi(self, par1_hand):
if par1_hand.score_hand(True) > 21:
return False
return True
def want_card(self, par1_hand, par2_bank, par3_list, par4_list):
par1_hand.score_hand(self.use_ace_hi(par1_hand))
if par1_hand.get_score() < 17:
return True
return False
class RandomPlayer(Player):
def use_ace_hi(self, par1_hand):
random.randint(0, 1)
def make_bet(self, par1_bal):
return random.randint(1, par1_bal)
def want_card(self, par1_hand, par2_bank, par3_list, par4_list):
par1_hand.score_hand(self.use_ace_hi(par1_hand))
if par1_hand.get_score() < 21:
return True
return False
class ConservativePlayer(Player):
def make_bet(self, par1_bal):
return par1_bal / 2
def use_ace_hi(self, par1_hand):
# Hey, he's a conservative dude, don't judge him
return False
def want_card(self, par1_hand, par2_bank, par3_list, par4_list):
par1_hand.score_hand(self.use_ace_hi(par1_hand))
if par1_hand.get_score() < 16:
return True
return False
|
91358716ddc829863e3d737ceca6319f46748b43 | manishadhakal/python-sms | /iterable_iteratier.py | 360 | 3.734375 | 4 | num=[1,2,3,4,5,6,7] #list ,string,tuple
def power(a):
return a**2
num2=map(lambda a:a**2,num) #fun,filter,map
new_iter=iter(num)
print(next(new_iter))
print(next(new_iter))
print(next(new_iter))
print(next(new_iter))
print(next(new_iter))
print(next(new_iter))
print(next(num2))
print(next(num))
for i in num2:
print(i)
for j in num2:
print(j) |
7f6e4a4573ba7a5e43ac40c53037c86bc96bad22 | pedrochaves/pyjson | /pyjson/utils.py | 805 | 3.515625 | 4 | def is_number(token):
return type(token) in [int, float]
def is_json_array(token):
return type(token) in [list, tuple]
def is_string(token):
return type(token) in [str, unicode]
def is_dict(token):
return type(token) == dict
def escape(string):
to_escape = {
'\"': '\\"',
"\n": "\\n",
"\r": "\\r",
"\t": "\\t",
"\b": "\\b",
"\u": "\\u"
}
for search, replace in to_escape.items():
string = string.replace(search, replace)
return string
def to_unicode(string):
token = ""
for char in string:
try:
token += char.decode("utf-8")
except UnicodeEncodeError:
unicode_token = "%x" % ord(char)
token += "\u%s" % (unicode_token.zfill(4))
return token
|
ab99bdb883e2f49183c2c20e232869bd08687e92 | NhanGiaHuy/CP1404_Pactical | /Prac_03/GPS.py | 1,009 | 3.96875 | 4 | import random
def main():
POPULATION = 1000
MAX_INCREASE_BORN = 20
MIN_INCREASE_BORN = 10
MAX_DECREASE_DIED = 25
MIM_DECREASE_DIED = 5
print("Welcome to the Gopher Population Simulator\nStarting population: 1000")
for year in range(1, 10):
print("year {}\n*****".format(year))
number_gopher_born = random_born(POPULATION, MAX_INCREASE_BORN, MIN_INCREASE_BORN)
number_gopher_died = random_died(POPULATION, MAX_DECREASE_DIED, MIM_DECREASE_DIED)
POPULATION = POPULATION + number_gopher_born - number_gopher_died
print("{} gophers were born. {} died.\nPopulation: {}".format(number_gopher_born,number_gopher_died,POPULATION))
def random_born(population, max, min):
number_gopher_born = round(population * (round(random.randint(min, max), 0)/100))
return number_gopher_born
def random_died(population, max, min):
number_gopher_died = round(population * (round(random.randint(min, max), 0)/100))
return number_gopher_died
main() |
7ac05a1d197d38b6aabad8b930f84f90e1b5872a | pascalmcme/myprogramming | /week3/round.py | 147 | 4.03125 | 4 | number = float(input('Enter a float number:'))
print(number)
roundedNumber = round(number)
print('{} rounded is {}' .format(number,roundedNumber)) |
6e08d0a904bd06c8864df1f8d51c0a57ee5e797b | sanskruti01/Social-Book | /Social Book App/passwd.py | 1,193 | 3.640625 | 4 | import string
def tooShort(pw):
'Password must be at least 6 characters'
return len(pw) >= 6
def tooLong(pw):
'Password cannot be more than 12 characters'
return len(pw) <= 12
def useLowercase(pw):
'Password must contain a lowercase letter'
return len(set(string.ascii_lowercase).intersection(pw)) > 0
def useUppercase(pw):
'Password must contain an uppercase letter'
return len(set(string.ascii_uppercase).intersection(pw)) > 0
def useNumber(pw):
'Password must contain a digit'
return len(set(string.digits).intersection(pw)) > 0
def useSpecialCharacter(pw):
'Password must contain a special character'
return len(set(string.punctuation).intersection(pw)) > 0
def checkCondition(pw, tests=[tooShort, tooLong, useLowercase, useUppercase, useNumber,useSpecialCharacter]):
for test in tests:
if not test(pw):
print(test.__doc__)
return False
return True
def passVerifier():
password=input("Please enter a password - must be secure and meet our format requirements")
if checkCondition(password):
print("Record has been written to file")
else:
passVerifier()
passVerifier()
|
76719fc292d9c3a7a48cee2f09f1e0bb63d750bd | matthewvedder/algorithms | /general/breadth-first-search.py | 1,170 | 3.578125 | 4 | from collections import deque
def breadth_first_search(graph, goal, initial_state):
node = { 'state': initial_state , 'cost': 0, 'path': [] }
frontier = deque()
frontier.append(node)
explored = []
if goal == node['state']: return node
while frontier:
node = frontier.popleft()
explored.append(node)
for child in graph[node['state']]:
child_node = {
'state': child,
'cost': node['cost'] + 1,
'path': node['path'] + [node['state']]
}
if not child_node in explored or frontier:
if goal == child_node['state']:
return child_node
else:
frontier.append(child_node)
explored.append(child_node)
social_graph = {}
social_graph["ayla"] = ["alice", "bob", "claire"]
social_graph["bob"] = ["anuj", "peggy"]
social_graph["alice"] = ["peggy"]
social_graph["claire"] = ["thom", "johnny"]
social_graph["anuj"] = []
social_graph["peggy"] = []
social_graph["thom"] = []
social_graph["johnny"] = []
print breadth_first_search(social_graph, "peggy", "ayla")
|
aa6e4478358ea3a95a291bad0d8cb3c2b9f4b712 | rxio/Python_Knowledge_Base | /File_Manipulation/0_Files_Intro.py | 390 | 3.96875 | 4 | file = open("numbers.txt", "r") #This line returns the file handle in read mode and stores it in the variable named 'file'
#If you don't pass in a second argument, it defaults to "r"
print(file) #This prints the file handle
print(file.name) #This prints the name of the file
print(file.mode) #This prints the mode that the file is currently in
file.close() #This closes the file handle ?
|
b8e98c624417e86dc1ead1dae3f91e156fc0f6e9 | nomadlife/project-euler | /p051.py | 844 | 3.921875 | 4 | # check prime. speed up by square root.
def isprime(n):
if n == 0 or n==1:
return False
i=2
loop=n**0.5
while i <= loop:
if n%i == 0:
return False
i+=1
return True
# replace and check if prime
def rep(num, s):
text = str(num)
if s not in text:
return False
cnt = text.count(s)
# result list
res=[]
# replace and check if prime
for i in range(int(s), 10):
test = text.replace(s, str(i), cnt)
if isprime(int(test)):
res.append(test)
return res, len(res)
for i in range(100, 10000000):
# target replacing number should start with 0,1,2. from 3, impossible to get 8 list.
for s in '012':
res = rep(i, s)
# print out
if res:
if res[1] > 6:
print(i, s, res)
|
5a5791001e6383e42281bc534f5162bd077dab66 | GHshangmu/Python_case | /python_code/algorithm/reverse_num.py | 448 | 3.8125 | 4 | # 反转数字
def reverse(x):
"""
:type x: int
:rtype: int
"""
str_num = str(x)
if x >= 0:
res = int(str_num[::-1])
if res <= -2 ** 32 or res >= 2 ** 31 - 1:
res = 0
return res
else:
res = -int(str_num[::-1][0:len(str_num) - 1])
if res <= -2 ** 32 or res >= 2 ** 31 - 1:
res = 0
return res
print(reverse(-1563847412))
print(-2147483651<=-2**32) |
ef26430871cf803b7b7b809620749bea6a773e5d | erickvaernet/Python3 | /5-Ventanas/3ra_ventana.pyw | 621 | 3.828125 | 4 | import tkinter
root = tkinter.Tk()
frame_1 = tkinter.Frame(root, width="1280", height="700")
frame_1.pack()
label1 = tkinter.Label(frame_1, text="Primer texto: Hola",
fg="black", font=("Arial", 12),)
label1.place(x=10, y=20)
"""Se podria resumir asi si es que no usamos mas la etiqueta:
tkinter.Label(frame_1, text="Primer texto: Hola", fg="black", font=("Arial", 12),).place(x=10, y=20)
"""
# IMAGENES solo png y gif=? sino agregar otra libreria
miImagen = tkinter.PhotoImage(file="icono.png")
label2 = tkinter.Label(frame_1, image=miImagen, )
label2.place(x=50, y=50)
root.mainloop()
|
Subsets and Splits