blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
6610b6e86f1ed82c852c6826fb28b2dec1aaa829
|
RichInCode/projectEulerProblems
|
/summationOfPrimes.py
| 481 | 3.734375 | 4 |
import largestPrimeFactor
import math
def summationOfPrimes( x ):
runningSum = 2
lastPrime = 3
i = 3
while i < x:
if largestPrimeFactor.isPrime( i ):
runningSum = runningSum + i
lastPrime = i
print i
i = i+2
print runningSum
def main():
#summationOfPrimes( 10 )
summationOfPrimes( 2000000 )
# Standard boilerplate to call the main() function.
if __name__ == '__main__':
main()
|
d0477d1e044926b376c50a804abccb60d1edd35b
|
jfenton888/AdvancedCompSciCode
|
/CS550 Fall/September 22/RandomNumberGen_1.py
| 366 | 3.859375 | 4 |
import random
play = 1
while play == 1:
numGen = int(random.uniform(1,100))
numPick = int(input("Pick a number between 1 and 100"))
print(numGen)
while numGen != numPick:
if numGen == numPick:
print("Correct")
else if numPick < numGen:
print("Too Low")
else if numPick > numGen:
print("Too High")
play = int(input("Want to play again? 1 or 0"))
|
d07ee30572a6179ab1853136b3b44401d7fb1ff6
|
ljia2/leetcode.py
|
/solutions/range/056.Merge.Intervals.py
| 1,545 | 4.125 | 4 |
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
def merge(self, intervals):
"""
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
:type intervals: List[Interval]
:rtype: List[Interval]
"""
ans = []
# use operator and sorted to sort class instances
intervals.sort(key=lambda x: x.start)
s = intervals[0].start
e = intervals[0].end
for i in range(1, len(intervals)):
interval = intervals[i]
# if it is overlap with the most recent "reference" interval (left, right)
# that may merge all overlap intervals before.
if e >= interval.start:
s = min(interval.start, s)
e = max(interval.end, e)
# update results; reset the "reference" interval as current one.
else:
ans.append(Interval(s, e))
s = interval.start
e = interval.end
# Note! Do not forget the last interval (left, right) !!!!
ans.append(Interval(s, e))
return ans
|
b97ac7d0fea0b78b3518f0e195ffe6ef4d36c9c9
|
CleberSilva93/Study-Exercicios-Python
|
/Exercício Udemy/ex08.py
| 714 | 3.921875 | 4 |
#coding: utf-8
__author__ = 'Cleber Augusto'
########################
#### Cleber Augusto ####
########################
print("Determine o intervalo")
det = int(input("Valor Inicial:\n"))
det2 = int(input("Valor Final:\n"))
l = []
for a in list(range(det,det2)):
x = 0
c2 = a%2
if a==0:
continue
if c2==0:
continue
for b in range(a-1, 0, -1):
if(a%b == 0):
break
if(a%b > 0):
if(b==2):
l.append(a)
print("Determine os 3 valores a serem excluidos")
a1 = int(input("Valor 1:\n"))
a2 = int(input("Valor 2:\n"))
a3 = int(input("Valor 3:\n"))
if a1 in l:
l.remove(a1)
if a2 in l:
l.remove(a2)
if a3 in l:
l.remove(a3)
print(l)
|
d97b37eedf6cdd121c96e97b46f9275a914d0fc7
|
duk1edev/tceh
|
/003_tryexcept_func_homework/self_practice.py
| 2,165 | 3.703125 | 4 |
import random
# 1 Функция которая выбрасивает случаено одно из исключений
import random
error_list = [
(TypeError, 'Error1'),
(ValueError, 'Error2'),
(RuntimeError, 'Error3')
]
# random.shuffle(error_list)
error, message = random.choice(error_list)
print(error, message)
def random_error_maker():
try:
raise error
except ValueError:
print('Value Error Here!')
except TypeError:
print('Type Error Here!')
except RuntimeError:
print('RunTimeError Here!')
random_error_maker()
print(str('---------------------------------------------/'))
# 2 Которая принимает список на входб и если все элементы списка числа отсортировать их
list1 = [9, 43, 2, 87, 13, 43, 24, 12, 1, 5]
list2 = ['as', 23, False, None, 3.23, 'ds']
def check_sort_list(in_list):
try:
for item in in_list:
if not isinstance(item, int):
raise ValueError
except ValueError as e:
print('ValueError: value is not integer!', e)
else:
in_list.sort()
print('list before func: ', list1)
check_sort_list(list1)
print('list after func: ', list1)
check_sort_list(list2)
print(str('---------------------------------------------/'))
# 3 Функция которая принимает словарьб преобразует все ключи словаря вк сторкам и возвращает словарь
my_dict = {1: 'aaa', 2: 'bbbb', 3: 'ccccc', 4: 'ddddd', 5: 'eeeee'}
def key_change_dict(dict):
new_dict = {}
for key, value in dict:
new_dict[key[value]] = str(dict[key])
return new_dict
print('before func: ', my_dict)
dict2 = key_change_dict(my_dict)
print(dict2)
print(str('---------------------------------------------/'))
# 4 Принимает список чисел и возвращает их произвдение.
list_num = [1, 3, 4, 5]
def multiply_list(numbers):
mul = 1
for item in numbers:
mul *= item
return mul
print(list_num, 'multiply...')
print(multiply_list(list_num))
|
7653f13e5061299335a99843b612224e9575a3c4
|
Vaskovics/My_100_projects
|
/07_Hagman_game/07_Hagman_game.py
| 1,935 | 3.921875 | 4 |
import random
logo = '''
_
| |
| |__ __ _ _ __ __ _ _ __ ___ __ _ _ __
| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
__/ |
|___/ '''
stages = ['''
+---+
| |
O |
/|\ |
/ \ |
|
=========
''', '''
+---+
| |
O |
/|\ |
/ |
|
=========
''', '''
+---+
| |
O |
/|\ |
|
|
=========
''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========
''', '''
+---+
| |
O |
|
|
|
=========
''', '''
+---+
| |
|
|
|
|
=========
''']
print(logo)
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
print(chosen_word)
display = []
word_length = len(chosen_word)
for l in range(word_length):
display += "_"
print(display)
lives = 6
end_of_game = False
while not end_of_game:
guess = input("Please guess a letter:\n").lower()
if guess in display:
print("You're already guessed this letter")
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
if guess not in chosen_word:
lives -= 1
print(f"You have {lives} left")
if lives == 0:
end_of_game = True
print("You lose.")
print(f"{' '.join(display)}")
if guess not in chosen_word:
print(f"The '{guess}' is not in this word. You lose a life.")
if "_" not in display:
end_of_game = True
print(stages[lives])
|
4263fcbc8fcd7773c978a7f8f484d62da5add528
|
ghensto/python
|
/supermarket.py
| 1,311 | 3.921875 | 4 |
# CSCI 2061, Assignment 09, Problem 02
# Abiola Adimi
# Supermarket program.
#Main function.
def main():
#Shopping dictionary
shoppingList = {'potato':2, 'lettuce':5, 'onion':1}
#Inventory dictionary
inventory = {'potato':6, 'lettuce':0, 'onion':32, 'carrot':15}
#Prices dictionary
prices = {'potato':4, 'lettuce':2, 'onion':1.5, 'carrot':3}
#Prints Cub foods Inventory
print("*********CUB Foods Inventory********")
print("************************************")
printInventory(inventory, prices)
print()
#Prints bill
print("Your shopping bill is:")
computeBill(inventory, shoppingList, prices)
#Function to process inventory
def printInventory(inv, pr):
print("{:<8} {:<8} {:<8} {:<8}".format("Item", "Price","Quantity","Value"))
for (i, j), (k, l) in sorted(zip(inv.items(), pr.items())):
print("{:<8} ${:<8} {:<8} ${:<8}".format(i, l, j, (j*l)))
#Function to display the bill
def computeBill(inv, shp, pr):
for ((i, j),(k, l),(m,n)) in sorted(zip(inv.items(), shp.items(), pr.items())):
if(j == 0):
print("{:<28} -out of stock".format(k))
elif(j > l):
print("{} {:<8} at ${:<8} each -total ${}".format(l,k,n,l*n))
if __name__ == "__main__": main()
|
755cd0470530a975393031526cb76cfeacb06921
|
penghuiping/python-learn
|
/src/c1_basic/StringTest.py
| 945 | 3.71875 | 4 |
# coding=utf-8
import re
# 字符串拼接
a = "hello" + "," + "world"
print("字符串拼接:", a)
print("字符串大写", a.upper())
print("字符串小写", a.lower())
print("字符串截取", a[0:5])
print("判断字符串是以特定格式开始", a.startswith("hello"))
print("判断字符串是否包含特定字符串", "hello" in a)
# trim
a = " hello "
print(a.strip())
# 使用正则表达式抓取固定电话
b = "我家的固定电话为021-12345678,不是18812345678,这个是手机号。我姐家固定电话为021-33333333"
print(re.findall("[0-9]+-[0-9]+", b, re.M))
# str转成int
print(int('12'))
# int转成str
print(str(12))
# str format
a = "这个错误是:{}".format("空指针错误")
print(a)
# 字符串转bytes
a = "hello world"
bytess = bytes(a, encoding="utf-8")
print("字节数组为:{}".format(bytess))
# bytes转字符串
str = str(bytess, encoding="utf-8")
print("字符串为:{}".format(str))
|
ae95a8039720a1447824bf97b9f0786630896397
|
AdamZhouSE/pythonHomework
|
/Code/CodeRecords/2680/60759/280659.py
| 352 | 3.671875 | 4 |
def getPath(x1, y1, x2, y2):
global ans
if x1 == x2 and y1 == y2:
ans += 1
else:
if x1 < x2:
getPath(x1+1, y1, x2, y2)
if y1 < y2:
getPath(x1, y1+1, x2, y2)
ts = int(input())
for t in range(ts):
x2, y2 = map(int, input().split(' '))
ans = 0
getPath(1, 1, x2, y2)
print(ans)
|
a00c8b65d45c9478893eefafd4fe4184644188ee
|
shivam-02/Adventures-in-Python
|
/eg25.py
| 98 | 3.59375 | 4 |
def add(x,y):
print(y)
return x+y
print(add(y=10,x=20))
#print(add(y=10,20))
print(type(add))
|
1e27a182fe435185dad830e3919799498ace443f
|
Clockwick/DataStructureP2
|
/VIM.py
| 3,568 | 4 | 4 |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def __str__(self):
show_str = ""
current = self.tail
while current:
show_str += current.data + " "
current = current.next
return show_str
def append(self, item):
new_node = Node(item)
if self.tail is None:
self.head = self.tail = new_node
else:
self.head.next = new_node
self.afterAppend(new_node)
self.head = new_node
def afterAppend(self, new_node):
current = self.tail
while current:
if current.data == "|":
self.swap(current, new_node)
temp = current.next
while temp:
self.swap(temp, temp.next)
temp = temp.next
# print("After :", self)
break
else:
current = current.next
def swap(self, a, b):
if a is not None and b is not None:
a.data, b.data = b.data, a.data
def index(self, item):
new_node = Node(item)
index = 0
current = self.head
while current.next and current.data != item:
current = current.next
index += 1
if current.data == item:
return index
return -1
def walkBack(self):
# swap with left node
current = self.tail
try:
while current:
if current.next.data == "|":
self.swap(current, current.next)
break
else:
current = current.next
except:
pass
def walk(self):
# swap with right node
current = self.tail
try:
while current:
if current.data == "|":
self.swap(current, current.next)
break
else:
current = current.next
except:
pass
def removeRight(self):
current = self.tail
try:
while current:
if current.next.next and current.data == "|":
current.next = current.next.next
break
elif current.data == "|":
self.head = current
current.next = None
break
else:
current = current.next
except:
pass
def removeLeft(self):
current = self.tail
try:
while current:
if current.next.next and current.next.next.data == "|":
current.next = current.next.next
break
elif current.next.data == "|":
self.tail = current.next
break
else:
current = current.next
except:
pass
if __name__ == "__main__":
n = input("Enter Input : ").split(",")
ll = LinkedList()
ll.append("|")
for i in range(len(n)):
cmd = n[i].split()
if cmd[0] == "I":
ll.append(cmd[1])
elif cmd[0] == "L":
ll.walkBack()
elif cmd[0] == "R":
ll.walk()
elif cmd[0] == "B":
ll.removeLeft()
elif cmd[0] == "D":
ll.removeRight()
print(ll)
|
f4b2d3d6909fc2b2e09c1b1a16b547942c6707ce
|
ZodiacSyndicate/leet-code-solutions
|
/easy/437.路径总和-iii/437.路径总和-iii.py
| 1,562 | 3.734375 | 4 |
#
# @lc app=leetcode.cn id=437 lang=python3
#
# [437] 路径总和 III
#
# https://leetcode-cn.com/problems/path-sum-iii/description/
#
# algorithms
# Easy (46.92%)
# Total Accepted: 3.5K
# Total Submissions: 7.4K
# Testcase Example: '[10,5,-3,3,2,null,11,3,-2,null,1]\n8'
#
# 给定一个二叉树,它的每个结点都存放着一个整数值。
#
# 找出路径和等于给定数值的路径总数。
#
# 路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
#
# 二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
#
# 示例:
#
# root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
#
# 10
# / \
# 5 -3
# / \ \
# 3 2 11
# / \ \
# 3 -2 1
#
# 返回 3。和等于 8 的路径有:
#
# 1. 5 -> 3
# 2. 5 -> 2 -> 1
# 3. -3 -> 11
#
#
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
if root is None:
return 0
res = self.path(root, sum)
return res + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)
def path(self, node, sum):
if node is None:
return 0
res = 0
if node.val == sum:
res += 1
return res + self.path(node.left, sum - node.val) + self.path(node.right, sum - node.val)
|
bbdbae511d743172c6923212fe36196459201995
|
kwanhur/leetcode
|
/two-sum.py
| 1,129 | 3.640625 | 4 |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import operator
class Solution(object):
"""
https://leetcode-cn.com/problems/two-sum/description/
"""
def add(self, nums):
return operator.add(nums[0], nums[1])
def twoSum(self, nums, target):
ret = {}
for i in range(len(nums)):
num = target - nums[i]
if num in ret:
return [ret[num], i]
else:
ret[nums[i]] = i
return
def twoSum1(self, nums, target):
if not nums or target is None:
return
if len(nums) == 2 and self.add(nums) == target:
return [0, 1]
else:
for i, a in enumerate(nums):
nums2 = nums[i+1:]
num = target - a
for j, b in enumerate(nums2):
if b == num:
return [i, i + j + 1]
return
if __name__ == '__main__':
so = Solution()
print so.twoSum([2, 7, 11, 15], 9)
print so.twoSum([2, 7, 11, 15], 17)
print so.twoSum([2, 7, 11, 15], 0)
print so.twoSum([], 0)
|
2bb9d6db0b20972baef19c889564f2153354daec
|
SMS-NED16/pcc-data-vis
|
/rw_and_plot/15_3_molecular.py
| 879 | 3.65625 | 4 |
import matplotlib.pyplot as plt
from random_walk import RandomWalk
"""Simulating brownian motion of a pollen grain"""
#Create a RandomWalk object and populate it with values
data_points = 5000
pollen_rw = RandomWalk(data_points)
pollen_rw.fill_walk()
#Specifying figure dimensions
plt.figure(figsize=(4.5, 4.5), dpi=150)
#Plotting random walk as a line graph instead of scatterplot
plt.plot(pollen_rw.x_values, pollen_rw.y_values, linewidth=0.5,
color="orange")
#Plotting start and end location as scatterplot points
plt.scatter(pollen_rw.x_values[0], pollen_rw.y_values[0],
c='green', edgecolor='none', s=50)
plt.scatter(pollen_rw.x_values[-1], pollen_rw.y_values[-1],
c='red', edgecolor='none', s=50)
#Figure label adjustments
plt.title("Pollen Grain in Brownian Motion")
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
|
04c637619420b23507b08d7da39bf615667988ff
|
YanaQ/python
|
/lesson2/hw_2_5.py
| 1,551 | 3.515625 | 4 |
# 5. Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел.
# У пользователя необходимо запрашивать новый элемент рейтинга. Если в рейтинге существуют элементы
# с одинаковыми значениями, то новый элемент с тем же значением должен разместиться после них.
# Подсказка. Например, набор натуральных чисел: 7, 5, 3, 3, 2.
# Пользователь ввел число 3. Результат: 7, 5, 3, 3, 3, 2.
# Пользователь ввел число 8. Результат: 8, 7, 5, 3, 3, 2.
# Пользователь ввел число 1. Результат: 7, 5, 3, 3, 2, 1.
# Набор натуральных чисел можно задать непосредственно в коде, например, my_list = [7, 5, 3, 3, 2].
number = int(input('Дайте оценку нашему приложению по 10-бальной системе, где 1 - плохо, 10 - очень хорошо: '))
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = my_list.count(number)
for el in my_list:
if number <= 10 and number >= 1:
i = my_list.index(number)
my_list.insert(i + a, number)
print(my_list)
break
else:
print('Вы ввели неправильное значение')
|
6d67c7f5031cfee88314fe32f26aced6a22534da
|
RohitSavant24/Python
|
/assign3.py
| 88 | 3.859375 | 4 |
age=int(input('Enter Age:'))
print('Entered Age:',age)
age=age-10
print('New Age:',age)
|
e2bb6c24c843ad5ad9a0d533ba55dffed3ca18e8
|
AyaanShaikh1/Backup-Python
|
/backup.py
| 425 | 3.5 | 4 |
import os
import shutil
# path
path = 'C:/Users/Imtiyaz shaikh/Desktop'
print("Before Moving File: ")
print(os.listdir(path))
# source
source = 'C:/Users/Imtiyaz shaikh/Desktop/Project/68'
# destination
destination = 'C:/Users/Imtiyaz shaikh/Desktop'
# move content from source to destination example: Mumbai to Goa
dest = shutil.move(source,destination)
print(dest)
print("After Moving File: ")
print(os.listdir(path))
|
8fc75caf824c91a3c39827b338efa6b60ff627d7
|
minosys-jp/tempcloud
|
/current.py
| 177 | 3.59375 | 4 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime, time
def current():
now = datetime.datetime.now()
return int(time.mktime(now.timetuple()))
d = current()
print d
|
7220da761faba6244710ce6b06e9c2879f3b96ca
|
smitajani/HB-Homework
|
/produce_summary.py
| 1,571 | 3.828125 | 4 |
""" Open raw data files the and print to the sales report
"""
# Iteration-1: Fix the report to print correct values - melon, count & amount,
# on each line
# Iteration:2: Code cleanup and optimization
# Open the file object passed as the argument, loop through each row and do the
# following:
# - Strip spaces on the right
# - Split the values separated by '|' into a list
# - Print the values in a readable format on the report
def print_report(the_file, day_num):
print(f"Day {day_num}: {the_file.name}")
for line in the_file:
line = line.rstrip()
words = line.split('|')
melon = words[0]
count = words[1]
amount = words[2]
print("Delivered {} {}s for total of ${}".format(
count, melon, amount))
print(f"---- (EOF) End of file #{day_num}----\n\n")
the_file.close()
# Assign file names to a list and loop through. This replaces the code block
# below that called the function for each individual file
# ----------------------------------------------------------
list_of_files = []
list_of_files = ["um-deliveries-20140519.txt", "um-deliveries-20140520.txt", "um-deliveries-20140521.txt"]
for index, current_file in enumerate(list_of_files):
current_file = open(current_file)
print_report(current_file, index)
# current_file = open("um-deliveries-20140519.txt")
# print_report(current_file, 1)
# current_file = open("um-deliveries-20140520.txt")
# print_report(current_file, 2)
# current_file = open("um-deliveries-20140521.txt")
# print_report(current_file, 3)
|
228b7f0596af443423582da39ae4560db4355a70
|
Viktor-Paul/review
|
/2020_07_06/sql_02.py
| 504 | 3.6875 | 4 |
"""
pymysql.py读操作
"""
import pymysql
db = pymysql.connect(host='localhost',
port=3306,
user='root',
password='',
database='stu',
charset='utf8')
cur = db.cursor()
sql = "select * from class_1 where class_num = 3;"
cur.execute(sql)
# one_row = cur.fetchone()
# print(one_row)
#
# many_row = cur.fetchmany(2)
# print(many_row)
all_row = cur.fetchall()
print(all_row)
cur.close()
db.close()
|
0d80b80aafc32e73a94f6e20d0c299f4a12feade
|
HaidiChen/Coding
|
/python/linkedlist/odd_even_merge.py
| 617 | 4.125 | 4 |
# reorder the linked list in such a way that even nodes followed by odd nodes.
# time complexity is O(n)
# space complexity is O(1)
class Solution(object):
"""
Solution class to the question.
"""
def even_odd_merge(self, L):
if not L:
return L
even_head, odd_head = L, L
tails, turn = [even_head, odd_head], 0
L = L.next
while L:
tails[turn].next = L
L = L.next
tails[turn] = tails[turn].next
turn ^= 1
tails[1].next = None
tails[0].next = odd_head.next
return even_head
|
cc9f38516fb0fe87b8f1080f981d3c1cdc97e463
|
yinhuax/leet_code
|
/datastructure/daily_topic/NumArray.py
| 1,169 | 3.96875 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Mike
# @Contact : [email protected]
# @Time : 2021/3/1 5:59
# @File : NumArray.py
from typing import List
"""
给定一个整数数组 nums,求出数组从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点。
实现 NumArray 类:
NumArray(int[] nums) 使用数组 nums 初始化对象
int sumRange(int i, int j) 返回数组 nums 从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点(也就是 sum(nums[i], nums[i + 1], ... , nums[j]))
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/range-sum-query-immutable
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class NumArray:
def __init__(self, nums: List[int]):
self.nums = nums
for i in range(1, len(self.nums)):
self.nums[i] = self.nums[i] + self.nums[i - 1]
def sumRange(self, i: int, j: int) -> int:
return self.nums[j] - self.nums[i - 1] if i > 0 else self.nums[j]
if __name__ == '__main__':
print(NumArray([-2, 0, 3, -5, 2, -1]).sumRange(0, 5))
|
b9f4ac7c5494beb61103ab3cc9b2af091f218b19
|
mivargas/ejercicios-de-python
|
/documentacion.py
| 317 | 3.78125 | 4 |
def suma(num1, num2, num3):
""" calcula las sumade 3 elementos
pasados por parametro a esa funcion"""
print(num1+num2+num3)
def resta(num1, num2):
print(num1-num2)
def potencia(base, exponente):
print(pow(base, exponente))
suma(2,4,7)
print(suma.__doc__) # imprimir la documentacion en consola
help(suma)
|
1583aa3fe4f6777afb617482530e14c37870c2b4
|
minotaur423/Python3
|
/Python-Scripts/milestone1_pj.py
| 4,553 | 4 | 4 |
def display_board(board):
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
import random
def choose_first():
players = ['Player1', 'Player2']
return random.choice(players)
def space_check(board, position):
return board[position] == ' '
def full_board_check(board):
if ' ' not in board[1:]:
return False
else:
return True
def player_input():
mark = ' '
while mark.upper() != 'X' and mark.upper() != 'O':
mark = input("Do you want to be 'X' or 'O' ")
mark1 = mark.upper()
if mark1 == 'X':
mark2 = 'O'
else:
mark2 = 'X'
return (mark1, mark2)
def place_marker(board, mark, position):
board[position] = mark
def win_check(board, mark):
win = [mark]*3
if board[1:4] == win or board[4:7] == win or board[7:] == win:
result = True
elif board[1:8:3] == win or board[2:9:3] == win or board[3::3] == win:
result = True
elif board[1::4] == win or board[3:8:2] == win:
result = True
else:
result = False
return result
def player_choice(board):
position = 0
while position not in range(1,10) or not space_check(board,position):
try:
position = int(input('Please enter a number from 1-9: '))
if position > 9 or position < 0:
print("\nYou must enter a number from 1 to 9: ")
continue
except ValueError:
print("\nYou must enter a number from 1 to 9: ")
continue
else:
break
return position
def replay():
play_again = input('\nDo you want to play again? Enter Yes or No: ')
if play_again.upper() == 'YES' or play_again.upper() == 'Y':
return True
else:
return False
print('Welcome to Tic Tac Toe!\n')
turn = ''
next_turn = ''
marker = ''
game_on = bool()
while True:
# Select first player.
turn = choose_first()
print(f'{turn} will go first.\n')
# Conditional statement to designate Player1 and Player2 and each's mark.
if turn == 'Player1':
next_turn = 'Player2'
marker = player_input()
else:
turn = 'Player2'
next_turn = 'Player1'
marker = player_input()
# Confirm player is ready to start game.
ready = input('Are you ready to play? Enter Yes or No. ')
if ready.lower() == 'yes' or ready.lower() == 'y':
game_on = True
else:
break
# Construct the board and display
play_board = [' '] * 10
display_board(play_board)
# Start game loop.
while game_on:
# First player's turn.
print(f'\n{turn}:', end=" ")
# Take input from first player and place mark on board.
position1 = player_choice(play_board)
place_marker(play_board,marker[0],position1)
# Display the board with the first player's mark.
display_board(play_board)
# Check if there is a winner.
we_have_a_winner = win_check(play_board,marker[0])
if we_have_a_winner == True:
print(f'\nCongratulations {turn}! You have won the game!')
break
# Check if the board is full and declare a draw if this is the case.
game_on = full_board_check(play_board)
if game_on == False:
print('The game is a draw!')
break
# Second player's turn.
print(f'\n{next_turn}:', end=" ")
# Take input from first player and place mark on board.
position2 = player_choice(play_board)
place_marker(play_board,marker[1],position2)
# Display the board with the first player's mark.
display_board(play_board)
# Check if there is a winner.
we_have_a_winner = win_check(play_board,marker[1])
if we_have_a_winner == True:
print(f'\nCongratulations {next_turn}! You have won the game!')
break
# Check if the board is full and declare a draw if this is the case.
game_on = full_board_check(play_board)
if game_on == False:
print('The game is a draw!')
break
# Play new game if player selects yes.
if not replay():
break
|
609ef79c9ba865d1199d6cabcdf67ee9a3c9d984
|
besenthil/Algorithms
|
/algoexpert/reconstruct_BST.py
| 884 | 3.640625 | 4 |
# This is an input class. Do not edit.
class BST:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# o(n) - time
def reconstructBst(preOrderTraversalValues):
head = BST(preOrderTraversalValues[0])
idx = 1
while idx < len(preOrderTraversalValues):
traverse_bst(head, preOrderTraversalValues[idx])
idx += 1
return head
def traverse_bst(tree, val):
if tree is None:
return
else:
if val < tree.value and tree.left is None:
tree.left = BST(val)
elif val < tree.value and tree.left is not None:
traverse_bst(tree.left, val)
elif val >= tree.value and tree.right is None:
tree.right = BST(val)
elif val >= tree.value and tree.right is not None:
traverse_bst(tree.right, val)
|
09d3f8dcfd4e0c181f2644fcdd5ccd3182c03760
|
ericgarig/daily-coding-problem
|
/209-longest-substring-of-3-stirngs.py
| 1,965 | 4.15625 | 4 |
"""
Daily Coding Problem - 2019-05-05.
Write a program that computes the length of the longest common subsequence of
three given strings. For example, given "epidemiologist", "refrigeration", and
"supercalifragilisticexpialodocious", it should return 5, since the longest
common subsequence is "eieio".
"""
def solve_substring(a, b, c):
"""Find the length of longest common substring of 3 strings."""
string_list = [a, b, c]
shortest = min(string_list, key=len)
string_list.remove(shortest)
for i in range(len(shortest)):
sub_list = get_substring_list(shortest, len(shortest) - i)
for one_sub in sub_list:
if one_sub in string_list[0] and one_sub in string_list[1]:
return len(one_sub)
def get_substring_list(s, k):
"""For the specified string s and length k, get all substrings."""
result = []
for i in range(len(s) - k + 1):
result.append(s[i : i + k])
return result
def solve_subsequence(a, b, c):
"""Find the longest subsequence of the 3 specified strings."""
return max(
longest_subsequence_order_a(a, b, c),
longest_subsequence_order_a(b, a, c),
longest_subsequence_order_a(c, b, a),
)
def longest_subsequence_order_a(a, b, c):
"""Find the longest subsequence based on the order of a."""
result = []
for i in range(len(a)):
if a[i] in b and a[i] in c:
result.append(a[i])
b = b[b.index(a[i]) + 1 :]
c = c[c.index(a[i]) + 1 :]
return len(result)
assert (
solve_substring(
"epidemiologist", "refrigeration", "supercalifragilisticexpialodocious"
)
) == 2
assert solve_substring("apple", "apple pie", "mappl") == 4
assert (
solve_subsequence(
"epidemiologist", "refrigeration", "supercalifragilisticexpialodocious"
)
) == 5
assert (solve_subsequence("abc", "adbc", "acb")) == 2
assert (solve_subsequence("abcb", "adbcb", "acb")) == 3
|
1b370c41914d68504d62e115a794d61880249f59
|
pengyuhou/git_test1
|
/leetcode/236. 二叉树的最近公共祖先(again).py
| 656 | 3.796875 | 4 |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root, p, q):
if not root:
return None
if (root.left == p and root.right == q) or root == p or root == q:
return root
val_left = self.lowestCommonAncestor(root.left, p, q)
val_right = self.lowestCommonAncestor(root.right, p, q)
if val_left and val_right:
return root
if val_left:
return val_left
if val_right:
return val_right
|
50ac3eef475b272a34714cdff9b99859c372643f
|
vasyanch/stepik
|
/Algorithms_theory_practic_methods/Greedy_algorithms/Theory/My_heap/My_heap.py
| 1,196 | 4.03125 | 4 |
def siftdown(heap, i):
while 2 * i < len(heap) :
j = i #j - индекс наибольшего из тройки
if heap[2 * i] > heap[i]:
j = 2 * i
if 2 * i + 1 < len(heap) and heap[2*i + 1] > heap[j]:
j = 2 * i + 1
if i == j:
break
else:
heap[i], heap[j] = heap[j], heap[i]
i = j
def siftup(heap, i):
while i > 1 and heap[i] > heap[i // 2]:
heap[i // 2], heap[i] = heap[i], heap[i // 2]
i //= 2
def insert(heap, a):
heap.append(a)
siftup(heap, len(heap)-1)
def extract_max(heap):
if len(heap) > 2:
ans = heap[1]
heap[1] = heap.pop(-1)
siftdown(heap, 1)
else:
ans = heap.pop(1)
return ans
def main():
heap = ['heap']
for i in range(int(input(''))):
s = input('').strip()
if s == 'ExtractMax':
print(extract_max(heap))
else:
s = s.split()
insert(heap, int(s[1]))
if __name__ == '__main__':
main()
|
e0c98333fdba84a21f5592911e9b3abc7c37eb4c
|
Emanuelvss13/ifpi-ads-algoritimos2020
|
/cap_07_iteracao/Lista_Fábio_03_em_for/fabio_iteracao_Q11_LimitesPrimos.py
| 858 | 3.90625 | 4 |
def main():
limiteInferior = int(input('Digite o Limite Inferior: '))
limiteSuperior = int(input('Digite o Limite Superior: '))
if limiteInferior <= 0:
print('O limite inferior tem que ser acima de zero(0).')
else:
for i in range( limiteInferior, limiteSuperior+1):
if limiteInferior % limiteInferior == 0 and limiteInferior % 2 != 0 and limiteInferior % 3 != 0 and limiteInferior % 5 != 0 and limiteInferior % 7 != 0:
print(limiteInferior)
limiteInferior = limiteInferior + 1
continue
elif limiteInferior == 2 or limiteInferior == 3 or limiteInferior == 5 or limiteInferior == 7:
print(limiteInferior)
limiteInferior += 1
else:
limiteInferior += 1
main()
|
941dae9f8e8bac54342791bb14aa88b39cf4fc2a
|
Kipkorir-Gideon/News-Api
|
/tests/test_articles.py
| 1,246 | 3.71875 | 4 |
import unittest
from app.models import Articles
class ArticlesTest(unittest.TestCase):
'''
Test Class to test the behavior of the Articles class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_article = Articles('Yuri2','Yuri Gagari','From Facebook to Meta','Facebook has changed its parent name to Meta. This is, they said, to reflect the vision of the company.','https://www.yurinews.com/news/facebook-meta','meta.jpg','2021-10-31T06:43:22Z')
def test_instance(self):
self.assertTrue(isinstance(self.new_article,Articles))
def test_to_check_instance_variables(self):
self.assertEquals(self.new_article.id,'Yuri2')
self.assertEquals(self.new_article.author,'Yuri Gagari')
self.assertEquals(self.new_article.title,'From Facebook to Meta')
self.assertEquals(self.new_article.description,'Facebook has changed its parent name to Meta. This is, they said, to reflect the vision of the company.')
self.assertEquals(self.new_article.url,'https://www.yurinews.com/news/facebook-meta')
self.assertEquals(self.new_article.image,'meta.jpg')
self.assertEquals(self.new_article.date,'2021-10-31T06:43:22Z')
|
06e61b07f4da1394ad93e9c9fadbcac449172ba5
|
woongsup123/python-practice1
|
/6_numberOfMultiplesOfThreeAndSum.py
| 222 | 3.890625 | 4 |
number_list = []
for i in range(1, 30):
number_list.append(i)
num = 0
sum_of_nums = 0
for number in number_list:
if number % 3 == 0:
num += 1
sum_of_nums += number
print(num)
print(sum_of_nums)
|
2c9947f6088e8aca27cc8b56d42d597dc6c7d02d
|
nibsdey/PythonToy1
|
/Exercise3_1.py
| 199 | 4.03125 | 4 |
hours=float(input("Enter hours: "))
rate=float(input("Enter rate: "))
if (hours > 40):
extra=hours - 40
pay = (40 * rate) + (extra * (1.5 * rate))
else:
pay = hours * rate
print("Pay: "+ str(pay))
|
592870b2b4ba106e101e44ce08c5e66c0d756b00
|
raywongstudy/python_workshop
|
/exercise.py
| 466 | 3.625 | 4 |
import time
name = input("what is your name:")
print("Hello "+name+" welcome you!")
sleep_time = input("How long you want to sleep:")
if(int(sleep_time) < 10):
time.sleep(int(sleep_time))
else:
print("the sleep time so long!")
print("please wake up!")
# 引入 requests 模組
import requests
# 使用 GET 方式下載普通網頁
r = requests.get('https://www.google.com.tw/')
if(r.status_code == 200):
print(r.text)
else:
print("you get some error!")
|
e9361d494bf42beb0ddcd7331d4a34b81c379f88
|
tea2code/make-it-hit
|
/graphics/tkdrawer.py
| 1,184 | 3.6875 | 4 |
from abc import ABCMeta, abstractmethod
from formulary import screenconvert
class TkDrawer(metaclass = ABCMeta):
''' Base class for objects which can draw something using tk.
Member:
color -- The color of the line (string).
fill -- The fill color (string).
line -- The line width (float).
screenXCoefficient -- Coefficient for world to screen conversion in x direction (float).
screenYCoefficient -- Coefficient for world to screen conversion in y direction (float).
'''
def __init__( self ):
self.color = 'black'
self.fill = ''
self.line = 1
self.screenXCoefficient = 1
self.screenYCoefficient = 1
@abstractmethod
def draw( self, canvas ):
''' The derived class must implement this method. Receives the canvas to draw on. '''
def worldToScreenX( self, x ):
''' Converts world x to screen x coordinate. '''
return screenconvert.worldToScreen( x, self.screenXCoefficient )
def worldToScreenY( self, y ):
''' Converts world y to screen y coordinate. '''
return screenconvert.worldToScreen( y, self.screenYCoefficient )
|
8f189e5815342ccb7cffb936e91511098c92c885
|
vlarkov/geekhub_homeworks
|
/lesson 2 hw/task12.py
| 276 | 3.609375 | 4 |
# Задание 12*
# Дана строка. Удалите из нее все символы, чьи индексы делятся на 3.
my_str = "0123456789"
new_str = ''
i = 0
for i in range(len(my_str)):
if i % 3 != 0:
new_str += my_str[i]
print(new_str)
|
4fcae09789bf1a8deee32a0f90a6efec8aa8f088
|
TeknikhogskolanGothenburg/Python20_Python_Programming
|
/23Sep/sorting_objects.py
| 636 | 3.96875 | 4 |
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age}"
def comp(person):
return person.age
def main():
p1 = Person("Pia", 45)
p2 = Person("Lars", 34)
p3 = Person("Ove", 67)
p4 = Person("Stina", 27)
p5 = Person("Anna", 39)
people = [p1, p2, p3, p4, p5]
new_people = sorted(people, key=lambda p: p.age)
for person in new_people:
print(person)
print("------")
people.sort(key=comp)
for person in people:
print(person)
if __name__ == '__main__':
main()
|
15890fbf96cb735dcf16fb5f30d8a057f0fe995a
|
ddzumajo/python-scripts
|
/covariance_mm.py
| 1,639 | 3.578125 | 4 |
# -*- coding: utf-8 -*-
"""
This script computes the covariance of fluctuations between two matrix.
Example: density_covariance = <mu*nu> - <mu><nu> = A - B
Author: DiegoDZ
Date: 24 june 2016
Modified: 16 december 2016
run: >> python convariance_mm matrix1 matrix2 > output_file
"""
import numpy as np
import sys
def covariance(arg1, arg2):
# load files
datafile1 = np.loadtxt(str(arg1))
datafile2 = np.loadtxt(str(arg2))
# define number of nodes
number_nodes = len(datafile1[0])
# define number of snapshots
number_snapshots = len(datafile1)
# create a 3D array in which we will save information per snapshot
node_density_snapshot = np.zeros((number_snapshots, number_nodes, number_nodes))
for i in range(0,number_snapshots):
# compute the outer product (row x row) in each snapshot and save it.
node_density_snapshot[i,:,:] = np.outer(datafile1[i], datafile2[i])
# Compute the first term of the covariance (A)
A = np.sum(node_density_snapshot, axis = 0) / number_snapshots
# Sum column elements of the datafile and average the result.
node_density1 = datafile1.sum(axis = 0) / number_snapshots
node_density2 = datafile2.sum(axis = 0) / number_snapshots
# Compute the second term of the covariance (B)
B = np.outer(node_density1, node_density2)
covariance = A - B
return covariance
(covariance) = covariance(sys.argv[1], sys.argv[2])
#For convenience the output will save in matrix format.
aux = ''
for line in covariance:
for element in line:
aux = aux + str(element) + ' '
aux = aux + '\n'
print aux
#EOF
|
6c2d499dcb5a5ebfbce15aee554294e86089c596
|
mariachacko93/luminarDjano
|
/luminarproject/pythoncollections/list demo/pair.py
| 347 | 3.8125 | 4 |
# input-->3...o/p-->1,2
list=[2,3,4,1,6]
element=int(input("enter the number"))
list.sort()
low=0
# print(len(list))
up=len(list)-1
while(low<up):
total=list[low]+list[up]
if(total==element):
print("pairs=",list[low],",",list[up])
break
elif(total>element):
up=up-1
elif(total<element):
low+=1
|
9a36ece6f5217aa89718ce817d755ff0148c7191
|
iWaleedibrahim/elementry-python
|
/conditionals/conditions.py
| 183 | 4.125 | 4 |
# if else, if elif elif ... else
loc = "Bank"
if loc == "AutoShop":
print("GetACar!")
elif loc == "Bank":
print("GetMoney!")
else:
print("I Don't know where are we!")
|
85df9bf29f3cdcb9c3c7fc739ca6b35fe75d195d
|
pcolt/CS50-Web-Programming
|
/Testing_CI-CD/test1.py
| 598 | 4 | 4 |
# unittest comes for free with Python
import unittest
# import the function that I want to test
from prime import is_prime
class Tests(unittest.TestCase):
def test_1(self):
"""Check that 1 is not prime"""
#call class Tests itself with self and use methods inherited from TestCase
self.assertFalse(is_prime(1))
def test_2(self):
"""Check that 2 is prime"""
self.assertTrue(is_prime(2))
def test_3(self):
"""Check that 8 is not prime"""
self.assertFalse(is_prime(8))
#if you run the program, call main() that will run all unittests
if __name__ == "__main__":
unittest.main()
|
f83727d72e86b9078dfa503b2e633afda4fdd139
|
jonathanqbo/moncton-python-2020
|
/week8/homework/andy_guess_10.31.py
| 2,036 | 3.640625 | 4 |
import turtle
import random
MTN=100
def ct(x,y,hide=False,color='red',size=2,pencolor='blue',pensize=2,heading=90,speed='fastest'):
a=turtle.Turtle()
if hide:
a.hideturtle()
a.shape('turtle')
a.color('red')
a.shapesize(size)
a.setheading(heading)
a.pensize(pensize)
a.pencolor(pencolor)
a.penup()
a.goto(x,y)
a.speed(speed)
return a
def dt(x,y,text,color='blue',size=16):
tt=ct(x,y,pencolor=color,hide=True)
tt.write(text,move=True,font=('gabriola',size,'normal'))
def dl(from_x,from_y,to_x,to_y,hide,line_weight=2):
lt=ct(from_x,from_y,to_x,to_y,hide,pensize=line_weight)
lt.pendown()
lt.goto(to_x,to_y)
def stw(the_turtle):
the_turtle.shapesize(5)
the_turtle.circle(5)
dt(-50,100,'you win!',color='red',size=50)
def stl(t):
t.shapesize(1)
t.color('black')
t.speed('fast')
t.circle(180)
t.forward(360)
dt(-50,100,'you lose!',color='red',size=36)
def pin():
return turtle.numinput('Give a nuber','Give me your number:')
def sd(target_number,guessed_number):
indicator_turtle.goto((guessed_number-target_number)*x_max/MTN,0)
x_max,y_max=turtle.window_width()//2,turtle.window_height()//2
#draw indicator ruler
dl(0,30,0,-30,hide=True,line_weight=10)
dl(-turtle.window_width()//2,0,turtle.window_width()//2,0,hide=True)
#draw game description
dt(-100,200,'Guess a number',size=36)
dt(-200,-150,'Well,I am thinking a number between 1 and 100')
str(MTN)+('./nyou have 5 chances to guess it')
indicator_turtle=ct(0,0,color='red',speed='fastest')
used_chances=0
target_number=random.randint(0,MTN)
gos=False
hin=[]
while used_chances<5:
guessed_number=pin()
hin.append(guessed_number)
if guessed_number==target_number:
stw(indicator_turtle)
gos=True
break
else:
sd(target_number,guessed_number)
used_chances+=1
if not gos:
stl(indicator_turtle)
dt(-100,-80,'my number is'+str(target_number))
dt(-100,-120,'you number are'+str(hin))
turtle.done()
|
93b7dd9d19520f7346286eb4c2cd93a1a527fcfa
|
SamuelChanYankah/entry_programing
|
/Vending machine.py
| 3,073 | 3.765625 | 4 |
class Item:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def updateStock(self, stock):
self.stock = stock
def buyFromStock(self):
if self.stock == 0:
# raise not item exception
pass
self.stock -= 1
class VendingMachine:
def __init__(self):
self.amount = 0
self.items = []
def addItem(self, item):
self.items.append(item)
def showItems(self):
print('\nitems available \n***************')
for item in self.items:
if item.stock == 0:
self.items.remove(item)
for item in self.items:
print(item.name, item.price)
print('***************\n')
def addCash(self, money):
self.amount = self.amount + money
def buyItem(self, item):
if self.amount < item.price:
print('You can\'t but this item. Insert more coins.')
else:
self.amount -= item.price
item.buyFromStock()
print('You got ' +item.name)
print('Your Change is: ' + str(self.amount))
def containsItem(self, wanted):
ret = False
for item in self.items:
if item.name == wanted:
ret = True
break
return ret
def getItem(self, wanted):
ret = None
for item in self.items:
if item.name == wanted:
ret = item
break
return ret
def insertAmountForItem(self, item):
price = item.price
while self.amount < price:
self.amount = self.amount + float(input('insert ' + str(price - self.amount) + ': '))
def checkRefund(self):
if self.amount > 0:
print(self.amount + " refunded.")
self.amount = 0
print('Thank you, have a nice day!\n')
def vend():
machine = VendingMachine()
item1 = Item('choc', 1.5, 2)
item2 = Item('pop', 2.5, 1)
item3 = Item('chips', 2.0, 3)
item4 = Item('gum', 0.50, 1)
item5 = Item('mints',1.0, 3)
machine.addItem(item1)
machine.addItem(item2)
machine.addItem(item3)
machine.addItem(item4)
machine.addItem(item5)
print('Welcome to the vending machine!\n***************')
continueToBuy = True
while continueToBuy == True:
machine.showItems()
selected = input('select item: ')
if machine.containsItem(selected):
item = machine.getItem(selected)
machine.insertAmountForItem(item)
machine.buyItem(item)
a = input('buy something else? (y/n): ')
if a == 'n':
continueToBuy = False
machine.checkRefund()
else:
continue
else:
print('Item not available. Select another item.')
continue
vend()
|
19b156cfaf0918a7e7cf97ee34344943a3931914
|
AnTznimalz/python_prepro
|
/gcd_n.py
| 656 | 3.734375 | 4 |
'''GCD_N by ศิษย์เทพปอง#2'''
def gcd():
'''Func. gcd for finding gcd of N numbers'''
last = int(input())
cat = 1
rat = 0
for _ in range(last):
num = int(input())
dog = cal(num)
if dog != 0:
if dog % cat == 0 or cat % dog == 0:
rat = cat
cat = dog
elif dog % cat != 0:
rat = cat
cat = dog % cat
elif cat % dog != 0:
rat = cat
cat = cat % dog
else:
pass
print(rat)
def cal(num):
'''Func. cal for calculating'''
return num
gcd()
|
3518f3bd9658a59ac79c34629655916589f8a963
|
bellos711/python_practice
|
/python/OOP/chaining_methods.py
| 1,613 | 3.90625 | 4 |
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance=0
def make_deposit(self, amount):
self.account_balance += amount
return self
def make_withdraw(self, amount):
self.account_balance -= amount
return self
def display_user_balance(self):
print(f"User: {self.name}, Balance: {self.account_balance}")
#EXTRA METHOD
def transfer_money(self, other_user, amount):
self.make_withdraw(amount)
other_user.make_deposit(amount)
print(f"you transferred {amount} to {other_user.name}.")
return self
kahlil = User('Kahlil', '[email protected]')
holmes = User('Holmes', '[email protected]')
stig = User('Stig', '[email protected]')
#Have the first user make 3 deposits and 1 withdrawal and then display their balance
# kahlil.make_deposit(500)
# kahlil.make_deposit(300)
# kahlil.make_deposit(700)
# kahlil.make_withdraw(800)
# kahlil.display_user_balance()
print("Updated version:")
kahlil.make_deposit(500).make_deposit(300).make_deposit(700).make_withdraw(800).display_user_balance()
print("\n")
#user 2 deposits and 2 withdraws
print("Updated version:")
holmes.make_deposit(1000).make_deposit(200).make_withdraw(100).make_withdraw(300).display_user_balance()
print("\n")
#user make 3 deposits and 1 withdraw
print("Updated version:")
stig.make_deposit(2000).make_withdraw(800).make_withdraw(800).make_withdraw(300).display_user_balance()
print("\n")
print("Updated version:")
kahlil.transfer_money(stig, 100).display_user_balance()
stig.display_user_balance()
|
6e706dbc943eb4671029e2c7b5500c5e28d5b5ee
|
dephiloper/independent-coursework-rl
|
/preparation/05_v_learning/minimax_tictactoe.py
| 2,568 | 3.78125 | 4 |
import collections
import math
import random
import copy
from typing import Tuple, List
from gym_tictactoe import TicTacToeEnvironment
BOARD_WIDTH = 3
BOARD_HEIGHT = 3
env = TicTacToeEnvironment()
saved_action = -1
wanted_depth = 9
def random_move(obs: Tuple):
return random.choice(possible_moves(obs))
def possible_moves(obs: Tuple) -> List[int]:
moves = []
for i in range(BOARD_WIDTH):
for j in range(BOARD_HEIGHT):
if 2 ** (i * BOARD_WIDTH + j) & (obs[0][0] | obs[0][1]) == 0:
moves.append(i * BOARD_WIDTH + j)
return moves
def min(obs: Tuple, depth: int, alpha: float, beta: float):
global env, saved_action
print("min alpha:", alpha, "beta:", beta)
moves = possible_moves(obs)
if depth == 0 or len(moves) == 0 or obs[1] != 0:
return obs[1]
min_score = beta
env_copy = copy.copy(env)
for move in moves:
obs = env.step(move)
score = max(obs, depth - 1, alpha, min_score)
env = copy.copy(env_copy)
if score < min_score:
min_score = score
if min_score <= alpha:
break
return min_score
def max(obs: Tuple, depth: int, alpha: float, beta: float):
global env, saved_action
print("max alpha:", alpha, "beta:", beta)
moves = possible_moves(obs)
if depth == 0 or len(moves) == 0 or obs[1] != 0:
return -obs[1]
max_score = alpha
env_copy = copy.copy(env)
for move in moves:
obs = env.step(move)
score = min(obs, depth - 1, max_score, beta)
env = copy.copy(env_copy)
if score > max_score:
max_score = score
if max_score >= beta:
break
if depth == wanted_depth:
saved_action = move
print("saved_action",saved_action)
return max_score
if __name__ == "__main__":
observation = (env.reset(), 0, False, None)
#env.reset()
#env._player_0 = 3
#env._player_1 = 36
#env._current_player = 0
#observation = ((env._player_0, env._player_1), 0, False, None)
#env.render()
while not observation[2]:
# action = random_move((observation, 0, False))
_ = max(observation, wanted_depth, -math.inf, math.inf)
if saved_action != -1:
observation = env.step(saved_action)
env.render()
wanted_depth -= 1
if not observation[2]:
observation = env.step(int(input("step:")))
env.render()
wanted_depth -= 1
|
a68219764191ab80380fb829c1b143327f33bde2
|
sumanshil/TopCoder
|
/TopCoder/python/ntree/MaxDepthOfNaryTree.py
| 1,474 | 3.6875 | 4 |
import sys
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
"""
if root is None:
return 0
maxdepthvalue = -sys.maxsize - 1
for child in root.children:
maxdepthvalue = max(maxdepthvalue, self.maxDepth(child))
if maxdepthvalue == -sys.maxsize - 1:
return 1
else:
return maxdepthvalue + 1
"""
"""
currentlist = [root]
nextlist = []
count = 1
while currentlist:
count = count + 1
while currentlist:
node = currentlist.pop(0)
for child in node.children:
nextlist.append(child)
currentlist = nextlist
return count
"""
if root is None:
return 0
max_depth = 1
queue = [(1, root)]
while len(queue):
depth, node = queue.pop()
max_depth = max(max_depth, depth)
queue.extend([(depth+1, child) for child in node.children])
return max_depth
node5 = Node(5, [])
node6 = Node(6, [])
node3 = Node(3, [node5, node6])
node2 = Node(2, [])
node4 = Node(4, [])
node1 = Node(1, [node3, node2, node4])
sol = Solution()
res = sol.maxDepth(node1)
print(res)
|
899571ac902e1bdcb454bc722e0f611e79ea800e
|
LauraPeraltaV85/holbertonschool-higher_level_programming
|
/0x04-python-more_data_structures/100-weight_average.py
| 194 | 3.6875 | 4 |
#!/usr/bin/python3
def weight_average(my_list=[]):
z = 0
y = 0
if not my_list:
return 0
for x in my_list:
z += (x[0] * x[1])
y += x[1]
return (z / y)
|
49ae4ceb888194c11d883faae3cfbba878184ccc
|
jvpupcat/holbertonschool-higher_level_programming
|
/0x03-python-data_structures/9-max_integer.py
| 361 | 3.90625 | 4 |
#!/usr/bin/python3
def max_integer(my_list=[]):
length = len(my_list)
if length == 0:
return None
else:
sort_list = sorted(my_list)
length2 = len(sort_list)
largest = my_list[0]
for i in range(1, length2):
if sort_list[i] > largest:
largest = sort_list[i]
return (largest)
|
5310f19ee91cdc53c7145a1a478463944d276d0e
|
rosario17/cursos_gauss
|
/funcion_suma.py
| 704 | 3.984375 | 4 |
def funcion_Suma(A,num1):
A= A+int(num1)
return A
def funcion_Resta(A,num2):
A=A-int(num1)
return A
def funcion_Multiplica(A,num1):
A=A*int(num1)
return A
def funcion_Divide(A,num1):
A=A/int(num1)
return A
A=0
while True:
operacion=raw_input("Teclee una operacion +,-,*,/, 0 para salir ")
if operacion == "0":
break
num1=raw_input("Teclee un numero ")
if operacion== "+":
A=funcion_Suma(A,num1)
elif operacion == "-":
A=funcion_Resta(A,num1)
elif operacion=="*" :
A= funcion_Multiplica(A,num1)
elif operacion=="/":
if A==0:
print("division entre cero no permitida")
else:
A=funcion_Divide(A,num1)
else:
print ("Operacion erronea")
print "RESULTADO :" +str(A)
|
b5f60d872be25819e62fea305f184222b8c442f0
|
seasign10/STUDY
|
/00_Supplementary classes/03_algorithm/supplementary/보충 수업/JUNGOL/day2/145_반복제어문3 - 형성평가6.py
| 246 | 3.8125 | 4 |
num = int(input())
strnum = ''
empty = (2*num) - 2
for i in range(1, num+1):
# strnum += str(i)
# print(strnum) # 숫자가 제대로 출력되는 것을 확인
strnum += str(i) + ' '
print(' '*empty + strnum)
empty -= 2
|
d907c554416d0154709ef1cdb58763044a1886f8
|
nikhilbhatewara/HackerRank
|
/Python/Day1_Quartiles.py
| 1,311 | 4 | 4 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
digits = int(input())
values_input = input()
values_list = list(values_input.split(' '))
values = [int(v) for v in values_list]
#get median of series
def getmedian(digits, values):
values = sorted(values)
mid = (digits - 1) // 2
if digits % 2 != 0:
return values[mid]
else:
return (values[mid] + values[mid + 1]) / 2.0
def getparts(series):
series = sorted(series)
digits = int(len(series))
mid_series = getmedian(digits, series)
lower = [None] * (digits // 2)
higher = [None] * (digits // 2)
lower.clear()
higher.clear()
#if there are odd number of values, then we will not include middle value in quartile calculation
if digits % 2 == 0:
for s in series:
if s < mid_series:
lower.append(s)
else:
higher.append(s)
else:
for s in series:
if s < mid_series:
lower.append(s)
elif s == mid_series:
pass
else:
higher.append(s)
return (lower, higher)
(L, H) = getparts(values)
# print(L)
# print(H)
q1 = getmedian(int(len(L)), L)
q2 = getmedian(digits, values)
q3 = getmedian(int(len(H)), H)
print int(q1)
print int(q2)
print int(q3)
|
131c3146b7721220e776277f378116f35d94d94a
|
2019-a-gr1-python/py-guevara-sanandres-juan-diego
|
/Funciones/Funciones.py
| 1,536 | 3.890625 | 4 |
#Funciones
def hola_mundo():
print("Hola estupida")
hola_mundo()
#Argumentos requeridos la f es chevere porque te permite de todo
def sumar_dos_numeros(num1,num2):
return num1+num2
print(f"Suma {sumar_dos_numeros(1,2)}")
#Opcionales
def imprimir_universidad(nombre='EPN'):
print(f"{nombre}")
imprimir_universidad()
#Parametro por posicion
def imprimir_carro(color,placa,hp,anio=1999):
print(f"Color: {color}")
print(f"Placa: {placa}")
print(f"Hourse Power: {hp}")
print(f"Año: {anio}")
imprimir_carro("rojo",123,23,2010)
#Name Parameters tu pones el nombre del atributo y luego le pones el valor
#todos los argumentos hay que mandar
#para opcionales los parametros requeridos y Luego los opcionales
#No es necesario enviar los parametros opcionales
#Si ya puse un nombrado, debe seguir siendo nombrado
imprimir_carro(placa=234,color="azulado",hp=2)
#PARAMETROS INFINITOS
def sumar_numeros_infinita_veces(primer_numeros,*numeros):
print(type(primer_numeros))
print(type(numeros))
# print(type(tuplas))
long=len(numeros)
if long==0:
return primer_numeros
else:
suma=0+primer_numeros
for numero in numeros:
suma=suma+numero
return suma
print(f"{sumar_numeros_infinita_veces(1,2,3)}")
#Parametros aun mas raros key work arguments
#Key_word_arguments son los parametros que no estan definidos en la funcion
def imprir_configuracion(nombre,valor=10,*valor_carga,**key_word_rguments):
print(type(key_word_rguments))
print(key_word_rguments)
imprir_configuracion("config_1",20,tiempo_espera=10,conexiones=55)
|
7c4feba01a1ee48c3973ef51d0f74b5c1820dd01
|
Aasthaengg/IBMdataset
|
/Python_codes/p03424/s882315101.py
| 95 | 3.5 | 4 |
n=int(input())
if "Y" in list(map(str,input().split())):
print("Four")
else:
print("Three")
|
2f7275fbe0353c95b36c5b3043d62d48ab3c9cc5
|
HyunSeokJeon/coding_plus_algorithm
|
/algorithm_basic/weeklyquiz/week6/q3.py
| 424 | 3.609375 | 4 |
nums = [1, 0, -1, 0, -2, 2]
target = 0
answer = list()
for a in range(len(nums)):
for b in range(a+1, len(nums)):
for c in range(b+1, len(nums)):
for d in range(c+1, len(nums)):
if (nums[a] + nums[b] + nums[c] + nums[d]) == target:
lista = [nums[a], nums[b], nums[c], nums[d]]
lista.sort()
answer.append(lista)
print(answer)
|
19406fc028d47566054f88a03f110427838ea0a3
|
wimurad1981/DS8008-NLP
|
/wiki/utils.py
| 1,039 | 3.65625 | 4 |
import requests
def get_text_from_wikipedia(title, wiki_domain='en.wikipedia.org'):
"""
Retrieve Wikipedia article content as plain-text
:param title: Title of Wikipedia article
:param wiki_domain: API domain (e.g., en.wikipedia.org)
:return: Article content as plain-text
"""
res = requests.get(f'https://{wiki_domain}/w/api.php', params={
"action":"query",
"prop":"revisions",
"rvprop":"content",
"format":"json",
"titles":title,
"rvslots":"main"
})
from gensim.corpora.wikicorpus import filter_wiki
pages = [p for p_id, p in res.json()['query']['pages'].items()]
if len(pages) == 0:
raise ValueError(f'Cannot find Wikipedia article: {title}')
elif len(pages) > 1:
raise ValueError(f'Wikipedia article title is unambigious. Multiple articles returned from API: {title}')
else:
p = pages[0]
wikitext = p['revisions'][0]['slots']['main']['*'] #
text = filter_wiki(wikitext).strip()
return text
|
eb3e37d69bb5da18918d96e021ca3a38c08553ca
|
firoj557/python-tutorial
|
/print pyramid in repetet number program.py
| 296 | 3.890625 | 4 |
""" Author: Firoj Kumar
Date: 10-05-2020
This program print pattern !"""
x=4
for i in range(0,x):
for j in range(0,x-i-1):
print(end=" ")
for j in range(0,i+1):
print('{}'.format(i),end=" ")
print( )
"""output 0
1 1
2 2 2
3 3 3 3 """
|
5857f5ebf4009a69f425c30946e729d141fe4d58
|
guyhth/udacity-dsnd-prj2
|
/data/process_data.py
| 3,935 | 3.515625 | 4 |
# Import libraries
import sys
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
""" Load messages and categories datasets and merge into a single DataFrame
Arguments:
messages_filepath (str): path to messages dataset (CSV file)
categories_filepath (str): path to categories dataset (CSV file)
Returns:
df (DataFrame): merged Pandas DataFrame
"""
# Load messages and categories datasets
messages = pd.read_csv(messages_filepath)
categories = pd.read_csv(categories_filepath)
# Merge datasets using inner join to only keep rows that appear in both datasets
df = pd.merge(messages, categories, on='id', how='inner')
return df
def clean_data(df):
""" Clean the data by splitting, cleaning, and converting the categories column
Arguments:
df (DataFrame): the data to process
Returns:
df (DataFrame): cleaned data
"""
# Create a dataframe of the 36 individual category columns
categories = df['categories'].str.split(';', expand=True)
# Select the first row of the categories dataframe
first_row = categories.iloc[0]
# Use this row to create new column names for categories
category_colnames = first_row.apply(lambda col_string: col_string[0:-2])
categories.columns = category_colnames
for column in categories:
# Set each value to be the last character of the string
categories[column] = categories[column].str[-1]
# Convert column from string to numeric
categories[column] = pd.to_numeric(categories[column])
# Convert the 'related' column to binary (contains 0, 1, 2 by default)
categories['related'] = categories['related'].astype('str').str.replace('2', '1')
categories['related'] = pd.to_numeric(categories['related'])
# Drop the original categories column from df
df.drop('categories', axis=1, inplace=True)
# Concatenate the original dataframe with the new categories dataframe
df = pd.concat([df, categories], axis=1)
# Check for and remove duplicate messages
num_duplicates = df.shape[0] - df['message'].nunique()
df.drop_duplicates(subset='message', inplace=True)
print("{} duplicate messages removed.".format(num_duplicates))
return df
def save_data(df, database_filename):
""" Save data to an SQLite database. Table will be replaced if it already exists.
Arguments:
df (DataFrame): data to save
database_filename (string): filename to save data to
"""
engine = create_engine('sqlite:///' + database_filename)
df.to_sql('MessagesAndCategories', engine, index=False, if_exists='replace')
def main():
# Expect 4 arguments, otherwise print the usage guide
if len(sys.argv) == 4:
# Pull filepaths from the command line arguments provided by the user
messages_filepath, categories_filepath, database_filepath = sys.argv[1:]
print('Loading data...\n MESSAGES: {}\n CATEGORIES: {}'
.format(messages_filepath, categories_filepath))
df = load_data(messages_filepath, categories_filepath)
print('Cleaning data...')
df = clean_data(df)
print('Saving data...\n DATABASE: {}'.format(database_filepath))
save_data(df, database_filepath)
print('Cleaned data saved to database!')
else:
print('Please provide the filepaths of the messages and categories '\
'datasets as the first and second argument respectively, as '\
'well as the filepath of the database to save the cleaned data '\
'to as the third argument. \n\nExample: python process_data.py '\
'disaster_messages.csv disaster_categories.csv '\
'DisasterResponse.db')
if __name__ == '__main__':
main()
|
4353617f8c65ba42d08e0a6e4ee77d022a4d8c83
|
dantclee/how-to-think-like-a-computer-scientist
|
/10.4.py
| 484 | 3.640625 | 4 |
import time
nterms = int(input('Terms start from 0. Enter term: '))
#nterms = 35
if nterms == 0:
print('{0}th term is 0'.format(nterms))
elif nterms == 1:
print('{0}st term is 1'.format(nterms))
else:
two_term_b4 = 0
one_term_b4 = 1
count = 1
while count < nterms:
sum = two_term_b4 + one_term_b4
two_term_b4 = one_term_b4
one_term_b4 = sum
count += 1
print('{0}th term is'.format(nterms), sum)
print(time.process_time())
|
feb43d752e520dd362cf64a80cc11ebd01cab227
|
blogdoon/dailycodingproblems
|
/solutions/queen.py
| 586 | 3.546875 | 4 |
def n_queens(n, board=[]):
if n == len(board):
return 1
count = 0
for col in range(n):
board.append(col)
if is_valid(board):
count += n_queens(n, board)
board.pop()
return count
def is_valid(board):
cur_row, cur_col = len(board)-1, board[-1]
for row, col in enumerate(board[:-1]):
col_diff = abs(cur_col - col)
row_diff = abs(cur_row - row)
if col_diff == 0 or row_diff == col_diff:
return False
return True
for i in range(10):
print(n_queens(i, board=[]))
|
46ef53f171db78bab0e002a0305c8979351034c5
|
CBPHAM/King_Takehome
|
/libraries/southwest_date_helper.py
| 1,965 | 4.40625 | 4 |
from datetime import datetime
from dateutil import parser
def format_my_date(mydate):
"""
Simple function to take a date in the format %m/%d/%Y and convert it to a format that is used on Southwest's calendar picker.
For example, given date 05/23/2019 return may-23
This is required to make sure that we pick the correct date on the date picker for departure and return date.
"""
date = mydate
date = date.split('/')
day = date[1]
monthDict = {1:'january', 2:'february', 3:'march', 4:'april', 5:'may', 6:'june', 7:'july',
8:'august', 9:'september', 10:'october', 11:'november', 12:'december'}
month = monthDict[int(date[0])]
return "%s-%s" % (month,day)
def date_diff_months_to_shift(d1_date,d2_date):
"""
Simple function to take 2 dates (depart and return) in the format %m/%d/%Y and calculate
the number of shift forward on the calendar picker.
For example, given departure 05/23/2019 return 06/10/2019 this function will return 0
We return the difference -1 because Southwest's calendar picker shows 2 months at a time.
"""
d1 = datetime.strptime(d1_date, '%m/%d/%Y')
d2 = datetime.strptime(d2_date, '%m/%d/%Y')
return (d2.year - d1.year) * 12 + d2.month - d1.month-1
def date_with_day_of_week_appended(mydate):
"""
Simple function to take a date in the format %m/%d/%Y and return a shortened version with the
last 2 digits of the year along with the day of the week.
For example, given departure 05/23/2019 return 5/23/19 Thursday
This is used to validate any date printed on Southwest's page in the format like 5/23/19 Thursday.
"""
import datetime
month, day, year = (int(x) for x in mydate.split('/'))
shortened_year = abs(year) % 100
day_of_week = datetime.date(year, month, day).strftime("%A")
return "%s/%s/%s %s" % (month,day,shortened_year, day_of_week)
|
4f16777053779ee769ba60bc84e735f13cf6ece1
|
bkaczmarczik28/python-challenge
|
/PyBank/main.py
| 2,773 | 4 | 4 |
#this is main.py in PyBank
import csv
import os
#Identify csv file
csvpath = os.path.join("Resources", "budget_data.csv")
#initialize variables
totalMonths=0
totalAmount=0
sumChange=0
profit = 0
loss = 0
previous = 0
#Open the file using the "write" mode
with open(csvpath, newline="") as csvfile:
#identify how the data is broken up in csv file
csvreader=csv.reader(csvfile, delimiter=",")
#skip first header row in csv file
csvHeader = next(csvreader)
for row in csvreader:
#ensure first line is skipped to calculate average change
if previous != 0:
if float(row[1])>profit:
#store greatest profit
profit = float(row[1])-previous
profitPeriod = (row[0])
if float(row[1])<loss:
#store greatest loss
loss = float(row[1])-previous
lossPeriod = (row[0])
#calculate average of the changes in profit/loss over entire period
#calculate change from previous month
change=float(row[1])-previous
sumChange=sumChange+change
#exclude from if statement so first row is included
#track total number of months
totalMonths=totalMonths+1
#store the current profit/loss to use for the next iteration
previous=float(row[1])
#calculate net total amount
totalAmount=totalAmount+float(row[1])
#calculate the average of the changes in profit/loss over entire period
#subtrate 1 to eliminate first month from average
averageChange = (sumChange)/(totalMonths-1)
print("Financial Analysis")
print("--------------------------------")
print("Total Months: " + str(totalMonths))
#convert float number to US currency
totalAmount = '${:,.2f}'.format(totalAmount)
averageChange = '${:,.2f}'.format(averageChange)
profit = '${:,.2f}'.format(profit)
loss='${:,.2f}'.format(loss)
print("Total: " + str(totalAmount))
print("Average Change: " + str(averageChange))
print("Greatest Increase in Profits: (" + profitPeriod + ") " + str(profit))
print("Greatest Decrease in Profits: (" + lossPeriod + ") " + str(loss))
#create a txt file with the information
file = open("pybankStore.txt", "w")
textlist = [f"Financial Analysis",
f"--------------------------------",
f"Total Months: {str(totalMonths)}",
f"Total: {str(totalAmount)}",
f"Average Change: {str(averageChange)}",
f"Greatest Increase in Profits: ({profitPeriod}) {str(profit)}",
f"Greatest Decrease in Profits: ({lossPeriod}) {str(loss)}",
]
for line in textlist:
file.write(line)
file.write("\n")
file.close()
|
4f49ce14d0b4b21e2ab1ddb0807782b38e1b110c
|
calfdog/Robs_automation_tools
|
/misc_utils/time_a_function.py
| 758 | 3.96875 | 4 |
"""
Description: Can be used for timing test and such. timing_function takes a decorated function as an
arg and returns the time it took for the function to complete.
Developer: Rob Marchetti
"""
import time
def timing_function(some_function):
"""
Outputs the time a function takes
to execute.
"""
def wrapper():
t1 = time.time()
some_function()
t2 = time.time()
return "Time it took to run the function: " + str((t2-t1)) + "\n"
return wrapper
@timing_function
def my_function():
num_list = []
for x in (range(1, 99999)):
num_list.append(x)
print("\nSum of all the numbers: " +str((sum(num_list))))
# prints the time it took to sum all the numbers
print(my_function())
|
4d33f64cf9be68762ac35b4effd7bfe0e99504fe
|
ChristineKarimi/Project-euler
|
/tests.py
| 858 | 3.5625 | 4 |
#
import unittest
import smallest
class TestSmallest(unittest.TestCase):
def tearDown(self):
smallest.start_point = 1
def test_range_generator(self):
input = 20
range_length=len(smallest.range_generator(input))
self.assertTrue(range_length==20)
def test_start_point_exists(self):
start= smallest.start_point
self.assertEqual(1,start)
def test_start_point_increment(self):
smallest.increment_start()
start= smallest.start_point
self.assertEqual(start,2)
def test_check_divisibility_false(self):
divisible=smallest.is_divisible(10,3)
self.assertFalse(divisible)
def test_check_divisibility_true(self):
divisible=smallest.is_divisible(10,5)
self.assertTrue(divisible)
if __name__ =="__main__":
unittest.main()
|
a23cd094920e41fdb3cd5dc6847510487c6019e9
|
tsharretts/GEOG673_Python_Fall2020_UniversityDelaware
|
/Week02_Matplotlib.py
| 2,269 | 4.5625 | 5 |
# Tyler Sharretts
# Week 03 Matplotlib Tutorial
### Import Matplotlib
import matplotlib.pyplot as plt
import numpy as np
### The "easy" way
# Defining the x and y
x = np.arange(0,100,0.01)
y1 = np.cos(x)
y2 = np.sin(x)
# 3 different plots and their labels (run first two separately and then last one all at same time)
plt.plot(x, y1, label = 'cos(x)')
plt.plot(x, y2, label = 'sin(x)')
plt.axhline(y = 0, color = 'k')
# Another plot (run all at once)
plt.plot(x, y1, label = 'cos(x)')
plt.plot(x, y2, label = 'sin(x)')
plt.axhline(y = 0, color = 'k')
plt.xlim([0, 10])
# Adding in labels, titles, grids, and legends (run all at once)
plt.plot(x, y1, label = 'cos(x)')
plt.plot(x, y2, label = 'sin(x)')
plt.axhline(y = 0, color = 'k')
plt.xlim([0, 10])
plt.xlabel("x")
plt.ylabel("y")
plt.title("$sin(x)$ & $cos(x)$")
plt.grid()
plt.legend()
# End the plotting instance by closing it
plt.close()
### The "customizable" way
# Create sample data
x = np.linspace(0, 2, 100)
# Explicitly create a figure and axes as OBJECTS
fig, ax = plt.subplots(1, 1)
# Plot x variable on the x-axis and x^2 on the y-axis
ax.plot(x, x**2)
# Add labels to the plot
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
# Reprint fig
print(fig)
# Add a title with latex syntax
ax.set_title('$y = x^2$', fontdict = {'size': 22})
print(fig)
# Figure size (inches & resolution)
fig, ax = plt.subplots(figsize=(6,4), dpi = 100)
# Plot of set of different plynomials
# The label argument is used when generating a legend
ax.plot(x, x, label = '$x$')
ax.plot(x, x * x, label = '$x^2$')
ax.plot(x, x**3, label = '$x^3$')
# Add labels and title
ax.set_xlabel('x')
ax.set_ylabel('f(x')
ax.set_title('Polynomials')
# Add gridlines
ax.grid(True)
# Add a legend to the upper left corner of the plot
ax.legend(loc = 'upper left')
print(fig)
# Save with a path
fig.savefig("chosen_path")
### In-class plotting exercise
# Creat range of numbers using Numpy
x = np.arange(0,29,1)
deg_c = np.arange(0, 29, 1, dtype = 'float32')
deg_f = (deg_c * 9/5) + 32
# Plot parameters (run all at once)
plt.scatter(x, deg_c)
plt.scatter(x, deg_f)
plt.xlabel("Days")
plt.ylabel("Temperature")
plt.ylim(0,100)
|
78929e52202ccea2c3be9f49c1881d1fdc8f242e
|
AndrewZhaoLuo/Practice
|
/Euler/Problem46.py
| 1,098 | 3.953125 | 4 |
# -*- coding: cp1252 -*-
'''
It was proposed by Christian Goldbach that every odd composite number can be written
as the sum of a prime and twice a square.
9 = 7 + 212
15 = 7 + 222
21 = 3 + 232
25 = 7 + 232
27 = 19 + 222
33 = 31 + 212
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime
and twice a square?
'''
'''
Idea: use sieve to generate primes, then iterate through squares up to a square composite's number
'''
import timeit
start = timeit.default_timer()
UPPER_BOUND = 100000000
isPrime = [False] * 2 + [True] * (UPPER_BOUND)
bound = int(len(isPrime) ** 0.5)
for i in xrange(2, bound + 1):
if isPrime[i]:
for a in xrange(i * i, bound + 1, i):
isPrime[a] = False
#33, is given man
i = 33
go = True
while go:
if not isPrime[i]:
bound = int((i/2) ** 0.5)
go = False
for a in xrange(0, bound + 1):
if isPrime[i - a * a * 2]:
go = True
i += 2
print "Answer : " + str(i - 2)
print "Elapsed: " + str(timeit.default_timer() - start)
|
2d6f6c4a79de066b4007dc995e08ab3012e2f8f6
|
barvaliyavishal/DataStructure
|
/GeeksForGeeks/CommonElements.py
| 1,217 | 3.828125 | 4 |
'''
this is a common element problem from GeeksForGeeks and
link and defination of this problem is given below
https://practice.geeksforgeeks.org/problems/common-elements1132/1
Given three arrays sorted in increasing order. Find the elements that are common in all three arrays.
Note: can you take care of the duplicates without using any additional Data Structure?
Example 1:
Input:
n1 = 6; A = {1, 5, 10, 20, 40, 80}
n2 = 5; B = {6, 7, 20, 80, 100}
n3 = 8; C = {3, 4, 15, 20, 30, 70, 80, 120}
Output: 20 80
Explanation: 20 and 80 are the only
common elements in A, B and C.
'''
def commonElements (A, B, C, n1, n2, n3):
arr=[];
i=j=k=0;
while i < n1 and j < n2 and k < n3:
if A[i]==B[j]==C[k]:
if len(arr)>0:
if A[i] not in arr:
arr.append(A[i]);
else:
arr.append(A[i]);
i+=1;
j+=1;
k+=1;
elif A[i] < B[j]:
i+=1;
elif B[j] < C[k]:
j+=1;
else:
k+=1;
return arr
n1 = 6;
A = [1, 5, 10, 20, 40, 80]
n2 = 5;
B = [6, 7, 20, 80, 100]
n3 = 8;
C = [3, 4, 15, 20, 30, 70, 80, 120];
print(commonElements(A,B,C,n1,n2,n3))
|
793a29b213d725f4ff22afe29c67576d6a9e6240
|
pietr1n/aulaslpoo2sem21
|
/aula2.py
| 180 | 3.953125 | 4 |
def main():
#
nota1 = int(input("Digite a nota 1:"))
nota2 = int(input("Digite a nota 2:"))
#
if (nota1 + nota2)/2 >= 5:
print("Passou")
#
else:
print("Bombou")
main()
|
09868a7c12dac8af534d27832f2bbde223b47ea9
|
philipwerner/python_data_structures
|
/Tree/node.py
| 536 | 3.921875 | 4 |
"""Node class module for Binary Tree."""
class Node(object):
"""The Node class."""
def __init__(self, value):
"""Initialization of node object."""
self.value = value
self.left = None
self.right = None
def __str__(self):
"""Return a string representation of the node object."""
return f'{self.value}'
def __repr__(self):
"""Return a representation of the node object."""
return f'<Node | Value: {self.value} | Left: {self.left} | Right: {self.right}>'
|
46977ec88522e4d5df2ac727cd6725eb64359986
|
mwele/web-scraping
|
/inheritance.py
| 483 | 3.71875 | 4 |
class Contact:
all_contacts=[]
def __init__(self,name,email):
self.name=name
self.email=email
Contact.all_contacts.append(self)
#print(all_contacts)
#c=Contact()
class Supplier(Contact):
def order(self,order):
print("if this were a real system we would send" "'{}' order to '{}' ".format (order,self.name))
c=Contact("somebody","[email protected]")
s=Supplier("supplier","[email protected]")
print(c.name,c.email)
print(s.name,s.email)
print(c.all_contacts)
print(s.order("I need pliers"))
|
96d18eeb866636b04fb2adfacbdf5d8bf798e97b
|
jpbot/adventofcode
|
/2020/day10.py
| 3,178 | 3.8125 | 4 |
#!/usr/bin/env python
#
# ===============================================================
# ADVENT OF CODE
# ===============================================================
# DAY 13 Shuttle Search: find the shuttle bus you wait the
# shortest time for. Buses depart at timestamp 0 and
# every <busid> timestamps.
#
# A: busid * time to wait
#
# B:
# ===============================================================
INPUTFILE = "day10.input"
def count_gaps(joltdapters, gap_size):
last = 0
gaps = 0
for j in joltdapters:
if(j - last == gap_size):
gaps += 1
last = j
return gaps
def test_valid(joltdapters, max_gap = 3):
last = 0
for j in joltdapters:
if(j - last > max_gap):
return False
last = j
return True
def main():
input = open(INPUTFILE, 'r')
joltdapters = []
# read values
for line in input:
joltdapters.append(int(line.rstrip()))
# sort the joltdapters
joltdapters.sort()
if(not test_valid(joltdapters)):
print("Missing joltdapter")
exit()
#
# PART A
#
# count gaps
# add one to the 3 difference for the jolt adapter to device internal adapter
one_gaps = count_gaps(joltdapters, 1)
three_gaps = count_gaps(joltdapters, 3) + 1
print("PART A: Using all adapters: there are {} differences of 1 jolt".format(one_gaps))
print(" there are {} differences of 3 jolt".format(three_gaps))
print(" puzzle answer product of 1 and 3 differences: {}".format(
one_gaps * three_gaps))
#
# PART B
#
# determine the combinations of adapters that convert the source jolts (0)
# to the highest adapter in the collection (3 jolts lower than our device)
# given the gap between adapters must be 1, 2, or 3.
memo = {}
joltdapters.sort(reverse=True)
# important to follow path to the source in case two adapters can attach to the source
joltdapters.append(0)
# print(joltdapters, len(joltdapters))
combos = all_combos(joltdapters, memo)
print("PART B: combinations: {}".format(combos))
def all_combos(joltdapters, memo):
return find_combos(0, joltdapters, memo)
def find_combos(j, joltdapters, memo):
# memoized reverse order recursive search, memoization enables long searches in reasonable time
if(j == len(joltdapters) - 1):
return 1
if(not j in memo.keys()):
if(j+3 < len(joltdapters)):
if(joltdapters[j] - 3 <= joltdapters[j + 3]):
memo[j] = find_combos(j + 3, joltdapters, memo) + find_combos(j + 2, joltdapters, memo) + find_combos(j + 1, joltdapters, memo)
return memo[j]
if(j+2 < len(joltdapters)):
if(joltdapters[j] - 3 <= joltdapters[j + 2]):
memo[j] = find_combos(j + 2, joltdapters, memo) + find_combos(j + 1, joltdapters, memo)
return memo[j]
memo[j] = find_combos(j + 1, joltdapters, memo)
return memo[j]
if __name__ == "__main__":
main()
|
3bb4024bdb389ac6de67558a31c5838b9af20740
|
XinheLIU/Coding-Interview
|
/Python/Algorithm/Sorting/Templates/Selection Sort Linked List.py
| 705 | 3.71875 | 4 |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def selectionSort(self, head):
"""
input: ListNode head
return: ListNode
"""
# dummy node
self.next = head
tail = self
while tail.next:
prev, cur = tail, tail.next
min_node, prev_min_node = cur, prev
while cur:
if cur.val < min_node.val:
min_node, prev_min_node = cur, prev
prev, cur = cur, cur.next
prev_min_node.next = min_node.next
next = tail.next
tail.next = min_node
min_node.next = next
tail = tail.next
return self.next
|
5c31708d09d234c397060cb53f505721bb87aa5c
|
abriggs914/Coding_Practice
|
/Python/ChatGPT3/demo_pong.py
| 859 | 3.8125 | 4 |
import tkinter as tk
# Create the window
window = tk.Tk()
window.title("Pong")
# Create the canvas
canvas = tk.Canvas(window, width=600, height=400)
canvas.pack()
# Create the paddles
left_paddle = canvas.create_rectangle(10, 150, 30, 250, fill="white")
right_paddle = canvas.create_rectangle(570, 150, 590, 250, fill="white")
# Move the left paddle up
def move_up(event):
canvas.move(left_paddle, 0, -10)
# Move the left paddle down
def move_down(event):
canvas.move(left_paddle, 0, 10)
# Bind the keys to the corresponding paddle movements
canvas.bind("<w>", move_up)
canvas.bind("<s>", move_down)
# Create the ball
ball = canvas.create_oval(290, 190, 310, 210, fill="black")
# Function to move the ball
def move_ball():
canvas.move(ball, 5, 0)
# Call the move_ball function continuously
while True:
move_ball()
window.update()
|
1b27c1f28acf650b785282155102b8d1a4085593
|
fox-io/udemy-100-days-of-python
|
/day_005.py
| 5,941 | 4.25 | 4 |
"""
Day 5 Practice
"""
import random
def for_loop():
names = ["Karen", "Bob", "Joe"]
for name in names:
print(name)
# for_loop()
def average_height():
total_heights = 0
heights = input("Enter a list of heights, separated by spaces: ").split()
for height in range(0, len(heights)):
# Convert heights from strings to ints
heights[height] = int(heights[height])
# Add up the total of all heights
total_heights = total_heights + int(heights[height])
print(heights)
# Calculate average. format as integer
print(f"Average Height: {int(total_heights/len(heights))}")
# average_height()
def high_score():
highest_score = 0
scores = input("Enter a list of scores, separated by spaces: ").split()
for score in range(0, len(scores)):
scores[score] = int(scores[score])
if scores[score] > highest_score:
highest_score = scores[score]
print(f"The highest score is: {highest_score}.")
# high_score()
def add_evens():
evens_total = 0
for even_number in range(2, 101, 2):
evens_total = evens_total + even_number
print(evens_total)
# add_evens()
def fizzbuzz():
for counter in range(1, 101):
if not counter % 3 and not counter % 5:
print("FIZZBUZZ")
elif not counter % 3:
print("FIZZ")
elif not counter % 5:
print("BUZZ")
else:
print(counter)
# fizzbuzz()
"""
Day 5 Project: Password Generator
Asks how many characters do you want in the password.
Asks how many symbols to include.
Asks how many numbers to include.
Prints random password with those characteristics.
(c)2021 John Mann <[email protected]>
"""
class Password:
# Variables for password construction
num_letters = 0 # Total letters to generate in the password.
num_symbols = 0 # Total symbols to generate in the password.
num_numbers = 0 # Total numbers to generate in the password.
num_characters = 0 # Total characters in the password
# Character sets
allowed_letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
allowed_symbols = ["!", "#", "$", "%", "&", "(", ")", "*", "+"]
allowed_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
# Output placeholder
generated_password = ""
def get_password_layout(self):
# Loop until we get at least one character to generate.
while self.num_characters == 0:
# Ask user for how many of each character type to include in the password.
self.num_letters = int(input("How many letters would you like in your password?\n: "))
self.num_symbols = int(input("How many symbols would you like in your password?\n: "))
self.num_numbers = int(input("How many numbers would you like in your password?\n: "))
# Save the total number of characters to a variable for use during generation.
self.num_characters = self.num_letters + self.num_symbols + self.num_numbers
# Give user an informative statement if they tried to allow for a zero-length password.
if self.num_characters == 0:
print("Try Again. Please enter at least one character for the password to be generated.")
def get_random_character(self, character_list):
return character_list[random.randint(0, len(character_list) - 1)]
def generate_password(self):
# Use our length to loop through the password generation.
for character_position in range(0, self.num_characters):
# Flag used for continuing to loop until we have chosen a character for the current character position.
character_position_filled = False
while not character_position_filled:
# Randomly choose a character type for the current character position.
# 1 = letter, 2 = symbol, 3 = number
character_position_type = random.randint(1, 3)
if character_position_type == 1:
# Only add letters if we still have letters to add.
if self.num_letters > 0:
# Randomly choose a letter from allowed letters
random_letter = self.get_random_character(self.allowed_letters)
# Add letter to password
self.generated_password = self.generated_password + random_letter
self.num_letters -= 1
character_position_filled = True
elif character_position_type == 2:
# Add symbols if we still need symbols
if self.num_symbols > 0:
self.generated_password = self.generated_password + \
self.get_random_character(self.allowed_symbols)
self.num_symbols -= 1
character_position_filled = True
elif character_position_type == 3:
# Add numbers if we still need numbers
if self.num_numbers > 0:
self.generated_password = self.generated_password +\
self.get_random_character(self.allowed_numbers)
self.num_numbers -= 1
character_position_filled = True
def generate_password():
print("Password Generator\n------------------")
my_password = Password()
my_password.get_password_layout()
my_password.generate_password()
print(my_password.generated_password)
generate_password()
|
d731b3e51e91490e9937e23bd1cef121c1f4905e
|
r4isstatic/python-learn
|
/if_lang.py
| 250 | 4.03125 | 4 |
#!/usr/bin/env python
#This does an if statement, but tests it against a known set of values, rather than a number.
language = raw_input('Please enter a programming language: ')
if language in ['C++','python','Java']:
print language, "is great!"
|
bf09f9775a49202b6393c78765f12bc9d88e1153
|
dielew/core_python
|
/p27.py
| 128 | 3.671875 | 4 |
#!/usr/bin/env python
while True:
str = raw_input('Plz input a string')
i = 0
while i < len(str):
print str[i]
i += 1
|
ec997d782b4776d3f5412d9a9628e8376774576e
|
xuxu829475/Pythonstudy
|
/xi_04_个人信息.py
| 649 | 4.21875 | 4 |
# 在python中,定义变量是不需要指定变量的类型的
# 在运行的时候,python解释器,会根据赋值语句等会右边的数据
# 自动推导出变量中保存数据的准确类型
# str 字符串类型
name = "小明"
# int整数类型
age = 18
# bool 布尔类型 真 True 假 False
gender = True
# float 浮点类型
height = 1.75
weight = 75
print(name)
# 字符串拼接 两个字符串用 + 相连
last_name = "张"
print(last_name + name)
# 字符串多次输出 用 *
print((last_name + name) * 10)
# input() 键盘输入 输入的结果都是字符串类型
password = input("请输入密码:")
print(password)
|
2385692ad562e8dabfbbd0d59f86e37998f36ca6
|
csalonso/python
|
/guessing_number.py
| 363 | 3.875 | 4 |
import random
def guessing_number():
number = random.randint(0, 100)
user_input = int(input('Digite um número: '))
while (user_input != number):
print('Errou')
if(user_input > number):
print('Alto')
else:
print('Baixo')
user_input = int(input('Digite um número: '))
print('Acertou')
|
08008169f146b72c3d28627b05022bd51c0d2128
|
Tigul/pycram
|
/src/pycram/designator.py
| 9,145 | 3.515625 | 4 |
"""Implementation of designators.
Classes:
DesignatorError -- implementation of designator errors.
Designator -- implementation of designators.
MotionDesignator -- implementation of motion designators.
"""
from inspect import isgenerator, isgeneratorfunction
from pycram.helper import GeneratorList
from threading import Lock
from time import time
class DesignatorError(Exception):
"""Implementation of designator errors."""
def __init__(self, *args, **kwargs):
"""Create a new designator error."""
Exception.__init__(self, *args, **kwargs)
class Designator:
"""Implementation of designators.
Designators are objects containing sequences of key-value pairs. They can be resolved which means to generate real parameters for executing actions from these pairs of key and value.
Instance variables:
timestamp -- the timestamp of creation of reference or None if still not referencing an object.
Methods:
equate -- equate the designator with the given parent.
equal -- check if the designator describes the same entity as another designator.
first -- return the first ancestor in the chain of equated designators.
current -- return the newest designator.
reference -- try to dereference the designator and return its data object
next_solution -- return another solution for the effective designator or None if none exists.
solutions -- return a generator for all solutions of the designator.
copy -- construct a new designator with the same properties as this one.
make_effective -- create a new effective designator of the same type as this one.
newest_effective -- return the newest effective designator.
prop_value -- return the first value matching the specified property key.
check_constraints -- return True if all the given properties match, False otherwise.
make_dictionary -- return the given parameters as dictionary.
"""
def __init__(self, properties, parent = None):
"""Create a new desginator.
Arguments:
properties -- a list of tuples (key-value pairs) describing this designator.
parent -- the parent to equate with (default is None).
"""
self._mutex = Lock()
self._parent = None
self._successor = None
self._effective = False
self._data = None
self.timestamp = None
self._properties = properties
if parent is not None:
self.equate(parent)
def equate(self, parent):
"""Equate the designator with the given parent.
Arguments:
parent -- the parent to equate with.
"""
if self.equal(parent):
return
youngest_parent = parent.current()
first_parent = parent.first()
if self._parent is not None:
first_parent._parent = self._parent
first_parent._parent._successor = first_parent
self._parent = youngest_parent
youngest_parent._successor = self
def equal(self, other):
"""Check if the designator describes the same entity as another designator, i.e. if they are equated.
Arguments:
other -- the other designator.
"""
return other.first() is self.first()
def first(self):
"""Return the first ancestor in the chain of equated designators."""
if self._parent is None:
return self
return self._parent.first()
def current(self):
"""Return the newest designator, i.e. that one that has been equated last to the designator or one of its equated designators."""
if self._successor is None:
return self
return self._successor.current()
def _reference(self):
"""This is a helper method for internal usage only.
This method is to be overwritten instead of the reference method.
"""
pass
def reference(self):
"""Try to dereference the designator and return its data object or raise DesignatorError if it is not an effective designator."""
with self._mutex:
ret = self._reference()
self._effective = True
if self.timestamp is None:
self.timestamp = time()
return ret
def next_solution(self):
"""Return another solution for the effective designator or None if none exists. The next solution is a newly constructed designator with identical properties that is equated to the designator since it describes the same entity."""
pass
def solutions(self, from_root = None):
"""Return a generator for all solutions of the designator.
Arguments:
from_root -- if not None, the generator for all solutions beginning from with the original designator is returned (default is None).
"""
if from_root is not None:
desig = self.first()
else:
desig = self
def generator(desig):
while desig is not None:
try:
yield desig.reference()
except DesignatorError:
pass
desig = desig.next_solution()
return generator(desig)
def copy(self, new_properties = None):
"""Construct a new designator with the same properties as this one. If new properties are specified, these will be merged with the old ones while the new properties are dominant in this relation.
Arguments:
new_properties -- a list of new properties to merge into the old ones (default is None).
"""
properties = self._properties.copy()
if new_properties is not None:
for key, value in new_properties:
replaced = False
for i in range(len(properties)):
k, v = properties[i]
if k == key:
properties[i] = (key, value)
replaced = True
# break
if not replaced:
properties.append((key, value))
return self.__class__(properties)
def make_effective(self, properties = None, data = None, timestamp = None):
"""Create a new effective designator of the same type as this one. If no properties are specified, this ones are used.
Arguments:
new_properties -- a list of properties (default is None).
data -- the low-level data structure the new designator describes (default is None).
timestamp -- the timestamp of creation of reference (default is the current).
"""
if properties is None:
properties = self._properties
desig = self.__class__(properties)
desig._effective = True
desig._data = data
if timestamp is None:
desig.timestamp = time()
else:
desig.timestamp = timestamp
return desig
def newest_effective(self):
"""Return the newest effective designator."""
def find_effective(desig):
if desig is None or desig._effective:
return desig
return find_effective(desig._parent)
return find_effective(self.current())
def prop_value(self, key):
"""Return the first value matching the specified property key.
Arguments:
key -- the key to return the value of.
"""
for k, v in self._properties:
if k == key:
return v
return None
def check_constraints(self, properties):
"""Return True if all the given properties match, False otherwise.
Arguments:
properties -- the properties which have to match. A property can be a tuple in which case its first value is the key of a property which must equal the second value. Otherwise it's simply the key of a property which must be not None.
"""
for prop in properties:
if type(prop) == tuple:
key, value = prop
if self.prop_value(key) != value:
return False
else:
if self.prop_value(prop) is None:
return False
return True
def make_dictionary(self, properties):
"""Return the given properties as dictionary.
Arguments:
properties -- the properties to create a dictionary of. A property can be a tuple in which case its first value is the dictionary key and the second value is the dictionary value. Otherwise it's simply the dictionary key and the key of a property which is the dictionary value.
"""
dictionary = {}
for prop in properties:
if type(prop) == tuple:
key, value = prop
dictionary[key] = value
else:
dictionary[prop] = self.prop_value(prop)
return dictionary
class MotionDesignator(Designator):
"""
Implementation of motion designators.
Variables:
resolvers -- list of all motion designator resolvers.
"""
resolvers = []
"""List of all motion designator resolvers. Motion designator resolvers are functions which take a designator as argument and return a list of solutions. A solution can also be a generator."""
def __init__(self, properties, parent = None):
self._solutions = None
self._index = 0
Designator.__init__(self, properties, parent)
def _reference(self):
if self._solutions is None:
def generator():
for resolver in MotionDesignator.resolvers:
for solution in resolver(self):
if isgeneratorfunction(solution):
solution = solution()
if isgenerator(solution):
while True:
try:
yield next(solution)
except StopIteration:
break
else:
yield solution
self._solutions = GeneratorList(generator)
if self._data is not None:
return self._data
try:
self._data = self._solutions.get(self._index)
return self._data
except StopIteration:
raise DesignatorError('Cannot resolve motion designator')
def next_solution(self):
try:
self.reference()
except DesignatorError:
pass
if self._solutions.has(self._index + 1):
desig = MotionDesignator(self._properties, self)
desig._solutions = self._solutions
desig._index = self._index + 1
return desig
return None
|
750bb3d0f4e64b301a883d02e7c02444306b43b8
|
aksh0001/algorithms-journal
|
/questions/arrays_strings/BinarySearch.py
| 750 | 3.921875 | 4 |
"""
Implement binary search.
@author a.k
"""
from typing import List
def search(A: List[int], target: int) -> int:
"""
Givens a sorted list, A, returns the index of element target.
:param A: list of numbers
:param target: target element
:Time: O(log(n))
:return: index of target if exists.
"""
l, r = 0, len(A) - 1
while l <= r: # while pointers do not cross. equalling is ok since they can converge on the same element!
mid = (l + r) // 2
if A[mid] == target:
return mid
elif target < A[mid]:
r = mid - 1
else:
l = mid + 1
return -1
if __name__ == '__main__':
assert search([-1, 0, 3, 5, 9, 12], target=9) == 4
print('PASSED')
|
5f071db3364e823a99acc705e0200a238dc3c4ef
|
SeanM743/coding-problems
|
/intpal.py
| 392 | 4.09375 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Thu May 2 20:56:12 2019
@author: seanm
"""
#This version reverses the integer and compares it to the original int. If they are equal it's a palindrome
def intPal(n):
rev = 0
revn = n
while revn >= 1:
x = revn%10
revn = revn//10
temp = rev*10 + x
rev = temp
return rev == n
|
551644a423582080c883ea07990bc059d713bb06
|
dpctrey/Python
|
/Core Reference Examples/Exercise Files/02 Quick Start/inherAndPoly.py
| 1,527 | 4 | 4 |
# Using Inheritance and Polymorphism
class myActions:
def sing(self): return self.strings['sing']
def covering(self): return self.strings['covering']
def speak(self): return self.strings['speak']
def fur(self): return self.strings['fur']
class Dog(myActions):
strings = dict(
sing = "AAooohohhh!"
covering = "The dog har hair that covers it"
speak = "The dog cannot bark!"
fur = "The dog usually will not have fur"
)
class Person(myActions):
strings = dict(
sing = "**sings song**"
covering = "skin"
speak = "Hello World!"
fur = "Humans do not have fur!"
)
class bird(myActions):
strings = dict(
sing = "chirp chirp!"
covering = "The bird is covered in feathers"
speak = "The bird cannot speak!"
fur = "Birds do not have fur"
)
def doghouse(dog):
print(dog.sing())
print(dog.covering())
print(dog.speak())
print(dog.fur())
def forest(bird):
print(bird.sing())
print(bird.covering())
print(bird.speak())
print(bird.fur())
def house(person):
print(person.sing())
print(person.covering())
print(person.speak())
print(person.fur())
def main():
tweetie = Bird()
trey = Person()
bingo = Dog()
print("In the Forest: ")
for o in (tweetie, trey, bingo):
forest(o)
print("In the Doghouse: ")
for o in (tweetie, trey, bingo):
doghouse(o)
if __name__ == "__main__": main()
|
53f2c894a6386f857762ce6b39b60f69cf2beebe
|
prakhar21/Learning-Data-Structures-from-Scratch
|
/tree/top_view_tree.py
| 685 | 3.859375 | 4 |
from collections import deque
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def top_view(root, hd, q):
if root == None: return q
if hd in q:
q[hd].append(root.data)
else:
q[hd] = [root.data]
top_view(root.left, hd-1, q)
top_view(root.right, hd+1, q)
root = Node('a')
root.left = Node('b')
root.left.right = Node('e')
root.left.left = Node('d')
root.left.left.right = Node('l')
root.right = Node('c')
root.right.left = Node('f')
root.right.right = Node('g')
coll = {}
hd = 0
vertical_traversal(root, hd, coll)
for k,v in coll.items():
print (k, v[0])
|
d9cf121ff7809cb336ea4b76a927ce59dde6ead0
|
himankjn/DS-ALGO
|
/Python DS & ALGO/graphs/traversals/bfs,dfs.py
| 1,086 | 3.53125 | 4 |
from collections import deque
from collections import defaultdict
class Graph:
def __init__(self,V):
self.V=V
self.edges=defaultdict(list)
def addedge(self,src,dest):
self.edges[src].append(dest)
def dfs(self,src):
visited={}
self.dfs_helper(src,visited)
def dfs_helper(self,src,visited):
visited[src]=True
print(src)
for adj in self.edges[src]:
if(not visited.get(adj,False)):
self.dfs_helper(adj,visited)
def bfs(self,src):
q=deque()
visited={}
self.bfs_helper(src,visited,q)
def bfs_helper(self,src,visited,q):
visited[src]=True
print(src)
for adj in self.edges[src]:
if(not visited.get(adj,False)):
visited[adj]=True
q.append(adj)
while(q):
self.bfs_helper(q.popleft(),visited,q)
G=Graph(4)
G.addedge("a","b")
G.addedge("b","c")
G.addedge("c","a")
G.addedge("d","c")
G.addedge("d","a")
G.bfs("d")
|
bf62f4c5bbf23e252cf916f55e6428c737ffd3fb
|
misszhao1121/python-study
|
/python06_文件操作/01-文件復制附件.py
| 334 | 3.734375 | 4 |
def copy():
copyfile = input("請輸入你要膚質的文件名")
f = open(copyfile,"r")
strl = f.read()
position = copyfile.rfind(".")
new_file = copyfile[:position]+"附件"+copyfile[position:]
l = open(new_file,"w+")
l.write(strl)
print("復制文件結束")
f.close()
l.close()
copy()
|
cb2316faae4ad6834e004eef8403f31f85f500b1
|
inhumanitas/python_course
|
/material/data_iteration.py
| 1,504 | 3.609375 | 4 |
# coding: utf-8
# ---------------------------------------------------------------------------
# Iterator
# list iteration
for el in [1, 2, 3, 4, 5]:
print el
lst = range(5)
lst_iterator = xrange(5)
print lst, lst_iterator
for el in lst_iterator:
print el
for el in lst_iterator:
print el
class SimpleIterator(object):
__curitem = 0
def __iter__(self):
return self
def next(self):
self.__curitem += 1
if self.__curitem > 5:
self.__curitem = 0
raise StopIteration()
return self.__curitem
for i in SimpleIterator():
print 'i = ', i
iterable = SimpleIterator()
for i in iterable:
print 'i = ', i,
print
for i in iterable:
print 'i = ', i,
print '-----------------'
class DataHandler(object):
def __init__(self, iterable):
super(DataHandler, self).__init__()
self.__iterable = iterable
self.__cur_position = 0
self.__high = len(iterable)
def next(self):
if self.__cur_position >= self.__high:
raise StopIteration()
value = self.__iterable.__getitem__(self.__cur_position)
self.__cur_position += 1
return value
class Iterable(object):
def __init__(self, data):
super(Iterable, self).__init__()
self.data = data
def __iter__(self):
return self.data
for i in Iterable(DataHandler([1, 2, 3, 4])):
print i,
print
for i in Iterable(DataHandler(range(10))):
print i,
print
|
161752a78748403e2b727e2c84cabbe2f884adf5
|
u73535508/270201030
|
/lab7/example6.py
| 297 | 3.96875 | 4 |
numbers1 = [2,3,4,20,5,5,15]
numbers2 = [10,20,20,15,30,40]
intersections = []
numbers1=set(numbers1)
numbers2=set(numbers2)
for i in numbers1:
if i in numbers2:
intersections.append(i)
print("Intersection",intersections)
union = list(numbers2)+list(numbers1)
print("Union",set(union))
|
3a30fce72d8aa4482bb7c9ebd3a3a3a42aad12e7
|
jeremyosborne/ant_cities
|
/src/entities/components/facing.py
| 759 | 3.5 | 4 |
from entities.components.component import Component
from common.calc import Heading
class Facing(Heading, Component):
"""Which direction our entity is facing.
This is in regards to navigational heading where the nose of a ship or
aircraft might not be facing in the vessels velocity direction.
Using degrees: 0 is facing north, 90 is east, 180 is south, 270 is west.
Using radians: 0 is north, pi/2 is east, pi is south, 3*pi/2 is west.
Degrees is the default, radians are optional.
"""
_cname = "facing"
# Everything else should be made available through the heading class.
# Name change from "Headings" because it's difficult having two "Headings"
# float around and be used a lot.
|
62cd09c212d30ecfec01a10511b8e6e7bfb3dd0e
|
vitorbarbosa123/lp1-python
|
/Semana2/cilindro/cilindro.py
| 670 | 3.734375 | 4 |
# Universidade Federal de Campina Grande
# Bacharelado em ciências da computação - 2020.2e
# Aluno: José Vitor Barbosa Maciel - Matrícula: 120210954
# Atividade-titulo: Área do cilindro
# Objetivo do código:
diametro = float(input())
altura = float(input())
raio = diametro / 2
area_base = 3.141592653589793 * ( raio ** 2 )
perimetro_base = (3.141592653589793 * 2) * raio
area_lateral_cilindro = altura * perimetro_base
area_cilindro = (area_base * 2) + area_lateral_cilindro
print("Cálculo da Superfície de um Cilindro")
print("---")
print(f'Medida do diâmetro? {diametro}')
print(f'Medida da altura? {altura}')
print("---")
print(f'Área calculada: {area_cilindro:.2f}')
|
413fb367029a2873a1f2ba483d8beeef2e4b748b
|
sdpb/matrix_calculator
|
/calculator/operations.py
| 877 | 3.578125 | 4 |
from numpy import transpose
from numpy.linalg import matrix_rank, det
class Operate:
def __init__(self, matrix, operation, scalar=2):
if operation == 'determinant':
self.result = Determinant(matrix)
elif operation == 'rank':
self.result = Rank(matrix)
elif operation == 'scalar':
self.result = Scalar(matrix, scalar)
elif operation == 'transpose':
self.result = Transpose(matrix)
else:
self.result = None
def __str__(self) -> str:
return str(self.result)
def Determinant(matrix):
result = round(det(matrix))
return result
def Rank(matrix):
rank = matrix_rank(matrix)
return rank
def Scalar(matrix, scalar):
return [list(map(lambda x: x * scalar, _)) for _ in matrix]
def Transpose(matrix):
return transpose(matrix).tolist()
|
18cce10d424a577828eda50680f56a4a6ff502a3
|
duzhencai/python_course_old
|
/GuessNumberGame.py
| 880 | 3.90625 | 4 |
#!/usr/local/bin/python2.7
import random
def play_game(num):
while True:
a = int(raw_input("please input a number:"))
if a > num:
print "The number is bigger"
elif a < num:
print "The number is zsmaller"
else:
print "You are right!"
break
def if_continue():
num = random.randint(0, 99)
while True:
c = raw_input("Do you want to play the game once more,please input Y/N:")
if c == "Y":
play_game(num)
elif c == "N":
print "Thank you for playing this game, GoodBye!"
break
else:
print "The input is not correct, Please input Y/N only!"
def main():
print "----------begin game-----------"
num = random.randint(0, 99)
play_game(num)
if_continue()
if __name__ == '__main__':
main()
|
072374d81472c8e99f48859e65db0a811579f5f8
|
sunita6/python-assignment4
|
/assignment4/pythonassignment41.py
| 713 | 4.4375 | 4 |
print("program to extract substring\n")
string=input("enter a sentence of ur choice:\n").lower()
search_letter=input("\nenter the search letter:").lower()
length=len(string)
index=0
if length>0:
if search_letter in string:
count=string.count(search_letter)
index=string.index(search_letter)
print(f"\n substring count:{count}\n")
print(f"length={length}\n")
print(f"index of the substring:{index}\n")
else:
print("enter a valid search letter ?\n")
#output
program to extract substring
enter a sentence of ur choice:
what we think we become;we are Python programmer!!
enter the search letter:we
substring count:3
length=50
index of the substring:5
|
7909dab2765e176baa1318de046e8b827d47b7dc
|
betty29/code-1
|
/recipes/Python/67671_functiunzip_simple_listlike/recipe-67671.py
| 740 | 3.90625 | 4 |
def unzip(p, n):
"""Split a list-like object, 'p', into 'n' sub-lists by taking
the next unused element of the main list and adding it to the
next sub-list. A list of tuples (the sub-lists) is returned.
Each of the sub-lists is of the same length; if p%n != 0, the
shorter sub-lists are padded with 'None'.
Example:
>>> unzip(['a','b','c','d','e'], 3)
[('a', 'd'), ('b', 'e'), ('c', None)]
"""
(mlen, lft) = divmod(len(p),n) # find length of longest sub-list
if lft != 0: mlen += 1
lst = [[None]*mlen for i in range(n)] # initialize list of lists
for i in range(len(p)):
(j, k) = divmod(i, n)
lst[k][j] = p[i]
return map(tuple, lst)
|
14819a37c6526a0239f7bee3419aa399f00f3ae7
|
yangboyubyron/DS_Recipes
|
/zSnips_Python/Plotting/Scatter.py
| 301 | 3.765625 | 4 |
#----------------------------------------------------------
# EXAMPLE COMPARE IMPORT METHODS
import matplotlib.pyplot as plt
x=[1,2,3,4,5,6]
y=[2,3,4,5,6,7]
plt.plot(x,y)
plt.show()
import matplotlib.pyplot
from matplotlib.pyplot import plot, show
x=[1,2,3,4,5,6]
y=[2,3,4,5,6,7]
plot(x,y)
show()
|
e78ed299a50f5d893a284fbcecb95891dbf6d716
|
meet1509/Hotel-Management-System
|
/check_in.py
| 1,101 | 3.625 | 4 |
from tkinter import *
from tkinter import messagebox
from guests import Guest
#gui for check in window
def submit():
gname = str(name.get())
ph = int(phone.get())
room = int(room_no.get())
guest = Guest()
if not guest.check_in(gname, ph, room):
messagebox.showinfo("Room not found", "Room not available")
return
messagebox.showinfo("Inserted", "Guest checked in")
root = Tk()
root.title('Check In')
root.geometry("400x600")
clicked = StringVar()
clicked.set("Single")
#create entries
name = Entry(root, width=30)
name.grid(row=0, column=1, padx=20, pady=(10, 0))
phone = Entry(root, width=30)
phone.grid(row=1, column=1)
room_no = Entry(root, width=30)
room_no.grid(row=2, column=1)
# Create Text Box Labels
Label(root, text="Name").grid(row=0, column=0, pady=(10, 0))
Label(root, text="Phone").grid(row=1, column=0)
Label(root, text="Room No.").grid(row=2, column=0)
# Create Submit Button
submit_btn = Button(root, text="Check In", command=submit, width=25)
submit_btn.grid(row=6, column=0, columnspan=3, pady=10, padx=10, ipadx=100)
root.mainloop()
|
60ac2210df6235c0e3468538ffe6d28825dce63e
|
PauloGunther/Python_Studies
|
/Teorias/5.1_Exemplos.py
| 1,755 | 3.90625 | 4 |
from time import sleep
from random import randint
# AREA DO TERRENO
def area(x, y):
a = x * y
print(f'A area de um terreno {x}x{y} é de {a:.2f}m².')
a = float(input('Comprimento: '))
b = float(input('Largura: '))
area(a, b)
# FORMACATAO ACOMAPNHA TEXTO
def form(texto): # funcao
tamanho = len(texto)
print('-'*(tamanho+5))
print(f' {texto}') # Dois espaços antes de inicia centraliza a mensagem
print('-'*(tamanho+5))
form('MATRIX')
form('SE O TEXTO FOR MAIOR?')
# CONTAGENS
def lin():
print('-'*40)
def contagem(a, b, c):
if a > b:
for i in range(a, b-1, -c):
print(f'{i} ', end='')
sleep(0.5)
else:
for i in range(a, b+1, c):
print(f'{i} ', end='')
sleep(0.5)
print('Fim!')
lin()
contagem(1, 10, 1)
contagem(10, 0, 2)
print('Agora é sua vez: ')
contagem(a=int(input('Inicio: ')),
b=int(input('Fim: ')),
c=abs(int(input('Passo: '))))
lin()
lin()
# FUNCAO MAIOR
def maior(*n):
print('Analisando os valores...')
cont = maior = 0
for i in n:
if cont == 0:
maior = i
elif i > maior:
maior = i
cont += 1
print(f'{i} ', end='')
print(f'Foram {cont} valores ao todo.')
print(f'O maior valor foi {maior}.')
lin()
maior(1, 2, 8, 21, 9)
maior(1, 8, 6, 1, 99)
maior(95, 20, 10, 55)
lin()
# SORTEIO E SOMA DE PARES
def sorteio(sor):
for i in range(0, 5):
a = randint(0, 10)
print(f'{a} ', end='')
sor.append(a)
print('Pronto!')
def somapar(sor):
s = 0
for i in sor:
if i % 2 == 0:
s += i
print(f'A soma dos valores {sor} é {s}')
lst = []
sorteio(lst)
somapar(lst)
|
91dd0759ba0d351ab5aa38dbee41a8d90ea0f3ee
|
phyrenight/python-practice-projects
|
/collatz conjecture/collatz conjecture.py
| 326 | 3.953125 | 4 |
userNumber = int(raw_input("Please choose a number: "))
original = userNumber
steps = 0
while userNumber != 1:
if(userNumber % 2) == 0:
userNumber = userNumber /2
steps += 1
else:
userNumber = (userNumber * 3) + 1
steps += 1
print " To get %s to 1 it took %s steps " % (original, steps)
|
2334bc92ebaa271ce8789d04f326432e083a6503
|
Soulor0725/PycharmProjects
|
/python3/twoweek/test3.py
| 201 | 3.59375 | 4 |
#输入数字输出中文星期
weeks="星期一星期二星期三星期四星期五星期六星期日"
n=input("输入数字1-7:")
pos=(int(n)-1)*3
weeksday=weeks[pos:pos+3]
print("是:"+weeksday)
|
46005ec7c842c8e92b0bcc4d9e31b471f2c9bd6d
|
TheCyberMonster/ds-and-algo-in-python3
|
/sorting algorithms/merge sort.py
| 913 | 4 | 4 |
# tutorial link https://www.youtube.com/watch?v=_trEkEX_-2Q
def mergesort(arr):
if(len(arr)>1):
mid = len(arr)//2
left = arr[:mid]
right = arr[mid:]
mergesort(left)
mergesort(right)
i=0
j=0
k=0
while(i<len(left) and j<len(right)):
if(left[i] < right[j]):
arr[k] = left[i]
i=i+1
k=k+1
else:
arr[k] = right[j]
j=j+1
k=k+1
while i<len(left):
arr[k]=left[i]
i=i+1
k=k+1
while j<len(right):
arr[k]=right[j]
k=k+1
j=j+1
arr=[10,2,11,3,43431,34,2343,3,43,413432,4,324,32432,332,342,4,32,43,432,5223543,24,32,432,4634243,5,435,43,5,324,32,5435,34,54,6,4,5,435,23,432,56,4,6,34543,4,543,65,4646,74576,7,657,67]
mergesort(arr)
print(arr)
|
0037ce094b4d62c54e9dbe8853f9fd3b4e876093
|
assuncaofelipe/Python-DataStructure
|
/q7.py
| 460 | 4.25 | 4 |
#coding: utf-8
#!python3
# 7) Converta uma temperatura digitada em Celsius para Fahrenheit. F = 9*C/5 + 32. 8)
# Faça agora o contrário, de Fahrenheit para Celsius.
t_c = int(input('Temperatura em Celcius: '))
t_F = (9*(t_c /5)+32)
print('Temperatura em F: ', t_F)
## conversão de Fahrenheit para Celsius
# Exercicio 08
# °C = (°F − 32) / 1,8
t_F = float(input('Temperatura: '))
t_c = ((t_F-32)/1.8)
print('Celcius: {:.2f}'.format(t_c))
|
68eef874f13808c98034192deec5ada12e2827fa
|
lychiyu/AdvancePython
|
/chapter03/self_ex.py
| 753 | 3.796875 | 4 |
# coding: utf-8
"""
Created by liuying on 2018/9/13.
"""
"""
python自省: 通过一定的机制查询到对象的内部结构
"""
# coding: utf-8
"""
Created by liuying on 2018/9/13.
"""
from chapter03.class_method import Date
class Person:
name = 'Person'
class Student(Person):
name = 'Student'
def __init__(self, school_name):
self.school_name = school_name
if __name__ == '__main__':
stu = Student('大学')
# 通过__dict__查询属性 {'school_name': '大学'}
print(stu.__dict__)
print(stu.name)
# 动态操作
stu.__dict__['addr'] = '深圳'
print(stu.addr)
print(Person.__dict__)
print(Student.__dict__)
# dir 会列出对象的所有属性名称
print(dir(stu))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.