blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
afe0ef534b69888c879cae4ab334e9bccb71d9c2 | csutjf/autoprogramming | /findvalue.py | 536 | 3.96875 | 4 | import fileinput
from random import randint #for random threshold of filter
from functions import *
'''This script uses autowriting to modify the function calls and avoid the loop needed to find the optimum value
run python findvalue.py in terminal'''
opt=26
guess=0
guess=findOptimum(opt)
'''Once the optimum value has been found, the next run of this code would have O(1) complexity, since the function with the loop is no longer called'''
if(guess==opt):
print "Guess is optimum"
|
48e8863a460152f27ec8ed065d98f5dbc73891c7 | katryo/leetcode | /218-the-skyline-problem/solution2.py | 2,429 | 3.546875 | 4 | from typing import List
from heapq import heappush, heappop
class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
heap = []
LEFT = 0
RIGHT = 1
END = 10
events = []
for left, right, height in buildings:
left_event = [-height, left, LEFT, None]
right_event = [-height, right, RIGHT, left_event]
heappush(events, (left, left_event))
heappush(events, (right, right_event))
ans = []
while events:
x, event = heappop(events)
nega_height = event[0]
right_or_left = event[2]
if right_or_left == LEFT:
if not heap or nega_height < heap[0][0]:
ans.append([x, - nega_height])
heappush(heap, event)
else:
left_event = event[3]
left_event[3] = END
while heap and heap[0][3] == END:
# Removes the current largest which has finished
heappop(heap)
if heap:
if heap[0][0] > nega_height:
if ans and ans[-1][0] == x:
popped = ans.pop()
if popped[1] > - heap[0][0]:
continue
else:
ans.append([x, -heap[0][0]])
else:
ans.append([x, - heap[0][0]])
else:
ans.append([x, 0])
real_ans = []
# cur = 0
for elem in ans:
if real_ans and real_ans[-1][0] == elem[0] and real_ans[-1][1] <= elem[1]:
real_ans.pop()
real_ans.append(elem)
else:
real_ans.append(elem)
return real_ans
# s = Solution()
# print(s.getSkyline([[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]))
# print(s.getSkyline([[1, 2, 1], [1, 2, 2], [1, 2, 3]]))
# print(s.getSkyline([[6765, 184288, 53874], [13769, 607194, 451649], [43325, 568099, 982005], [
# 47356, 933141, 123943], [59810, 561434, 119381], [75382, 594625, 738524]]))
# print(s.getSkyline([[2, 9, 10], [9, 12, 15]]))
# print(s.getSkyline([[2, 9, 10], [3, 7, 15], [
# 5, 12, 12], [15, 20, 10], [19, 24, 8]]))
# print(s.getSkyline([[15, 20, 10], [19, 24, 8]]))
|
75c5c39070b4adaa01001c4078d1e86b4b0e732b | Say10IsMe/SVBA-ED | /Examen Unidad II-Inciso 3- Suarez Abraham.py | 3,009 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 6 01:10:26 2018
@author: pc
"""
#definimos el arreglo para la pila y el indice para las posiciones
listaregistros=[]
ind=1
#nuestro metodo para agregar registros
def ingresarregistro():
#declaramos la variable global para poder utilizarla aquí
global ind
#agregamos el registro con el mismo numero del indice
listaregistros.append(ind)
#incrementamos el valor del indice para almacenar el registro en la
#siguente posción
ind+=1
#desplegamos este mensaje y seguido la pila con los registros ingresados
print("\nSe ha agregado el registro:")
print(listaregistros)
#definimos el metodo obtener registro, lo que sería el POP de la pila
def obtenerregistro():
global ind
#definimos la condición para no hacer pop cuando la pila esta vacía
if (len(listaregistros)>0):
print("\nEl registro que será obtenido será el:")
print(listaregistros[len(listaregistros)-1])
del (listaregistros[len(listaregistros)-1])
print(listaregistros)
ind-=1
else:
print("La lista de registros se encuentra vacía!, inserte antes un registro a obtener")
#definmos el metodo de visualización, el cual mostrará todas las migraciones
#de la mas reciente a la mas antigua
def vertodosregistros():
#pero antes, compara la longitud de la pila, si esta es mayor de 0, es
#decir, si no esta vacía, procede con la impresión utilizando un ciclo
#for e imprimiendolos a la inversa en la que fueron ingresados
if (len(listaregistros)>0):
print("Las migraciones desde la mas nueva a la mas antigua:")
for i in range(len(listaregistros)):
print(listaregistros[len(listaregistros)-i-1])
#si la pila esta vacia, se despliega este mensaje al usuario
else:
print("La lista de migraciones esta vacía! no hay registros que mostrar")
#creamos nuestro metodo para el menu, llamado opciones
def opciones():
print("\nSi desea agregar una migracion, presione: 1")
print("Si desea obtener la migracion mas reciente, presione: 2")
print("Si desea ver todas las versiones, presione: 3")
print("Si desea salir del programa, presiones: 4")
s=int(input());
#comparamos la entrada del usuario con cada una de las opciones del menu
#y si hay coincidencia, ejecutamos el metodo deseado, además de usar
#recursividad para volver al menu de opciones, llamandolo despues de cada
#comparación
if (s==1):
ingresarregistro();
opciones();
if (s==2):
obtenerregistro();
opciones();
if (s==3):
vertodosregistros();
opciones();
#en el ultimo caso, no lloamamos al metodo de opciones ya que es la salida
if (s==4):
print ("\nQue tenga buen dia:D")
opciones();
|
76a43ad1106be8e70803625eb69e746d2f5a4113 | officialGanesh/Dollar-Exchange | /main.py | 1,512 | 3.828125 | 4 | # Import the required modules
import requests, json, os
base_url = "http://apilayer.net/api/live?"
access_key = os.getenv('currencyAPI')
end_point = f"{base_url}access_key={access_key}"
def main_function():
'''This function is used to get the json data and convert into python dictionary'''
try:
r = requests.get(end_point)
r.raise_for_status()
# print(r.status_code)
# load the json data
with open('CurrencyData.json','w') as f:
source = r.json()
f.write(json.dumps(source,indent=2))
# python dictionary
with open('CurrencyData.json','r') as f:
python_file = json.load(f)
def Display_data():
'''This function is used to display the required data'''
USD_INR = python_file['quotes']['USDINR']
# Rate of usd to inr or 1 dollar to inr
print(f"Current USDINR RATE --> {USD_INR}")
print('-----------------------------------------------')
def INR_USD():
'''Converting INR to USD'''
amount = eval(input('Enter the amount you like to convert into USD --> '))
usd = (1 / USD_INR) * amount
print(f'INR --> {amount}\n USD --> {usd}')
INR_USD()
Display_data()
except Exception as e:
print("Something Went Wrong 💢 ",e)
if __name__ == "__main__":
main_function()
print("Code Completed 🔥") |
a6058c0cfb99bf3958af0f1f05ea4bf9fe5a11a4 | Asad1o1/Roboprener | /Test_2.py | 451 | 4.25 | 4 | # Write a Python Program to find the two largest numbers in an array.
def find_largest(arr: list, n: int) -> list:
largest_number = []
for i in range(n):
arr.sort()
x = arr.pop(len(arr) - 1)
largest_number.append(x)
return largest_number
if __name__ == '__main__':
total_largest_number_to_find = 2
ar = [1, 2, 3, 7, 8, 9, 10, 11, 12, 14, 15, 25]
print(find_largest(ar, total_largest_number_to_find))
|
c786d545d03713d179d3d381dd2cf016f5448223 | Vitosh/AlgoTests | /abba1.py | 189 | 3.53125 | 4 | input_word = input()
input_target = input()
def a_to_end(input_word):
return input_word + 'A'
def b_to_end(input_word):
input_word = input_word[::-1]
return input_word + 'B'
|
4b23b20c70374163d5912baf20fe960b40467fa9 | liudandanddl/python_study | /leetcode/test.py | 11,057 | 3.78125 | 4 | #!/usr/bin/env python
# coding=utf-8
import Queue
__author__ = 'ldd'
def trailingZeroes(n):
"""
求阶乘结果尾部0的个数.0是由2*5所得,计算能被多少个5,25,125.。。。。整除
:type n: int
:rtype: int
"""
return 0 if n==0 else n/5 +trailingZeroes(n/5)
def twoSum(nums, target):
"""
从数组中查找两数相加=target,返回对应两数的下标。
:type nums: List[int]
:type target: int
:rtype: List[int]
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
"""
for i in range(0, nums.__len__(), 1):
find = target - nums[i]
if find in nums:
print(find, nums)
j = nums.index(find)
if i != j:
return i, j
return
def threeSum(nums):
'''
先升序排序,然后用第一重for循环确定第一个数字。然后在第二重循环里,第二、第三个数字分别从两端往中间扫。时间复杂度:O(n2)
如果三个数的sum等于0,得到一组解。如果三个数的sum小于0,说明需要增大,所以第二个数往右移。如果三个数的sum大于0,说明需要减小,所以第三个数往左移。
:type nums: List[int]
:rtype: List[List[int]]
'''
res = []
length = len(nums)
if length < 3:
return res
nums.sort()
for i in range(length):
if nums[i] > 0: # 第一个数大于0
break
if i > 0 and nums[i] == nums[i-1]: # 重复元素不重复计算
continue
begin = i+1
end = length-1
while begin < end:
sum = nums[i]+nums[begin]+nums[end]
if sum == 0:
tmp = [nums[i], nums[begin], nums[end]]
res.append(tmp)
begin += 1
end -= 1
while begin < end and nums[begin] == nums[begin-1]:
begin += 1
while begin < end and nums[end] == nums[end+1]:
end -= 1
elif sum > 0:
end -= 1
else:
begin += 1
return res
def reverse(x):
'''
有符号23位整数的反数
如123 rew=321 -123 res=-321 120res=21
'''
a = int(str(abs(x))[::-1])
if x <0:
a = -a
if (pow(-2,31)<= a <= pow(2,31)): # 有符号32位整数的取值范围
return a
return 0
def reverse1(x):
'''
:param x:int
:return: bool
判断一个整数是否是回文数,负数不是回文数。不开辟额外的空间。
'''
if x == 0:
return True
if (x<0) or (x%10==0):
return False
res = 0
temp = x
while(temp>0): # 利用取模方式将数反转
res *=10
i = temp % 10
temp = temp /10
res +=i
return True if x==res else False
def isValid(s):
"""
输入是['(', '[', '{']或者[')', ']', '}'],判断括号使用是否合法
:type s: str
:rtype: bool
"""
q = Queue.LifoQueue() # 先进后出队列
for ele in s:
if ele in ['(', '[', '{']:
q.put(ele) # 元素从右侧插入队列
if ele in [')', ']', '}']:
if q.empty(): # 判断队列是否为空
return False
if ele == ')' and q.get()!='(': # q.get()从队列尾部获取元素,并从队列中删除该元素
return False
if ele == '}' and q.get()!='{':
return False
if ele == ']' and q.get()!='[':
return False
if not q.empty():
return False
return True
def maxSubArray(nums):
"""
动态规划问题
求数组的最大子串和。常规办法:for循环两边,第一遍遍历子串头,在内部遍历子串尾,算出所有子串和。
eg:[59, 26, -53, 58, 97, -93, -23, 84] res=187, [59, 26, -53, 58, 97]
[-2,1,-3,4,-1,2,1,-5,4] res=6, [4, -1, 2, 1]
:type nums: List[int]
:rtype: int
"""
if nums.__len__() == 0:
return 0
max_end = nums[0] # 目前最大值
max_far = nums[0] # 已知最大值
res_end = [nums[0]]
res_far = [nums[0]] # 最终结果的子序列
for temp in nums[1:]:
print(temp, max_far, max_end, res_far, res_end)
if max_end < 0: # 累加失败,重新开始
max_end = temp
res_end = [temp]
else:
max_end += temp
res_end.append(temp)
max_far = max(max_end, max_far)
if max_far == max_end:
res_far = []
for temp in res_end:
res_far.append(temp)
return max_far, res_far
def mySqrt(x):
'''
用二分法求一个数的最近平方根
对于一个非负数n,它的平方根不会大于n/2+1
eg:4 res=2 ; 8 res=2 ; 9 res=3 ; 15 res=3 ; 16 res=4
'''
left = 1
right = x/2+1
if x in [0, 1]:
return x
while left < right-1: # 比如输入35, 最后一次left=5 right=7 mid=6 经过while更改值之后left=6 right=7,不需要在while了,res肯定6或7
mid = (left + right)/2
print(left, right, mid)
if mid == x / mid:
return int(mid)
if mid > x / mid:
right = mid
else:
left = mid
res = right if right*right<x else right-1
return res
def countPrimes(n):
"""
计算比n小的素数的个数
:type n: int
:rtype: int
厄拉多塞筛法:先将 2~n 的各个数放入表中,然后在2的上面画一个圆圈,然后划去2的其他倍数;
第一个既未画圈又没有被划去的数是3,将它画圈,再划去3的其他倍数;
现在既未画圈又没有被划去的第一个数 是5,将它画圈,并划去5的其他倍数……
依次类推,一直到所有小于或等于 n 的各数都画了圈或划去为止。这时,表中画了圈的以及未划去的那些数正好就是小于 n 的素数。
当你要画圈的素数的平方大于 n 时,那么后面没有划去的数都是素数,就不用继续判了
"""
# if n < 2:
# return 0
# ditA = dict.fromkeys(range(2, n, 1), True) # 默认都是素数
# for key in range(2, int((n-1)**0.5)+1, 1):
# if ditA[key]:
# for i in range(2*key-1, n, 1):
# if i % key == 0:
# ditA[i] = False
# return sum(ditA.values())
# 上面算法效率较低
if n < 3:
return 0
primes = [True]*n # 默认所有小于n的都是素数
primes[:2] = [False, False] # primes[0],primes[1]就是数字0和1,都不是素数
for base in xrange(2, int((n-1)**0.5)+1): # 当你要画圈的素数的平方大于 n 时,那么后面没有划去的数都是素数,就不用继续判了
if primes[base]:
primes[pow(base, 2)::base] = [False] * len(primes[pow(base, 2)::base]) # base的倍数都不是素数.巧用分片赋值操作。
return sum(primes) # 素数是True,是1,非素数是0,求和即可
def isUgly(num):
"""
判断一个数能否被2、3、5整除
:type num: int
:rtype: bool
"""
if num <=0:
return False
if num == 1:
return True
if num % 2 == 0:
return isUgly(num/2)
if num % 3 == 0:
return isUgly(num/3)
if num % 5 == 0:
return isUgly(num/5)
return False
def moveZeroes(nums):
"""
将数组的所有0移到后面。必须在不复制数组的情况下完成此操作。最小化操作总数
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]
"""
a = len(nums)
for i in range(0, a, 1):
temp = nums[i]
if temp == 0:
nums.append(0)
nums.remove(temp) # 移除列表中某个值的第一个匹配项,修改列表无返回值。
def removeDuplicates(nums):
"""
不增加额外空间,原地删除一个有序数组的重复元素,返回新数组的个数。
Given nums = [1,1,2],return length = 2, with the first two elements of nums being 1 and 2 respectively。
It doesn't matter what you leave beyond the new length.
:type nums: List[int]
:rtype: int
"""
if nums == []:
return 0
j = 0
for i in range(1, len(nums), 1):
if nums[j] != nums[i]:
nums[j+1] = nums[i]
j = j+1
# for i in nums[j+1:]:
# nums.remove(i) 多余的重复元素在原地删除
print(nums)
return j+1
def isToeplitzMatrix(matrix):
'''
从左上角到右下角的每个对角线上的元素是否相等
对角线遍历,注意对角线的性质:当前元素为matrix[i][j],下一元素为matrix[i+1][j+1]
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: True
Explanation:
1234
5123
9512
In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]",
and in each diagonal all elements are the same, so the answer is True.
'''
n = len(matrix)
m = len(matrix[0])
for i in range(0, n-1, 1):
for j in range(0, m-1):
if matrix[i][j] != matrix[i+1][j+1]:
return False
return True
def rotate(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
原地反转一个数组,For example, k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]
"""
nums[:k], nums[k:] = nums[len(nums)-k:], nums[:len(nums)-k]
def getSum(a, b):
"""
位操作计算整数加法
:type a: int
:type b: int
:rtype: int
既然不能使用加法和减法,那么就用位操作。下面以计算5+4的例子说明如何用位操作实现加法:
1. 用二进制表示两个加数,a=5=0101,b=4=0100;
2. 用and(&)操作得到所有位上的进位carry=0100;
3. 用xor(^)操作找到a和b不同的位,赋值给a,a=0001;
4. 将进位carry左移一位,赋值给b,b=1000;
5. 循环直到进位carry为0,此时得到a=1001,即最后的sum。
因为Python的整数不是固定的32位,所以需要做一些特殊的处理。代码里的将一个数对0x100000000取模(注意:Python的取模运算结果恒为非负数),
是希望该数的二进制表示从第32位开始到更高的位都同是0(最低位是第0位),以在0-31位上模拟一个32位的int。
"""
while b != 0:
carry = a & b
a = (a ^ b) % 0x100000000
b = (carry << 1) % 0x100000000
return a if a <= 0x7FFFFFFF else a | (~0x100000000+1)
if __name__ == "__main__":
# [4,-1,2,1] has the largest sum = 6.
# [-2,1,-3,4,-1,2,1,-5,4] 187
# [59, 26, -53, 58, 97, -93, -23, 84]
# print(maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
print(countPrimes(120)) # 30
|
23a8a1b5f82bb4fb4f9612064747f939468c9583 | lachlankuhr/AdventOfCode2017 | /5/part2.py | 408 | 3.65625 | 4 | import numpy as np
array = np.loadtxt("input.txt")
index = 0
counter = 0
# my poor little laptop doesn't like this :(
while (index < len(array)):
value = array[int(index)]
if value >= 3:
array[int(index)] = array[int(index)] - 1
else:
array[int(index)] = array[int(index)] + 1
index = index + value
counter = counter + 1
print("It took {} steps.".format(counter))
|
fe2fa9d08c08b441549b567e47bf95d733620a54 | tathagata-c/everyday-tools | /ip_finder.py | 1,567 | 3.671875 | 4 | import re
import os
# Define regex to find any pattern of an IPv4 address pattern.
r = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
# Function to validate if the IPv4 address is valid or not.
# Each octet should be a number between 0 - 255 for it to be valid IPv4 address.
def validate_ip(ip):
s = ip.split('.')
for x in s:
y = int(x)
if y < 0 or y > 255:
return False
return True
# Initialize list to store valid IPv4 addresses.
ip_list = []
# Parse through the directories recursively to identify files.
# Give the path of the parent directory that you want to scan recursively in 'os.walk'
for root, dirs, files in os.walk("/home/user"):
for name in files:
# Open the files in READ mode using the absolute path of the file in each loop/recursion.
input_file = os.path.abspath(os.path.join(root, name))
f = open(input_file, 'r')
lines = f.readlines()
# Parse each file one line at-a-time and match regex of IPv4 address pattern.
for line in lines:
i = r.findall(line)
# For any IPv4 address pattern match, check if the IP is valid and if already exists in our list.
# If the IP is valid and is not a duplicate entry, append it to our list of stored IPv4 addresses.
for ip in i:
if ip is not None and validate_ip(ip) is True and ip not in ip_list:
ip_list.append(ip)
f.close()
# The sorted() function automatically sorts the IP addresses lexicographically using the first octet.
s = sorted(ip_list)
# Join and print the sorted list.
output = '\n'.join(s)
print output |
451c444ede997f040e9fae046b6ee396990ad38e | BalaIyyappan/Guvi-Tasks | /Task-Completed/Area of triangle.py | 188 | 3.984375 | 4 | 14. Write a program to enter base and height of a triangle and find its area.
SOL:
b=int(input("Enter Base:"))
h=int(input("Enter Height:"))
area=(h*b)*0.5
print("Area of triangle:",area)
|
116e63c75023b2bec36e5a0cc9ce30de2bfb5efa | ploew/uebungsaufgaben | /BA1l.py | 495 | 3.625 | 4 |
pattern="GAA"
def PatternToNumber(pattern):
if pattern == '':
return 0
return 4 * PatternToNumber(pattern[0:-1])+ SymbolToNumber(pattern[-1:])
def SymbolToNumber (symbol):
if symbol == "A":
return 0
if symbol == "C":
return 1
if symbol == "G":
return 2
if symbol == "T":
return 3
print(PatternToNumber(pattern))
|
f5deb0fc5e34cdc8483b17c5a4a947763d582efa | maxim371/OOP_Zoo | /OOP_Zoo/tests.py | 1,543 | 3.59375 | 4 | import unittest
from .animals import Animal, Doggo, Iguana, Human
class TestAnimals(unittest.TestCase):
def setUp(self) -> None:
self.anim = Animal('Anim', 40)
self.dog = Doggo('Watson', 11)
self.lizi = Iguana('Lizi', 3)
self.human = Human('Human', 40, 'Coding')
def test_init(self):
self.assertTrue(isinstance(self.anim, Animal))
self.assertEqual(self.anim.name, 'Anim')
self.assertEqual(self.anim.age, 40)
self.assertEqual(self.human.name, 'Human')
def test_move_up(self):
self.assertEqual(self.anim.position, 0)
self.anim.move_up()
self.assertEqual(self.anim.position, 1)
def test_move_down(self):
self.assertEqual(self.anim.position, 0)
self.anim.move_down()
self.assertEqual(self.anim.position, -1)
def test_speak(self):
self.assertEqual(self.dog.speak(), f"{self.dog.name} says 'I think you're so heckin' great! Woof.'")
self.assertEqual(self.human.speak(), f'My name is {self.human.name}, I am {self.human.age} years old, '
f'and I like to do {self.human.hobby}.')
def test_hiss(self):
self.assertEqual(self.lizi.speak(), f'{self.lizi.name} says "Hiss."')
def test_hair(self):
self.assertTrue(self.dog.hair)
self.assertFalse(self.lizi.hair)
def test_scales(self):
self.assertTrue(self.lizi.scales)
self.assertFalse(self.dog.scales)
if __name__ == "__main__":
unittest.main()
|
26f81bdf0656a3912e8d7e0e690c13510cc56a30 | optionalg/programming-introduction | /Aula 07/Aula7-Lab-10.py | 389 | 3.71875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Aula 7
# Laboratório
# Exercício 10
# Autor: Lucien Constantino
def deltaPressure(target, current):
return target - current
targetPressure = int(input())
currentPressure = int(input())
assert deltaPressure(30, 18) == 12
assert deltaPressure(27, 27) == 0
assert deltaPressure(27, 30) == -3
print (deltaPressure(targetPressure, currentPressure))
|
057620ebdf9939f7b729748235756e29f1cab1d5 | UWPCE-PythonCert-ClassRepos/Wi2018-Online | /students/Gorthi_kavita/4module/4Mailroom.py | 5,409 | 3.640625 | 4 |
ltn =[] # user entered donar names with duplicate name
lt = [] #donar names,amount of the donars with duplicate names
ldupname = [] # all the names of the donar with duplicates names
luniname = [] # no duplicate names
lcountname = [] #this will count the names how many times donar donated
lfinal = []
lfinalname_amount_count = [] #this is final list of names ,total amount,number of times donated and average amount
ldonationlistentered = []
def flist(x,y):
name = x
amount = y
c =(name,amount,1)
lt.append(c)
def fdonate():
x = input("enter name : ")
y = input("enter amount: ")
y1 = int(y)
c = (x,y1,1)
c1 =(x,y1)
ldonationlistentered.append(c1)
ltn.append(c)
fask()
def fask():
print("do you want donate: y/n")
c1 = input("enter ")
if(c1 =='y' or c1 == 'Y'):
fdonate()
def fappend():
for i in ltn:
lt.append(i)
def fdupname():
for i in lt:
ldupname.append(i[0])
def funiname():
luniname = set(ldupname)
return list(luniname)
def fsumcount():
ltuni = funiname()
for i in ltuni:
lcount = 0
lsum = 0
for j in lt:
if(i == j[0]):
lsum = lsum +j[1]
lcount = lcount+j[2]
ln = i
lm = lsum
lc = lcount
c =(ln,lm,lc)
lfinal.append(c)
def fcountname():
from collections import Counter
count_names = Counter(ldupname)
for i in count_names:
n = i
c = count_names[i]
f = (n, c)
lcountname.append(f)
def ffinal():
for i in lcountname:
for j in lfinal:
if(i[0] == j[0] and i[1]== j[2]):
ln = i[0]
lm = j[1]
lc = i[1]
lv = int(lm/lc)
c =(ln,lm,lc,lv)
lfinalname_amount_count.append(c)
def ftablehead():
print("+----------------------------+------------------+-------------------+-------------------+")
print("| Donar Name | Total given | Number of gifts | Average gift |")
print("+----------------------------+------------------+-------------------+--------------------")
def ffinalreport(x):
lt = x
for i in lt:
name = i[0].upper()
total = '$'+str(i[1])
avg = i[2]
avgtotal ='$'+str(i[3])
print("{: >20} {: >20} {: >20}{: >20}".format(name, total, avg, avgtotal))
def ffinaln_m_cl(x):
lt = set(x)
print(lt)
def fdata():
flist("mike",100)
flist("praveen",231)
flist("praveen",35)
flist("mike",50)
flist("ravi",300)
flist("praveen",4)
flist("kelly",5)
flist("mark zack hio",1.5)
flist("joy",20007)
def fall():
fask()
fdata()
fappend()
fdupname()
fsumcount()
fcountname()
ffinal()
ftablehead()
ffinalreport(lfinalname_amount_count)
print("Menu:")
print("1.Send thank you mail")
print("2.Create report")
print("3.quit")
i = int(input("enter your choice 1 or 2 or 3: "))
if(i == 1):
print("Thank you")
print("1.Do you want to see the donars list")
print("2.Do you want to donate ")
print("3.quit")
k = int(input("enter your choice 1 or 2 or 3: "))
if(k == 1):
fdata()
fappend()
fdupname()
fsumcount()
fcountname()
ffinal()
luni = funiname()
print("The list of donars")
for i in luni:
print("{: >20}".format(i.upper()))
elif(k == 2):
fall()
l = ldonationlistentered
for i in l:
a = '4'+i[0].upper()
b = '$'+str(i[1])
c = i[0].upper()
file = open("{}"".txt".format(a),'a+')
file.write(" Dear ""{}".format(c))
file.write("\n")
file.write(" \n")
file.write(" Thank you for your very kind donation of ")
file.write("{}".format(b))
file.write(".\n")
file.write("\n")
file.write(" It will be used for very good cause.")
file.write("\n")
file.write(" Sincerely, \n")
file.write(" -The Team ")
file.close
elif(i == 2):
fdata()
fappend()
fdupname()
fsumcount()
fcountname()
ffinal()
ftablehead()
ffinalreport(lfinalname_amount_count)
print("DO you like to send thank you mail to donars")
print("Enter y/n")
i = input("enter ")
if(i == 'Y' or i == 'y'):
for i in lfinalname_amount_count:
a = '4'+i[0].upper()
b = '$'+str(i[1])
c = i[0].upper()
file = open("{}"".txt".format(a),'a+')
file.write(" Dear ""{}".format(c))
file.write("\n")
file.write(" \n")
file.write(" Thank you for your very kind donation of ")
file.write("{}".format(b))
file.write(".\n")
file.write("\n")
file.write(" It will be used for very good cause.")
file.write("\n")
file.write(" Sincerely, \n")
file.write(" -The Team ")
file.close
|
66d8a36d1676d5a2bd5f8e8afd11f87973f1ca49 | Tracyee/visualization-of-gaussian-bayes-classifier | /gaussian.py | 1,714 | 3.546875 | 4 | import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
class BivariateGauss:
def __init__(self, X, Y, mu, Sigma):
self.X = X
self.Y = Y
self.mu = mu
self.Sigma = Sigma
# Pack X and Y into a single 3-dimensional array
self.pos = np.empty(self.X.shape + (2,))
self.pos[:, :, 0] = self.X
self.pos[:, :, 1] = self.Y
def multivariate_gaussian(self):
"""
Return the multivariate Gaussian distribution on array pos.
pos is an array constructed by packing the meshed arrays of variables
x_1, x_2, x_3, ..., x_k into its _last_ dimension.
"""
n = self.mu.shape[0]
Sigma_det = np.linalg.det(self.Sigma)
Sigma_inv = np.linalg.inv(self.Sigma)
N = np.sqrt((2*np.pi)**n * Sigma_det)
# This einsum call calculates (x-mu)T.Sigma-1.(x-mu) in a vectorized
# way across all the input variables.
fac = np.einsum('...k,kl,...l->...', self.pos-self.mu, Sigma_inv, self.pos-self.mu)
return np.exp(-fac / 2) / N
def in_test():
# Our 2-dimensional distribution will be over variables X1 and X2
N = 60
X1 = np.linspace(-3, 3, N)
X2 = np.linspace(-3, 4, N)
X1, X2 = np.meshgrid(X1, X2)
# Mean vector and covariance matrix
mu = np.array([0., 1.])
Sigma = np.array([[ 1. , -0.5], [-0.5, 1.5]])
fig, ax = plt.subplots()
gauss = BivariateGauss(X1, X2, mu, Sigma)
Z = gauss.multivariate_gaussian()
CS = ax.contour(X1, X2, Z, colors='0.4')
ax.clabel(CS, inline=1, fontsize=10)
plt.show()
if __name__ == "__main__":
in_test()
|
c7edc98fc235dc223fa7ad95fbf128aec1b61347 | ramya-kiran/Connect-four-game | /board.py | 3,784 | 3.78125 | 4 | # Board class implements some of the basic functionalities of a connect four board.
import numpy as np
class Board:
# initializing the board with a stack to keep track of the remaining moves
# and a list to keep the board state.
def __init__(self):
self.stack = []
for i in range(7):
self.stack.append([])
for j in range(6):
self.stack[i].append([j, i])
self.lst = np.zeros((6, 7))
self.turn = 1
self.value = None
self.list_moves = []
self.count = 0
# Generates all the allowed possible moves using the stack.
def generate_moves(self):
place = []
for i in range(7):
if self.stack[i]:
place.append(self.stack[i][-1][1])
return place
# makes a move which is given to this function, and changes the turn of
# the player.
def make_move(self, move):
# implement allowed moved concept
if self.stack:
row, col = self.stack[move].pop()
self.lst[row, col] = self.turn
self.list_moves.append([row, col])
self.turn = -self.turn
else:
pass
# unmake a move that has been made, and changes the board states to the
# previous move state.
def unmake_last_move(self):
if self.list_moves:
r, c = self.list_moves[-1]
self.lst[r, c] = 0
self.stack[c].extend([[r, c]])
self.turn = -self.turn
self.list_moves.pop()
else:
pass
# This function checks if the last move won. It generates the horizontal, vertical, and diagonal elements and scans it
# to find 4 plays together.
def last_move_won(self):
if not self.list_moves:
return False
else:
r, c = self.list_moves[-1]
play = self.lst[r, c]
# horizontal +ve direction
hx1 = self.scan(play, r, c, 0, 1)
# horizontal -ve direction
hx2 = self.scan(play, r, c, 0, -1)
# vertical +ve direction
vy1 = self.scan(play, r, c, -1, 0)
# vertical -ve direction
vy2 = self.scan(play, r, c, 1, 0)
# diagonal in 45 degrees
dd1 = self.scan(play, r, c, -1, 1)
# diagonal in 135 degrees
dd2 = self.scan(play, r, c, -1, -1)
# diagonal in 225 degrees
dd3 = self.scan(play, r, c, 1, -1)
# diagonal in 315 degrees
dd4 = self.scan(play, r, c, 1, 1)
horizontal = hx1 + hx2
vertical = vy1 + vy2
diagonal1 = dd1 + dd3
diagonal2 = dd2 + dd4
if play == 1:
if (sum(horizontal) >= 5 * play) or (sum(vertical) >= 5 * play) or (sum(diagonal1) >= 5 * play) \
or (sum(diagonal2) >= 5 * play):
return True
else:
return False
elif play == -1:
if (sum(horizontal) <= 5 * play) or (sum(vertical) <= 5 * play) or (sum(diagonal1) <= 5 * play) \
or (sum(diagonal2) <= 5 * play):
return True
else:
return False
else:
print("No valid player")
# This function is to just display the board state
def __str__(self):
# return self.lst, self.stack
return str(self.lst) + ":" + str(self.stack)
# scanning is used by last_move_won function.
def scan(self, play, x, y, dx, dy):
checking = []
while (0 <= x < 6) and (0 <= y < 7) and self.lst[x, y] == play:
checking.append(self.lst[x, y])
x = x + dx
y = y + dy
return checking
|
7e6057895343c2aafb0b4a2d9a0ab68894fdcb2c | AndyRachmat27/LihatApa- | /Kategori Usia.py | 332 | 3.890625 | 4 | print ("Program Usia")
#input data
usia = int(input("Masukkan usia : "))
#Rumus
if usia < 5 :
print ("Toddler")
elif 6 < usia < 12 :
print ("Kids")
elif 13 < usia < 20 :
print ("Teenager")
elif 21 < usia < 40 :
print ("Young")
elif 41 < usia < 60 :
print ("Adult")
if usia > 60 :
print ("Old") |
05cb1521168d0320f080cd8c25137ea9ef6e91b9 | dindamazeda/intro-to-python | /lesson2/exercises/3.number-guessing.py | 821 | 4.1875 | 4 | # Create list of numbers from 0 to 10 but with a random order (import random - see random module and usage)
# Go through the list and on every iteration as a user to guess a number between 0 and 10
# At end the program needs to print how many times the user had correct and incorrect guesses
# random_numbers = [5, 1, 3, 9, 7, 2, 4, 6, 8]
# program: Guess a number between 0 and 10.
# (If we look at the above list the current number is 5) user: 8
# program: That is not a correct number. Try to guess a new number between 0 and 10.
# (If we look at the above list the next number is 1) user: 1
# program: Bravo! That is the correct number. Try to guess a new one.
# The program continues until the end of the list...
# program: Congratulations. You've guessed the correct number 3 times and 7 times you were not correct. |
f6a2fa59297411fb2987cdb5afb0dcbf8a855804 | kavinandha/kavipriya | /prg53.py | 119 | 3.96875 | 4 | n1=int(input("enter the num1:"))
n2=int(input("enter the num2:"))
n3=int(input("enter the num3:"))
n=n1+n2+n3
print(n)
|
35346551a5839520a3e1b07783ea39781c9883bc | tburcham/codepoetry | /dicts.py | 336 | 3.96875 | 4 | person = {
"first_name": "Karl",
"last_name": "Marx",
"age":235,
"pet": {
"name":"Proleterry",
"species": "parrot",
"age": 12
}
}
print(person)
print(person["age"])
print(person.get("abc")) # returns a truthy/falsy None if not found
for key in person:
print(key)
print(person[key])
|
f2aa66377636a32c7f74f5dfbd7589833f4035d4 | cica-mica/domaci01 | /1.1_zadatak.py | 479 | 3.859375 | 4 | """
1. Napisati kod koji za date katete a i b (a>b) pravouglog trougla racuna povrsinu i zapreminu tijela koje se dobija rotacijom trougla
oko manje katete.
"""
import math
# rotacijom trougla oko katete b dobija se kupa s poluprecnikom a i visinom b
a = 8
b = 6
# racunamo duzinu hipotenuze jer ce nam biti potrebna pri racunanju povrsine
c = math.sqrt(a*a + b*b)
P = math.pi * math.pow(a,2) + c*a* math.pi
V = (math.pow(a,2)*b* math.pi)/3
print(P)
print(V) |
31649b7f357b54c05f4fa17054a01aacedf15c50 | cationly/Huckel-Energy | /scripts/hamiltonian.py | 10,281 | 3.859375 | 4 | '''
This is a class to implement a Hamiltonian
variable parameters (now, up to 2)
'''
class hamiltonian:
def __init__(self):
'''
We simulate the hamiltonian as an array. The action of a "2D array"
is replicated by a 1D array and knowledge of the hamiltonian size.
This should be faster, although in reality other things will
probably kill the speed before array access, but it's nice to be
efficient....
'''
self.elements = [] # The actual elements of the hamiltonian
self.size = 0 # The dimension of the hamiltonian
self.tokens = [] # list of the tokens to be used
self.tokenLocs = {} # a map of token "names" to their locations within H
self.tokenRange = {} # map of token names to a list of form [start,stop,step]
def parse(self):
'''
Parse in the hamiltonian from the command line
'''
# we have to reinitialise everything from scratch
self.elements = []
self.size = 0
self.tokens = []
self.tokenLocs = {}
self.tokenRange = {}
tokenString = raw_input('Token declarations: ')
#if len(tokenString.split()) == 0:
# while len(tokenString.split()) > 2 or len(tokenString.split()) == 0:
# print('invalid number of token declarations (1 or 2)')
# tokenString = raw_input('\nToken declarations: ')
for token in tokenString.split():
self.tokens.append(token) # add it to our list of tokens
self.tokenLocs[token] = [] # initialise our location dictionary
self.tokenRange[token] = [] # initialise range dicionary
# prompt user for hamSize, set size
while True:
try:
hamSize = raw_input('\n Hamiltonian size: ')
self.size = int(hamSize)
if self.size == 0:
print '\ninvalid size passed'
continue
except ValueError:
hameSize = raw_input('\n invalid size passed, choose again: ')
continue
else:
break
# prompt for hamiltonian
print '\n\nInput hamiltonian matrix:\n '
# iterate SIZE times
for row in range(self.size):
while True: # must make sure we have a valid line
errVal = False # is there an INvalid entry in the line?
hamLine = raw_input()
if len(hamLine.split()) == self.size:
for entry in hamLine.split():
try:
float(entry)
except ValueError: # the value is *not* a number
if(entry not in self.tokens): # and *not* a token
print "\nundefined token passed,\
re-enter line: "
errVal = True # entry is invalid...
break # one invalid input ruins the line
if(errVal): # entry is invalid so we cycle and ask for
continue # input again
else:
for entry in hamLine.split():
try:
self.elements.append(float(entry))
except ValueError: # if it is a token
self.elements.append(0.0) # could have put anything
self.tokenLocs[entry].append(len(self.elements)-1)
# the -1 accounts for the fact we start @ 0
break
else:
print "\ninvalid number of elements passed,\
re-enter line: "
continue
# print spaces to niceify input
print(' ')
# prompt user for start,stop and step values
for token in self.tokens:
errVal = False
print('enter start,stop and step values for token "'+token+'" :')
while True:
loop_vals = raw_input()
if(len(loop_vals.split()) != 3):
print '\ninvalid number of inputs, re-enter: '
continue
for value in loop_vals.split():
try:
float(value)
except ValueError:
print'\nnon-numeric input, re-enter: '
errVal = True
break
if(errVal):
continue
else:
if float(loop_vals.split()[0]) > float(loop_vals.split()[1]):
print '\ninvalid range, re-enter all values: '
continue
elif float(loop_vals.split()[2]) == 0:
print '\ninvalid step value, re-enter all values: '
continue
for value in loop_vals.split():
self.tokenRange[token].append(value)
break
if(not(self.symmetric())):
print 'asymmetric hamiltonian parsed: please re-enter\n'
self.parse()
def symmetric(self):
'''
Test for a symmetric hamiltonian
'''
# iterate over upper triangle (minus the leading diagonal)
# i = 0 --> N-2
# j = i+1 -->N-1
# test that ham[i][j] == ham[j][i]
# i.e. ham[i*size + j] == ham[j*size + i]
# if not then return false
#for token in self.tokens:
# if(len(self.tokens[token]) % 2 != 0):
# return False # if the number of token entries for any given
# # token is not even then cannot be symmetric
for token in self.tokens:
for position in self.tokenLocs[token]:
row = position / self.size # find the "row" of the element
col = position % self.size # "column" of the element
if col*self.size + row not in self.tokenLocs[token]:
return False # this is just taking the transpose
# i.e. if the element's transposed position is not also the
# same token then the hamiltonian cannot be symmetric
# NB: even though the embedded loop is slower, it means it is more
# evident what we are doing: also enables us to easily only choose
# the upper triangle to iterate through - making it faster overall
for row in range(self.size -1): # now check numerical values
for col in range(row+1, self.size):
if self.elements[row*self.size + col]\
== self.elements[col*self.size + row]:
continue
else:
return False
return True
def assign(self,token,value):
'''
assign the elements in 'token' to 'value'
'''
# iterate through tokenLocs(token)
# for each location, assign value to ham[loc]
if token not in token:
raise LookupError
elif value < 0:
raise ArithmeticError
for location in self.tokenLocs[token]:
self.elements[location] = value
def filePrint(self,fileName):
'''
Print the hamiltonian to a file in a format compatible with
the huckel_energy program.
'''
# open file
# print size
# for i in sequence 0 --> size-1
# for j in sequence 0 --> size-1
# print ham[i*size + j]
# print "\n"
# close file
try:
hamFile = open(fileName,'w')
hamFile.write(str(self.size)+'\n')
#NB: I do not know whether embedded loops or a single loop with
# an IF statement would be more efficient. I think that the loops
# would be more inefficient, as python would use more stack to
# keep the loop variables in scope, whereas IF statements are cheap
for row in range(self.size):
for col in range(self.size):
hamFile.write(str(self.elements[row*self.size + col])+' ')
hamFile.write('\n')
hamFile.close()
return 0
except TypeError: # invalid filename type (not string) passed
return 1
def getTokenVal(self,string):
'''
Return a list of the values of the tokens in the hamiltonian
'''
# if string in tokens
# return ham[tokenLocs[string][0]]
# else
# return BADNUM
if string in self.tokens:
return self.elements[self.tokenLocs[string][0]]
else:
raise LookupError
def getTokenRange(self,string):
'''
Return a list of form [start,stop,step] for token "string"
'''
# if string in tokens
# return tokenRange[string]
# else
# return BADNUM
if string in self.tokens:
return self.tokenRange[string]
else:
return [] # the empty list
def getTokens(self):
return self.tokens
def getElement(self,i,j):
'''
Return element i,j of the hamiltonian. The "-1"s are an offset so
that the user can have a 1-based as opposed to 0-based index for
compatability with standard mathematical notation
'''
if(self.size == 0):
raise ArithmeticError
elif((i-1)*self.size + (j-1) > self.size*self.size -1):
raise LookupError
else:
return self.elements[(i-1)*self.size + (j-1)]
|
a8d044d7db5cb6c0980dd69f582fb1a9ac34a6e5 | LizaPleshkova/PythonLessonsPart2 | /venv/lessons/5.py | 841 | 3.859375 | 4 | '''
Entry - созздает однострочное текстовое поле, в которое пользователь может вводить какие-то данные,
так же и для вывода информации для пользователя
'''
from tkinter import *
def add_str():
e.insert(END,'Hello!')
def del_str():
e.delete(0,END)
def get_str():
l_text['text'] = e.get()
root = Tk()
root.geometry('600x400+500+200')
l = Label(root, text='Input text')
l.pack()
e = Entry(root)
e.insert(0,'Hello')
e.insert(END, ' world!')
e.pack()
l_text = Label(root, bg='blue', fg='#fff')
l_text.pack(fill=X)
btn_add = Button(root, text='add', command=add_str).pack()
btn_del = Button(root, text='del', command=del_str).pack()
btn_get = Button(root, text='get', command=get_str).pack()
root.mainloop() |
148478f52edb188a8a12d87bde52eb6e247cfd85 | OnlyLoveLin/studentManageProject | /referTool.py | 9,121 | 3.5 | 4 | # 这是一个查询文件
# 导入需要的模块
import Io
# 定义一个查询学生基本信息主界面
def referMainMenu():
while True:
print("------------------------------------")
print("\t教师客户端")
print("\t\t1.按照学生的编号查询")
print("\t\t2.按照学生的名字查询")
print("\t\t3.按照学生的班级查询")
print("\t\t4.查询所有学生")
print("\t\t5.退出")
print("------------------------------------")
c = input("请输入您的选项:")
if c == '1': # 按照学生的编号查询
stuReferIdBaseMessage()
elif c == '2': # 按照学生的名字查询
stuReferNameBaseMessage()
elif c == '3': # 按照学生的班级查询
stuReferClassBaseMessage()
elif c == '4': # 查询所有学生
stuReferBaseMessage()
elif c == '5': # 退出
break
else:
input("没有这个选项,请重新输入!")
# 定义一个从编号查询学生基本信息的函数
def stuReferIdBaseMessage():
try:
stuList = Io.StudentIo().read_student()
except:
return print("请先添加学生!")
# 从键盘读取信息
stuId = input("请输入你想要查询的学生编号:")
if len(stuList) > 0:
# 遍历列表
for s in stuList:
if s.stu_id == stuId:
print("编号:%s--姓名:%s--年龄:%s--性别:%s--家庭住址:%s--班级:%s" \
%(s.stu_id,s.stu_name,s.stu_age,s.stu_sex,s.stu_address,s.stu_class))
break
else:
print("没有此学生")
# 定义一个从名字查询学生基本信息的函数
def stuReferNameBaseMessage():
try:
stuList = Io.StudentIo().read_student()
except:
return print("请先添加学生!")
# 定义一个布尔型变量
b = False
# 创建一个新的列表存储名字重复的学生
stu = []
# 从键盘读取信息
stuName = input("请输入你想要查询的学生名字:")
if len(stuList) > 0:
# 遍历列表
for s in stuList:
if s.stu_name == stuName:
stu.append(s)
b = True
if b == True:
# 变量stu列表
for s1 in stu:
print("编号:%s--姓名:%s--年龄:%s--性别:%s--家庭住址:%s--班级:%s" \
% (s1.stu_id, s1.stu_name, s1.stu_age, s1.stu_sex, s1.stu_address, s1.stu_class))
else:
print("没有此学生!")
# 定义一个从班级查询学生基本信息的函数
def stuReferClassBaseMessage():
try:
stuList = Io.StudentIo().read_student()
except:
return print("请先添加学生!")
# 定义一个布尔型变量
b = False
# 创建一个新的列表存储名字重复的学生
stu = []
# 从键盘读取信息
stuClass = input("请输入你想要查询的班级:")
if len(stuList) > 0:
# 遍历列表
for s in stuList:
if s.stu_class == stuClass:
stu.append(s)
b = True
if b == True:
# 变量stu列表
for s1 in stu:
print("编号:%s--姓名:%s--年龄:%s--性别:%s--家庭住址:%s--班级:%s" \
% (s1.stu_id, s1.stu_name, s1.stu_age, s1.stu_sex, s1.stu_address, s1.stu_class))
else:
print("没有此班级!")
# 定义个函数查询所有学生
def stuReferBaseMessage():
try:
stuList = Io.StudentIo().read_student()
except:
return print("请先添加学生!")
if len(stuList) > 0:
# 遍历列表
for s in stuList:
print("编号:%s--姓名:%s--年龄:%s--性别:%s--家庭住址:%s--班级:%s" \
% (s.stu_id, s.stu_name, s.stu_age, s.stu_sex, s.stu_address, s.stu_class))
# ----------------------------------------------------------------------------------------------------------
# 以下是查看学生成绩
# 定义一个查询学生基本信息主界面
def referGradeMainMenu():
while True:
print("------------------------------------")
print("\t教师客户端")
print("\t\t1.按照学生的编号查询")
print("\t\t2.按照学生的名字查询")
print("\t\t3.按照学生的班级查询")
print("\t\t4.查询所有学生")
print("\t\t5.退出")
print("------------------------------------")
c = input("请输入您的选项:")
if c == '1': # 按照学生的编号查询
stuReferGradeId()
elif c == '2': # 按照学生的名字查询
stuReferGradeName()
elif c == '3': # 按照学生的班级查询
stuReferGradeLesson()
elif c == '4': # 查询所有学生成绩
stuReferGradeAll()
elif c == '5': # 退出
break
else:
input("没有这个选项,请重新输入!")
# 定义一个按编号查询学生成绩的函数
def stuReferGradeId():
try:
gradeList = Io.GradeIo().read_lesson()
except:
return print("请先添加成绩!")
# 定义一个布尔型变量
b = False
# 定义个变量存放总分数
sum = 0
# 定义个列表存放该编号的成绩
gList = []
# 提示用户输入学生编号
stu_id = input("请输入学生编号:")
# 遍历列表,查找编号相同的学生
for g in gradeList:
if stu_id == g.stuId:
sum += int(g.stuGrade)
# 如果存在,就添加进列表
gList.append(g)
b = True
if b == True:
for g1 in gList:
print("编号:%s--班级:%s--%s学生的%s成绩为:%s" % (g1.stuId,g1.stuLesson,g1.stuName, g1.stuMajor, g1.stuGrade))
print("总分为:%s" %sum)
else:
print("您输入的编号不存在")
# 定义一个按名字查询学生成绩的函数
def stuReferGradeName():
try:
gradeList = Io.GradeIo().read_lesson()
except:
return print("请先添加成绩!")
# 定义一个布尔型变量
b = False
# 定义个列表存放该姓名的成绩
gList = []
# 定义个变量存放总分数
sum = 0
# 提示用户输入学生姓名
stu_name = input("请输入学生姓名:")
# 遍历列表,查找编号相同的学生
for g in gradeList:
if stu_name == g.stuName:
sum += int(g.stuGrade)
# 如果存在,就添加进列表
gList.append(g)
b = True
if b == True:
for g1 in gList:
print("编号:%s--班级:%s--%s学生的%s成绩为:%s" % (g1.stuId,g1.stuLesson,g1.stuName, g1.stuMajor, g1.stuGrade))
print("总分为:%s" % sum)
else:
print("您输入的姓名不存在")
# 定义一个按班级查询学生成绩的函数
def stuReferGradeLesson():
try:
gradeList = Io.GradeIo().read_lesson()
except:
return print("请先添加成绩!")
# 定义一个布尔型变量
b = False
# 定义个列表存放该班级的成绩
gList = []
# 提示用户输入班级
stu_lesson = input("请输入班级:")
# 遍历列表,查找班级相同的学生
for g in gradeList:
if stu_lesson == g.stuLesson:
# 如果存在,就添加进列表
gList.append(g)
b = True
if b == True:
for g1 in gList:
print("编号:%s--班级:%s--%s学生的%s成绩为:%s" % (g1.stuId,g1.stuLesson,g1.stuName, g1.stuMajor, g1.stuGrade))
else:
print("您输入的班级不存在")
# 定义一个查询学生所有成绩的函数
def stuReferGradeAll():
try:
gradeList = Io.GradeIo().read_lesson()
except:
return print("请先添加成绩!")
for g1 in gradeList:
print("编号:%s--班级:%s--%s学生的%s成绩为:%s" % (g1.stuId, g1.stuLesson, g1.stuName, g1.stuMajor, g1.stuGrade))
# ----------------------------------------------------------------------------------------------------------
# 以下是学生端功能
# 查询学生的基本信息,s1为当前登录学生对象
def stuBaseMessage(s1):
stuList = Io.StudentIo().read_student()
for s in stuList:
if s1.stu_id == s.stu_id:
print("%s学生的基本信息为:" %s.stu_name)
print("编号:%s--姓名:%s--年龄:%s--性别:%s--家庭住址:%s--班级:%s" \
% (s.stu_id, s.stu_name, s.stu_age, s.stu_sex, s.stu_address, s.stu_class))
break
else:
print("请输入正确的编号!")
# 定义一个查看学生成绩的函数,s1为当前登录学生对象
def referStuGrade(s1):
try:
gradeList = Io.GradeIo().read_lesson()
except:
return print("请先添加成绩!")
# 定义个变量存放学生的总成绩
sum = 0
for g in gradeList:
if g.stuId == s1.stu_id:
sum += int(g.stuGrade)
print("您的%s成绩为:%s" % (g.stuMajor, g.stuGrade))
print("您的总分为:%s" %sum)
|
da4e95647ee87343f14742d71d0428db277a8d07 | Mariani-code/PythonProjects | /ProjectEuler/EP34.py | 506 | 3.609375 | 4 | from math import factorial
import time
start = time.time()
result=0
# store all 10 factorial numbers in a dictionary
d_factorial=dict()
for t in range(0,10):
d_factorial[str(t)] = factorial(t)
max = 7 * d_factorial['9']
# print(max)
for i in range(3,max+1):
temp=0
for j in str(i):
temp+=d_factorial[j]
if temp>i: break
if (i==temp):
print(f'i: {i}')
result+=temp
print(f'Sum: {result}')
print(f'Time: {time.time()-start}')
|
5a091e78be66d3283ee6c6715753ead2fb197ca8 | pcw263/py2-al | /Sort/bubble_sort.py | 1,493 | 4.125 | 4 | #!/usr/bin/env python2
#-*- coding:utf-8 -*-
import time
def bubble_sort(unorder_list):
#start = time.time()
count = 0
for epoch in range(len(unorder_list)-1,0,-1):
'''
这里迭代器是从大到小地生成序列(9,8,7,.....,1)
如:range(3,0,-1) ------> 依次生成 3,2,1 (注意递减生成时不包括最后一项)
'''
for i in range(epoch): #已经将前(n-epoch)个最大的数字”冒泡“到其应在的位置上
if unorder_list[i] > unorder_list[i+1]:
unorder_list[i],unorder_list[i+1] = unorder_list[i+1],unorder_list[i]
count += 1
#end = time.time()
print "冒泡操作数:",count
#return unorder_list
def short_bubble_sort(unorder_list):
#start = time.time()
count = 0
change = True
num = len(unorder_list)-1
while num > 0 and change:
change = False
#for epoch in range(num,0,-1):
for i in range(num):
if unorder_list[i] > unorder_list[i+1]:
change = True
unorder_list[i],unorder_list[i+1] = unorder_list[i+1],unorder_list[i]
count += 1
num -= 1
#end = time.time()
print "冒泡操作数:",count
if __name__ == "__main__":
unorder1 = [1,3,5,6,8,9,15,55,36,28,99,77,88]
unorder2 = [1,3,5,6,8,9,15,55,36,28,99,77,88]
bubble_sort(unorder1) #sort
short_bubble_sort(unorder2)
print "1:", unorder1
print "2:", unorder2 |
701675b033b7e59954e5d3b5f5decc4ead4d2892 | Rishika2022/Gitam-Python | /assignment july 10 2019.py | 276 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
def reverseFib(n):
a = [0] * n
a[0] = 0
a[1] = 1
for i in range(2, n):
a[i] = a[i - 2] + a[i - 1]
for i in range(n - 1, -1 , -1):
print(a[i],end=" ")
n = 5
reverseFib(n)
|
47a69e373e1ae8e3329cc2e9d826443146664aff | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_1/hrathore/CountingSheep.py | 462 | 3.546875 | 4 | t = int(raw_input()) # read a line with a single integer
for x in xrange(1, t + 1):
N = int(raw_input())
digits = ['\r']
i = 0;
while True:
if N == 0:
print "Case #%d: %s" % (x, "INSOMNIA")
break
i = i + 1
n = N * i
for s in str(n):
if s not in digits:
digits.append(s)
if len(digits) == 11:
print "Case #%d: %d" % (x, n)
break
|
e9c6309be3ae341baf7a021b788a8d74a5d3da08 | seongjaelee/ProjectEuler | /problem045.py | 786 | 3.734375 | 4 | import problem
import math
class Problem(problem.Problem):
def __init__(self):
number = 45
question = 'After 40755, what is the next triangle number that is also pentagonal and hexagonal?'
problem.Problem.__init__(self, number, question)
def getAnswer(self):
# n^2 + n - 2x = 0
# n = [-1 + sqrt(1 + 8x)] / 2
def isTriangle(n):
m = (math.sqrt(8*n+1) - 1) / 2
return int(m) == m
# 3n^2 - n - 2x = 0
# x = [-b +- sqrt(b^2 - 4ac)] / 2a
def isPentagonal(n):
m = (math.sqrt(24*n+1) + 1) / 6
return int(m) == m
def getHexagonal(n):
return n * (2*n-1)
assert isTriangle(getHexagonal(143))
assert isPentagonal(getHexagonal(143))
n = 144
while True:
m = getHexagonal(n)
if isPentagonal(m) and isTriangle(m):
return m
n += 1 |
7de443002e36a1adb6885ec9a7e3b2436ed728eb | SzymonTurek/my-bioinf-tools | /motif.py | 572 | 3.640625 | 4 | def reada(filename):
with open(filename) as file:
seq=''
line = file.readline()
while line :
if line[0]==">":
seq+=","
line = file.readline().rstrip()
else:
seq+=line
line = file.readline().rstrip()
lista = seq.split(",")
lista.pop(0)
slowo = ''
longest = ''
a = lista[1]
for i in range(len(a)):
for x in range(len(a)):
slowo = (a[i:x])
if all(lista[z].__contains__(slowo) for z in range(len(lista))) and len(slowo)>=len(longest):
longest = slowo
return( longest)
print(reada('rosalind_lcsm.txt'))
|
53ab4fbfa0a9e952fb0835dcdbf315ac50a42889 | GSantos23/Crash_Course | /Chapter16/Exercises/ex16_2.py | 2,385 | 3.59375 | 4 | # Exercise 16.2
'''
Sitka-Death Valley Comparison: The temperature scales on the Sitka
and Death Valley graphs reflect the different ranges of the data. To accu-
rately compare the temperature range in Sitka to that of Death Valley, you
need identical scales on the y-axis. Change the settings for the y-axis on
one or both of the charts in Figures 16-5 and 16-6, and make a direct com-
parison between temperature ranges in Sitka and Death Valley (or any two
places you want to compare). You can also try plotting the two data sets on
the same chart.
'''
import csv
from datetime import datetime
from matplotlib import pyplot as plt
# Get dates, high and low temperatures from file.
#filename = 'sitka_weather_2014.csv'
filename = 'death_valley_2014.csv'
filename2 = 'sitka_weather_2014.csv'
list_files = [filename, filename2]
with open(filename) as f, open(filename2) as f2:
reader = csv.reader(f)
header_row = next(reader)
dates, highs, lows = [], [], []
for row in reader:
try:
current_date = datetime.strptime(row[0], '%Y-%m-%d')
high = int(row[1])
low = int(row[3])
except ValueError:
print(current_date, 'missing data')
else:
dates.append(current_date)
highs.append(high) # The value [1] represent the column
lows.append(low)
reader2 = csv.reader(f2)
header_row = next(reader2)
dates2, highs2, lows2 = [], [], []
for row2 in reader2:
try:
current_date2 = datetime.strptime(row2[0], '%Y-%m-%d')
high2 = int(row2[1])
low2 = int(row2[3])
except ValueError:
print(current_date2, 'missing data')
else:
dates2.append(current_date2)
highs2.append(high2) # The value [1] represent the column
lows2.append(low2)
# print(highs)
# Plot data, Death Valley
fig = plt.figure(dpi=128, figsize=(10,6))
plt.plot(dates, highs, c='red',alpha=0.5)
plt.plot(dates, lows, c='blue', alpha=0.5)
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
# Plot data, Sitka
plt.plot(dates2, highs2, c='magenta',alpha=0.5)
plt.plot(dates2, lows2, c='green', alpha=0.5)
plt.fill_between(dates2, highs2, lows2, facecolor='blue', alpha=0.1)
# Format plot
title = "Daily high and low temperatures - 2014\nDeath Valley, CA Sitka, AK"
plt.title(title, fontsize=20)
plt.xlabel('', fontsize=16)
fig.autofmt_xdate()
plt.ylabel("Temperature (F)", fontsize=15)
plt.tick_params(axis='both', which='major', labelsize=16)
plt.show() |
b9758c5aec684603419b50b006983a8ac06dd031 | ArtyomKeller1/artyomkeller | /lesson2/homework5.py | 368 | 3.859375 | 4 | y = 0
while y < 10:
numbers = [7, 5, 3, 3, 2]
x1 = len(numbers)
x = int(input())
if x in numbers:
el_index = numbers.index(x)
numbers.insert(el_index, x)
numbers.sort()
numbers.reverse()
print(numbers)
else:
numbers.append(x)
numbers.sort()
numbers.reverse()
print(numbers)
|
0db57e6d71eccb259f32be9e6f6441b0aae1df68 | Jessmin/dl_utils | /convert_Dataset/table/iou.py | 918 | 3.5 | 4 | def calculate_IOU(rec1, rec2):
""" 计算两个矩形框的交并比
Args:
rec1: [left1,top1,right1,bottom1] # 其中(left1,top1)为矩形框rect1左上角的坐标,(right1, bottom1)为右下角的坐标,下同。
rec2: [left2,top2,right2,bottom2]
Returns:
交并比IoU值
"""
left_max = max(rec1[0], rec2[0])
top_max = max(rec1[1], rec2[1])
right_min = min(rec1[2], rec2[2])
bottom_min = min(rec1[3], rec2[3])
# 两矩形相交时计算IoU
if (left_max < right_min
or bottom_min > top_max): # 判断时加不加=都行,当两者相等时,重叠部分的面积也等于0
rect1_area = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1])
rect2_area = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1])
area_cross = (bottom_min - top_max) * (right_min - left_max)
return area_cross / rect2_area
else:
return 0
|
d0a7c66cc2594046fa6cb14e201660e77f1da343 | Lcast15/useful-functions | /number-to-ordinal.py | 275 | 4.0625 | 4 | def Ordinal(Num):
Num = str(Num)
if Num.endswith('1') and not Num.endswith('11'):
return Num + 'st'
elif Num.endswith('2') and not Num.endswith('12'):
return Num + 'nd'
elif Num.endswith('3') and not Num.endswith('13'):
return Num + 'rd'
else:
return Num + 'th'
|
0c96bb02db92443ddf8ac29bdd0a4fd26c3bf3fc | jimengya/Algorithms | /实操演练/templates/t003.py | 719 | 4.03125 | 4 | def smallest_k_numbers(k, *args):
"""Return a collection containing the k smallest numbers
Args:
k: the number of numbers to return
args: all given numbers
Returns:
A collection of results
"""
# Put your code here.
pass
if __name__ == "__main__":
assert {1,2,3,4} == smallest_k_numbers(4, 4,5,1,6,2,7,3,8)
assert {} = smallest_k_numbers(0, )
assert {1} == smallest_k_numbers(1, 1)
assert {} == smallest_k_numbers(0, 4,5,1,6,2,7,3,8)
assert {4,5,1,6,2,7,3,8} == smallest_k_numbers(8, 4,5,1,6,2,7,3,8)
assert {4,5,1,6,2,7,3,8} == smallest_k_numbers(8, 11,33,4,5,1,6,99,384,27,2,7,3,8,10)
assert {1,99} == smallest_k_numbers(2, 1, 99)
|
ecf4bc12d6b579aac8cd4a882ae5de7b5b84f728 | gndit/datastructure | /preordertree.py | 804 | 4.21875 | 4 |
#tree traversal in binary tree
class node:
def __init__(self,data):
self.left=None
self.right=None
self.key=data
def print_preorder(root):
if root:
print(root.key),
print_preorder(root.left)
print_preorder(root.right)
#inorder traversal
def print_inorder(root):
if root:
print_inorder(root.left)
print(root.key),
print_inorder(root.right)
def print_postorder(root):
if root:
print_postorder(root.left)
print_postorder(root.right)
print(root.key),
#main programe
root=node(5)
root.left=node(1)
root.right=node(3)
root.left.left=node(4)
root.left.right=node(6)
print("preoder :")
print_preorder(root)
print("inorder :")
print_inorder(root)
print("postorder :")
print_postorder(root)
|
842cabbb6135cc76a9354c43dae88a4cfe5da0f2 | sivaneshl/python_data_analysis | /intro_data_science_python/statistical_analysis_in_python/assignment4/assignment4.0.py | 14,871 | 3.65625 | 4 | import pandas as pd
import numpy as np
from scipy import stats
import re
pd.options.display.float_format = '{:.8f}'.format
# Definitions:
# # A quarter is a specific three month period,
# Q1 is January through March,
# Q2 is April through June,
# Q3 is July through September,
# Q4 is October through December.
# A recession is defined as starting with two consecutive quarters of GDP decline, and ending with two consecutive
# quarters of GDP growth.
# A recession bottom is the quarter within a recession which had the lowest GDP.
# A university town is a city which has a high percentage of university students compared to the total population of
# the city.
# Hypothesis: University towns have their mean housing prices less effected by recessions. Run a t-test to compare the
# ratio of the mean price of houses in university towns the quarter before the recession starts compared to the
# recession bottom. (price_ratio=quarter_before_recession/recession_bottom)
# The following data files are available for this assignment:
# From the Zillow research data site there is housing data for the United States. In particular the datafile for all
# homes at a city level, City_Zhvi_AllHomes.csv, has median home sale prices at a fine grained level.
# From the Wikipedia page on college towns is a list of university towns in the United States which has been copy and
# pasted into the file university_towns.txt.
# From Bureau of Economic Analysis, US Department of Commerce, the GDP over time of the United States in current dollars
# (use the chained value in 2009 dollars), in quarterly intervals, in the file gdplev.xls. For this assignment, only
# look at GDP data from the first quarter of 2000 onward.
# Each function in this assignment below is worth 10%, with the exception of run_ttest(), which is worth 50%.
# Use this dictionary to map state names to two letter acronyms
states = {'OH': 'Ohio', 'KY': 'Kentucky', 'AS': 'American Samoa', 'NV': 'Nevada', 'WY': 'Wyoming', 'NA': 'National',
'AL': 'Alabama', 'MD': 'Maryland', 'AK': 'Alaska', 'UT': 'Utah', 'OR': 'Oregon', 'MT': 'Montana',
'IL': 'Illinois', 'TN': 'Tennessee', 'DC': 'District of Columbia', 'VT': 'Vermont', 'ID': 'Idaho',
'AR': 'Arkansas', 'ME': 'Maine', 'WA': 'Washington', 'HI': 'Hawaii', 'WI': 'Wisconsin', 'MI': 'Michigan',
'IN': 'Indiana', 'NJ': 'New Jersey', 'AZ': 'Arizona', 'GU': 'Guam', 'MS': 'Mississippi', 'PR': 'Puerto Rico',
'NC': 'North Carolina', 'TX': 'Texas', 'SD': 'South Dakota', 'MP': 'Northern Mariana Islands', 'IA': 'Iowa',
'MO': 'Missouri', 'CT': 'Connecticut', 'WV': 'West Virginia', 'SC': 'South Carolina', 'LA': 'Louisiana',
'KS': 'Kansas', 'NY': 'New York', 'NE': 'Nebraska', 'OK': 'Oklahoma', 'FL': 'Florida', 'CA': 'California',
'CO': 'Colorado', 'PA': 'Pennsylvania', 'DE': 'Delaware', 'NM': 'New Mexico', 'RI': 'Rhode Island',
'MN': 'Minnesota', 'VI': 'Virgin Islands', 'NH': 'New Hampshire', 'MA': 'Massachusetts', 'GA': 'Georgia',
'ND': 'North Dakota', 'VA': 'Virginia'}
quarterly_gdp = pd.read_excel('C:/python_data_analysis/resources/course1_downloads/gdplev.xls',
skiprows=219,
usecols=[4, 6],
names=['Quarter', 'gdp'])
def get_list_of_university_towns():
"""Returns a DataFrame of towns and the states they are in from the
university_towns.txt list. The format of the DataFrame should be:
DataFrame( [ ["Michigan", "Ann Arbor"], ["Michigan", "Yipsilanti"] ],
columns=["State", "RegionName"] )
The following cleaning needs to be done:
1. For "State", removing characters from "[" to the end.
2. For "RegionName", when applicable, removing every character from " (" to the end.
3. Depending on how you read the data, you may need to remove newline character '\n'. """
university_towns_df = pd.DataFrame(columns=['State', 'RegionName'])
current_state = ''
fhand = open('C:/python_data_analysis/resources/course1_downloads/university_towns.txt',
encoding='utf-8')
for line in fhand:
if line.endswith('[edit]\n'):
current_state = line.replace('[edit]\n', '').strip()
else:
university_towns_df = university_towns_df.append({'State': current_state,
'RegionName': re.sub(r' \(.*\n', '', line).strip()},
ignore_index=True)
# university_towns_df.replace(to_replace={'RegionName': r' \(.*\n'}, value={'RegionName': ''},
# regex=True,
# inplace=True)
return university_towns_df
def get_recession_start():
"""Returns the year and quarter of the recession start time as a
string value in a format such as 2005q3"""
for i in range(0, len(quarterly_gdp['gdp'])-2):
if quarterly_gdp.loc[i, 'gdp'] > quarterly_gdp.loc[i + 1, 'gdp'] > quarterly_gdp.loc[i + 2, 'gdp']:
return quarterly_gdp.loc[i + 1, 'Quarter']
def get_recession_end():
"""Returns the year and quarter of the recession end time as a
string value in a format such as 2005q3"""
for i in range((quarterly_gdp[quarterly_gdp['Quarter'] == get_recession_start()].index.values[0]),
len(quarterly_gdp['gdp'])-2):
if quarterly_gdp.loc[i, 'gdp'] < quarterly_gdp.loc[i + 1, 'gdp'] < quarterly_gdp.loc[i + 2, 'gdp']:
return quarterly_gdp.loc[i + 2, 'Quarter']
def get_recession_bottom():
"""Returns the year and quarter of the recession bottom time as a
string value in a format such as 2005q3"""
recession_bottom_df = quarterly_gdp[quarterly_gdp['Quarter'] == get_recession_end()]
recession_bottom_value = recession_bottom_df['gdp'].values[0]
recession_bottom_index = recession_bottom_df.index.values[0]
# print((quarterly_gdp[quarterly_gdp['Quarter'] == get_recession_start()].index.values[0]),
# (quarterly_gdp[quarterly_gdp['Quarter'] == get_recession_end()].index.values[0]))
# print(quarterly_gdp[34:38])
# print(quarterly_gdp[34:38]['gdp'].idxmin())
return (quarterly_gdp.loc[quarterly_gdp[
(quarterly_gdp[quarterly_gdp['Quarter'] == get_recession_start()].index.values[0]):
(quarterly_gdp[quarterly_gdp['Quarter'] == get_recession_end()].index.values[0])
]['gdp'].idxmin(),'Quarter'])
# for i in range((quarterly_gdp[quarterly_gdp['Quarter'] == get_recession_start()].index.values[0]),
# (quarterly_gdp[quarterly_gdp['Quarter'] == get_recession_end()].index.values[0])):
# if quarterly_gdp.loc[i, 'gdp'] < recession_bottom_value:
# recession_bottom_value = quarterly_gdp.loc[i, 'gdp']
# recession_bottom_index = i
#
#
# print(quarterly_gdp.loc[recession_bottom_index, 'Quarter'])
# return quarterly_gdp.loc[recession_bottom_index, 'Quarter']
def convert_housing_data_to_quarters():
"""Converts the housing data to quarters and returns it as mean
values in a dataframe. This dataframe should be a dataframe with
columns for 2000q1 through 2016q3, and should have a multi-index
in the shape of ["State","RegionName"].
Note: Quarters are defined in the assignment description, they are
not arbitrary three month periods.
The resulting dataframe should have 67 columns, and 10,730 rows.
"""
# select desired columns
columns_list = ['State', 'RegionName']
year_month_list = [x for x in [None if i == 2016 and j > 8
else str(i) + '-' + str(j).zfill(2)
for i in range(2000, 2017)
for j in range(1, 13)]
if x is not None]
# this is a nested list comprehension where the inner list is to get all
# the year and months and puts None for 2016-09/10/11/12 and the outer list
# excludes the None values - Repalcement logic is below
# for i in range(2000, 2017):
# for j in range(1, 13):
# if i == 2016 and j > 8:
# break
# else:
# column_name = str(i) + '-' + str(j).zfill(2)
# # if column_name in housing_df.columns:
# columns_list.append(column_name)
columns_list = columns_list + year_month_list
# Read data
housing_df = pd.read_csv('C:/python_data_analysis/resources/course1_downloads/City_Zhvi_AllHomes.csv',
usecols=columns_list)
# replace state codes from map
housing_df['State'] = housing_df['State'].map(states)
# reduce to quarters
# find the quarters
quarter_groups = dict()
for yrmo in year_month_list:
yearmonth = yrmo.split('-')
quarter = int((int(yearmonth[1])-1)/3)+1
quarter_groups.setdefault(yearmonth[0] + 'q' + str(quarter),[]).append(yrmo)
# use the quarters and compute the mean
columns_list = ['State', 'RegionName']
for quarter, month_list in quarter_groups.items():
housing_df[quarter] = housing_df[month_list].mean(axis=1)
columns_list.append(quarter)
# select the desired columns list and set State and RegionName as multi index
housing_df = housing_df[columns_list].set_index(['State', 'RegionName'])
return housing_df
def run_ttest():
"""First creates new data showing the decline or growth of housing prices
between the recession start and the recession bottom. Then runs a ttest
comparing the university town values to the non-university towns values,
return whether the alternative hypothesis (that the two groups are the same)
is true or not as well as the p-value of the confidence.
Return the tuple (different, p, better) where different=True if the t-test is
True at a p<0.01 (we reject the null hypothesis), or different=False if
otherwise (we cannot reject the null hypothesis). The variable p should
be equal to the exact p value returned from scipy.stats.ttest_ind(). The
value for better should be either "university town" or "non-university town"
depending on which has a lower mean price ratio (which is equivilent to a
reduced market loss)."""
housing_df = convert_housing_data_to_quarters()
# columns_list = list(housing_df.columns.values)
columns_list = ['2000q1', '2000q2', '2000q3', '2000q4', '2001q1', '2001q2', '2001q3', '2001q4', '2002q1', '2002q2', '2002q3', '2002q4', '2003q1', '2003q2', '2003q3', '2003q4', '2004q1', '2004q2', '2004q3', '2004q4', '2005q1', '2005q2', '2005q3', '2005q4', '2006q1', '2006q2', '2006q3', '2006q4', '2007q1', '2007q2', '2007q3', '2007q4', '2008q1', '2008q2', '2008q3', '2008q4', '2009q1', '2009q2', '2009q3', '2009q4', '2010q1', '2010q2', '2010q3', '2010q4', '2011q1', '2011q2', '2011q3', '2011q4', '2012q1', '2012q2', '2012q3', '2012q4', '2013q1', '2013q2', '2013q3', '2013q4', '2014q1', '2014q2', '2014q3', '2014q4', '2015q1', '2015q2', '2015q3', '2015q4', '2016q1', '2016q2', '2016q3']
# housing_df = housing_df[(housing_df.columns.values[columns_list.index(recession_start): columns_list.index(recession_bottom)+1])]
housing_df['price_ratio'] = housing_df[housing_df.columns.values[columns_list.index(get_recession_start())-1]]\
.div(housing_df[housing_df.columns.values[columns_list.index(get_recession_bottom())]])
# print(housing_df[[housing_df.columns.values[c
# olumns_list.index(recession_start)-1], # quarter before recession start
# housing_df.columns.values[columns_list.index(recession_bottom)], # recession bottom
# 'price_ratio']])
university_towns_df = get_list_of_university_towns()
# print(university_towns_df)
# merged_df = pd.merge(university_towns_df,
# housing_df.reset_index(),
# how='outer',
# on=['State', 'RegionName'],
# indicator='_flag')
uni_towns = university_towns_df['State']+university_towns_df['RegionName']
housing_df = housing_df.reset_index()
housing_df['_flag'] = housing_df.apply(lambda x: x['State']+x['RegionName'] in set(uni_towns), axis=1)
housing_df.drop_duplicates(keep=False)
university_towns_df.drop_duplicates(keep=False)
# univ_town_values = merged_df[merged_df['_flag']=='both']
# non_univ_town_values = merged_df[merged_df['_flag']!='both']
univ_town_values = housing_df[housing_df['_flag']==1]
non_univ_town_values = housing_df[housing_df['_flag']==0]
print(len(univ_town_values))
print(len(non_univ_town_values))
univ_town_mean_ratio = univ_town_values['price_ratio'].mean()
non_univ_town_mean_ratio = non_univ_town_values['price_ratio'].mean()
ttest_result = stats.ttest_ind(univ_town_values['price_ratio'],
non_univ_town_values['price_ratio'],
nan_policy='omit')
print(ttest_result, univ_town_mean_ratio, non_univ_town_mean_ratio)
different = ttest_result.pvalue < 0.01
print(univ_town_values['price_ratio'].mean() ,
non_univ_town_values['price_ratio'].mean() ,
(univ_town_values['price_ratio'].mean() < non_univ_town_values['price_ratio'].mean() ))
if univ_town_mean_ratio < non_univ_town_mean_ratio:
better = "university town"
else:
better = "non-university town"
return (different, ttest_result.pvalue, better)
# test output type (different, p, better)
def test_q6():
q6 = run_ttest()
different, p, better = q6
res = 'Type test: '
res += ['Failed\n','Passed\n'][type(q6) == tuple]
res += 'Test "different" type: '
res += ['Failed\n','Passed\n'][type(different) == bool or type(different) == np.bool_]
res += 'Test "p" type: '
res += ['Failed\n','Passed\n'][type(p) == np.float64]
res +='Test "better" type: '
res += ['Failed\n','Passed\n'][type(better) == str]
if type(better) != str:
res +='"better" should be a string with value "university town" or "non-university town"'
return res
res += 'Test "different" spelling: '
res += ['Failed\n','Passed\n'][better in ["university town", "non-university town"]]
return res
get_list_of_university_towns()
# print(df[df['State'] == 'Massachusetts'])
recession_start = get_recession_start()
print('Recession Start', recession_start)
recession_end = get_recession_end()
print('Recession End', recession_end)
recession_bottom = get_recession_bottom()
print('Recession Bottom', recession_bottom)
# print(convert_housing_data_to_quarters())
q6 = run_ttest()
print(q6)
print(test_q6())
|
05c907ede171a51602d9d622f3a72f4a4d0edef7 | Made-of-Dark-Matter/DSA-Agorithmic-Toolkit | /1-6-last_digit_of_fibonacci_number.py | 678 | 3.984375 | 4 | # python3
def last_digit_of_fibonacci_number_naive(n):
assert 0 <= n <= 10 ** 7
if n <= 1:
return n
return (last_digit_of_fibonacci_number_naive(n - 1) + last_digit_of_fibonacci_number_naive(n - 2)) % 10
def last_digit_of_fibonacci_number(n):
assert 0 <= n <= 10 ** 7
fib_1 = 0
fib_2 = 1
fib = 0
if n<=1:
return n
for index in range(2,n+1):
fib = (fib_1 + fib_2) % 10
fib_1 = fib_2
fib_2 = fib
#last_fib_n.append((last_fib_n[index-1] + last_fib_n[index-2]) % 10)
return fib
if __name__ == '__main__':
input_n = int(input())
print(last_digit_of_fibonacci_number(input_n))
|
298a75a3fae2e1c3d9274fdfd3e3a1c373b0bb49 | ShivaniMadda/Python | /Basics/Q4.py | 347 | 3.5625 | 4 | #import math
#a = 4
#b = math.sqrt(a)
#print(b)
s=input("Enter an integer sequence seperated by comma: ")
list1 = list(s.split(","))
for i in range(0,len(list1)):
list1[i] = int(list1[i])
C = 50
H = 30
for D in list1:
if D != list1[len(list1)-1]:
Q = int(((2*C*D)/H)**0.5)
print(Q,end=",")
else:
Q = int(((2*C*D)/H)**0.5)
print(Q)
|
fb715586393b211c9adab98ba1b8b5f07cf430be | u101022119/NTHU10220PHYS290000 | /student/100021216/factorial_rec.py | 241 | 3.9375 | 4 | def factorial_rec(n):
if n-int(n)!=0:
return 'None'
elif n<0:
return 'None'
elif n==0:
return 1
else:
return int(n*factorial_rec(n-1))
n=input('Enter a number:')
m=factorial_rec(n)
print m
|
db351e59cdc8d13da12f7f4526a075572627aa28 | entropy2333/leetcode | /medium/24_swapPairs.py | 608 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
p = ListNode(-1)
p.next, a = head, p
while a.next and a.next.next:
l,r = a.next, a.next.next
r = a.next.next
l.next = r.next
r.next = l
a.next = r
a = l
return p.next |
37c7d420d3a63def0df0ce6e55c60d7b567963f3 | pastorcmentarny/DomJavaKB | /python/src/tools/text/enum_station_generator.py | 449 | 3.59375 | 4 | # left this empty after use
stations = []
def convert_to_enum(station):
return station.replace(" & ", "_AND_").replace(' ', '_').replace("'", "") \
.replace(" & ", "_AND_").replace('(', '_').replace(')', '_') \
.upper() + '("' + station + '",OVERGROUND),'
def generate_station_enum():
for station in stations:
print(convert_to_enum(station))
if __name__ == '__main__':
generate_station_enum()
|
41d45cf69fb1d7be45da1bf321cc58b6e45a0174 | cz-fish/sneeze-dodger | /sneeze/Actor.py | 1,236 | 3.5 | 4 | import abc
from sneeze.Sprite import Sprite
from sneeze.Types import *
from typing import Optional
class Actor(abc.ABC):
def __init__(self):
self.pos = Pos(0, 0)
self.prev_pos = Pos(0, 0)
self.speed_vec = Pos(0, 0)
self.max_speed = 10
self.accel = 5
self.slowdown = 1.3
self.sprite: Optional[Sprite] = None
self.animation = Animation('idle', 0)
@abc.abstractmethod
def move(self, player_pos: Pos) -> None:
pass
def move_to(self, pos: Pos) -> None:
self.prev_pos = self.pos
self.pos = Pos(pos.x, pos.y)
def update_speed(self, xmove: int, ymove: int) -> None:
def one_axis(velocity, input):
if input == -1:
return max(-self.max_speed, velocity - self.accel)
elif input == 1:
return min(self.max_speed, velocity + self.accel)
else:
return velocity / self.slowdown
self.speed_vec = Pos(
one_axis(self.speed_vec.x, xmove),
one_axis(self.speed_vec.y, ymove)
)
def get_size(self) -> Pos:
if self.sprite is None:
return Pos(0, 0)
return self.sprite.get_size()
|
605776446dab81c774ee111302a9247e7dd334e8 | sankoudai/py-knowledge-center | /com.xulf.learn.py.basis/pattern/map_test.py | 1,192 | 3.625 | 4 | __author__ = 'quiet road'
import unittest
from printutil.printutil import printVar
class MapTest(unittest.TestCase):
"""
map:
map is a class, which implements iterable pattern and iterator pattern.
constructor: map(f, iterator1, iterator2, ...)
"""
def setUp(self):
self.a_list = [1, 2, 3, 4]
self.b_list = [4, 3, 2, 1]
self.small_list = [1, 2]
self.unary_f = lambda x : x + 1
self.n_nary_f = lambda x, y : x + y
def test_unary_map(self):
map_object = map(self.unary_f, self.a_list)
printVar(map_object)
print()
for item in map_object:
printVar(item)
def test_nnary_map(self):
map_object = map(self.n_nary_f, self.a_list, self.b_list)
printVar(map_object)
print()
for item in map_object:
printVar(item)
def test_diff_lengths(self):
# map_object has size of self.small_list
map_object = map(self.n_nary_f, self.a_list, self.small_list)
printVar(map_object)
print()
for item in map_object:
printVar(item)
if __name__ == '__main__':
unittest.main()
|
60b95897966791b80ac616599b0c594c2114fede | genevievepoint/CP1404_Assignment_Part1 | /attempt1_fail.py | 2,159 | 3.640625 | 4 | # Genevieve Point#
import csv
# menu()
# print("Items for Hire - By Genevieve Point")# 06/04/2016
workbook_file = open('items.csv', 'r')
workbook_reader = csv.reader(workbook_file)
sheets_list = []
for row in workbook_reader:
print(row)
# row = row.split()
# row_info = row.strip('\n')
sheets_list.append(row)
items_list = row
print(items_list)
#
counter_strip = 0
for lists in items_list:
items_list[counter_strip] = items_list[counter_strip].strip()
counter_strip += 1
counter_split = 0
for items in items_list:
items_list[counter_split] = items_list[counter_split].split(',')
counter_split += 1
counter_main = 0
for i in items_list:
working_list = items_list[counter_main]
counter_main += 1
print("() -{} [()]\t\t\t= $()",format(counter_main, working_list[0], " ", working_list[2], working_list[3])
# print(working_list)
workbook_reader.close()
# print(sheets_list)
# def menu():
# print("Menu: \n (L)ist all items \n (H)ire an item \n (R)eturn an item \n (A)dd an item \n (Q)uit \n")
# choice = input()
#
# if choice == "L" or choice == "l":
# list_items()
# menu()
# elif choice == "H" or choice == "h":
# hire_item()
# menu()
# elif choice == "R" or choice == "r":
# return_item()
# menu()
# elif choice == "A" or choice == "a":
# add_item()
# menu()
# elif choice == "Q" or choice == "q":
# print("quit()")
# else:
# print("Please enter a valid choice")
# menu()
#
# def load_items():
# print("List all items")
# menu()
# def list_items(items_list):
# print("All items on file")
# if items_list == "out":
# print("*")
# def hire_item():
# print("Hire an item")
# for line in lines:
# if country_name in line:
# line = line.strip().split(',')
# line_info = line[0], line[1], line[2]
# return tuple(line_info)
# menu()
def return_item():
print("Return an item")
# menu()
def add_item():
print("Add an item for hire")
|
ffda68bf09d71286fff546cc89b24358b5b0d4be | jiangshanmeta/lintcode | /src/0104/solution.py | 1,067 | 3.9375 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param lists: a list of ListNode
@return: The head of one sorted list.
"""
def mergeKLists(self, lists):
L = len(lists)
if L == 0 :
return None
return self.mergeHelper(lists,0,L-1)
def mergeHelper(self,lists,start,end) :
if start == end :
return lists[start]
if start+1 == end :
return self.merge2(lists[start],lists[end])
mid = (start+end) >> 1
return self.merge2(
self.mergeHelper(lists,start,mid),
self.mergeHelper(lists,mid+1,end)
)
def merge2(self,l1,l2):
if l2 is None :
return l1
if l1 is None :
return l2
if l1.val<l2.val :
l1.next = self.merge2(l1.next,l2)
return l1
else :
l2.next = self.merge2(l2.next,l1)
return l2
|
6815bb6567fcfd337a6110598f6bdc0d18c8d717 | rahuljnv/rg_code | /Faulty_cal_ex2.py | 1,097 | 4.09375 | 4 | # Exercise 2 - Faulty Calculator
# 45 * 3 = 555, 56+9 = 77, 56/6 = 4
# Design a calculator which will correctly solve all the problems except
# the following ones:
# 45 * 3 = 555, 56+9 = 77, 56/6 = 4
# Your program should take operator and the two numbers as input from the user
# and then return the result
var1 = {"45*3":555, "55+9":77, "56/6":4}
var2 = ["+","-","*","/"]
# print(var1,var2)
print("Enter two numbers:")
inp1 = input()
inp2 = input()
inch = int(input("Make ur choice:\n1.+\n 2.-\n 3.*\n 4./\n"))
#print(inp1+var2[3]+inp2)
# print(var1.get("55/6"))
if inch == 1:
if (inp1+var2[0]+inp2) in var1.keys():
print(var1.get((inp1+var2[0]+inp2)))
else:
print(int(inp1) + int(inp2))
elif inch == 3:
if (inp1+var2[2]+inp2) in var1.keys():
print(var1.get((inp1+var2[2]+inp2)))
else:
print(int(inp1) * int(inp2))
elif inch == 4:
if (inp1+var2[3]+inp2) in var1.keys():
print(var1.get((inp1+var2[3]+inp2)))
else:
print(int(inp1) / int(inp2))
else:
print(int(inp1) - int(inp2))
|
54120460b42ec334eb3b27f00a9e2544228429d6 | Aboechko/Data-structures-and-algorithms-with-Python | /Simple methods.py | 513 | 3.984375 | 4 | #Implement the simple methods getNum and getDen that will return the numerator and denominator of a fraction.
class Fraction:
def __init__(self,top,bottom):
self.num = top
self.den = bottom
def __str__(self):
return str(self.num) + "/" + str(self.den)
def getNum(self):
return self.num
def getDen(self):
return self.den
myfraction = Fraction(n,d)
n = input("input numerator")
d = input("input denominator")
print(myfraction)
print(myfraction.getNum())
print(myfraction.getDen()) |
db212199a7c81444fae95ecfd3ce1600ec2c4fab | NikitaFir/Leetcode | /Longest Uncommon Subsequence I.py | 351 | 3.625 | 4 | class Solution(object):
def findLUSlength(self, a, b):
n = len(a)
m = len(b)
if n > m:
return n
elif n < m:
return m
else:
if a == b:
return -1
else:
return n
print(Solution.findLUSlength(0,"aba", "cdc"))
|
620c75d5f8c78b2e592029e92e3019ab72887fad | curieshicy/My_Utilities_Code | /Grokking_the_Coding_Interviews/p60_search_bitonic_array.py | 1,522 | 3.75 | 4 | def search_bitonic_array(arr, key):
# find the index of max
l = 0
h = len(arr) - 1
while l < h:
m = (l + h) // 2
if arr[m] < arr[m+1]:
l = m + 1
else:
h = m
max_index = l # or h
def binary_search(nums, low, high, target, ascending):
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
if ascending == True:
low = mid + 1
else:
high = mid - 1
else:
if ascending == True:
high = mid - 1
else:
low = mid + 1
return -1
if max_index == 0:
return binary_search(arr, 0, len(arr) - 1, key, False)
if max_index == len(arr) - 1:
return binary_search(arr, 0, len(arr) - 1, key, True)
idx_1 = binary_search(arr, 0, max_index, key, True)
idx_2 = binary_search(arr, max_index + 1, len(arr) - 1, key, False)
if idx_1 == -1 and idx_2 == -1:
return -1
if idx_1 != -1:
return idx_1
if idx_2 != -1:
return idx_2
def main():
print(search_bitonic_array([1, 3, 8, 4, 3], 4))
print(search_bitonic_array([3, 8, 3, 1], 8))
print(search_bitonic_array([1, 3, 8, 12], 12))
print(search_bitonic_array([10, 9, 8], 10))
print(search_bitonic_array([10, 9, 8], 1))
main()
|
5378a84380410a10d532926a05ddee4edaf7df1e | pyliut/Rokos2021 | /Wk4/Inverse_Digamma_bounds.py | 717 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 20 11:55:29 2021
@author: pyliu
"""
import numpy as np
import scipy as sp
def Inverse_Digamma_bounds(k):
"""
From Batir paper on Inverse Digamma bounds
The lower bound is a good approximation for the Inverse Digamma function
Parameters
----------
k : FLOAT, scalar
k ~ Digamma(lower_bound)
Returns
-------
lower_bound : FLOAT, scalar
Mathematical lower bound of the inverse digamma
"""
lower_bound = 1 / np.log(1 + np.exp(-k))
upper_bound = np.exp(k) + 0.5
if lower_bound - upper_bound > lower_bound:
print("ERROR: bounds are not close")
return lower_bound |
32a6ce46d53c593c21cf866114904d1981288389 | razzledazze/Python-Turtle---10x10-Screen | /Pixel Screen.py | 1,853 | 4.21875 | 4 |
from turtle import Turtle
import csv
colours = ['blue','red','yellow','green','orange','purple']
turtles = []
names = []
def MakeScreen():
for row in range(10):
print("Setting up Column:"+str(row+1))
for column in range(10):
name = str(row)+str(column) #makes a unique name for the coordinates
names.append(name) #adds the name to an array
name = Turtle() #makes it into a turtle
name.speed(0)
turtles.append(name) #adds the turtle to a different array
name.shape('square') #makes it a square (pixel)
name.shapesize(3) #makes it the correct size
name.penup()
name.goto(row*60-300,column*60-250) #goes to its coordinates
MakeScreen()
if input("Enter M for manual of F for file: ")[0].upper() == "M": #takes the uppercase version of the first letter of the choice
while True:
rowchoice = input("\nEnter row: ")
columnchoice = input("Enter column: ")
colourchoice = input("Enter colour: ")
turtles[names.index(str(rowchoice)+str(columnchoice))].color(colourchoice) #finds the matching turtle to the name and makes it the chosen colour
else:
filename = input("\nEnter filename with .csv extension: ")
with open(filename) as file:
pixelreader = csv.DictReader(file)
rowno = 0
for row in pixelreader: #reads every line of the file
for columnno in range(1,11): #for every column in the file
print("Scanning row:"+str(rowno+1)+" Column:"+str(columnno)) #shows the location of the coordinate (colour) in the file
turtles[names.index(str(columnno-1)+str(10-rowno-1))].color(row[str(columnno)]) #makes the relevant turtle that colour
rowno += 1
|
a288ead6f0487ae3a361c5f8485b3c1bf4cb1bac | mare7811/Numerical-Methods | /HW_april10.py | 3,763 | 3.578125 | 4 | """
Miguel Mares
Numerical Methods
Homework
Due 4/10/2020
"""
#This function uses the finite difference method to solve the problem:
#y'' + 2y' + (k^2)y = 0, y(0) = 0 and y(1) = 0 for acceptable values of k.
#First different lambda values are swept from -40 to 0, and a determinant
#for each lambda tested is found from the matrix (A-lI). These values are used
#to find lambda's and determinants that are close to a root. The secant method
#is then used to on those values to find a root (lambda). This lambda is
#where the determinant is zero and the k can be found from these. The k that
#is found is an allowable value of k.
import numpy as np
import math
import pandas as pd
import matplotlib.pyplot as plt
#secant method function accepts two lambda values and two determinant values
#and then finds the closest root at those entries.
def secant(x1,x2,y1,y2):
global A_l
#Create lists and set first entries
r = []
y = []
r.append(x1)
r.append(x2)
y.append(y1)
y.append(y2)
#loops through x values until the difference between two y values is too small to use
i = 2
while(r[i-1] != 0):
if((y[i-1]-y[i-2]) != 0):
l_new = (r[i-2]*y[i-1] - r[i-1]*y[i-2])/(y[i-1]-y[i-2])
r.append(l_new)
A_lambda(l_new)
y.append(determinant())
else:
r.append(0)
i += 1
return(r[i-2])
#This functions finds the determinant of the (A-lI) matrix
def determinant():
global A_l
global A
Det = np.zeros(N)
Det[0] = A_l[0][0]
Det[1] = A_l[1][1]*Det[0] - A_l[1][0]*A_l[0][1]
for i in range(2,N):
Det[i] = A_l[i][i]*Det[i-1] - A_l[i][i-1]*A_l[i-1][i]*Det[i-2]
return Det[N-1]
#This function updates the (A-lI) matrix to be used by the determinant() function
def A_lambda(l):
global A_l
global A
for i in range(0,N):
A_l[i][i] = A[i][i] - l
#specifying step size and boundary conditions
h = .2
a = 0
b = 1
y_upper = 0
y_lower = 0
#Number of intervals, minus 1
N = math.floor((b-a)/h) - 1
y_a = (1/h**2) + (1/h)
y_b = -2/(h**2)
y_c = (1/h**2) - (1/h)
#matrix, A, from second order ODE, finite difference equation
A = np.zeros((N,N))
A[0][0] = y_b
A[0][1] = y_c
A[N-1][N-2] = y_a
A[N-1][N-1] = y_b
for i in range(1,N-1):
A[i][i-1] = y_a
A[i][i] = y_b
A[i][i+1] = y_c
#This section sweeps through different lambda values from -40 to 0 and plots results
M = 40
l = np.zeros(M)
D = np.zeros(M)
for i in range(-M,0):
l[i] = i
A_lambda(l[i])
D[i] = determinant()
#Plotting
myFigSize = (15,15)
plt.figure(figsize=myFigSize)
plt.subplot(1,1,1)
plt.plot(l,D)
plt.grid(True)
plt.show()
#This section creates a table of lambda and determinant values for outputting
l.resize((l.size,1))
D.resize((D.size,1))
T = np.concatenate((l,D),axis=1)
T = pd.DataFrame(T)
T.columns = ['lambda','determinant']
#print(T.to_string(index=False))
#These statements use the secant() function to find the root, given the lambda and determinant values
root1 = secant(l[30],l[31],D[30],D[31])
print('root1 = ',root1)
root2 = secant(l[5],l[6],D[5],D[6])
print('root2 = ',root2)
#finds the appropriate k for the root that is found (lambda = -k^2)
k1 = np.sqrt(-root1)
k2 = np.sqrt(-root2)
print('k1 = ',k1)
print('k2 = ',k2,'\n')
print('These k\'s can be plugged into the original problem and then be solved',
'using previous methods.')
print('This method can be extended to find more roots and thus more acceptable',
'values of k')
|
3bf798874e19fe35ef9d646b561d8014c1e381ac | abkunal/Data-Structures-and-Algorithms | /leetcode/easy/binary_tree_paths.py | 1,306 | 4.125 | 4 | """ Binary Tree Paths - https://leetcode.com/problems/binary-tree-paths/
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
# inorder traversal of binary tree
def inorder(root, path, all_paths):
if root:
if root.left is None and root.right is None:
path += str(root.val)
all_paths.append(path)
else:
inorder(root.left, path + str(root.val) + "->", all_paths)
inorder(root.right, path + str(root.val) + "->", all_paths)
path = ""
all_paths = []
inorder(root, path, all_paths)
return all_paths
# a = Solution()
# n1 = TreeNode(1)
# n2 = TreeNode(2)
# n3 = TreeNode(3)
# n5 = TreeNode(5)
# n1.left = n2
# n1.right = n3
# n2.right = n5
# a.binaryTreePaths(n1) |
07e7e87b0a758df0dcc1f4db6e1ad7d1a8024770 | williamf1/Maths-Cheating-Device | /long multiplication.py | 307 | 3.5 | 4 | import time
print("test multi")
#input
no1=raw_input("1st number")
no2=raw_input("times by")
#calculator
no1int=int(no1)
no2int=int(no2)
answer=no1int * no2int
#printing
print("in long multiplication")
print(" ")
print(str(no1)+" x")
print(str(no2))
print("-----")
print(str(answer)) |
af844f63f2d68cde7fd4b7c9c455ca325e17e0fa | whgmltn15/basic_grammar | /basic_loop.py | 3,502 | 3.84375 | 4 | '''
for i in range (10):
print("*"*i)
for i in range (10):
print("*"*(10-i))
for i in range (100):
one = i % 10
if(one%3 == 0 and one != 0):
print("*")
else:
print(i)
for i in range (100):
a = i % 10
b = i // 10
if b % 3 == 0 and a % 3 == 0:
print("**")
elif b % 3 == 0 or a % 3 == 0:
print("*")
else:
print(i)
for i in range(1, 10):
for j in range (1, 10):
print("%d * %d = %d" % (i, j , j * i))
a = int(6)
b = int(3)
while True:
c = int(input("Enter the number: "))
if (c == 1):
print(b + a)
elif (c == 2):
print(b - a)
elif (c == 3):
print (b * a)
elif (c == 4):
print (b // a)
elif c == 10:
break
i = 0
while True:
i = (i + 1)
print(i)
if i == 100:
break
i = 1
j = 1
while i != 10:
i = i + 1
j = 1
while j != 10:
j = j + 1
print ("%d * %d = %d" % (i, j , j * i))
i = 1
j = 1
while True:
i = i + 1
j = 1
if i == 10:
break
while True:
j = j + 1
print("%d * %d = %d" % (i, j, j * i))
if j == 10:
break
a = []
for i in range (1, 101):
a.append(i)
for i in range (100):
print(a[i])
a = [5, 3, 4, 2, 10]
b = 0
c = 3
b,c = c,b
for i in range (5):
if a[i] < b:
b = a[i]
print (b)
a = int(input())
b = [2, 3, 5, 7]
c = 0
for i in range (2, a):
if a % i == 0:
c = 1
break
if c == 0:
print("소수아님")
elif c != 0:
print("소수")
a = "xyz"
b = input()
c = 0
if len(b) == len(a):
for i in range(len(a)):
if a[i] != b[i]:
c = 1
break
if c == 0:
print("같다")
else:
print("다르다")
else:
print("다르다")
def test_function(a, b, c):
for i in range (len(a)):
if a[i] != b[i]:
c = 1
break
if c == 0:
print("같다")
else:
print("다르다")
a = "xyz"
b = input()
c = 0
if len(a) == len(b):
c = test_function(a, b, c)
else:
print("다르다")
def add(x, y):
a = x + y
print ("%d + %d = %d" % (x, y, a))
def sub(x, y):
a = x - y
print ("%d - %d = %d" % (x, y, a))
def mul(x, y):
a = x * y
print ("%d * %d = %d" % (x, y, a))
def div(x, y):
a = x // y
print ("%d // %d = %d" % (x, y, a))
b = 3
while True:
a = int(input("Enter the number: "))
if a == 1:
add(a, b)
elif a == 2:
sub(a, b)
elif a == 3:
mul(a, b)
elif a == 4:
div(a, b)
elif a == 10:
break
def test(a):
a = a + 10
print("in function is a", a)
return a
a = 1
print ('out a is', a)
test(a)
print("out a is 2", a)
def game_369():
for i in range(1, 100):
a = i % 10
b = i // 10
if a % 3 == 0 and b % 3 == 0:
print("**")
elif a % 3 == 0 or b % 3 == 0:
print("*")
else:
print(i)
game_369()
'''
def mul(a, b, i):
while a != 10:
c = i + 1
d = 1
while b != 10:
c = i + 1
print ("%d * %d = %d" % (a, b , a * b))
a = int(input("Enter the Number: "))
b = int(input("Enter the Number: "))
i = 0
mul(a, b, i) |
7e79bea6f9d33873d5b8168bc57d68c8b113dc42 | kapsali29/ml-exercises-coursera | /exercise4/kernels.py | 823 | 3.84375 | 4 | import numpy as np
def gaussianKernel(x1, x2, sigma):
"""
Computes the radial basis function
Returns a radial basis function kernel between x1 and x2.
Parameters
----------
x1 : numpy ndarray
A vector of size (n, ), representing the first datapoint.
x2 : numpy ndarray
A vector of size (n, ), representing the second datapoint.
sigma : float
The bandwidth parameter for the Gaussian kernel.
Returns
-------
sim : float
The computed RBF between the two provided data points.
"""
sim = np.exp((-1) * ((np.linalg.norm(x1 - x2, ord=2) ** 2) / (2) * (sigma ** 2)))
return sim
if __name__ == "__main__":
x1 = np.array([1, 2, 1])
x2 = np.array([0, 4, -1])
sigma = 2
sim = gaussianKernel(x1, x2, sigma)
print(sim)
|
bcc2045e953975bbdf2d78dc2888346072a0af24 | chantigit/pythonbatch1_june2021data | /Python_9to10_June21Apps/project1/listapps/ex5.py | 407 | 4.3125 | 4 | #II.Reading list elements from console
list1=list()
size=int(input('Enter size of list:'))
for i in range(size):
list1.append(int(input('Enter an element:')))
print('List elements are:',list1)
print('Iterating elements using for loop (index based accessing)')
for i in range(size):
print(list1[i])
print('Iterating elements using foreach loop(element based accessing)')
for i in list1:
print(i) |
d9db13350751482d3a3df3f3f8db800f77e05710 | localsnet/Python-Learn | /PCC/ch10/105programming_poll.py | 431 | 3.71875 | 4 | #!/usr/bin/python3
filename = 'poll_responds.txt'
name = ''
respond = ''
with open(filename, 'a') as file_object:
while not (name and respond):
name = input('What is your name? \n Answer: ')
respond = input('Why you like programming? \n Answer: ')
if not (name and respond):
print('you must provide all requested informtaion')
continue
print('Thank you ' + name)
file_object.write(name + ': ' + respond + '\n')
|
2948b578a5ae79c70fb852e22668897ecfbfb4ea | olivergoodman/food-recipes | /coding_util.py | 4,327 | 3.765625 | 4 | import re
import string
def find_term(sentence, term_list):
'''
find which term in term_list exists in the sentence
'''
terms =[]
for term in term_list:
m = re.search(term, sentence, re.IGNORECASE)
if m:
terms.append(term)
return terms
def find_term_by_direction(sentence, ingred_list):
'''
takes in a sentence cleaned of punctuation, list of ingredients
search for each word in a direction for its existence in ingred_list
returns ingredient name
'''
terms = []
direc_lst = sentence.split(' ')
for d in direc_lst:
if d not in stopwords:
for i in ingred_list:
if d in i and i not in terms:
terms.append(i)
return terms
# 'abc. 123.' -> ['abc','123']
def split_sentences(text):
'''
split text into list of sentences
'''
sentences = re.split(r' *[\.\?!\n*][\'"\)\]]* *',text)
return filter(lambda x: len(x)>0,sentences)
def print_help(s):
if s != '':
print s,
def print_list(l):
for x in l:
print '%s;'%x,
print
def print_recipe_readable(recipe):
ingredient_list = recipe['ingredients']
tool_list = recipe['tools']
primary_method_list = recipe['primary_methods']
secondary_method_list = recipe['secondary_methods']
step_list = recipe['steps']
print "The ingredients you need:"
for ingred in ingredient_list:
print "\t",
print_help(ingred['quantity'])
print_help(ingred['measurement'])
print_help(ingred['descriptor'])
print_help(ingred['preparation'])
print_help(ingred['name'])
print
print
print "The tools you need:"
for tool in tool_list:
print '\t%s'%tool
print
print "Primary Methods:"
for me in primary_method_list:
print '\t%s'%me.lower()
print "Secondary Methods:"
for me in secondary_method_list:
print '\t%s'%me.lower()
print
print "Directions:"
i = 1
for step in step_list:
print "Step %d:"%i
print "\tingredients:",
print_list(step['ingredients'])
print "\ttools:",
print_list(step['tools'])
print "\tmethods:",
print_list(step['primary_methods'] + step['secondary_methods'])
print "\tdirection: %s"%step['text']
print "\ttime: %s\n"%step['time']
i += 1
primary_cooking_methods = ['BAKE', 'BOIL', 'BROIL', 'FRY', 'GRILL', 'PAN-BROIL',
'PAN-FRY', 'PARBOIL', 'POACH', 'ROAST', 'SAUTE', 'SIMMER', 'STEAM', 'STEW', 'STIR']
other_cooking_methods = ['AL DENTE', 'BARBECUE', 'BASTE', 'BATTER', 'BEAT', 'BLANCH',
'BLEND', 'CARAMELIZE', 'CHOP', 'CLARIFY', 'CREAM', 'CURE', 'DEGLAZE',
'DEGREASE', 'DICE', 'DISSOLVE', 'DREDGE', 'DRIZZLE', 'DUST', 'FILLET', 'FLAKE',
'FLAMBE', 'FOLD', 'FRICASSEE', 'GARNISH', 'GLAZE', 'GRATE', 'GRATIN',
'GRIND', 'JULIENNE', 'KNEAD', 'LUKEWARM', 'MARINATE', 'MEUNIERE', 'MINCE', 'MIX',
'PARE', 'PEEL', 'PICKLE', 'PINCH', 'PIT', 'PLANKED',
'PLUMP', 'PUREE', 'REDUCE', 'REFRESH', 'RENDER', 'SCALD',
'SCALLOP', 'SCORE', 'SEAR', 'SHRED', 'SIFT', 'SKIM', 'STEEP',
'STERILIZE', 'TOSS', 'TRUSS', 'WHIP', 'WHISK']
stopwords = ['and', 'i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', 'your', 'yours',
'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', 'her', 'hers',
'it', 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves',
'what', 'which', 'who', 'whom', 'this', 'that', 'these', 'those', 'am', 'is', 'are',
'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does',
'did', 'doing', 'a', 'an', 'the', 'but', 'if', 'or', 'because', 'as', 'until',
'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into',
'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down',
'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here',
'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more',
'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so',
'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', 'should', 'now'] |
006994e29c418e5cfe369fc039f4d813e5a79086 | MWessels62/BasicInvestmentInterestCalculator | /Investment_Calculator.py | 1,611 | 4.125 | 4 | #Task12
#Compulsory_Task
#Building an investment calculator to calculate interest earned and total investment value at end of investment period
import math
#Get user input
principal = float(input("Please enter in the amount you are depositing: ")) #This is the principal amount to be invested
interest_rate = (float(input("Type in the interest rate (as a %) [dont type in the '%' symbol]: "))/100) #Divided it by 100 to already get it to a decimal percentage format
years = int(input("Number of years to be invested: ")) #cast to int, assumed for the moment that we wouldnt do part years
interest_type = input("Enter the type of interest to be used [Either 'compound' or 'simple']: ")
#Print out calculation outcomes
print("=====OUTCOME=====")
print("\nThe original investment amount was R",str(principal),", at a",str(interest_rate*100), "% interest rate, for ",str(years)," years.") #Re-prints a summary of the inputs provided by user
if interest_type == "compound":
final_investment_value = principal* math.pow((1+interest_rate),years) #This is the compond interest calculation; Will equal the total value of the investment after the investment period
elif interest_type == "simple":
final_investment_value = principal*(1+interest_rate*years) # Simple interest calculation
else:
print("You have not entered in the interest type correctly, please try again") # Runs if user entered interest type incorrectly
print("The value of the investment at the end of the period, using ", interest_type, " interest is: R", str(round(final_investment_value,2))) # Summary of final investment amount |
69874c3931368518a761e6f994fe0c21a5f0e601 | zhch-sun/leetcode_szc | /852.peak-index-in-a-mountain-array.py | 829 | 3.515625 | 4 | #
# @lc app=leetcode id=852 lang=python
#
# [852] Peak Index in a Mountain Array
#
class Solution(object):
def peakIndexInMountainArray(self, A):
"""
:type A: List[int]
:rtype: int
"""
lo, hi = 1, len(A) - 2
while lo < hi: # invariant [lo, hi]
mid = lo + (hi - lo) // 2
if A[mid] < A[mid + 1]:
lo = mid + 1
else:
hi = mid
return lo
if __name__ == '__main__':
"""
题设:
整个array是个山脉, len(A) > 3, 相邻元素不等, 找峰.
162题相似
解法:
注意不变量[lo, hi], 一定存在解
解的范围实际是 [1, N-2]
"""
s = Solution()
print(s.peakIndexInMountainArray([0,2,1,0]))
print(s.peakIndexInMountainArray([0,1,0]))
|
d6d884b0cc002bb2f946c59cfe529789bfbf41f7 | C-CCM-TC1028-102-2113/tarea-1-programas-que-realizan-calculos-AndresEmiliano | /assignments/18CuentaBancaria/src/exercise.py | 360 | 3.84375 | 4 | def main():
#escribe tu código abajo de esta linea
a = float(input("Dame el saldo del mes anterior:"))
b = float(input("Dame los ingresos:"))
c = float(input("Dame los egresos:"))
d = int(input("Dame el número de cheques:"))
e = d*13
f = a+b-c-e
g = f*.075
h = f-g
print("El saldo final de la cuenta es:")
print(h)
if __name__ == '__main__':
main()
|
7b2effbc1a14615bdc56191d52453af7043d27a7 | sergeyuspenskyi/hillel_homeworks | /HW-16.py | 226 | 3.90625 | 4 | my_dict = {'orange': None,
'red': 'красный',
'green': None,
'yellow': 'желтый',
'black': None}
result = {k: v for k, v in my_dict.items() if v is not None}
print(result) |
b3bcade2fca769788b045bfb1e740ad5268b5fc5 | tomasderner97/customutils2 | /mathutils/__init__.py | 1,057 | 4.09375 | 4 | from scipy.misc import derivative as _derivative
def partial_derivative(f, with_respect_to, arguments, n=1, dx=1e-6):
"""
Calculates partial derivative of function f(a1, a2, a3,...) with respect to
argument in position given by with_respect_to.
Parameters
----------
f : callable, N arguments
function to differentiate
with_respect_to : int in range(0, N)
position of the argument with respect to which f should be differentiated
arguments : N-sequence
arguments to f
n : int
dx : float
"""
arguments_list = list(arguments)
def helper(arg):
""" is the f function with only the argument of interest exposed """
arguments_with_val = arguments_list[:with_respect_to] \
+ [arg] \
+ arguments_list[with_respect_to + 1:]
return f(*arguments_with_val)
if helper(arguments[with_respect_to]) is None:
raise Exception("f doesn't have a return value")
return _derivative(helper, arguments[with_respect_to], n=n, dx=dx)
|
a2e8b66febf9087269581218ae54ca829e78d762 | tlechien/PythonCrash | /Chapter 9/9.6.py | 1,367 | 4.5625 | 5 | """
9-6. Ice Cream Stand: An ice cream stand is a specific kind of restaurant. Write
a class called IceCreamStand that inherits from the Restaurant class you wrote
in Exercise 9-1 (page 162) or Exercise 9-4 (page 167). Either version of
the class will work; just pick the one you like better. Add an attribute called
flavors that stores a list of ice cream flavors. Write a method that displays
these flavors. Create an instance of IceCreamStand, and call this method.
"""
class Restaurant:
def __init__(self, name, cuisine, number_served=0):
self.restaurant_name = name
self.cuisine_type = cuisine
self.number_served = number_served
def describe_restaurant(self):
print(*map(lambda x: f"\n{x} : {self.__getattribute__(x)}", vars(self)))
def open_restaurant(self):
print("The restaurant is open.")
def set_number_served(self, nbr):
self.number_served = nbr
def increment_number_served(self, nbr):
self.number_served += nbr
class IceCreamStand(Restaurant):
def __init__(self, name, cuisine, flavor, number_served=0):
super().__init__(name, cuisine, number_served)
self.flavor = flavor
def flavors(self):
print(*self.flavor)
if __name__ == '__main__':
ice = IceCreamStand("Ice", "gelato", ["Vanilla", "Chocolate", "Strawberry"])
ice.flavors() |
2123eec112ceb537b4912bc741876e3acb1e1e47 | Lemito66/Python | /Derivadas_Ejemplo.py | 695 | 4.0625 | 4 | from sympy import Derivative, diff, simplify,Symbol
x=Symbol('x')
y=Symbol('y')
fxy = x*2*y+x*2*y*2+x+y-3
dx=simplify(diff(fxy, x))
dy = Derivative(fxy, y).doit()
simplify(dy)
print (dx)
print (dy)
from sympy import Derivative, diff, simplify,Symbol
x=Symbol('x')
y=Symbol('y')
fxy = x*2*y+x*y*2+x+y-3
dx=simplify(diff(fxy, x))
dy = Derivative(fxy, y).doit()
simplify(dy)
print (dx)
print (dy)
fx1=simplify(diff(dx, x))
fx2=simplify(diff(dy, x))
fy1=simplify(diff(dx, y))
fy2=simplify(diff(dy, y))
print (fx1)
print (fx2)
print (fy1)
print (fy2)
fs1=dx.subs(x, 1)
fs11=fs1.subs(y, 1)
print (fs11)
A=int(input( "ingrese la formula: \n"))
fs1=dx.subs(x, 1)
fs11=fs1.subs(y, 1)
print (fs11) |
a4b3ecac0f4f8cddbbc1e513eb8d70eb4ff8213b | dasqueel/lambda-challenges | /rotationPoint.py | 832 | 3.859375 | 4 | # def find_rotation_point(words):
# sort = sorted(words)
# return words.index(sort[0])
# def find_rotation_point(words):
# idx = 0
# while (words[idx] < words[idx + 1]): idx += 1
# return idx + 1
def find_rotation_point(words):
firstWord = words[0]
floorIdx = 0
ceilIdx = len(words) - 1
while floorIdx < ceilIdx:
# guess point between two idxs
midpoint = (ceilIdx + floorIdx) // 2
if words[midpoint] >= firstWord:
# go right
floorIdx = midpoint
else:
ceilIdx = midpoint
return ceilIdx
words = [
'ptolemaic',
'retrograde',
'supplant',
'undulate',
'xenoepist',
'asymptote',
'babka',
'banoffee',
'engender',
'karpatka',
'othellolagkage',
]
print find_rotation_point(words) |
13401de098576b78c8b17c18ba18ba7a68deeeda | Eitherling/Python_homework1 | /homework7_9.py | 695 | 3.828125 | 4 | # -*- coding:utf-8 -*-
sandwich_orders = ['Babiq', 'pastrami', 'tuna', 'pastrami', 'cip', 'pastrami']
finished_sandwiches = []
while sandwich_orders:
sandwich = sandwich_orders.pop()
print('I made ' + sandwich + ' for you.')
finished_sandwiches.append(sandwich)
print("\nI have made these:")
for sandwich in finished_sandwiches:
print(sandwich.title())
# pastrami ˣ
sandwich_orders = ['Babiq', 'pastrami', 'tuna', 'pastrami', 'cip', 'pastrami']
print("\n--- The pastrami has been sold out. ---")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print("The new sandwich list is:")
print(sandwich_orders)
|
eaa167afb1e87722575f3f247298d694de8f573d | Denzaaaaal/python_crash_course | /Chapter_7/multiple_of_ten.py | 346 | 4.375 | 4 | # Writing prompt
prompt = "Let's find out if a number is a multiple of 10"
prompt += "\nPlease enter a number: "
number = input(prompt)
number = int(number)
# Finding out if the number is divisable by 10
if number % 10 == 0:
print (f"The number {number} is a multiple of 10")
else:
print (f"The number {number} is not a multiple of 10") |
069f5c227fcdfe62c625d1188945fcac6873443e | nathan-builds/python_labs | /iterated_remove_pairs.py | 360 | 3.578125 | 4 | def iterated_remove_pairs(items):
i = 1
while i < len(items) - 1:
if items[i - 1] == items[i]:
del (items[i - 1:i + 1])
i = 1
elif items[i + 1] == items[i]:
del (items[i:i + 2])
i = 1
else:
i += 1
if items[0] == items[1]:
items.clear()
print(items)
|
dc594617ee9c31c59b456c7ef427491b4b80b574 | shubhangi2803/Practice_Python | /Exercise 3.py | 930 | 4.4375 | 4 | # Take a list, say for example this one:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# and write a program that prints out all the elements of the list
# that are less than 5.
# Extras:
# 1. Instead of printing the elements one by one, make a new list
# that has all the elements less than 5 from this list in it and
# print out this new list.
# Write this in one line of Python.
# 2. Ask the user for a number and return a list that contains only
# elements from the original list a that are smaller than that number
# given by the user.
x=input("Enter space separated numbers to form a list : ")
li=list(map(int,x.split()))
print("List : {}".format(li))
print("Numbers less than 5 : ")
##for num in li:
## if num<5:
## print(num)
li2=list(filter(lambda x:x<5,li))
print(li2)
num=int(input("Enter a number to have a list with numbers less than that number : "))
li3=list(filter(lambda x:x<num,li))
print(li3)
|
ecccfaa71bdd2d5e80665c1eb81a4d8baac4a47a | Iamankitatiwari/Python-Basic-problems | /AddTwoNumber.py | 117 | 3.8125 | 4 | a = int(input("Enter first number to add:"))
b = int(input("Enter second number to add:"))
c = print(a + b)
print (c) |
05671b2a3c3c992f282743c33dc73c168e9a508d | eric496/leetcode.py | /two_pointers/167.two_sum_II_input_array_is_sorted.py | 1,632 | 3.921875 | 4 | """
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
"""
# Solution 1: binary search - O(nlogn) TC
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
low = i + 1
high = len(nums) - 1
while low <= high:
mid = low + (high - low >> 1)
if nums[mid] == target - nums[i]:
return [i + 1, mid + 1]
elif nums[mid] < target - nums[i]:
low = mid + 1
elif nums[mid] > target - nums[i]:
high = mid - 1
return []
# Solution 2: two pointers - O(n) TC
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
i, j = 0, len(nums) - 1
while i < j:
twosum = nums[i] + nums[j]
if twosum == target:
return [i+1, j+1]
elif twosum < target:
i += 1
elif twosum > target:
j -= 1
return []
|
7d6ec622da12cb53fecdb7c31fa8dba9b526951e | nkandra/Udemy | /DSA/string_compression.py | 1,289 | 3.953125 | 4 | #String compression problem
#example: AAAABBBCCC should give A4B3C3
from collections import OrderedDict
def string_compression(string):
count = OrderedDict()
for char in string:
if char in count:
count[char] += 1
else:
count[char] = 1
result = ""
for k, v in count.items():
result += "{}{}".format(k,v)
return result
#without using ordered dict
def string_compression2(string):
if len(string) == 0:
return ""
result = ""
start_char = string[0]
char_count = 1
for char in string[1:]:
if char == start_char:
char_count += 1
else:
start_char = char
char_count = 1
result = result + start_char + str(char_count)
return result
# Run length compression algorithm
def string_compression3(s):
l = len(s)
r = ""
if l == 0:
return ""
i = 1
cnt = 1
while i < l:
if s[i] == s[i-1]:
cnt += 1
else:
r = r + s[i-1] + str(cnt)
cnt = 1
i = i+1
r = r + s[i-1] + str(cnt)
return r
print string_compression("AAAAABBBBCCCDDE")
print string_compression2("AAAAABBBBCCCDDE")
print string_compression2("")
print string_compression3("AAEEDDDDDRRRRRC")
|
319102a641d92426b0f6d4acc9c8587fc4024fec | YuxuanSu-Sean/learning | /learnpython/demo_parrot_pizza.py | 391 | 4.03125 | 4 | #编写一个循环,提示用户输入一系列的比萨配料,并在用户输入'quit'的时候结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添加这种配料。
prompt = "Please Enter a pizza topping!"
prompt += "\n"
while True:
message = input(prompt)
if message == 'quit':
break
else:
print(message) |
3d932a1f99d2dc012434a3bc9bc0ff8c285d90c4 | TheWildMonk/automated-birthday-wisher-project | /main.py | 1,247 | 3.578125 | 4 | import os
import random
import smtplib
import datetime as dt
import pandas as pd
# Emails & password
email = "demo@email.com"
password = "##########"
# Create a dictionary from birthdays.csv
df_birthdays = pd.read_csv("birthdays.csv")
birthday_dict = df_birthdays.to_dict(orient="records")
# Check whether any birthday matches today's date
today = dt.datetime.today()
for name in range(len(birthday_dict)):
if today.month == birthday_dict[name]["month"] and today.day == birthday_dict[name]["day"]:
receiver = birthday_dict[name]["email"]
# Choose a random letter from letter_templates directory
letter_template = random.choice(os.listdir("letter_templates"))
with open(f"letter_templates/{letter_template}") as data_file:
data = data_file.read()
letter = data.replace("[NAME]", birthday_dict[name]["name"])
# Send the birthday wish email
with smtplib.SMTP("smtp.gmail.com") as connection:
connection.starttls()
connection.login(user=email, password=password)
connection.sendmail(from_addr=email, to_addrs=receiver, msg=f"subject: HAPPY BIRTHDAY!!!\n\n"
f"{letter}")
|
f0ffd0cbe4d29ba673cc55ecacb2aaf15be2d0e5 | niranjan-nagaraju/Development | /python/hackerrank/challenges/next_greater_element/next_greater_element.py | 1,943 | 4.125 | 4 | '''
https://www.hackerrank.com/contests/second/challenges/next-greater-element
Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in array. Elements for which no greater element exist, consider next greater element as -1.
For the input array [4, 5, 2, 25}, the next greater elements for each element are as follows.
Element --> NGE
4 --> 5
5 --> 25
2 --> 25
25 --> -1
For the input array [13, 7, 6, 12}, the next greater elements for each element are as follows.
Element --> NGE
13 --> -1
7 --> 12
6 --> 12
12 --> -1
Input Format
The first line of input contains an integer n denoting the size of the array
The next line contains n space seperated array elements in integer range
0 < n < = 65535
Output Format
Output consists of n lines
Each line should contain 2 space seperated integers
The first integer should represent the array element and second integer should represent the next greater element
Sample Input
4
4 5 2 25
Sample Output
4 5
5 25
2 25
25 -1
'''
'''
Solution outline
0. Initialize nge = [-1]*n
nge : [-1, -1, -1, ..., -1]
1. Use a stack and solve the problem of next-greater-element like matching parantheses.
2. For each item in array, array[i], pop every x from the stack if array[i] > array[x]
also record nge[x] = array[i]
3. Push i onto stack
'''
def next_greater_element(array):
stack = []
nge = [-1] * len(array)
for i in xrange(len(array)):
while stack and array[stack[0]] < array[i]:
x = stack.pop(0)
nge[x] = array[i]
stack.insert(0, i)
return nge
if __name__ == '__main__':
assert next_greater_element([1,2,3,4]) == [2,3,4,-1]
assert next_greater_element([3,1,2,4]) == [4,2,4,-1]
assert next_greater_element([4,5,2,25]) == [5,25,25,-1]
assert next_greater_element([13,7,6,12]) == [-1,12,12,-1]
assert next_greater_element([4,3,2,1]) == [-1,-1,-1,-1]
|
7e512dfc27cf3c632dea5db8e25eb4e472f2d9c7 | TaylorWhitlatch/Python | /exercises.py | 177 | 3.703125 | 4 | i = 1
j = 1
for i in range (1, 11):
print ("\n** %ss Multiplication Table **" % (i))
for j in range (1, 11):
x = i * j
print("%s X %s = %s" % (i, j, x))
|
c343c27a751aaaa6c63b56116f616a99e99651eb | alexsv/checkio | /sci_islands.py | 1,424 | 3.828125 | 4 | from collections import defaultdict
def print_replaces(replaces):
for k in sorted(replaces.keys()):
print "%d: %d %s" % (k, replaces[k][0], sorted(replaces[k][1]))
def checkio(data):
def get_value(x,y):
if x < 0 or y < 0 or x >= len(data[0]) or y >= len(data):
return 0
else:
return data[y][x]
curr = 1
replaces = defaultdict(lambda: [0, set()])
for y in range(len(data)):
for x in range(len(data[y])):
if get_value(x, y) > 0:
if get_value(x - 1, y) == 0:
curr += 1
replaces[curr][0] += 1
data[y][x] = curr
for dx in [-1, 0, 1]:
v = get_value(x + dx, y - 1)
if v > 0:
replaces[curr][1].add(v)
for i in reversed(sorted(replaces.keys())):
sq, upper = replaces[i][0], sorted(replaces[i][1])
if len(upper) > 0:
top = upper[0]
replaces[top][0] += sq
replaces[i][0] = 0
for j in upper[1:]:
replaces[j][1].add(top)
return sorted([i for i in map(lambda x: x[0], replaces.values()) if i > 0])
if __name__ == "__main__":
print checkio([[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0],
[0, 0, 1, 0, 0],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1]])
|
e60fc45ee4ca4a6726c0b4f6e1427243f46d7d8a | SatyaAccenture/PythonCodes | /arraysortandmaxelemlogic.py | 496 | 3.671875 | 4 | from numpy import *
arr1=array([6,7,8,9,10,13])
arr2=array([15,13,9,3,21,7])
i=len(arr2)
arr3=zeros(i,int)
for a in range(0,i):
arr3[a]=arr1[a]+arr2[a]
a+=1
print(arr3)
#sorting
# for a in range(0,i):
# for b in range(a+1,i):
# temp=0
# if arr3[a] > arr3[b]:
# temp=arr3[b]
# arr3[b]=arr3[a]
# arr3[a]=temp
# b+=1
# a += 1
print(arr3)
#max element
max=0
for a in range(0,i):
if arr3[a] > max :
max=arr3[a]
a += 1
print(max) |
58d81ca1e08ec5647066bc68c6d337e06a4ba245 | DahlitzFlorian/article-introduction-to-itertools-snippets | /itertools_combinations_with_replacement.py | 202 | 3.5625 | 4 | from itertools import combinations_with_replacement
l = [1, 2, 3]
result1 = list(combinations_with_replacement(l, 3))
result2 = list(combinations_with_replacement(l, 2))
print(result1)
print(result2)
|
e4cccc5c85e8b3229dd1478552cac81eb175af4e | Citrie/Euler | /1.py | 262 | 4.125 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
n = 0
for i in range(1000):
if not i%3 or not i%5: n += i
print n
|
b7aa0944354a84039537bdf5050afd72891ffcd3 | jakubbaron/dailycodingproblem | /No010/main.py | 2,292 | 4.1875 | 4 | #!/usr/bin/env python
# Good morning. Here's your coding interview problem for today.
# This problem was asked by Apple.
#
# Implement a job scheduler which takes in a function f and an integer n,
# and calls f after n milliseconds.
import heapq
import time
import threading
current_micros_time = lambda: int(round(time.time() * 1000000))
class Task:
def __init__(self, entry, micros):
self.entry = entry
self.micros = micros
def run(self):
if self.entry:
self.entry()
def __gt__(self, other):
return self.micros > other.micros
def __lt__(self, other):
return self.micros < other.micros
class Scheduler(threading.Thread):
def __init__(self):
self.queue = []
self.mutex = threading.Lock()
self.run_scheduler = True
super(Scheduler, self).__init__()
def toggle_run_scheduler(self):
self.run_scheduler = not self.run_scheduler
if self.run_scheduler:
self.run()
def run(self):
while self.run_scheduler:
if not self.queue:
time.sleep(0.0001) #sleep 100 microseconds
continue
if current_micros_time() >= self.queue[0].micros: #What if there are more tasks that were to be run now?
while self.queue and current_micros_time() >= self.queue[0].micros:
self.mutex.acquire()
next_task = heapq.heappop(self.queue)
next_task.run()
self.mutex.release()
time.sleep(0.0001) #sleep 100 microseconds
print "Scheduler has been stopped"
def schedule(self, entry, n):
time_to_run_at = current_micros_time() + n * 1000
print str(current_micros_time()) + " Scheduling a task to be run at: " + str(time_to_run_at)
task = Task(entry, time_to_run_at)
self.mutex.acquire()
heapq.heappush(self.queue, task)
self.mutex.release()
def hello_world():
print "Running Hello World at: " + str(current_micros_time())
print "Hello world"
def hello_world2():
print "Running Hello World 2 at: " + str(current_micros_time())
print "Hello world 2"
def main():
s = Scheduler()
s.start()
s.schedule(hello_world, 1000)
time.sleep(2)
s.schedule(hello_world2, 500)
s.schedule(hello_world2, 5000)
s.schedule(hello_world, 1000)
time.sleep(10)
s.toggle_run_scheduler()
s.join()
if __name__ == "__main__":
main()
|
e4f690fe509907d1283c9a449bea28edc889cc90 | Gmle7/myPythonCode | /generator.py | 582 | 3.640625 | 4 | #生成器
# G = (i * i for i in range(1, 11))
# for g in G:
# print(g)
# def fibonacci(max):
# n, a, b = 0, 0, 1
# while n < max:
# yield (b)
# a, b = b, a + b
# n = n + 1
# return 'done'
# F = fibonacci(8)
# while True:
# try:
# x = next(F)
# print('g', x)
# except StopIteration as e:
# print('Generator return value:', e.value)
# break
def pascalsTriangle():
L=[1]
while True:
yield L
L=[L[0]]+[L[n]+L[n+1] for n in range(len(L)-1)]+[L[-1]]
p=pascalsTriangle()
next(p)
|
9d8d3fa0a9b42f9921e0c7d865354352fc151722 | git-vish/Soft-Computing-Lab | /BackProp_XOR.py | 1,880 | 3.703125 | 4 | import numpy as np
import matplotlib.pyplot as plt
# STEP-1: initialization
X = np.array([(0, 0), (0, 1), (1, 0), (1, 1)])
Y = np.array([[0], [1], [1], [0]])
Y_hat = None
W1 = np.random.uniform(size=(2, 2))
b1 = np.zeros((1, 2))
W2 = np.random.uniform(size=(2, 1))
b2 = np.zeros((1, 1))
epochs = 10000
alpha = .1
E = {'x': [], 'y': []} # for plotting
# STEP-2: defining required functions
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
def compute_error(e): # calculates mean squared error
return (1 / 2) * sum(e ** 2)
# STEP-3: learning
for _ in range(1, epochs+1):
# forward propagation
Z1 = np.dot(X, W1) + b1
A1 = sigmoid(Z1)
Z2 = np.dot(A1, W2) + b2
A2 = sigmoid(Z2)
Y_hat = A2
# backward propagation
error = Y - A2
d2 = error * sigmoid_derivative(A2)
error_hidden_layer = d2.dot(W2.T)
d1 = error_hidden_layer * sigmoid_derivative(A1)
# updating parameters
W2 += A1.T.dot(d2) * alpha
b2 += np.sum(d2, axis=0, keepdims=True) * alpha
W1 += X.T.dot(d1) * alpha
b1 += np.sum(d1, axis=0, keepdims=True) * alpha
# printing error and accuracy
if _ % 1000 == 0:
e = compute_error(error)
E['y'].append(e)
E['x'].append(_)
print('Epoch:', _)
print('loss:', e)
print('-----------------------------')
# STEP-4: printing results
print('\nLearning Completed')
print('Results: ')
print('x1 \t x2 \t xor')
for x, y in zip(X, Y_hat):
print(x[0], '\t', x[1], '\t', round(y[0], 3))
# STEP-5: visualization
plt.plot(E['x'], E['y'])
plt.title('Learning')
plt.xlabel('no. of Epochs')
plt.ylabel('Error')
plt.show()
'''
DESCRIPTION:
1. np.random.uniform(size=(row, col)) : similar to np.random.randn(), but returns uniformly distributed numbers
2. round(float, digits): round(1.265, 2) ==> 1.27
'''
|
22ad2007c37cec25c6b09e923d55b8b4580c6e1e | codypeak/Intro-Python-II | /examples/seanplayer.py | 306 | 3.578125 | 4 | #player needs a starting place and ability to move around map
class Player:
def __init__(self, current_room):
self.current_room = current_room
def __repr__(self):
return f"Player is in {self.current_room}"
#if current room werent here computer would find out until run time.
|
f955471e6ad75b4896c9bdee3873cfaf40a39c4f | mbslak98/ScriptingEssentials | /Mod02Tutorial (1).py | 2,120 | 4.0625 | 4 | #Matthew Selakovich
#Mod02Tutorial
import random
import copy
def rando_insert(thing_being_inserted):
position = random.randint(0,9)
my_list.insert(position, thing_being_inserted)
counter = 0
my_list = []
ints_only=copy.deepcopy((my_list))
while counter < 10:
list_item = input('Please enter a word or a number: ')
my_list.append(list_item)
counter += 1
else:
print(' ')
#Task 1
print(' ')
print('Task 1')
print('This list has 10 items ' + ' '+str(len(my_list) == 10))
#Task 2
print(' ')
print('Task 2')
print(my_list)
#Task 3
print(' ')
print('Task 3')
first_thing = my_list[0]
my_list[0] = my_list[-1]
my_list[-1] = first_thing
print(my_list)
#task 4
print(' ')
print('Task 4')
print(my_list[0:3], my_list[-3:])
#task 5
print(' ')
print('Task 5')
for i in my_list:
print(i)
#task 6
print('Task 6')
if 'cat' in my_list:
print('There is a cat in my list')
else:
print('There is no cat in my list')
#Task 7
print(' ')
print('Task 7')
another_item = input('Please insert the name of a Marvel character: ')
rando_insert(another_item)
#Task 8
print('\nTask 8')
print(another_item + ' is at index ' +str(my_list.index(another_item)))
#Task 9
print(' ')
print('Task 9')
for list_item in my_list:
try:
int(list_item)
ints_only.append(int(list_item))
except:
continue
ints_only.sort()
print('These are the integers from the list')
print(ints_only)
#Task 10
print(' ')
print('Task 10')
my_tuple = tuple(my_list)
print(my_tuple)
#Task 11
print(' ')
print('Task 11')
try:
my_tuple[0] = 'cat'
except:
print('Tuples are immutable!')
#Task 12
print(' ')
print('\nTask 12')
list_in_list = [[1,2,3], ['a','b','c']]
for i in list_in_list:
for j in i:
print(j)
|
abd365a52091e2c9511ec36084bddcd90df9c722 | cbermudez97/fuzzy-logic-project | /fuzzy_logic/utils.py | 560 | 3.578125 | 4 | def isFloatIn(x, m=None, M=None):
try:
float(x)
except:
raise ValueError('Data must be a float.')
if not m is None and not m <= float(x):
raise ValueError(f'Data must be greater or equal than {m}.')
if not M is None is None and not M >= float(x):
raise ValueError(f'Data must be lesser or equal than {M}.')
def inputUntil(msg, cond):
while True:
data = input(msg)
try:
cond(data)
return data
except Exception as e:
print(str(e))
continue
|
43be5a287bb2b25ec85a22bcb5c8ba686ae8fe49 | yandrea888/momento1-algoritmos | /algoritmo9.py | 227 | 4.03125 | 4 |
num = int(input("Ingrese un número: "))
if num==0 :
print("El número", num, "no es par ni impar")
elif num % 2 == 0:
print('El número', num, 'es par.')
elif num %2 != 0:
print('El número', num, 'es impar.')
|
308b140dd86db5b8b66fcc2e680d95a10a162fab | august110th/pythonProject2 | /main.py | 3,999 | 3.859375 | 4 |
class Student:
def __init__(self, name, surname, gender):
self.name = name
self.surname = surname
self.gender = gender
self.finished_courses = []
self.courses_in_progress = []
self.grades = {}
def add_courses(self, course_name):
self.finished_courses.append(course_name)
def rate_lector(self, lecturer, course, grade):
if isinstance(
lecturer, Lecturer
) and course in lecturer.courses_attached and course in self.courses_in_progress:
if course in lecturer.grades:
lecturer.grades[course] += [grade]
else:
lecturer.grades[course] = [grade]
else:
return 'Ошибка'
def __str__(self):
print("print(some_student)")
print(f"Имя: {self.name}")
print(f"Фамилиия: {self.surname}")
class Mentor:
def __init__(self, name, surname):
self.name = name
self.surname = surname
self.courses_attached = []
class Reviewer(Mentor):
def rate_hw(self, student, course, grade):
if isinstance(
student, Student
) and course in self.courses_attached and course in student.courses_in_progress:
if course in student.grades:
student.grades[course] += [grade]
else:
student.grades[course] = [grade]
else:
return 'Ошибка'
def __str__(self):
print("print(some_reviewer)")
print(f"Имя: {self.name}")
print(f"Фамилия: {self.surname}")
class Lecturer(Mentor):
def __init__(self, name, surname):
self.name = name
self.surname = surname
self.courses_attached = []
self.grades = {}
def __str__(self):
print("print(some_lecturer)")
print(f"Имя: {self.name}")
print(f"Фамилия: {self.surname}")
best_student = Student('Ruoy', 'Eman', 'your_gender')
best_student.courses_in_progress += ['Python']
worst_student = Student("Petr", "Ivanov", "male")
worst_student.courses_in_progress += ["Git"]
middle_student = Student("Jack", "Daniels", "male")
middle_student.courses_in_progress += ["Python", "Git"]
cool_reviewer = Reviewer('Some', 'Buddy')
cool_reviewer.courses_attached += ['Python']
usual_reviewer = Reviewer("Phil", "Collins")
usual_reviewer.courses_attached += ["Git"]
cool_reviewer.rate_hw(best_student, 'Python', 10)
cool_reviewer.rate_hw(best_student, 'Python', 9)
cool_reviewer.rate_hw(best_student, 'Python', 10)
cool_reviewer.rate_hw(middle_student, "Python", 8)
cool_reviewer.rate_hw(middle_student, "Python", 7)
cool_reviewer.rate_hw(middle_student, "Python", 9)
usual_reviewer.rate_hw(worst_student, "Git", 4)
usual_reviewer.rate_hw(worst_student, "Git", 5)
usual_reviewer.rate_hw(worst_student, "Git", 4)
cool_lecturer = Lecturer("Ivan", "Petrov")
cool_lecturer.courses_attached += ['Python']
bad_lecturer = Lecturer("Mick", "Jagger")
bad_lecturer.courses_attached += ["Git"]
best_student.rate_lector(cool_lecturer, "Python", 10)
best_student.rate_lector(cool_lecturer, "Python", 9)
best_student.rate_lector(cool_lecturer, "Python", 10)
worst_student.rate_lector(bad_lecturer, "Git", 2)
worst_student.rate_lector(bad_lecturer, "Git", 5)
worst_student.rate_lector(bad_lecturer, "Git", 6)
# print(cool_lecturer.grades)
# print(middle_student.grades)
for key, value in middle_student.grades.items():
print(sum(value) / len(value))
lecturer_grades = []
student_grades = []
student_grades.append(best_student.grades)
student_grades.append(middle_student.grades)
student_grades.append(worst_student.grades)
lecturer_grades.append(cool_lecturer.grades)
lecturer_grades.append(bad_lecturer.grades)
print(student_grades)
print(lecturer_grades)
# for key, value in lecturer_grades:
# print(key)
# def course_stat(student):
# if isinstance(student, Student) and course in student.courses_in_progress:
bad_lecturer.__str__()
|
bd7bae4035545ed93b0c920bc3fc1c6e826b5125 | Dericrp6/CYPEricRP | /funciones.py | 2,114 | 4.34375 | 4 | #funciones python
def sumar (x , y):
z = x + y
return z
def restar (x , y):
return x - y
def mi_print( texto ):
print(f"este es mi print: {texto}")
def multiplica (valor, veces):
if veces == None :
print("Debes enviar el ssegundo argumento de la segunda funcion")
else:
print(valor * veces)
def comanda(mesa , comensal , entrada, medio , fuerte , postre="Gela de limon"): #argumneto variables internas de la funcion
print(f"Mesa: {mesa} comensal: {comensal}")
print(f"\t Entrada: {entrada}")
print(f"\t Segundo tiempo: {medio}")
print(f"\t Plato fuerte: {fuerte}")
print(f"\t Postre: {postre}")
def comanda2( **comida ):
llaves = comida.keys()
for elem in llaves:
print(elem, "-->" , comida[elem])
def imprime_argumentos( *argumentos ):
for index in range(len(argumentos)):
print(argumentos[index])
"""
#print('---->', argumentos, '<-----')
"""
"""
#for ele in argumentos: #for con iteracion
print(ele)
"""
a = 10
b = 5
c = sumar (a,b)
print(f"la suma de {a} y {b} es {c}")
c = restar(a,b)
print(f"la resta de {a} y {b} es {c}")
mi_print("Hola!!!")
multiplica(10,3)
multiplica(10, None)
multiplica('hola',3)
comanda(2, 1 ,"Ensalada", "Sopa de rana", "Filete de pompi de sirena", "Flan") #parametro los valor de la funcion
comanda("Ensalada", "Sopa de rana", "Filete de pompi de sirena", "Flan", 2, 1)
comanda(entrada="Ensalada", medio="Sopa de rana", fuerte="Filete de pompi de sirena" , mesa=2, comensal=1)
#argumentos por defecto
comanda(entrada="Ensalada", medio="Sopa de rana", fuerte="Filete de pompi de sirena", mesa=2, comensal=1)
imprime_argumentos('hola', True, 3.1416, 1000, {'id':'sc01', 'nombre':'juan'}) #Tupla
imprime_argumentos()
#diccionario
comanda2(entrada="Ensalada", medio="Sopa de rana", fuerte="Filete de pompi de sirena", mesa=2, comensal=1, postre="Strudel de manzana" , bebida='coca ligh' )
"""
# def main (): otra forma de funcion
if __name__ == '__main__' : #¿se mando a ejecutar (interpretar) este archivo?
main()
"""
|
9d004e03e146c7497ccd0ece9468a7483cefdc2f | Sahil12S/Working-with-PyGame | /BouncingBall/script.py | 1,059 | 4.125 | 4 | # Simple program to see working of PyGame
# Import necessary modules
import sys, pygame
# Initialize PyGame
pygame.init()
size = width, height = 1280, 720 # Set window size
speed = [2, 2] # Set movement speed
black = 0, 0, 0
screen = pygame.display.set_mode(size) # Create graphical window
ball = pygame.image.load("intro_ball.gif") # Load image
ballrect = ball.get_rect() # For storing rectangular coordinates.
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed) # move ball with set speed
# If ball goes outside the screen, we reverse the speed in that direction.
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black) # Fill screen with black color.
screen.blit(ball, ballrect) # Draw image onto screen.
pygame.display.flip() # Make everything visible.
|
e17fd8675face7223471fcf7f3ee15a094902d66 | udhayajillu17/python_player | /hello5times.py | 502 | 3.65625 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: 16cse041
#
# Created: 21/10/2017
# Copyright: (c) 16cse041 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
count = 5
while (count < 9):
print 'The count is:', count
count = count + 5
print "hello!"
if __name__ == '__main__':
main()
|
b1ba5d1fe442e7af664c4afddd4999695f03076a | AlexandraMilts/Web_Crawler | /Replacement.py | 578 | 3.734375 | 4 | # Example 1
# marker = "AFK"
#replacement = "away from keyboard"
#line = "I will now go to sleep and be AFK until lunch time tomorrow."
#Example 2 # uncomment this to test with different input
marker = "EY"
replacement = "Eyjafjallajokull"
line = "The eruption of the volcano EY in 2010 disrupted air travel in Europe for 6 days."
###
# YOUR CODE BELOW. DO NOT DELETE THIS LINE
###
length = len(marker)
start = line.find(marker)
to_replace = line [start:start+length]
end = start + length
replaced = line[0:start] + replacement + line[end:]
print(replaced) |
418170c2f2d6299ba5b533d7dc0b77e4ccb47455 | gabrielsalesls/curso-em-video-python | /ex029.py | 268 | 3.984375 | 4 | num = float(input('Digite a velocidade do carro: '))
if num >= 80:
multa = (num - 80) * 7
print('Você esta {} acima da velocidade maxima de 200km, sua multa é {}'.format(num - 80, multa))
else:
print("Você esta dentro do limite de velocidade.")
|
6793cac9a32e623141ada2157cfbfb8850c80c9b | starswap/ComSoc-Blockchain | /RSA.py | 275 | 3.5 | 4 | import random
def miller_rabin(integer):
twoToS = 1
S = 0
while (integer%twoToS == 0):
twoToS *= 2
S+=1
twoToS /= 2
S -= 1
q = integer/twoToS
a = random.randint(1,integer)
if (pow(a,q,integer)):
return True
else:
for (i in range(S)):
|
0645d6ea95cf2d756e3010f87693185069f74f53 | DouglasKosvoski/URI | /1051 - 1060/1052.py | 423 | 3.875 | 4 | # Accepted
num = int(input())
if num == 1: print('January')
elif num == 2: print('February')
elif num == 3: print('March')
elif num == 4: print('April')
elif num == 5: print('May')
elif num == 6: print('June')
elif num == 7: print('July')
elif num == 8: print('August')
elif num == 9: print('September')
elif num == 10: print('October')
elif num == 11: print('November')
elif num == 12: print('December')
|
7173099848bc52181007cadbb86da3204f6d8d80 | hossamelmansy/computer-algorithms | /app/bruteForce/python/closestPoints.py | 814 | 3.65625 | 4 | import math
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--points')
args = parser.parse_args()
points = eval('[' + args.points + ']')
minDistance = float('inf')
print "Minimum distance:", minDistance
print ""
for i in range(len(points)):
for j in range(i+1, len(points)):
x1, y1 = points[i]
x2, y2 = points[j]
distance = math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2))
print "Distance between (%d, %d) and (%d, %d) = %d" % (
x1, y1, x2, y1, distance)
if distance < minDistance:
minDistance = distance
point1 = i
point2 = j
print ""
x1, y1 = points[point1]
x2, y2 = points[point2]
print "Minimum distance between (%d, %d) and (%d, %d) = %d" % (
x1, y1, x2, y2, minDistance)
|
159c0d25e9fc9b12a5f3b11c8ac4b32afced063b | adarshk007/DATA-STURCTURES-and-ALGORITHMS | /DATA STRUCTURE/Linked_list/circular_linkedlist.py | 2,615 | 4.59375 | 5 | #Circular_linked_list
#SUB TOPICS :
"""
* Insertion in an empty list
* Insertion at the beginning of the list
* Insertion at the end of the list
* Insertion in between the nodes
"""
# ADARSH KUMAR
#--------------------------------Description-----------------------------------#
"""
Circular linked list:
Is a linked list where all nodes are connected to form a circle.
There is no NULL at the end.
A circular linked list can be a singly or doubly circular linked list.
"""
#APPLICATION
"""
Used in queues
Used in Fibonacci Heap.
"""
#__________________________________CODE________________________________________#
class Node(object): #not necessary to use define object
def __init__(self,data):
self.data=data
self.next=None
class Circular_Linked_List(object):
def __init__(self): #self has always the last with none instance
self.last=None #here we have initialised with last only
self.size=0
#therefore,only last will be available after object function calling
def add1(self,data):
"""Insertion in an empty list"""
node=Node(data)
self.last=node
node.next=node
self.size=self.size+1
def add(self,data,pos):
if(self.last is None):
self.add1(data)
elif(self.last is not None):
if(pos==0):
#Insertion in beginning of the list
node=Node(data)
node.next=self.last.next
self.last.next=node
#insertion in the end
elif(pos==self.size):
node=Node(data)
node.next=self.last.next
self.last.next=node
self.last=node
elif(pos>0 and pos<self.size):
#insertion in between 2 nodes
node=Node(data)
cur=self.last
while(pos>0):
pos=pos-1
cur=cur.next
y=cur.next
cur.next=node
node.next=y
self.size=self.size+1
def getsize(self): #to print size
print("size",self.size,sep=" ")
def printele(self): #to print elements
e=self.size
cur=self.last.next
print("circular_linked_list :",end=" ")
while(e>0):
e=e-1
print(cur.data,end=" ")
cur=cur.next
print()
n=Circular_Linked_List()
n.add(5,0)
n.add(4,0)
n.add(3,1)
n.getsize()
n.printele()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.