blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
bc4d41e348d92f4f932e0dac299d6025e4fc2221 | dreamofwind1014/gloryroad | /练习题/2020.06.18练习题--赵华恬.py | 2,965 | 3.953125 | 4 | # 练习171:不区分大小写对包含多个字符串对象的列表进行排序,显示排序后的结果还需要显示大小写不变的原字符串
# l = ["Abc", "zhangsan", "gloryroad", "nanjing"]
# print(sorted(l))
# 练习172:一个数如果恰好等于它的因子之和,这个数就称为完数,
# 例如6的因子为1, 2, 3,而6 = 1 + 2 + 3,因此6是完数,
# 编程找出1000之内的所有完数,并按6 its factors are 1, 2, 3 这样的格式输出
# 遍历1000以内的数#用数自身遍历除以小于数自身的数,求约数,所有约数和等于数自身
# for i in range(1, 1000):
# result = []
# for value in range(1, i):
# if i % value == 0:
# result.append(value)
# if i == sum(result):
# print(i, "its factors are ", end="")
# for v in result:
# print(v, end=",")
# print()
# # 练习173:使用二分法实现在一个有序列表中查找指定的元素
# lst = list(range(100)) # print(lst)
#
#
# def binary_search(arr, item):
# low = 0
# high = len(arr) - 1
# while low <= high:
# mid = (low + high) // 2
# if arr[mid] == item:
# return "%d 索引位置是: %d " % (item, mid)
# elif arr[mid] > item:
# high = mid - 1
# elif arr[mid] < item:
# low = mid + 1
# print(binary_search(lst, 88))
# 练习174:分离list1与list2中相同部分与不同部分
# list1 = [1, 2, 3, 4, 5, 0]
# list2 = [1, 2, 5, 6, 7, 8, 9]
# same_list = []
# diff_list = []
# for v in list1:
# if v in list2:
# same_list.append(v)
#
# else:
# diff_list.append(v)
# for v in list2:
# if v not in list1:
# diff_list.append(v)
# print("相同部分:%s" % same_list)
# print("不同部分:%s" % diff_list)
# 练习175:找出一个多维数组的鞍点,即该位置上的元素在该行上最大,在该列上最小,也可能没有鞍点
# 首先找出每行的最大值,每列的最小值存入两个列表,个数和函数和列数对应#遍历列表的每个元素,
# 如果等于最大值列表和最小值列表对应位置上的值,则是鞍点,否则打印没有鞍点
# l = [
# [13, 2, 6, 4],
# [14, 3, 5, 6],
# [16, 8, 9, 0],
# [19, 2, 3, 4]
# ]
#
# row_max_item_list = []
# col_min_item_list = []
# for i in range(len(l)):
# row_max_item_list.append(max(l[i]))
# print(row_max_item_list)
# for i in range(len(l)):
# # 存储每列的元素
# temp_list = []
# for j in range(len(l[i])):
# temp_list.append(l[j][i])
# col_min_item_list.append(min(temp_list))
# print(col_min_item_list)
# for i in range(len(l)):
# for j in range(len(l[i])):
# if l[i][j] == row_max_item_list[i] and l[i][j] == col_min_item_list[j]:
# print("%d 行 %d 列 鞍点是 %d" % (i, j, l[i][j]))
# else:
# print("%d 行 %d 列 没有鞍点" % (i, j))
# 共计62行代码
|
3af1f947862099145d100d986ad158586368d47b | thetrashprogrammer/StartingOutWPython-Chapter3 | /fat_and_carbs.py | 1,491 | 4.375 | 4 | # Programming Exercise 3.7 Calories from Fat and Carbohydrates
# May 3rd, 2010
# CS110
# Amanda L. Moen
# 7. Calories from Fat and Carbohydrates
# A nutritionist who works for a fitness club helps members by
# evaluating their diets. As part of her evaluation, she asks
# members for the number of fat grams and carbohydrate grams
# that they consumed in a day. Then, she calculates the number
# of calories that result from the fat, using the following
# formula:
# calories from fat = fat grams X 9
# Next, she calculates the number of calories that result from
# the carbohydrates, using the following formula:
# calories from carbs = carb grams X 4
# The nutritionist asks you to write a program that will make
# these calculations.
def main():
# Ask for the number of fat grams.
fat_grams = input('Enter the number of fat grams consumed: ')
fat_calories(fat_grams)
# Ask for the number of carb grams.
carb_grams = input('Enter the number of carbohydrate grams consumed: ')
carb_calories(carb_grams)
def fat_calories(fat_grams):
# Calculate the calories from fat.
# calories_from_fat = fat_grams*9
calories_from_fat = fat_grams * 9
print 'The calories from fat are', calories_from_fat
def carb_calories(carb_grams):
# Calculate the calories from carbs.
# calories_from_carbs = carb_grams * 4
calories_from_carbs = carb_grams * 4
print 'The calories from carbohydrates are', calories_from_carbs
# Call the main function.
main()
|
35cf58ab0216092a7f64fa19a89acab686194db7 | pshenoki/PythonALg | /Orlov_Vadim_les_3/task_3_les_3.py | 1,350 | 4.03125 | 4 | """В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. """
import random as r
SIZE = 10
MIN_ITEM = 0
MAX_ITEM = 100
array = [r.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
print(array)
if array[0] > array[1]:
spam_max, spam_min = array[0], array[1]
max_ind, min_ind = 0, 1 # пришлось написать из-за: Name 'min_ind', 'max_ind' can be undefined
else:
spam_max, spam_min = array[1], array[0]
max_ind, min_ind = 1, 0 # пришлось написать из-за: Name 'min_ind', 'max_ind' can be undefined
""" for i in array:
if i > spam_max:
spam_max = i
if i < spam_min: # первый вариант
spam_min = i
max_ind = array.index(spam_max)
min_ind = array.index(spam_min) """
for num, i in enumerate(array):
if i > spam_max:
spam_max = i # но этот, наверно, лучше
max_ind = num # хотя не уверен :)
if i < spam_min:
spam_min = i
min_ind = num
array[max_ind], array[min_ind] = array[min_ind], array[max_ind]
print(f"{spam_max:<2} - max elem")
print(f"{spam_min:<2} - min elem")
print(array)
|
69d3656cd6c33453c0d8b6d87947723af9eb3356 | pshenoki/PythonALg | /Orlov_Vadim_les_3/task_1_les_3.py | 609 | 3.953125 | 4 | """В диапазоне натуральных чисел от 2 до 99 определить,
сколько из них кратны каждому из чисел в диапазоне от 2 до 9"""
LEFT_BOARD_i = 2
RIGHT_BOARD_i = 99
LEFT_BOARD_j = 2
RIGHT_BOARD_j = 9
for j in range(LEFT_BOARD_j, RIGHT_BOARD_j + 1):
count = 0
for i in range(LEFT_BOARD_i, RIGHT_BOARD_i + 1):
if i % j == 0:
count += 1
print(f" В диапазоне натуральных чисел от {LEFT_BOARD_i} до {RIGHT_BOARD_i} \n "
f"{count} чисел кратных {j}")
|
78709068dc408fb29864ccc26c0898cfa3147211 | Mi-clouds/git_homework | /bankapp/exception_handling_task/savings_account.py | 2,477 | 3.6875 | 4 | from account import Account
from insufficient_funds_exception import InsufficientFunds
from max_number_withdrawals import MaxNumberOfWithdrawals
class SavingsAccount(Account):
def __init__(self, name, balance, interest_rate, withdrawal_num_limit, num_of_withdrawals):
Account.__init__(self, name, balance)
self._interest_rate = interest_rate
self._withdrawal_num_limit = withdrawal_num_limit
self._num_of_withdrawals = num_of_withdrawals
def __str__(self):
super().__str__()
return f"{self._name}'s bank balance is {self._balance:.2f}, interest rate: {self._interest_rate}, " \
f"number of withdrawals limit: {self._withdrawal_num_limit}, sort code: {self._sortcode}, account number: {self._account_number}"
def make_withdrawal(self, amount):
if self._withdrawal_num_limit < self._num_of_withdrawals:
raise MaxNumberOfWithdrawals("Error: You have reached your limit of " + str(self._withdrawal_num_limit) +
" withdrawals this month")
elif amount - self._balance >= 0:
raise InsufficientFunds("Error: Insufficient funds to withdraw:£" + str(amount))
else:
self._balance -= amount
self._num_of_withdrawals += 1
if __name__ == "__main__":
account4 = SavingsAccount("Jonny Cash", 50, 0.5, 5, 4)
try:
account4.make_withdrawal(15)
except MaxNumberOfWithdrawals as max_error:
print(str(max_error))
except InsufficientFunds as my_error:
print(str(my_error))
print(account4.get_balance())
try:
account4.make_withdrawal(60)
except MaxNumberOfWithdrawals as max_error:
print(str(max_error))
except InsufficientFunds as my_error:
print(str(my_error))
print(account4.get_balance())
try:
account4.make_withdrawal(30)
except MaxNumberOfWithdrawals as max_error:
print(str(max_error))
except InsufficientFunds as my_error:
print(str(my_error))
print(account4.get_balance())
try:
account4.make_withdrawal(30)
except MaxNumberOfWithdrawals as max_error:
print(str(max_error))
except InsufficientFunds as my_error:
print(str(my_error))
# account4.make_withdrawal(5)
# print(account4.get_balance())
# account4.make_withdrawal(5)
# print(account4.get_balance())
# account4.make_withdrawal(5)
# print(account4.get_balance()) |
ee4a430f250014f9f2bdc7edc69b02766cfb6388 | Mi-clouds/git_homework | /bankapp/client_script.py | 986 | 3.5625 | 4 | from employee import Employee
from customer import Customer
from exception_handling_task.savings_account import Savings_account
from current_account import Current_account
#Employee and Customer classes both inherit from Person class
#each greeting method is encapsulated in the relevant class
#Inheriting Employee from Person is polymorphism as we are changing the data type
jessie = Employee("Jessie", "auguste", "25", "2747373783")
print(jessie.get_profile())
asia = Customer("Asia", "Sharif", "23", "3454354")
print(jessie.greeting())
print(asia.greeting())
jessie_savings = Savings_account(500, 2.5, 3, 2)
jessie_savings.withdraw(300)
print(jessie_savings.get_balance())
jessie_savings.withdraw(500)
asia_current = Current_account(1000, -500, 500)
print(asia_current.get_balance())
print(asia_current.send_money(100, "jessie"))
print(asia_current.get_balance())
asia_current.send_money(3000, "jackie")
asia_current.receive_money(50, "jessie")
print(asia_current.get_balance())
|
acf7f4a2e51f1eca3b379ccbccd8aeabc333be27 | mooseman/moose_parse | /groupparser.py | 1,127 | 3.625 | 4 |
# groupparser.py
# This code counts the number of occurrences of each character-type
# in the input. It could be adapted to count the number of tokens
# as well.
# This code is released to the public domain.
# "Share and enjoy...." ;)
import string, itertools, curses, curses.ascii
def test(input):
mydict = {"a": 0, "d": 0, "s": 0, "p":0, "o": 0}
result = ""
typelist = []
numlist = []
count = 0
for ch in input:
if ch.isalpha():
type = "a"
elif ch.isdigit():
type = "d"
elif ch.isspace():
type = "s"
elif curses.ascii.ispunct(ch):
type = "p"
else:
type = "o"
typelist.append(type)
mydict.update({type: mydict[type] + 1})
mylist = [[k, len(list(g))] for k, g in itertools.groupby(typelist)]
for x in mylist:
result = result + str(x[1]) + str(x[0])
print mylist
print result
for k, v in mydict.items():
print k, v
print typelist
test("foo12345#$%^ 435bar")
|
5838440bbbd4f0af0061cf519c4541d18f415b73 | brobusta/ctci | /python/chapter-4/MinimalTree.py | 635 | 3.546875 | 4 | class TreeNode(object):
def __init__(self, data = None, left = None, right = None):
self.data = data
self.left = left
self.right = right
def createMinimalBST(A):
N = len(A)
if N == 0:
return None
mid = N / 2
root = TreeNode(A[mid])
root.left = createMinimalBST(A[:mid])
root.right = createMinimalBST(A[mid+1:])
return root
def printInOrder(root):
if root is not None:
printInOrder(root.left)
print root.data,
printInOrder(root.right)
if __name__ == '__main__':
root = createMinimalBST([1,3,5,7,9,12,14,15,17,19])
printInOrder(root)
|
cfec8d825f316ed4af01ff7cb8b3be8a4ab93b57 | brobusta/ctci | /python/chapter-4/CheckBalanced.py | 1,007 | 3.6875 | 4 | import sys
class TreeNode(object):
def __init__(self, data = None, left = None, right = None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
def CheckBalanced(root):
height, balanced = CalHeight(root)
print "height =",height
return balanced
def CalHeight(root):
if root is None:
return -1, True
hLeft, leftBalanced = CalHeight(root.left)
if not leftBalanced:
return (-sys.maxint-1), False
hRight, rightBalanced = CalHeight(root.right)
if not rightBalanced:
return (-sys.maxint-1), False
h = max(hLeft, hRight) + 1
if abs(hLeft - hRight) > 1:
return (-sys.maxint-1), False
return h, True
if __name__ == '__main__':
n1 = TreeNode(1)
n2 = TreeNode(2, n1)
n4 = TreeNode(4)
n3 = TreeNode(3, n2, n4)
n6 = TreeNode(6)
n8 = TreeNode(8)
n7 = TreeNode(7, n6, n8)
n5 = TreeNode(5, n3, n7)
print CheckBalanced(n5)
|
7dcc48ffebb1ae534fa973cab9d70c77e7b7a610 | wade-sam/variables | /Second program.py | 245 | 4.15625 | 4 | #Sam Wade
#09/09/2014
#this is a vaiable that is storing th value entered by the user
first_name = input("please enter your first name: ")
print(first_name)
#this ouputs the name in the format"Hi Sam!"
print("Hi {0}!".format(first_name))
|
452252aeb474b5b4d684adc7263e04e636763405 | lianemeth/hackerrank | /twins.py | 554 | 3.640625 | 4 | def twins(lower_limit, upper_limit):
array = [True] * (upper_limit + 1)
array[0] = array[1] = False
for (i, isprime) in enumerate(array):
if isprime:
for n in xrange(i*i, len(array), i):
array[n] = False
count = 0
for i in range(lower_limit, len(array) - 2):
if i + 2 < upper_limit and array[i] and array[i + 2]:
count += 1
return count
if __name__ == "__main__":
n, m = raw_input().split(' ')
n, m = int(n), int(m)
primes = twins(n, m+1)
print primes
|
0b93d92d1723d83b14f61a60e1ea87d61c2b7a2b | naichao/deeptest | /第二期/深圳--奶茶哥/快学Python3/task_date_time.py | 1,854 | 3.734375 | 4 |
from datetime import date, datetime,time
__author__ = u'奶茶哥'
if __name__ == '__main__':
# 获取今天的日期
today = date.today()
print('今天日期是:%s' % today)
# 把年月日分开年月日三部分获取,然后展示
print('今天日期是:%s %s %s' % (today.day,today.month,today.year))
# 获取星期几对于的序号
weekday_num = today.weekday()
print('今天weekday是:%s' % weekday_num)
# 输出可读性更好的星期几
weekdays = ('Monday','Tuesday','Wednesday',
'Thursday','Firday','Saturday','Sunday')
print('今天是:%s' % weekdays[weekday_num])
print('_' * 30)
# 时间
today_now = datetime.now()
print('现在时间是:%s' % today_now)
# 用time造个时间
t = time(hour=12,minute=20,second=30,microsecond=200)
print('自己造的时间是:%s' % t )
# 再造个日期出来
d = datetime(year=2018,month=4,day=22,hour=17,minute=7,second=30)
print('自己造的日期是:%s' % d)
print('-' * 30)
import time
localtime = time.asctime(time.localtime())
print('当前默认时间日期格式是:%s' % localtime)
# 格式:年-月-日 时:分:秒 星期几
print('24小时制格式:', time.strftime('%Y-%m-%d %H:%M:%S %A',
time.localtime()))
print('12小时制格式:',time.strftime('%Y-%m-%d %I:%M:%S %a',
time.localtime()))
# 带a.m或p.m
print('带a.m/p.m时间格式:',time.strftime('%Y-%m-%d %H:%M:%S %p %A',
time.localtime()))
# 带时区的时间格式(时区乱码没有解决)
print('带时区的时间格式:',time.strftime('%Y-%m-%d %H:%M:%S %p %A %z',
time.localtime()))
|
0713f2aa877dcdcad3ad4700fcb423c95cd27ab7 | naichao/deeptest | /第二期/深圳--奶茶哥/first_task/my_sort.py | 1,244 | 3.890625 | 4 | import random
class MySort:
def __init__(self,start,end,count):
'''
初始化
生成随机数,返回排序后的结果
start, end为限制随机数生成的范围
count为生成的随机数个数
'''
self.start = start
self.end = end
self.count = count
def __mysort__(self):
'''生成数据并排序'''
list = [random.randint(self.start,self.end) for _ in range(self.count)]
# print('list'+str(list))
# 比较轮数,每比较1轮则i取一次值
num_lun = self.count-1
for i in range(num_lun):
# 每轮比较次数,每比较1次则j取一次值
for j in range(num_lun-i):
if list[j] > list[j+1]:
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
print('第'+str(i+1)+'轮第'+str(j+1)+'次比较的结果是:'+str(list))
print('第'+str(i+1)+'轮比较的结果是:'+str(list))
print('最后结果是:'+str(list))
return list
if __name__ == '__main__':
sorted_data = MySort(10,1000,100)
# 打印排序后的结果
print(sorted_data.__mysort__()) |
662903f992e036d174c71e420cfbd07998ad79f3 | cameronabel/advent2020py | /day3/day3.py | 942 | 4.0625 | 4 | import sys
def part_one(array, over, down):
"""Returns the number of trees encountered in the given array at the given slope"""
trees = 0
col = 0
for line in array[down::down]:
col += over
if col >= len(line):
col -= len(line)
if line[col] == '#':
trees += 1
return trees
def part_two(array, slopes):
"""Returns the product of trees for the given array and each given slope"""
trees = 1
for slope in slopes:
trees *= part_one(array, slope[0], slope[1])
return trees
def build_array(text):
"""Returns an array representing the hill in the given text source"""
with open(text, 'r') as f:
array = [line.strip() for line in f]
return array
if __name__ == '__main__':
array = build_array(sys.argv[1])
print(part_one(array, 3, 1))
slopes = ((1, 1), (3, 1), (5, 1), (7, 1), (1, 2))
print(part_two(array, slopes))
|
7af6bcfb8ae5eac8862f30e232755bbdcf122d34 | egallop/learn-arcade-work | /Lab 06 - Text Adventure/lab_06.py | 2,367 | 3.65625 | 4 | import arcade
total_score = 0
# Welcome statement
print("Welcome to the rock and roll pop culture Quiz")
# line break
print()
# question about REM
print ("Who wrote the song Losing my Religion in 1991? ")
print ("A) Judas Priest\n"
"B) Pantera\n"
"C) R.E.M.\n"
"D) Iron Maiden")
answer_REM = input("Enter your choice: ")
if answer_REM.lower() == "c":
print("That is correct!")
total_score += 20
print("Your new score is", total_score)
else:
print("The correct answer is R.E.M.")
print("Your current score is:", total_score)
# line break
print()
# Rush question
answer_rush = input("How many studio albums has the Toronto based band, Rush, released? ")
if answer_rush == "19":
print("Nice job!")
total_score += 20
print("Your new score is", total_score)
else:
print("Try harder next time! ")
print("Your current score is:", total_score)
# line break
print()
# Ozzy Osbourne
answer_ozzy = input("What year did Ozzy Osbourne bite the head of a bat off on stage?")
if answer_ozzy == "1982":
print("Wow! nice job")
total_score += 20
print("Your new score is", total_score)
else:
print("Probably best that you do not watch it here: https://www.youtube.com/watch?v=GeuW4Smf9PI ")
print("Your current score is:", total_score)
# line break
print()
# question about Led Zeppelin
print ("What is the best Led Zeppelin song? ")
print ("A) Houses of The Holy\n"
"B) Zeppelin IV\n"
"C) The Song Remains the Same\n"
"D) In Through the Out Door \n")
answer_LZ = input("Enter your choice: ")
if answer_LZ.lower() == "b":
print("You have amazing taste!")
total_score += 20
print("Your new score is", total_score)
else:
print("Zeppelin IV is better")
print("Your current score is:", total_score)
# line break
print()
# who does not belong
print ("Who does not belong? ")
print ("A) John Lennon\n"
"B) Robert Plant\n"
"C) Angus Young\n"
"D) Dave Grohl")
answer_WDNB = input("Enter your choice: ")
if answer_WDNB.lower() == "d":
print("We still love you Dave!")
total_score += 20
print("Your new score is", total_score)
else:
print("The correct answer is Dave is the only non-lead singer here")
print("Your current score is:", total_score)
# final statements
print(" Good game, let's play again sometime! Your final score is:", total_score)
|
9cbc19445225bebe3b0a672cdd9779bea3e645f5 | MohammadMahdiOmid/Mathematical_Of_AI | /orthogonality/inner_product_features.py | 1,713 | 3.765625 | 4 | import math
import fractions
import matplotlib.pyplot as plt
import numpy as np
import sympy as sy
# computing x**T Ay
def lengthOfVector(x):
result = 0
sum = (x[0] ** 2) - (x[0] * x[1]) + (x[1] ** 2)
result = math.sqrt(sum)
print("result is:", result)
def orthogonal(x, y):
# dot product
multiple = 0
for i in range(len(x)):
multiple = multiple + x[i] * y[i]
print('multiple for angle is:', multiple)
# length of x
sum_x = 0
for i in range(len(x)):
sum_x = sum_x + x[i] * x[i]
sum_x = math.sqrt(sum_x)
print('length x for angle is:', sum_x)
# length of y
sum_y = 0
for i in range(len(y)):
sum_y = sum_y + y[i] * y[i]
sum_y = math.sqrt(sum_y)
print('length y for angle is:', sum_y)
# multiple of length x and y
mul_len = sum_x * sum_y
print('multiple of length x and y is :', mul_len)
# angle of x and y
frac = fractions.Fraction(multiple, int(mul_len))
print("fraction is:", frac)
if frac == 0:
print("Two vectores are orthogonal")
else:
print("Two vectores are not orthogonal")
ang = math.cos(frac)
print("Angle of x and y is:", ang)
def integrate(x):
def f(x):
return sy.tan(x)
def g(x):
return sy.cos(x)
x = sy.symbols('x')
result = sy.integrate(f(x) * g(x), (x, -math.pi, math.pi))
if result == 0:
print("Sin and Cos are orthonomial", '\n', "result of integral is:", result)
else:
print("Sin and Cos are not orthonomial", '\n', "result of integral is:", result)
if __name__ == '__main__':
x = [1, 1]
y = [-1, 1]
lengthOfVector(x)
orthogonal(x, y)
integrate(10)
|
a91cbef788753abfacad5c3263fd87e3668a9f01 | ErikWhiting/precalhelp | /precalhelp.py | 698 | 3.984375 | 4 | import factor
import trigfunctions
import raddegree
def getFactors() :
print "enter number to be factored"
x = eval(raw_input("> "))
factor.Factor(x)
User_Prompt()
def getFunctions() :
trigfunctions.Find_Functions()
User_Prompt()
def Conversion() :
raddegree.Get_Answer()
User_Prompt()
def User_Prompt() :
print """
What would you like to do?
[1] Find factors of a number.
[2] Find trigonometric functions.
[3] Convert radians to degrees or degrees to radians
[4] Exit
"""
userInput = eval(raw_input("> "))
if userInput == 1 :
getFactors()
elif userInput == 2 :
getFunctions()
elif userInput == 3 :
Conversion()
elif userInput == 4 :
exit()
User_Prompt()
|
911643de6eb6c03967499faa03e2c6efbbc2aefe | MrFunnyide/Study-Python | /Belajar/OperasiDanEkspresi/operasiBit.py | 433 | 3.5 | 4 | print(11 >> 1) # 11 = 1011 binner >> kekanan 1 jadi 101, 101 = 5 desimal ( right shift )
print(2 << 2) # 2 = 10 binner >> kekiri 2 jadi 1000 ( ditambahkan 0 ), 1000 = 8 desimal ( left shift )
print(5 & 3) # 5 = 101 dan 3 = 011 , 101 & 011 = 001 , 001 = 1 desimal (AND)
print(5 | 3) # 5 = 101 dan 3 = 011, 101 | 011 = 111, 111 = 7 desimal (OR)
print(5 ^ 3) # 5 = 101 dan 3 = 011, 101 xor 011 = 110, 110 = 6 desimal (xor)
|
b2207a262e2e839f63072621144b06d9997c1316 | MrFunnyide/Study-Python | /Belajar/perulangan/ListComprehnsion1.py | 901 | 4.09375 | 4 | # contohKe3 menemukan item yang ada di kedua list
list1 = ['d', 'i', 'c', 'o']
list2 = ['d', 'i', 'n', 'g']
duplikat = []
for a in list1:
for b in list2:
if a == b:
duplikat.append(a)
print(duplikat) # output ['d','i']
# dibandingkan dengan
# contohKe4 Implementasi dengan list comprehension
list_a = ['d', 'i', 'c', 'o']
list_b = ['d', 'i', 'n', 'g']
yang_Sama = [c for c in list_a for d in list_b if c == d]
print(yang_Sama) # output ['d', 'i']
# contohKe5 Kecilkan semua huruf
list_c = ['Hello', 'World', 'In', 'Python']
small_list_c = [_.lower() for _ in list_c]
print(small_list_c)
# Anda tidak perlu bingung saat melihat kode di Internet yang menuliskan seperti contoh di atas,
# karena garis bawah (underscore) termasuk penamaan variabel yang valid
# Secara umum "_" biasa digunakan sebagai throwaway variable (variabel tidak penting).
|
44239c05cae934363078d8829baf0c6fdce1c378 | MrFunnyide/Study-Python | /Belajar/Method/StaticMethod.py | 587 | 3.671875 | 4 | # sebuah fungsi yang mengubah metode menjadi metode statis (static method).
# Metode statis (static method) tidak menerima masukan argumen pertama secara implisit.
# contohnya :
class Kalkulator:
"""contoh kelas kalkulator sederhana"""
def f(self):
return 'hello world'
@staticmethod
def kali_angka(angka1, angka2):
return '{} x {} = {}'.format(angka1, angka2, angka1 * angka2)
# Pemanggilan dari class
# a = Kalkulator.kali_angka(2, 3)
# print(a)
# pemanggilan dari objek
# k = Kalkulator()
# a = k.kali_angka(2, 3)
# print(a) |
607f2c0b64c5135c729c98e4511c9cf65799bdd2 | MrFunnyide/Study-Python | /Belajar/OperasiListSetandString/inAndNotIn.py | 280 | 3.5 | 4 | # in dan not in = mengetahui sebuah nilai atau objek dalam list
# dan kasih nilai boolean
kalimat = 'Belajar Python di dalam Dicoding sangat menyenangkan'
print('Dicoding' in kalimat)
print('tidak' in kalimat)
print('Dicoding' not in kalimat)
print('tidak' not in kalimat)
|
541dd4981725c9e37816b577351cb8c13911624e | muhamadsechansyadat/learn-python-kelas-terbuka | /old/3/Main.py | 461 | 3.5 | 4 | # list itterable
jajan = ['baso', 'cimol', 'cilok', 'cilor']
for beli in jajan:
print(beli)
# string itterable
varString = 'sechan'
for nama in varString:
print(nama)
print(100*"=")
# for in for
varBuah = ['semangka', 'melon', 'jeruk', 'anggur']
varSayur = ['timun', 'tomat', 'cabai', 'selada']
varDataBelanjaan = [jajan, varBuah, varSayur]
for dataBelanja in varDataBelanjaan:
for semuaBelanjaan in dataBelanja:
print(semuaBelanjaan) |
3b7c810d3fecf7cf7be61a0383f967f34e43eb15 | wce-mtu/ev-smart-charge | /Simulation_1/singleCar.py | 2,907 | 3.8125 | 4 | def main():
car1 = make_car()
calc_rate_options(car1)
class Car(object):
# inputs
timeParked = 0
stateOfCharge = 0
batCapacity = 0
maxChargeRate = 0
# outputs
chargeRate = 0
priceRate = 0
balance = 0
def make_car():
car = Car()
car.timeParked = float(input('Enter amount of time vehicle will be parked (hrs): '))
car.stateOfCharge = float(input('Enter current state of charge of battery (%): '))
car.batCapacity = float(input('Enter max capacity of battery (kWh): '))
car.maxChargeRate = float(input('Enter max rate of charge battery can handle (kW): '))
return car
def calc_rate_options(car):
# INPUT car object
PRICE = 0.15 # Price per kWh
car.stateOfCharge = car.stateOfCharge / 100. # convert stateOfCharge percentage into number 0-1
maxPercentOutcome = ((car.maxChargeRate * car.timeParked) / car.batCapacity) + car.stateOfCharge
if maxPercentOutcome > 1: # Get High Percentage
highPercentOutcome = 1
else:
highPercentOutcome = maxPercentOutcome
midPercentOutcome = ((2.0/3) * (highPercentOutcome - car.stateOfCharge)) + car.stateOfCharge # Get Mid Percentage
lowPercentOutcome = ((1.0/3) * (highPercentOutcome - car.stateOfCharge)) + car.stateOfCharge # Get Low Percentage
rateHigh = ((highPercentOutcome - car.stateOfCharge) * car.batCapacity) / car.timeParked # Rate to charge to high (kW)
rateMid = ((midPercentOutcome - car.stateOfCharge) * car.batCapacity) / car.timeParked # Rate to charge to mid
rateLow = ((lowPercentOutcome - car.stateOfCharge) * car.batCapacity) / car.timeParked # Rate to charge to mid
# Assume customer is paying $1/kW
priceHigh = rateHigh * car.timeParked * PRICE # Price for high rate of charge
priceMid = rateMid * car.timeParked * PRICE # Price for mid rate of charge
priceLow = rateLow * car.timeParked * PRICE # Price for low rate of charge
print('High - Final Percentage: ', highPercentOutcome*100,'%', sep="") # Print High Button
print('Cost: $', "%.2f" % priceHigh)
print()
print('Mid - Final Percentage: ', midPercentOutcome*100,'%', sep="") # Print Mid Button
print('Cost: $', "%.2f" % priceMid)
print()
print('Low - Final Percentage: ', lowPercentOutcome*100,'%', sep="") # Print Low Button
print('Cost: $', "%.2f" % priceLow)
chosen = input('Choose "high" "med" or "low" rate: ')
if chosen == "high":
car.chargeRate = rateHigh
car.priceRate = priceHigh
elif chosen == "med":
car.chargeRate = rateMid
car.priceRate = priceMid
elif chosen == "low":
car.chargeRate = rateLow
car.priceRate = priceLow
else:
print('Invalid Input')
if __name__ == '__main__':
main()
|
b75efc543c76cd6aebd0a6c1a53d12c62797e4a9 | PathomphongPromsit/LAB-Programming-Skill | /code/reverse-111629.py | 651 | 3.921875 | 4 | from __future__ import print_function
def reverse(string_list,start_index,stop_index):
start_index -= 1
stop_index -= 1
reverse_list = string_list[start_index:stop_index+1]
LRevese= len(reverse_list)
for i in range(1,LRevese+1):
string_list[start_index] = reverse_list[-i]
start_index += 1
return string_list
if __name__ == "__main__":
n = int(input())
for i in range(n):
string = input()
string_list = list(string)
operand = int(input())
for i in range(operand):
start_index,stop_index = [int(i) for i in input().split()]
reverse(string_list,start_index,stop_index)
for i in string_list:
print(i, end='')
print()
|
6373bd20e4938d78d4a7ebb16abe3aa4e2487edf | Pappa/exercism | /python/rotational-cipher/rotational_cipher.py | 396 | 3.890625 | 4 | import string
lower = string.ascii_lowercase
upper = string.ascii_uppercase
def rotate(letters, rotation):
mapped = [_map(l, rotation) if l.isalpha() else l for l in letters]
return ''.join(mapped)
def _map(letter, rotation):
alphabet = (lower, upper)[letter.isupper()]
for i, c in enumerate(alphabet):
if c == letter:
index = (i + rotation) % len(alphabet)
return alphabet[index]
|
2c7d72136cf270bb2e1b965dc715db6027adfeda | Pappa/exercism | /python/isbn-verifier/isbn_verifier.py | 351 | 3.515625 | 4 | def verify(isbn):
chars = [c for c in isbn if c.isdigit() or c == 'X']
if len(chars) != 10:
return False
digits = [int(c) if c.isdigit() else 10 for idx, c in enumerate(chars) if c.isdigit() or (c == 'X' and idx == 9)]
multipliers = range(1, 11)[::-1]
return sum([d * m for (d, m) in zip(digits, multipliers)]) % 11 == 0
|
58c83c8518650bf3d81f0ba7d61b8fe2be538248 | Pappa/exercism | /python/pig-latin/pig_latin.py | 603 | 3.828125 | 4 | from string import ascii_lowercase
vowels = set(['a', 'e', 'i', 'o', 'u'])
consonants = set(ascii_lowercase) - vowels
def translate(phrase):
return ' '.join([translate_word(word) for word in phrase.split()])
def translate_word(word):
if word[0:3] in ['squ', 'sch', 'thr']:
word = word[3:] + word[0:3]
if word[0:2] not in ['yt', 'xr']:
if ((word[0] in consonants
and word[1] in consonants)
or word[0:2] == 'qu'):
word = word[2:] + word[0:2]
elif (word[0] in consonants):
word = word[1:] + word[0]
return word + 'ay' |
3f00d473d5ca721799a446f7d38f2a685c44934c | Pappa/exercism | /python/nth-prime/nth_prime.py | 333 | 3.734375 | 4 | def nth_prime(n):
if n < 1: raise ValueError
candidate = 2
primes = []
while len(primes) < n:
if is_prime(candidate):
primes.append(candidate)
candidate += 1
return primes.pop()
def is_prime(n):
for i in [2, 3, 5, 7, 9]:
if (n % i == 0):
return n == i
return all(False for i in range(11, n, 2) if (n % i == 0))
|
124bfa11a7c1c566422faad790e410707941b542 | Babecherry/CP1404_Practicals | /prac_03/oddnames.py | 325 | 3.8125 | 4 | """Sable Ching"""
def get_name():
global main
def main():
while True:
name = str(input("Please enter your name: \n"))
if name == '':
print("Invalid, please enter your name.")
else:
print(name[1::2])
break
get_name()
main()
|
6e769e65c9b4b5961ba912822edd2594e7327d01 | jobassous/flask_app | /strings.py | 249 | 3.53125 | 4 | orphan_fee = 200
teddy_bear_fee = 121.08
total = orphan_fee + teddy_bear_fee
name = "Joseph Bassous"
print(name, "the total will be", total)
print("%s, the total will be, %d" % (name, total))
print("{} the total will be ${}".format(name, total)) |
f64a7d1200db59192b0688977ab0d1be841231fc | ganjunhua/python | /numpytest/testnumpy.py | 389 | 3.546875 | 4 | import numpy as np
#切片
array=np.random.randint(1,10,16).reshape(4,4)
print(array)
#取出第一行所有值
#print(array[0])
#取出第一列所有值
#print(array[:,0])
#取出第一行和第三行
#print(array[1::2])
#取出第二列和第四列
print(array[::,1::2])
#取出第一行和第三行第二列和第四列
#print(array[0::2,1::2])
#c[2,1] = c[2][1]
#c[1,1,1]=c[1][1][1] |
805fafe1749557d9dad0a9b823bee4f30bb53399 | Nicholas-Nwanochie/python-work | /for-loops.py | 989 | 4.09375 | 4 | for name in friends:
print(name)
" for loop with numbers, last number is not shown"
for index in range(3, 10):
print(index)
friends = ["jim", "beth", "kevin"]
for index in range(len(friends)):
print(friends[index])
friends = ["jim", "beth", "kevin"]
for index in range(5):
if index == 0:
print("first go")
else:
print("not first")
for variable in range(1, 11):
for inner in range(1, 11):
sum = variable * inner
print(variable, "*", inner, "=", sum)
name ='nick'
print(f'hello {name}')
week= ["week1", "week2","week3", "week4","week5", "week6","week7", "week8"]
day = ["* monday","* tuesday","* wednsday","* thursday","* friday","* saturday","* sunday",]
nada = ["- sleep "" - sleep"]
for variable in week:
print("")
print("*", variable, "*")
for inner in day:
print("")
print(inner)
mystring ="".join(nada)
for blah in nada:
print(mystring ,",")
|
7909e0bf65ecb58fcef8817a8255efa18bd460fd | pankhurisri21/100-days-of-Python | /day1-exercise4.py | 132 | 4.28125 | 4 | #length of a string and variables
str=input("Enter the string\n")
print("The length of string "+"'"+str+"'"+" is:")
print(len(str))
|
d4fa98e23180564af50fc81547c953792c055d5f | pankhurisri21/100-days-of-Python | /19-dictionary.py | 91 | 3.5 | 4 | #dictionary
mydict={
"name":"John",
"age":21
}
print(mydict) #{'name': 'John', 'age': 21}
|
8a5739c9a6e6fc0209dfc47ec3879afad8a78a8a | pankhurisri21/100-days-of-Python | /sum_prog2.py | 245 | 3.8125 | 4 | #sum of n numbers
numbers=[1,2,3,4,5]
print("Sum of numbers in the list = ", sum(numbers))#sum of numbers in the list
print("Sum of numbers in the list and the start number =",sum(numbers,20))#sum ofnumbers in the list + the start number given
|
d490e1f73448f32eb150b3994f359cffb155acc4 | pankhurisri21/100-days-of-Python | /variables_and_datatypes.py | 548 | 4.125 | 4 | #variables and datatypes
#python variables are case sensitive
print("\n\nPython variables are case sensitive")
a=20
A=45
print("a =",a)
print("A =",A)
a=20#integer
b=3.33 #float
c="hello" #string
d=True #bool
#type of value
print("Type of different values")
print("Type of :",str(a)+" =",type(a))
print("Type of :",str(b)+" =",type(b))
print("Type of : "+str(c)+ " =",type(c))
print("Type of : "+str(d)+" =",type(d))
#Type conversion
print("New Type of:",a,end=" = ")
print(type(str(a)))
print("New Type of:",b,end=" = ")
print(type(int(b)))
|
f33e0bc2471b0dabd1ba19519be80b3428e9a197 | triplejingle/cito | /Eva/Applicatie/Backend/PythonPrototypes/Prototypes/MemoryTest/BinarySearchTree.py | 1,852 | 3.625 | 4 | from VariableNode import VariableNode
class BinarySearchTree(object):
def __init__(self):
self.root = None
def find(self, key):
if self.root.key == key:
return self.root
if self.root.key < key:
return self.__find(self.root.right, key)
if self.root.key > key:
return self.__find(self.root.left, key)
def __find(self, node, key):
if node.key < key:
node = self.__find(node.right, key)
if node.key > key:
node = self.__find(node.left, key)
return node
def insert(self, key, value):
node = VariableNode(key)
node.value = value
if self.root is None:
self.root = node
return
self.__insert(self.root, key, value)
def __insert(self, root, key, value):
node = VariableNode(key)
node.value = value
if root.key < key:
if root.right is None:
root.right = node
return
self.__insert(root.right, key, value)
if root.key > key:
if root.left is None:
root.left = node
return
self.__insert(root.left, key, value)
def find_leaf(self, root):
if root.left is not None:
return self.find_leaf(root.left)
if root.right is not None:
return self.find_leaf(root.right)
return root
def find_min(self):
return self.__find_min(self.root)
def __find_min(self, node):
if node.left is not None:
return self.__find_min(node.left)
return node
def find_max(self):
return self.__find_max(self.root)
def __find_max(self, node):
if node.right is not None:
return self.__find_max(node.right)
return node
|
a3217003bf74872adb90e519b0a04a8606b8af4e | flxsosa/CodingProblems | /morsels_1.py | 1,983 | 3.96875 | 4 | '''
I'd like you to write a function that accepts two lists-of-lists of numbers and returns one list-of-lists with each of the corresponding numbers in the two given lists-of-lists added together.
It should work something like this:
>>> matrix1 = [[1, -2], [-3, 4]]
>>> matrix2 = [[2, -1], [0, -1]]
>>> add(matrix1, matrix2)
[[3, -3], [-3, 3]]
>>> matrix1 = [[1, -2, 3], [-4, 5, -6], [7, -8, 9]]
>>> matrix2 = [[1, 1, 0], [1, -2, 3], [-2, 2, -2]]
>>> add(matrix1, matrix2)
[[2, -1, 3], [-3, 3, -3], [5, -6, 7]]
Try to solve this exercise without using any third-party libraries (without using pandas for example).
Before attempting any bonuses, I'd like you to put some effort into figuring out the clearest and most idiomatic way to solve this problem. If you're using indexes to loop, take a look at the first hint.
There are two bonuses this week.
Bonus 1
For the first bonus, modify your add function to accept and "add" any number of lists-of-lists. ✔️
>>> matrix1 = [[1, 9], [7, 3]]
>>> matrix2 = [[5, -4], [3, 3]]
>>> matrix3 = [[2, 3], [-3, 1]]
>>> add(matrix1, matrix2, matrix3)
[[8, 8], [7, 7]]
Bonus 2
For the second bonus, make sure your add function raises a ValueError if the given lists-of-lists aren't all the same shape. ✔️
>>> add([[1, 9], [7, 3]], [[1, 2], [3]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "add.py", line 10, in add
raise ValueError("Given matrices are not the same size.")
ValueError: Given matrices are not the same size.
'''
def add(m1,m2):
# Assuming matrices have same shapes
m = []
for row1,row2 in zip(m1,m2):
row = []
for col1,col2 in zip(row1,row2):
row.append(col1+col2)
m.append(row)
return m
def add_argv(*arg):
if len(arg) == 1:
return arg[0]
add_argv(arg[1:])
matrix1 = [[1, -2], [-3, 4]]
matrix3 = [[1, -2], [-3]]
matrix2 = [[2, -1], [0, -1]]
print(add(matrix1,matrix2))
print(add_argv(matrix1,matrix2))
|
ebb0a699bca0308d439959ad77f323fd94776774 | JingqiDuan/Hash-Code-2018 | /Vehicle.py | 2,183 | 3.78125 | 4 | from Point import Point
class Vehicle:
# #
# Init function
#
# city is a link to the parent
# index is the number associated with the vehicle
def __init__(self, city, index):
self.position = Point(0,0)
self.index = index
self.city = city
self.inRide = False
self.ride = self.nextRide()
self.pastRides = []
# #
# Allow to quickly display a vehicle
def __repr__(self):
return "Vehicle n°" + str(self.index) + " at the position " + str(self.position)
# #
# Move the car to the next step
def nextStep(self):
if self.inRide:
newPosition = self.ride.end.goTo( self.position )
self.position.set(newPosition[0], newPosition[1])
elif not(self.inRide) and (self.ride != False) and self.ride != None:
newPosition = self.ride.start.goTo( self.position )
if newPosition != True:
self.position.set(newPosition[0], newPosition[1])
# Check if we stop the ride
if self.inRide and self.position == self.ride.end:
# print("Stop ride ", self.ride)
self.inRide = False
self.ride.endRide = self.city.time
self.pastRides.append(self.ride)
self.ride = self.nextRide()
# Check if we start the ride
if not(self.inRide) and (self.ride != False) and (self.ride.start == self.position) and (self.ride.s <= self.city.time):
self.inRide = True
self.ride.startRide = self.city.time
# print("Start ride", self.ride)
# #
# Find the next ride
#
# This function is subjected to optimisation
def nextRide(self):
if( len(self.city.ridesToDo) == 0 ):
return False
# Highest weight ever !
weight = self.city.T
for ride in self.city.ridesToDo:
if ride.getWeight(self) < weight:
weight = ride.getWeight(self)
closestRide = ride
# Change the array of rides
self.city.ridesToDo.remove(closestRide)
self.city.ridesDone.append(closestRide)
return closestRide
|
f501c9f172241079ef33440ccaac5cf3e473bc48 | vanjara/problems | /cyclelist.py | 2,236 | 3.953125 | 4 | # /usr/bin/python2.7
# Converting Sam's Java code to Python
from nose.tools import assert_equal
class Node (object):
def __init__(self, value):
self.value = value
self.next = None
# Algorithm using extra space. Mark visited nodes and check that you
# only visit each node once.
def hasCycle(node):
visited = set()
current = node
while current is not None:
if current in visited:
return True
else:
visited.add(current)
current = current.next
return False
# Floyd's algorithm. Increment one pointer by one and the other by two.
# If they are ever pointing to the same node, there is a cycle.
# Explanation is at:
# https://www.quora.com/How-does-Floyds-cycle-finding-algorithm-work
def hasCycleFloyd(node):
if node is None:
return False
slow = node
fast = node.next
while fast is not None and fast.next is not None:
if (fast == slow):
return True
fast = fast.next.next
slow = slow.next
return False
# Tests
# Test Case 1 - create a cyclical linked list
a = Node(1)
b = Node(2)
c = Node(3)
a.next = b
b.next = c
c.next = a # Cycle Here!
# Test Case 2 - not a cycle
a1 = Node(4)
b1 = Node(5)
c1 = Node(6)
a1.next = b1
b1.next = c1
# Test Case 3 - None
a2 = None
# Test Case 4 - Single Node
a3 = Node(1)
# Test Case 5 - Single Node linked to itself
a4 = Node(1)
a4.next = a4
# Define Class for Testing
class TestLinkedListCycle(object):
def test(self, sol):
print "Testing Case 1 -- Cycle"
assert_equal(sol(a), True) # Case 1 - cycle
print "Testing Case 2 -- Not a Cycle"
assert_equal(sol(a1), False) # Case 2 - not a cycle
print "Testing Case 3 -- None"
assert_equal(sol(a2), False) # Case 3 - None
print "Testing Case 4 -- Single Node"
assert_equal(sol(a3), False) # Case 4 - Single Node, not a cycle
print "Testing Case 5 -- Single Node Cycle"
assert_equal(sol(a4), True) # Case 5 - Single Node cycle
print "Passed all test cases"
# Run Tests
myTest = TestLinkedListCycle()
myTest.test(hasCycle)
# Test Floyd's algorithm implementation
myTest.test(hasCycleFloyd)
|
04676613eb281256e87c53bcf7f3dfabe4e19663 | LucasXS/PythonExercicios | /exer013.py | 382 | 3.59375 | 4 | #LER O SALÁRIO DE UMA FUNCIONÁRIA E MOSTRAR SEU NOVO SALÁRIO COM 15% DE AUMENTO
nomeFuncionario = input('NOME FUNCIONARIO: ')
salarioAtualFunc = float(input('SALÁRIO ATUAL R$'))
novoSalario = salarioAtualFunc + (salarioAtualFunc * 15/100)
print('O Funcionário {} deixará de receber {:.2f} e passará a receber {:.2f}'.format(nomeFuncionario, salarioAtualFunc, novoSalario))
|
d02db2c39a06353f685bff400170807e67fc1993 | LucasXS/PythonExercicios | /exer010.py | 322 | 3.515625 | 4 | #LER QUANTO DINHEIRO UMA PESSOA TEM E CONVERTER P/ OUTRAS MOEDAS - 07/02/2021
emReal = float(input('Quanta grana você tem? R$'))
emDolar = emReal / 5.37
emEuro = emReal / 6.47
emIene = emReal /0.051
print('R${} reais dá exatamente \n${:.2f} dolares \n€{:.2f} Euros \n¥{:.2f} Ienes'.format(emReal, emDolar, emEuro, emIene))
|
c0f6cb573875db49cc49a94920e44a4f04030e23 | LucasXS/PythonExercicios | /exer017.py | 530 | 3.9375 | 4 | #ler o comprim cateto oposto e cateto adjacente (triag. retang). Cal. e mostre o compr. da hipotenusa.
print("="*25)
print('{:=^25}'.format('SEJA BEM VINDO!!'))
print("="*25)
import math
print("Insira o cateto oposto e adjacente para calcular a hipotenusa!")
catOposto = float(input('Digite o valor do cateto oposto: '))
catAdjacente = float(input('Digite o valor do cateto adjacente: '))
hipotenusa = math.hypot(catOposto, catAdjacente)
print('O valor da hipotenusa é {:.2f}'.format(hipotenusa))
print('ESPERO TER AJUDADO!')
|
475999ede4a2eb11fe5a11028966331fb5c33f42 | LucasXS/PythonExercicios | /exer003.py | 326 | 3.875 | 4 | #SOMAR DOIS NUMEROS E MOSTRAR NA TELA, USAR O .FORMAT.
n1 = int (input('Digite um valor: '))
n2 = int (input('Digite um valor: '))
s = n1 + n2
#print('A soma entre',n1, 'e', n2,' vale', s) sem o .format
print('A Soma entre \033[4;33m{}\033[m e \033[4;35m{}\033[m vale \033[1;31;46m{}\033[m'.format(n1, n2, s)) #com o .format
|
941bb40a625b55519e563120b4d84652c580b84f | aaronhoby/csua-git-workshop | /best.py | 373 | 3.765625 | 4 |
def main():
person_a = "Yi"
superlative_a = "dankest"
person_b = "Ni"
superlative_b = "weebest"
name = "Garcia"
position = "professor"
print("{0}: {1} is the {2} {3}!".format(person_a, name, superlative_a, position))
print("{0}: {1} is the {2} {3}!".format(person_b, name, superlative_b, position))
if __name__ == '__main__':
main()
|
e62f086dd89dd61ef0bc10ca8203fc3ba11e0190 | beibeisongs/K-Means-Realizing | /K-Means Test1.py | 9,280 | 4.40625 | 4 | # encoding=utf-8
# Date: 2018-7-22
# Author: MJUZY
"""
The Analysis of K-Means algorithm:
* Advantages:
Easy to be Realized
* Disadvantages:
Probable to Converge to a local minimum value
Converge to a local minimum value: 收敛到局部最小值
* IDEA of K-Means:
First, we should choose a value K
The K refers to the num of the Clusters we will create later
Second, we should choose the original Centroid
Centroid: n 质心 重心 聚类点
The Centroid is generally chosen at Random
And the Centroid here is chosen among the Data Region at Random
And the another method is to choose one of the Sample of the DataSet
But it may cause Converging to a local minimum value
So we do not use the second Method
* The Notes of K-Means Realising by myself:
Then we will compute every Distance between each Sample and the Centroid
and Classify the Samples to the Centroid when they have the Minimun Distance
After Completing the Step above, we will repeat the same step
util the result stops to Converge
* Recording the Functions:
def loadDataSet(filename)
# Read the DataSet from the file
def distEclud(VecA, VecB)
# Compute the Distances
# Using Euclidean Distance
# In Addition, Other kinds of reasonable Distance are OK, too
def randCent(dataSet, k)
# Create Centroids at Random
# Choose a specific Point in the Data Region
def kMeans(dataSet, k, distMeas=distEclud, createCent=randCent)
# K-Means Algorithm: Input the DataSet and the K value
# The next two Parameters respectively are the Computing Method optional and the Method to choose Centroids
def show(dataSet, k, centroid, clusterAssment)
# Make the Result visualized
"""
from numpy import *
import csv
def loadDataSet(filename):
"""
:param label: an One Dimension Array
:param dataSet: A Multi-Dimension Matrix
:return: dataSet, label
"""
dataSet = []
with open(filename, "r") as csvfile:
reader2 = csv.reader(csvfile) # 读取csv文件,返回的是迭代类型
for item2 in reader2:
dataSet.append(item2)
csvfile.close()
label = ['特征一', '特征二', '特征三', "特征四"]
return dataSet
def randCent(dataSet, k):
"""
Create Centroids at Random
:param dataSet:
:param k: refers to the num of Centroids to be created
:return:
"""
# <Sample>: dataSet.shape = <class 'tuple'>: (150, 4) n = 4
# Get the num of the Features of the Samples
n = shape(dataSet)[1]
# <Description>: create a k * n matrix to store the k centroids of n dimensions
centroids = mat(zeros((k, n)))
for j in range(n):
# ---------------------------------------------- There is a Wonderful Coding Technique !
minJ = min(dataSet[:, j])
rangeJ = float(max(array(dataSet)[:, j]) - minJ)
# ----------------------------------------------
centroids[:, j] = minJ + rangeJ * random.rand(k, 1) # Get Numbers from [0, 1]
# And rand(k, 1) means the Array Size of k * 1
return centroids
def distEclud(vecA, vecB):
"""
Compute the Euclidean distance of the Vectories
:param vecA:
:param vecB:
:return:
"""
power_value = power(vecA - vecB, 2)
sum_value = sum(power_value)
result = sqrt(sum_value)
return result
def kMeans(dataSet, k, distMeans=distEclud, createCent=randCent):
# <Sample>: dataSet.shape = <class 'tuple'>: (150, 4) m = 150
m = shape(dataSet)[0]
"""
Functions of "zeos()":
Create an Array whose elements are all 0
Samples:
>>myMat=np.zeros(3) # Create an Array with elements all 0
>>print(myMat)
>>array([0.,0.,0.])
>>myMat1=np.zeros((3,2)) # Create an 3 * 2 Array with elements all 0
>>print(myMat)
>>array([[0.,0.],
[0.,0.]
[0.,0.]])
clusterAssment = mat(zeros((m, 2)))
Used to create matrix to assign data points
to a centroid, also holds SE of each point
"""
clusterAssment = mat(zeros((m, 2))) # <Description>: So the size of the Matrix
# clusterAssment is m * 2
# During this Sample
centroids = createCent(dataSet, k)
clusterChanged = True
while clusterChanged:
clusterChanged = False
for i in range(m): # for each data Point assign it to the Closest Centroid
minDist = inf # inf = Infinity n 无穷大
minIndex = -1
for j in range(k):
"""
centroids[j, :] get all elements of the specific dimension
dataSet[i, :] get all elements of the specific dimension
distJI = distMeans(centroids[j, :], dataSet[i, :])
Get the Distance of the two Vectories
"""
distJI = distMeans(centroids[j, :], dataSet[i, :])
if distJI < minDist:
minDist = distJI # <Description>: minDist/distJI is the Euclidean distance of the two Vectories
minIndex = j # <Attention>:
# Now the j's range is [0, k]
# The most ideal situation is that all the clusterAssment[i, 0] = minIndex
# When all the clusterAssment[i, 0] equals minIndex
# The Loop will be stopped
if clusterAssment[i, 0] != minIndex:
"""<Attention>:
So the size of the Matrix
clusterAssment is m * 2
During this Sample, its size is 150 * 2
"""
clusterChanged = True # So the "while" Loop will be continued
# <Description>: Symbol "** 2" means to Calculate the Square
# <Attenion>;
# the Size of the list "clusterAssment" is m * 2
# During this Sample m * 2 equals 150 * 2
# [i, :] = minIndex, minDist **2, after that, it has only 2 elements in each Dimension
clusterAssment[i, :] = minIndex, minDist **2
print("Centroid Temporary : ", centroids)
for cent in range(k): # Recalculate the Centroids
# <Attention>: k is the num of the clusters will be created
"""
Get all the Points in this cluster
if you want to Grasp the logic Details clearly
please debug the codes following:
"""
Get_FirstElement_intoArray = clusterAssment[:, 0].A
Get_Matched_Array = (Get_FirstElement_intoArray == cent)
operate_nonzero = nonzero(Get_Matched_Array)
Get_FirstElement_Again = operate_nonzero[0]
ptsInClust = dataSet[Get_FirstElement_Again]
# <Description>: correct the Temporary Centroids by the Average Distance Points
centroids[cent, :] = mean(ptsInClust, axis=0)
return centroids, clusterAssment
def show(dataMat, k, centroids, clusterAssment):
from matplotlib import pyplot as plt
numSamples, dim = dataMat.shape
mark = ['or', 'ob', 'og', 'ok', '^r', '+r', 'sr', 'dr', '<r', 'pr']
"""
Attention:
PLT can only show the Clusters in a TWO-DIMNSION Graph
"""
for i in range(numSamples):
markIndex = int(clusterAssment[i, 0])
plt.plot(dataMat[i, 0], dataMat[i, 1], mark[markIndex])
mark = ['Dr', 'Db', 'Dg', 'Dk', '^b', '+b', 'sb', 'db', '<b', 'pb']
for i in range(k):
plt.plot(centroids[i, 0], centroids[i, 1], mark[i], markersize=12)
plt.show()
def main(k):
"""
:param k: whick is set for the K-Means before hand
:param dataMat: type: matrix
:return NULL
"""
# Funtion mat() can transform the paramter's data type from list to matrix
# Specifically refering: http://www.cnblogs.com/MrLJC/p/4127553.html
# <Attention>:
# Function "mat()" will make the elements of the Matrix string
# Function "astype(DataType)"will make the elements of the Matrix DataType
dataMat = mat(loadDataSet('iris_Test1.csv')).astype(float)
print("This is the original Data Matrix : ", dataMat)
centroids, clusterAssment = kMeans(dataMat, k)
print("My Centroids are : ", centroids)
show(dataMat, k, centroids, clusterAssment)
if __name__ == "__main__":
"""
:param k: this is the num of the clusters you want to create
"""
k = 3
main(k) |
a272f4c2b2f76f6b8ea4ba0d7d157eec6a8e4f45 | SanFullStack/MyHTML | /moviename.py | 2,523 | 3.84375 | 4 | import random
def choose():
List=[junglebook,titanic,dearzindagi,deshdrohi,stree,fan,tamasha,thappad,sexeducation]
secret=random.choice(list)
return secret
def moviename():
p1name=input("Player 1 please enter your name :")
p2name=input("Player 2 please enter your name :")
pp1=0
pp2=0
turn=0
willing=True
while willing:
if (turn%2==0):
print(p1name," its your turn : ")
picked_movie=random.choice(List)
qn=create_question(picked)
print (qn)
modified_qn=qn
not_said=True
while not_said:
letter=input("Enter the letter : ")
if(is_present(letter,picked_movie)):
modified_qn=unlock(modifeid_qn,picked_movie,ch)
print(modified_qn)
d=input("PRess 1 to guess the movie name or 2 to unlock anpther letter :")
if d==1:
ans=input("Your answer : ")
if (ans==picked_movie):
pp1=pp1+5
print("Correct")
not_said=False
print(p1name," your score is ",pp1)
else:
print (letter," not found ")
c=input("Press 1 to continue or 0 to quit : ")
if (c==0):
print(pp1,pp2)
willing=False
else:
turn=turn+1
else:
print(p2name," its your turn : ")
picked_movie=random.choice(List)
qn=create_question(picked)
print (qn)
modified_qn=qn
not_said=True
while not_said:
letter=input("Enter the letter : ")
if(is_present(letter,picked_movie)):
modified_qn=unlock(modifeid_qn,picked_movie,ch)
print(modified_qn)
d=input("Press 1 to guess the movie name or 2 to unlock anpther letter :")
if d==1:
ans=input("Your answer : ")
if (ans==picked_movie):
pp2=pp2+5
print("Correct")
not_said=False
print(p2name," your score is ",pp2)
else:
print (letter," not found ")
else:
play()
|
3c2ca2d36af1386e0259d7b72efea78b6dfc7486 | ameet-1997/Machine-Learning | /Boston_House_Prices/boston_price.py | 775 | 3.890625 | 4 | import pandas as pd
from sklearn.datasets import load_boston
# boston is a dictionary
boston = load_boston()
# Store the data and target in respective variables
data = boston.data
target = boston.target
# Convert to pandas dataframe and assign column names to dataframe
(data, target) = (pd.DataFrame(data), pd.DataFrame(target))
data.columns = boston.feature_names
# Print the shape of the data
print('The shape of the data is : ' + str(data.shape))
# Find dependence of data on attribute "CHAS", see description
# of data to see what it represents
# Calculate the average price for houses "not near" and "near" the river Charles("CHAS")
chas = [0, 0]
chas[0] = target[np.array(data['CHAS'] == 0)][0].mean()
chas[1] = target[np.array(data['CHAS'] == 1)][0].mean()
|
ecd41eb8842c8e498b92a82c7559dbfb9ef89a52 | haved/haved.github.io | /assets/tasks/bus/impl.py | 1,669 | 3.71875 | 4 | #!/bin/env python3
n = int(input())
trips = []
for _ in range(n):
times = input().split(' ')
trips.append((int(times[0]), int(times[1])))
# Sort by decreasing arrive_time when the leave_time is the same
trips.sort(key=lambda x:x[1], reverse=True)
# By increasing leave_time
trips.sort(key=lambda x:x[0])
trips = [trips[0]] + [b for a,b in zip(trips, trips[1:]) if a!=b] #Remove duplicates
stack = []
for trip in trips:
while stack and stack[-1][1] >= trip[1]:
#The trip on the stack is worse than trip
stack.pop()
stack.append(trip)
# The stack contains trips not yet determined to be bad.
# The trips are processed in acending leave_time.
# This means any trip already on the stack, has a lower or equal
# leave_time than the trip we are currently looking at
# If the trip on the stack arrives later than the current trip
# that means the trip on the stack starts earlier and ends later
# than the current trip. Therefore the stack trip is worse, and the stack is popped.
# This is repeated until the trip on the top of the stack ends before the current trip.
# At that point, all trips down the stack are safe, because
# no trip further down the stack ends after the top trip.
# After the stack-popping is done, we add the current trip.
# If multiple trips start at the same time, the one
# with the larger arrive_time comes first, because
# it needs to be popped by the better trip, when it comes later.
# The sorting we do at the start makes sure
# that a trip always comes before the trip it is objectivly worse than.
# This means the last trip is guarranteed to be good.
print(len(stack))
for a, b in stack:
print(a, b)
|
2ab9aadcc835b15bd2d5c16450bdeec70e2c40df | 00008883/seminar8 | /task1.py | 173 | 3.53125 | 4 | student1 = ('00008883', 19, 'Tashkent')
student2 = ('00009623', 18, 'Andijan')
print(student1[0]>student2[0])
print(student1[1]>student2[1])
print(student1[2]>student2[2]) |
4ba1e62b154b3b46c84c4a94ce09fceaced1d982 | lvrohai/rhprapy | /days100/days1_15/12/untitled/re_operation.py | 2,391 | 3.53125 | 4 | import re
def main():
username=input("请输入用户名")
qq = input("请输入QQ")
# match方法的第一个参数是正则表达式字符串或正则表达式对象
# 第二个参数是要跟正则表达式做匹配的字符串对象
# 用正则表达式匹配字符串 成功返回匹配对象 否则返回None
m1 = re.match(r'^[0-9a-zA-Z_]{6,20}$',username)
if not m1:
print('请输入有效的用户名')
m2 = re.match(r'^[1-9]\d{4,11}$',qq)
if not m2:
print('请输入有效的QQ号')
if m1 and m2:
print('输入都有效')
def main1():
pattern = re.compile(r'(?<=\D)1[34578]\d{9}(?=\D)')
sentence = '''
重要的事情说8130123456789遍,我的手机号是13512346789这个靓号,
不是15600998765,也是110或119,王大锤的手机号才是15600998765。
'''
# 查找所有匹配并保存到一个列表中
mylist = re.findall(pattern,sentence)
print(mylist)
print('-----------------------------')
# 通过迭代器取出匹配对象并获得匹配的内容
# 查找字符串所有与正则表达式匹配的模式 返回一个迭代器
# print(pattern.finditer(sentence))
for temp in pattern.finditer(sentence):
print(temp.group())
print('-----------------------------')
# 通过search函数指定搜索位置找出所有匹配
m = pattern.search(sentence)
while m:
print('m->'+ str(m))
print(m.group())
print(m.groups())
print(m.end())
m = pattern.search(sentence,m.end())
def main2():
sentence = '你丫是傻叉吗? 我操你大爷的. Fuck you.'
# sub(pattern, repl, string, count=0, flags=0)用指定的字符串替换原字符串中与正则表达式匹配的模式 可以用count指定替换的次数
purified = re.sub(r'[操肏艹]|fuck|shit|傻[比屄逼叉缺吊屌]|煞笔','*',sentence,flags=re.IGNORECASE)
print(purified)
def main3():
poem = ',窗前明月光,疑是地上霜。举头望明月,低头思故乡。'
# split(pattern, string, maxsplit=0, flags=0)用正则表达式指定的模式分隔符拆分字符串 返回列表
sentence_list = re.split(r'[,.,。]',poem)
print(sentence_list)
while '' in sentence_list:
sentence_list.remove('')
print(sentence_list)
if __name__ == '__main__':
main3()
|
c3178ae575e71a862d6c43c8a7a00ea81b706226 | kaciyn/set09103 | /battleship.py | 1,526 | 3.765625 | 4 | from flask import Flask,redirect,url_for
app = Flask(__name__)
@app.route('/')
def battleship():
from random import randint
board = []
#board build
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
#intro
print "Battleship time, motherfucker!"
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
#debug from here:
#print ship_row
#print ship_col
#main bit
#edit tries here
tries=10
for turn in range(tries):
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
if guess_row == ship_row and guess_col == ship_col:
print "you FUCKER that's my SHIP"
break
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "that's not even in the ocean you ingrate"
tries=tries+1
elif(board[guess_row][guess_col] == "X"):
print "you guessed that one already????"
else:
print "haha you missed you waste of space"
board[guess_row][guess_col] = "X"
if turn==10:
print'Game Over'
print (tries-(turn+1)),' turns left'
print_board(board)
|
300d9dbb91d2c5dd41f05aba997593774157f7b0 | MattWarren97/PatienceSolver | /Move.py | 551 | 3.546875 | 4 | from Card import Card
class Move:
def __init__(self, card, newPos, oldPos):
self.card = card
self.newPos = newPos
self.oldPos = oldPos
def getPosStr(self, pos):
return "(" + str(pos[0]) + "," + str(pos[1]) + ")"
def __repr__(self):
toPrint = ""
toPrint += "Move: " + str(self.card)
toPrint += " from " + self.getPosStr(self.oldPos)
toPrint += " to " + self.getPosStr(self.newPos)
return toPrint
def getOldPos(self):
return self.oldPos
def getNewPos(self):
return self.newPos
def getCard(self):
return self.card
|
697648a2525e9e48b9e1260fd07c41375d977e57 | MilaMaest/NumPy_Tutorials | /numpy_tuto2.py | 682 | 3.546875 | 4 | import numpy as np
x = np.array([
[2,8,6],
[5,9,3],
[9,6,7]
])
print(x)
y = np.array([
(1,1,1),
(2,2,2),
(3,3,3)
])
print(y)
# Specify the type of array explicitly
z = np.array([ [7,8,7,8], [5,9,5,9] ], dtype=float)
print(z)
# zeros()
zeros_array = np.zeros((2,4))
print('Zeros array : \n',zeros_array)
zeros_like_array =np.zeros_like(zeros_array)
print(zeros_like_array)
# ones()
ones_array = np.ones((3,5))
print('Ones array : \n',ones_array)
# make an empty array
empty_array = np.empty( (4,4) )
print('Empty array', empty_array) # the values may vary
|
d6bc3dc3ede95a6049fa9d1ed185087bf1475833 | HeWei-imagineer/Algorithms | /Leetcode/002_Add_Two_Number.py | 1,470 | 3.65625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
num1,num2,i=0,0,0
while(l1):
num1 = num1 + l1.val*10**i
l1 = l1.next
i+=1
i=0
while(l2):
num2 = num2 + l2.val*10**i
l2 = l2.next
i+=1
num = num1+num2
alist = []
while(num//10):
n=num%10
alist.append(n)
num=num//10
alist.append(num)
i=0
anodelist = []
for i in alist:
anodelist.append(ListNode(i))
for i in range((len(anodelist)-1)):
anodelist[i].next = anodelist[i+1]
return anodelist[0]
#改进,直接在一趟循环里计算
def addTwoNumbers_1(self, l1, l2):
head = ListNode(0)
p,q,h,temp = l1,l2,head,0
while p or q:
x=p.val if p else 0
y=q.val if q else 0
num = x + y + temp
h.next = ListNode(num%10)
h = h.next
temp = num // 10
if p :
p = p.next
if q :
q = q.next
return head.next
#test
n1 = ListNode(6)
n2 = ListNode(2)
n3 = ListNode(6)
n1.next = n2
s = Solution()
ll=s.addTwoNumbers_1(n1, n3)
l = ll
while l:
print(l.val)
l = l.next
|
d9f185d9097e1341c3769d693c9976e25eea6d23 | HeWei-imagineer/Algorithms | /Leetcode/hanoi.py | 591 | 4.15625 | 4 | #关于递归函数问题:
def move_one(num,init,des):
print('move '+str(num)+' from '+init+' to '+des)
print('---------------------------------')
def hanoi(num,init,temp,des):
if num==1:
move_one(num,init,des)
else:
hanoi(num-1,init,des,temp)
move_one(num,init,des)
hanoi(num-1,temp,init,des)
# 一件很难的事,我可以完成其中一小步,剩下的交给第二个人做。
# 第二个人接到任务时,想我可以完成其中一小步,剩下的交给第三个人做。...
# 直到任务最后被分解成简单的一小步。 |
36ad67d73e00225de0b641daea241b9810071915 | HeWei-imagineer/Algorithms | /Leetcode/009_Palindrome_Number.py | 958 | 3.546875 | 4 | class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
s = str(x)
star,end=0,len(s)-1
while star<end:
if s[star]==s[end]:
star += 1
end -=1
else:
break
return False if star<end else True
def isPalindrome_1(self, x):
"""
:type x: int
:rtype: bool
"""
#虽然ac,但考虑太少,负数,没注意不能有额外空间
#so another show
if x<0 or (x%10==0 and x!=0):
return False
else:
revertedNum = 0
#这里很巧妙,倒置整数会导致overflow
while x > revertedNum:
revertedNum = revertedNum*10 + x%10
x = x//10
if x==revertedNum or x==revertedNum//10:
return True
else:
return False
s = Solution()
print(s.isPalindrome_1(-2147483648)) |
d6de93d7b9a1ce5be40af662edee4f86e69f840d | HeWei-imagineer/Algorithms | /Leetcode/023_Merge_k_Sorted_Lists.py | 1,395 | 4.0625 | 4 | #Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
#cool, harder ac one time
class Solution:
def mergeKLists(self, lists):
if len(lists)>1:
middle = len(lists)//2
return self.merge(self.mergeKLists(lists[:middle]),
self.mergeKLists(lists[middle:]))
else:
return lists
def merge(self,l1,l2):
head = dump = ListNode(0)
while l1 or l2:
if not l1 or not l2:
dump.next = l2 if not l1 else l1
break
elif l1.val <= l2.val:
dump.next = l1
l1 = l1.next
else:
dump.next = l2
l2 =l2.next
dump = dump.next
return head.next
#there is another way of comparision node one by one. it used priority queue.
from queue import PriorityQueue
def mergeKLists(self, lists):
head = dump = ListNode(0)
q = PriorityQueue()
for l in lists:
q.put((l.val,l))
while not q.empty():
val,node = q.get()
dump.next = ListNode(val)
node = node.next
if node:
q.put((node.val,node))
return head.next
if True:#__name__ == "__main()__":
s = Solution()
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n5 = ListNode(5)
n6 = ListNode(6)
n7 = ListNode(7)
n1.next = n3
n3.next = n4
n4.next = n6
n2.next = n5
n5.next = n7
l = s.merge(n1,None)
while l:
print(l.val)
l = l.next
|
bb0185098dcf19ccbf277239364d8e46fa6d7e88 | nimberledge/MiscScripts | /rotate180.py | 656 | 3.875 | 4 | test_matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
def rotate180(matrix):
new_matrix = [None for i in range(len(matrix))]
# Here's the algorithm
# Take the i-th row, reverse it
# Insert as the N-1-ith row
for i, row in enumerate(matrix):
new_matrix[len(matrix)-i-1] = row[::-1]
return new_matrix
def disp(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
print matrix[i][j],
print
if __name__ == "__main__":
disp(test_matrix)
print "\n\n"
final = rotate180(test_matrix)
disp(final)
|
e6486c00528623a4f674b57a36abc8dd0b759ea8 | Thorchy/advent-of-code-2017 | /day_02/day_02.py | 1,689 | 4 | 4 | import csv
import os
LARGEST_SMALLEST = False
def largest_smallest(filepath):
with open(filepath) as f:
csv_reader = csv.reader(f, delimiter='\t')
checksum = 0
# Create checksum with the largest - smallest integer
for row in csv_reader:
row = map(int, row)
largest = max(row)
smallest = min(row)
difference = largest - smallest
checksum += difference
return checksum
def divide_whole(filepath):
with open(filepath) as f:
csv_reader = csv.reader(f, delimiter='\t')
checksum = 0
# Create checksum by dividing the 2 integers that divide whole
for row in csv_reader:
row = map(int, row)
number_1 = None
number_2 = None
for x in row:
first = True
for y in row:
if x == y and first:
first = False
continue
if x % y == 0:
number_1 = x
number_2 = y
checksum += number_1 / number_2
return checksum
def main():
print "Day 2, Half 1: {}".format(largest_smallest(os.path.join(os.path.dirname(__file__), 'input.txt')))
print "Day 2, Half 2: {}".format(divide_whole(os.path.join(os.path.dirname(__file__), 'input.txt')))
def test_largest_smallest():
assert largest_smallest(os.path.join(os.path.dirname(__file__), 'test_input_01.txt')) == 18
def test_divide_whole():
assert divide_whole(os.path.join(os.path.dirname(__file__), 'test_input_02.txt')) == 9
if __name__ == '__main__':
main()
|
60517bb8871144f55f41e4931167fec7379cf83e | swansonk14/graphing_fleas | /board.py | 8,028 | 3.859375 | 4 | import pygame
import random
from constants import COLOR_MAP
from helpers import row_column_to_pixels
from square import Square
class Board:
"""A Board contains, controls, and displays all Squares and Fleas in the simulation."""
def __init__(self,
screen,
num_rows,
num_cols,
flea_class,
num_fleas,
flea_rows,
flea_cols,
init_directions,
square_colors,
image,
visited,
coordinates,
hide_grid):
"""Initializes the Board.
Arguments:
screen(Surface): A pygame Surface representing the screen display.
num_rows(int): The number of rows in the Board.
num_cols(int): The number of columns in the Board.
flea_class(class): The class of the Fleas to create.
num_fleas(int): The number of Fleas to create.
flea_rows(list): The initial rows of the fleas.
(None to start in the center vertically.
Unspecified fleas will be placed randomly.)
flea_cols(list): The initial columns of the fleas.
(None to start in the center horizontally.
Unspecified fleas will be placed randomly.)
init_directions(list): The initial directions of the fleas.
(Uspecified fleas will start facing up.)
square_colors(list): Initial configuration of the colors of the squares.
(list of list of ints representing square colors.)
If None, all squares are initialized to color 0.
image(str): Name of image file in images directory to use as the flea image.
visited(bool): True to add an X to indicate which squares have been visited.
coordinates(bool): True to add coordinates to squares.
hide_grid(bool): True to hide the grid lines.
"""
self.screen = screen
self.num_rows = num_rows
self.num_cols = num_cols
self.flea_class = flea_class
self.num_fleas = num_fleas
self.flea_rows, self.flea_cols = self.initialize_flea_locs(flea_rows, flea_cols)
self.init_directions = self.initialize_flea_directions(init_directions)
self.square_colors = self.initialize_square_colors(square_colors)
self.image = image
self.visited = visited
self.coordinates = coordinates
self.hide_grid = hide_grid
self.squares = pygame.sprite.Group()
self.board = []
# Initialize squares on board
for row in range(self.num_rows):
row_squares = []
for col in range(self.num_cols):
square = Square(self,
row,
col,
self.flea_class.num_colors,
self.square_colors[row][col],
self.flea_class.cycle_size,
self.flea_class.color_map,
self.visited,
self.coordinates)
self.squares.add(square)
row_squares.append(square)
self.board.append(row_squares)
# Initialize fleas (first is centered, others are random)
self.fleas = pygame.sprite.Group()
for i in range(self.num_fleas):
self.fleas.add(self.flea_class(self,
self.flea_rows[i],
self.flea_cols[i],
self.init_directions[i],
self.image))
def initialize_flea_locs(self, flea_rows, flea_cols):
"""Determines the initial rows and columns of the fleas.
Arguments:
flea_rows(list): The initial rows of the fleas.
(None to start in the center vertically.
Unspecified fleas will be placed randomly.)
flea_cols(list): The initial columns of the fleas.
(None to start in the center horizontally.
Unspecified fleas will be placed randomly.)
Returns:
A tuple of lists with the first list containing the
initial rows of the fleas and the second list containing
the initial columns of the fleas.
"""
# Replace None with center
flea_rows = [flea_row if flea_row is not None else self.num_rows // 2 for flea_row in flea_rows]
flea_cols = [flea_col if flea_col is not None else self.num_cols // 2 for flea_col in flea_cols]
# Replace negative with positive
flea_rows = [flea_row if flea_row >= 0 else self.num_rows + flea_row for flea_row in flea_rows]
flea_cols = [flea_col if flea_col >= 0 else self.num_cols + flea_col for flea_col in flea_cols]
# Fill in remaining fleas with random
flea_rows += [random.randint(0, self.num_rows - 1)] * (self.num_fleas - len(flea_rows))
flea_cols += [random.randint(0, self.num_cols - 1)] * (self.num_fleas - len(flea_cols))
return flea_rows, flea_cols
def initialize_flea_directions(self, init_directions):
"""Determines the initial directions of the fleas.
Arguments:
init_directions(list): The initial directions of the fleas.
(Uspecified fleas will start facing up.)
Returns:
A list of strings containing the initial directions
of the fleas.
"""
init_directions += ['up'] * (self.num_fleas - len(init_directions))
return init_directions
def initialize_square_colors(self, square_colors):
"""Determine the initial square colors.
Arguments:
square_colors(list): Initial configuration of the colors of the squares.
(list of list of ints representing square colors.)
If None, all squares are initialized to color 0.
Returns:
A list of lists containing the initial colors of all
squares on the board.
"""
if square_colors is None:
square_colors = [[0] * self.num_cols] * self.num_rows
return square_colors
def get_square(self, row, col):
"""Gets the Square in a given row and column.
Arguments:
row(int): The row number.
col(int): The column number.
Returns:
The Square in the provided row and column.
"""
return self.board[row][col]
def rotate_fleas(self):
"""Rotates all Fleas."""
for flea in self.fleas.sprites():
flea.rotate()
def change_square_colors(self):
"""Changes the color of the Squares under the Fleas."""
for flea in self.fleas.sprites():
flea.square.change_color()
def move_fleas(self):
"""Moves all Fleas."""
for flea in self.fleas.sprites():
flea.move()
def draw_grid(self):
"""Draws a grid of lines to visualize separate the Squares."""
# Draw horizontal lines
for row in range(self.num_rows + 1):
left = row_column_to_pixels(row, 0)
right = row_column_to_pixels(row, self.num_cols)
pygame.draw.line(self.screen, COLOR_MAP['gray'], left, right)
# Draw vertical lines
for col in range(self.num_cols + 1):
top = row_column_to_pixels(0, col)
bottom = row_column_to_pixels(self.num_rows, col)
pygame.draw.line(self.screen, COLOR_MAP['gray'], top, bottom)
def draw(self):
"""Draws the Board including the Squares, grid, and Fleas."""
self.squares.draw(self.screen)
if not self.hide_grid:
self.draw_grid()
self.fleas.draw(self.screen)
pygame.display.flip()
|
647fc365d85cfbd23b7a576c16a59f72507018e5 | glareprotector/glare | /my_lists.py | 8,619 | 3.90625 | 4 | class my_list(list):
@classmethod
def get_class(cls):
return cls
def __repr__(self):
ans = ''
for item in self:
ans = ans + repr(item) + '\n'
return ans
# NOTE: think about how this should be organized when i have time. maybe have a class that pairs an object with the kind of list that holds it
def apply_feature(self, f, cls = self.get_class()):
"""
returns my_list or child class of it, where each element is f applied to each element as a whole
f should either return single_value_object or raise exception. here, item isn't added if exception raised. elsewhere, entire function raises that exception
"""
ans = cls()
for item in self:
candidate = f.generate(item)
try:
candidate.get_value()
except my_exceptions.NoFxnValueException:
pass
else:
ans.append(candidate)
return ans
def apply_feature_no_catch(self, f, cls = self.get_class()):
ans = cls()
for item in self:
candidate = f.generate(item)
candidate.get_value()
return ans
# note: to be safe, when creating a my_list or child class of it and passing in an argument, always use basic list, or a parent_class object at least
class ordered_object(object):
def __lt__(self, other):
pass
def __gt__(self, other):
pass
def __eq__(self, other):
pass
class base_single_ordinal_ordered_object(ordered_object):
"""
ordered_object where the comparison is based on attribute that can be retrieved with get_ordinal member function
"""
def get_ordinal(self):
pass
def __lt__(self, other):
return self.get_ordinal() < other.get_ordinal()
def __gt__(self, other):
return self.get_ordinal() > other.get_ordinal()
def __eq__(self, other):
return self.get_ordinal() == other.get_ordinal()
class base_single_value_object(object):
def get_value(self):
pass
def set_value(self, val):
pass
class no_value_object(base_single_value_object):
def __init__(self):
pass
def get_value(self):
raise my_exceptions.NoFxnValueException
class single_value_object(base_single_value_object):
def __init__(self, val):
self.val = val
def get_value(self):
return self.val
def set_value(self, val):
self.val = val
class base_single_ordinal_single_value_ordered_object(base_ordinal_ordered_object, base_single_value_object):
pass
class single_ordinal_single_value_ordered_object(base_single_ordinal_single_value_ordered_object, single_value_object):
def __init__(self, ordinal, val):
self.ordinal = ordinal
single_value_object.__init__(self, val)
def get_ordinal(self):
return self.ordinal
class ordered_interval(ordered_object):
def contains(self, item):
return item.get_ordinal() >= self.low and item.get_ordinal() < self.high
def __init__(self, low, high):
self.low = low
self.high = high
def __lt__(self, other):
return self.low < other.low
def __gt__(self, other):
return self.low < other.low
def __repr__(self):
return '('+repr(self.low)+'/'+repr(self.high)+')'
class ordinal_list(my_list):
"""
each element is an ordered_object, which are just comparable objects. comparison might be done based on objects with get_ordinals() function, but doesn't have to be
"""
def __iter__(self):
self.sort()
return self
class single_ordinal_ordinal_list(my_list):
"""
holds items where the ordinal comparison is based on single attribute retrieved with get_ordinals
"""
def get_ordinals(self):
ans = ordered_list()
for item in self:
ans.append(item.get_ordinal())
return ans
class bucketed_list(my_list):
"""
list where each element is a single_value_object, and get_value() returns a iterable
"""
pass
class bucketed_ordinal_list(ordinal_list, bucketed_list):
"""
now, each element is also a single_ordinal element, and the ordinal is an interval. could make parent more general classes, but i'm not going to use them
"""
@classmethod
def init_from_intervals_and_ordinal_list(cls, intervals, l):
"""
assumes l is a ordinal_list. so l might be
"""
ans = list()
for interval in intervals:
temp = my_list()
for item in l:
if interval.contains(item):
temp.append(item)
ans.append(single_ordinal_single_value_ordered_object(interval, temp))
return cls(ans)
@classmethod
def init_from_homo_my_list_list(cls, hll):
"""
takes in homo_my_list_list, returns bucketed_ordinal_list, where each element is single_ordinal, and single_valued. don't have a specific class for this type, but could, if there is a function that requires this type. but could also keep track mentally of what specializing of the class this actually returns
"""
for in hll.get_ordinals():
temp = my_list()
# NOTE: didn't think thorugh my_list_list yet
class my_list_list(my_list):
def apply_feature_vertical(self, f):
"""
returns new my_list_list with f applied to each list
"""
ans = my_list_list()
for l in self:
ans.append(f.generate(l))
return ans
class my_list_ordinal_list(my_list_list):
pass
class homo_my_list_list(my_list_list):
"""
all the ordinals in the lists are the same
unlike my_list_list, this requires that each element be a single_ordinal_ordered_object.
"""
def get_member_ordinals(self):
try:
return self[0].get_ordinals()
except IndexError:
raise ValueError('homo_my_list_ordinal_list is empty or the lists contained are not single_ordinal_ordered_objects, has no ordinals')
def get_horizontal_iter(self):
"""
iterates through each list and return a my_list of the columns
"""
# create iter instance, and keep calling it, putting results into a my_list
horizontal_iters = [iter(l) for l in self]
import itertools
column_tuple_iter = itertools.izip(horizontal_iters)
for column_tuple, ordinal in itertools.izip(column_tuple_iter, self.get_member_ordinals()):
yield single_ordinal_single_value_ordered_object(ordinal, my_list(column_tuple))
class homo_my_list_interval_list(homo_my_list_list):
"""
a homo_my_list_list where the member ordinals are intervals
"""
@classmethod
def init_from_intervals_and_my_list_ordinal_list(cls, intervals, ll):
"""
creates homo list of lists by bucketizing each list, so that each list is single_ordinal_single_value and the value is a bucket
ll is a parent class, so ans is parent class, so init call is safe(i think)
"""
def f(l):
return bucketed_ordinal_list.init_from_intervals_and_ordinal_list(intervals, l)
ans = ll.apply_f_vertical(f)
return cls.(ans)
# same as regular dictionary, except that key and value type are specified at init
class IO_dict(dict):
def __init__(self, key_cls, val_cls, data = {}):
self.key_cls = key_cls
self.val_cls = val_cls
dict.__init__(self, data)
@classmethod
def init_from_str(cls, key_cls, val_cls, the_string):
#assume that keys are on their own line, and the line begins with $$KEY$$
m = {}
s = the_string.split('\n')
i = 0
key_str = s[0].strip().split('|')[0]
assert key_str == '$$KEY$$'
pdb.set_trace()
while i < len(s):
if s[i].strip().split('|')[0] == '$$KEY$$':
key_str = s[i].strip().split('|')[1]
key = init_from_str(key_cls, key_str)
val_str = ''
else:
val_str = val_str + s[i]
if i == len(s)-1 or s[i+1].strip().split('|')[0] == '$$KEY$$':
val = init_from_str(val_cls, val_str)
m[key] = val
i += 1
return cls(key_cls, val_cls, m)
def __str__(self):
ans = ''
for key in self:
ans = ans + '$$KEY$$' + '|' + str(key) + '\n'
ans = ans + str(self[key]) + '\n'
return ans
|
b6830ff43c0f5203e8c77a87a73b939dd51d761b | AnushkaZ44/SDP-Task-1 | /Gross salary.py | 140 | 3.703125 | 4 | BS= float(input("Enter Basic Salary :"))
TA = BS * 0.4;
DA = BS * 0.2;
HRA = BS * 0.3;
GS = BS + DA + HRA + TA;
print('Gross Salary = ',GS)
|
8aa017212b91c72541f1a7b1117f0c776745e255 | darkhorse1998/100-Days-Of-Self-Customised-Data-Science-Helper-Modules | /code/Day_3/skewness.py | 5,503 | 3.71875 | 4 | import pandas as pd
import numpy as np
def skew_stats(df_col):
"""
Input: Pandas Series Data format (single column)
Output: void type
Prints: skew_tye, skewness, comment
"""
try:
skew = df_col.skew()
if skew>0:
if skew <= 0.5:
skew_tye = 'Approximately Normal'
skewness = skew
comment = "Can be considered as Normal Distribution"
elif skew < 1:
skew_tye = 'Positive'
skewness = skew
comment = "Moderately Skewed"
else:
skew_tye = 'Positive'
skewness = skew
comment = "Highly Skewed"
elif skew<0:
if skew >= -0.5:
skew_tye = 'Approximately Normal'
skewness = skew
comment = "Can be considered as Normal Distribution"
elif skew > -1:
skew_tye = 'Negative'
skewness = skew
comment = "Moderately Skewed"
else:
skew_tye = 'Negative'
skewness = skew
comment = "Highly Skewed"
else:
skew_tye = 'Normal'
skewness = skew
comment = "Perfect Normal Distribution"
print("Skew Type --> {}".format(skew_tye))
print("Skewness --> {}".format(skewness))
print("Comments --> {}".format(comment))
pct_max_occur = list(df_col.value_counts(normalize=True))[0]
max_occur = list(df_col.value_counts().index)[0]
if pct_max_occur > 0.80:
print(f"{df_col} :: Entry : {max_occur} --> {pct_max_occur*100}%")
print("Standard Deviation --> {}".format(df_col.values.std()))
except Exception as e:
print(e)
print("This function takes a single Pandas Series column.")
def transform(df_col,details=False):
"""
Input: df_col --> Pandas Series Data
details --> Default : False, if True returns Details of all Transformations
Output: Numpy Array containing the Transformed Data
"""
p_skew_t = {
0: lambda x: np.log(x),
1: lambda x: np.sqrt(x),
2: lambda x: np.cbrt(x)
}
n_skew_t = {
0: lambda x: np.square(x),
1: lambda x: np.cube(x)
}
diff = []
try:
initial_skew = df_col.skew()
print(f"Initial Skewness --> {initial_skew}")
if initial_skew > 0:
Transformations = [
"Logarithmic Transformation",
"Square Root Transformation",
"Cube Root Transformation"
]
t_log_skew = np.log(df_col).skew()
t_sqrt_skew = np.sqrt(df_col).skew()
t_cbrt_skew = np.cbrt(df_col).skew()
if t_log_skew < initial_skew and t_log_skew > 0:
diff.append(initial_skew-t_log_skew)
else:
diff.append(float('-inf'))
if t_sqrt_skew < initial_skew and t_sqrt_skew > 0:
diff.append(initial_skew-t_sqrt_skew)
else:
diff.append(float('-inf'))
if t_cbrt_skew < initial_skew and t_cbrt_skew > 0:
diff.append(initial_skew-t_cbrt_skew)
else:
diff.append(float('-inf'))
max_diff = max(diff)
max_diff_index= np.argmax(diff)
if details:
print("Logarithmic Transformation Skewness --> {}".format(t_log_skew))
print("Square Root Transformation Skewness --> {}".format(t_sqrt_skew))
print("Cube Root Transformation Skewness --> {}".format(t_cbrt_skew))
print("Transformation Completed...")
print("Transformation Used --> {}".format(Transformations[max_diff_index]))
print("Skewness improved by --> {}".format(max_diff))
return p_skew_t[max_diff_index](df_col)
elif initial_skew < 0:
Transformations = [
"Square Transformation",
"Cube Transformation"
]
t_sq_skew = np.square(df_col)
t_cu_skew = np.cube(df_col)
if t_sq_skew > initial_skew and t_log_skew < 0:
diff.append(abs(initial_skew - t_sq_skew))
else:
diff.append(float('-inf'))
if t_cu_skew > initial_skew and t_sqrt_skew < 0:
diff.append(abs(initial_skew - t_cu_skew))
else:
diff.append(float('-inf'))
max_diff = max(diff)
max_diff_index= np.argmax(diff)
if details:
print("Square Transformation Skewness --> {}".format(t_sq_skew))
print("Cube Transformation Skewness --> {}".format(t_cu_skew))
print("Transformation Completed...")
print("Transformation Used --> {}".format(Transformations[max_diff_index]))
print("Skewness improved by --> {}".format(max_diff))
return n_skew_t[max_diff_index](df_col)
else:
diff.append(0)
print("No Transformation Required.")
except Exception as e:
print(e)
print("This function takes a single Pandas Series column.")
# def box_cox(df_col):
#
# try:
# skewness = df_col.skew()
# box_cox_range = np.arange(-5,5,0.001)
except Exception as e:
print(e)
print("This function takes a single Pandas Series column.")
|
352995fc9653e83111180dcaba567b53ea0f649f | liyingliincsvw/test | /project C.py | 1,643 | 3.546875 | 4 | # -*- coding: utf-8 -*-
from sklearn.cluster import KMeans
from sklearn import preprocessing
import pandas as pd
import numpy as np
data = pd.read_csv('CarPrice_Assignment.csv', encoding='gbk')
#print(df1)
d = pd.read_excel('Data_Dictionary_carprices.xlsx')
df = pd.DataFrame(data)
aa = []
aa = list(df.columns)
print(aa)
train_x = data[aa]
# LabelEncoder
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
encoder_list = ['CarName','fueltype','aspiration','doornumber','carbody','drivewheel','enginelocation','enginetype','cylindernumber','fuelsystem']
for item in encoder_list:
train_x[item] = le.fit_transform(train_x[item])
# 规范化到 [0,1] 空间
min_max_scaler=preprocessing.MinMaxScaler()
train_x=min_max_scaler.fit_transform(train_x)
pd.DataFrame(train_x).to_csv('temp.csv', index=False)
#print(train_x)
### 使用KMeans聚类
kmeans = KMeans(n_clusters=7)
kmeans.fit(train_x)
predict_y = kmeans.predict(train_x)
# 合并聚类结果,插入到原数据中
result = pd.concat((data,pd.DataFrame(predict_y)),axis=1)
result.rename({0:u'Kmeans result'},axis=1,inplace=True)
print(result)
# 将结果导出到CSV文件中
result.to_csv("CarPrice_Assignment_result.csv",index=False)
"""
# K-Means 手肘法:统计不同K取值的误差平方和
import matplotlib.pyplot as plt
sse = []
for k in range(1, 20):
# kmeans算法
kmeans = KMeans(n_clusters=k)
kmeans.fit(train_x)
#计算inertia簇内误差平方和
sse.append(kmeans.inertia_)
x = range(1, 20)
plt.xlabel('K')
plt.ylabel('SSE')
plt.plot(x, sse, 'o-')
plt.show()
""" |
bd423b580d1f126737fe06dcadbecd35ca5e3e59 | SruthiSudhakar/DLHW1 | /1_cs231n/cs231n/classifiers/softmax.py | 2,599 | 3.546875 | 4 | import numpy as np
from random import shuffle
import pdb
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs:
- W: C x D array of weights
- X: D x N array of data. Data are D-dimensional columns
- y: 1-dimensional array of length N with labels 0...K-1, for K classes
- reg: (float) regularization strength
Returns:
a tuple of:
- loss as single float
- gradient with respect to weights W, an array of same size as W
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using no explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
epsilon = 1e-9
predictions = np.dot(W,X)
predictions -= np.amax(predictions,axis=0)
p = np.exp(predictions)
sums = np.sum(p, axis=0)
all_probabilities = p/(sums)
correct_probabilities = all_probabilities[y,np.arange(len(y))]
regularizer = 0.5*reg*np.sum(W*W) #0.5 to account for gradient overflow/underflow
loss = -np.sum(np.log(correct_probabilities + epsilon))/X.shape[1] + regularizer
dlds = all_probabilities
dlds[y,range(len(y))] -= 1
dlds/=len(y)
dW = np.dot(dlds,X.T) + reg*W
'''print('predictions: ',np.argwhere(np.isnan(predictions)))
print('p:',np.argwhere(np.isnan(p)))
print('sums: ',np.argwhere(sums==0))
print('dlds: ',np.argwhere(np.isnan(dlds)))
print('correct_probabilities',correct_probabilities)
print('predictions',predictions)
print('p',p)
print('sums',sums)
print('all_probabilities',all_probabilities)
print('correct_probabilities',correct_probabilities)
print('loss', loss)
print('dlds-1: ',dlds, np.argwhere(np.isnan(dlds)))
print('dlds/n: ',dlds,np.argwhere(np.isnan(dlds)))
print('reg*W: ',reg*W, np.argwhere(np.isnan(reg*W)))
print('XT: ',X.T)
print('dlds dot XT: ',np.dot(dlds,X.T), np.argwhere(np.isnan(np.dot(dlds,X.T))))
print('dw: ',dW, np.argwhere(np.isnan(np.dot(dlds,X.T))))'''
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
|
016b921a2195604125f98d94315328dea06d5c6c | pilino1234/AdventOfCode2015 | /5/Day5.py | 930 | 3.71875 | 4 | from itertools import groupby
def is_nice(string):
if has_vowels(string, 3):
if has_rep_letter(string, 2):
if has_no_bad_string(string):
return True
return False
def has_vowels(string, number):
return sum(map(string.count, "aeiou")) >= number
def has_rep_letter(string, number):
for letter, group in groupby(string):
if len(list(group)) >= number:
return True
return False
def has_no_bad_string(string):
bad_list = ["ab", "cd", "pq", "xy"]
return not any(bad_string in string for bad_string in bad_list)
if __name__ == "__main__":
print(is_nice("ugknbfddgicrmopn"))
print(is_nice("aaa"))
print(is_nice("jchzalrnumimnmhp"))
print(is_nice("haegwjzuvuyypxyu"))
print(is_nice("dvszwmarrgswjxmb"))
with open("Day5-input.txt") as file:
lines = file.read().splitlines()
print(sum(map(is_nice, lines)))
|
c398458e39a43152c60f040d0500246e3d9d8cbd | pilino1234/AdventOfCode2015 | /1/day1-2.py | 260 | 3.53125 | 4 | moves = {"(": 1, ")": -1}
def move(filename):
floor = 0
with open(filename) as file:
for pos, i in enumerate(file.read()):
floor += moves[i]
if floor < 0:
return pos + 1
print(move("day1-1-input.txt"))
|
b5c48a38649438e70f5e61fb800022584835f24e | rbk2145/DataScience | /010_Merging DataFrames with pandas/2_Concatenating data/2_Appending & concatenating DataFrames.py | 1,292 | 3.984375 | 4 | ####Appending DataFrames with ignore_index
# Add 'year' column to names_1881 & names_1981
names_1881['year'] = 1881
names_1981['year'] = 1981
# Append names_1981 after names_1881 with ignore_index=True: combined_names
combined_names = names_1881.append(names_1981, ignore_index=True)
# Print shapes of names_1981, names_1881, and combined_names
print(names_1981.shape)
print(names_1881.shape)
print(combined_names.shape)
# Print all rows that contain the name 'Morgan'
print(combined_names.loc[combined_names['name']=='Morgan'])
####Concatenating pandas DataFrames along column axis
# Concatenate weather_max and weather_mean horizontally: weather
weather = pd.concat([weather_max, weather_mean], axis=1)
# Print weather
print(weather)
####Reading multiple files to build a DataFrame
for medal in medal_types:
# Create the file name: file_name
file_name = "%s_top5.csv" % medal
# Create list of column names: columns
columns = ['Country', medal]
# Read file_name into a DataFrame: df
medal_df = pd.read_csv(file_name, header=0, index_col='Country', names=columns)
# Append medal_df to medals
medals.append(medal_df)
# Concatenate medals horizontally: medals
medals = pd.concat(medals, axis='columns')
# Print medals
print(medals)
####
|
d5d0940641384b80a06069ef0b9d54491c807328 | rbk2145/DataScience | /010_Merging DataFrames with pandas/3_Merging data/2_Ordered merges.py | 897 | 3.671875 | 4 | #####Using merge_ordered()
# Perform the first ordered merge: tx_weather
tx_weather = pd.merge_ordered(austin, houston)
# Print tx_weather
print(tx_weather)
# Perform the second ordered merge: tx_weather_suff
tx_weather_suff = pd.merge_ordered(austin, houston, on='date', suffixes=['_aus', '_hus'])
# Print tx_weather_suff
print(tx_weather_suff)
# Perform the third ordered merge: tx_weather_ffill
tx_weather_ffill = pd.merge_ordered(austin, houston, on='date', fill_method='ffill', suffixes=['_aus', '_hus'])
# Print tx_weather_ffill
print(tx_weather_ffill)
####Using merge_asof()
# Merge auto and oil: merged
merged = pd.merge_asof(auto, oil, left_on='yr', right_on='Date')
# Print the tail of merged
print(merged.tail())
# Resample merged: yearly
yearly = merged.resample('A',on='Date')[['mpg','Price']].mean()
# Print yearly
print(yearly)
# Print yearly.corr()
print(yearly.corr())
|
b2eb51f1c07dc6b03bd49499e392191e4578a2ed | rbk2145/DataScience | /9_Manipulating DataFrames with pandas/2_Advanced indexing/1_Index objects and labeled data.py | 814 | 4.4375 | 4 | ####Index values and names
sales.index = range(len(sales))
####Changing index of a DataFrame
# Create the list of new indexes: new_idx
new_idx = [month.upper() for month in sales.index]
# Assign new_idx to sales.index
sales.index = new_idx
# Print the sales DataFrame
print(sales)
######Changing index name labels
# Assign the string 'MONTHS' to sales.index.name
sales.index.name = 'MONTHS'
# Print the sales DataFrame
print(sales)
# Assign the string 'PRODUCTS' to sales.columns.name
sales.columns.name = 'PRODUCTS'
# Print the sales dataframe again
print(sales)
####Building an index, then a DataFrame
# Generate the list of months: months
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
# Assign months to sales.index
sales.index = months
# Print the modified sales DataFrame
print(sales)
|
8bb960dd2df317cd9e7fbb3bfb96b6313995e11d | weiteli/leetcode2018-19 | /LC257.py | 766 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
self.res = []
self.DFS(root, "")
return self.res
def DFS(self, root, s):
if root == None:
return
s = s + str(root.val)
if root.left == None and root.right == None:
# it's a leaf node
self.res.append(s)
else:
s = s + "->"
self.DFS(root.left, s)
self.DFS(root.right, s)
|
b05c9ea0da1f1562bece1f4d881a054b0f4e97df | weiteli/leetcode2018-19 | /LC515.py | 1,546 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
res = []
queue = [(root, 1)]
#BFS
prev_height = 1
tmp_max = float('-inf')
while len(queue) != 0:
q, cur_height = queue.pop(0)
if q.left != None:
queue.append((q.left, cur_height+1))
if q.right != None:
queue.append((q.right,cur_height+1))
if cur_height > prev_height:
# Change height
res.append(tmp_max)
tmp_max = q.val
prev_height = cur_height
else:
if q.val > tmp_max:
tmp_max = q.val
res.append(tmp_max)
return res
def largestValues(self, root):
self.ans = []
self.DFS(root, 0)
return self.ans
def DFS(self, root, level):
if root == None:
return
if len(self.ans) == level:
# First time visit
self.ans.append(root.val)
else:
self.ans[level] = max(self.ans[level], root.val)
self.DFS(root.left, level+1)
self.DFS(root.right, level+1)
|
c41f102a86b292fc338d6c7f3bbe689f02151f1c | davidthaler/arboretum | /arboretum/forest.py | 6,303 | 3.53125 | 4 | '''
Class Forest implements a random forest using the trees from tree.py.
author: David Thaler
date: September 2017
'''
import numpy as np
from . import tree
from .base import BaseModel
class Forest(BaseModel):
'''
Class Forest implements random forest classification and regression
models using trees from arboretum.tree.
'''
estimator_params = ['max_features', 'min_leaf', 'max_depth']
def __init__(self, base_estimator, n_trees, max_features, min_leaf, max_depth):
self.base_estimator = base_estimator
self.n_trees = n_trees
self.max_features = max_features
self.min_leaf = min_leaf
self.max_depth = max_depth
def _get_maxf(self):
'''Get adjusted max_features value. Overridden in RFClassifier.'''
return self.max_features
def fit(self, x, y, weights=None):
'''
Fits a random forest using tree.Tree to the given data.
Also sets the oob_decision_function_ attribute.
Args:
x: Training data features; ndarray of shape (n_samples, n_features)
y: Training set labels; shape is (n_samples, )
weights: sample weights; shape is (n_samples, )
default is None for equal weights/unweighted
Returns:
Returns self, the fitted estimator
'''
if weights is None:
weights = np.ones_like(y)
n = len(y)
self.n_features_ = x.shape[1]
self.estimators_ = []
est_params = {ep:getattr(self, ep) for ep in self.estimator_params}
est_params['max_features'] = self._get_maxf()
all_idx = np.arange(n)
oob_ct = np.zeros(n)
oob_prob = np.zeros(n)
for k in range(self.n_trees):
model = self.base_estimator.__class__(**est_params)
boot_idx = np.random.randint(n, size=n)
oob_idx = np.setdiff1d(all_idx, boot_idx)
model.fit(x[boot_idx], y[boot_idx], weights=weights[boot_idx])
self.estimators_.append(model)
oob_ct[oob_idx] += 1
oob_prob[oob_idx] += model.decision_function(x[oob_idx])
# TODO: check for NaN
self.oob_decision_function_ = oob_prob / oob_ct
return self
def decision_function(self, x):
'''
Returns the decision function for each row in x. In regression trees,
this is an estimate. In classification trees, it is a probability.
In either case, it is the average over the trees in this forest.
Args:
x: Test data to predict; ndarray of shape (n_samples, n_features)
Returns:
array (n_samples,) decision function for each row in x
'''
self._predict_check(x)
dv = np.zeros(len(x))
for model in self.estimators_:
dv += model.decision_function(x)
return dv / self.n_trees
class RFRegressor(Forest):
'''
RFClassifier implements a random forest regression model using an
arboretum.tree.RegressionTree for its basis functions.
This is a single-output model that minimizes mse.
Args:
n_trees: (int) number of trees to fit
max_features: controls number of features to try at each split
If float, should be in (0, 1]; use int(n_features * max_features)
If int, use that number of features. If None, use all features.
min_leaf: minimum number of samples for a leaf; default 5
max_depth: (int) the maximum depth of the trees grown.
Default of None for no depth limit.
'''
def __init__(self, n_trees=30, max_features=None, min_leaf=5, max_depth=None):
base_estimator = tree.RegressionTree()
super().__init__(base_estimator, n_trees=n_trees,
max_features=max_features, min_leaf=min_leaf,
max_depth=max_depth)
def predict(self, x):
'''
Estimates target for each row in x.
Args:
x: Test data to predict; ndarray of shape (n_samples, n_features)
Returns:
array (n_samples,) of estimates of target for each row in x
'''
return self.decision_function(x)
class RFClassifier(Forest):
'''
RFClassifier implements a random forest classifier using an
arboretum.tree.ClassificationTree for its basis functions.
This is a single-output, binary classifier, using gini impurity.
Args:
n_trees: (int) number of trees to fit
max_features: controls number of features to try at each split
If float (0, 1]; use int(n_features * max_features)
If int, use that number of features.
If None, use np.round(np.sqrt(n_features)).
min_leaf: minimum number of samples for a leaf; default 1
max_depth: (int) the maximum depth of the trees grown.
Default of None for no depth limit.
'''
def __init__(self, n_trees=30, max_features=None, min_leaf=1, max_depth=None):
base_estimator = tree.ClassificationTree()
super().__init__(base_estimator, n_trees=n_trees,
max_features=max_features, min_leaf=min_leaf,
max_depth=max_depth)
def _get_maxf(self):
'''
Get the adjusted value for max_features.
NB: self.n_features_ has to be set before calling this.
'''
if self.max_features is None:
return int(np.round(np.sqrt(self.n_features_)))
return self.max_features
def predict_proba(self, x):
'''
Predicts probabilities of the positive class for each row in x.
Args:
x: Test data to predict; ndarray of shape (n_samples, n_features)
Returns:
array of shape (n_samples,) of probabilities for class 1.
'''
return self.decision_function(x)
def predict(self, x):
'''
Predicts class membership for the rows in x. Predicted class is the one
with the higest mean probability across the trees.
Args:
x: Test data to predict; ndarray of shape (n_samples, n_features)
Returns:
array of shape (n_samples, ) of class labels for each row
'''
return (self.predict_proba(x) > 0.5).astype(int)
|
4d66085eb9572ff519aaefb16281b587aac2cb1a | SVdeJong/day2 | /project_tip_calculator.py | 952 | 3.96875 | 4 | #If the bill was $150.00, split between 5 people, with 12% tip.
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
#Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.💪
#HINT 1: https://www.google.com/search?q=how+to+round+number+to+2+decimal+places+python&oq=how+to+round+number+to+2+decimal
#HINT 2: https://www.kite.com/python/answers/how-to-limit-a-float-to-two-decimal-places-in-python
total_bill = input("Welcome to the tip calculator.\nWhat was the total bill? $")
tip = input("What percentage tip would you like to give? 10, 12, 15? ")
people = input("How many people to split the bill? ")
tip_float = (int(tip)/100) + 1
pay_per_person = (float(total_bill) / int(people)) * tip_float
limited_pay_per_person = round(pay_per_person, 2)
limited_pay_per_person = "{:.2f}".format(pay_per_person)
print(f"Each person should pay: ${limited_pay_per_person}")
|
fe541905e877fa7b24a95d6b8916e14896be514e | lalitkapoor112000/Python | /Character in name.py | 236 | 4.03125 | 4 | name,key=input("Enter your name and a character seperated by comma:").split(",")
print(f"Length of your name is {len(name.strip())}")
print(f"Hi {name} ,{key} is {name.lower().strip().count(key.lower().strip())} times in your name")
|
f932a3cdb88fa9c1735bb68c4f6684e6e1d12066 | lalitkapoor112000/Python | /Finding position of String in a name.py | 187 | 3.78125 | 4 | def pos(l,key):
for index,name in enumerate(l):
if key==name:
return index
else:
return -1
l=['Lalit','lalit']
print(pos(l,'lalit'))
|
20aee8962ae91f40d0edd2672d76e08476382e74 | lalitkapoor112000/Python | /Number Guessing Game Modified.py | 250 | 3.78125 | 4 | import random
num=random.randint(1,101)
x=int(input("Guess a number:"))
k=0
while x!=num:
if x>num:
print("Too high")
else:
print("Too Low")
x=int(input("Guess again:"))
k+=1
print(f"You Won,in {k} times")
|
2fb3f8899a33dc03d137260b9a03068282a8bb70 | lalitkapoor112000/Python | /List Comprehension Example.py | 142 | 3.78125 | 4 | l=[]
while 'q' not in l:
l.append(input("Enter string to list and enter q to exit:"))
l.remove("q")
l=[i[::-1] for i in l]
print(l)
|
7301647ec241cedae05a63daeffb6417f45dcc91 | lalitkapoor112000/Python | /Removing Data from list.py | 215 | 3.953125 | 4 | fruits=['apple','orange','grapes','mango','peach']
fruits.remove('orange')
print(fruits)
fruits.pop()
print(fruits)
del fruits[1]
print(fruits)
fruits.pop(1)
print(fruits)
for i in fruits:
print(i)
|
7b84e2c07f670b19006381635e712aacf14bc43e | lalitkapoor112000/Python | /List Squaring.py | 245 | 3.796875 | 4 | def listSquare(m):
sq=[]
m.remove('q')
for i in m:
sq.append(int(i)**2)
return sq
l=[]
i=0
while 'q' not in l:
l.append(input("Enter list elements and enter to stop:"))
print(listSquare(l))
|
0c37fdab26b134508e03c706c7833d5b73ba3896 | BryanCAlcorn/NumberGuesses | /Number Guesses.py | 2,652 | 4.09375 | 4 | import random;
# Rolls 1-50, and has user guess until they are correct.
def spinner():
spin = random.randint(1,50);
while(True):
Target = input('Pick a number(1-50): ');
if(Target > spin):
print 'Too high';
elif(Target < spin):
print 'Too low';
else:
print 'Correct!!';
again = raw_input("Would you like to play again?(Y/N) ");
spin = random.randint(1,50);
if(again == "n" or again == "N"):
break;
print "Good-Bye";
#Generates 2 Random coordinates, takes 2 input coordinates and checks if you
#guessed correctly. You have 20 Turns to guess correctly, enabling hints adds 15.
#Typing (99,99) tells you what the location is, but ends the game.
def HaS():
x = random.randint(1,10);
y = random.randint(1,10);
turn = 0;
hints = False;
print 'I bet you can not find me in 20 turns!'
print 'Type (50,50) to enable hints (costs 15 turns).';
print 'Type (99,99) to get the location (ends the game).';
#Infinite loop that breaks when the user uses 20 guesses, cheats, or wins.
while(True):
xCoord = input('What is your X-Coordinate(1-10)? ');
yCoord = input('What is your Y-Coordinate(1-10)? ');
turn += 1;
#Prints hint statements.
if(hints == True):
if(xCoord > x):
print 'X is too big';
if(xCoord < x):
print 'X is too small';
if(yCoord > y):
print 'Y is too big';
if(yCoord < y):
print 'Y is too small';
#Prints the coordinates, ends the game.
if(xCoord == 99 and yCoord == 99):
print 'X =',x,'Y =',y,'CHEATER!!';
AgainHaS();
break;
if(xCoord == x and yCoord == y):
print 'You found me!!';
AgainHaS();
break;
#Enables hints.
elif(xCoord == 50 and yCoord == 50):
hints = True;
print 'Hints Enabled +15 turns.';
turn += 14;
else:
print'Wrong spot';
#Gives the user a limited number of turns to guess in.
if(turn >= 20):
print 'Ok, I am in',x,',',y;
AgainHaS();
break;
#Algorithm for playing again.
def AgainHaS():
again = raw_input("Would you like to play again?(Y/N) ");
if(again == "y" or again == "Y"):
HaS();
elif(again == "n" or again == "N"):
print "Good-bye";
else:
print "Your statement was not recognized, please re-enter your request";
AgainHaS();
HaS();
|
c31cfdfc797c4f40d719d1ef28549059c291c76f | SandjayRJ28/Python | /Python Ep 03 Strings.py | 1,539 | 4.21875 | 4 | #Variablen defineren gaat heel makkelijk heeft het een naam en waarde het its done
Voor_naam = "Sandjay"
print(Voor_naam)
#Je kan stringe combineren met +
Achter_naam = "Jethoe"
print(Voor_naam + Achter_naam)
print("Hallo" + Voor_naam + "" + Achter_naam)
#Je kan functies gebruiken om je string aan te passen
zin = "Ik kan eindelijke een beetje Pyhton"
print(zin.upper())
print(zin.lower())
print(zin.capitalize())
print(zin.count("a"))
#De functies helpen on om de tekste een opmaak te geven om het op te slaan naar bestanden,Databases of om aan gebruikers te laten zien.
print("Hallo" + Voor_naam.capitalize() + " \n" + Achter_naam.capitalize())
#verschillende string oefeningen met tab voor autocomplete
print(Voor_naam + Achter_naam)
print("Hallo, " + Voor_naam + " " + Achter_naam)
#input geven via de console
V_naam = input("Vul hier jou naam is ")
A_naam = input("Vul hier jou Achternaam in ")
print("Hallo, " + V_naam.capitalize() + " " + A_naam.capitalize())
#String formatting
output = "Hallo, " + V_naam + " " + A_naam
output = "Hallo, {} {} ".format(V_naam, A_naam)
output = "Hallo, {0} {1} ".format(V_naam, A_naam)
#Deze formatting is alleen in Python 3 beschikbaar
output = f'Hallo, {V_naam} {A_naam}'
#String formatting Part 2
V2_naam = "Sandjay"
A2_naam = "Jethoe"
output = "Hallo, " + V2_naam + " " + A2_naam
output2 = "Hallo, {} {} ".format(V2_naam, A2_naam)
output3 = "Hallo, {0}, {1} ".format(V2_naam, A2_naam)
output4 = f'Hallo, {V2_naam} {A2_naam}'
print(output)
print(output2)
print(output3)
print(output4) |
183a316c248315e2fad1ece6eeeb2f53506bb770 | boogiedev/pair-programming-exercises | /andrei-aroosh/group_project/main.py | 733 | 3.8125 | 4 | from libs.map import *
class Character:
def __init__(self, name, cord):
self.name = name
self.cord = cord
def change_cord(self):
ui = input("Where would you like to move?: ")
if ui.lower() == "up":
self.cord=self.cord[0],self.cord[1]-1
elif ui.lower() == "down":
self.cord=self.cord[0],self.cord[1]+1
elif ui.lower() == "left":
self.cord=self.cord[0]-1,self.cord[1]
elif ui.lower() == "right":
self.cord=self.cord[0]+1,self.cord[1]
char = Character('Androosh', (0, 0))
game_map = Map(4, 4, 'X', char.cord)
game_map.show()
while True:
char.change_cord()
game_map.move_marker(char.cord)
game_map.show()
|
f471530103696bc3d847968fa6ba67f00b02617e | mobibridge/assingments | /test_fizzbuzz.py | 427 | 4 | 4 | import unittest
from fizz import fizz_buzz
class FizzBuzzTest(unittest.TestCase):
"""Testing FizzBuzzTest
"""
def test_returns_fizz_when_divisible__by_three(self):
"""Test return fizz when input is divisile
"""
self.assertEqual(fizz_buzz(3),"fizz")
def test_returns_buzz_when_divisible__by_five(self):
"""Test return buzz when input is divisile
"""
self.assertEqual(fizz_buzz(5),"buzz")
unittest.main()
|
a991555e799064d6a89f9c0c1cc460fcf41ce8ea | TazoFocus/UWF_2014_spring_COP3990C-2507 | /notebooks/scripts/cli.py | 664 | 4.21875 | 4 | # this scripts demonstrates the command line input
# this works under all os'es
# this allows us to interact with the system
import sys
# the argument list that is passed to the code is stored
# in a list called sys.argv
# this list is just like any list in python so you should treat it as such
cli_list = sys.argv
# how many elements is in the list?
print 'The length of my cli list is: ', len(cli_list)
# what is the list of arguments?
print 'Here is my list: ', cli_list
# what is the first element?
print 'this is the name of my python file: ', cli_list[0]
# how about the rest of the elements
for cli_element in cli_list[1:]:
print cli_element
|
870ba0cb86c6b9b3892a9df89066f3c5adc8e037 | ysguoqiang/abigproject | /python_socket_server/server.py | 654 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:server.py
import socket # 导入 socket 模块
s = socket.socket() # 创建 socket 对象
host = "127.0.0.1" #socket.gethostname() # 获取本地主机名
port = 12345 # 设置端口
s.bind((host, port)) # 绑定端口
s.listen(5) # 等待客户端连接
c,addr = s.accept() # 建立客户端连接
while True:
# print('连接地址:', addr)
val = c.recv(100)
if val:
print(val.decode())
c.send(val)
# c.send('欢迎访问菜鸟教程!'.encode())
# c.close() # 关闭连接 |
223976072a2bab6eca68dc1eed3de5d707703317 | sumit-jaswal/competitive_programming | /check_sum.py | 397 | 3.71875 | 4 | # Find the numbers in an array that add upto a specific value and return true else return false.
# Input : [4,7,1,-3,2], 6
# Output : ([4, 2], True)
def two_sum(list,k):
sum = []
for i in range(0,len(list)):
for j in range(0,i):
if(list[j]+list[i]==k):
sum += [list[j]]
sum += [list[i]]
if(len(sum)!=0):
return (sum,True)
else:
return False
print(two_sum([4,7,1,-3,2],6)) |
bee0307649c0eab9a8f0a1abdf48deddb9709d68 | 99sujeong/py-data | /python/tokenize.py | 362 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 24 21:13:09 2020
@author: Park
"""
from nltk.tokenize import word_tokenize
text = "I am actively lookin for Ph.D. students. and you are a Ph.D student."
print('=>', text); print()
print('=>', word_tokenize(text)); print()
from nltk.tag import pos_tag
x = word_tokenize(text)
print('=>', pos_tag(x))
|
2b9170d094bf3a1bd3a254aa8b7a9fa9e16f5cc0 | 99sujeong/py-data | /data/iris-ANN-simple.py | 951 | 3.578125 | 4 | from sklearn.datasets import load_iris
import pandas as pd
# iris데이터셋을 iris라는 변수에 저장
iris = load_iris()
# to excel... by Uchang
df = pd.DataFrame(data=iris['data'], columns = iris['feature_names'])
df.to_excel('iris.xlsx', index=False)
print(iris['data'][0:10])
X = iris['data']
y = iris['target']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y)
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
from sklearn.neural_network import MLPClassifier
mlp = MLPClassifier(hidden_layer_sizes=(10,10,10))
mlp.fit(X_train, y_train)
predictions = mlp.predict(X_test)
from sklearn.metrics import classification_report, confusion_matrix
print(confusion_matrix(y_test, predictions))
print(classification_report(y_test, predictions))
|
88453495020770a660950be174fbe255f1b6ec3b | 99sujeong/py-data | /python/201006.py | 1,151 | 3.59375 | 4 | #알고리즘
'''
n=int(input())
if (n%3==1):
print(n, "3의 배수가 아니다.")
else:
print(n, "3의 배수이다.")
m=352 # 거스름돈
#100원
m100=0
while m>=100:
m100 += 1
m-=100
print("100원 동전 =>", m100)
# 10원
m10 = 0
while m>=10:
m10 += 1
m-=10
print("10원 동전 =>", m10)
# 1원
m1 = 0
while m>0:
m1 += 1
m-=1
print("1원 동전 =>", m1)
# 80, 8, 1
m=352 # 거스름돈
# 80원
m80=0
while m>=80:
m80 += 1
m-=80
print("80원 동전 =>", m80)
# 8원
m8 = 0
while m>=8:
m8 += 1
m-=8
print("8원 동전 =>", m8)
# 1원
m1 = 0
while m>0:
m1 += 1
m-=1
print("1원 동전 =>", m1)
'''
# 검색, 정렬
ages = [17, 14, 18, 13, 19]
# 13?
key=13
found = False ##
position = 0
for i in range(len(ages)):
position+=1
if ages[i] == key:
found = True
print("Y", position,"번째")
break
if(not found):
print('N')
# 가장 나이가 많은 값
max= 0
for age in ages:
if age > max:
max = age
print(max)
# 정렬
ages.sort()
print(ages)
|
f68f8aaf53e834b5b3297a2852518edba06ebbe0 | denrahydnas/SL9_TreePy | /tree_while.py | 1,470 | 4.34375 | 4 | # Problem 1: Warm the oven
# Write a while loop that checks to see if the oven
# is 350 degrees. If it is, print "The oven is ready!"
# If it's not, increase current_oven_temp by 25 and print
# out the current temperature.
current_oven_temp = 75
# Solution 1 here
while current_oven_temp < 350:
print("The oven is at {} degrees".format(current_oven_temp))
current_oven_temp += 25
else:
print("The oven is ready!")
# Problem 2: Total and average
# Complete the following function so that it asks for
# numbers from the user until they enter 'q' to quit.
# When they quit, print out the list of numbers,
# the sum and the average of all of the numbers.
def total_and_average():
numbers = []
while True:
add = input("Please give me a number, or type 'q' to quit: ").lower()
if add == 'q':
break
try:
numbers.append(float(add))
except ValueError:
continue
print("You entered: ", numbers)
print("The total is: ", sum(numbers))
print("The average is: ", sum(numbers)/len(numbers))
total_and_average()
# Problem 3: Missbuzz
# Write a while loop that increments current by 1
# If the new number is divisible by 3, 5, or both,
# print out the number. Otherwise, skip it.
# Break out of the loop when current is equal to 101.
current = 1
# Solution 3 here
while current < 101:
if not current % 3 or current % 5 == 0:
print(current)
current += 1
|
78c6cd735ab26eabf91d6888118f9e5ec1320ccf | denrahydnas/SL9_TreePy | /tree_calc.py | 746 | 4.28125 | 4 | # Step 1
# Ask the user for their name and the year they were born.
name = input("What is your name? ")
ages = [25, 50, 75, 100]
from datetime import date
current_year = (date.today().year)
while True:
birth_year = input("What year were you born? ")
try:
birth_year = int(birth_year)
except ValueError:
continue
else:
break
current_age = current_year - birth_year
# Step 2
# Calculate and print the year they'll turn 25, 50, 75, and 100.
for age in ages:
if age > current_age:
print("Congrats, Sandy! You will be {} in {}.".format(age, (birth_year+age)))
# Step 3
# If they're already past any of these ages, skip them.
print("You will turn {} this calendar year.".format(current_age)) |
823bf53c272967e7b32ef32d2831a867d8996f2b | prabhus489/Python_Bestway | /Factorial_of_a_Number.py | 700 | 4.09375 | 4 | def fac_of_num():
global num
factor = 1
flag = True
while flag:
flag = False
try:
num = int(round(float(input("Enter the Number: "))))
if num == 0:
print("The Factorial of Zero is One")
flag = True
else:
if num < 0:
print("The Number should be Positive")
flag = True
except ValueError:
print("Enter a Valid Input")
flag = True
if num > 0:
for x in range(1, num + 1):
factor = factor * x
return factor
fac = fac_of_num()
print("The factorial of", num,"is",fac) |
528a622f441ed7ac306bc073548ebdf1e399271e | prabhus489/Python_Bestway | /Length_of_a_String.py | 509 | 4.34375 | 4 | def len_string():
length = 0
flag = 1
while flag:
flag = 0
try:
string = input("Enter the string: ")
if string.isspace()or string.isnumeric():
print("Enter a valid string")
flag = 1
except ValueError:
print("Enter a Valid input")
flag = 1
for x in string:
length += 1
return length
str_length = len_string()
print("The length of the string is: ", str_length) |
dca6907cca6ed9a0d94ba80a2ec3f49c6e16bd10 | PauloHMTeixeira/Tic-Tac-Toe-jogo-da-velha-. | /JogoDaVelha.py | 2,148 | 3.859375 | 4 | # Paulo Henrique Melo Teixeira e Pedro Henrique Bezerra Buarque de Paula
board = ['_'] * 9
def print_board():
print(board[0] + '|' + board[1] + '|' + board[2])
print(board[3] + '|' + board[4] + '|' + board[5])
print(board[6] + '|' + board[7] + '|' + board[8])
print_board()
contador = 0
while True:
x = input('Qual a jogada do jogador 1 (de 0 a 8)? ')
x = int(x)
if board[x] == 'X' or board[x] == 'O':
print_board()
print('Jogada inválida, tente novamente!')
else:
board[x] = 'X'
print_board()
if board[contador] == board[contador + 1] and board[contador + 2] == board[contador] and board[contador] == 'X' or board[contador] == 'O':
print('Você ganhou!')
break
elif board[contador] == board[contador + 3] and board[contador + 5] == board[contador] and board[contador] == 'X' or board[contador] == 'O':
print('Você ganhou!')
break
elif board[0] == board[4] and board[8] == board[0] and board[contador] == 'X' or board[contador] == 'O':
print('Você ganhou!')
elif board[2] == board[4] and board[6] == board[0] and board[contador] == 'X' or board[contador] == 'O':
print('Você ganhou!')
y = input('Qual a jogada do jogador 2 (de 0 a 8)? ')
y = int(y)
if board[y] == 'X' or board[y] == 'O':
print_board()
print('Jogada inválida, tente novamente!')
else:
board[y] = 'O'
print_board()
if board[contador] == board[contador + 1] and board[contador + 2] == board[contador] and board[contador] == 'X' or board[contador] == 'O':
print('Você ganhou!')
break
elif board[contador] == board[contador + 3] and board[contador + 5] == board[contador] and board[contador] == 'X' or board[contador] == 'O':
print('Você ganhou!')
break
elif board[0] == board[4] and board[8] == board[0] and board[contador] == 'X' or board[contador] == 'O':
print('Você ganhou!')
elif board[2] == board[4] and board[6] == board[0] and board[contador] == 'X' or board[contador] == 'O':
print('Você ganhou!')
|
03fe80d2380837c73c218a6f5c65df137499b3ca | williamnie2088/Data_structure_sample | /Stack/stack_string_reverse.py | 568 | 3.84375 | 4 | class Stack():
def __init__(object):
object.items = []
def push(object, item):
object.items.append(item)
def pop(object):
return object.items.pop()
def is_empty(object):
return object.items == []
def revert(stack, input_str):
for i in range (len(input_str)):
stack.push(input_str[i])
rev_str = ""
while not stack.is_empty():
rev_str += stack.pop()
return rev_str
stack = Stack()
input_word = input("Enter the word to reverse: ")
input_str = input_word
print(revert(stack, input_str))
|
5d29efc5569e4828d8d725a0d32bc8239ec3af6e | yangtau/algorithms-practice | /practice/weekly-contest-178/rank-teams-by-votes.py | 1,262 | 3.5 | 4 | '''
https://leetcode.com/problems/rank-teams-by-votes/
'''
class Solution:
def rankTeams(self, votes: [str]) -> str:
ranks = {c: [0]*len(votes[0])+[c] for c in votes[0]}
for vote in votes:
for i, c in enumerate(vote):
ranks[c][i] -= 1
return ''.join(sorted(ranks.keys(), key=ranks.get))
def rankTeams0(self, votes: [str]) -> str:
ranks = dict(map(lambda x: (x, [0]*len(votes[0])), votes[0]))
for vote in votes:
for i in range(len(vote)):
ranks[vote[i]][i] += 1
ranks = sorted(sorted(ranks.items()), reverse=True, key=lambda x: x[1])
# print(ranks)
return ''.join(k for k, v in ranks)
s = Solution()
# TEST CASE 1:
votes = ["ABC", "ACB", "ABC", "ACB", "ACB"]
res = "ACB"
print('expect:', res)
print('result:', s.rankTeams(votes))
# TEST CASE 2:
votes = ["WXYZ", "XYZW"]
res = "XWYZ"
print('expect:', res)
print('result:', s.rankTeams(votes))
# TEST CASE 3:
votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
res = "ZMNAGUEDSJYLBOPHRQICWFXTVK"
print('expect:', res)
print('result:', s.rankTeams(votes))
# TEST CASE 4:
votes = ["BCA", "CAB", "CBA", "ABC", "ACB", "BAC"]
res = "ABC"
print('expect:', res)
print('result:', s.rankTeams(votes))
|
0dfa3cb523658865490771059f6f825088505cdf | marlhakizi/Greetings | /timing.py | 617 | 3.96875 | 4 |
#function taking in 2 parameters hr and period and returns a meal recommendation
def mealrec(hr,period):
if period=='AM':
if hr>=5 and hr<=11:
return("Breakfast TIME!!")
else:
return("It's too early! Go TO BED!!")
elif period=="PM":
if hr==12 or hr<=3:
return("Lunch TIME!!")
if hr==4 or hr<=6:
return("Snack TIME!!")
if hr==7 or hr<=10:
return("Dinner TIME!!")
else:
return("It's too late, GO TO BED!!")
else:
return("Weird.., can't recognize input")
#print(mealrec(12,'PM')) |
8f70f9fe6fd173ff692a7ea76f3f3a4b79ec88ed | HelloYeew/helloyeew-computer-programming-i | /6310545566_Phawit_ex4/coffee_machine_2.py | 7,234 | 4.15625 | 4 | import sys
# function zone
def summary():
global water, milk, coffee_beans, disposable_cups, money
print("The coffee machine has:")
print(f"{water} of water")
print(f"{milk} of milk")
print(f"{coffee_beans} of coffee beans")
print(f"{disposable_cups} of disposable cups")
if money != 0:
print(f"${money} of money")
else:
print(f"{money} of money")
def ask_action():
print("Write action (buy, fill, take, remaining, exit):")
answer = str(input())
return answer
def buy():
global water, milk, coffee_beans, disposable_cups, money
print("What do you want to buy? 1 - espresso, 2 - espresso, 3 - cappuccino, back - to main menu:")
buy_coffee = input()
if buy_coffee == 1:
if water >= 250 and coffee_beans >= 16 and disposable_cups >= 1:
print("I have enough resources, making you a coffee!")
water -= 250
coffee_beans -= 16
money += 4
disposable_cups -= 1
else:
if water < 250 and coffee_beans < 16 and disposable_cups < 1:
print("Sorry, not enough water, coffee beans and disposable cups!")
elif water < 250 and coffee_beans < 16:
print("Sorry, not enough water and coffee beans!")
elif water < 250 and disposable_cups < 1:
print("Sorry, not enough water and disposable cups!")
elif coffee_beans < 16 and disposable_cups < 1:
print("Sorry, not enough coffee beans and disposable cups!")
elif water < 250:
print("Sorry, not enough water!")
elif coffee_beans < 16:
print("Sorry, not enough coffee beans!")
else:
print("Sorry, not enough disposable cups!")
elif buy_coffee == 2:
if water >= 350 and milk >= 75 and coffee_beans >= 20 and disposable_cups >= 1:
print("I have enough resources, making you a coffee!")
water -= 350
milk -= 75
coffee_beans -= 20
money += 7
disposable_cups -= 1
else:
# 1 + 4 + 6 + 4 = 15
if water < 350 and milk < 75 and coffee_beans < 20 and disposable_cups < 1:
print("Sorry, not enough water, milk, coffee beans and disposable cups!")
elif water < 350 and milk < 75 and coffee_beans < 20:
print("Sorry, not enough water, milk and coffee beans!")
elif water < 350 and milk < 75 and disposable_cups < 1:
print("Sorry, not enough water, milk and disposable cups!")
elif water < 350 and coffee_beans < 20 and disposable_cups < 1:
print("Sorry, not enough water, coffee beans and disposable cups!")
elif milk < 75 and coffee_beans < 20 and disposable_cups < 1:
print("Sorry, not enough milk, coffee beans and disposable cups!")
elif water < 350 and milk < 75:
print("Sorry, not enough water and milk!")
elif water < 350 and coffee_beans < 20:
print("Sorry, not enough water and coffee beans!")
elif water < 350 and disposable_cups < 1:
print("Sorry, not enough water and disposable cups!")
elif milk < 75 and coffee_beans < 20:
print("Sorry, not enough milk and coffee beans!")
elif milk < 75 and disposable_cups < 1:
print("Sorry, not enough milk and disposable cups!")
elif coffee_beans < 20 and disposable_cups < 1:
print("Sorry, not enough coffee beans and disposable cups!")
elif water < 350:
print("Sorry, not enough water!")
elif milk < 75:
print("Sorry, not enough milk!")
elif coffee_beans < 20:
print("Sorry, not enough coffee beans!")
else:
print("Sorry, not enough disposable cups!")
elif buy_coffee == 3:
if water >= 200 and milk >= 100 and coffee_beans >= 12 and disposable_cups >= 1:
print("I have enough resources, making you a coffee!")
water -= 200
milk -= 100
coffee_beans -= 12
money += 6
disposable_cups -= 1
else:
if water < 200 and milk < 100 and coffee_beans < 12 and disposable_cups < 1:
print("Sorry, not enough water, milk, coffee beans and disposable cups!")
elif water < 200 and milk < 100 and coffee_beans < 12:
print("Sorry, not enough water, milk and coffee beans!")
elif water < 200 and milk < 100 and disposable_cups < 1:
print("Sorry, not enough water, milk and disposable cups!")
elif water < 200 and coffee_beans < 12 and disposable_cups < 1:
print("Sorry, not enough water, coffee beans and disposable cups!")
elif milk < 100 and coffee_beans < 12 and disposable_cups < 1:
print("Sorry, not enough milk, coffee beans and disposable cups!")
elif water < 200 and milk < 100:
print("Sorry, not enough water and milk!")
elif water < 200 and coffee_beans < 12:
print("Sorry, not enough water and coffee beans!")
elif water < 200 and disposable_cups < 1:
print("Sorry, not enough water and disposable cups!")
elif milk < 100 and coffee_beans < 12:
print("Sorry, not enough milk and coffee beans!")
elif milk < 100 and disposable_cups < 1:
print("Sorry, not enough milk and disposable cups!")
elif coffee_beans < 12 and disposable_cups < 1:
print("Sorry, not enough coffee beans and disposable cups!")
elif water < 350:
print("Sorry, not enough water!")
elif milk < 75:
print("Sorry, not enough milk!")
elif coffee_beans < 12:
print("Sorry, not enough coffee beans!")
else:
print("Sorry, not enough disposable cups!")
else:
pass
def fill():
global water, milk, coffee_beans, disposable_cups
print("Write how many ml of water do you want to add:")
fill_water = int(input())
print("Write how many ml of milk do you want to add:")
fill_milk = int(input())
print("Write how many grams of coffee beans do you want to add:")
fill_coffee = int(input())
print("Write how many disposable cups of coffee do you want to add:")
fill_cups = int(input())
water += fill_water
milk += fill_milk
coffee_beans += fill_coffee
disposable_cups += fill_cups
def take():
global money
print(f"I gave you ${money}")
money = 0
# main zone
water = 400
milk = 540
coffee_beans = 120
disposable_cups = 9
money = 550
while True:
action = ask_action()
print()
if action == "buy":
buy()
elif action == "fill":
fill()
elif action == "take":
take()
elif action == "remaining":
summary()
elif action == "exit":
sys.exit()
else:
print("No valid action")
print()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.