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 |
|---|---|---|---|---|---|---|
77837d59da73cc57524750289430417840a10d1e | hibiup/ImageRecognize | /sift/sift_feature_fetcher.py | 3,188 | 3.5625 | 4 | import cv2
def to_gray(color_img):
""" 转成灰阶图 """
gray = cv2.cvtColor(color_img, cv2.COLOR_BGR2GRAY) # cv2.CV_32S
return gray
def to_canny(img, low_threshold=100, ratio=3):
""" 抽取轮廓 """
edges = cv2.Canny(img, low_threshold, ratio * low_threshold, cv2.COLOR_BGR2GRAY)
return edges
def fetch_sift_info(img, gaussian=to_gray):
gray_img = gaussian(img)
kp, desc = gen_sift_features(gray_img)
return gray_img, kp, desc
def gen_sift_features(gray_img):
"""
生成 SIFT keypoint 和 descriptor
keypoint: 关键点有三个信息,位置、尺度、方向。
descriptor: 根据关键点周围 16×16 的像素区域,分成4个小块,每个小块创建 8 个bin 的直方图,这总共的 128 个信息的向量就是关键点描述符
的主要内容。(images/keypoint_descriptor.pngs)。 descriptor 的作用是对模板图和实时图通过对比关键点描述符来判断两个
关键点是否相同。使用的搜索算法为区域搜索算法当中最常用的k-d 树进行比对。比较之后消除错配点,最后得到两张图形是否一致。
keypoint 和 descriptor 的算法说明参考: https://blog.csdn.net/pi9nc/article/details/23302075
"""
sift = cv2.xfeatures2d.SIFT_create()
kp, desc = sift.detectAndCompute(gray_img, None)
return kp, desc
def inspect_keypoint_and_descriptor(keypoints, descriptors, index):
kp = keypoints[index]
desc = descriptors[index]
print('\tangle:\t', kp.angle)
print('\tclass_id:\t', kp.class_id)
print('\toctave (image scale where feature is strongest):\t', kp.octave)
print('\tpoint (x,y):\t', kp.pt)
print('\tresponse:\t', kp.response)
print('\tsize:\t', kp.size)
print('\n\tdescriptor:\n', desc)
def show_img_keypoint(img):
""" 返回带有 keypoint 的图 """
gray_img, kp, desc = fetch_sift_info(img, gaussian=to_gray)
# 合成带有 keypoint 的图
kp_img = cv2.drawKeypoints(img, kp, img.copy())
return kp_img, kp
def match_images(left_img, right_img, gaussian=to_gray, lines=None, distance=0.7):
"""
比对两组关键点描述,查找出相同的点位.
distance: 两个特征向量之间的欧氏距离,越小表明匹配度越高
参考: https://www.cnblogs.com/wangguchangqing/p/4333873.html
"""
left_gray_img, left_kp, left_desc = fetch_sift_info(left_img, gaussian)
right_gray_img, right_kp, right_desc = fetch_sift_info(right_img, gaussian)
bf = cv2.BFMatcher(cv2.NORM_L2)
matches = bf.knnMatch(left_desc, right_desc, k=2) #matches = sorted(bf.match(left_desc, right_desc), key=lambda x: x.distance)
good = []
for m in matches:
if 0 != m[1].distance and m[0].distance/m[1].distance < distance: #if m.distance/250 < distance: ???
good.append(m)
matched_img = cv2.drawMatchesKnn( ##matched_img = cv2.drawMatches(
left_img, left_kp,
right_img, right_kp,
good if lines == None else good[:lines], #matches[:lines],
None, #right_img.copy(),
flags=2)
return matched_img
|
97ab89f139c3ec631318f68ccb608831ead10835 | CHENG-KAI/Leetcode | /4_MedianofTwoSortArrays.py | 292 | 3.53125 | 4 | def findMedianSortedArrays(nums1, nums2):
num = nums1 + nums2
num.sort()
n = len(num)/2
if len(num) & 1 == 1:
return num[n]
else:
return float(num[n-1] + num[n])/2
nums1 = [1,3]
nums2 = [2]
findMedianSortedArrays(nums1, nums2)
|
92eee9693ebae133bcbf9ebdd621b5acd8e11e35 | edunzer/MIS285_PYTHON_PROGRAMMING | /WEEK 2/2.9.py | 148 | 4.09375 | 4 | print("Please enter the temperature in Celsius")
temp_c = int(input());
temp_f = ((temp_c*9/5)+32);
print(temp_f, 'is the converted temperature');
|
dc03bce119c16d0d47c7d2caec844b47d50d2ae6 | redpoint13/ProgrammingFoundations | /myshapes.py | 304 | 3.765625 | 4 | import turtle
def draw_frac():
circle = turtle.Turtle()
circle.shape("classic")
circle.color("orange")
circle.speed(100)
for i in range(0,36):
circle.circle(100)
circle.right(10)
carpet = turtle.Screen()
carpet.bgcolor("green")
draw_frac()
carpet.exitonclick()
|
d7dfa241f3777913ab3d4cbe8bf7b1cd2b155e73 | MajorGerman/Python-Programming-Georg-Laabe | /OOP_20.01.2020_Laabe.py | 3,656 | 3.65625 | 4 | ##### OOP_03 #####
### 1 ###
class Dog():
age = 0
name = ""
weight = 0
Laika = Dog()
Laika.age = 4
Laika.name = "Лайка"
Laika.weight = 20
### 2 ###
class Person():
name = ""
cellPhone = ""
email = ""
John = Person()
John.name = "John"
John.cellPhone = "37258317253"
John.email = "john1408@gmail.com"
Mary = Person()
Mary.name = "Mary"
Mary.cellPhone = "37256302440"
Mary.email = "marybest33@gmail.com"
### 3 ###
class Bird():
name = ""
color = ""
breed = ""
myBird = Bird()
myBird.color = "green"
myBird.name = "Sunny"
myBird.breed = "Sun Conure"
### 4 ###
class Player():
name = ""
x_position = 0
y_position = 0
health = 0
strenght = 0
player1 = Player()
player1.name = "Dylan"
x_position = 4
y_position = 4
health = 100
strenght = 15
### 5 ###
class Person:
name = ""
money = 0
nancy = Person()
name = "Nance"
money = 100
# Программист забыл обратиться к экземпляру
# Также после названия класса следует ставить скобки
class Person():
name = ""
money = 0
nancy = Person()
nancy.name = "Nance"
nancy.money = 100
### 6 ###
class Person:
name = ""
money = 0
bob = Person()
print (bob.name, "has",money, "dollars.")
# Программист забыл обратиться к экземпляру
# Также после названия класса следует ставить скобки
class Person():
name = ""
money = 0
bob = Person()
print(bob.name, "has",bob.money, "dollars.")
### 7 ###
# Программист не задал имя, поэтому принтуется базовое нулевое значение
class Person():
name = ""
money = 0
bob = Person()
bob.name = "Bob"
print(bob.name, "has",bob.money, "dollars.")
##### OOP_04 #####
### 1 ###
class Cat():
name = ""
color = ""
weight = 0
def meow(self):
print("MEEEOWWW")
Peach = Cat()
Peach.name = "Peach"
Peach.weight = 8
Peach.color = "Orange-White"
Peach.meow()
### 2 ###
class Aadress():
name = ""
country = ""
location = ""
def data(self):
print("Name: ", self.name)
print("Country: ", self.country)
print("Location: ", self.location)
tech = Aadress()
tech.name = "IVKHK"
tech.country = "Estonia"
tech.location = "Tallinna maantee 13"
### 3 ###
class Monster():
name = ""
health = 100
def decreaseHealth(self, amount):
self.health -= amount
if self.health < 0:
print("* Монстр умер *")
nikita = Monster()
##### ПРАКТИЧЕСКАЯ РАБОТА (КЛАСС "ВОИН") #####
import random
class Warrior():
health = 0
def getDamage(self):
self.health -= 20
pers_1 = Warrior()
pers_1.health = 100
pers_2 = Warrior()
pers_2.health = 100
while pers_1.health > 0 and pers_2.health > 0:
choice = random.randint(1,2)
if choice == 1:
pers_2.getDamage()
print("\nВоин 1 ударил воина 2")
print("Здоровье воина 1: ",pers_1.health)
print("Здоровье воина 2: ",pers_2.health)
else:
pers_1.getDamage()
print("\nВоин 2 ударил воина 1")
print("Здоровье воина 1: ",pers_1.health)
print("Здоровье воина 2: ",pers_2.health)
if pers_1.health <= 0:
print("\nПобедил воин 2!")
else :
print("\nПобедил воин 1!") |
eb3e5d63e3c1bdda250294bb23b4232ce47b3cba | chrisjdavie/interview_practice | /leetcode/find_first_and_last_position_of_element_in_sorted_array/binary_search_from_blank.py | 991 | 3.5 | 4 | import pytest
class Solution:
def searchRange(self, nums: list[int], target: int) -> list[int]:
def _search(target: int) -> int:
lo: int = 0
hi: int = len(nums)
while lo < hi:
mid: int = (lo + hi)//2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
lo: int = _search(target)
if nums and nums[lo] == target:
hi: int = _search(target + 1) - 1
return [lo, hi]
return [-1, -1]
@pytest.mark.parametrize(
"nums,target,expected",
(
([], 0, [-1,-1]), # from leetcode
([1, 2, 3], 2, [1, 1]),
([1, 2, 2, 2, 3], 2, [1, 3]),
([5,7,7,8,8,10], 8, [3,4]), # from leetcode
([5,7,7,8,8,10], 6, [-1,-1]) # from leetcode
)
)
def test(nums, target, expected):
assert Solution().searchRange(nums, target) == expected
|
6a6819578120af5da81599f0bba25d7a7723924f | macson777/test_repo | /src/task_8_7.py | 759 | 3.78125 | 4 | # Описать функцию fact2( n ) вещественного типа,
# вычисляющую двойной факториал :n!! = 1·3·5·...·n,
# если n — нечетное; n!! = 2·4·6·...·n, если n — четное
# (n > 0 — параметр целого типа.
# С помощью этой функции найти двойные
# факториалы пяти данных целых чисел [01-11.2-Proc35]
def fact2(n):
fact = 1
if n % 2 == 0:
for i in range(1, n + 1):
if i % 2 != 0:
fact *= i
elif n % 2 != 0:
for i in range(1, n + 1):
if i % 2 == 0:
fact *= i
return fact
print((fact2(8)))
|
bf0445b6d26cfd9fd7281f35a4434851884d5eed | lorjer/PythonTest | /copyfiletest1/test.py | 1,134 | 3.890625 | 4 | '''
#输入输出
#inputnum = int(input('请输入数字 :'))
inputnum = int(65535)
print("input number = ",inputnum,"\ncount 1024*768 = ",1024*768)
print("This is sample for %%, str:%s, number:%d"%("字符测试",1024))
s1 = 72
s2 = 85
print('去年成绩:%d,今年成绩:%d,今年提高的成绩百分比:%0.2f%%'%(s1,s2,(s2-s1)/s1*100))
#End
'''
'''
#20180913
#Test 数据类型
a,b,c = 1000,99.88,True
print(type(a),type(b),type(c))
'''
#20180914
'''
#字符串输出
str = '这是一个字符串测试'
print(str)
print(str[0])
print(str[2:5])
print(str+',这里是新增字符')
#字符串内建函数
str = 'This is a string for test, it was born for test,ended with test,nobody will care its mind'
sub = 'i'
print('i的出现次数是',str.count(sub))
#列表
list1 = ['google','baidu',300590,10086];
list2 = [1,2,3,4,5,6];
list3 = ['a','b','c','d','e']
print('List1[0]:',list1[0])
print('List2[2:4]:',list2[2:4]);
print('List3:',list3)
#元组
basket1 = set('12345abcde')
basket2 = set('1a2b1a2b')
print('Basket1:',basket1);
print('Basket2:',basket2);
print('2 in basket1 ? ','2' in basket1);
'''
|
1780ff33704b9cbe67004707ae21b3f9da660351 | frazynondo/Algorithms-in-Py | /arrays/dictiory_Run.py | 1,941 | 3.703125 | 4 | import math
from collections import defaultdict
def dictionarySearch():
tests = ['abba', 'bacd', 'baa', 'ghst', 'baa', 'bacd', 'bacd']
keys = [12, 14, 15, 16]
# result = dict(zip(tests, keys))
result = {}
for J in tests:
if J in result.keys():
temp = result.get(J) + 1
result.update({J: temp})
else:
result[J] = 1
# result.update({i: 1})
for k, v in result.items():
print("key: {} --> Value: {}".format(k, v))
print("Items : ", result.items())
# val = {}
# for i in temps:
# if temps.count(i) > 1:
# num = temps.count(i)
# print("Key: {} and Value: {}".format(i, num))
# else:
# val[i] = 1
# print(val)
if __name__ == "__main__":
tem = "frazy nondo is the best"
temp = [1,9, 2, 5, 7, 10, 13, 14, 15, 22]
temp.sort()
T = temp
se = set()
se.add(2)
se.add(5)
se.add(6)
se.add(2)
print(se)
# D = {}
# for count, i in enumerate(temp):
# D[count] = i
# D.get()
# for k, v in D.items():
# print("Key {} Value {}".format(k,v))
# t = int(len(temp)/2)
# print(temp[t])
# P = len(temp) - t
# t = P/2
# T = [3]
# simps = (1, "B")
# stack = [temp]
# print("Stach is : " + str(stack[-1]))
# team, people = stack.pop()
# print("team: {} and people: {}".format(team, people))
# print(temp[int(t)])
# P = len(temp) - t
# t = P // 2
# print(temp[int(t)])
# temps = defaultdict(int)
# for i in tem:
# if i != " ":
# temps[i] += 1
# for k, v in temps.items():
# print("{} : {}".format(k, v))
# event = list(map(lambda x: x + str("++-"), list(temps)))
# event = list(map(lambda x: x * 2, list(temp)))
# print(event)
# tem = list(temps)
# val[i - 'a'] += 1
# print(temps.split())
# print(tem)
|
20a30467c418b40cbe0ae42ad60bd26a029aaf69 | steinstadt/AOJ | /ITP1/prob2_a.py | 160 | 3.765625 | 4 | # Small, Large and Equal
a, b = map(int, input().split())
ans = ""
if a>b:
ans = "a > b"
elif a<b:
ans = "a < b"
else:
ans = "a == b"
print(ans)
|
08c578f7443f5fa889f97b8985e42e073b12aab1 | thelmuth/cs101-fall-2020 | /Class40/pixel.py | 2,586 | 4.03125 | 4 | from PIL import Image
def main():
image = Image.open("eliza.jpg")
# image.show()
my_pixel = Pixel((40, 100, 254))
print(my_pixel.r)
print(my_pixel.get_tuple())
print("This should be False:", my_pixel.is_grayscale())
gray_pixel = Pixel((92, 92, 92))
print("This should be True:", gray_pixel.is_grayscale())
print("Making my_pixel grayscale")
my_pixel.make_grayscale()
print(my_pixel.get_tuple())
# detect_grayscale(image)
# image.show()
print(my_pixel)
print(gray_pixel)
class Pixel():
"""Represents a pixel in an image."""
def __init__(self, rgb):
"""This is the _Constructor_ for the class.
This is called when we create a new Pixel object.
Sets the object's initial state by setting attributes."""
self.r = rgb[0]
self.g = rgb[1]
self.b = rgb[2]
def get_tuple(self):
"""Returns tuple representation of this pixel."""
return (self.r, self.g, self.b)
def is_grayscale(self):
"""Return True if this pixel is grayscale, and False otherwise."""
return self.r == self.g and self.g == self.b
def set_rgb(self, r, g, b):
"""Sets the r, g, and b values of this pixel."""
self.r = r
self.g = g
self.b = b
def luminance(self):
"""Find and return the luminance of this pixel"""
return (self.r + self.g + self.b) // 3
def make_grayscale(self):
"""Changes a pixel's components to be grayscale."""
lum = self.luminance()
self.r = lum
self.g = lum
self.b = lum
def __str__(self):
"""Must return a string representation of the object."""
s = "(R: " + str(self.r) + ", G: " + str(self.g)
s += ", B: " + str(self.b) + ")"
return s
def detect_grayscale(image):
"""Detects grayscale pixels in an image, making them bright red.
All other pixels are turned into grayscale to make it easier to see
the red pixels."""
for x in range(image.width):
for y in range(image.height):
pixel = Pixel(image.getpixel((x, y)))
if pixel.is_grayscale():
### Make this pixel bright red
pixel.set_rgb(255, 0, 0)
else:
### Make this pixel into grayscale
pixel.make_grayscale()
image.putpixel((x, y), pixel.get_tuple())
main() |
6ae373f80501a028df3c29ddd38a75a3e8a62eb6 | longmpham/algorithms_for_practice | /Python/algorithms/recursion/is_symmetric.py | 2,048 | 4.34375 | 4 | """
is the tree given symmetric?
ie.
1
2 2 == TRUE
3 4 4 3
"""
class Tree_Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def is_tree_symmetric(root) -> bool:
if root is None: return True
# check if the non-zero root has values
if root is not None:
return helper_function(root.left, root.right)
def helper_function(left, right):
"""
search from the outside and then search within
"""
# if both are null, its true.
# if either or null, its false
if left is None and right is None:
return True
if left is None or right is None:
return False
print('left:', left.value, 'right:', right.value, ' ==>', (left.value==right.value))
# if either has values, we check if the values match!
if left.value == right.value:
check1 = False
check2 = False
# keep checking with pointers point left and pointers pointing right until its exhausted.
if left.left is not None and right.right is not None:
check1 = helper_function(left.left, right.right)
elif left.left is None and right.right is None:
check1 = True
# then check with pointers pointing right and pointers pointing left until its exhausted.
if left.right is not None and right.left is not None:
check2 = helper_function(left.right, right.left)
elif left.right is None and right.left is None:
check2 = True
return check1 and check2
else:
return False
if __name__ == '__main__':
"""
1
2 2
3 4 3 4
"""
root1 = Tree_Node(1)
root1.left = Tree_Node(2)
root1.right = Tree_Node(2)
root1.left.left = Tree_Node(3)
root1.left.right = Tree_Node(4)
root1.right.left = Tree_Node(3)
root1.right.right = Tree_Node(4)
root2 = Tree_Node(1)
root2.left = Tree_Node(2)
root2.right = Tree_Node(2)
root2.left.left = Tree_Node(3)
root2.left.right = Tree_Node(4)
root2.right.left = Tree_Node(4)
root2.right.right = Tree_Node(3)
print(is_tree_symmetric(root1))
print()
print(is_tree_symmetric(root2))
|
115c21a532771a94348ace132efedb66354a1329 | swjtuer326/shiny-enigma | /字典.py | 727 | 4.03125 | 4 | # 字典类型是映射的体现
# {} 或 dict{}创建
# 键值对:键是数据索引的扩展
# 字典是键值对的集合,键值对之间无序
# del d[k]删除字典d中键k对应的数据值
# k in d 判断键k是否在字典中
# d.keys() 返回字典中所有键的信息
# d.values() 返回字典中所有值的信息
# d.items() 返回字典中所有键值对的信息,以列表形式
# d.popitem() 随机取出一个键值对
d = {'中国':'北京', '美国':'华盛顿', '英国':'伦敦'}
print(d.get('中国'))
print(d.popitem())
# 修改时 d["中国"] = 'beijing'
d["中国"] = 'beijing'
print(d)
print(d.items())
items = list(d.items())
for i in range(2):
key, value = items[i]
print(key)
print(value)
|
179fc4ae8b0172d03f722f1c4ac7314a67361930 | zh199609/pythonLearning | /Demo02/迭代器.py | 474 | 4.0625 | 4 | from typing import Iterable, Iterator
list = [1, 2, "fds"]
# 判断是否是迭代对象
# 可用被next()函数调用并不断返回下一个值的对象称为迭代器Iterator
# 生成器都是Iterator对象,但list,dict,str虽然是Iterable 却不是Iterator
# 把list,dict,str等Iterable变成Iterator可以使用iter()函数
print(isinstance(list, Iterable))
a = [564, "a"]
b = iter(a)
print(isinstance(b, Iterator))
print(b.__next__())
print(b.__next__())
|
9e27d52ab6e4cf7ae9dcbaa8f1855f9917082b00 | AdrianaES/Girls-Who-Code-Projects- | /Girls Who Code Work/Python/pseudocode.py | 122 | 3.78125 | 4 | ages = [4,7,3,9,6]
problem = input('ages: (4,7,3,9,6)')
for a in ages:
sum += a
count = len(ages)
print(sum/ count)
|
a26adcf3fbf77f74c2bcc8539464d773749cbd4b | IsaacYAGI/python-ejercicios | /tema6-condicionales/ejercicio9.py | 252 | 3.6875 | 4 | ##Ingresar el sueldo de una persona, si supera los 3000 dolares mostrar un
##mensaje en pantalla indicando que debe abonar impuestos.
sueldo = int(input("Ingrese cual es su sueldo: "))
if sueldo > 3000:
print("Esta persona debe pagar impuestos")
|
787fe3cb06fdb9105d53c47fb0f8a3569ca3e20a | ucsd-cse-spis-2020/spis20-lab02-Sidharth-Theodore | /main.py | 3,031 | 4.125 | 4 | #1: sum of two integers
import pandas as pd
def sumTwo(a,b):
c = a + b
return c
#2: gets a number based on user input
def getNumber():
nums = [] #list of numbers that the user inputs
cont = True #decides wether the loop continues
while cont:
digit = input("Please enter a digit ")#user input of a number
number = int(digit) #turning input into an int
if number >= 0: #only adds to list if positive
nums.append(number)
else: #if not the loop stops
cont = False
finalNum = 0 #the initialization of the digit sum variable
for a in range(len(nums)): #for each number in nums
length = len(nums)-1
powerIndex = length-a #set the power value to the inverse of its index in the list
thisNum = nums[a] #get the value of the number from the list
varNum = thisNum*(10**powerIndex) #set the new number in its unit form as a function of a power of ten
finalNum+=varNum #add this to the final number
return finalNum
#3: getting the sum of digits in a number
def sumDigits(num):
sum = 0
while num != 0:
#adds "ones" digit to sum
sum += num % 10
#chops off previous "ones" digit
num = int(num/10)
return sum
#4: Wage Converter
data = pd.read_csv('wagegap.csv')#reading the wage gap data
wageframe = pd.DataFrame(data[["LOCATION","VALUE"]])#create a dataframe based on the data we need
def convertWageMtoW(mWage, location):
newframe = wageframe.loc[wageframe['LOCATION']==location,"VALUE"] #creating a specific dataframe based on the country input
values = [] #list that holds the values of the wagegap percentages
for row in newframe:
values.append(row)#adding each wagegap value from this country to the list
wageGap = sum(values)/len(values) #finding he average wagegap value
wageGap /= 100 #making that value a percentage
ratio = 1-wageGap #subtracting the percentage from 1 to create a multipliable ratio
wWage = mWage*ratio
return "Womens' wage: " + str(wWage) + " Man's Wage: "+ str(mWage)+ " Country: "+ location
#womens' salary as a ration of the mens salary in the specified country
new = convertWageMtoW(100,"CAN")
print(new)
#5: Word Guessing game
def hangman(word, lives):
lives = lives
answerKey = word
guessKey = []
for i in range(len(word)):
guessKey += "_"
# print("answerKey = " + answerKey)
print(str(guessKey))
while lives > 1:
print("Lives: " + str(lives))
guessChar = input("Guess a character: ")
if guessChar in answerKey:
findIndex = 0
for i in range(len(word)):
guessKey[answerKey.find(guessChar,findIndex)] = guessChar
findIndex = answerKey.find(guessChar,findIndex) + 1
print(str)
else:
lives -= 1
print(guessKey)
if "_" in guessKey:
continue
else:
print("Congratulations, you win!")
break
#a = getNumber()
#print("Number: ",a)
#x = sumDigits(345)
#print("sum: ",x)
#print(convertWageMtoW(100))
hangman("molasses", 8) |
da20cfb6abde8b7c1b6a050a14ef03c1b033ed1e | JasonPlatzer/Capstone1 | /.vscode/class1_program3.py | 679 | 3.8125 | 4 | import re
to_check = True
while to_check:
sentence = str(input("Enter a sentence use only letters "))
# from automate the boring stuff book
# and from # from https://www.guru99.com/python-regular-expressions-complete-tutorial.html
check = re.match(r'[\d\W]', sentence)
if not check:
sentence = sentence.lower()
listWords = []
split = sentence.split(' ')
for word in split:
length = len(word)
x = word[0].upper()
listWords.append(x + word[1:length])
to_check = False
# from https://www.geeksforgeeks.org/python-string-join-method/
print("".join(listWords))
|
decc8528bbc8ddf8709da8044e20a15385d7abbb | whoissahil/python_tutorials | /hangman.py | 846 | 3.75 | 4 | lives = 2
word = "Apple"
wordList = list(word.lower())
# print(wordList)
def checkLives(bool):
global lives
if True:
# return lives
print(lives)
if False:
lives -= 1
# return lives
print(lives)
def check(alp):
global wordList
global lives
if len(wordList) != 0:
if alp in wordList:
print("YES")
# checkLives(True)
wordList.remove(alp) # del
# print(len(wordList))
else:
print("NO")
# print(len(wordList))
# checkLives(False)
lives -= 1
else:
print("You Won")
while True:
try:
alp = input("Please guess an alphabet: ")
check(alp)
if lives == 0:
break
except Exception:
print("Only Alphabet")
|
d75eb70d07c853069afd13917f9c7cda98bea77a | Elaviness/GB_start_python | /lesson5/task_6.py | 1,441 | 3.53125 | 4 | """ Необходимо создать (не программно) текстовый файл,
где каждая строка описывает учебный предмет и наличие
лекционных, практических и лабораторных занятий по этому
предмету и их количество. Важно, чтобы для каждого
предмета не обязательно были все типы занятий.
Сформировать словарь, содержащий название предмета и
общее количество занятий по нему. Вывести словарь на
экран. """
with open("lesson5_6.txt", 'r', encoding='utf-8') as file:
str = file.readlines()
tmp = []
for itm in str:
itm = itm.split(':')
tmp.append(itm)
str = tmp
for elem in str: # получаю подсписок
idx = 0
tmp = ''
for itm in elem: # строка из списка
sum = 0
if idx % 2 == 1:
for char in itm: # симовол из строки
if char.isdigit():
tmp += char
elif char == '(':
tmp += ' '
tmp = tmp.split(' ')
for num in tmp:
if num.isdigit():
sum += int(num)
idx +=1
elem[1] = sum
result = dict(str)
print(result)
|
f90b4747e2d993a404f359dbf8c8362b62a150bb | brentphilion/pythonbasics | /input/input.py | 363 | 3.875 | 4 | """
Explain input and try loops for error handling
todo "try and input checking for next week"
"""
name = input("What is your name?")
print(f"my name is {name}" )
print(f"{api call} {api argument}" )
#print('my name is ', name)
"""
api_call = "fixed_string"
api_argument = (f"fixed part{variable1} more fixed {variable2} nd more formoeeting as needed")
""" |
609baa7c19b7335e8614161f64b15da6f057d212 | SharanyaMarathe/Advance-Python | /busy_days.py | 354 | 3.71875 | 4 | booked=[1,3,9,12,13,18,26,27,28,29]
travel=[4,5,15,16,21,22]
month=list(range(1,31))
free_list=list()
busy=booked+travel
free_list=[item for item in month if item not in busy]
print(free_list)
'''for i in travel:
booked.append(i)
for item in month:
if item not in booked:
free_list.append(item)
print(free_list)'''
|
6799ddbb8c649d148201cab35d8226238f902a9e | JayapraveenS/GeneralProgramming | /mazimum finder.py | 152 | 3.921875 | 4 | a=float(input('enter the first number\n'))
b=float(input('enter the second number\n'))
c=float(input('enter the third number\n'))
print(max(a,b,c))
|
0036488b56de4c10ca84d77734d9a1bc21efd8e4 | orangecig/mit600 | /pset_09_greedy_algo/ps9a.py | 4,885 | 3.703125 | 4 | ###########################
# Problem Set 9: Space Cows
# Name: Jorge Amaya
# Collaborators: none
# Time: 6:00
import pylab
#============================
# Part A: Breeding Alien Cows
#============================
# Problem 1: File I/O
def loadData(filename):
"""
Read the contents of the given file. Assumes the file contents contain
data in the form of comma-separated x,y pairs.
Parameters:
filename - the name of the data file as a string
Returns:
(x, y) - a tuple containing a Pylab array of x values and
a Pylab array of y values
"""
txtFile = open(filename)
#parse file
xList = []
yList = []
for line in txtFile:
each = line.split(',')
x = each[0]
y = each[1].strip('\n')
xList.append(int(x))
yList.append(int(y))
#pylab arrays
xArray = pylab.array(xList)
yArray = pylab.array(yList)
return (xArray,yArray)
# Problem 2a: Curve Fitting: Finding a polynomial fit
def polyFit(x, y, degree):
"""
Find the best fit polynomial curve z of the specified degree for the data
contained in x and y and returns the expected y values for the best fit
polynomial curve for the original set of x values.
Parameters:
x - a Pylab array of x values
y - a Pylab array of y values
degree - the degree of the desired best fit polynomial
Returns:
a Pylab array of coefficients for the polynomial fit function of the
specified degree, corresponding to the input domain x.
"""
return pylab.polyfit(x, y, degree)
# Problem 2b: Curve Fitting: Finding an exponential fit
def expFit(x, y):
"""
Find the best fit exponential curve z for the data contained in x and y.
Parameters:
x - a Pylab array of x values
y - a Pylab array of y values
Returns:
a Pylab array of coefficients for the exponential fit function
corresponding to the input domain x.
"""
y = pylab.log2(y)
return pylab.polyfit(x,y,1)
# Problem 3: Evaluating regression functions
def rSquare(measured, estimated):
"""
Calculate the R-squared error term.
Parameters:
measured - one dimensional array of measured values
estimate - one dimensional array of predicted values
Returns: the R-squared error term
"""
assert len(measured) == len(estimated)
EE = ((estimated - measured)**2).sum()
mMean = measured.sum()/float(len(measured))
MV = ((mMean - measured)**2).sum()
return 1 - EE/MV
#======================
# TESTING CODE
#======================
def main():
# Problem 1
data1 = loadData('ps9a_data1.txt')
data2 = loadData('ps9a_data2.txt')
data3 = loadData('ps9a_data3.txt')
# Checks for Problem 1
assert all( [len(data) == 25 for xy in data] for data in [data1, data2] ), \
"Error loading data from files; number of terms does not match expected"
assert all( [len(data) == 100 for xy in data] for data in [data1, data2] ), \
"Error loading data from files; number of terms does not match expected"
# Problem 4
# TODO: Make calls to other functions here for calculating errors and
# generating plots.
def allPlots():
"""makes 3 calls to createPlots"""
allData = [data1, data2, data3]
prtData = 0
for data in allData:
prtData += 1
createPlots(data, prtData)
def createPlots(data, prtData):
"""
This function saves 4 pylab plots, modeling:
1. Linear
2. Quadratic
3. Quartic
4. Exponential
"""
degree = [1, 2, 4]
iterList = [1,2,3]
x = data[0]
y = data[1]
#use for 3 calls to polyFit()
for i in iterList:
#generate unique figure
figure = i + ((prtData-1) * 4)
#index for degree list
index = i-1
coef = polyFit(x, y, degree[index])
#reset pylab plotter
pylab.figure(figure)
estimate = pylab.polyval(coef, x)
##print rSquare(y, estimate)
#plots
pylab.scatter(x, y)
pylab.plot(x, estimate)
pylab.savefig(str(figure), format=None)
#single call to expFit()
pylab.figure(4 * prtData)
b, a = expFit(x,y)
a = pylab.exp2(a)
#exponential function
estimate = ( a * ( 2 ** (b * x) ) )
##print rSquare(y, estimate)
pylab.scatter(x, y)
pylab.plot(x, estimate)
pylab.savefig(str(4 * prtData), format=None)
allPlots()
if __name__ == "__main__":
main()
|
28c88227844e67616c48eb0bd93481915e3d7b83 | Metalszorny/RecepieShareRestServiceInPython | /RecepieShareRestService.py | 7,049 | 3.703125 | 4 | # https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask
# https://auth0.com/blog/developing-restful-apis-with-python-and-flask/
# https://www.youtube.com/watch?v=7lmCu8wz8ro
from flask import Flask, request
from flask_restful import Api, Resource, reqparse
from sqlalchemy import create_engine
from json import dumps
from flask.ext.jsonpify import jsonify
'''
Initialize a new instance of Flask as the application to be run.
This will run in the main loop of the application.
'''
app = Flask(__name__)
api = Api(app)
# The connection string to the database.
__connectionString = "user='root', password='root', host='localhost', database='MySqlTestDatabase'"
db_connect = create_engine('sqlite:///chinook.db')
users = [
{
"name": "Nicholas",
"age": 42,
"occupation": "Network Engineer"
},
{
"name": "Elvin",
"age": 32,
"occupation": "Doctor"
},
{
"name": "Jass",
"age": 22,
"occupation": "Web Developer"
}
]
# Handles the REST requests of the user data.
class User(Resource):
# Handles the get REST requests of the user data.
def get(self, name):
for user in users:
if (name == user["name"]):
return user, 200
return "User not found", 404
# Handles the post REST requests of the user data.
def post(self, name):
parser = reqparse.RequestParser()
parser.add_argument("age")
parser.add_argument("occupation")
args = parser.parse_args()
for user in users:
if (name == user["name"]):
return "User with name {} already exists".format(name), 400
user = {
"name": name,
"age": args["age"],
"occupation": args["occupation"]
}
users.append(user)
return user, 201
# Handles the put REST requests of the user data.
def put(self, name):
parser = reqparse.RequestParser()
parser.add_argument("age")
parser.add_argument("occupation")
args = parser.parse_args()
for user in users:
if (name == user["name"]):
user["age"] = args["age"]
user["occupation"] = args["occupation"]
return user, 200
user = {
"name": name,
"age": args["age"],
"occupation": args["occupation"]
}
users.append(user)
return user, 201
# Handles the delete REST requests of the user data.
def delete(self, name):
global users
users = [user for user in users if user["name"] != name]
return "{} is deleted.".format(name), 200
# These resources have database operations.
class Employees(Resource):
def get(self):
conn = db_connect.connect() # connect to database
query = conn.execute("select * from employees") # This line performs query and returns json result
return {'employees': [i[0] for i in query.cursor.fetchall()]} # Fetches first column that is Employee ID
class Tracks(Resource):
def get(self):
conn = db_connect.connect()
query = conn.execute("select trackid, name, composer, unitprice from tracks;")
result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}
return jsonify(result)
class Employees_Name(Resource):
def get(self, employee_id):
conn = db_connect.connect()
query = conn.execute("select * from employees where EmployeeId =%d " %int(employee_id))
result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}
return jsonify(result)
# The same can be achieved with annotations.
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = [task for task in tasks if task['id'] == task_id]
if len(task) == 0:
abort(404)
return jsonify({'task': task[0]})
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
@app.route('/todo/api/v1.0/tasks', methods=['POST'])
def create_task():
if not request.json or not 'title' in request.json:
abort(400)
task = {
'id': tasks[-1]['id'] + 1,
'title': request.json['title'],
'description': request.json.get('description', ""),
'done': False
}
tasks.append(task)
return jsonify({'task': task}), 201
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
task = [task for task in tasks if task['id'] == task_id]
if len(task) == 0:
abort(404)
if not request.json:
abort(400)
if 'title' in request.json and type(request.json['title']) != unicode:
abort(400)
if 'description' in request.json and type(request.json['description']) is not unicode:
abort(400)
if 'done' in request.json and type(request.json['done']) is not bool:
abort(400)
task[0]['title'] = request.json.get('title', task[0]['title'])
task[0]['description'] = request.json.get('description', task[0]['description'])
task[0]['done'] = request.json.get('done', task[0]['done'])
return jsonify({'task': task[0]})
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
task = [task for task in tasks if task['id'] == task_id]
if len(task) == 0:
abort(404)
tasks.remove(task[0])
return jsonify({'result': True})
from flask import url_for
#
def make_public_task(task):
new_task = {}
for field in task:
if field == 'id':
new_task['uri'] = url_for('get_task', task_id=task['id'], _external=True)
else:
new_task[field] = task[field]
return new_task
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': [make_public_task(task) for task in tasks]})
from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
@auth.get_password
def get_password(username):
if username == 'miguel':
return 'python'
return None
@auth.error_handler
def unauthorized():
return make_response(jsonify({'error': 'Unauthorized access'}), 401)
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
@auth.login_required
def get_tasks():
return jsonify({'tasks': tasks})
@auth.error_handler
def unauthorized():
return make_response(jsonify({'error': 'Unauthorized access'}), 403)
# Add the user request handler resource to the api's resources. This will handle REST commands for the user node.
api.add_resource(User, "/user/<string:name>")
api.add_resource(Employees, '/employees') # Route_1
api.add_resource(Tracks, '/tracks') # Route_2
api.add_resource(Employees_Name, '/employees/<employee_id>') # Route_3
# The main loop of the application.
if __name__ == '__main__':
# Enable debugging.
app.run(port='5002', debug=True)
|
4a7d94dedb52c6f3cebb30f40eade5a0319c08b4 | phassarun/projecteuler | /examples/3.py | 826 | 3.53125 | 4 | import math
import time
def factor(number):
if number == 1:
return 1
if number == 3:
return 3
if number == 5:
return 5
def is_prime(number):
if number == 1:
return False
if number == 2:
return True
if number > 2 and number % 2 == 0:
return False
max_divisor = math.floor(math.sqrt(number))
for d in range(3, 1 + max_divisor, 2):
if number % d == 0:
return False
return True
if __name__ == "__main__":
t0 = time.time()
value = 600851475143
l = []
for i in range(1, value+1):
if value == 1:
break
if is_prime(i) and value % i == 0:
l.append(i)
value = value / i
print(l)
t1 = time.time()
print(t1-t0) |
228ecc09d29db521e3d735cb3dade220ea381c40 | diegoasanch/Programacion-I-Trabajos-Practicos | /TP8 Tuplas, Conj, Dic/TP8.4 Dominos.py | 1,592 | 4.3125 | 4 | '''
Escribir una función que indique si dos fichas de dominó encajan o no. Las
fichas son recibidas en dos tuplas, por ejemplo: (3, 4) y (5, 4). La función
devuelve True o False. Escribir también un programa para verificar su
comportamiento.
'''
def ingreso_natural(texto='Ingrese un numero natural: ', max=6):
'Ingresa un numero entero valido o None'
while True:
try:
num = int(input(texto))
if num == -1:
raise KeyboardInterrupt
if num not in range(-1, max + 1):
raise ValueError(f'* Caracter invalido, debe ingresar un ' + \
'numero entero positivo menor a {max} o -1 para salir.')
break
except ValueError as error:
print(error)
return num
def encajan(ficha1, ficha2):
'Determina si las fichas de domino encajan entre ellas'
a, b = ficha1
return a in ficha2 or b in ficha2
def ingreso_domino():
'Ingresa una ficha de domino valida'
dom = ()
for i in range(2):
dom += ingreso_natural(texto='Ingrese un valor de domino: ', max=6),
return dom
def __main__():
try:
print('Ingrese la ficha 1')
ficha1 = ingreso_domino()
print('Ingrese la ficha 2')
ficha2 = ingreso_domino()
print(f'Fichas ingresadas: {ficha1} - {ficha2}')
if encajan(ficha1, ficha2):
print('Las piezas encajan.')
else:
print('Las piezas no encajan.')
except KeyboardInterrupt:
print('Abandono el programa')
if __name__ == "__main__":
__main__() |
92f72752ce0a913aca98ed493820bf069075c27c | yu-daniel/Newbie-Projects | /Password Generator.py | 711 | 4.21875 | 4 | # // Password Generator //
import random
import string
generator = input('Do you want to create a password? Enter: Yes or No ')
num = int(input('What length do you want the password? '))
diff = int(input('What difficulty do you want the password? \n[1] Easy\n[2] Moderate\n[3] Strong\n'))
password = ''
if diff == 1:
for char in range(1, num+1):
password += random.choice(string.ascii_lowercase)
elif diff == 2:
for char in range(1, num + 1):
password += random.choice(string.ascii_letters)
elif diff == 3:
for char in range(1, num+1):
password += random.choice(string.printable)
print('Your new password is ' + "' " + str(password) + " '")
|
c44ac74423c1f32129560a6be2ec1dc02e84dd74 | hevalhazalkurt/codewars_python_solutions | /6kyuKatas/Mexican_Wave.py | 338 | 3.53125 | 4 |
def wave(people):
if len(people) == 0:
return []
else:
people = people.lower()
the_waves = []
for e,i in enumerate(people):
if i == " ":
continue
else:
the_waves.append(people[:e] + people[e].upper() + people[e+1:])
return the_waves
|
e72563270d4dfb01e9bece81c3aa1ad838e640b3 | GingerStyle/Lab-3-Capstone | /Part1CamelCase.py | 837 | 4.25 | 4 | #get user sentence
def get_input():
sentence = input('Enter a sentence to convert to camel case. Include spaces, no punctuation')
return sentence
#chop up sentence into words
def split_sentence(sentence):
word_list = sentence.split(' ')
return word_list
#capitalize words except for first word
def process_sentence(word_list):
camelCase_list = (word_list[0] if word_list.index(x) == 0 else x.capitalize() for x in word_list)
return camelCase_list
def main():
# welcome message
print('Welcome User')
#get user sentence
sentence = get_input()
#split the sentence
splitSentence = split_sentence(sentence)
#process into a camel cased term
camelCase_list = process_sentence(splitSentence)
# print out result
for string in camelCase_list:
print(string, end='')
main() |
b94b464c448cc83ba07dd2b24b971975806cbc3f | mihirkelkar/hackerrank_problems | /prune_path_lessk.py | 1,647 | 4 | 4 | class node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class btree:
def __init__(self):
self.root = None
def insert(self, value, root = None):
root = self.root if root is None else root
if root == None:
root = node(value)
self.root = root
else:
if value < root.value:
if root.left != None:
self.insert(value, root.left)
else:
root.left = node(value)
elif value >= root.right:
if root.right != None:
self.insert(value, root.right)
else:
root.right = node(value)
def kpath(self, k, count = 0, root = None):
root = self.root if root is None else root
if root == None:
print "The tree is empty"
else:
#Do a depth first search until you hit a leaf node. Check count at that position.
#return true or false from that node.
#In th parent node, if return is True, go ahead and delete the child
count += root.value
if root.left != None:
ret = self.kpath(k, count, root.left)
if ret == True:
root.left = None
if root.right != None:
ret = self.kpath(k, count, root.right)
if ret == True:
root.right = None
if root.left == None and root.right == None:
if count < k:
return True
else:
return False
return False
def printnode(self, root = None):
root = self.root if root is None else root
print root.value
if root.left != None:
self.printnode(root.left)
if root.right != None:
self.printnode(root.right)
def main():
b = btree()
for i in range(1, 16):
b.printnode()
b.kpath(20)
b.printnode()
if __name__ == "__main__":
main()
|
f56d2e39b931527f01445174a23f51b738d7f24c | jai1/Heroes-of-Newerth-Recommendation-Engine | /honrc/regression/plot.py | 2,364 | 3.5 | 4 | from regression.trainModel import train
import numpy as np
import matplotlib.pyplot as plt
import pylab
import regression.performanceOfTestDataset as performanceOfTestDataset
NUM_OF_HEROES = 249
NUM_OF_FEATURES = NUM_OF_HEROES * 2
CORRECTION = 0.15
NUMBER_OF_POINT_ON_CURVE = 100
def evaluate(model, X, Y, positive_class, negative_class):
correct_predictions = 0.0
for i, legion_win_vector in enumerate(X):
overall_prob = performanceOfTestDataset.score(model, legion_win_vector)
prediction = positive_class if (overall_prob > 0.5) else negative_class
if prediction == Y[i]:
result = 1
else:
result = 0
correct_predictions += result
return correct_predictions / len(X)
# Code from Stackoverflow.com
def plot_learning_curves(num_points, X_train, Y_train, X_test, Y_test, positive_class=1, negative_class=0):
total_num_matches = len(X_train)
training_set_sizes = []
for div in list(reversed(range(1, num_points + 1))):
training_set_sizes.append(total_num_matches / div)
test_errors = []
training_errors = []
for training_set_size in training_set_sizes:
model = train(X_train, Y_train, training_set_size)
test_error = evaluate(model, X_test, Y_test, positive_class, negative_class)
training_error = evaluate(model, X_train, Y_train, positive_class, negative_class)
test_errors.append(test_error + CORRECTION)
training_errors.append(training_error + CORRECTION)
print("****************************************");
print("training_set_size = ", training_set_size);
print("*****************************************");
plt.plot(training_set_sizes, training_errors, 'bs-', label='Training accuracy')
plt.plot(training_set_sizes, test_errors, 'g^-', label='Test accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Number of training samples')
plt.title('Logistic Regression Learning Curve')
plt.legend(loc='lower right')
pylab.show()
def run():
training_data = np.load('train.npz')
X_train = training_data['X']
Y_train = training_data['Y']
testing_data = np.load('test.npz')
X_test = testing_data['X']
Y_test = testing_data['Y']
plot_learning_curves(NUMBER_OF_POINT_ON_CURVE, X_train, Y_train, X_test, Y_test)
if __name__ == '__main__':
run()
|
0d5e07a2d91fbe23aff12b123902a5fa3d8f1d0e | Bhargavpraveen/Basic-programs | /prime or not.py | 237 | 4.03125 | 4 | def prime_checker():
n=int(input('Enter the Number to check: '))
if n==1:
return 'Not a Prime'
return 'Not a Prime Number' if any([n%i==0 for i in range(2,n)])==True else 'Prime Number'
print(prime_checker())
|
93e215f41b1a31abf23354a1fbf5930d5fb76a81 | JulieSchneiderman/hash-function-comparison | /Assignment3.py | 3,656 | 3.921875 | 4 | import math
#Assignment 3
#Julie Schneiderman - 10201092
#I confirm that this submission is my own work and is consistent with the Queen's regulations on Academic Integrity.
#takes in .txt file and list of prime numbers
#creates list of varying size initialized to None
#loops through .txt file to find table sizes that result in collisions
#outputs table sizes that fail the 'cannot look at more than 10 locations' requirement
def func1(codenames, m):
for num in m:
#print("num-------------",num)
A = [None] * num #create empty list of size num - all values initialized to 'None' [None, None.....num-1]
codenames = open("codenames", "r")
#print(codenames) #test
#print(len(A)) #test
max_collisions = 0
#print("num = ",num)
#print("len(A) = ",len(A))
for word in codenames.readlines():
#print(word) #test
collisions = quadratic_probing_insert(A,word) #switch to quadratic_probing_insert(A,word) to do that experiment
if collisions > max_collisions:
max_collisions = collisions
if max_collisions > 10:
print("fails for table size equal to: ", num, " -- num collisions: ", max_collisions)
else:
print("success for table size equal to: ",num," -- num collisions: ", max_collisions )
#Algorithm from Dawes notes on March 6th
#input codename
#S[:-1] because last value of each word is \n which would increase the value of a by 10 (ord("\n") = 10)
#output int value for that codename
def codenames_to_int(s):
a = 0
for x in s[:-1]:
a += ord(x)*(ord(x))
#print(a)
#print('a=', a)
return (a) #key value
#------Quadratic Probing -----------#
#take in the 'None' list of size num and a word to be converted into an integer and then hashed
#returns the number of collisions that occured while attempting to insert a code word
def quadratic_probing_insert(T, w):
#constants - (trial 1 = 1,2), (trial 2 = 1,2), (trial 3 = 2,1)
c1 = 2
c2 = 1
i = 0
key = codenames_to_int(w) #sends to code name to integer converted, that value becomes the key value
v = h(key,len(T)) #value returned as 'sum' => type int
a = v
while ((i<len(T)) and (T[a] != None)): #T[a] is already assignned - collision occured, increment i
i+=1
a = (v + c1*i + (c2*(i*i))) % len(T)
if(T[a] == None):
T[a] = w
#print("inserted ",w)
#print(w)
#print(i)
return i
#hash function for quadratic probing - mulitplication method
def h(k,num):
V = (math.sqrt(5)-1)/2
whole = math.floor(V*k)
x = V*k - whole #gives fractional part of number
#print("hash func val: ", math.floor(num*x))
return math.floor(num*x)
#----------Double Hashing-------------#
#h(k,i) = (h'(k) + i*h"(k)) mod m
def double_hashing_insert(T, w):
i = 0
key = codenames_to_int(w)
v = h(key,len(T))
v2 = h2(key)
a = v
while ((i<len(T)) and (T[a] != None)): #T[a] is already assignned - collision occured, increment i
i+=1
#a = math.floor((v + (i*v) + (i*v2)) % len(T)) #trial 1
a = math.floor((v + (i*v2) + (i*v)) % len(T)) #trial 2
#a = math.floor((v + (i*v) + (i*v)) % len(T)) #trial 3
if(T[a] == None):
T[a] = w
return i
#h''(k) function
#mid square method -- Dawes' notes March 6th
def h2(k):
s = k*k
x = s / 1000
a = x % 1000
return a
#reads in codenames text file, sends call to func1
def main():
m = list(range(3700,6000))
codenames = open("codenames", "r")
func1(codenames, m)
main()
|
c8fb06df704aa9fa7922625ae0f9b703aca3a4dd | void523/Assignment_inapp_training | /Assignment_1.py | 2,113 | 4.34375 | 4 | # Assignment Question
# Make a two-player Rock-Paper-Scissors game. One of the players is the computer.
#
# 10 rounds. Print out the winner and points earned by both players at the end of the game.
#
# Remember the rules:
#
# Rock beats Scissors
# Scissors beats Paper
# Paper beats Rock
#
#
# Use a dictionary to store the history of choices made by the Player and the Computer.
#
#
# You should be able to print the choices made by the Player and the Computer in each round once the game is completed.
#
#
# Example -
#
#
#
# Enter the round for which you need the information >> 3
#
#
# Output
#
#
# Player choice = Rock
#
# Computer choice = Paper
#
# Player won Round 3
#
#
# * Please make sure that you use the appropriate control, data structures to ensure that the space, time complexity and number of lines of code are kept to a minimum.
import random
p1 = 0
p2 = 0
for i in range(1,11):
Human = input("Enter your choice Human (rock, paper, scissors): ")
possible_actions = ["rock", "paper", "scissors"]
Computer = random.choice(possible_actions)
game_dict = {"round": [], "choices": {'Human': [], 'Computer': []}}
if Human == Computer:
print("it's a tie!")
elif Human == "rock" and Computer == "paper":
p2 = p2 + 1
elif Human == "rock" and Computer == "scissors":
p1 = p1 + 1
elif Human == "paper" and Computer == "rock":
p1 = p1 + 1
elif Human == "paper" and Computer == "scissors":
p2 = p2 + 1
elif Human == "scissors" and Computer == "paper":
p1 = p1 + 1
elif Human == "scissors" and Computer == " rock":
p2 = p2 + 1
game_dict["round"].append(i)
game_dict["choices"]["Human"].append(Human)
game_dict["choices"]["Computer"].append(Computer)
print(game_dict)
print("\n")
if p1 == p2:
print("It's a Tie!\n")
elif p1>p2:
print('Human is the WINNER!!\n')
else:
print('Computer is the WINNER!!\n')
print('\tPOINT TABLE\n')
print('{0:8} | {1:9}'.format('Players', 'Points'))
print('{0:8} | {1:5}'.format('Human', p1))
print('{0:8} | {1:5}'.format('Computer', p2))
|
d7abed4df9177f49402979e764c1bc07dabef6d1 | BryanMorfe/ptdb | /tests/login.py | 1,089 | 3.84375 | 4 | from ptdb import parse
def login(email, password):
# Returns true or false whether is logged successfully
# parse the database
my_db = parse('database')
# Check if email is in database
if my_db.isItemInColumn('email', email.lower()):
# If email is in the database, check the password for that entered email.
db_password = my_db.getColumnItem('password', my_db.getRowIndex('email', email.lower()))
# This above statement is saying; 'Get the password of the row where the column email is 'email.lower()'
# Now we compare the entered password with the one corresponding to that email, if they're equal, the login is successfully, # else, it's not
if password == db_password:
return True
else:
return False
else:
# If email is not in database then return false.
return False
# Now we test the function login.
if login('bryanmorfe@gmail.com', 'password1'):
print("User logged successfully.")
else:
print("Credentials are incorrect.")
# Prints 'User logged successfully'
|
1ff9c7bebd1ffd9b82dcc11b7530858a5452af38 | flerdacodeu/CodeU-2018-Group7 | /aliskin/assignment1/anagram.py | 1,451 | 4.21875 | 4 | from collections import defaultdict
from collections import Counter
import string
def is_anagram(s, t, case_sensitive=True):
"""
Given two strings s and t returns True if t is anagram of s and False otherwise.
"""
if len(s) != len(t):
return False
if (not case_sensitive):
s = s.casefold()
t = t.casefold()
counter_s = Counter(s)
counter_t = Counter(t)
return counter_s == counter_t
def main():
"""
Some simple examples to test the function is_anagram
"""
test_examples = [('', '', True),
('a', 'A', False),
('a', 'aa', False),
('apple', 'lappe', True),
(string.ascii_lowercase, string.ascii_lowercase, True),
(string.ascii_lowercase, string.ascii_uppercase, False)]
for s, t, answer in test_examples:
assert (is_anagram(s, t) == answer), 'Incorrect answer for {} and {}, should be {}'.format(s, t, answer)
"""
Check case insensitive
"""
test_examples = [('', '', True),
('a', 'A', True),
('ABC', 'Cabbba', False),
(string.ascii_lowercase, string.ascii_lowercase, True),
(string.ascii_lowercase, string.ascii_uppercase, True)]
for s, t, answer in test_examples:
assert (is_anagram(s, t, case_sensitive=False) == answer), 'Incorrect answer for {} and {}, should be {}'.format(s, t, answer)
if __name__ == '__main__':
main()
|
b23508dbff2591092fff2940e0333fc0237858a1 | sourav-coder/100-Days-of-Code- | /assignment week 1 & 2/Tuple/3.py | 49 | 3.578125 | 4 | '3'
t=(1,2,3)
s=''
for i in t:s+=str(i)
print(s)
|
e13e99f378afb0d350159270d676f524c8fa54a6 | jiinmoon/Algorithms_Review | /Archives/Leet_Code/Old-Attempts/0010_Regular_Expression_Matching.py | 1,684 | 3.84375 | 4 | """ 10. Regular Expression Matching
Question:
Given an input string and a pattern, implement regular expression matching
with support for '.' and '*'.
+++
Solution:
DP would be a preferable approach to this problem - we can define DP[i][j]
as a match between string and pattern upto i (from string) and j (from
pattern) indicies.
Then, as we read on the string and pattern, we encounter two major cases:
1) s[i] == p[j] or p[j] == '.':
This is a matching case - for pattern, '.' matches any single char, thus it
would also fall under matching case as well. Then, DP[i][j] depends on
whether previous iteration has been a match: DP[i-1][j-1].
2) p[j] == '*':
If the current pattern is wildcard '*', then it would match zero or more of
the preceding element - meaning that we will have to look behind further.
First, we can check whether zero occurrence of the preceding element is the
true - it is done by examining DP[i][j-2]. Or, we could also check for one
or more matches of preceding element which is from DP[i-1][j]. Otherwise, it
would be False.
"""
class Solution:
def isMatch(self, text, pattern):
m, n = len(text), len(pattern)
dp = [[False] * (n+1) for _ in range(m+1)]
dp[-1][-1] = True
for i in range(m, -1, -1):
for j in range(n-1, -1, -1):
first_match = i < m and pattern[j] in {text[i], '.'}
if j + 1 < n and pattern[j+1] == '*':
dp[i][j] = dp[i][j+2] or first_match and dp[i+1][j]
else:
dp[i][j] = first_match and dp[i+1][j+1]
return dp[0][0]
|
5a2540d3760ec9194279bd51a9c74625fc890f95 | HarshvardhanKhajuria/datagiri_dec1 | /dtree.py | 7,355 | 3.546875 | 4 | # Step 1 - Import required libraries
from __future__ import division # for python 2 only
import pandas as pd
import numpy as np
from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from itertools import product
from datetime import datetime
# Step 2 - Load the data
data_df = pd.read_csv('loan_application.csv')
sample_df = pd.read_csv('manual_calculation.csv')
# Step 3 - Perform preprocessing steps
def relevant_data(data_df):
"""
Returns only the required columns from the data set
:param data_df: raw pandas data frame
:return: pandas data frame with relevant columns
"""
data_df = data_df.drop('Application_ID', axis=1)
return data_df
def cat2int(data_df):
"""
Converts categorical values in to discret numeric values
:param data_df: raw data frame
:return: data frame with categorical converted to numerics
"""
data_df['Dependents'] = data_df['Dependents'].map(
lambda x: 4 if x == '3+' else int(x))
data_df['Gender'] = data_df['Gender'].map(lambda x: 0 if x == 'No' else 1)
data_df['Education'] = data_df['Education'].map(
lambda x: 0 if x == 'Not Graduate' else 1)
data_df['Married'] = data_df['Married'].map(
lambda x: 0 if x == 'No' else 1)
data_df['Property_Area'] = data_df['Property_Area'].map(
lambda x: 0 if x == 'Urban' else 1 if x == 'Semiurban' else 2)
data_df['Income'] = data_df['Income'].map(
lambda x: 0 if x == 'low' else 1 if x == 'medium' else 2)
data_df['Self_Employed'] = data_df['Self_Employed'].map(
lambda x: 0 if x == 'No' else 1)
return data_df
def get_x_y(data_df):
"""
Returns X and y i.e. predictors and target variale from data set
:param data_df: raw data frame
:return: 2 pandas data frames
"""
X = data_df.drop('Application_Status', axis=1)
y = data_df.loc[:, 'Application_Status']
return X, y
# Step 4 - Perform manual Gini calculation
def get_probablities(data_df, variable):
"""
Provides probablities for Y and N outcomes for a given variable
:param
variable: Column name / Predictors
data_df: raw pandas dataframe
:return: pandas dataframe with count, probabilities, squared probabilities
and probabilities multiplied by its log
"""
# Count of every Y and N for variable's different values
count = pd.DataFrame(data_df.groupby([variable, 'Application_Status'])[
'Application_Status'].count())
count.columns = ['count']
# Count of every Y and N for the whole subset
target_count = pd.DataFrame(data_df.groupby(variable)[
'Application_Status'].count())
target_count.columns = ['target_count']
target_count['target_weight'] = target_count['target_count'].map(
lambda x: x / target_count['target_count'].sum())
count = count.merge(target_count, left_index=True, right_index=True,
how='left')
# Probability of every Y and N for variable's different values
prob = pd.DataFrame(data_df.groupby([variable, 'Application_Status'])[
'Application_Status'].count()).groupby(level=0).\
apply(lambda x: x / float(x.sum())).round(3)
prob.columns = ['prob']
# Merging these 2 dataframes
result_df = count.merge(prob, left_index=True, right_index=True)
result_df['sqrd_prob'] = result_df['prob'].map(lambda x: x**2)
result_df['log_prob'] = result_df['prob'].map(lambda x: x*np.log2(x))
# Calculate Gini Index for individual variable's outcomes
gini_resp = pd.DataFrame(result_df.groupby(level=0).
apply(lambda x: 1 - float(x.sqrd_prob.sum())))
gini_resp.columns = ['gini_respective']
result_df = result_df.merge(gini_resp, left_index=True, right_index=True,
how='left')
# Calculate Entropy for individual variable's outcomes
entropy_resp = pd.DataFrame(result_df.groupby(level=0).
apply(lambda x: -1*float(x.log_prob.sum())))
entropy_resp.columns = ['entropy_resp']
result_df = result_df.merge(entropy_resp, left_index=True,
right_index=True, how='left')
return result_df.round(3)
def get_gini_index(data_df):
"""
Provides Gini Index for every variable except for unique App ID and target
:param data_df: your test / train dataset
:return: pandas dataframe with gini score for each variable
"""
# Initiate a list to save the results
gini_ls = []
# Iterate over every columns and get its probabilities
for col in ['Gender', 'Married', 'Dependents', 'Education',
'Self_Employed', 'Credit_History', 'Property_Area', 'Income']:
data = get_probablities(data_df, col)
# Retaining only required columns
data = data[['target_weight', 'gini_respective']].drop_duplicates()
# Calculate Gini for the variable and append results to list
gini = pd.DataFrame(data['target_weight']*data['gini_respective']). \
sum()[0]
gini_ls.append((col, gini))
res_df = pd.DataFrame(gini_ls, columns=['Variable', 'Gini']).round(2)
return res_df.sort_values('Gini')
# Step 5 - Decision Trees using Scikit-Learn
def run_dtree(data_df, method='gini', max_depth=None, min_samples_leaf=1):
"""
Provides predictions made by decision tree and prints the accuracy score
on test dataset
:param method: criterion for split. Options:
gini
entropy
:return: numpay array of predictions
"""
X, y = get_x_y(data_df)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=7)
clf = tree.DecisionTreeClassifier(criterion=method, max_depth=max_depth,
min_samples_leaf=min_samples_leaf)
clf = clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print('Your accuracy is {}'.format(accuracy_score(y_test, y_pred)))
return round((accuracy_score(y_test, y_pred)), 2)
if __name__ == "__main__":
app_df = relevant_data(data_df)
app_df = cat2int(app_df)
print(test)
'''
method_ls = ['gini', 'entropy']
max_depth_ls = [None, 3, 4]
min_sample_ls = [1, 10, 20]
params_ls = []
for i in product(method_ls, max_depth_ls, min_sample_ls):
params_ls.append(list(i))
res_ls = []
run = 1
for params in params_ls:
run = run
method = params[0]
max_depth = params[1]
min_sample = params[2]
print('Running experiment # {} using {} as splitting criterion and ' \
'with max depth of {} & min sample leaf of {}'.format(run,
method, max_depth, min_sample))
accuracy = run_dtree(app_df, method=method, max_depth=max_depth,
min_samples_leaf=min_sample)
res_ls.append((run, method, max_depth, min_sample, accuracy))
run +=1
fin_df = pd.DataFrame(res_ls, columns=['Run No.', 'Mehtod', 'Max Depth',
'Min Samples Leaf', 'Accuracy'])
print(fin_df.head())''' |
e7be8e5ca688aadd05c46ca2f3ab041bb44aaceb | avidLearnerInProgress/cf-octo-journey | /old_attempts/339a.py | 296 | 3.515625 | 4 | def helpful_maths(myStr):
if len(myStr) <= 1:
print(myStr)
return
summans = list(myStr.split('+'))
#print(summans)
summans_s = sorted(summans)
res = summans_s[0] + '+'
print(str(res) + '+'.join(summans_s[1:]))
value = str(input())
helpful_maths(value) |
4e6d0a55ac69cdc476acfac419386f53dcf30916 | LuqiPan/Life-is-a-Struggle | /10_Sorting_and_Searching/2_group_anagrams/group_anagrams.py | 348 | 3.859375 | 4 | from collections import defaultdict
def group_anagrams(word_list):
dict = defaultdict(list)
for word in word_list:
sorted_word = ''.join(sorted(word))
dict[sorted_word].append(word)
result = []
for k, v in dict.iteritems():
result += v
return result
print group_anagrams(['abc', 'ab', 'acb', 'cba'])
|
7748c3c48e2b5d54b895f5e78d68faa598ddbba5 | jayhebe/Python_100ex | /ex012.py | 460 | 4.09375 | 4 | # **题目:**判断101-200之间有多少个素数,并输出所有素数。
def is_prime(number):
if number < 2:
return False
else:
for i in range(3, number):
if number % i == 0:
return False
return True
def print_prime_numbers(start, end):
for j in range(start, end + 1):
if is_prime(j):
print(j, end=" ")
if __name__ == '__main__':
print_prime_numbers(1, 100)
|
0602294c19c580cbb5eda9bccb22394acfc48e3d | academia-szycho/clases | /ejercicio_7_3_b.py | 594 | 3.9375 | 4 | '''
Ejercicio 7.3. Campaña electoral
b) Escribir una función que reciba una tupla con nombres, una posición de origen p y una
cantidad n, e imprima el mensaje anterior (Estimado <nombre>, vote por mí.)
para los n nombres que se encuentran a partir de la posición p.
'''
def ejercicio_siete(nombres, origen_p, n):
'''
'''
assert origen_p + n < len(nombres), "No hay tantos nombres para mostrar"
for i in range(origen_p, origen_p + n):
print(f"Estimado {nombres[i]}, vote por mí.")
nombres = ("Plofi", "Gabo", "Maty", "Oscar")
ejercicio_siete(nombres, 2, 3) |
ea8ee5f204b2c97d86303bc3ee05f1174de9d391 | owensheehan/ProgrammingFundamentals | /lab05_average.py | 401 | 3.5 | 4 | #Script: lab05_sandwiches.py
#Author: Owen Sheehan
#DEscription: Calculate Sandwich reduction
reduction=(float(input('Enter the percentage of the reduction:'))/100)
original_price=float(input('Enter the original price of the sandwich:'))
new_price=(original_price*(1-reduction))
print('Sandwiches reduced today by',reduction*100,'%',' from €',format(original_price,'.2f'),'to €',format(new_price,'.2f')) |
f3bef27bf12f9304bafd9034308adf228e0dc279 | kontur-courses/clean-code | /python/ControlDigit/Solved/Upc/control_digit.py | 566 | 3.921875 | 4 | # Общий код, который можно реиспользовать
from itertools import cycle
from typing import Iterable, Iterator, List
def get_digits_from_least_significant(number: int) -> List[int]:
digits = []
while number > 0:
digit = number % 10
digits.append(digit)
number = number // 10
return digits
def sum_with_weights(digits: Iterable, weights: Iterable) -> int:
return sum([digit * weight for digit, weight in zip(digits, weights)])
def repeat(items: List) -> Iterator:
return cycle(items)
|
2849f17f0a676703f32dedbcd903ae0a0a7a2968 | christian-hall/python-MAX | /ch03/ch04/main.py | 414 | 4.0625 | 4 | # Chapter 4, Control Statements
# python doesn't have a switch statement
# simple for loop, range is exclusive, the extra number is an incrementer so you don't have
# to just do 1. You cannot count by non-integers
# count to 10
for i in range(1, 11):
print('i: ', i)
# count 0 to 30 by 3's
for i in range(0, 31, 3):
print('i: ', i)
# count 0 to 5 by 0.05
for f in range(.3, .5, .05):
print('f:', f) |
30774078f4ac5dac7de0d5e7d3503fd04e201d84 | accolombini/python_completo | /lab12_entendendo_ranges.py | 1,514 | 4.5 | 4 | """
Prisamos conhecer o loop for para usar os ranges.
Precisamos conhecer o range para trabalhar melhor com o loop for.
Ranges são utilizados para gerar sequências numéricas, não de forma aleatória,mas sim de maneira específica.
Formas gerais:
</> Forma 1 -> range(valor_de_parada) => valor_de_parada não inclusive (início padrão 0, e passo de 1 em 1)
</> Forma 2 -> range(valor_de_inicio, valor_de_parada) => especifica um início diferente de 0, mantém o passo de
1 em 1 e valor_de_parada é não inclusive
</> Forma 3 -> range(valor_de_inicio, valor_de_parada, passo) => especifica um início diferente de 0,
especifica um passo diferente do default, ou melhor diferente de 1 em 1, valor_de_parada é não inclusive
</> Forma 4 -> range(valor_de_inicio, valor_de_parada, -passo) => especifica um início diferente de 0,
especifica um passo diferente do default, ou melhor diferente de 1 em 1, valor_de_parada é não inclusive. Usado para
fazer a inversão => range -> inverso
"""
# Forma 1
for num in range(11):
print(f'Valor {num} ', end=' ')
print('\n') # Apenas para saltar para a linha seguinte
# Forma 2
for num in range(5, 11):
print(f'Valor {num} ', end=' ')
print('\n') # Apenas para saltar para a linha seguinte
# Forma 3
for num in range(2, 11, 2):
print(f'Valor {num} ', end=' ')
print('\n') # Apenas para saltar para a linha seguinte
# Forma 4
for num in range(10, 3, -1):
print(f'Valor {num} ', end=' ')
print('\n') # Apenas para saltar para a linha seguinte
|
ae1102d63ef37613b7688ae0e57edc75f2e4c68c | jlyang1990/LeetCode | /394. Decode String.py | 834 | 3.546875 | 4 | class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
return self.decodeStringHelper(s, 0)[0]
def decodeStringHelper(self, s, i):
result = ""
while i < len(s) and s[i] != "]":
if not s[i].isdigit(): # s[i] is character
result += s[i]
i += 1
else:
n = 0
while s[i].isdigit():
n = n*10 + int(s[i])
i += 1
i += 1 # surpass inner "["
temp_result, temp_i = self.decodeStringHelper(s, i)
for j in range(n):
result += temp_result
i = temp_i+1 # surpass inner "]"
return result, i # i: index of (outer) "]" |
d06fd917abcbbd835782ddaea50acfb3c89fe9da | iafjayoza/Python | /Sorting_Algorithms/Bubble_Sort/bubble_sort_dynamic.py | 502 | 3.84375 | 4 | def bubble_sort_dynamic(collection):
l = len(collection)
for k in range(l-1):
flag = 0
for i in range(l-k-1):
if collection[i] > collection[i + 1]:
(collection[i], collection[i + 1]) = (collection[i + 1], collection[i])
flag += 1
if flag == 0:
break
m = [2,6,5,3,4,1]
bubble_sort_dynamic(m)
print(m)
j = list(range(500,0,-2))
bubble_sort_dynamic(j)
print(j)
n = list(range(500))
bubble_sort_dynamic(n)
print(n) |
c0e1488a286c62d3c80e7745b574daa6901e133a | Sukhrobjon/Hackerrank-Challanges | /ProblemSolving/Algorithm/pangram.py | 309 | 3.9375 | 4 | def pangrams(s):
# lowercase the string
# create a 26 letter
is_pangram = [0] * 26
s = s.replace(" ", "").lower()
for char in s:
index = ord(char) - 97
is_pangram[index] += 1
for i in is_pangram:
if i == 0:
return "not pangram"
return "pangram"
|
85e4f902c5d92fd259126f0af379b46b575afac3 | sarthak268/amubulance-routing-with-dynamic-traffic | /shortest_path.py | 900 | 3.6875 | 4 | from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
self.parent_node = [-1] * self.V
def addEdge(self, u, v, w):
self.graph.append([u, v, w])
def printArr(self, dist):
print("Vertex Distance from Source")
for i in range(self.V):
print("% d \t\t % d" % (i, dist[i]))
def BellmanFord(self, src):
dist = [float("Inf")] * self.V
dist[(int)(src)] = 0
self.parent_node[(int)(src)] = (int)(src)
for i in range(self.V - 1):
for u, v, w in self.graph:
if dist[u] != float("Inf") and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
self.parent_node[v] = u
return dist, self.parent_node |
25ea470e71fb7013eb8647385301ebb99affc057 | meghanaraokm/Python | /OOPsDemo/BubbleSort.py | 263 | 3.859375 | 4 |
def sort(nums):
for i in range(len(nums)-1, 0, -1):
for j in range(i):
if nums[j]>nums[j+1]:
temp=nums[j]
nums[j]=nums[j+1]
nums[j+1]=temp
nums = [3,5,6,9,-2,4]
sort(nums)
print(nums) |
ae10e2f1b5d8327d8c6d4126d7eaa505575ed6f4 | russellgao/algorithm | /dailyQuestion/2020/2020-07/07-24/python/solution_heap.py | 741 | 3.609375 | 4 | import heapq
class Ugly:
def __init__(self) :
# seen 用于记录有没有遍历过,也可以用heap 代替,但是效率低很多
seen = {1,}
self.nums = []
heap = [1]
for _ in range(1690) :
current_num = heapq.heappop(heap)
self.nums.append(current_num)
for i in [2,3,5] :
heap_num = current_num * i
if heap_num not in seen :
seen.add(heap_num)
heapq.heappush(heap,heap_num)
class Solution:
def nthUglyNumber(self, n: int) -> int:
u = Ugly()
return u.nums[n-1]
if __name__ == "__main__" :
s = Solution()
result = s.nthUglyNumber(10)
print(result)
|
adb2c739e36b615c8d5247078a8a46a0ea2f3e93 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2573/60761/247344.py | 217 | 3.90625 | 4 | def nthTerm(n):
if(n==1 or n==2):
return 2
elif(n%2==1):
return nthTerm(n-2)**2
else:
return nthTerm(n-2)**3
n=int(input())
for i in range(n):
print(nthTerm(int(input())))
|
2ffee98c3bb7b1c385e5aa58ab42f502b91a59ed | roshansinghbisht/hello-python | /day-13-python-comparison-operators.py | 1,015 | 4.09375 | 4 | # Try comparison operators in this quiz! This code calculates the
# population densities of Rio de Janeiro and San Francisco.
sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5
san_francisco_pop_density = sf_population/sf_area
rio_de_janeiro_pop_density = rio_population/rio_area
# Write code that prints True if San Francisco is denser than Rio,
# and False otherwise
print(san_francisco_pop_density > rio_de_janeiro_pop_density)
# The bool data type holds one of the values True or False, which are
# often encoded as 1 or 0, respectively.
# There are 6 comparison operators that are common to see in order to
# obtain a bool value:
# < : Less Than
# > : Greater Than
# <= : Less Than or Equal To
# >= : Greater Than or Equal To
# == : Equal to
# != : Not Equal to
# And there are 3 logical operators you need to be familiar with:
# and - Evaluates if all provided statements are True
# or - Evaluates if at least one of many statements is True
# not - Flips the Bool Value
|
0953dfface12205b6540770a015af449c4b6ac1b | BJV-git/leetcode | /math/ugly_number.py | 464 | 4.15625 | 4 | # logic: rule is that, we need to find that, if its only factors are 2 and 3 so just divide by 2,3 and 5 so that if reminder is zero
def isUgly(num):
if num == 0:
return False
while num % 5 == 0:
num = num // 5
# print(num)
while num % 3 == 0:
num = num // 3
# print(num)
while num % 2 == 0:
num = num // 2
# print(num)
if num == 1:
return True
else:
return False
|
5359f980e85716b584de8297c86e09af44afb7e0 | tusharacc/englishdictionary | /getwords.py | 1,655 | 3.765625 | 4 | ###The program is just to solve ne word puzzle that I got on whatsapp
import sqlite3
class ConnectToSqlite:
conn = None
cur = None
success_count = 0
error_count = 0
def __init__(self, db):
try:
self.conn = sqlite3.connect(db)
self.cur = self.conn.cursor()
except Exception as exc:
print('There was a problem: %s' % (exc))
exit(1)
def executeSelect(self,word):
try:
#print (word)
self.cur.execute("select * from dictionary where word like (?)", (word,))
return self.cur
except Exception as exc:
print('There was a problem: %s' % (exc))
self.error_count += 1
def executeQuery(self,word,word_type,definition):
#print ("The words are %s %s %s" %(word,word_type,definition))
try:
self.cur.execute("insert into dictionary (word,wordtype,definition) values (?, ?,?)", (word, word_type,definition))
self.conn.commit()
self.success_count += 1
except Exception as exc:
print('There was a problem: %s' % (exc))
self.error_count += 1
def __del__(self):
self.conn.close()
db = ConnectToSqlite('/Users/tusharsaurabh/entries.db')
word_list = ['_lb__t','G_r_','_nkn_wn','Sp__r','C_t_l_g__','_r__','_rg_n_z_t__n','_c_n_my','L_g_t_m_t_','M_b_l_']
temp_word = ""
for item in word_list:
cursor = db.executeSelect(item)
#print (type(cursor))
for row in cursor:
if (row[1] != temp_word):
print (" The word with %s is %s"%(item,row[1]))
temp_word = row[1]
del db |
f975ae3bb9d2d1fe80e16f08a610fb68de20e596 | abrodin/cours_Python | /working_with_class/examples3.py | 687 | 3.875 | 4 | class Vector2D:
def __init__(self, x=0, y=0):
self._x = x
self._y = y
def __add__(self, other):
"""
:param other:
:return: Сложение векторов
"""
return Vector2D(self._x + other._x, self._y + other._y)
def __mul__(self, other):
"""
:param other:
:return: Скалярное умножение векторов
"""
return self._x*other._x, self._y*other._y
def __str__(self):
return '(%d, %d)' %(self._x, self._y)
a = Vector2D(2, 2)
b = Vector2D(-1, 2)
c = a + b
d = a*b
print(a, '+', b, '=', c)
print(a, '*', b, '=', d) |
f875a07fc042e0c5d8b9cf85dfa7379add08a213 | carolchen89/TeamSabre | /csv_to_dicts.py | 3,263 | 3.609375 | 4 | import pandas
#DEFINE GLOBAL NAMES HERE
CREWDATA_CSV = 'CrewData.csv'
crew_df = pandas.read_csv(CREWDATA_CSV)
def get_base_dic():
# return a base dictionary
# example :
# bases = {
# 'b1' : {'900488', '900421'},
# 'b2' : {'900201', '900424'}
b1_ids = crew_df[crew_df.Current_Base == 1]['Crew_ID']
b2_ids = crew_df[crew_df.Current_Base == 2]['Crew_ID']
print "number of pilots in base 1 is " + str(len(b1_ids))
print "number of pilots in base 2 is " + str(len(b2_ids))
base_dict = {
"B1" : set(b1_ids),
"B2" : set(b2_ids),
}
return base_dict
def get_rank_dic():
# return a rank dictionary
# example :
# ranks = {
# 'cpt' : {'900201','900488', '900421'},
# 'fo' : {'900424'}
# }
cpt_ids = crew_df[crew_df.Rank == "CPT"]['Crew_ID']
fo_ids = crew_df[crew_df.Rank == "FO"]['Crew_ID']
print "number of first captains is " + str(len(cpt_ids))
print "number of first officers is " + str(len(fo_ids))
rank_dic = {
"CPT" : set(cpt_ids),
"FO" : set(fo_ids)
}
return rank_dic
def get_fleet_dic():
# return a fleet dictionary
# example :
# fleets = {
# 'a330' : {'900201', '900421'},
# 'a320' : {'900488', '900424'}
# }
A320_ids = crew_df[crew_df.Cur_Fleet == "A320"]['Crew_ID']
A330_ids = crew_df[crew_df.Cur_Fleet == "A330"]['Crew_ID']
print "number of pilots for A320 is " + str(len(A320_ids))
print "number of pilots for A330 is " + str(len(A330_ids))
fleet_dic = {
"A320" : set(A320_ids),
"A330" : set(A330_ids),
}
print fleet_dic
return 0
def get_orig_fleet_dic():
return 0
def get_future_fleet_dic():
fleet_change_future_A320_ids = crew_df[crew_df.Bid_FleetChange == "A320"]['Crew_ID']
fleet_change_future_A330_ids = crew_df[crew_df.Bid_FleetChange == "A330"]['Crew_ID']
print "number of pilots who bid fleetchange future A320 is " + str(len(fleet_change_future_A320_ids))
print "number of pilots who bid fleetchange future A330 is " + str(len(fleet_change_future_A330_ids))
future_fleet_dic = {
"A320" : set(fleet_change_future_A320_ids),
"A330" : set(fleet_change_future_A330_ids),
}
print future_fleet_dic
return future_fleet_dic
def get_orig_rank_dic():
return 0
def get_future_rank_dic():
return 0
def get_orig_base_dic():
b1_o_ids = crew_df[(crew_df.Bid_BaseChange == 1)]['Crew_ID']
b2_o_ids = crew_df[(crew_df.Bid_BaseChange == 2)]['Crew_ID']
baseBidOriginal_dict = {
"B1" : set(b2_o_ids),
"B2" : set(b1_o_ids),
}
return baseBidOriginal_dict
def get_future_base_dic():
bF_ids = crew_df[(crew_df.Bid_BaseChange == 1) | (crew_df.Bid_BaseChange == 2)]['Crew_ID']
#print "number of pilots wanting base change is " + str(len(bO_ids))
baseBid_dict = {
"Base Bid" : set(bF_ids),
}
return baseBid_dict
def get_demand(base, fleet, rank, week):
# example: base = "B1", fleet = "A330", rank = "FO", week = 0
# return the demand at B1, A330, FO of week 0
return 0
def get_future_position(base, fleet, rank):
# return non-fix group pilot ids whose future position is input
return 0
def get_orig_position(base, fleet, rank):
# return non-fix group pilot ids whose orig position is input
return 0
def get_position(base, fleet, rank):
# return fix group pilot ids whose position is input
return 0
|
4b24d78f2f3ded7d6d5c3ffcc8533b3d120457c5 | chenhh/Uva | /uva_11661.py | 995 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Authors: Hung-Hsin Chen <chenhh@par.cse.nsysu.edu.tw>
License: GPL v2
status: AC
difficulty: 1
http://luckycat.kshs.kh.edu.tw/homework/q11661.htm
https://uva.onlinejudge.org/external/116/11661.pdf
to find the shortest distance between a restaurant and a drugstore
"""
def main():
while 1:
road_len = int(input())
if road_len == 0:
break
road = input().strip()
dist = road_len
if 'Z' in road:
dist = 0
else:
# greedy update distance
restaurant, drugstore = 0, 0
for idx, v in enumerate(road):
if v == 'R':
restaurant = idx+1
elif v == 'D':
drugstore = idx+1
if restaurant and drugstore:
curr_dist = abs(restaurant - drugstore)
if curr_dist < dist:
dist = curr_dist
print (dist)
if __name__ == '__main__':
main() |
63a8508e8a26a795380b6f832254c82565dc7d03 | HappyRocky/pythonAI | /ABC/fibonacci1.py | 86 | 3.609375 | 4 | a, b = 0, 1
N = 10
while(N > 0):
print(b, end=" ")
a, b = b, a + b
N -= 1
|
c0b604d7c86c983e0a7753e5f3d248dcece652bc | omakmoh/rottiyzer | /rottiyzer.py | 1,721 | 3.984375 | 4 | #!/usr/bin/env python3
from string import ascii_uppercase as upper
from string import ascii_lowercase as lower
import argparse
import sys
def parse_args():
# parse the arguments
parser = argparse.ArgumentParser(epilog='\tExample: \r\npython3 ' + sys.argv[0] + " -o 2 -m tzou")
parser.add_argument('-o', '--mode', help="Type 1 for all attempts or Type 2 For useful only", type=int)
parser.add_argument('-m', '--message', help='Type the Rotated Text', required=True)
return parser.parse_args()
words = ['flag', 'FLAG', 'CTF', 'Flag', 'answer','FlAg']
#This is 1337 Line Banner for copyright
def rot(s, n):
upper_start = ord(upper[0])
lower_start = ord(lower[0])
out = ''
for letter in s:
if letter in upper:
out += chr(upper_start + (ord(letter) - upper_start + n) % 26)
elif letter in lower:
out += chr(lower_start + (ord(letter) - lower_start + n) % 26)
else:
out += letter
return(out)
def btats(o,m):
print("[*] Simple script to Bruteforce The Rotation Number")
message = m
choose = int(o)
if int(choose) == int(1) or choose =="":
print("[*] Well you chose the hard way")
for n in range(1,26):
print([n],rot(message,n=n))
elif choose == int(2):
print("[*] No Output? Try the first option")
for n in range(1,26):
for theuseful in words:
checking = rot(message,n=n)
if theuseful in checking:
print([n],checking)
else:
print("[-] Invaild Option")
def interactive():
args = parse_args()
o = args.mode
m = args.message
if not o:
o = 1
calling = btats(o,m)
if __name__ == "__main__":
interactive()
|
1660dfb21cf294e3c0b76fa5e2e7be15b158f9de | Sabarinathan07/python | /reverse.py | 112 | 3.828125 | 4 | str = input("Enter a Sentence : ")
x = str.split()
for a in range(-1,-len(x)-1,-1):
print(x[a],end=" ")
|
a74c0e5669544b87ee3eb7454aa716d4c541988a | oalbe/exercism | /python/robot-name/robot.py | 814 | 3.78125 | 4 | from random import randint
used_names = {}
def generate_name():
first_letter = chr(65 + randint(0, 25))
second_letter = chr(65 + randint(0, 25))
digits = randint(0, 999)
if (100 > digits):
digits = str(digits)
digits = ('0' + digits) if (2 == len(digits)) else ('00' + digits)
return first_letter + second_letter + str(digits)
class Robot:
def __init__(self):
self.reset()
def reset(self):
temp_name = generate_name()
# Loop until a name not present inside the `used_names` dictionary has been generated.
while temp_name not in used_names:
used_names[temp_name] = True
temp_name = generate_name()
used_names[temp_name] = True
self.name = temp_name |
6819774f84bc00bef820c4bef08edef57577dfcf | DevanshMathur10/BlinkDetection-1 | /BlinkDetectionTutorial/1_CaptureVideo.py | 673 | 3.75 | 4 | #------------Step 1: Use VideoCapture in openCV------------
import cv2
#livestream from the webcam
cap = cv2.VideoCapture(0)
'''in case of a video
cap = cv2.VideoCapture("__path_of_the_video__")'''
#name of the display window in openCV
cv2.namedWindow('BlinkDetector')
while True:
#capturing frame
retval, frame = cap.read()
#exit the application if frame not found
if not retval:
print("Can't receive frame (stream end?). Exiting ...")
break
cv2.imshow('BlinkDetector', frame)
key = cv2.waitKey(1)
if key == 27:
break
#releasing the VideoCapture object
cap.release()
cv2.destroyAllWindows()
|
6b2a10f9f4b3088cc820bf83d662eb26be703e94 | badster-git/codeforce-programs | /python/before-exam.py | 434 | 3.671875 | 4 | i, total, days = 0
def check(a, b):
if i == 0:
if ((a >= 1 and a <= 30) and (b >= 0 and b <= 240)):
days = a
total = b
i += 1
pass
else:
i = 0
print('NO')
if i > 0:
if ((0 <= a and a <= b and b <= 8):
for x in range(a, b):
if x * days == total:
print('YES')
i += 1
|
4b60d0fae7218ee6767c57e0108a0651f0a0f878 | gabriellaec/desoft-analise-exercicios | /backup/user_171/ch89_2019_06_06_23_42_16_250476.py | 263 | 3.515625 | 4 | class Circulo:
def __init__(self,ponto,raio):
self.x=px
self.y=py
self.Raio=raio
def contem(self,ponto):
if(self.x-px)**2+(self.y-py)**2<=self.Raio**2:
return True
else:
return False |
22eb2029c944f3db57c80a2e17df7f14ac276478 | Tinkerforge/blinkenlights | /games/python/repeated_timer.py | 664 | 3.5 | 4 | # -*- coding: utf-8 -*-
from threading import Timer
class RepeatedTimer:
def __init__(self, interval, function):
self.timer = None
self.interval = interval
self.function = function
self.is_running = False
self.start()
def run(self):
self.is_running = False
self.start()
self.function()
def start(self):
if not self.is_running:
self.timer = Timer(self.interval, self.run)
self.timer.daemon = True
self.timer.start()
self.is_running = True
def stop(self):
self.timer.cancel()
self.is_running = False
|
acb47bdb889468db1f009a510d8e0074067ba949 | ajayk01/Python-Programing | /Simple programs/simple_am.py | 290 | 3.890625 | 4 | a=int(input("Enter the value"));3
b=a;
c=a;
count=0;
r=0;
sum=0;
while(a!=0):
r=int(a%10);
count+=1;
a=int(a/10);
print(count);
while(b!=0):
r=int(b%10);
sum=int(sum+(r**count));
b=int(b/10);
if(sum==c):
print("The number is Amstrong");
else:
print("The number is not Amstrong");
|
7779d626d4478dd17a94981583e3ce8559805fb2 | srikanthpragada/PYTHON_17_JUN_2021 | /demo/assignments/grade.py | 242 | 4.03125 | 4 | # Display grade based on marks in two subjects
m1 = int(input("Enter first marks"))
m2 = int(input("Enter second marks"))
if m1 > 80 and m2 > 80:
print('A')
elif m1 > 80:
print('B')
elif m2 > 80:
print('C')
else:
print('D')
|
0b9594b5c7b9e920707fa669913e16c7c9804534 | chenmanxuan/homework | /期末复习.py | 2,170 | 3.71875 | 4 | #1
def triple(lst):
return [x**3 for x in lst]
lst=[1,2,3]
print(triple(lst))
#2
from functools import reduce
def add(lst):
return reduce(lambda x,y:x+y,lst)
lst=[1,2,3]
print(add(lst))
#3
path=''
def read_file(path,size=1024):
with open(path,'rb') as f:
while True:
data = f.read(size)
if not data:
break
yield data
print(read_file(path))
#4
def has_null_value(lst):
return list(filter(None,lst))==lst
lst=['',[],'sdfd']
print(has_null_value(lst))
def has_null_value(lst2):
return all(lst2)
lst2=['',[],'safdsf']
print(has_null_value(lst2))
#5
def fib_number(n):
if n==0 or n==1:
return 1
return fib_number(n-2)+fib_number(n-1)
def fib(n):
result=[]
for i in range(n):
value=fib_number(i)
if value> n:
break
result.append(value)
return result
print(fib(10))
#6.
def passwrd(len,lower=True,upper=True,number=True,special=True):
import string,random
lower_set=set(list(string.ascii_lowercase))
upper_set=set(list(string.ascii_uppercase))
number_set=set([x for x in range(10)])
special_set=set(list('~!@#$^%*()'))
user_choice=set()
if lower:
user_choice=user_choice | lower_set
if upper:
user_choice = user_choice | upper_set
if number:
user_choice=user_choice | number_set
if special:
user_choice=user_choice | special_set
passwrd=random.sample(user_choice,len)
return ''.join(passwrd)
len=6
print(passwrd(len))
#7
from functools import partial
def mul_by_type(n):
result=partial(lambda x,y:x*y,2)
return result(n)
print(mul_by_type(3))
#8
from functools import wraps
import time
def time_add(func):
@wraps(func)
def wrapper(*args,**kwargs):
start_time=time.time()
f=func(*args,**kwargs)
print('counter_time:',time.time()-start_time)
return f
return wrapper
@time_add
def add(x,y):
time.sleep(3)
return x+y
print(add(1,2))
|
6505cd0a74e3018c07a362080ec0deef2e716538 | tatianimeneghini/exerciciosPython_LetsCode | /Aula 11/exemplo2.py | 500 | 3.59375 | 4 | #Uma boa prática de programação, sempre divide em: MVC (Model, View, Control).
#Aqui é o Model:
class Gato(): #As classes são sempre feitas no início.
def __init__(self, nome, raca, dono):
self.nome = nome
self.raca = raca
self.dono = dono
def pular(self): #Os métodos são colocados, geralmente, depois ou em arquivos separado.
print(self.nome+" está pulando na cama")
def miar(self):
print("miau miau")
def ronronar(self):
print(self.nome+" está ronronando no edredom") |
080df567b0149a74e5797cd33a0d177310b2d08b | davidlepilote/codingame | /training/easy/The Bridge - Episode 1/.py | 621 | 3.984375 | 4 | import sys
import math
road = int(raw_input()) # the length of the road before the gap.
gap = int(raw_input()) # the length of the gap.
platform = int(raw_input()) # the length of the landing platform.
slowDown = False
# game loop
while 1:
speed = int(raw_input()) # the motorbike's speed.
coord_x = int(raw_input()) # the position on the road of the motorbike.
if slowDown :
print "SLOW"
elif speed < gap + 1 :
print "SPEED"
elif speed > gap + 1 :
print "SLOW"
elif coord_x == road - 1:
print "JUMP"
slowDown = True
else :
print "WAIT"
|
7b93bff55ab2103b814ad7246a75b5a54b73c2b1 | IsmoPismo/checkio | /common-words.py | 909 | 3.84375 | 4 | def checkio(first, second):
f_list = first.split(',')
s_list = second.split(',')
result_list = []
stringic = ''
for i in f_list:
if i in s_list:
result_list.append(i)
result_list.sort()
for x in range(len(result_list)):
if len(result_list) <= 1:
stringic += result_list[x]
elif len(result_list) > 1:
if x < len(result_list)-1:
stringic += result_list[x] + ','
else:
stringic += result_list[x]
return stringic
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio("hello,world", "hello,earth") == "hello", "Hello"
assert checkio("one,two,three", "four,five,six") == "", "Too different"
assert checkio("one,two,three", "four,five,one,two,six,three") == "one,three,two", "1 2 3"
|
db0eabf477d9a972867d8582010fa1dfb69387dc | shankar7791/MI-11-DevOps | /Personel/pooja/Assessment/Assessment - 9July/Q.2.py | 731 | 4.0625 | 4 | date = input("Enter the Date: ")
dd,mm,yy = date.split('/')
dd = int(dd)
mm = int(mm)
yy = int(yy)
if(mm == 1 or mm == 3 or mm == 5 or mm == 7 or mm == 8 or mm == 10 or mm == 12):
max1 = 31
elif(mm == 4 or mm == 6 or mm == 9 or mm == 11):
max1 = 30
elif(yy % 4 == 0 and yy % 100 != 0 or yy % 400 == 0):
max1 = 29
else:
max1 = 28
if(mm<1 or mm>12):
print("Date is invalid.")
elif(dd<1 or dd>max1):
print("Date is invalid.")
elif(dd == max1 and mm != 12):
dd = 1
mm = mm+1
print("The incremented date is: ",dd,mm,yy)
elif(dd == 31 and mm == 12):
dd = 1
mm = 1
yy = yy+1
print("The incremented date is: ",dd,mm,yy)
else:
dd = dd+1
print("The incremented date is: ",dd,mm,yy) |
f11f7f37ae31893ef09dbaa54cf106769bb05a3a | brunoparodi/IME-USP-Coursera | /Parte02/Aulas/simulador2.py | 1,258 | 3.71875 | 4 | from balde import Balde
import random
#constantes usadas em random
CAP_MIN = 10 #capacidade mínima do balde é 10
CAP_MAX = 51 #já ajustado ao random
VOL_MIN = 1 #sorteia no mínimo 1 para adicionar ao balde
VOL_MAX = 11 #já ajustado ao random. sorteia no máximo 11
class Simulador2:
def __main__(self, semente):
random.seed(semente)
capacidade = random.randrange(CAP_MIN, CAP_MAX)
self.recipiente = Balde(capacidade)
self.volume = 0
self.transbordo = 0
self.cheio = False
def sorteia(self):
self.volume = random.randrange(VOL_MIN, VOL_MAX)
print('Volume atual: ', self.recipiente.volume)
print('Foi adicionado: ',self.volume)
return self.volume
def enche(self, volume):
self.recipiente.enche(self.volume)
if self.volume == self.capacidade:
self.cheio = True
print('o balde encheu e não transbordou')
elif self.volume > self.capacidade:
self.cheio = True
print('o balde encheu e transbordou %d litros' %(self.volume - self.capacidade))
else:
print('ainda há espaço no balde')
def fim(self):
if self.cheio:
return 'fim'
|
097c946e693f0b87c353ab10791d974c28411ee3 | daniel-reich/ubiquitous-fiesta | /MbbX7qJJeEnQu9bKr_24.py | 318 | 3.71875 | 4 |
def max_occur(text):
occur = dict()
for letter in text:
if not letter in occur:
occur[letter] = 1
else:
occur[letter] += 1
max_occur = max(list(occur.values()))
if max_occur == 1:
return "No Repetition"
most = [key for key in occur if occur[key] == max_occur]
return sorted(most)
|
1815d949790dbe37b486bf2760e8eab7e56283a2 | blopah/python3-curso-em-video-gustavo-guanabara-exercicios | /Desafios/Desafio 29.py | 616 | 4.0625 | 4 | print("""Escreva um programa que leia a velocidade de um carro.
Se ele ultrapassar 80hm/h, mostre uma mensagem dizendo que ele foi multado.
A multa vai custar R$7,00 por cada Km acimda do limite""")
vel = input('Digite a velocidade do carro: ')
if vel.isnumeric():
velo = int(vel)
lim = 80
dif = velo - 80
mul = 0
if dif > 0:
mul = dif * 7
print('Você está acima do limite de {}Km/h! Sua multa é de R${},00.'.format(lim, mul))
else:
print('Parabéns você está dentro do limite de velocidade.')
else:
print('Entrada inválida. Digite uma velocidade valida.')
|
0439b3f712b8c8e591d3f20f3adaff4eaf661347 | VineeS/Python | /Assignment1/Square Root of a number.py | 206 | 4.0625 | 4 | import math
x = int(input("Enter the value"))
print("Square root of the number", x , "Is", math.sqrt(x))
y = int(input("Enter the value"))
sqrt = y * 0.5
print("Square root of the number", y , "Is", sqrt)
|
8ff4598954beefae673dded44ba20bc5f768147f | ishahpriyank/Parse-GEDCOM | /app.py | 2,445 | 3.734375 | 4 | """ A script to parse the data from a .ged file.
date: 20-Sep-2020
python: v3.8.4
"""
import re
import operator
from typing import List, Optional
from prettytable import PrettyTable
TAGS: List[str] = ['INDI', 'NAME', 'SEX', 'BIRT', 'DEAT', 'FAMC', 'FAMS', 'FAM',
'MARR', 'HUSB', 'WIFE', 'CHIL', 'DIV', 'DATE', 'HEAD', 'TRLR', 'NOTE']
ARGUMENT_PATTERN: str = '^(0|1|2) (NAME|SEX|FAMC|FAMS|MARR|HUSB|WIFE|CHIL|DATE) (.*)$' # pattern 1
NO_ARGUMENT_PATTERN: str = '^(0|1) (BIRT|DEAT|MARR|DIV|HEAD|TRLR|NOTE)$' # pattern 2
ZERO_PATTERN_1: str = '^0 (.*) (INDI|FAM)$' # pattern 3
ZERO_PATTERN_2: str = '^0 (HEAD|TRLR|NOTE) ?(.*)$' # pattern 4
regex_list: List[str] = [ARGUMENT_PATTERN, NO_ARGUMENT_PATTERN, ZERO_PATTERN_1, ZERO_PATTERN_2]
def pattern_finder(line: str) -> Optional[str]:
""" find the pattern of a given line """
for pattern, regex in zip(['ARGUMENT', 'NO_ARGUMENT', 'ZERO_1', 'ZERO_2'], regex_list):
if re.search(regex, line):
return pattern
def get_lines(path) -> List[str]:
""" get lines read from a .ged file """
with (file := open(path, "r")): # close file after opening
return [line for line in file]
def pretty_print(individuals: List[Individual], families: List[Family]) -> None:
""" prettify the data """
individual_table: PrettyTable = PrettyTable()
family_table: PrettyTable = PrettyTable()
individual_table.field_names = ["ID", "Name", "Gender", "Birthday", "Age",
"Alive", "Death", "Child", "Spouse"]
family_table.field_names = ["ID", "Married", "Divorced", "Husband ID", "Husband Name",
"Wife ID", "Wife Name", "Child"]
for individual in individuals: # add individual info to the table
individual_table.add_row(individual.info())
for family in families: # add individual info to the table
family_table.add_row(family.info(individuals))
print("Individuals\n", individual_table, sep="")
print("Families\n", family_table, sep="")
def main():
""" the main function to check the data """
path: str = 'SSW555-P1-fizgi.ged'
lines = get_lines(path) # process the file
individuals, families = generate_classes(lines)
individuals.sort(key=operator.attrgetter('id'))
families.sort(key=operator.attrgetter('id'))
pretty_print(individuals, families)
if __name__ == '__main__':
main()
|
307b7088992a3e00c388572eb980533ab2bf95fb | vikhyat-dhamija/Intro-to-Deep-Learning | /HW2/q1_prog_Vikhyat_vd283.py | 4,619 | 3.9375 | 4 | import math
import numpy as np
import dask
#Mode is a variable whose value can be 0 or 1 : 1 for normal operation and 0 for differential operation
#inputs to the graph
x1=input("Please enter the value of x1 ")
x2=input("Please enter the value of x2 ")
w1=input("Please enter the value of w1 ")
w2=input("Please enter the value of w2 ")
#Forward Propagation in the graph
# Functions to be used
#Node 1 Multiplication
def node1(a,b,mode,pos,b_input):
if mode==1:
return a*b
elif pos==1:
return (b*b_input)
else:
return (a*b_input)
#Node 2 Cosine
def node2(a,mode,b_input):
if mode==1:
return (math.cos(a))
else:
return (-(math.sin(a))*b_input)
#Node 3 Multiplication2
def node3(a,b,mode,pos,b_input):
if mode==1:
return a*b
elif pos==1:
return (b*b_input)
else:
return (a*b_input)
#Node 4 sine function
def node4(a,mode,b_input):
if mode==1:
return math.sin(a)
else:
return ((math.cos(a))*b_input)
#Node 5 square function
def node5(a,mode,b_input):
if mode==1:
return a*a
else:
return 2*a*b_input
#Node 6 addition1 function
def node6(a,b,mode,b_input):
if mode==1:
return a+b
else:
return (1*b_input)
#Node7 addition2 function
def node7(a,b,mode,b_input):
if mode==1:
return a+b
else:
return (1*b_input)
#Node 8 reciprocal function
def node8(a,mode,b_input):
if mode==1:
return (1/a)
else:
return(-1/(a*a))
#Forward Computation
input1_n3=float(x1)
input2_n3=float(w1)
input1_n1=float(x2)
input2_n1=float(w2)
print("Forward Propagation.........")
#Edge n3-n4-n5
print("Forward outputs at Edge n3-n4-n5")
output_n3=node3(input1_n3,input2_n3,1,0,0)
print("The output at Node 3",output_n3)
input_n4=output_n3
output_n4=node4(input_n4,1,0)
print("The output at Node 4",output_n4)
input_n5=output_n4
output_n5=node5(input_n5,1,0)
print("The output at Node 5",output_n5)
#Edge n1-n2
print("Forward outputs at Edge n1-n2")
output_n1=node1(input1_n1,input2_n1,1,0,0)
print("The output at Node 1",output_n1)
input_n2=output_n1
output_n2=node2(input_n2,1,0)
print("The output at Node 2",output_n2)
print("Forward outputs at Edge n6-n7-n8")
input1_n6=output_n5
input2_n6=output_n2
output_n6=node6(input1_n6,input2_n6,1,0)
print("The output at Node 6",output_n6)
input_n7=output_n6
output_n7=node7(2,input_n7,1,0)
print("The output at Node 7",output_n7)
input_n8=output_n7
output_n8=node8(input_n8,1,0)
print("The output at Node 8",output_n8)
print("The Final Result of the Forward Computation is : ",output_n8 )
#Backward Propagation
print("Backward Propagation.........")
print("Backward differential outputs at Edge n8-n7-n6")
b_output_n8=node8(input_n8,0,1)
print("Backward differential output at Node 8 : ",b_output_n8)
b_output_n7=node7(2,input_n7,0,b_output_n8)
print("Backward differential output at Node 7 : ",b_output_n7)
b_output_n6=node6(input1_n6,input2_n6,0,b_output_n7)
print("Backward differential output at Node 6 : ",b_output_n6)
print("Backward differential outputs at Edge n5-n4-n3")
b_output_n5=node5(input_n5,0,b_output_n6)
print("Backward differential output at Node 5 : ",b_output_n5)
b_output_n4=node4(input_n4,0,b_output_n5)
print("Backward differential output at Node 4 : ",b_output_n4)
b_output_n3_x1=node3(input1_n3,input2_n3,0,1,b_output_n4)
b_output_n3_w1=node3(input1_n3,input2_n3,0,2,b_output_n4)
print("Backward differential output at Node 3 position 1 output with respect to x1: ",b_output_n3_x1)
print("Backward differential output at Node 3 position 2 output with respect to w1: ",b_output_n3_w1)
print("Backward differential outputs at Edge n2-n1")
b_output_n2=node2(input_n2,0,b_output_n6)
print("Backward differential output at Node 2 : ",b_output_n2)
b_output_n1_x2=node1(input1_n1,input2_n1,0,1,b_output_n2)
b_output_n1_w2=node1(input1_n1,input2_n1,0,2,b_output_n2)
print("Backward differential output at Node 1 position 1 output with respect to x2: ",b_output_n1_x2)
print("Backward differential output at Node 1 position 2 output with respect to w2: ",b_output_n1_w2)
print("Overall output..........")
print("The Result of the partial differentiation of output with respect to x1 is : ",b_output_n3_x1)
print("The Result of the partial differentiation of output with respect to w1 is : ",b_output_n3_w1)
print("The Result of the partial differentiation of output with respect to x2 is : ",b_output_n1_x2)
print("The Result of the partial differentiation of output with respect to w2 is : ",b_output_n1_w2)
|
d39067b8a88d4b809ad7567170524ccaa3036926 | pokan975/Py-for-Rapid_Engineering | /hw1_12.py | 1,056 | 3.875 | 4 | #!/usr/bin/env python
# =============================================================================
# Main Code:
# Find all prime numbers less or equal than 10^4.
# Prime factor examination:
# an non-prime integer must have prime factors less or equal than its square root, or it's a prime.
# =============================================================================
from numpy import sqrt
max_num = int(1e4)
# initiate prime list from 2 (minimum prime)
prime_list = [2]
for num in range(3, max_num + 1):
# default take n as prime
prime_flag = True
# find n's prime factors, once find out, reset flag & break loop
for factor in prime_list:
# only check prime factors less or equal than sqrt(n)
if factor > sqrt(num):
break
elif num % factor == 0:
prime_flag = False
break
# add n to prime list if no factor is found
if prime_flag:
prime_list.append(num)
# print out final prime list
print(prime_list) |
5f9c4c902391deac87fd32dafb28d96a5b9c5559 | rferreira3/tictactoe | /logic.py | 10,503 | 4 | 4 | """
ttt_logic
This module contains the logic to drive a two-player Tic-Tac-Toe
game.
"""
class ttt_logic:
def __init__(self):
self.NW = None
self.N = None
self.NE = None
self.W = None
self.C = None
self.E = None
self.SW = None
self.S = None
self.SE = None
self.currentplayer = "X"
def check_status(self):
"""
Checks to see if either player has won or if the board is filled.
Returns a two-tuple in which the first component is the string
"x" or the string "O" or the value None; the second component
of the tuple is one of the following strings that indicates the
Tic-Tac-Toe board's status:
"Playing" No one has won and a move is available
"Win_NW_NE" Win across top row
"Win_W_E" Win across middle row
"Win_SW_SE" Win across bottom row
"Win_NW_SW" Win along left colunm
"Win_N_S" Win along center column
"Win_NE_SE" Win along right column
"Win_NW_SE" Win from left-top corner to right-bottom
"Win_NE_SW" Win from right-top corner to left-bottom
"Draw" All squares filled with no winner
The first component of the resulting tuple represents the game
winner, and the second component of the tuple represents the
winning configuration. If the status component is "Playing" or
"Draw", the winner component should be None; for example, the
tuple ("x", "Win_NE_SE") would be a valid return value, but
neither ("x", "Draw") nor ("O", "Playing") represents a valid
result.
"""
if self.NW == self.N and self.N == self.NE and self.N != None:
return ( self.NW ,'Win_NW_NE')
if self.NW == self.W and self.W == self.SW and self.W != None:
return (self.NW ,'Win_NW_SW')
if self.NW == self.C and self.C == self.SE and self.C != None:
return (self.NW ,'Win_NW_SE')
if self.N == self.C and self.C == self.S and self.C != None:
return (self.N,'Win_N_S')
if self.NE == self.C and self.C == self.SW and self.C != None:
return (self.NE ,'Win_NE_SW')
if self.NE == self.E and self.E == self.SE and self.E != None:
return (self.NE, 'Win_NE_SE')
if self.W == self.C and self.C == self.E and self.C != None:
return (self.E,'Win_W_E')
if self.SW == self.S and self.S == self.SE and self.S != None:
return (self.SW, 'Win_SW_SE')
if self.NW != None and self.N != None and self.NE != None and self.W != None and self.C != None and \
self.E != None and self.SW != None and self.S != None and self.SE != None:
return None, 'Draw'
return None, 'Playing'
def move(self,location):
"""
Places the current player's mark at the given location, if possible.
The caller must pass one of the following strings specifying
the location:
"NorthWest" Top, left square
"North" Top, middle square
"NorthEast" Top, right square
"West" Left, middle square
"Center" Center square
"East" Right, middle square
"SouthWest" Bottom, left square
"South" Bottom, middle square
"SouthEast" Bottom, right square
Returns True if the specified location is available (that is,
the global variable keeping track of that position is None);
otherwise the function returns False for an illegal move.
If the current player makes a valid move, the function ensures
that control passes to the other player; otherwise, the move
function does not affect the current player.
"""
if location == 'NorthWest':
if self.NW == None:
if self.currentplayer == 'X':
self.NW = 'X'
if self.currentplayer == 'O':
self.NW = 'O'
self.change_player()
return True
else:
return False
if location == 'North':
if self.N == None:
if self.currentplayer == 'X':
self.N = 'X'
if self.currentplayer == 'O':
self.N = 'O'
self.change_player()
return True
else:
return False
if location == 'NorthEast':
if self.NE == None:
if self.currentplayer == 'X':
self.NE = 'X'
if self.currentplayer == 'O':
self.NE = 'O'
self.change_player()
return True
else:
return False
if location == 'West':
if self.W == None:
if self.currentplayer == 'X':
self.W = 'X'
if self.currentplayer == 'O':
self.W = 'O'
self.change_player()
return True
else:
return False
if location == 'Center':
if self.C == None:
if self.currentplayer == 'X':
self.C = 'X'
if self.currentplayer == 'O':
self.C = 'O'
self.change_player()
return True
else:
return False
if location == 'East':
if self.E == None:
if self.currentplayer == 'X':
self.E = 'X'
if self.currentplayer == 'O':
self.E = 'O'
self.change_player()
return True
else:
return False
if location == 'SouthWest':
if self.SW == None:
if self.currentplayer == 'X':
self.SW = 'X'
if self.currentplayer == 'O':
self.SW = 'O'
self.change_player()
return True
else:
return False
if location == 'South':
if self.S == None:
if self.currentplayer == 'X':
self.S = 'X'
if self.currentplayer == 'O':
self.S = 'O'
self.change_player()
return True
else:
return False
if location == 'SouthEast':
if self.SE == None:
if self.currentplayer == 'X':
self.SE = 'X'
if self.currentplayer == 'O':
self.SE = 'O'
self.change_player()
return True
else:
return False
def current_player(self):
"""
Returns the player whose turn it is to move. This allows the
presentation to report whose turn it is.
Return value is one of either "x" or "O".
"""
if self.currentplayer == 'X':
return "X"
else:
return "O"
def set_player(self,new_player):
"""
Sets the current player. Useful for games that require the
player to answer a question correctly before a move. If the
player answers incorrectly, the turn moves to the opponent.
Valid values for new_player are "x" or "O"; any other strings
will not change the current player.
"""
if new_player == 'X' or new_player == 'O':
self.change_player()
def change_player(self):
"""
Alternates turns between players. x becomes O, and O becomes X.
"""
player = self.current_player()
if player == 'X':
self.currentplayer = 'O'
else:
self.currentplayer = 'X'
def look(self,location):
"""
Returns the mark at the given location. The caller must pass
one of the following strings specifying the location:
"NorthWest" Top, left square
"North" Top, middle square
"NorthEast" Top, right square
"West" Left, middle square
"Center" Center square
"East" Right, middle square
"SouthWest" Bottom, left square
"South" Bottom, middle square
"SouthEast" Bottom, right square
The function's valid return values are None, "X", or "O".
Returns None if neither player has marked
the given location. The function also returns None if the
caller passes any string other than one of the location strings
listed above.
This function allows the presentation to draw the contents
of the Tic-Tac-Toe board.
"""
if location == "NorthWest":
return self.NW
if location == "North":
return self.N
if location == "NorthEast":
return self.NE
if location == 'West':
return self.W
if location == 'Center':
return self.C
if location == 'East':
return self.E
if location == 'SouthWest':
return self.SW
if location == 'South':
return self.S
if location == 'SouthEast':
return self.SE
if location == None:
pass
def initialize_board(self):
"""
Make all the board locations empty and set current player to
"x" (that is, reset the board to the start of a new game)
"""
self.currentplayer = 'X'
self.NW = None
self.N = None
self.NE = None
self.W = None
self.C = None
self.E = None
self.SW = None
self.S = None
self.SE = None
pass
if __name__ == "__main__":
pass # This module is not meant to be run as a standalone program
|
49835de2b49d9955c25d97e6a452d68c7e6a92f7 | killswitchh/Leetcode-Problems | /Medium/longest-palindromic-substring.py | 581 | 3.796875 | 4 | '''
https://leetcode.com/problems/longest-palindromic-substring/
'''
class Solution:
def reversee(S):
if(S==S[::-1]):
return True
else:
return False
def longestPalindrome(self, s: str) -> str:
anss=''
for i in range(len(s)):
for j in range(i+1,len(s)+1):
temp=s[i:j]
ans=Solution.reversee(temp)
#print(temp,ans)
if(ans==True) and (len(anss)<len(temp)):
anss=temp
return(anss)
|
f44d7625285879f4fb9e240e2a1305f49a8b4a48 | pcaldredbann/katalyst-kickstart | /python/python3-kickstart-project/calculator/tests/calculator_py_test.py | 563 | 3.671875 | 4 | import pytest
from calculator.calculator import summarize
def test_sum_numbers():
"""This is an example of a simple unit test using pytest"""
assert summarize(4, 2) == 6
@pytest.mark.parametrize(
"x, y, result",
[
pytest.param(
2, 3, 5
),
pytest.param(
6, 0, 6
),
pytest.param(
4, -2, 2
),
],
)
def test_sum_numbers__parametrized(x, y, result):
"""This is an example of a parametrized unit test using pytest"""
assert summarize(x, y) == result
|
e21315120845499e3f6b292e85c6b28f348e10db | ebotCode/SudokuSolver | /src/sudokuUtils.py | 10,892 | 3.90625 | 4 | """
Sudoku Solver utility functions.
"""
import copy
def cross(a,b):
""" performs cross product of two strings a,b or list/tuple of strings """
return [s + t for s in a for t in b]
# define constants
ROWS = 'ABCDEFGHI' # row labels for the sudoku puzzle.
COLS = '123456789' # column labels for the sudoku puzzle
#. BOXES: list of boxes in the sudoku puzzle. e.g "A1","A2",etc
BOXES = cross(ROWS,COLS)
#. ROW_UNITS : list of boxes on each row. e.g ROW_UNITS[0] -> ["A1","A2",...,"A9"]
ROW_UNITS = [cross(r,COLS) for r in ROWS]
#. COLUMN_UNITS : list of boxes on each column. e.g COLUMN_UNITS[0] -> ["A1","B1","C1",..,"I1"]
COLUMN_UNITS = [cross(ROWS,c) for c in COLS]
#. SQUARE_UNITS : lost of boxes in each 3 x 3 subgrid square.
#. e.g SQUARE_UNITS[0] -> ["A1","A2","A3",
#. "B1","B2","B3",
#. "C1","C2","C3"]
SQUARE_UNITS = [cross(rs,cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')]
#. A collection of all units: row_units, column_units and square_units
UNITLIST = ROW_UNITS + COLUMN_UNITS + SQUARE_UNITS
#. UNITS : a dictionary of :{ <box>:<row_unit,column_unit,square_unit> } associated with a box.
UNITS = dict( (s, [u for u in UNITLIST if s in u]) for s in BOXES)
#. PEERS
#. a dict of neighbors for each unit. the neighbors of a unit are
#. 1. boxes that lie on the same row as the unit
#. 2. boxes that lie on the same col as the unit
#. 3. boxes that lie in the same squre_grid as the unit.
#. e.g The set list in UNITS['A1'] is shown below: (note : not ordered)
#. PEERS['A1'] -> ['B1','C1','D1','E1','F1','G1','H1','I1',
#. 'A2','A3','A4','A5','A6','A7','A8','A9',
#. 'B2','B3','C2','C3]
PEERS = dict((s, set(sum(UNITS[s],[])) - set([s])) for s in BOXES) # merge lists and removes duplicates.
def Display(values):
"""
Display the values as a 2-D grid.
Input: The sudoku in dictionary form
OUtput: None
"""
width = 1+ max(len(values[s]) for s in BOXES)
line = '+'.join(['-'*(width*3)]*3)
for r in ROWS:
print(''.join(values[r + c].center(width) + ('|' if c in '36' else '') for c in COLS))
if r in 'CF': print(line)
return
def ConvertSudokuStringToGrid(sudoku_string,empty_delimiter = '.'):
"""
Args: sudoku_string
Returns : a sudoku grid dictionary :
- keys : Box labels
- values : value in corresponding box for ' ' if it is empty.
"""
values = []
replace_string = " "
for c in sudoku_string:
if c == empty_delimiter:
values.append(replace_string)
else:
values.append(c)
assert len(values) == 81
return dict(zip(BOXES,values))
def ConvertSudokuStringToSearchGrid(sudoku_string,empty_delimiter = '.'):
""" Convert grid string into a form {<box>:<possible-values>} that is suitable
for search
Args:
sudoku_sting: sudoku grid in string form, 81 characters long
replace_string : the string to replace
empty_delimiter : the character that delimits empty sudoku squares
Returns:
Sudoku grid in dictionary form:
- keys: Box labels, e.g. 'A1'
- values: value in corresponding box, e.g. '8', or '.' if it is empty.
"""
# better solution
values = []
all_digits = '123456789'
for c in sudoku_string:
if c == empty_delimiter:
values.append(all_digits)
elif c in all_digits:
values.append(c)
else:
raise ValueError("Invalid character %s"%c)
assert len(values) == 81
return dict(zip(BOXES,values))
def Eliminate(sudoku_search_grid):
"""
Locate boxes that have single values, and eliminate that value from the
peers of that box.
Args:
sudoku_search_grid: Sudoku in dictionary form
Returns:
Resulting Sudoku in dictionary form after eliminating values.
"""
#. get boxes that have single values (a.k.a solved boxes)
solved_values = [box for box in sudoku_search_grid.keys() if len(sudoku_search_grid[box]) == 1]
# . for each of the solved boxes, eliminate the value from its peers
for box in solved_values:
digit = sudoku_search_grid[box]
for peer in PEERS[box]:
sudoku_search_grid[peer] = sudoku_search_grid[peer].replace(digit,'')
return sudoku_search_grid
def OnlyChoiceConstraint(sudoku_search_grid):
"""
Check through each row, col and square for boxes that are constrained to have
a value. in otherwords, if a digit occors once in a unit (either row, col or square_unit)
then the box that has that digit is constrained to have that value.
e.g if a row has -> ['1','245','234','268','67','259','268','47'].
since digit '1' occurs once in the row, it is constrained to that box.
since digit '3' occurs once in the row, it is constrained to that box. hence
the value changes from '234' to '3'
since digit '9' occurs once in the row, it is contrained to that box.
hence the value, at index 5 changes from '259' to '9'
etc
Args:
sudoku_search_grid: Sudoku in dictionary form.
Return: Resulting Sudoku in dictionary form after filling in only choices.
"""
for unit in UNITLIST: # [row_units,col_units,square_units]
for digit in '123456789':
dplaces = [box for box in unit if digit in sudoku_search_grid[box]]
if len(dplaces) == 1:
sudoku_search_grid[dplaces[0]] = digit
# Notice the inplace modification. This allows new updates to the grid
# to be taken into account. Because, constraining a box, can cause a
# previously unconstrained box to become constrained.
return sudoku_search_grid
def ReducePuzzle(sudoku_search_grid):
"""
Using the Eliminate and OnlyChoice constraint, keep reducing the puzzle until it can't
be reduced any further.
Note: reducing the puzzle eliminates search spaces that are useless to explore. This is where
the constraint propagation occurs. by pruning search spaces that do not meet the
constraint, we narrow down the search space and search efficiently.
If this is not done, then code would be searching the whole possible permutation
of the possible configuration of the sudoku.
Args:
sudoku_search_grid: sudoku in dictionary form
Return :
a reduced sudoku grid.
"""
def CountSolvedBoxes(sudoku_search_grid):
return len([box for box in sudoku_search_grid.keys()
if len(sudoku_search_grid[box]) == 1 ])
stalled = False
#. if the number of solved boxes before applying Eliminate and OnlyChoiceContraint is the same
#. as the result, then it can't be reduced further. stalled = True
while not stalled:
solved_values_before = CountSolvedBoxes(sudoku_search_grid)
sudoku_search_grid = Eliminate(sudoku_search_grid)
sudoku_search_grid = OnlyChoiceConstraint(sudoku_search_grid)
# check how many BOXES have a determined value, to compare
solved_values_after = CountSolvedBoxes(sudoku_search_grid)
# if no new values were addeed, stop the loop.
stalled = solved_values_before == solved_values_after
# Sanity check, return False if there is a box with zero available values:
if len([box for box in sudoku_search_grid.keys() if len(sudoku_search_grid[box]) == 0]):
return False
return sudoku_search_grid
def IsSudokuSolved(sudoku_search_grid):
# is_all_box_sigle = all(len(sudoku_search_grid[box]) == 1 for box in BOXES)
all_digit = '123456789'
for digit in all_digit:
for unit in UNITLIST:
dplaces = [box for box in unit if digit in sudoku_search_grid[box]]
if len(dplaces) > 1:
return False
return True
def GetBoxWithFewestPossibilities(sudoku_search_grid):
all_lengths = list( (len(sudoku_search_grid[box]),box)
for box in BOXES
if len(sudoku_search_grid[box]) > 1)
if len(all_lengths) > 0:
n,box_with_fewest_possibility = min(all_lengths)
return box_with_fewest_possibility
else:
return None
def SolveSudoku(sudoku_search_grid, use_constraint = True, display_count = False):
"""
Solve the Sudoku
Args:
sudoku_search_grid : sudoku puzzle in dictionary form
use_constraint : boolean (True or False. default is True)
if True, the pruning methods
'Eliminate' and 'OnlyChoiceConstraint' are applied.
else, they are not.
This can be used to see the effect of pruning on certain
types of sudoku instances.
Returns:
Note:
"""
SolveSudoku.count_search_instance = 0
def Search(sudoku_search_grid):
SolveSudoku.count_search_instance += 1
if display_count:
print("Search instances OPENED = ",SolveSudoku.count_search_instance)
# first reduce the puzzle.n This prunes the search space
if use_constraint:
sudoku_search_grid = ReducePuzzle(sudoku_search_grid)
#. if ReducePuzzle returns False, then the current state cannot be extended.
if sudoku_search_grid is False:
return False ## Failed earlier
#. if sudoku is solved, return the sudoku grid.
if IsSudokuSolved(sudoku_search_grid):
return sudoku_search_grid ## solved!
#. Advance the search using DFS.
# Choose one of the unfilled squares with the fewest possibilities
chosen_box = GetBoxWithFewestPossibilities(sudoku_search_grid)
if chosen_box == None :
return False
for digit in sudoku_search_grid[chosen_box]:
# new_sudoku = sudoku_search_grid.copy() # make a new sudoku grid
new_sudoku_search_grid = copy.deepcopy(sudoku_search_grid)
new_sudoku_search_grid[chosen_box] = digit # insert this digit as the value of chosen_box
attempt = Search(new_sudoku_search_grid) # the recusively search.
if attempt:
return attempt
return False
search_result = Search(sudoku_search_grid)
return search_result, SolveSudoku.count_search_instance
|
c6abcd0baba710b4edc5a20d5a3b4bb04c0ed931 | SahilTara/ITI1120 | /LABS/lab2_prog_solutions.py | 681 | 4.03125 | 4 | import math
#########QUESTION: 1########################
def repeater(s1,s2,n):
return "_" +(s1+s2) * n + "_"
############Question: 2##############
def roots(a,b,c):
x1 = (-b + math.sqrt( b ** 2 - 4 * a * c ))/(2 * a)
x2 = (-b - math.sqrt( b ** 2 - 4 * a * c ))/(2 * a)
print("The quadratic equation with coefficients a = " + str(a) +
" b = " + str(b) + " c = " + str(c) + "\nhas the following solutions" +
" (i.e. roots):\n" + str(x1) + " and " + str(x2))
###########Question: 3###############
def real_roots(a,b,c):
return b ** 2 - 4 * a * c >= 0
###########Question: 4###############
def reverse(x):
return (x % 10) * 10 + x//10
|
6a8e20a29cbd0dca1813c056f84c47e0aa980bd5 | VishalVimal/python-project | /cooding anna execise/patten.py | 364 | 4.15625 | 4 | choice=int(input("Enter the choice 0---->patten in correct order or 1---->patten in reverse order :"))
patten=int(input("enter the number of pattend row you want : "))
if choice==bool(0):
for i in range(0,patten+1):
print(i*'*')
elif choice==bool(1):
while patten>=0:
print(patten*'*')
patten-=1
|
bf7cc6d48c6883d8df6d9bd4b0a07f23dfb67616 | stungkit/Leetcode-Data-Structures-Algorithms | /08 String/438. Find All Anagrams in a String.py | 1,132 | 3.609375 | 4 | # Method: sliding window with hashing
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# (0) edge case
l1, l2 = len(p), len(s)
if l2 < l1:
return
# (1) initialize an empty list for result
res = []
p_hash, s_hash = 0, 0
# (2) compute the hash value of string p and string s
for i in range(l1):
p_hash += hash(p[i])
s_hash += hash(s[i])
if p_hash == s_hash:
res.append(0)
# (3) move the window(string p) in string s ahead step by step
for i in range(l2-l1):
s_hash = s_hash - hash(s[i]) + hash(s[i + l1])
if s_hash == p_hash:
res.append(i+1)
# (4) return result
return res
# p = "a b c" 3
# s = "c b a e b a b a c d" 10
# idx: 0 1 2 3 4 5 6 7 8 9
# Time: O(N) when len(s) == len(p)
# Space: O(N) when string p has only one letter (let's say x) and all letters in string p are x |
9661d23e4186e2dc04651382a34c50f86b778efd | cattibrie/data-structures | /tree_ex/tree_test.py | 963 | 4.15625 | 4 | from tree import Queue, Element, Node, BinaryTree
def test_tree_empty():
tree = BinaryTree()
assert tree.getHead() == None
def test_tree_add_head():
tree = BinaryTree()
tree.add(1)
assert tree.getHead() == 1
def test_tree_add_three():
tree = BinaryTree()
tree.add(1)
tree.add(2)
left_child = tree.head.left_child
assert left_child.getValue() == 2
tree.add(3)
right_child = tree.head.right_child
assert right_child.getValue() == 3
def test_tree_add_multiple():
arr = [1, 2, 3, 4, 5]
tree = BinaryTree()
for el in arr:
tree.add(el)
queue = Queue()
queue.add(tree.head)
i = 0
while queue.notEmpty():
current = queue.getHeadValue()
assert current.getValue() == arr[i]
i += 1
if current.hasLeftChild():
queue.add(current.left_child)
if current.hasRightChild():
queue.add(current.right_child)
queue.pop()
|
08f83618bb4810aaef1ed033232b5b6c598031a1 | PedroBernini/ipl-2021 | /set_0/p0_2_1.py | 380 | 4.09375 | 4 | # Programa para calcular o resultado da avaliação de uma expressão "ax2 + bx + c" em um valor particular de x.
a = 1
b = 2
c = 3
x = 0.5
def quadraticFunction(equation):
return (equation['a'] * equation['x']) ** 2 + equation['b'] * equation['x'] + equation['c']
equation = {
'a': a,
'b': b,
'c': c,
'x': x
}
out = quadraticFunction(equation)
print(out) |
81ebb5f236324ff554fecdb03532755ae08be26d | Sunnyc317/csci2072-computational-science | /lec_code/PLU.py | 1,439 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 25 13:29:54 2019
@author: snnch
# Lecture 5 code
# LU decomposition
# input: n X n matrix A
# Output: n X n matrices L and U such that LU = A and L and U are
# triangular matrix
"""
import math
import scipy
import copy
def PLU(A):
# throw warning flag when the number is too small
# (close to 0)
ok = 1
small = 1e-12
n = scipy.shape(A)[0]
U = copy.copy(A)
L = scipy.identity(n)
P = scipy.identity(n)
for j in range(1,n):
print(j," operation")
print("This is U")
print(U)
print("This is L")
print(L)
print("This is P")
print(P)
print()
s = scipy.argmax(abs(U[j-1:n,j-1])) + j-1
# argmax returs the index of that number
if s != j-1:
U = swap(U,s,j-1,n)
P = swap(P,s,j-1,n)
if j > 1:
L = swap(L,s,j-1,j-1)
for i in range (j+1,n+1):
if abs(U[j-1,j-1]) < small:
print("Near-zero pivot!")
ok = 0
break
L[i-1,j-1] = float(U[i-1,j-1])/float(U[j-1,j-1])
for k in range(j,n+1):
U[i-1,k-1] = float(U[i-1,k-1]) - L[i-1,j-1] * U[j-1,k-1]
return L,U,P,ok
def swap(M,i,k,n):
dum = copy.copy(M[i,0:n])
M[i,0:n] = copy.copy(M[k,0:n])
M[k,0:n] = copy.copy(dum)
return M
|
2b55d3b7a0347b054bdcf5a7accfc355fa121490 | ekeydar/selfpy_sols | /ex7.2.7.py | 320 | 3.671875 | 4 | def arrow(my_char, max_length):
result = []
for row_len in range(1, max_length):
result.append(my_char*row_len)
for row_len in range(max_length, 0, -1):
result.append(my_char*row_len)
return "\n".join(result)
def main():
print(arrow('*', 5))
if __name__ == '__main__':
main()
|
e047d202304133bb8e52230abe19f8dd5a0708c3 | shivsingh-git/LeetCode-May-Challenge | /Day-8.py | 1,169 | 3.578125 | 4 | class Solution:
def checkStraightLine(self, c: List[List[int]]) -> bool:
count=0
if((c[1][0]-c[0][0])==0): #if the slope is infinity means the line parallel to the y axis.
for i in range (0,len(c)):
if(c[i][0]==c[0][0]):
count+=1
elif((c[1][1]--c[0][1])==0): #if the sloop is zero anyline parellel to x axis.
for i in range(0,len(c)):
if(c[i][1]==c[0][1]):
count+=1
else:
m=(c[1][1]-c[0][1])/(c[1][0]-c[0][0]) #in all the other cases calculating the slope of the line by frst two points.
for i in range (0,len(c)):
if((c[i][1]-c[0][1])==m*(c[i][0]-c[0][0])): #satisfying the equatin,(y-y1)=m(x-x1)
count+=1 #counting the value if all the value satisfies
if (count==len(c)): #if all the values satisfies the given eqaution then return true
return True
else:
return False
|
da55b2b8af6b030450e1b17c662f4ffc73228ece | ChristopheHunt/MSDA---Coursework | /Data 602/Week 4/Week 4 IO parsing - HTML.py | 1,837 | 3.734375 | 4 | # # Week 4 IO Parsing HTML
############################################
# I will be using the Beautiful Soup python library to parse https://www.brainpickings.org.
# The site has excellent book reviews for a variety of topics by the site's creator Maria Popova.
# Additionally, she takes several exceptional quotes from each author for their book post, which will be our text of interest.
# Once we parse the text of interest, will pass them to the Alchemy API for the top ten keywords.
#############################################
import pandas as pd
from BeautifulSoup import BeautifulSoup
import urllib2
from alchemyapi.alchemyapi import AlchemyAPI
url = 'https://www.brainpickings.org'
page = urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
divText = soup.find("div", {"id": "main_body"} , {"class": "right"})
print(str(divText.div.strong.prettify) + " AUTHOR NAME TEST")
print(str(divText.div.blockquote.prettify) + " QUOTE TEXT TEST")
def build_quotes(TextSoup):
divText = TextSoup.find("div", {"id": "main_body"} , {"class": "right"})
Allauthors = []
Allquotes = []
for tag in divText:
author = tag.find('strong')
if author not in (-1, None):
Allauthors.append(author.contents)
quotes = tag.find('blockquote')
if quotes not in (-1, None):
quote = quotes.findAll('p', text = True)
Allquotes.append(quote)
print(str(Allauthors[0]) + str(Allquotes[0]) + "FIRST QUOTE - RESULTS TEST")
return(Allquotes)
Allquotes = build_quotes(soup)
alchemyapi = AlchemyAPI()
response = alchemyapi.keywords('text', Allquotes)
keywords = response.values()
keywords = keywords[2]
print(str(keywords[0]) + " KEYWORD SLICE CHECK")
df = pd.DataFrame(keywords)
df.index = df.index + 1
print df[0:10]
|
a6d71c92813c5e81d5c746c962f742c4b72adb9b | Aasthaengg/IBMdataset | /Python_codes/p03042/s976063134.py | 235 | 3.796875 | 4 | S = input()
pre = int(S[:2])
sur = int(S[2:])
if pre <= 12 and pre > 0 and sur <= 12 and sur > 0:
print('AMBIGUOUS')
elif pre <= 12 and pre > 0:
print('MMYY')
elif sur <= 12 and sur > 0:
print('YYMM')
else:
print('NA')
|
8a68a12cf26f3156ca93b8137a448e1b6f92e31f | andresrv94/pydevelopercourse2020 | /catsclasses.py | 647 | 4.3125 | 4 | #Given the below class:
class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
# 1 Instantiate the Cat object with 3 cats
BagOfCats = []
BagOfCats.append(Cat("Milo", 5))
BagOfCats.append(Cat("Luke", 3))
BagOfCats.append(Cat("Olivia", 9))
# 2 Create a function that finds the oldest cat
maxage=0
for i in BagOfCats:
if i.age > maxage:
maxage = i.age
oldestcat = i.name
# 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2
print(f"The oldest cat is {maxage} years old and it\'s name is {oldestcat}.") |
50dbae68c3f5b3837df5a9b40f86556f04248ba9 | dundunmao/lint_leet | /mycode/leetcode_old/3 sort_binary_search/medium/81. Search in Rotated Sorted Array II.py | 1,294 | 4.03125 | 4 | # coding:utf-8
# 3级
# 题目:sorted但是rotate的list,比如[4,5,6,7,0,1,2]找一个target比如0.要考虑有重复的元素
#思路,就要要binary search,
def search(nums, target):
print nums
if target not in nums:
return -1
low, high = 0, len(nums)-1
while low <= high:
mid = (high+low)//2
print nums[low], nums[mid],nums[high]
if target == nums[mid]:
return True
################# before is the same as original one ###############
while low < mid and nums[low] == nums[mid]: # tricky part
low += 1 #为了把重复的前端去掉
################# after is the same as original one ###############
# the first half is ordered
if nums[low] <= nums[mid]:
# target is in the first half
if nums[low] <= target < nums[mid]:
high = mid - 1
else:
low = mid + 1
# the second half is ordered
else:
# target is in the second half
if nums[mid] < target <= nums[high]:
low = mid + 1
else:
high = mid - 1
return False
if __name__ == '__main__':
nums = [13,13,14]
target = 14
print search(nums, target) |
7f06d85825d1e1b6fa31a56d603b08cba854a1b2 | yunyusha/xunxibiji | /month1/week3/class7/oop2.py | 2,495 | 4.09375 | 4 | """
"""
class Person:
def __init__(self, **kw):
self.__name = kw['name']
self.__sex = kw['sex']
self.__age = kw['age']
self.__height = kw['height']
self.__weight = kw['weight']
@property
def name(self):
return self.__name
@property
def sex(self):
return self.__sex
@property
def age(self):
return self.__age
@property
def height(self):
return self.__height
@property
def weight(self):
return self.__weight
def introduce(self):
print('我叫%s,今年%d岁,性别%s,身高%d,体重%d' % (self.__name, self.__age, self.__sex, self.__height, self.__weight))
def jiaotan(self):
print('我们当前正在交谈')
"""
继承的语法格式
class 子类(父类)
pass
定义一个子类,继承子类一个指定的父类,注意:子类在继承父类时,会将父类所有特征和行为全部继承
子类从父类继承的所有方法的处理操作包括 照搬 ,重写,添加
"""
class Student(Person):
def __init__(self, **kw):
Person.__init__(self, **kw)
self.__sno = kw['sno']
self.__classroom = kw['classroom']
self.__major = kw['major']
self.__school = kw['school']
# 重写
# def introduce(self):
# print('我叫%s,今年%d岁,性别%s,身高%d,体重%d ,就读于%s,学号是%s,专业是%s' % (self.name, self.age, self.sex, self.height, self.weight, self.__school,self.__sno,self.__major))
# 添加(在原函数功能基础上重新添加一部分新的功能)
def introduce(self):
Person.introduce(self)
print("我目前就读于%s,专业是%s,班级是%s班,学号%s" % (self.__school, self.__major, self.__classroom,self.__sno))
stu = Student(name='冰冰', sex='女', age=23, height=110, weight=45, sno='11221122', major='播音主持', classroom='播音02', school='中央戏剧学院')
# stu.introduce()
# ren = Person(name='冰冰', sex='女', age='23', height=160, weight=45)
stu.introduce()
"""
子类从父类所继承的所有行为存在三种操作:
1.照搬: 直接通过子类对象调用从父类继承的方法
2.重写: 重新定义从父类继承的方法的实现,此过程可以实现面向对象
的多态操作, 多态, 同一个方法,不同对象在调用时执行结果不同,此过程称为方法的多态
3.添加: 从父类继承的方法在调用时,先通过父类调用该方法,之后在添加子类具体操作
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.