blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
2dc7914b8579bd2def0fb0c92063843c00915a44 | JosyulaSaiCharitha/Atom_Programs | /class_intro.py | 579 | 4.4375 | 4 | '''
Introducing how class and object works
'''
class Parrot:
# class attribute
species = 'bird'
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
# instantiating the Parrot class
blue = Parrot('Blue', 10)
woo = Parrot('Woo', 15)
# accessing class attribute
print("Blue is a {}".format(blue.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
# accessing instance attribute
print("{} is {} years old".format(blue.name, blue.age))
print("{} is {} years old".format(woo.name, woo.age))
|
1db12b3585b30994c082172c3ca3cef2cee0fb62 | zeelat7/MathematicalModeling | /Final/Final-3Test.py | 379 | 3.75 | 4 | import numpy as np
from matplotlib.pyplot import *
import numpy
from numpy import *
def W(x):
if x <= 28:
return 50 + 2.85*x + 0.6519*x**2 + 0.00804*x**3
else:
return -1097 + 68.9*x
x=arange(0,100.1,0.1)
y=arange(0,100.1,0.1)
vW = np.vectorize(W)
xlim(0,60)
ylim(0,1000)
y = vW(x)
xlabel('Days')
ylabel('Weight in Grams')
title('Final Number 3')
plot(x,y)
show()
|
7262d7a82834b38762616a30d4eac38078e4b616 | miaoxu1com/Python_project | /untitled/day03/Str01.py | 855 | 4 | 4 | # 遍历(循环) 出字符串中的每一个元素
str01 = "大发放而非asdfasfasdfa,,,,aadfa阿斯顿发水电费&&"
# ----->字符串中的元素都是有索引的,根据索引可以得到对应的元素
# 而---3
a = str01[3]
print(str01[3])
# 发---1
print(str01[1])
#---->计算字符串的长度
# 这个字符串中 有 35个元素 ,长度是35
l01 = len(str01)
print(l01)
str01 = "大放而非asdfasfasdfa,,,,aadfa阿斯顿发水电费&&"
# 最后一个元素的索引:字符串的长度-1
len01 = len(str01)# 字符串的长度
index_last = len01 - 1 # 最后一个元素的索引
i = 0 # i变量表示是 元素的索引
while i <= index_last:
print(str01[i])
i += 1
print()
print("上面的循环结束了 执行到这里")
'''
0 1 2 ..... 34
'''
|
48f4f3ee829b1a4c855d87d79e527f0135f0f58f | tugger/eda132 | /reversi/node.py | 614 | 3.59375 | 4 | from board import Board
class Node:
def __init__(self,board, player):
self.children = []
self.board = board
self.player = player
def print_state(self):
self.board.print_board()
def legal_moves(self, player):
return self.board.find_legal_moves(player)
def make_children(self, depth):
legal_moves = self.board.find_legal_moves(self.player)
for move in legal_moves:
b = Board(self.board.board, depth)
b.place_brick(self.player,move[0],move[1])
n = Node(b, -self.player)
self.children.append(n)
|
a8d3b9a9b7817897d887afa85f7d02ded126721a | rzlatkov/Softuni | /OOP/Classes_and_Instances/circle.py | 386 | 3.890625 | 4 | class Circle:
pi = 3.14
def __init__(self, radius):
self.radius = radius
def set_radius(self, new_radius):
self.radius = new_radius
def get_area(self):
area = Circle.pi*self.radius*self.radius
return round(area, 2)
def get_circumference(self):
circumference = Circle.pi*2*self.radius
return round(circumference, 2) |
953028eb646df660ee3560f624c8e00c65cd01a7 | timsergor/StillPython | /207.py | 1,942 | 3.71875 | 4 | # 1209. Remove All Adjacent Duplicates in String II. Medium. Contest.
# Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
# We repeatedly make k duplicate removals on s until we no longer can.
# Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
class Solution(object):
def removeDuplicates(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
symbols = []
lengths = []
i = 0
while i < len(s):
if symbols == []:
symbols.append(s[i])
lengths.append(1)
i += 1
else:
if s[i] != symbols[-1]:
if lengths[-1] >= k:
t = k
x = symbols[-1]
while symbols and symbols[-1] == x and t:
symbols.pop()
t -= 1
if symbols and symbols[-1] == x:
lengths[-1] -= k
else:
lengths.pop()
else:
symbols.append(s[i])
lengths.append(1)
i += 1
else:
symbols.append(s[i])
lengths[-1] += 1
i += 1
if lengths and lengths[-1] >= k:
t = k
x = symbols[-1]
while symbols and symbols[-1] == x and t:
symbols.pop()
t -= 1
if symbols and symbols[-1] == x:
lengths[-1] -= k
else:
lengths.pop()
return "".join(symbols)
# 25min.
|
badcc689d1acd2991865164af65a2375235cfd65 | ipsorus/lesson_2 | /for_challenges.py | 2,688 | 3.5625 | 4 | # Задание 1
# Необходимо вывести имена всех учеников из списка с новой строки
names = ['Оля', 'Петя', 'Вася', 'Маша']
def new_string_names(names):
for name in names:
print(name)
# Задание 2
# Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём.
names = ['Оля', 'Петя', 'Вася', 'Маша']
def names_lengh(names):
for name in names:
print(name, len(name))
# Задание 3
# Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика
is_male = {
'Оля': False, # если True, то пол мужской
'Петя': True,
'Вася': True,
'Маша': False,
}
names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???
def names_gender(names):
for name in names:
if is_male[name] == False:
print(f'{name}, \'Пол женский\'')
else:
print(f'{name}, \'Пол мужской\'')
# Задание 4
# Даны группу учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней
# Пример вывода:
# Всего 2 группы.
# В группе 2 ученика.
# В группе 3 ученика.
groups = [
['Вася', 'Маша'],
['Оля', 'Петя', 'Гриша'],
]
def count_group_students(groups):
groups_count = len(groups)
print(f'Количество групп: {groups_count}')
for group in groups:
students = len(group)
print(f'Число студентов в группе: {students}')
# Задание 5
# Для каждой пары учеников нужно с новой строки перечислить учеников, которые в неё входят.
# Пример:
# Группа 1: Вася, Маша
# Группа 2: Оля, Петя, Гриша
groups = [
['Вася', 'Маша'],
['Оля', 'Петя', 'Гриша'],
]
def students_in_group(groups):
group_number = 1
for group in groups:
#for name in group:
#name_student = name
students_names = (', '.join(group))
print(f'Группа {group_number}: {students_names}')
group_number += 1
if __name__ == '__main__':
new_string_names(names)
names_lengh(names)
names_gender(names)
count_group_students(groups)
students_in_group(groups) |
4e4b2a2226f5d810c20f485c3d03620df6a1af06 | denizlektemur/Algoritmen-Datastructuren | /Week4/Opdracht 4.py | 795 | 3.578125 | 4 | def F(n):
if n > 10000:
return "Value is too high"
coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000]
waysToPay = []
for coin in range(len(coins)):
if n > coins[coin]:
maxCoin = coin
for coin in range(maxCoin + 2):
waysToPay.append([])
for way in range(n + 1):
waysToPay[coin].append(1)
for coin in range(1, maxCoin + 2):
for way in range(len(waysToPay[coin])):
if way >= coins[coin]:
waysToPay[coin][way] = waysToPay[coin - 1][way] + waysToPay[coin][way - coins[coin]]
elif way < coins[coin]:
waysToPay[coin][way] = waysToPay[coin - 1][way]
return waysToPay[-1][-1]
print(F(18))
print(F(26))
print(F(5403))
print(F(20000))
|
eed8b40dc26e78148d10e6fee0b89274f9a62c26 | sdan/python-deanza | /unitB/inclass.py | 524 | 3.875 | 4 | name = (str(input("Enter your name")))
print(name.upper())
print(len(name)-1)
print(name[3])
name2 = name.replace("o", "x")
print(name2)
print(name)
quote = "Believe you can and you're halfway there."
print("QUOTE: ",quote.count('a'))
first_instance = quote.find("a")
print(first_instance)
second_instance = quote.find("a", first_instance+1)
print(second_instance)
third_instance = quote.find("a", second_instance+1)
print(third_instance)
fourth_instance = quote.find("a", third_instance+1)
print(fourth_instance) |
b27e7e0b30b087db259ce5a9239c261601d07b0a | YutingYao/leetcode-3 | /leetcode/array/259.py | 801 | 3.609375 | 4 | from typing import List
class Solution:
def threeSumSmaller(self, nums: List[int], target: int) -> int:
'''较小的三数和
@Note:
排序->三指针,固定一个,双边遍历
'''
count=0
lens=len(nums)
nums=sorted(nums)
for i in range(lens):
l=i+1
r=lens-1
while l<r:#当前i下的所有满足条件的个数
if nums[i]+nums[l]+nums[r]>=target:
r-=1
else:
count+=r-l
l+=1#双边遍历
return count
if __name__=='__main__':
arr=[int(x) for x in input().strip().split(' ')]
target=int(input().strip())
solution=Solution()
print(solution.threeSumSmaller(arr,target)) |
0f443e84e570b73e994a2f19b97016964cc903a1 | mynameismon/12thPracticals | /question_14/question_14.py | 2,162 | 4.3125 | 4 | # Write a python program to create CSV file and store empno,name,salary in it.
import csv
import os
path = "question_14/emp.csv"
def create_csv():
if os.path.exists(path):
pass
else:
with open(path, 'w', newline='') as outcsv:
writer = csv.writer(outcsv, delimiter=',')
writer.writerow(i for i in ['empno', 'name', 'salary'])
# add data to csv file
def add_data_csv(empno, name, salary):
create_csv()
with open(path, 'a', newline='') as outcsv:
writer = csv.writer(outcsv, delimiter=',')
writer.writerow(i for i in [empno, name, salary])
# Take empno from the user and display the corresponding name, salary from the file.
def display_data_csv(empno):
with open(path, 'r', newline='') as incsv:
reader = csv.reader(incsv, delimiter=',')
res = []
for row in reader:
if row[0] == empno:
res.append(row)
if len(res) == 0:
print("No data found")
else:
for i in res:
print(i)
add_data_csv(1, 'ramesh', 10000)
#alternate
import csv
def CreateFile() :
fc=open("employee.csv","w+")
truthval= input("Do you want to enter another record ? (y/n) : ")
while truthval == "y" or truthval== "Y" :
fcwriter=csv.writer(fc)
empno = int(input("enter employee number : "))
name = input("enter employee name : ")
sal = int(input("enter salary : "))
rec=[empno, name, sal]
fcwriter.writerow(rec)
truthval= input("Do you want to enter records ? (y/n) : ")
fc.close()
def search() :
with open("employee.csv","r+",newline="\r\n") as fc :
fcreader=csv.reader(fc)
empsearch = int(input("Enter the employee number required : "))
global count
count=0
for rec in fcreader :
if int(rec[0])==int(empsearch) :
print("For EmpID = ",empsearch, " | Name : ",rec[1]," | Salary : ",rec[2])
count+=1
if count ==0 :
print("employee not found")
CreateFile()
search()
|
d6e87b5e979c17aaca921f29e99a8dda85e62a50 | crazese/LeetCode | /Letter Combinations of a Phone Number.py | 996 | 3.625 | 4 | class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
# [2, 3, 4, 5, 6, 7, 8, 9]
code = ['abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
if len(digits) ==0:
return []
elif len(digits) == 1:
return list(code[int(digits)-2])
elif len(digits) == 2:
list1 = list(code[int(digits[0])-2])
list2 = list(code[int(digits[1])-2])
print list1,list2
return self.combination(list1,list2)
else:
list1 = list(code[int(digits[0])-2])
list2 = self.letterCombinations(digits[1:])
return self.combination(list1,list2)
def combination(self,list1,list2):
list3 = []
for i in list1:
for j in list2:
list3.append(i+j)
return list3
test = Solution()
print test.letterCombinations('234') |
295e5509bb5883bb5646d47102971456f3597481 | HUGGY1174/MyPython | /Chapter02/P03.py | 139 | 3.609375 | 4 | radius = int(input("반지름을 입력하세요"))
size = 3.14159 * radius
print("반지름이", radius, "인 원의 넓이 =", size)
|
c2cedf8071ae380ffafde30e327d1552de95ae4b | chudichen/algorithm | /recursion/pascal_triangle.py | 945 | 3.734375 | 4 | """
Pascal三角
利用n=1为终止条件进行递归,后一项除了两边的元素外,其余元素值均为前一项的n+n-1
https://leetcode.com/explore/learn/card/recursion-i/251/scenario-i-recurrence-relation/1659/
"""
from typing import List
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
def helper(n):
if n == 1:
return [[1]]
else:
res = helper(n - 1)
base = res[-1]
cur = []
for i in range(len(base) + 1):
if i == 0 or i == len(base):
cur += [1]
else:
cur += [base[i] + base[i - 1]]
res.append(cur)
return res
if numRows == 0:
return []
return helper(numRows)
if __name__ == '__main__':
result = Solution().generate(6)
print(result)
|
8751030fe90134d5172a8005f18e6871a944068a | Yeami/aiplt | /lab2/2_4_1.py | 361 | 3.859375 | 4 | import random
if __name__ == '__main__':
_list = [random.randint(-10, 10) for i in range(10)]
print('Generated list: ', _list)
value = int(input('Input the number that you want to insert: '))
index = int(input('Input the index of the list where you want to insert item: '))
_list[index:index] = [value]
print('Updated list: ', _list)
|
370d6a36af00c898c3c8c839cfb631607dd6a4e1 | AaronEC/CBR-House-Price-Recommender | /Recommender.py | 5,810 | 3.578125 | 4 | # TODO:
# Impliment distance scoring?
# Calculation for bool value weighting?
# RETAIN new case (customers house) and add it to existing database
# This import is just for showing monetary values formatted in local currency
import locale
locale.setlocale(locale.LC_ALL, '')
class house:
""" This class holds all data for each object of house. """
def __init__(self, row):
self.name = row[0]
self.price = float(row[1])
self.date = int(row[2])
self.distance = float(row[3])
self.area = int(row[4])
self.rooms = int(row[5])
self.bedrooms = int(row[6])
self.detached = row[7]
self.garage = row[8]
self.energy = str(row[9]).strip('\n')
# Adjust price for inflation (3% per 3 months)
for i in range(0, self.date, 3):
self.price += self.price * 0.03
# Initial value setting
self.value = 0
def value(house):
""" Calculates and updates value of a passed house, relative to the customers house,
based on weighted values.
:type house: house[class]
:rtype: void
"""
adjustment = 0
if house.distance > 0.25:
print(f"\nHouse {house.name} too far away, disregarded")
house.value, house.price = 0, 0
else:
print(f"\nHouse {house.name} within distance, calculating...")
value = weights["distance"]
if house.area and customerHouse.area:
value += weights["area"] * (house.area / customerHouse.area)
if house.rooms and customerHouse.rooms:
value += weights["rooms"] * (house.rooms / customerHouse.rooms)
if house.bedrooms and customerHouse.bedrooms:
value += weights["bedrooms"] * (house.bedrooms / customerHouse.bedrooms)
if house.energy and customerHouse.energy:
value += weights["energy"] * (energyRating[house.energy] / energyRating[customerHouse.energy])
if house.detached == 'Y':
value += weights["detached"]
if house.garage == 'Y':
value += weights["garage"]
if customerHouse.detached == 'N':
adjustment += weights["detached"]
if customerHouse.garage == 'N':
adjustment += weights["garage"]
house.value = round(value / (potential - adjustment), 2)
print(f"Relative value: {house.value}")
def saveHouse(file, savedHouse):
""" Saves customer house back to database, with recommended value, for re-use
:type file: database file name
:type savedHouse: house[class]
:rtype: void
"""
# Format house object ready for saving
savedHouse.name = len(houseDatabase) + 1
savedHouse.price = round(savedHouse.price)
savedHouse.energy = savedHouse.energy + "\n"
# Convert object to list
savedHouse = list(savedHouse.__dict__.values())
savedHouse.pop()
# Convert list to string
outputString = ','.join(str(x) for x in savedHouse)
# Save string to .csv file
with open('Database.csv', 'a') as databaseOut:
# Check if exact house is already in database (to prevent double saving)
for line in databaseIn:
line = ','.join(str(x) for x in line)
if outputString.split(',', 1)[1] == line.split(',', 1)[1]:
print("Exact house already in database, not saving...")
break
# Save to database, if it is a unique entry
else:
print("House not already in database, saving...")
databaseOut.write(outputString)
# Define weignting to be used for comparison (based off expert knowledge)
weights = {
"distance": 4,
"area": 2,
"rooms": 2,
"bedrooms": 2,
"detached": 3,
"garage": 1,
"energy": 1
}
potential = sum(weights.values())
# Define energy rating scale
energyRating = {
"A": 6,
"B": 5,
"C": 4,
"D": 3,
"E": 2,
"F": 1
}
# Send database files to 2d arrays ready for processing
houseIn = [line.split(',') for line in open('House.csv')]
databaseIn = [line.split(',') for line in open('Database.csv')]
# Define object of class 'house' for customer house and reset price
customerHouse = house(houseIn[1])
customerHouse.price = 0
# Define comparison houses (array of objects of class 'house')
houseDatabase = []
for row in databaseIn[1:]:
houseDatabase.append(house(row))
# Weighted comparisons between customer house and database houses
valueTotals = []
for house in houseDatabase:
value(house)
valueTotals.append(house.value)
# Find closest database house value match to customer house value
bestMatchIndex = valueTotals.index(min(valueTotals, key=lambda x:abs(x-1)))
# Calculate estimated customer house price based on value adjusted price of best match house
customerHouse.price = houseDatabase[bestMatchIndex].price / min(valueTotals, key=lambda x:abs(x-1))
# Output results summary to terminal
print(f"""
------------------------------------------------------------------------------------
Closest match: House {houseDatabase[bestMatchIndex].name}
Relative weighted value: {houseDatabase[bestMatchIndex].value}
------------------------------------------------------------------------------------
Estimated customer house value: {locale.currency(customerHouse.price, grouping=True)}p
------------------------------------------------------------------------------------
""")
# Save customer house to database to improve future recommendation accuracy
userSave = ""
while userSave.lower() != "y" or userSave.lower() != "n":
userSave = input("Save valuation to database? (Y/N): \n")
if userSave.lower() == "y":
saveHouse('Database.csv', customerHouse)
break
elif userSave.lower() == "n":
print("Not saving")
break
else:
print("Invalid input, enter Y for yes, or N for no") |
f094904b7f925cb276e6f6e0a8f28b73715655fa | LinearAlgeb/Automate-The-Boring-Stuff-With-Python | /chapter 8/sandwichMaker.py | 1,485 | 3.78125 | 4 | import pyinputplus as pyip
price=0
prompt='What bread type do you want?\n'
response= pyip.inputMenu(['wheat', 'white','sourdough'],prompt)
if response=='wheat':
price+=10
elif response=='white':
price+=7
elif response=='sourdough':
price+=12
prompt='What protein type do you want?\n'
response= pyip.inputMenu(['chicken', 'turkey','ham','tofu'],prompt)
if response=='chicken':
price+=10
if response=='turkey':
price+=12
if response=='ham':
price+=14
if response=='tofu':
price+=15
prompt='Do you want cheese ?\n'
response= pyip.inputYesNo(prompt)
if response=='yes':
prompt='What cheese type do you want?\n'
response= pyip.inputMenu(['cheddar', 'swiss','mozzarella'],prompt)
if response=='cheddar':
price+=7
if response=='swiss':
price+=9
if response=='mozzarella':
price+=10
prompt='Do you want mayo?\n'
response= pyip.inputYesNo(prompt)
if response=='yes':
price+=5
prompt='Do you want mustard?\n'
response= pyip.inputYesNo(prompt)
if response=='yes':
price+=5
prompt='Do you want lettuce?\n'
response= pyip.inputYesNo(prompt)
if response=='yes':
price+=5
prompt='Do you want tomatoes?\n'
response= pyip.inputYesNo(prompt)
if response=='yes':
price+=5
print('You have to pay %s for this sandwich!' % (price))
prompt='How many sandwiches do you want?\n'
response= pyip.inputInt(prompt,min=1)
print('You have to pay %s for %s sandwich(s)!' % (price*response,response))
|
cd907fd0297a174e8f3fd2c2ea0570dcba47b19d | godboys/python_20191222 | /time_process/time/easy.py | 817 | 3.859375 | 4 | import time
def calcProd():
#Calculate the product of the first 100,000 numbers
product=1
for i in range(1,100000):
product=product*i
return product
if __name__ == '__main__':
# 表示从1970年到当前时间一共的秒数
print(time.time()) # 1577022497.295276
# 计算一百万行代码运行的时间
#startTime = time.time()
# prod = calcProd()
#endTime = time.time()
# print ('The result is %s digits long' % (len(str(prod)))) # The result is 456569 digits long
#print ('Took %s seconds to calculate' % (endTime - startTime)) # Took 2.6482274532318115 seconds to calculate
# 定时 10s钟
print("start: " + time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
time.sleep(10)
print("end: " + time.strftime("%Y-%m-%d %H:%M:%S"),time.localtime()) |
1ab8265a5be95396633514fcbd482ac6dce8183a | shuyuqing/likou | /Monotonic Array.py | 1,700 | 3.828125 | 4 | # 如果数组是单调递增或单调递减的,那么它是单调的。
#
# 如果对于所有 i <= j,A[i] <= A[j],那么数组 A 是单调递增的。 如果对于所有 i <= j,A[i]> = A[j],那么数组 A 是单调递减的。
#
# 当给定的数组 A 是单调数组时返回 true,否则返回 false。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/monotonic-array
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
#单调list的话有两种情况(无论如何都要遍历两遍)
# 1.单调递减list,后一个元素减掉前一个元素一直小于等于0,遍历的过程中一旦小于0,那么就不是单调list
# 2.单调递增list,后一个元素减掉前一个元素一直大于等于0,遍历的过程中一旦大于0,那么就不是单调list
class Solution:
def isMonotonic(self,A):
return Solution.issorted(self,A,True) or Solution.issorted(self,A,False)
def issorted(self,A,increasing):
n = len(A)
if(increasing):
for i in range(1,n):
if A[i-1]>A[i]:
return False
else:
for i in range(1,n):
if A[i-1]<A[i]:
return False
return True
l=[1,2,2,2]
p=Solution()
print(p.isMonotonic(l))
#参考
# class Solution:
# def isMonotonic(self, A: List[int]) -> bool:
# if len(A)==1:
# return True
# B=A.copy()
# A.sort()
# if B==A:
# return True
# A.reverse()
# if B==A:
# return True
# return False
|
9db052897fa77e0a691b4ae7857cab3b41a398bb | ahmedmeshref/Leetcode-Solutions | /graph/bfs.py | 342 | 3.671875 | 4 | from collections import deque
def bfs(graph, node):
seen = set()
queue = deque()
queue.append(node)
while queue:
c_node = queue.popleft()
seen.add(c_node)
for val in graph[c_node]:
queue.append(val)
return seen
graph = [[1, 2], [3], [3], []]
print(bfs(graph, 0))
|
2a3f471a36b23afa18eb781756529390a7d366fa | bystanders/cy.book.code | /learn.python.the.hardway.3rd/ex33.py | 685 | 3.96875 | 4 | def while_loop(quit_var, increment):
i = 0
numbers = []
while i < quit_var:
print "At the top i is %d" % i
numbers.append(i)
i = i + increment
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
def for_loop(quit_var, increment):
numbers = []
for i in range(0, quit_var, increment):
print "At the top i is %d" % i
numbers.append(i)
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
while_loop(6, 1)
print
for_loop(6, 1)
|
bd86f95f9763ff3ee11f5ab4fe5757dc759c5c0d | melijov/course_python_essential_training | /sets-working.py | 607 | 4.03125 | 4 | def main():
"""
Set is like a list that does not allow duplicate elements
"""
a = set("We're gonna need a bigger boat.")
b = set("I'm sorry, Dave. I'm afraid I can't do that.")
print_set(sorted(a))
print_set(sorted(b))
print_set(a - b) # members in a but not in b
print_set(b - a) # members in b but not in a
print_set(a | b) # members in a, b or in both
print_set(a ^ b) # members in a, b but not in both
print_set(a & b) # members in a and b
def print_set(o):
print('{',end=' ')
for x in o: print(x,end=' ')
print('}')
if __name__=='__main__':main() |
21fe84e65cf980ed0fb641c8e9f326f3353328d6 | flyerooo/learnpy | /py_eg.py | 866 | 3.859375 | 4 | import turtle
def drawLine(x1, y1, x2, y2):
turtle.penup()
turtle.goto(x1, y1)
turtle.pendown()
turtle.goto(x2, y2)
def writeText(s, x, y):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.write(s)
def drawPoint(x, y):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.begin_fill()
turtle.circle(3)
turtle.end_fill()
def drawCircle(x = 0, y = 0, radius = 10):
turtle.penup()
turtle.goto(x, y - randius)
turtle.pendown()
turtle.circle(randius)
def drawRectangle(x = 0, y = 0, width = 10, height = 10):
turtle.penup()
turtle.goto(x + width / 2, Y + height / 2)
turtle.pendown()
turtle.right(90)
turtle.forward(height)
turtle.right(90)
turtle.forward(width)
turtle.right(90)
turtle.forward(height)
turtle.right(90)
turtle.forward(width)
|
0402c6970b4bee9c799fd5585921b6c56eb1e4de | beidou9313/deeptest | /第一期/深圳--NLJY/日期.py | 264 | 3.65625 | 4 | from datetime import date
from datetime import time
from datetime import datetime
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)
|
a84b19d9d0c7561194b686c92177d8beb3d69982 | vicalbiter/crsim | /agent.py | 5,291 | 3.625 | 4 | import pygame
from geometry import *
from pygamehelper import *
from pygame import *
from pygame.locals import *
from math import e, pi, cos, sin, sqrt
from random import uniform
class Agent:
def __init__(self, width, obstaclesR):
#self.prevpos = Vector(0, 0)
self.id = 0
self.pos = Vector2(0, 0)
self.target = Vector2(0, 0)
self.velocity = Vector2(0, 0)
self.acceleration = Vector2(0, 0)
self.width = width
self.goalStack = []
self.goal = None
self.priority = 0
self.obstacles = obstaclesR
self.lineToTNextGoal = Line(Point(0, 0), Point(0, 0))
# Go to target at a certain speed
# If the agent can see its next target directly (i.e. there are no obstacles
# in between), pop the current action from the BS
def goToTarget(self, target):
self.dir = Vector2(target - self.pos)
#self.updateVelocity(dir)
if len(self.goalStack) != 0:
# If the next goal is within reach, skip the current goal
nextGoal = self.goalStack[len(self.goalStack) - 1]
self.lineToNextGoal = Line(Point(self.pos.x, self.pos.y), Point(nextGoal[1].x, nextGoal[1].y))
for r in range(len(self.obstacles)):
result = getIntersectionLR(self.lineToNextGoal, self.obstacles[r])
if result == True:
break;
else:
if r == len(self.obstacles) - 1:
self.goal = self.goalStack.pop()
#l = Line(Point(pos.x, pos.y), Point())
if self.dir.length() > 3:
self.pos = self.pos + self.velocity
else:
if len(self.goalStack) != 0:
self.goal = self.goalStack.pop()
def updateVelocity(self, neighbors):
self.velocity = 2.0*self.dir.normalize()
separation = self.calculateSeparationVector(neighbors)
velchange = separation
if velchange.length() > 0:
velchange.scale_to_length(0.2)
self.velocity = self.velocity + velchange
# Plan a bath, using BFS to a certain target, and add all the intermediate
# steps necessary to get to that path to the behavior stack
def planPathTo(self, target, navgraph):
path = self.findPath(target, navgraph)
for p in path:
self.goalStack.insert(0,("goto", p))
if len(self.goalStack) != 0:
self.goal = self.goalStack.pop()
# Perform the task at hand
def performTask(self, goal):
if goal[0] == "goto":
self.goToTarget(goal[1])
# Find a path from the current position to the target position
def findPath(self, target, navgraph):
posclosest = self.findClosestPoint(self.pos, navgraph)
tarclosest = self.findClosestPoint(self.target, navgraph)
path = self.bfs(Node(None, posclosest), Node(None, tarclosest), navgraph)
path.append(self.target)
return path
# BFS algortithm to find the shortest path (assuming unitary costs) from
# one vertex to another
def bfs(self, initial, goal, navgraph):
q = []
current = initial
visited = set([initial])
while current.pos.x != goal.pos.x or current.pos.y != goal.pos.y:
# Highly optimizible
neighbors = navgraph.neighbors(current.pos)
# Highly optimizible
for p in neighbors:
node = Node(current, p)
if node not in visited:
q.insert(0, node)
visited.add(node)
current = q.pop()
#for p in neighbors:
# idp = self.getID(p, navgraph.gpoints)
# if visited[idp] == False:
# q.insert(0, Node(current, p))
# visited[idp] = True
#current = q.pop()
path = []
while current != None:
path.insert(0, current.pos)
current = current.parent
return path
# Get the label of the vertex
def getID(self, p, gpoints):
for point in range(len(gpoints)):
tp = Vector2(gpoints[point])
if p.x == tp.x and p.y == tp.y:
return point
return 0
# Find the closest vertex in the graph to a certain test point
def findClosestPoint(self, pos, navgraph):
closest = Vector2(navgraph.gpoints[0])
cdistance = pos.distance_to(closest)
for p in navgraph.gpoints:
vp = Vector2(p)
if pos.x != vp.x or pos.y != vp.y:
if pos.distance_to(vp) < cdistance:
closest = vp
cdistance = pos.distance_to(vp)
return closest
def calculateSeparationVector(self, neighbors):
separation = Vector2(0, 0)
for neighbor in neighbors:
if neighbor.pos.x == self.pos.x and neighbor.pos.y == self.pos.y:
continue;
distance = self.pos.distance_to(neighbor.pos)
vector = self.pos - neighbor.pos
vector.scale_to_length(10/distance)
separation = separation + vector
return separation
class Node:
def __init__(self, parent, pos):
self.parent = parent
self.pos = pos
|
4000687cc99224bf9effb01bb51e21034ab934b6 | aabhishek-chaurasia-au17/MyCoding_Challenge | /coding-challenges/week07/day04/Q.3.py | 648 | 4.1875 | 4 | """
Given an array with NO Duplicates . Write a program to find PEAK
ELEMENT
Return value corresponding to the element of the peak element.
Example :
Input : - arr = [2,5,3,7,9,13,8]
Output : - 5 or 13 (anyone)
HINT : - Peak element is the element which is greater than both
neighhbours.
def FindPeak(arr ):
"""
# write code here
def FindPeak(arr):
l=len(arr)
if(arr[0]>arr[1]):
print(arr[0])
if(arr[l-1]>arr[l-2]):
print(arr[l-1])
for i in range(1,l-1):
if arr[i]>arr[i+1] and arr[i]>arr[i-1]:
print(arr[i])
arr = [10,2,5,3,7,9,13,81]
FindPeak(arr) |
12502b795a4bd11a9d56af979617f253f7d1693b | coder20910/degreeOfProfanity | /degreeOfProfanity.py | 818 | 3.984375 | 4 | import os
import re
file_path = input("Enter the path of your file: ")
assert os.path.exists(file_path), "I did not find the file at, "+str(file_path)
# Getting all words from text file.
sentenceList = []
with open(file_path,"r", encoding='cp437') as file:
for row in file:
sentence = re.split(r"\. |\?|\!",row)
sentenceList.extend(sentence)
slangList = ['fool', 'donkey', 'dumb', 'filthy']
slangsInEachSentence = []
for sentence in sentenceList:
slang = 0
for word in sentence.split(" "):
if word in slangList: # we can search in set of all slangs or use inbuilt library(better_profanity) to identify slang word
slang += 1
slangsInEachSentence.append(slang)
print(slangsInEachSentence)
|
2c10ce3830b92a039d79444d7965faa38d7ede6c | martsc1/Automate-the-boring-stuff-with-python | /debuggedCoinToss.py | 594 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 4 11:01:24 2021
@author: martsc1
"""
# Debugging coin toss
import random
guess = ''
coin = ['heads','tails']
while guess not in ('heads', 'tails'):
print('Guess the coin toss! Enter heads or tails:')
guess = input()
toss = random.randint(0, 1) # 0 is tails, 1 is heads
toss = coin[toss]
if toss == guess:
print('You got it!')
else:
print('Nope! Guess again!')
guess = input()
if toss == guess:
print('You got it!')
else:
print('Nope. You are really bad at this game.') |
215149befd83c2fa8c7b9959986a7d48957a7ce1 | hcodyd/reversi | /ReversiRandom_Python/RandomGuy.py | 6,629 | 3.765625 | 4 | import sys
import socket
import time
from random import randint
GAME_OVER = -999 # the turn is set to -999 if the game is over
UPPER_LEFT = [0, 0]
UPPER_RIGHT = [0, 7]
LOWER_LEFT = [7, 0]
LOWER_RIGHT = [7, 7]
t1 = 0.0 # the amount of time remaining to player 1
t2 = 0.0 # the amount of time remaining to player 2
state = [[0 for x in range(8)] for y in range(8)] # state[0][0] is the bottom left corner of the board (on the GUI)
def random_move(valid_moves):
"""
Take a random move
:param valid_moves: the valid moves in the current game
:return: the INDEX within valid_moves
"""
corner_move = []
for i in range(0, len(valid_moves)):
if (valid_moves[i] == UPPER_LEFT) or (valid_moves[i] == UPPER_RIGHT) or (valid_moves[i] == LOWER_LEFT) or (
valid_moves[i] == LOWER_RIGHT):
corner_move.append(i)
if len(corner_move) > 0:
rand = randint(0, len(corner_move) - 1)
print("PURPOSEFULLY SELECTED A CORNER MOVE")
return corner_move[rand]
side_move = []
for i in range(0, len(valid_moves)):
if (valid_moves[i][0] == 0) or (valid_moves[i][0] == 7) or (valid_moves[i][1] == 0) or (valid_moves[i][1] == 7):
side_move.append(i)
if len(side_move) > 0:
rand = randint(0, len(side_move) - 1)
print("PURPOSEFULLY SELECTED A SIDE MOVE")
return side_move[rand]
my_move = randint(0, len(valid_moves) - 1)
print("PICKED A RANDOM MOVE")
return my_move
def check_dir(row, col, incx, incy, me):
"""
Figures out if the move at row,col is valid for the given player.
:param row: the row of the unoccupied square (int)
:param col: the col of the unoccupied square (int)
:param incx: ?
:param incy: ?
:param me: the given player
:return: True or False
"""
sequence = []
for i in range(1, 8):
r = row + incy * i
c = col + incx * i
if (r < 0) or (r > 7) or (c < 0) or (c > 7):
break
sequence.append(state[r][c])
count = 0
for i in range(len(sequence)):
if me == 1:
if sequence[i] == 2:
count = count + 1
else:
if (sequence[i] == 1) and (count > 0):
return True
break
else:
if sequence[i] == 1:
count = count + 1
else:
if (sequence[i] == 2) and (count > 0):
return True
break
return False
def could_be(row, col, me):
"""
Checks if an unoccupied square can be played by the given player
:param row: the row of the unoccupied square (int)
:param col: the col of the unoccupied square (int)
:param me: the player
:return: True or False
"""
for incx in range(-1, 2):
for incy in range(-1, 2):
if (incx == 0) and (incy == 0): # no need to check curr place
continue
if check_dir(row, col, incx, incy, me):
return True
return False
def get_valid_moves(rnd, me):
"""
Generates the set of valid moves for the player
:param rnd: what number round the game is currently at.
:param me: ?
:return: A list of valid moves
"""
valid_moves = []
if rnd < 4:
if state[3][3] == 0:
valid_moves.append([3, 3])
if state[3][4] == 0:
valid_moves.append([3, 4])
if state[4][3] == 0:
valid_moves.append([4, 3])
if state[4][4] == 0:
valid_moves.append([4, 4])
else:
for i in range(8):
for j in range(8):
if state[i][j] == 0:
if could_be(i, j, me):
valid_moves.append([i, j])
return valid_moves
def print_game_state():
"""
Uses global variable state to print current game state.
:return: None
"""
for i in range(8): # prints the state of the game in readable rows
print(state[i])
def init_client(me, host):
"""
Establishes a connection with the server.
:param me: ?
:param host: ?
:return: a "sock"
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (host, 3333 + me)
print('starting up on %s port %s' % server_address, file=sys.stderr)
sock.connect(server_address)
info = sock.recv(1024)
print("Sock info: {}".format(info))
return sock
def read_message(sock):
"""
Reads messages from the server that tell the player whose turn it is and what moves are made.
:param sock: ?
:return: the current turn and the round
"""
message = sock.recv(1024).decode("utf-8").split("\n")
turn = int(message[0])
if turn == GAME_OVER:
time.sleep(1)
sys.exit()
rnd = int(message[1])
# update the global state variable
count = 4
for i in range(8):
for j in range(8):
state[i][j] = int(message[count])
count += 1
return turn, rnd
def play_game(me, host):
"""
Establishes a connection with the server.
Then plays whenever it is this player's turn.
:param me: ?
:param host: ?
:return: ?
"""
sock = init_client(me, host) # Establish connection
while True:
status = read_message(sock) # get update from server
if status[0] == me: # status[0] has turn
print("-----------------Round {}-----------------".format(status[1])) # status[1] has round
print("My turn.")
print_game_state()
valid_moves = get_valid_moves(status[1], me) # status[1] has round
my_move = random_move(valid_moves) # TODO: Call your move function instead. NOTE: This returns an *index*
print("Valid moves: {}".format(valid_moves))
print("Selected move: {}".format(valid_moves[my_move]))
# Send selection
selection = str(valid_moves[my_move][0]) + "\n" + str(valid_moves[my_move][1]) + "\n"
sock.send(selection.encode("utf-8"))
print("------------------------------------------")
else:
print("Other player's turn.")
if __name__ == "__main__":
"""
Call from command line like this: python AIGuy.py [ip_address] [player_number]
ip_address is the ip_address on the computer the server was launched on. Enter "localhost" if on same computer
player_number is 1 (for the black player) and 2 (for the white player)
"""
print('Argument List:', str(sys.argv))
play_game(int(sys.argv[2]), sys.argv[1])
|
5811632f6a45c4b08b3e958b6d707461dfe5c51c | tsflatif/project-euler | /euler4.py | 476 | 3.8125 | 4 | min_num = 100
max_num = 1000
largest_palindrome = 0
count = 0
def is_palindrome(num1, num2):
product = num1*num2
if str(product) == str(product)[::-1]:
return True
else:
return False
for x in range(min_num, max_num):
for y in range(min_num, max_num):
if is_palindrome(x, y):
count = count + 1
if x * y > largest_palindrome:
largest_palindrome = x * y
print(largest_palindrome)
print(count)
|
5d49ab5197a191ce982a39fc52b33e0780c741af | diegolinkk/exercicios-python-brasil | /estrutura-de-decisao/exercicio17.py | 440 | 3.90625 | 4 | #Faça um Programa que peça um número correspondente a um determinado ano e em seguida informe se este ano é ou não bissexto.
ano = int(input("Digite o ano: "))
if ano % 4 == 0:
if ano % 100 != 0:
print("O ano é bisexto")
elif ano % 400 == 0:
print("O ano é bisexto")
else:
print("O ano não é bisexto")
elif ano % 400 == 0:
print("O ano é bisexto")
else:
print("O ano não é bisexto") |
c721f0bf7d67b46bf24d2fb1d17897061657dd78 | sadofnik/Python | /Lesson_1/practice_1.1.py | 331 | 3.984375 | 4 | a = 1
b = 3
print(a, b)
name = input("Введите ваше имя: ")
age =2020 - int(input ("Введите год рождения: "))
hobby = input("Чем вы любите заниматься: ")
print(f"Вас зовут {name}, в этом году вам исполнится {age}, ваше хобби: {hobby}")
|
f976abf5e64945fb4e73b0daabe197623c5fd642 | MatthewNielsen2/CP1404practicles | /Week 05/netflix.py | 890 | 3.515625 | 4 | from operator import itemgetter
netflix_list_file = open("netflix.csv", "r")
netflix_list = []
for line in netflix_list_file:
netflix_list.append(line.strip().split(","))
def get_max_column_width(column_number, table):
max_width = 0
for row in table:
current_width = len(row[column_number])
if current_width > max_width:
max_width = current_width
return max_width + 5
def display_netflix_list(netflix_list):
netflix_list.sort(key=itemgetter(0))
string_formatter = "{} {}. {:{}} Seasons: {:1}"
title_column_width = get_max_column_width(0, netflix_list)
print(title_column_width)
for i in range(0, len(netflix_list)):
complete = " "
if netflix_list[i][-1] == "c":
complete = "*"
print(string_formatter.format(complete, i + 1, netflix_list[i][0], title_column_width, netflix_list[i][1]))
|
ccc42ca6419e50904ada783aababd3dbde2af143 | sampsyo/bril | /examples/util.py | 369 | 4.09375 | 4 | import itertools
def flatten(ll):
"""Flatten an iterable of iterable to a single list.
"""
return list(itertools.chain(*ll))
def fresh(seed, names):
"""Generate a new name that is not in `names` starting with `seed`.
"""
i = 1
while True:
name = seed + str(i)
if name not in names:
return name
i += 1
|
54395169a2728635ff737fcd2b137239412b52c8 | GuanYangCLU/AlgoTestForPython | /LeetCode/0349_Intersection_of_Two_Arrays.py | 427 | 3.625 | 4 | class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
if not nums1 or not nums2:
return []
rs = []
numLen = min(len(nums1), len(nums2))
if numLen != len(nums1):
nums1, nums2 = nums2, nums1
for i in range(numLen):
if nums1[i] in nums2 and nums1[i] not in rs:
rs.append(nums1[i])
return rs
|
f6618fafd1855ced158aa5cf5645b48702ffa693 | RedExtreme12/python-intern-AC | /first_week/Get-The-Middle-Character/solution.py | 189 | 3.6875 | 4 | def get_middle(s):
word_length = len(s)
characters = s[word_length // 2 - 1:word_length // 2 + 1] if word_length % 2 == 0 \
else s[word_length // 2]
return characters
|
9a8244e3f897ea487875d0954af24b99cfd20121 | joeryan/interact-python | /pong/pong_pygame.py | 821 | 3.75 | 4 | # simple pong game in pygame
# Author: Joe Ryan
# 21 MAR 2015
import sys, pygame
import time
pygame.init()
size = width, height = 720, 500
ball_vel = [1,1]
black = 0, 0, 0
white = 255, 255, 255
pad_w = 400
pad_h = 80
screen = pygame.display.set_mode(size)
ball = pygame.image.load('pong_ball.gif')
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(ball_vel)
time.sleep(0.001)
if ballrect.left < 0 or ballrect.right > width:
ball_vel[0] = -ball_vel[0]
if ballrect.top < 0 or ballrect.bottom > height:
ball_vel[1] = -ball_vel[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
l_gut = pygame.draw.line(screen, white, (pad_w, 0), (pad_w, height), 4)
|
ac5c2c8f3125a66908254c3799c97ff65793a2b9 | teppi1995/AtCoder | /BeginnerContest_146/C/solver2.py | 1,130 | 3.84375 | 4 | import logging
logging.basicConfig(level=logging.INFO, format="%(message)s")
#logging.disable(logging.CRITICAL)
def binary_search(A, B, X, N, counter):
low = 0
high = 10 * N
mid = (low + high) // 2
ans = A * N + B * len(str(N))
mid_ans = A * mid + B * len(str(mid))
while (counter > 0):
mid = (low + high) // 2
mid_ans = A * mid + B * len(str(mid))
if mid_ans < ans:
low = mid + 1
else:
high = mid - 1
counter -= 1
return mid, mid_ans
def main():
A, B, X = map(int, input().split())
logging.info("Hello!")
N, ans = binary_search(A, B, X, X // A, 100)
if ans > X:
while (ans > X) and (N > 0):
N = N - 1
ans = A * N + B * len(str(N))
else:
while (ans < X):
N = N + 1
ans = A * N + B * len(str(N))
N = N - 1
if N > 10 ** 9:
print(10 ** 9)
elif N < 0:
print(0)
else:
print(N)
if __name__ == "__main__":
main()
|
36dbbc12f72a3840d77740044c9abd07e6e9a8fc | Milan-Pro/Python | /TwoPointer_MergeSorted.py | 695 | 3.90625 | 4 | class solution:
def merge_sorted(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
# two get pointers for num1 and num2
p1 = m - 1
p2 = n - 1
# set pointer for num1
p = m + n - 1
# while there are still elements to compare
while p1 >= 0 and p2>=0:
if nums1[p1] < nums2[p2]:
nums1[p] = nums2[p2]
p2 -= 1
else:
nums1[p] = nums1[p1]
p1 -= 1
p -= 1
# add missing elements from nums2
nums1[:p2 + 1] = nums2[:p2 + 1]
'''
Complexity Analysis
Time complexity : O(n+m).
Space complexity : O(1).
'''
|
a56da8e6874a874d6bd59a525d3cf439de2943f9 | jcclarke/learnpythonthehardwayJC | /python3/exercise24/ex24.py | 1,144 | 4.40625 | 4 | #!/usr/bin/env python3
print ("Let's practice everything.")
print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print ("---------------")
print (poem)
print ("---------------")
five = 10 - 2 + 3 - 6
print (f"This should be five: {five}")
def secret_formula (started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
# remember that this is another way to format a string
print ("With a starting point of: {}".format(start_point))
# It's just like with an f"" string
print (f"We'd have {beans} beans, {jars} jars, and {crates} crates.")
start_point = start_point / 10
print (f"We can also do it this way with a starting point of: {start_point}")
formula = secret_formula(start_point)
print ("We'd have {} beans, {} jars, and {} crates.".format(*formula))
|
7ee7a2efd2ea5dd178fd331e8f44f8642b22c465 | ProdigyX6217/interview_prep | /get_cheapest_cost.py | 886 | 3.859375 | 4 | def get_cheapest_cost(rootNode):
# getting root node's children
children = len(rootNode.children)
# getting the leaf node and its value
if children == 0:
return rootNode.cost
minCost = float("inf")
# for each children node
for i in range(children):
tempCost = get_cheapest_cost(rootNode.i)
if tempCost < minCost :
minCost = tempCost
return minCost + rootNode.cost
##########################################
# Use the helper code below to implement #
# and test your function above #
##########################################
#tree of nodes (distribution system)
#each node has a value, Looking for path that returns smallest sum
#leaf nodes are the last nodes in a path
# A node
class Node:
# Constructor to create a new node
def __init__(self, cost):
self.cost = cost
self.children = []
self.parent = None
|
735b600fdb1fcfef648589e812884d335d7cf82d | amipy/automanteu | /Creator.py | 1,782 | 3.515625 | 4 | import json
import math
import random
import sys
#load words
with open("words_dictionary.json") as f:
wrd = json.load(f)
words = list(wrd.keys())
#print(len(words))
#pick starting word
strtIndex = random.randrange(0, len(words))
start = words[strtIndex]
#print(start, strtIndex)
usedWords = start
lbuilt = ""
built = start
addedWords = 0
making = True
#set this to None to remove limit
wordLimit = None
lenght=wordLimit
if not lenght:
lenght=len(words)
#exit function
def bungalow():
print(f"Finished. Used {addedWords} of {lenght} words. Result is {len(built)} letters long.")
with open("result.txt", "w") as rslt:
rslt.write(built)
input("Press enter to display.")
print(built)
sys.exit(0)
# for sig in (SIGABRT, SIGBREAK, SIGILL, SIGINT, SIGSEGV, SIGTERM):
# signal(sig, bungalow)
try:
while making:
for ind, i in enumerate(words):
if i[0] == built[len(built) - 1]:
#Update lists and add word
usedWords += i
lbuilt = built
built += i[1:]
addedWords += 1
del words[ind]
random.shuffle(words)
break
if not lbuilt == built:
#print occasional status updates if portmanteu has been expanded
if addedWords % 10 == 0:
print(f"Used {addedWords} of {lenght} words ({math.floor(addedWords / lenght * 100)}%).")
# print(usedWords)
if addedWords % 100 == 0:
print(f"Portmanteu is {len(built)} letters long.")
if wordLimit:
if addedWords >= wordLimit:
bungalow()
bungalow()
except:
bungalow()
|
528309a10c7452f5d704ee113db5c67ff28621d9 | sn-lvpthe/CirquePy | /07-tkinter/secret_number_gui.py | 949 | 3.609375 | 4 | #!/usr/bin/env python2.7
# _*_ coding: utf-8 _*_
import Tkinter
import tkMessageBox
import random
secret = random.randint(1, 100)
window = Tkinter.Tk()
window.title("Welkom bij ons raadspel")
window.geometry('400x240')
# greeting text
greeting = Tkinter.Label(window, text="Raad een geheim nummer!\nTussen 1 en 100", font=("Courier", 20), fg="green" )
greeting.pack()
# guess entry field
guess = Tkinter.Entry(window)
guess.pack()
# check guess
def check_guess():
if int(guess.get()) == secret:
result_text = "CORRECT! Maar er is geen prijs."
elif int(guess.get()) > secret:
result_text = "FOUT! Te hoog gegokt."
else:
result_text = "FOUT! Te laag gegokt."
tkMessageBox.showinfo("Je keuze is ...", result_text) # message box
# submit button
submit = Tkinter.Button(window, text="Bevestig",font=("Courier", 16), command=check_guess) # check_guess, not check_guess()
submit.pack()
window.mainloop()
|
494f8b669e4bd368b47d65477fc8ebc27e5cad39 | Abooow/BattleShips | /BattleShips/framework/cell.py | 5,497 | 3.828125 | 4 | ''' This module contains the Cell class
'''
import pygame
import config
import sprites
import surface_change
import framework.animations as animations
from framework.ship import Ship
class Cell:
''' Base class for a cell
A Cell contains a part of a ship or it's empty, can contain a mine as well (SPRINT 3)
this class is meant to be used together with the Board class
example of a placed ship:
image_set = [U, #, ^]
^ <- prow | image_index = 2 | ship_part = 3
# <- deck | image_index = 1 | ship_part = 2
# <- deck | image_index = 1 | ship_part = 1
U <- stern | image_index = 0 | ship_part = 0
'''
def __init__(self, ship = None, image_index = 0, ship_part = 0, rotation = 0):
'''
:param ship (Ship): the reference to the ship that stands on this cell
:param image_index (int): index for the image to use in the ship.image_set
:param ship_part (int): what part of the ship is on this cell (0 is the part furthest back of the ship (the stern))
:param rotation (int): the rotation of the ship image
'''
self.ship = ship
self.image_index = image_index
self.ship_part = ship_part
self.rotation = rotation
self.hit = False
self._fire_anim = animations.Fire()
self._explotion_anim = animations.Explosion()
self._water_splash_anim = animations.WaterSplash()
self._ship_sunken_explosion = False
def shoot_at(self) -> bool:
''' Shoot at this cell
:returns: the ship placed on this cell if there is one otherwise None
:rtype: Ship
'''
self.hit = True
# the ship that was standing on this cell will take damage, if any
if self.ship is not None:
self.ship.hit(self.ship_part)
return True
else:
return False
def update(self, delta_time) -> None:
''' Updates all animation in this cell, if any
:param delta_time (int): the time since last frame
:returns: NoReturn
:rtype: None
'''
# no need to update any animation if the cell doesn't contain a ship or if the cell have not been shot at
if self.hit:
# explosion animation
if self.ship is not None:
# update explosion
if not self._explotion_anim.done:
self._explotion_anim.update(delta_time)
# update fire
self._fire_anim.update(delta_time)
if self.ship.have_sunken and not self._ship_sunken_explosion:
self._ship_sunken_explosion = True
self._explotion_anim = animations.Explosion()
else:
# update water splash
if not self._water_splash_anim.done:
self._water_splash_anim.update(delta_time)
def draw(self, position) -> None:
''' Draws everything that's in this cell
:param position (tuple[int,int]): where to draw the Cell
:returns: NoReturn
:rtype: None
'''
x = position[0]
y = position[1]
# draw cell boarder img 50x50
config.window.blit(sprites.img_cell, (x, y))
# TODO: draw explosion and fire animation if hit
if self.ship != None: # if it's a cell on this cell
img = pygame.transform.rotate(self.ship.image_set[self.image_index], self.rotation)
# draw ship image
if self.hit: # hit, draw the ship part red
config.window.blit(surface_change.colorize(img, (150, 0, 0)), (x, y))
else: # not hit, draw the ship part normally
config.window.blit(img, (x, y))
elif self.hit: # not a ship part, draw miss marker if hit
config.window.blit(sprites.img_missmarker, (x+1, y+1))
self._draw_animations(position)
def draw_enemy(self, position) -> None:
''' Draws hit/miss but not the ship
:param position (tuple[int,int]): where to draw the Cell
:returns: NoReturn
:rtype: None
'''
x = position[0]
y = position[1]
# draw cell boarder img 50x50
config.window.blit(sprites.img_cell, (x, y))
# draw hitmarker after shot
if self.hit:
# TODO: if the ship is hit draw a destroyed sprite
if self.ship != None: # Hit
config.window.blit(sprites.img_hitmarker, (x+1, y+1))
#pygame.draw.rect(config.window, (0, 100, 70), (x+1, y+1, 40, 40))
elif self.ship == None: # Miss
config.window.blit(sprites.img_missmarker, (x+1, y+1))
#pygame.draw.rect(config.window, (100, 30, 30), (x+1, y+1, 40, 40))
self._draw_animations(position)
def _draw_animations(self, position):
x = position[0]
y = position[1]
if self.hit:
if self.ship is not None:
# fire anim
self._fire_anim.draw((x - 25, y - 25))
self._fire_anim.draw((x - 13, y - 18))
# explosion anim
if not self._explotion_anim.done:
self._explotion_anim.draw((x - 76, y - 76))
else:
# update water splash
if not self._water_splash_anim.done:
self._water_splash_anim.draw((x-30, y-25)) |
0ed789707b311da154308a4c38bca69fe5e72024 | Naouali/Leetcode_Python | /climbing_stairs.py | 213 | 4.15625 | 4 | #!/usr/bin/python3
def staire(n):
step = n
value = 0
while n > 0:
n = n - 2
if n < 0:
break
value += 1
return value + step
print(staire(3))
print(staire(3))
|
1bb4c706d97354ed070ef1a4faaaf80a79025a7d | patfennemore/python_fundamentals-master | /03_more_datatypes/3_tuples/03_14_list_of_tuples.py | 526 | 4.1875 | 4 | '''
Write a script that takes a string from the user and creates a list of tuples with each word.
For example:
input = "hello world"
result_list = [('h', 'e', 'l', 'l', 'o'), ('w', 'o', 'r', 'l', 'd')]
'''
user_input = input("Please type a sentence: ")
user_words = list(user_input.split())
count = 0
new_list = []
for word in user_words:
if count == 0:
new_list.append(tuple(word))
count += 1
if count >= 2:
new_list.append(tuple(word))
result_list = list(new_list)
print(result_list) |
1172494037c8e9cf99017632b2213ede06160495 | ZMbiubiubiu/FunDSA | /Python-Knowledge/Iterator_chain.py | 2,035 | 4.625 | 5 | #! /home/bingo/anaconda3/bin/python
# *- coding=utf-8 -*
__author__ = "ZzLee"
__date__ = "2019/04/27"
__mail__ = "zhangmeng.lee@foxmail.com"
"""
If you want to know more about python's iterator chains
You can see "https://dbader.org/blog/python-iterator-chains"
"""
"""
step 1 .Remove spaces
step 2. Capitalize the word
step 3. Add a '~' at the end
"""
strings = [' hello ', 'world ', 'this ', 'is']
# =================================================================
# method 1 normal method
new_strings1 = []
for word in strings:
word = word.strip()
word = word.capitalize()
word = word + '~'
new_strings1.append(word)
print(new_strings1)
"""
tips:
1.The 'travel' generator yields a single word, let’s say 'world '.
2.This “activates” the Strip generator, which processes the value
and passes it on to the next stage as word.strip() to 'world'
3.The 'world' yielded by the Strip generator gets fed immediately
into the Capitalize generator, which modifies it to 'World' and yields it again.
4. Eventually activates the Add generator, which processes the value
and passes it on to the next stage as word+"~" to 'World~'
"""
# =================================================================
# method 2 Iterator chains
def travel(seq):
for word in seq:
yield word
def Strip(seq):
for word in seq:
yield word.strip()
def Capitalize(seq):
for word in seq:
yield word.capitalize()
def Add(seq):
for word in seq:
yield word+'~'
new_strings2 = list(Add(Capitalize(Strip(travel(strings)))))
print(new_strings2)
# =================================================================
# method 3 Generator expressions
travel = (word for word in strings)
strip = (word.strip() for word in travel)
capitalize = (word.capitalize() for word in strip)
add = (word+'~' for word in capitalize)
new_strings3 = list(add)
print(new_strings3)
"""
Compared to the first method, the remaining two methods
have no buffering between the processing steps in the chain
""" |
f9be4f864022a77d1f57014cb94217e093816b3e | AndersonBatalha/Programacao1 | /Estrutura de Repetição/repeticao-02.py | 431 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 2. Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.
nome = raw_input("Nome: ")
senha = raw_input("Senha: ")
while nome == senha:
print "Nome não pode ser igual a senha."
nome = raw_input("Nome: ")
senha = raw_input("Senha: ")
else:
print "Válido."
|
c9e8c03ca6d736c987709ab0eb01c220e52651aa | JasonBenn/interview-questions | /backtracking.py | 551 | 4 | 4 | # go through a tree, put all elements at leaves of tree into a list, return the list.
class Node:
def __init__(self, value, children=[]):
self.value = value
self.children = children
def dfs(node, collected=[]):
for child in node.children:
dfs(child, collected)
# print('reached the end of', node.value, collected)
collected += [node.value]
return collected
a = Node('a')
b = Node('b')
c = Node('c', [a, b])
d = Node('d')
e = Node('e')
f = Node('f', [d, e])
g = Node('g', [c, f])
co = dfs(g)
print(co)
|
cadaf124c2337593aa1cf147e789a9d03b429f11 | veronicaerick/coding-challenges | /intersection_ll.py | 2,224 | 3.515625 | 4 | def point_of_int(l1,l2):
seen = set()
# start at head of l1
current = l1.head
while current != None:
# add each node's data to seen set,
# then move to next node
seen.add(current.data)
current = current.next
current = l2
# see if any nodes data are in seen set
while current != None:
if current.data in seen:
return current
current = current.next
return "no intersection"
def get_subsets(s):
# get everything starting at index 0
subsets = get_subsets(s[1:])
results = []
for ss in subsets:
results.append(s[0] + ss)
results.append(ss)
def sort_sorted(list1, list2):
index1 = 0
index2 = 0
results = []
while len(index1) < list1 and len(index2) < list2:
if list1[index1] < list2[index2]:
results.append(list1[index1])
index1 += 1
else:
results.append(list2[index2])
index2 += 1
results.extend(list1[index1:])
results.extend(list2[index2:])
return results
def word_occurance(string):
word_dict = {}
words = string.split()
for word in string:
word_dict[word] = 1
return word_dict
def reverse_string_inplace(string):
length = len(string)
string = list(string)
for i in range(length(string)):
string[i], string[i-1] = string[i-1, string[i]]
return "".join(string)
def two_sum_array(lst):
two_sum = []
for i, num1 in enumerate(lst):
for j, num2 in enumerate(lst):
if num1 + num2 == 0 and lst[i] != lst[j] and i,j not in two_sum:
two_sum.append(i,j)
return two_sum
def sum_to_k(lst, k):
sum_k = []
for i in range(len(lst)):
for j in range(len(lst) + 1):
if lst[i] + lst[j] == k:
append.sum_k(i,j)
def three_sum_k(lst,k):
int_dict = {}
int_set = ()
for i, num in enumerate(lst):
int_dict.setdefault(num, []).append[i]
for i in range(len(lst)):
for j in range(i+1, len(lst)):
difference = lst[i] - lst[j]
if k - difference in int_set:
return i,j, int_dict[k - difference][0]
|
7088fa0b488fa0bd494b404d3608bba0e34600d0 | Ubuntu18-04/py | /10d.py | 325 | 3.765625 | 4 | l=['a',0,2]
for i in l:
print(i)
try:
print("reciprocal: ",1/i )
except ZeroDivisionError as e:
print("zero can't be divided ",e)
except TypeError as e:
print("can divide only nos ",e)
except Exception as e:
print(e)
finally:
print("Iteration done") |
51e3469707f98c8f3c3b0a5ba2c9a4b02bf137e6 | HITOfficial/College | /ASD/graph_templates/Prims_MST_matrix_adjacency.py | 1,410 | 3.546875 | 4 | # Prims MST alg. returning edges representing MST of graph
# Graph representation: connected undirected graph on matrix adjacency
# complexity:
# - time O(V^2)
# - space O(V) / O(E)
def best_vertex(n, distances, visited):
lowest_dist, index = float("inf"), 0
for idx in range(n):
if visited[idx] is False and lowest_dist > distances[idx]:
lowest_dist, index = distances[idx], idx
return index
def Prims_MST_matrix_adjacency(graph):
n = len(graph)
MST_edges = []
visited = [False]*n
distances = [float("inf")]*n
distances[0] = 0
parent = [None]*n
edges = 0
while edges < n:
u = best_vertex(n, distances, visited)
visited[u] = True
# adding edges to MST, condition to do not take edge on beggining of algorithm
if parent[u] is not None:
MST_edges.append((parent[u], u))
edges += 1
for v in range(n):
if graph[u][v] != 0 and distances[v] > distances[u] + graph[u][v]:
parent[v] = u
distances[v] = distances[u] + graph[u][v]
return MST_edges
graph = [
[0, 1, 0, 0, 2, 3, 7],
[1, 0, 7, 0, 3, 0, 0],
[0, 7, 0, 6, 0, 12, 0],
[0, 0, 6, 0, 2, 0, 0],
[2, 3, 0, 2, 0, 0, 4],
[3, 0, 12, 0, 0, 0, 0],
[7, 0, 0, 0, 4, 0, 0]
]
print(Prims_MST_matrix_adjacency(graph))
|
eb25fab9ac62ff9ae06d241a5720961e2917d9c4 | vaskocuturilo/test-engineer | /base/users.py | 275 | 3.5625 | 4 | users = [
{"name": "invalid_user", "login": "admin", "password": "admin"}]
def get_user(name):
try:
return (user for user in users if user["name"] == name).next()
except:
print("\n User %s is not defined, enter a valid user.\n" % name)
|
ac9289fa1eee48b14894220b38be36926a3e496b | dbms-ops/hello-Python | /1-PythonLearning/7-面向对象/1-类的基础知识.py | 1,468 | 4.46875 | 4 | # coding=utf-8
#
#
# !/data1/Python2.7/bin/python27
#
#
# 创建一个简单额类
#
# 创建类:
# 类本身是一种数据类型,本身不占据内存。通过类是实例化的对象是占据内存空间的
# class 类名(父类列表)
# 属性
# 行为
# object 称为基类,超类,所有类的父类,没有合适的父类的时候,就是object
class Person(object):
# 定义属性:本质上就是在定义变量,这里的变量是以下的方法所公用的,特例在具体的方法中声明
name = ''
age = 10
height = 120
weight = 10
# 定义方法:定义函数
# self:必须是第一参数,代表类的实例,代表第一个对象
def run(self):
print "just run"
def eat(self, food):
"""
:param food: what you eat
"""
print "eat {}".format(food)
def drink(self, type):
"""
:param type: what kind of drink
"""
print "{} drink {}".format(self.name, type)
# 类实例化对象
# 对象名 = 类名(参数列表)
# 没有参数()不能够省略
tom = Person()
print tom, type(tom), id(tom)
jerry = Person()
print jerry, type(jerry), id(jerry)
# 访问对象的属性和方法
# 添加属性
# 对象名.属性名 = 新值
tom.name = "tom"
tom.age = 12
tom.height = 120
tom.weight = 14
print tom.name, tom.age, tom.height, tom.weight
# 访问方法
# 对象名.方法名(参数列表)
#
tom.drink("orange")
|
7f4ef5b5f880dbe5816eb5a24cd6955e3d33c9d0 | widesky867/blackjack | /player.py | 1,532 | 3.625 | 4 | # player class file, includes dealer as well
# code adapted from https://brilliant.org/wiki/programming-blackjack/
# editted to include elements of OOP as a practice
from deck import values
class player(object):
def __init__(self, name):
self.name = name
self.reset_hand()
def reset_hand(self):
self.hand = []
self.player_in = True
def deal(self, deck):
self.hand.append(deck.drawCard())
return self
def showHand(self):
for card in self.hand:
card.show()
def getScore(self):
tmp_value = sum(self.card_value(_) for _ in self.hand)
num_aces = len([_ for _ in self.hand if _.value is 'ACE'])
while num_aces > 0:
if tmp_value > 21 and 'ACE' in values:
tmp_value = tmp_value - 10
num_aces = num_aces - 1
else:
break
if len(self.hand) == 5 and tmp_value <= 21:
# conditions of LUCKYSTRIKE, 5 cards and total score <= 21
return ["LUCKYSTRIKE", tmp_value]
elif len(self.hand) == 2 and tmp_value == 21:
return ["BLACKJACK", 21]
elif tmp_value <= 21:
return [str(tmp_value), tmp_value]
else:
return ["BUST", 100]
def card_value(self, card):
# return value of a card
value = card.value
if value in values[0:-4]:
return int(value)
elif value is 'ACE':
return 11
else:
return 10
|
5a9bad9feeebdb579a7df2239d6606768dea5a8d | JonathanKutsch/Python-Schoolwork | /Labs/Lab03b/Program2.py | 1,373 | 3.578125 | 4 | # By submitting this assignment, I agree to the following:
# �Aggies do not lie, cheat, or steal, or tolerate those who do�
# �I have not given or received any unauthorized aid on this assignment�
#
# Name: Jonathan Kutsch
# Section: 514
# Assignment: Lab 3b - Program 2
# Date: 05 September 2020
import math
# t = (x, y)
t1 = float(input('Time for first point is: '))
# tested with 50 s
x1 = float(input('Initial position in the x-direction is: '))
# tested with 25 m
y1 = float(input('Initial position in the y-direction is: '))
# tested with 10 m
t2 = float(input('Time for second point is: '))
# tested with 100 s
x2 = float(input('Second position in the x-direction is: '))
# tested with 50 m
y2 = float(input('Second position in the y-direction is: '))
# tested with 25 m
velocity_x = (x2-x1) / (t2-t1)
velocity_y = (y2-y1) / (t2-t1)
print('Velocity in the x-direction is:', velocity_x, 'm/s')
# test output = 0.5 m/s
print('Velocity in the y-direction is:', velocity_y, 'm/s')
# test output = 0.3 m/s
overall_velocity = math.hypot(velocity_x, velocity_y)
print("Red's velocity is:", overall_velocity, 'm/s')
# test output = 0.58309518948453 m/s
mass = 3
kinetic_energy = (1/2 * mass * (overall_velocity ** 2))
print("Red's kinetic energy is:", kinetic_energy)
# test output = 0.5099999999999999
|
9c79432d54cf5e8f415db18223ffb421c869a176 | andy2332/Python_Study | /a_Python基础_预习/01_基础1/demo003_转义字符.py | 776 | 3.625 | 4 | # 作者:蔡不菜
# 时间:2020/10/2 13:27
# 转义字符
# \ + 转义功能的首字母 例如:\n n-->newline的首字母表示换行
print('hello\nworld') # \n 换行
print('hello\tworld') # \t tab键,水平制表符
print('helloooo\tworld') # \t tab键,占四个空格的位置
print('hello\rworld') # \r 回车键,world将hello进行了覆盖
print('hello\bworld') # \b 退格,将o退没了
print('http:\\\\www.baidu.com') # \\ 表示斜杠 \\\\ 表示双斜杠
print('小明说:\'我吃饱了!\"') # \' 单引号 \" 双引号
# 原字符,不希望字符串中的转义字符起作用,就使用原字符,就是在字符串之前加上r或R
print(r'hello\tworld')
# 注意:最后一个字符不能是反斜杠
# print(R'helloworld\')
|
63c5a52c01bb03be5d02199624884439ccadd1b7 | Naveen479/python | /square_root.py | 189 | 4.125 | 4 | #!/usr/bin/python
import math
def main():
number = float(raw_input('enter the number'))
square_root = math.sqrt(number)
print('the square root of', number, 'is', square_root)
main()
|
33aa92c46f935638bacf693158f1f508e37680c3 | 1306298019/YOLOV4 | /rename.py | 694 | 3.765625 | 4 |
import os
import sys
def rename():
path=input("请输入路径(例如D:\\\\picture):")
name=input("请输入开头名:")
startNumber=input("请输入开始数:")
fileType=input("请输入后缀名(如 .jpg、.txt等等):")
print("正在生成以"+name+startNumber+fileType+"迭代的文件名")
count=0
filelist=os.listdir(path)
for files in filelist:
Olddir=os.path.join(path,files)
if os.path.isdir(Olddir):
continue
Newdir=os.path.join(path,name+str(count+int(startNumber))+fileType)
os.rename(Olddir,Newdir)
count+=1
print("一共修改了"+str(count)+"个文件")
rename() |
4f591116d4a8776ad95033529e7d43352bf26e8e | bojanabj/programiranje | /domzad.py | 1,708 | 3.765625 | 4 | class krug:
def __init__(self, poluprecnik):
self.poluprecnik = poluprecnik
def obimkruga(self, obim):
return f"obim kruga je {obim}"
def povrsinakruga(self, povrsina):
return f"povrsina kruga je {povrsina}"
class pravougaonik:
def __init__(self, a, b):
self.a = a
self.b = b
def obimpravougaonika(self, obim):
return f"obim pravougaonika je {obim}"
def povrsinapravougaonika(self, povrsina):
return f"povrsina pravougaonika je {povrsina}"
class kvadrat:
def __init__(self, a):
self.a = a
def obimpravougaonika(self, obim):
return f"obim kvadrata je {obim}"
def povrsinapravougaonika(self, povrsina):
return f"povrsina kvadrata je {povrsina}"
if __name__ == '__main__':
poluprecnikkruga = float(input("Unesite poluprecnik kruga: "))
krug = krug(poluprecnikkruga)
obimkr = (2*krug.poluprecnik)*3.14
print(krug.obimkruga(obimkr))
povrsinakr = (krug.poluprecnik*krug.poluprecnik)*3.14
print(krug.povrsinakruga(povrsinakr))
a = float(input("Unesite stranicu a pravouganika: "))
b = float(input("Unesite stranicu b pravouganika: "))
pravougaonik = pravougaonik(a, b)
obimp = 2*(pravougaonik.a+pravougaonik.b)
print(pravougaonik.obimpravougaonika(obimp))
povrsinap = pravougaonik.a*pravougaonik.b
print(pravougaonik.povrsinapravougaonika(povrsinap))
ak = float(input("Unesite stranicu kvadrata: "))
kvadrat = kvadrat(a)
obimkv = 4 * kvadrat.a
print(kvadrat.obimpravougaonika(obimkv))
povrsinakv = kvadrat.a * kvadrat.a
print(kvadrat.povrsinapravougaonika(povrsinakv)) |
0f8af37f250c1eecc3572127f372abf02790cd4b | sudheeramya/python | /ifelseconditon4.py | 133 | 3.640625 | 4 | is_hot = False
is_cold = True
if is_hot:
print('It is Summer')
elif is_cold:
print ('It is Cold')
print('It is ENJOY DAY ')
|
d2f58f99eb8fda49cbfbce11c65210cd3f0568f2 | bajpaigaurav/python | /someexamples.py | 709 | 3.84375 | 4 | # prime
def isprime(n):
return (factors(n) == [1,n])
def factors(n):
flist = []
for i in range(1,n+1):
if n%i==0:
flist = flist + [i]
return flist
print(isprime(10))
print(isprime(11))
# primes upto n
def primesupto(n):
primelist = []
for i in range(1,n+1):
if isprime(i):
primelist = primelist + [i]
return primelist
print(primesupto(20)) # very slow for this 2000000
# first n primes
def nprimes(n):
(count,i,plist) = (0,1,[])
while(count<n):
if isprime(i):
(count,plist)=(count+1,plist+[i])
i=i+1
return (plist)
print(nprimes(200)) # very slow for this 2000000
# simulate for with while
|
0d97fafb7b34b3ecd10cc1cbfe4d0c8c8dc8597a | WayneChen1994/Python1805 | /day13/多继承.py | 1,373 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Wayne
'''
多继承:
1、子类可以继承多个父类中的属性以及方法
2、一个子类可以有多个父类,一个父类也可以有多个子类
3、当一个子类继承多个父类的时候,多个父类中出现同名方法
子类使用此方法的时候,调用的是写在小括号里面,
最前面那个拥有此方法的类中的方法。
【小括号中写在前面的优先级高于后面的】
'''
class GrandFather:
def dance(self):
print("广场舞。。。")
class Father(GrandFather):
def __init__(self, name, money):
self.name = name
self.money = money
def drive(self):
print("开车。。。")
def sing(self):
print("娘子,啊哈。。。")
class Mother:
def __init__(self, name, faceValue):
self.name = name
self.faceValue = faceValue
def sing(self):
print("唱歌。。。")
def dance(self):
print("恰恰。。。")
class Chind(Father, Mother):
def __init__(self, name, money, faceValue):
Father.__init__(self, name, money)
Mother.__init__(self, name, faceValue)
if __name__ == "__main__":
child1 = Chind("小明", 100000000, 90)
print(child1.faceValue)
child1.sing()
child1.dance()
child1.drive()
print(child1.money)
|
c11fc3e38dd194c694ab9f9de7224f6c1e611a8f | deanMike/TitanicPrediction | /Python/PredictionFinalTitanic/PredictionFinalTitanic/genderModel.py | 842 | 3.5 | 4 | import csv as csv ## Allows for the use and manipulation of csv files.
import numpy as np ## Numpy allows for statistical analysis.
csvFile = open('../data/test.csv', 'rb')
csvFileObject = csv.reader(csvFile)
headerTest = csvFileObject.next()
predictionFile = open('../output/genderbasedmodel.csv', 'wb')
predictionFileObject = csv.writer(predictionFile)
predictionFileObject.writerow(["PassengerId", "Survived"])
for row in csvFileObject: # For each row in test.csv
if row[3] == "female": # is it a female, if yes then
predictionFileObject.writerow([row[0],'1']) # predict 1
else: # or else if male,
predictionFileObject.writerow([row[0],'0']) # predict 0
predictionFile.close()
csvFile.close()
|
cab3b2e375eaef512e037d2ea0e1131d60ad4090 | hannesSimonsson/advent_of_code_2020 | /day5/day5_2.py | 1,062 | 3.765625 | 4 | '''
--- Part Two ---
Ding! The "fasten seat belt" signs have turned on. Time to find your seat.
It's a completely full flight, so your seat should be the only missing boarding pass in your list. However, there's a catch: some of the seats at the very front and back of the plane don't exist on this aircraft, so they'll be missing from your list as well.
Your seat wasn't at the very front or back, though; the seats with IDs +1 and -1 from yours will be in your list.
What is the ID of your seat?
'''
from day5_1 import binaryConversion
# get input
with open("input_day5.txt") as f:
inputs = f.read().splitlines()
# calculate seat ID and remove it from the full list of possible IDs
seatIDs = list(range(0, 1023))
for seat in inputs:
seatID = binaryConversion(seat[:7]) * 8 + binaryConversion(seat[-3:])
if seatID in seatIDs:
seatIDs.remove(seatID)
# check all remaining IDs in order, if break in list -> next ID should be the one we want
noID = 0
for ID in seatIDs:
if noID != ID:
print(ID)
break
noID += 1
|
c54ec84dfd88fa66d632da7e3d31bdd4105cd87d | youikim/algorithms | /basicSort/checkSort.py | 255 | 3.734375 | 4 | def checkSort(a, n):
isSorted=True
for i in range(1, n):
if (a[i] > a[i+1]):
isSorted = False
if (not isSorted):
break
if isSorted:
print("정렬 완료")
else:
print("정렬 실패") |
0419d3c29b2374358b07233c2ac2584aa51d9234 | DanielDuchnicki/ProjektPythonIMGW | /count_temperature.py | 1,999 | 3.71875 | 4 | from datetime import timedelta, date
def first_days_of_seasons(database):
"""Funkcja zwraca średnie temperatury dla pierwszego dnia wiosny, lata, jesieni i zimy
:param database: object of DatabaseReader class
:return: temperatures: dictionary in format {'dd/mm': mean_temperature}
"""
dates = ["21/03", "22/06", "23/09", "22/12"]
temperatures = {}
for next_date in dates:
temperatures[next_date] = count_mean_temperature(next_date, database)
return temperatures
def weather_forecast(database):
"""Funkcja zwraca prognozę pogody dla dwóch kolejnych dni, korzystając z metody klimatycznej
:param database: object of DatabaseReader class
:return: dictionary in format {'dd/mm': mean_temperature}
"""
tomorrow_date = date.today() + timedelta(days=1)
tomorrow = translate_date(tomorrow_date)
day_after_tomorrow_date = tomorrow_date + timedelta(days=1)
day_after_tomorrow = translate_date(day_after_tomorrow_date)
return {'tomorrow': count_mean_temperature(tomorrow, database), 'day after tomorrow': count_mean_temperature(day_after_tomorrow, database)}
def count_mean_temperature(given_date, database):
"""
:param given_date: date in string format - 'dd/mm'
:param database: object of DatabaseReader class
:return: mean_temperature
"""
temperatures = [float(temp) for temp in database.get_temperatures(given_date).values()]
mean_temperature = sum(temperatures)/len(temperatures)
return mean_temperature
def translate_date(given_date):
"""
:param given_date: date in datetime format - datetime.date(yyyy, mm, dd)
:return: day_month: date in string format - 'dd/mm'
"""
month = given_date.month
day = given_date.day
if month < 9:
month_str = '0' + str(month)
else:
month_str = str(month)
if day < 9:
day_str = '0' + str(day)
else:
day_str = str(day)
day_month = day_str + '/' + month_str
return day_month
|
47e8fbdaf3fa8dc4b1809dfe24d4ab7c7e4d7a93 | RyanPennell/6.001.x | /DealWithHands.py | 896 | 3.765625 | 4 | import words.txt
f = open('words.txt', 'r')
content = f.read()
hand = {'h':1, 'e':1, 'l':2, 'm':1, 'o':1, 'i':1}
def updateHand(hand, word):
""" function takes random hand given by program and a word chosen by player and checks if the word is in the
txt file. If the word is in the txt file then the funtion checks if the letters in the word are in the hand.
If the letters are in the hand, function checks if player has a letters needed if duplicates are needed using
keys.
"""
if word.upper() in content:
for letter in word:
if letter in hand:
handcopy = hand.copy()
for letter in word:
if letter in handCopy.keys():
handCopy[letter] -=1
return handCopy
else: return 'nope'
|
a0f97a4e1e625f128e370374d3a7ce69024043dc | Lyl571297371/Python-Learning | /6.27-7.3/Exercise.4.10.py | 391 | 3.796875 | 4 | #coding:gb2312
#Ԫϰ
fruits=("apple","banana","peach","strawberry","orange\n\n")
print("Original items :")
for fruit in fruits:
print(fruit)
#fruits[0]=watermelon
#print(fruits) #ԪԪDZֹ
fruits=("litchi","banana","peach","pear","orange") #ˮ
print("Modified items :")
for fruit in fruits:
print(fruit)
|
c1deddd6f020199f490480f9e0ee8ef135fe4a23 | LorenzoChavez/CodingBat-Exercises | /Logic-1/love6.py | 334 | 3.953125 | 4 | # The number 6 is a truly great number.
# Given two int values, a and b, return True if either one is 6.
# Or if their sum or difference is 6. Note: the function abs(num) computes the absolute value of a number.
def love6(a, b):
sums = a + b
diff = abs(a - b)
if 6 in [a,b,sums,diff]:
return True
else:
return False
|
100a480353fc0eeae4d5a79860ab3258d176eb18 | lucas2396/Tic-Tac-Toe | /main.py | 2,307 | 3.796875 | 4 | if __name__ == '__main__':
ttt = ""
winners = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
game_active=False
draw=True
while True:
if not game_active:
init=input("Welcome to Tic Tac Toe, enter p to play or q to quit\n")
if init=="p":
game_active = True
count = 0
player1 = True
position = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
elif init=="q":
break
else:
print("Wrong choice \n")
if game_active:
if draw:
game_init=True
count+=1
if game_init:
game_init=False
if player1:
fill_grid="X"
player="Player 1"
player1=False
else:
fill_grid="0"
player = "Player 2"
player1=True
if count==1:
PlayerInput=input("{} input a position:\n1|2|3\n4|5|6\n7|8|9\n".format(player))
else:
PlayerInput = input("{} input a position:".format(player))
try:
if position[int(PlayerInput)-1]==" ":
position[int(PlayerInput)-1]=fill_grid
draw=True
else:
print("position already taken, please try again")
draw=False
except:
print("Please enter a correct value")
draw = False
if draw:
for i in range(3):
for j in range(3):
ttt += "|" + position[i*3 +j]
ttt+="|\n"
print(ttt)
for three in winners:
if position[three[0]]==position[three[1]]==position[three[2]] and position[three[0]]!=" ":
print("{} won!".format(player))
game_active = False
if count==9 and game_active:
print("No one win")
game_active = False
|
482e5d0a8a5d51f7ac353bfba37c901fde4aee12 | TirumalaKrishnaMohanG/Codeforces | /24A.py | 373 | 3.515625 | 4 | #!/usr/bin/env python
# Heders
import os
# Input
n = int(input())
k = [int(x) for x in input().split()]
e,o =[],[]
even,odd = 0,0
# Finding the odd one in list
for i in k:
if i%2 == 0:
e.append(str(k.index(i)))
elif i%2 == 1:
o.append(str(k.index(i)))
if len(o) <= 1:
val = int(''.join(o))+1
print(val)
elif len(e) <= 1:
val = int(''.join(e))+1
print(val)
|
65e24136296f0cb51327965028b85f5f1b930e7b | kyranyerkin/pp2 | /week3/9.py | 80 | 3.640625 | 4 | n=int(input())
sum=0
for i in range(n):
a=int(input())
sum+=a
print(sum) |
c3194601d7cc89a69b5509ff3a350d741a9cb1af | joongsup/merely-useful.github.io | /zipfs-law/bin/collate.py | 1,001 | 3.984375 | 4 | #!/usr/bin/env python
'''
Read one or more CSV files given as command-line arguments, or standard input if
no filenames are given, and produce a collated two-column CSV of words and
counts.
'''
import sys
import csv
from collections import Counter
def main(filenames):
'''
Read standard input or one or more files and report results.
'''
results = Counter()
if not filenames:
process(sys.stdin, results)
else:
for fn in filenames:
with open(fn, 'r') as reader:
process(reader, results)
report(sys.stdout, results)
def process(reader, results):
'''
Extract and count words from stream.
'''
for (word, count) in csv.reader(reader):
results[word] += int(count)
def report(writer, results):
'''
Report results to stream.
'''
writer = csv.writer(writer)
for (key, value) in results.items():
writer.writerow((key, value))
if __name__ == '__main__':
main(sys.argv[1:])
|
d96a20a677951a2ea57f2b2151dacbc365ebcc95 | KevTiv/delivery_management_system_wgu_C950 | /chaining.py | 2,745 | 4.15625 | 4 | # Name : Kevin Tivert
# Student ID: 001372496
# Use of hashtable to store necessary data
# O(n)
class Chaining(object):
# Constructor
# Constructor with predefine storage capacity
# Assigns all buckets with an empty list.
# O(1)
def __init__(self, inital_storage=10):
# initialize the hash table with empty bucket list entries.
self.table = []
for i in range(inital_storage):
self.table.append([])
# Assign a new item
# Function will first determine the length of the current list then
# assign the new object at the end of the existing bucket list or
# create a new bucket list.
# O(1)
def insert(self, item):
bucket = hash(item) % len(self.table)
bucket_list = self.table[bucket]
# Assign the item to the end of the bucket list.
bucket_list.append(item)
# Searches for item with same key in the hash table and return result
# Similar as the insert () function this function will first determine
# the size of the list and using a loop, the function will go through the
# list and compare every single object until one matches our search object
# or will return none
# O(n)
def search(self, key):
bucket = hash(key) % len(self.table)
bucket_list = self.table[bucket]
# search key in the bucket list
if key in bucket_list:
# find the item's index and return the item that is in the bucket list.
item_index = bucket_list.index(key)
return bucket_list[item_index]
else:
# No key found
print("No Result")
return None
# Remove an item with same key from the hash table.
# The function will first determine the size of the list, go through the list
# using a loop and compare object in the list with the given object (key) the
# function has to remove. If the key is found in the list, it will be removed
# but if it is not found the function will go through the list and end.
# O(n)
def remove(self, key):
bucket = hash(key) % len(self.table)
bucket_list = self.table[bucket]
# remove the item from the bucket list if it is found
if key in bucket_list:
bucket_list.remove(key)
# Overloaded string conversion method to create a strings that represent the hashtable
# bucket in the hastable is shown as a pointer to a list object.
# O(1)
def __str__(self):
index = 0
wrd = " -----\n"
for bucket in self.table:
wrd += "%2d:| ---|-->%s\n" % (index, bucket)
index += 1
wrd += " -----"
return wrd |
2994cba93565a63804f7e05d9c2a9b7c48c911be | MelvinDunn/Algorithm_Implementations | /algorithms/algorithms/ridge.py | 1,896 | 3.9375 | 4 | import numpy as np
from sklearn.datasets import load_iris
"""
ridge_value is lambda in Hastie text.
This monotone decreasing function of λ is the effective degrees of freedom
of the ridge regression fit. Usually in a linear-regression fit with p variables,
the degrees-of-freedom of the fit is p, the number of free parameters. The
idea is that although all p coefficients in a ridge fit will be non-zero, they
are fit in a restricted fashion controlled by λ. Note that df(λ) = p when
λ = 0 (no regularization) and df(λ) → 0 as λ → ∞. Of course there
is always an additional one degree of freedom for the intercept, which was
removed apriori. This definition is motivated in more detail in Section 3.4.4
and Sections 7.4–7.6. In Figure 3.7 the minimum occurs at df(λ) = 5.0.
Table 3.3 shows that ridge regression reduces the test error of the full least
squares estimates by a small amount.
http://statsmaths.github.io/stat612/lectures/lec17/lecture17.pdf :
Ordinary least squares and ridge regression have what are called
analytic solutions, we can write down an explicit formula for what
the estimators are.
"""
def main(X, y, ridge_value=0.1):
#Taken from figure 3.47 of elements of statistical learning by Hastie.
lambda_I = np.identity(X.shape[1]) * ridge_value
return np.dot(np.dot(np.linalg.inv(np.dot(data.T, data)+lambda_I), data.T), y)
def rss(residuals):
return np.sum(residuals) ** 2
if __name__ == "__main__":
data = (load_iris()["data"])
original_data = data.copy()
y = (load_iris()["target"])
intercept = np.ones((data.shape[0],1))
data = np.column_stack((intercept, data))
#shrinkage doesn't work without an intercept. lesson learned, it would seem.
print(main(data,y,0.0001))
print(main(data,y,0.001))
print(main(data,y,0.1))
print(main(data,y,0.7))
print(main(data,y,0.8))
print(main(data,y,0.95))
|
ced4ba754a59e66a5707df5642ac3e89467a1d2c | C-TAM-TC1028-003-2113/tarea-1-OswaldoSobrevilla | /assignments/19Editorial/src/exercise.py | 338 | 3.734375 | 4 | def main():
# escribe tu código abajo de esta línea
palabras = float(input("Dame el número de palabras: "))
b = (palabras//475)*60
c = palabras%475
if 1<=c:
d=60
x = (b+d)
total = (x-(x*10/100))
print("El costo de la publicación es:", total)
if __name__ == '__main__':
main()
|
01a752d13c0a72b7e9f6ecdb4d818f5472068639 | urnotzdy/python | /list.py | 1,183 | 3.5 | 4 | #使用[]表示列表
names=["zdy","xyh","zs"]
print(names[0]+"\n"+names[1]+"\n"+names[2])
print("----"+names[2])
names[2]="ls"
print(names[0]+"\n"+names[1]+"\n"+names[2])
print("---------------")
#a.insert(索引,值)在列表中插入值
#append在末尾追加
names.insert(0,"kt")
names.insert(2,"zj")
names.append("mw")
print(names)
print("--------------")
#使用-1 -2表示倒第几个
print(names.pop(-1))
print(names.pop(-1))
print(names.pop(-1))
print(names.pop(-1))
print(names)
print('------------')
#删除 del a[1]
#删除并使用 a.pop(1)
#删除末尾 a.pop()
#删除某值 a.remove(val)
del names[1]
print(names)
names.remove('kt')
print(names)
names=["zdy","xyh","zs"]
#对列表进行永久性排序 a.sort()
#倒排 a.sort(reverse=True)
#临时性排序 sorted(a)
#临时排序,倒排 sorted(a,reverse=True)
names.sort()
print(names)
names.sort(reverse=True)
print(names)
print('----')
print(sorted(names))
print(names)
print('----')
print(sorted(names,reverse=True))
print('=====')
#reverse永久性反转
names.reverse()
print(names)
print(names.reverse())
#len(a) 列表的长度
print(len(names))
print("*"*100)
yuanzu= (1,2,3)
zidian = {'1':'a'}
|
e12def3cc7bdde13afb873da8a4cac930a300dab | sainihimanshu1999/Interview-Bit | /LEVEL 6/Trees/validpreordertraversal.py | 504 | 3.859375 | 4 | class Solution:
def BSTfromPreorder(self,A):
root = float('-infinity')
stack = []
for i in range(len(A)):
if A[i]<root:
return 0
if(stack and stack[-1]<A[i]):
root = stack.pop()
stack.append(A[i])
return 1
'''
In Pre order traversal, if we encounter any number greater than root or current node then every
item we encounter should be greater than root or current node then return 1 else return 0
''' |
1b8b386e628c329ca03f2a3227eef4948df9e7d9 | mohammedtarekk/2d-maze-solver-using-bfs-python | /2D Maze Solver.py | 7,334 | 3.84375 | 4 | # region BFSSearchAlgorithms
class Node:
id = None
up = None
down = None
left = None
right = None
previousNode = None
def __init__(self, value):
self.value = value
class SearchAlgorithms:
path = [] # Represents the correct path from start node to the goal node.
fullPath = [] # Represents all visited nodes from the start node to the goal node.
board = [[]] # Represents the 2D board
rows_count = 0 # Number of rows in maze
cols_count = 0 # Number of columns in maze
def __init__(self, mazeStr):
''' mazeStr contains the full board
The board is read row wise,
the nodes are numbered 0-based starting
the leftmost node'''
self.mazeStr = mazeStr
# This function calculates the number of rows and columns in the maze
def GetCountOfColsAndRows(self):
x = 0
while x != len(self.mazeStr):
if self.mazeStr[x] == ' ':
self.rows_count += 1
x += 1
self.rows_count += 1
x = 0
while self.mazeStr[x] != ' ':
if self.mazeStr[x] == ',':
self.cols_count += 1
x += 1
self.cols_count += 1
# This function converts the maze string to a 2D board
def CreateBoard(self):
self.board = [x.split(',') for x in self.mazeStr.split(' ')]
# This function converts the board char elements to nodes and give every node an id
# id is given to each node as it's the index of this node in a virtual 1D array "output constraint"
def CreateNodes(self):
self.GetCountOfColsAndRows()
avail_id = 0
for row in range(self.rows_count):
for col in range(self.cols_count):
self.board[row][col] = Node(self.board[row][col])
self.board[row][col].id = avail_id
avail_id += 1
# This function initializes every node neighbors "up, down, left, right"
def InitializeNeighbors(self):
for row in range(self.rows_count):
for col in range(self.cols_count):
if self.board[row - 1][col].value != '#' and (row - 1) >= 0:
self.board[row][col].up = self.board[row][col].id - self.cols_count
if (row + 1) < self.rows_count:
if self.board[row + 1][col].value != '#':
self.board[row][col].down = self.board[row][col].id + self.cols_count
if self.board[row][col - 1].value != '#' and (col - 1) >= 0:
self.board[row][col].left = self.board[row][col].id - 1
if (col + 1) < self.cols_count:
if self.board[row][col + 1].value != '#':
self.board[row][col].right = self.board[row][col].id + 1
# IMPLEMENTATION OF BFS ALGORITHM
def BFS(self):
# ---------- [1] Initializing the board and nodes -----------
self.CreateBoard()
self.CreateNodes()
self.InitializeNeighbors()
# Find the start node
for i in range(self.rows_count):
for j in range(self.cols_count):
if self.board[i][j].value == 'S':
start_node = self.board[i][j] # StartNode 'S'
# -----------------------------------------------------------
# --------- [2] Initializing the lists used in BFS ---------
visited = []
not_visited = [start_node]
# -----------------------------------------------------------
# --------- [3] SEARCHING FOR THE GOAL NODE AS WELL AS TRACKING ITS FULL & SHORTEST PATH ---------
while not_visited: # while not_visited list is not empty
current_node = not_visited.pop(0) # getting the first node in the list
visited.append(current_node.id) # appending its id to the visited list "MAKE IT VISITED"
if current_node.value == 'E': # if the goal node is reached, then save its path and break
self.fullPath = visited
break
# these 4 blocks explore the current node VALID Neighbours "UP, DOWN, LEFT, RIGHT":
# [1] check if the up neighbour is valid and not visited yet
# [2] if valid, get it from the 2D board
# [3] then check if it exists in not_visited list or not, to prevent repeating nodes in the path
# [4] if not existed in not_visited list, add it
# [5] then save its previous node, to keep track for the shortest path
if current_node.up is not None and current_node.up not in visited:
for i in range(self.rows_count):
for j in range(self.cols_count):
if self.board[i][j].id == current_node.up:
if self.board[i][j] not in not_visited:
not_visited.append(self.board[i][j])
self.board[i][j].previousNode = current_node
break
if current_node.down is not None and current_node.down not in visited:
for i in range(self.rows_count):
for j in range(self.cols_count):
if self.board[i][j].id == current_node.down:
if self.board[i][j] not in not_visited:
not_visited.append(self.board[i][j])
self.board[i][j].previousNode = current_node
break
if current_node.left is not None and current_node.left not in visited:
for i in range(self.rows_count):
for j in range(self.cols_count):
if self.board[i][j].id == current_node.left:
if self.board[i][j] not in not_visited:
not_visited.append(self.board[i][j])
self.board[i][j].previousNode = current_node
break
if current_node.right is not None and current_node.right not in visited:
for i in range(self.rows_count):
for j in range(self.cols_count):
if self.board[i][j].id == current_node.right:
if self.board[i][j] not in not_visited:
not_visited.append(self.board[i][j])
self.board[i][j].previousNode = current_node
break
# ------------------------------------------------------------------------------------------------
# --------------- [4] GENERATE SHORTEST PATH ------------------
while current_node.value != 'S':
self.path.append(current_node.id)
current_node = current_node.previousNode
self.path.append(current_node.id)
self.path.reverse()
# -------------------------------------------------------------
return self.fullPath, self.path
# endregion
######################## MAIN ###########################
if __name__ == '__main__':
searchAlgo = SearchAlgorithms(input("Enter your 2D maze: "))
fullPath, path = searchAlgo.BFS()
print('**MAZE SOLUTION**\n Full Path is: ' + str(fullPath) + "\n Path: " + str(path))
|
c1608262ac135469dce203ccc4a87994d100bd53 | ltrzalez/py4e | /02ejecucion_condicional.py | 3,697 | 4.40625 | 4 |
# *condicional
# """ Ejecucion condicional """
""" usaremos la palabra reservada if, elif, para que python tome 'decisiones'
al chekiar si una condicion es verdadera o falsa """
""" Tipo de dato Booleano, pueden ser Verdadeo o falso """
# print(5 == 5)
# True
# print(5 == 6)
# False
""" operadores de comparacion """
# x != y # x es distinto de y
# x > y # x es mayor que y
# x < y # x es menor que y
# x >= y # x es mayor o igual que y
# x <= y # x es menor o igual que y
# x is y # x es lo mismo que y
# x is not y # x no es lo mismo que y
""" Operadores lógicos
Existen tres operadores lógicos: and (y), or (o), y not (no). El significado
semántico de estas operaciones es similar a su significado en inglés.
"""
# suponer valores de las variables para entender cuando son verdaros o falso
# x > 0 and x < 10
# n%2 == 0 or n%3 == 0
# not (x > y)
""" una simple """
# if x > 0 :
# print('x es positivo')
""" tomamos un solo camino cada vez que chekiamos la condicion. Hablar de la importancia de la identacion """
# x = 5
# if x < 18:
# print('menor')
# if x > 18:
# print('adulto')
""" dos deciciones. Else y porque no lleva parametro de condicional """
# if x%2 == 0 :
# print('x es par')
# else :
# print('x es impar')
""" condicionales encadenados """
# if x < y:
# print('x es menor que y')
# elif x > y:
# print('x es mayor que y')
# else:
# print('x e y son iguales')
""" condicionales anidados y mas identacion """
# if 0 < x:
# if x < 10:
# print('x es un número positivo con un sólo dígito.')
# if x == y:
# print('x e y son iguales')
# else:
# if x < y:
# print('x es menor que y')
# else:
# print('x es mayor que y')
""" varios caminos de decicion elif y la no utilizacion de else y la importancia del orden """
# agregar variante que falta para que funcione
# if choice == 'a':
# print('Respuesta incorrecta')
# elif choice == 'b':
# print('Respuesta correcta')
# elif choice == 'c':
# print('Casi, pero no es correcto')
""" try and except y operador ternario """
# ent = input('Introduzca la Temperatura Fahrenheit:')
# try:
# fahr = float(ent)
# cel = (fahr - 32.0) * 5.0 / 9.0
# print(cel)
# except:
# print('Por favor, introduzca un número la proxima vez')
# try:
# print('x' if True else 'nada')
# except:
# pass
""" operador ternario en js """
# try{
# console.log(true ? 'x' : 'nada')
# }
# catch{
# console.log('error')
# }
""" ejercicios
Ejercicio 1: Reescribe el programa del cálculo del salario para darle al empleado
1.5 veces la tarifa horaria para todas las horas trabajadas que excedan de 40.
Introduzca las Horas: 45
Introduzca la Tarifa por hora: 10
Salario: 475.0 a dasd
Ejercicio 2: Reescribe el programa del salario usando try y except, de modo que el
programa sea capaz de gestionar entradas no numéricas con elegancia, mostrando
un mensaje y saliendo del programa. A continuación se muestran dos ejecuciones
del programa:
Introduzca las Horas: 20
Introduzca la Tarifa por hora: nueve
Error, por favor introduzca un número
Introduzca las Horas: cuarenta
Error, por favor introduzca un número
Ejercicio 3: Escribe un programa que solicite una puntuación entre 0.0 y 1.0. Si la
puntuación está fuera de ese rango, muestra un mensaje de error. Si la puntuación
está entre 0.0 y 1.0, muestra la calificación usando la tabla siguiente:
"""
precio = 10
precio_ex = 15
try:
horas = int(input('Ingrese cantidad de horas: '))
if horas > 40:
print((horas - 40) * precio_ex)
else:
print((horas)*(precio))
except:
print('Introduzca un numero por favor') |
9976f09ae7f6eb8d6486c8fea5ab8968314e5d5c | huilizhou/Leetcode-pyhton | /algorithms/901-/1137.n-th-tribonacci-number.py | 568 | 3.515625 | 4 | # 第N个泰波那契数
class Solution(object):
def tribonacci(self, n):
"""
:type n: int
:rtype: int
"""
# ans = [0, 1, 1]
# if n < 3:
# return ans[n]
# for i in range(3, n + 1):
# ans.append(ans[i - 3] + ans[i - 2] + ans[i - 1])
# return ans[n]
result = [0] * 38
result[0] = 0
result[1] = 1
result[2] = 1
for i in range(3, 38):
result[i] = sum(result[i - 3:i])
return result[n]
print(Solution().tribonacci(4))
|
380de0421c6dddf1a4991f2169999e139f8e24e1 | implse/Dynamic_Programming | /Code/DP_makeChange.py | 1,785 | 3.75 | 4 | # Given an integer representing a specific amount of change and a set of coin sizes,
# determine the minimum number of coins required to make that amount of change.
# You may assume there is always a 1 cent coin.
# coins = (1, 5, 10, 25)
# change(1) = 1 (1)
# change(6) = 2 (5 + 1)
# change(47) = 5 (25 + 10 + 10 + 1 + 1)
# Brute Force Approach:
# Recursively try every possible combination to find the smallest.
# Each recursive step, we will try each coin possibility that is less than the remaining total.
# Substract the coin value from the total remaining until the remaining coin value is 0.
# Brute Force Recursive
def makeChange(amount, coins):
if amount == 0:
return 0
minCoins = float("inf")
for coin in coins:
if amount - coin >= 0:
currMin = makeChange(amount - coin, coins)
minCoins = min(currMin, minCoins)
return minCoins + 1
# DP Memoize Top-Down
def makeChange(amount, coins):
memo = [0 for _ in range(amount + 1)]
return makeChange_helper(amount, coins, memo)
def makeChange_helper(amount, coins, memo):
if memo[amount] == 0:
if amount == 0:
return 0
minCoins = float("inf")
for coin in coins:
if amount - coin >= 0:
currMin = makeChange(amount - coin, coins)
minCoins = min(currMin, minCoins)
memo[amount] = minCoins + 1
return memo[amount]
# DP Memoize Bottom-Up
def makeChange(amount, coins):
memo = [0 for _ in range(amount + 1)]
for i in range(1, amount + 1):
minCoins = float("inf")
for coin in coins:
if i - coin >= 0:
minCoins = min(minCoins, memo[i - coin])
memo[i] = minCoins + 1
return memo[amount]
# Test
coins = [1, 5, 10, 25]
print(makeChange(47, coins))
coins = [10, 6, 1]
print(makeChange(12, coins))
|
94c12f524f74a491fc2ce160abb6a212aa497a77 | loyess/Note | /aiohttp/06_字节流形式获取数据(不像text,read一次获取所有数据).py | 1,546 | 3.625 | 4 | import asyncio
import aiohttp
"""
注意1:
我们获取的session.get()是Response对象,他继承于StreamResponse
注意2:
async with session.get(url,params=params) as r: #异步上下文管理器
with open(filename,"wb") as fp: #普通上下文管理器
两者的区别:
在于异步上下文管理器中定义了__aenter__和__aexit__方法
异步上下文管理器指的是在enter和exit方法处能够暂停执行的上下文管理器
为了实现这样的功能,需要加入两个新的方法:__aenter__ 和__aexit__。这两个方法都要返回一个 awaitable类型的值。
推文:
(https://blog.csdn.net/tinyzhao/article/details/52684473)
异步上下文管理器async with和异步迭代器async for
"""
async def func1(url, params):
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params) as r:
print(await r.content.read(10)) # 读取前10字节
async def func2(url, params, filename):
"""
下面字节流形式读取数据,保存文件
"""
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params) as r:
with open(filename, "wb") as fp:
while True:
chunk = await r.content.read(10)
if not chunk:
break
fp.write(chunk)
tasks = [func2('https://www.ckook.com/forum.php', {"gid": 6}, "1.html"), ]
|
3ae34a178134449c68525baf4ebdd896725934b8 | timekeeper13/python_scripts | /conditions_and_loops/positive_or_negative.py | 182 | 4.25 | 4 |
a = float(input("enter the number : "))
if a < 0:
print(f"the number {a} is negative")
elif a == 0 :
print(f"the number {a} is zero")
else :
print(f"the number {a} is positive") |
95ebb95bb8a77e398eeabcfacd5bd964f85fdc84 | FeketeMiklosBenjamin/Python_1_Sikidom_feladat | /main.py | 760 | 3.734375 | 4 | def main() -> None:
print('A téglalap kerületét kiszámoló függvény!')
a : float = float(input('a (oldal) = '))
b : float = float(input('b (oldal) = '))
if a < 1 or b < 1:
print('A megadott adatokkal nem lehet számolni!')
else:
téglalap_kerület: float = 2 * (a + b)
print(f'A téglalap kerülete: {téglalap_kerület}')
print('A téglalap területét kiszámoló függvény!')
a : float = float(input('a (oldal) = '))
b : float = float(input('b (oldal) = '))
if a < 1 or b < 1:
print('A megadott adatokkal nem lehet számolni!')
else:
téglalap_terület: float = a * b
print(f'A téglalap területe: {téglalap_terület}')
if __name__ == "__main__":
main() |
002ac925e47261dc846c34718a533a7bbc11a795 | Journetta/LearningPython | /stringstutorial.py | 1,330 | 4.3125 | 4 | #formatted strings
first = 'John'
last = 'Doe'
#This works but isn't that optimized
message = first + ' [' + last + '] is a coder'
#this is a more optimized way of doing it
msg = f'{first} [{last}] is a coder!'
print(msg)
course = 'Python For Beginners'
#len counts how many characters in a input field (but it's not limited to only that as it's general)
print(len(course))
#meta (when a function belongs to a specfic object it's a meta)
#This changes the 'Python for Beginners' to 'PYTHON FOR BEGINNERS'
print(course.upper())
#lower case
print(course.lower())
#orignal not modified
print(course)
#will return the index of the letter first character (starts at 0) (-1 means it's not found)
print(course.find('P')) #P is character 0
#Beginners starts at index 11
print(course.find('Beginners'))
#This replaces Beginners with Absolute Beginners
print(course.replace('Beginners', 'Absolute Beginners'))
#This will replace the P with a J (Jython For Beginners)
print(course.replace('P', 'J'))
#This should reply 'TRUE' As it's looking for the word "Python" in the course variable
# (but if it's a lower case instead of a upper case, then it'll return false)
print('python' in course)
#len function = number of characters in a string (general purpose)
#meta includes, upper, lower, title,find,replace
#in operator ('...) in (string)
|
c8834f782b05e05cb61ec2816208d2c14431ac45 | jhampson-dbre/github-move | /get_player_game_stats.py | 1,913 | 3.5625 | 4 | """
Get player stats from a given game
"""
import re
from requests import get
from bs4 import BeautifulSoup
def get_player_stats_from_game(team, year, week):
"""
Get player stats for a particular game
"""
def get_game_urls(year, week):
"""
Get the box score URL for each game by team
returns a dictionary with the team as the key
and the link to the detailed game stats
"""
base_url = "https://www.pro-football-reference.com"
# URL for the summary of all games for a given week
# This page has the each match up for the week and
# a link to the detailed game stats
url = "https://www.pro-football-reference.com/years/{}/week_{}.htm".format(
year, week)
response = get(url)
week_summary = BeautifulSoup(response.content, 'html.parser')
# Get just the game summary content
week_summary_games = week_summary.find_all(
attrs={"class": "game_summary expanded nohover"})
losing_teams = []
winning_teams = []
game_link = []
# For each game played, extract the losing team,
# the winning team, and the detailed game stats link
for game in week_summary_games:
try:
losing_team_strings = [text for text in game.find(
attrs={"class": "loser"}).stripped_strings]
losing_teams.append(losing_team_strings[0])
except AttributeError:
pass
try:
winning_team_strings = [text for text in game.find(
attrs={"class": "winner"}).stripped_strings]
winning_teams.append(winning_team_strings[0])
except AttributeError:
pass
for link in game.find_all(href=re.compile("boxscores")):
game_link.append(base_url + link.get('href'))
game_urls = dict(zip(losing_teams, game_link))
game_urls.update(dict(zip(winning_teams, game_link)))
return game_urls
|
ebc76b392c760f8a88e5ece5903fd9f3f7bf2fb6 | milu-buet/data-science | /vector.py | 585 | 3.9375 | 4 | import math
class Vector:
def __init__(self, a, b):
self.x = a
self.y = b
def __mul__(self, u):
if type(u) in [int, float]:
return Vector(u*self.x, u*self.y)
return self.x * u.x + self.y * u.y
def __len__(self):
return int(math.sqrt(self.x**2 + self.y**2))
def __eq__(self, x):
return [x]*10
def __contains__(self, a):
return self.x==a or self.y==a
def print(self):
print(self, self.x, self.y)
#---------------------------------------
v = Vector(3,4)
u = Vector(7,12)
print( v * u )
print( len(v) )
print( v == 5 )
print( 5 in v )
w = v * 10
w.print()
|
788fc51aa6be5081a49798b9a7891775b00bf42a | Anthonymcqueen21/Algorithms-in-Python | /Algorithms/Bubble Sort.py | 934 | 4.25 | 4 | # Bubble sorting is an algorithm which is used to sort a list of elements in arrays.
# Implementation
# Python Script
def bubble_sort(nlist):
for passnum in
for i in range(len(nlist)-1,0,-1):
for j in range(passnum):
if nlist[j]>nlist[j+1]:
nlist[j], nlist[j+1] = nlist[j+1], nlist[j]
return bubble_sort
# Defining num_swaps and count_swaps in a problem statement
def countSwaps(lst):
num_swaps = 0
if len(lst) < 2:
return num_swaps
for i in range(len(lst) - 1, 0, -1):
for j in range(i):
if lst[j] > lst[j + 1]:
lst[j], lst[j+1] = lst[j+1],lst[j]
num_swaps += 1
return num_swaps
n = int(input().strip())
a = [int(a_temp) for a_temp in input().strip().split(' ')]
swaps = countSwaps(a)
print('Array is sorted in {0} swaps.'.format(swaps))
print('First Element: {0}'.format(a[0]))
print('Last Element: {0}'.format(a[-1]))
|
43eaa3647fd73b634ae2b354b2e08dcb640a7071 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4464/codes/1734_2502.py | 254 | 3.9375 | 4 | from math import *
n = int(input("insira os n primeiros termos"))
soma = (1/(1*3**0))
raiz = sqrt(12)
cont = 1
while (cont < n):
soma = soma + (-1)**cont * (1/((cont*2+1)*3**cont))
cont = cont + 1
raiz = raiz * soma
print(round(raiz,8)) |
8a64e84e4eb35f18846534e556affc4096020308 | andrewppar/sat-solver | /sat_solver/solver.py | 7,649 | 3.96875 | 4 | import copy
from .formula import Atom, Not, And, Or, If, Formula
from typing import List, Dict, Tuple
import time
"""A sat-solver implemented in python for experimental purposes.
This implements a sat-solver that can be used for basic purposes.
Currently it's only ~300 lines of code so it is easy to dive into
and manipulate. I plan to use it for experimentation with different
methods of approaching sat-solvers.
Typical usage example:
formula = If(Atom("p"), Atom("p"))
truth_table = TruthTable(formula)
"""
###############
# Truth Table #
###############
class TruthTable:
"""The TruthTable class hold all the possible truth values for a formula
This subclass assigns all possible truth values to all of the atomic
formulas of a formula and for each possibility evaluates the truth value
of the formula that it is passed.
:ivar formula: This is the formula the truth table is being generated for.
"""
def __init__(self, formula: Formula):
"""The init class for truth tables.
This class sets the formula. Gets all the atomic formulas. Generates
the rows for the truth table. It calculates the value for the
value of each possibility of assignment to truth tables.
"""
self.formula = formula
self.atoms = formula.atomic_formulas()
start_rows = time.time()
print("Starting Rows")
self.atom_rows = self.generate_rows()
stop_rows = time.time()
print(f"Done with Rows: {stop_rows - start_rows}")
self.resolution = self.solve()
done = time.time()
print(f"finished {done - stop_rows}")
def generate_rows(self) -> List[Dict[Atom, bool]]:
"""Generates all the rows for the TruthTable's formula
This function creates all the possible assignments of T and F
to the formula for a truth table.
:returns: A list of dictionaries whose keys are atomic formulas
and whose values are booleans.
"""
# @todo this is tail recurive -- convert it to a while loop
# @todo maybe make List[Dict[Atom, bool]] it's own class?
atom_list = list(self.atoms)
return self.generate_rows_internal([], atom_list)
def generate_rows_internal(self,
acc,
atom_list) -> List[Dict[Atom, bool]]:
"""An internal method for generating rows of truth tables.
This function should only be called by generate_rows. It
is almost explicitly tail recursive and so could be
optimized with a while loop or some dynamic programming.
:param acc: An accumulator that is used in the next
recursive iteration.
:param atom_list: A list of atomic formulas that is being
iterated over.
:returns: A list of dictionaries whose keys are atomic formaulas
and whose values are booleans.
"""
if atom_list == []:
return [{}]
else:
recursive_case = self.generate_rows_internal(acc, atom_list[1:])
current_atom = atom_list[0]
result_list: List[Dict[Atom, bool]] = []
for dictionary in recursive_case:
# TODO We probably don't need two copies of the dictionary.
# This could be way more space efficient if we used some other
# datastructure.
true_dictionary = copy.copy(dictionary)
true_dictionary[current_atom] = True
result_list.append(true_dictionary)
false_dictionary = copy.copy(dictionary)
false_dictionary[current_atom] = False
result_list.append(false_dictionary)
return result_list
def solve(self) -> List[Tuple[Dict[Atom, bool], bool]]:
"""Determines the truth value of a formula for each row in
its truth table.
:returns: A list of tuples where the first value is a row
of the truth table and the second value is the value
of that truth table's formula.
"""
result = []
for case in self.atom_rows:
resolution = self.resolve(case)
result.append(resolution)
return result
def resolve(self,
case: Dict[Atom, bool]) -> Tuple[Dict[Atom, bool], bool]:
"""Solves a particular row of a truth table.
:param case: A dictionary of atomic formulas and booleans.
:returns: A tuple whose first element is the input dictionary
and whose second element is the value of the truth
table's formula for that cases assignment of booleans
to atomic formulas.
"""
truth_value = self.resolve_internal(self.formula, case)
return (case, truth_value)
def resolve_internal(self,
formula: Formula,
case: Dict[Atom, bool]) -> bool:
"""A helper to self.resolve()
:param formula: the formula that is being solved for.e
:param case: A dictionary of atomic formulas and booleans.
:returns: A dictionary whose values are atomic formulas and whose
keys are booleans.
"""
if isinstance(formula, Atom):
return case[formula]
elif isinstance(formula, Not):
return not self.resolve_internal(formula.negatum, case)
elif isinstance(formula, And):
result = True
for conjunct in formula.conjuncts:
if not self.resolve_internal(conjunct, case):
result = False
return result
elif isinstance(formula, Or):
result = False
for disjunct in formula.disjuncts:
if self.resolve_internal(disjunct, case):
result = True
return result
elif isinstance(formula, If):
ant_value = self.resolve_internal(formula.antecedent, case)
cons_value = self.resolve_internal(formula.consequent, case)
return (not ant_value) or cons_value
else:
raise RuntimeError(f"{formula} has not been implemented")
def show_resolution(self):
"""Prints a representation of a table to stdout."""
atoms = list(self.atoms)
atom_string = "|"
for atom in atoms:
padding = ""
if len(str(atom)) < len(str(False)):
padding = " " * (len(str(False)) - len(str(atom)))
atom_string += f"{atom}{padding}|"
header = f"{atom_string}{self.formula}"
print(header)
print('-' * len(header))
for dictionary, value in self.resolution:
row = "|"
for atom in atoms:
atom_case = dictionary[atom]
padding = ""
if atom_case:
padding = " "
row += f"{atom_case}{padding}|"
row += f"{value}"
print(row)
def tautology(self) -> bool:
"""Determines whether the formula for a table is a tautology.
:returns: A boolean that indicates whether or not the formula
is a tautology.
"""
result = True
for case, value in self.resolution:
if not value:
result = False
break
return result
def contradiction(self) -> bool:
result = True
for case, value in self.resolution:
if value:
result = False
break
return result
|
a4db96fcf7c5c82fab1ed3df99a5b005c5a48529 | czHero/PAT_Basic | /1009.py | 187 | 3.8125 | 4 | #答案正确
import sys
sdata = input()
words = sdata.split(' ')
words.reverse()
first = 1
for word in words:
if first:
print (word,end='')
first = 0
else:
print('',word,end='') |
97d3552c8d96f4d493c79b462329ee4eba836254 | ewil32/volunteer_tutoring | /selection_sort.py | 5,209 | 4.15625 | 4 | """
--- SELECTION SORT ---
The intuition for the algorithm is as follows.
We can divide the list of numbers into a sorted and unsorted part
The sorted part can be incrementally built by finding the smallest number in the unsorted part
and placing it at the tail of the sorted part
I think it is easiest though to build up intuition with an example...
Let's imagine our list of numbers is L = [3, 4, 2, 1]
Note the list can be named anything but I chose L for List
We imagine the sorted portion of the list is S (S for sorted) which starts empty
and the unsorted part is the entire L
So our initial state is
L = [3, 4, 2, 1]
S = []
S will not actually be another list, but will denote the sorted part of L that we build
I think it's just useful to see to keep track of how much we've sorted
We go through L from position 1 to 4 and find the smallest number 1 at position 4
We swap this number 1 with the number at postion 1 of the list, 3, which gives us
L = [1, 4, 2, 3]
S = [1]
Now L is sorted from position 1 to 1
So we go from postion 2 to 4 and find the smallest number 2 and swap it with the number at position 2
This gives us
L = [1, 2, 4, 3]
S = [1, 2]
Now L is sorted from position 1 to 2
So we go from postion 3 to 4 and find the smallest number 3 and swap it with the number at position 3
This gives us
L = [1, 2, 3, 4]
S = [1, 2, 3]
Since L is sorted from position 1 to 3 and only one number remains, L must be sorted
as we can see above.
L = [1, 2, 3, 4]
S = [1, 2, 3, 4]
So the algorithm can be stated as
Given a list of numbers L
1. If L is empty, return L immediately
2. Otherwise set p = 1 (p for position) and set N = the length of L
3. If p = N, we are finished so return L
4. Otherwise find the smallest number in L from p to N
5. swap that number with the number at p
6. Set p = p + 1
7. Go back to step 3
Let's see what this looks like in python
Note that the first position of a list in python is given by 0 not 1
"""
def selection_sort(list_of_numbers):
# Set N = length of list
N = len(list_of_numbers)
if N == 0:
return []
# set p = 0
p = 0
# while we still have numbers in list_of_numbers
# note we need -1 here because python starts at 0 not 1 so last position in the list is N-1
while p < N - 1:
# find the smallest number in the remaining unsorted part
# start by assuming it's the number at position p
smallest_number = list_of_numbers[p]
smallest_position = p
# then check the rest of the list
for i in range(p+1, N):
if list_of_numbers[i] < smallest_number:
smallest_position = i
smallest_number = list_of_numbers[i]
# swap the number at position p with the smallest number
# we use temp so we don't lose a number
temp_number = list_of_numbers[smallest_position]
list_of_numbers[smallest_position] = list_of_numbers[p]
list_of_numbers[p] = temp_number
# increase p by one
p = p+1
# the loop has finished so we return list_of_numbers
return list_of_numbers
"""
---- TEST OUR SORT FUNCTION ----
We will create a function that tries some simple test lists
Note here that we use += 1 to increment by 1
"""
def selection_sort_test():
print(" --- Testing selection sort --- ")
# keep track of how many tests are successful and unssuccesful
num_tests_passed = 0
num_tests_failed = 0
# random order
test_list = [6,1,8,2,9,4,3,0,5,7]
if selection_sort(test_list) == [0,1,2,3,4,5,6,7,8,9]:
num_tests_passed = num_tests_passed + 1
else:
print("Test failed for:", test_list)
num_tests_failed = num_tests_failed + 1
# empty list
test_list = []
if selection_sort(test_list) == []:
num_tests_passed = num_tests_passed + 1
else:
print("Test failed for:", test_list)
num_tests_failed = num_tests_failed + 1
# positive sorted list
test_list = [1,2,3,4]
if selection_sort(test_list) == [1,2,3,4]:
num_tests_passed = num_tests_passed + 1
else:
print("Test failed for:", test_list)
num_tests_failed = num_tests_failed + 1
# only negative
test_list = [-1,-3,-2,-4]
if selection_sort(test_list) == [-4,-3,-2,-1]:
num_tests_passed = num_tests_passed + 1
else:
print("Test failed for:", test_list)
num_tests_failed = num_tests_failed + 1
# positive and negative
test_list = [-1, 1, -2, 2, -3, 3, -4, 4]
if selection_sort(test_list) == [-4,-3,-2,-1,1,2,3,4]:
num_tests_passed = num_tests_passed + 1
else:
print("Test failed for:", test_list)
num_tests_failed = num_tests_failed + 1
# including decimal numbers
test_list = [1, 0.1, -1]
if selection_sort(test_list) == [-1, 0.1, 1]:
num_tests_passed = num_tests_passed + 1
else:
print("Test failed for:", test_list)
num_tests_failed = num_tests_failed + 1
print("Number of tests passed:", num_tests_passed)
print("Number of tests failed:", num_tests_failed)
# --- RUN THE TESTING CODE---
selection_sort_test()
|
796a0e96791e0574355762457a42148ee101eeb6 | ManuBedoya/AirBnB_clone | /tests/test_models/test_city.py | 372 | 3.8125 | 4 | #!/usr/bin/python3
"""Module to test the city class
"""
import unittest
from models.city import City
class TestCity(unittest.TestCase):
"""TestCity Class
"""
def test_create_city(self):
"""Test when create a city
"""
my_model = City()
dict_copy = my_model.to_dict()
self.assertEqual(dict_copy['__class__'], 'City')
|
7248fdd30a6dab3a658dbe7a88b7b3d3dad92da3 | Jzjsnow/navi-complexity | /code/funcs.py | 19,292 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Basic functions for calculations in the network.
"""
import math
import pandas as pd
import numpy as np
import networkx as nx
from networkx.classes.function import path_weight
from itertools import islice
def k_shortest_paths(G, source, target, k, weight=None):
"""
Get the k shortest paths from source to target in G
Parameters
----------
G : a networkx graph.
source : the orgin node.
target : the destination node.
k : the number of shortest paths.
weight : the name of the edge attribute to be used as a weight when
calculating the path length. The default is None.
Returns
-------
A generator that produces lists of the k shortest paths, in order from
shortest to longest.
"""
return list(
islice(nx.shortest_simple_paths(G, source, target, weight=weight), k)
)
def get_od_ksp_attr_all(
o_label,
d_label,
G_relabeled,
kmax,
dura_thres):
"""
Get the attributes of all the shortest paths from station o_label to
station d_label in the subway network [G_relabeled] whose travel time is
within the threshold [dura_thres].
Parameters
----------
o_label : the origin station identified by the string of "lineid-stationid".
d_label : the destination station identified by the string of "lineid-
stationid".
G_relabeled : the networkx graph of the subway network.
kmax : the max number of shortest paths to get.
dura_thres : the threshold of the travel time of the paths, exceed which no
more shortest paths are calculated.
Returns
-------
list_paths : a list of the shortest paths whose travel time is within the threshold.
list_plen : a list of the travel time of the returned paths.
list_dist : a list of the path distances of the returned paths.
list_nroutes : a list of the number of lines on each returned path.
list_list_lines : a list contains the list of lines on each returned path.
k : the number of the returned paths.
"""
list_paths = []
list_plen = []
list_dist = []
list_nroutes = []
list_list_lines = []
k = 0
for path in k_shortest_paths(
nx.DiGraph(G_relabeled),
o_label,
d_label,
kmax,
weight='duration'):
duration = path_weight(G_relabeled, path, weight='duration')
if(duration > dura_thres):
break
k += 1
list_paths.append(path)
paths = [key for i in range(0, len(
path) - 1) for key in G_relabeled.get_edge_data(path[i], path[i + 1]).keys()] # line ID
list_lines = [paths[i] for i in range(len(paths)) if (
i == 0 or i > 0 and paths[i] != paths[i - 1])and paths[i] != 0]
list_pathturns = [path[i] for i in range(
len(paths)) if i > 0 and paths[i] != paths[i - 1]]
distance = path_weight(G_relabeled, path, weight='distance')
len_path = len(list_lines)
list_plen.append(duration)
list_nroutes.append(len_path)
list_dist.append(distance)
list_list_lines.append(list_lines)
return list_paths, list_plen, list_dist, list_nroutes, list_list_lines, k
def dual_shortest_path(G, source, target, ifgetturnseq=True):
"""
Get all the shortest paths between source and target in the information
network (dual graph).
Parameters
----------
G : the networkx graph of the information network.
source : the origin node in G.
target : the destination node in G.
ifgetturnseq : True if the edges along the paths are returned. The default
is True.
Returns
-------
list_paths : a list of all the shortest paths and the node sequence of each
path is saved in a list in list_paths.
list_pathsturns : the edge list along each path in list_paths.
E : the entropy needed to locate any of the path in list_paths in the
information network.
"""
list_paths = list(nx.all_shortest_paths(G, source, target, weight=None))
p_st_sum = 0
p_st = 1
list_pathsturns = [] # edge(transfer station) sequences
for path in list_paths: # e.g. path = [1,7,12]
n_turns = len(path) - 1 # number of transfers
list_turnsid = []
# get the transfer sequence of a single path
if(ifgetturnseq):
for i in range(0, n_turns):
# interchange station for Line path[i] and line path[i+1]
crossings = dict(G[path[i]][path[i + 1]])
n_crossing_per_line = len(crossings) # number of transfers
if(i == 0):
for crossing in crossings:
list_turnsid.append([crossings[crossing]['sid']])
else:
n_index = 0
while(n_index < len(list_turnsid)):
list_id = list_turnsid[n_index]
# If there is only one path, add the transfer station
# directly
if(n_crossing_per_line == 1):
for crossing in crossings:
list_id.append(crossings[crossing]['sid'])
# If there are multiple paths, add the transfer
# station for each line
elif(n_crossing_per_line > 1):
for crossing in crossings:
list_turnsid.insert(
n_index, list_id + [crossings[crossing]['sid']])
del list_turnsid[n_index + n_crossing_per_line]
n_index += n_crossing_per_line
list_pathsturns.append(list_turnsid)
# the search information for each path
if(n_turns > 0):
p_st = 1 / len(G[path[0]])
for i in range(0, n_turns - 1):
k_options = len(G[path[i + 1]]) - \
1 if len(G[path[i + 1]]) - 1 > 0 else 1
p_st *= 1 / k_options
p_st_sum += p_st
E = -np.log2(p_st_sum)
return list_paths, list_pathsturns, E
def get_stops_relabeled(
o_label,
d_label,
list_paths,
list_pathsturns,
G_relabeled):
"""
Transform the path in the information network to the path in the subway
network which is encoded by the sequence of stations.
Parameters
----------
o_label : the origin station identified by the string of "line number-
station number".
d_label : the destination station identified by the string of "line
number-station number".
list_paths : the node sequence of the path in the information network.
list_pathsturns : the edge sequence of the path in the information network.
G_relabeled : the networkx graph of the subway network.
Returns
-------
stops : the sequences of stations along the path.
"""
sid1 = int(o_label.split('-')[1])
sid2 = int(d_label.split('-')[1])
line1 = int(o_label.split('-')[0])
line2 = int(d_label.split('-')[0])
lineid = line1
G_sub = G_relabeled.edge_subgraph(
[edge for edge in G_relabeled.edges if edge[2] == lineid])
if(line1 == line2):
stops = nx.shortest_path(G_sub, o_label, d_label)
else:
lineid = line1
G_sub = G_relabeled.edge_subgraph(
[edge for edge in G_relabeled.edges if edge[2] == lineid])
transfer = list_pathsturns[0][0][0]
stops = nx.shortest_path(
G_sub, o_label, str(line1) + '-' + str(transfer))
for i in range(1, len(list_paths[0]) - 1):
lineid = list_paths[0][i]
s1 = list_pathsturns[0][0][i - 1]
s2 = list_pathsturns[0][0][i]
G_sub = G_relabeled.edge_subgraph(
[edge for edge in G_relabeled.edges if edge[2] == lineid])
stops += nx.shortest_path(G_sub,
str(lineid) + '-' + str(s1),
str(lineid) + '-' + str(s2))
lineid = line2
G_sub = G_relabeled.edge_subgraph(
[edge for edge in G_relabeled.edges if edge[2] == lineid])
transfer = list_pathsturns[0][0][-1]
stops += nx.shortest_path(G_sub, str(line2) +
'-' + str(transfer), d_label)
return stops
def cal_entropy_in_dualG(list_paths, dualG):
"""
Calculate the entropy of finding a path in the information network (dual
graph)
Parameters
----------
list_paths : contains the list of sequence nodes on the path.
dualG : a networkx graph of the information network.
Returns
-------
E : the entropy of finding the path.
"""
path = list_paths[0]
n_turns = len(path) - 1
p_st = 1
if(n_turns > 0):
p_st = 1 / len(dualG[path[0]])
for i in range(0, n_turns - 1):
k_options = len(dualG[path[i + 1]]) - 1 if path[i] != path[i + 2] \
else len(dualG[path[i + 1]])
# avoid the cases where the denominator is 0 due to a circular path
# in the matched paths
p_st *= 1 / k_options
E = -np.log2(p_st)
return E
def merge_2_st_const_width(
G_relabeled,
matrix_Ss,
matrix_nroutes,
mat_width,
thres_C=None,
matrix_Ktot_sub=None):
"""
Get the line-level TSI by aggregating from the station-level search
information.
The aggregation uses the station-level entropy of the fastest simplest
paths between line pairs and the flow weights are set to 1
Parameters
----------
G_relabeled : subway network.
matrix_Ss : station-level search information.
matrix_nroutes : number of subway lines included in the simplest path from
station i to j (= number of transfers C + 1).
mat_width : width of result matrix (line-level search information).
thres_C : if only the simplest paths with specific number of transfers C
are used in the calculation, thres_C is set to the number of transfers
included in the path.
None - does not filter the number of transfers of the simplest
paths (all the simplest paths between a pair of subway lines are
used for averaging).
The default is None.
matrix_Ktot_sub : optional. Number of connections in the sub-networks. The
default is None.
Returns
-------
matrix_S_nid: line-level search information between each line pair.
matrix_Ktot_sub: average number of connections in the sub-networks of all
the OD stations between the line pair.
"""
# line id
list_nid = list(set([int(node.split('-')[0])
for node in G_relabeled.nodes]))
# station id
list_sids = [list(set([int(node.split('-')[1])
for node in G_relabeled.nodes if int(node.split('-')[0]) == nid])) for nid in list_nid]
matrix_S_nid = np.zeros((mat_width, mat_width)) * np.nan
matrix_Ktot_st_sub = np.zeros((mat_width, mat_width)) * np.nan
for i in range(0, len(list_nid)):
for j in range(0, len(list_nid)):
list_sid1 = np.array(list_sids[i]) - 1
list_sid2 = np.array(list_sids[j]) - 1
list_S = matrix_Ss[list_sid1, :]
list_S = list_S[:, list_sid2]
list_nlines = matrix_nroutes[list_sid1, :]
list_nlines = list_nlines[:, list_sid2]
if(matrix_Ktot_sub is not None):
list_Ktot = matrix_Ktot_sub[list_sid1, :]
list_Ktot = list_Ktot[:, list_sid2]
list_Ktot = list_Ktot[list_nlines > 0]
list_S = list_S[list_nlines > 0]
list_nlines = list_nlines[list_nlines > 0]
if(thres_C is None):
matrix_S_nid[list_nid[i] - 1][list_nid[j] - 1] = \
np.sum(list_S) / (list_S.size)
if(matrix_Ktot_sub is not None):
matrix_Ktot_st_sub[list_nid[i] - 1][list_nid[j] - 1] = \
np.sum(list_Ktot) / list_Ktot.size
else:
list_S = list_S[list_nlines == thres_C + 1]
matrix_S_nid[list_nid[i] - 1][list_nid[j] - 1] = \
np.sum(list_S) / (list_S.size)
if(matrix_Ktot_sub is not None):
list_Ktot = list_Ktot[list_nlines == thres_C + 1]
matrix_Ktot_st_sub[list_nid[i] - 1][list_nid[j] - 1] = \
np.sum(list_Ktot) / list_Ktot.size
if(matrix_Ktot_sub is not None):
return matrix_S_nid, matrix_Ktot_st_sub
else:
return matrix_S_nid
def get_sub_dualG_relabeled(G, dualG_nodes, dualG_edges):
"""
Map the input subway's sub-network G to an information network.
Parameters
----------
G : the (sub-)network to map.
dualG_nodes : the total nodes in the global information network.
dualG_edges : the total edges in the global information network.
Returns
-------
dualG : the local information network transformed from the sub-network G.
dualG_nodes_sub : the list of nodes in dualG.
dualG_edges_sub : the list of edges in dualG.
"""
H = G.to_undirected()
dualG_nodes_sub = [x for x in dualG_nodes if x[0] in list(
set([key for u, v, key in H.edges(keys=True)]))]
dualG_edges_sub = []
for sid in H.nodes():
incident_lines = list(set([int(y.split('-')[0])
for y in list(H[sid])]))
sid = int(sid.split('-')[1])
if(len(incident_lines) > 1): # sid: transfer station
add_edges = [x for x in dualG_edges if x[2] == sid
and x[0] in incident_lines
and x[1] in incident_lines
and x not in dualG_edges_sub]
dualG_edges_sub = dualG_edges_sub + add_edges
dualG = nx.MultiGraph()
dualG.add_nodes_from(dualG_nodes_sub)
keys = dualG.add_edges_from(dualG_edges_sub)
return dualG, dualG_nodes_sub, dualG_edges_sub
def get_matrixC(dualG, dual_nodes, mat_width):
"""
Get the minimum number of transfers between two subway lines.
Parameters
----------
dualG : a networkx graph of the information network.
dualG_nodes : nodes in the information network dualG.
mat_width : width of result matrix.
Returns
-------
matrix_C : the minimum number of transfers between each two
subway lines in dualG.
"""
list_nodes = list(max(nx.connected_components(dualG), key=len))
list_cols = []
for col in np.arange(0, len(dual_nodes)):
if(dual_nodes[col][0] in list_nodes):
list_cols.append(col)
matrix_C = np.zeros((mat_width, mat_width)) - 1
is_connected = nx.is_connected(dualG)
p = dict(nx.shortest_path_length(dualG))
for i in range(0, len(dual_nodes)):
for j in range(0, len(dual_nodes)):
if(is_connected is True or dual_nodes[i][0] in list_nodes and dual_nodes[j][0] in list_nodes):
matrix_C[dual_nodes[i][0] - 1][dual_nodes[j][0] -
1] = p[dual_nodes[i][0]][dual_nodes[j][0]]
return matrix_C
def merge_2_st_matching_C(
G_relabeled,
df_matched_paths,
max_width,
thres_C=None,
count_weighted=False):
"""
Get the average number of transfers between each two subway
lines. The aggregation uses the number of transfers and flow
weights of all the matched paths between line pairs.
Parameters
----------
G_relabeled : the subway network.
df_matched_paths : the dataframe containing all the matched paths and
their search information between station pairs.
('S_sub': entropy of the path calculated in the
sub-network.
'avg_counts': the number of trips (records)
matching the path.)
max_width : width of result matrix.
thres_C : if only paths with specific number of transfers C are used in the
calculation, thres_C is set to the number of transfers included in the
path. The default is None.
count_weighted : True if the average values need to be weighted by the flow
of the paths. The default is False.
Returns
-------
matrix_C : the average number of transfers between each two subway lines.
"""
list_nid = list(set([int(node.split('-')[0])
for node in G_relabeled.nodes]))
list_sids = [list(set([int(node.split('-')[1])
for node in G_relabeled.nodes if int(node.split('-')[0]) == nid])) for nid in list_nid]
matrix_S_nid = np.zeros((max_width, max_width)) * np.nan
matrix_C = np.zeros((max_width, max_width)) * np.nan
for i in range(0, len(list_nid)):
for j in range(0, len(list_nid)):
sort_paths = df_matched_paths[(df_matched_paths['i'].isin(np.array(
list_sids[i]) - 1)) & (df_matched_paths['j'].isin(np.array(list_sids[j]) - 1))]
list_S = np.array(sort_paths['S_sub'].tolist())
list_nlines = np.array(sort_paths['nroutes'].tolist())
if(count_weighted):
list_count = np.array(sort_paths['avg_counts'].tolist())
list_count = list_count[list_nlines > 0]
list_S = list_S[list_nlines > 0]
list_nlines = list_nlines[list_nlines > 0]
if(thres_C is None):
if(count_weighted):
matrix_S_nid[list_nid[i] - 1][list_nid[j] - 1] = np.sum(
list_S * list_count) / np.sum(list_count[list_nlines > 0])
matrix_C[list_nid[i] - 1][list_nid[j] - 1] = np.sum(
list_nlines * list_count) / np.sum(list_count[list_nlines > 0])
else:
matrix_S_nid[list_nid[i] - 1][list_nid[j] - 1] = \
np.sum(list_S) / list_S.size
matrix_C[list_nid[i] - 1][list_nid[j] - 1] = \
np.sum(list_nlines) / list_nlines
else:
list_S = list_S[(list_nlines > 0) & (
list_nlines == thres_C + 1)]
list_nlines = list_nlines[(list_nlines > 0) & (
list_nlines == thres_C + 1)]
if(count_weighted):
list_count = list_count[(list_nlines > 0) & (
list_nlines == thres_C + 1)]
matrix_S_nid[list_nid[i] - 1][list_nid[j] - 1] = \
np.sum(list_S * list_count) / np.sum(list_count)
matrix_C[list_nid[i] - 1][list_nid[j] -
1] = np.sum(list_nlines * list_count) / np.sum(list_count)
else:
matrix_S_nid[list_nid[i] - 1][list_nid[j] - 1] = \
np.sum(list_S) / list_S.size
matrix_C[list_nid[i] - 1][list_nid[j] -
1] = np.sum(list_nlines) / list_nlines
return matrix_C - 1
|
0f4b6e70c04ff5f423dbf1b3064c0a51e7d6bcf1 | sayan1995/DP-4 | /largestSquare.py | 2,437 | 3.859375 | 4 | '''
Effecient:
Time Complexity: O(n^2)
Space Complexity: O(n^2)
Explanation: Use the logic to find the length of the square from the neighboring cells. Use the following conditions
to find the DP solution:
If i == 0 or j ==0: length =0
if [i][j] == 0 length = 0
if [i][j] == 1 length = 1 + min(min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1])
BruteForce:
Time Complexity: O((mn^2)
Space Complexity: O(1)
Did this code successfully run on Leetcode : Yes
Explanation: Iterate through the matrix from the diagonals (bottom and right) and keep checking if it is a square, if
even once you see a '0', end the current search. contiue until u see a 0 or reach the end and save the largest square
size on the way.
'''
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if matrix == None or len(matrix) == 0:
return 0
# +1 because first few rows and columns are 0
rows = len(matrix)
if rows > 0:
col = len(matrix[0])
else:
col = 0
dp = [[0 for i in range(col + 1)] for j in range(rows + 1)]
maxL = 0
for i in range(1, (rows + 1)):
for j in range(1, (col) + 1):
if matrix[i - 1][j - 1] == '1':
dp[i][j] = 1 + min(min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1])
maxL = max(maxL, dp[i][j])
return maxL * maxL
def maximalSquareBruteForce(self, matrix: List[List[str]]) -> int:
if matrix == None or len(matrix) == 0:
return 0
rows = len(matrix)
col = len(matrix[0])
maxSqlen = 0
for i in range(0, rows):
for j in range(0, col):
if matrix[i][j] == '1':
sqlen = 1
flag = True
while sqlen + i < rows and sqlen + j < col and flag:
for k in range(j, sqlen + j + 1):
if matrix[i + sqlen][k] == '0':
flag = False
break
for k in range(i, sqlen + i + 1):
if matrix[k][j + sqlen] == '0':
flag = False
break
if flag:
sqlen += 1
maxSqlen = max(maxSqlen, sqlen)
return maxSqlen * maxSqlen
|
521ab61bfcbfbf04fd1da1297772e211a4af90db | Watotacho/python-classes-and-object | /pyquiz/python_test.py | 1,075 | 3.9375 | 4 | x=[100,110,120,130,140,150]
for b in x:print(b*5)
#2
def divisible_by_three(n):
for number in range(1,n):
if number%3==0:
print(number)
divisible_by_three(16)
#3
x = [[1,2],[3,4],[5,6]]
new_list = []
for lists in x:
for numbers in lists:
new_list.append(numbers)
print(new_list)
def divisible_by_seven():
all_numbers = []
for number in range(100,200):
if number%7==0:
all_numbers.append(number)
print(all_numbers)
divisible_by_seven()
#6
x=range(100.200)
for b in x:
if b%7==0:
print(b)
#5
x=['a','b','a','e','d','b','c','e','f','g','h']
b=set(x)
print(b)
#7
students=[{"age":19,"name":"eunice"},{"age":21,"name":"Agnes"},{"age":18,"name":"Teresa"},{"age":22,"name":"sarah"}],
for student in students:
name=student['name']
age=students['age']
# sentence={f" {} you were born {}"
class Rectangle():
def __init__(self,width,length):
self.width=width
self.length=length
def area():
return 6*5
def perimeter():
return 8*6
|
cc3bf1286904124d585b7ea992970f67e7731253 | stellakaniaru/practice_solutions | /list_copy.py | 161 | 3.609375 | 4 | '''
Write a program that clones or copies a list.
'''
#function definition
def clone(list1):
#initialize a new list from the original one
return list(list1)
|
8904ac112ed9ac9a2186a04e07539ae9df083d36 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/meetup/e7c03b3b0f3547508dfb4b0d5edf682b.py | 1,440 | 3.921875 | 4 | from datetime import timedelta
from datetime import date
dayMap = {'Monday':0, 'Tuesday':1, 'Wednesday':2, 'Thursday':3, 'Friday':4, 'Saturday':5, 'Sunday':6}
modifierMap = {'1st':0, '2nd':1, '3rd':2, '4th':3}
def meetup_day(year, month, dayString, modifier):
"""Find first meeting day in specified year and month.
"""
# level set. find first instance of the day we want in specified month
workingDate = findFirstDayInMonth(year, month, dayMap[dayString])
# Now populate list with all days in month, including
# the first one we just identified
daysInMonth = []
while workingDate.month == month:
daysInMonth.append(workingDate)
workingDate += timedelta(7)
# Now select which day from the list we want
if modifier == 'teenth':
for day in daysInMonth:
if isTeenth(day.day):
return day
elif modifier == 'last':
return daysInMonth[-1]
else:
return daysInMonth[modifierMap[modifier]]
def isTeenth(day):
if day > 12 and day < 20:
return True
return False
def findFirstDayInMonth(year, month, day):
workingDate = date(year, month, 1)
weekday = workingDate.weekday()
# Find closest previous Monday to the first of the month,
# and then add back the offset for the day we want. If the
# result is still in the previous month, add another week
workingDate = workingDate - timedelta(weekday) + timedelta(day)
if workingDate.month < month:
workingDate = workingDate + timedelta(7)
return workingDate
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.