blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cd147b8843f5b5d42b0c7a06018644353cb4b441 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2377/60628/266940.py | 514 | 3.765625 | 4 | def noncolinearPoints(coordinates):
x_0 = coordinates[0][0]
y_0 = coordinates[0][1]
x_1 = coordinates[1][0]
y_1 = coordinates[1][1]
k = (y_0 - y_1) / (x_0 - x_1) if (x_0 != x_1) else 0
b = y_0 - k * x_0
x = coordinates[2][0]
y = coordinates[2][1]
if y != k * x + b:
return "True"
else:
return "False"
num = int(input())
coordinates = []
for i in range(num):
coordinates.append(list(map(int,input().split(','))))
print(noncolinearPoints(coordinates)) |
ace8e962431dff0e87a243940823a0407d09b9ef | cocoon333/DSL | /data_structure_learning/lifegame/test.py | 3,188 | 3.609375 | 4 | import unittest
from life import *
class TestLife(unittest.TestCase):
def setUp(self):
pass
def test_display(self):
l = Life()
s = l.display()
expr_s = """\
0 1 2 3 4 5 6 7 8 9
--------------------
0 | 0 0 0 0 0 0 0 0 0 0
1 | 0 0 0 0 0 0 0 0 0 0
2 | 0 0 0 0 0 0 0 0 0 0
3 | 0 0 0 0 0 0 0 0 0 0
4 | 0 0 0 0 0 0 0 0 0 0
5 | 0 0 0 0 0 0 0 0 0 0
6 | 0 0 0 0 0 0 0 0 0 0
7 | 0 0 0 0 0 0 0 0 0 0
8 | 0 0 0 0 0 0 0 0 0 0
9 | 0 0 0 0 0 0 0 0 0 0
"""
#self.assertEqual(s, expr_s)
pass
def test_neighbors(self):
l = Life()
n = l.neighbors(0, 0)
self.assertEqual(set(n), set([(0,1), (1,0), (1,1)]))
n = l.neighbors(1, 0)
self.assertEqual(set(n), set([(0, 0), (0, 1), (1, 1), (2, 0), (2, 1)]))
n = l.neighbors(5, 5)
self.assertEqual(set(n), set([(4, 4), (4, 5), (4, 6), (5, 4), (5, 6), (6, 4), (6, 5), (6, 6)]))
n = l.neighbors(9, 5)
self.assertEqual(set(n), set([(8, 4), (8, 5), (8, 6), (9, 4), (9, 6)]))
def test_set_next_live(self):
l = Life()
l.set_next_live(0, 0)
l.grid = l.next_grid
for r in range(len(l.grid)):
for c in range(len(l.grid[0])):
if r == 0 and c == 0:
self.assertEqual(l.next_grid[r][c], 1)
else:
self.assertEqual(l.next_grid[r][c], 0)
def test_set_next_dead(self):
l = Life()
l.set_next_live(0, 0)
l.grid = l.next_grid
for r in range(len(l.grid)):
for c in range(len(l.grid[0])):
if r == 0 and c == 0:
self.assertEqual(l.next_grid[r][c], 1)
else:
self.assertEqual(l.next_grid[r][c], 0)
l.set_next_dead(0, 0)
for r in range(len(l.grid)):
for c in range(len(l.grid[0])):
self.assertEqual(l.next_grid[r][c], 0)
def test_step(self):
l = Life()
l.step()
for r in l.grid:
for c in l.grid[0]:
self.assertFalse(c)
l.set_next_live(0, 0)
l.sync_next()
l.step()
for r in l.grid:
for c in l.grid[0]:
self.assertFalse(c)
l.set_next_live(0,0)
l.set_next_live(0,1)
l.set_next_live(1,0)
l.set_next_live(1,1)
l.sync_next()
l.step()
self.assertTrue(l.grid[0][0])
self.assertTrue(l.grid[0][1])
self.assertTrue(l.grid[1][0])
self.assertTrue(l.grid[1][1])
for r in l.grid[2:]:
for c in r:
self.assertFalse(c)
for r in l.grid[:2]:
for c in r[2:]:
self.assertFalse(c)
for i in xrange(10):
l.step()
self.assertTrue(l.grid[0][0])
self.assertTrue(l.grid[0][1])
self.assertTrue(l.grid[1][0])
self.assertTrue(l.grid[1][1])
for r in l.grid[2:]:
for c in r:
self.assertFalse(c)
for r in l.grid[:2]:
for c in r[2:]:
self.assertFalse(c)
if __name__ == '__main__':
unittest.main()
|
12b32961246747de71ccc58b125b53170ea77a2c | hermetique/eso | /metafractran/metafractran.py | 973 | 3.6875 | 4 | import sys
import re
import pathlib
import fractions as fr
path = pathlib.Path(sys.argv[1]).resolve()
if not path.is_file():
print("File does not exist")
sys.exit(1)
name, *parts = reversed(path.parts)
is_fraction = re.compile(r"^(\d+):(\d+)$")
fractions = []
for i in parts:
match = is_fraction.match(i)
if not match:
break
num, denom = match.groups()
fractions.append(fr.Fraction(int(num), int(denom)))
fractions.reverse() # they were added backwards
is_valid_name = re.compile(r"(\d+)(?:\..*)?")
match = is_valid_name.match(name)
if not match:
print("File name is not valid")
sys.exit(1)
num = int(match.group(1))
# run the fractran program
def run_fractran(num, fractions):
while True:
for i in fractions:
product = num * i
if product.denominator == 1:
num = int(product)
break
else:
return num
print(run_fractran(num, fractions)) |
66bd3d05de32aeee63c3a9f1e5d4e397d61d06a9 | tzphuang/python_work | /pythonJuly12.py | 6,544 | 4.5 | 4 | # ~~ PYTHON CLASS AND OBJECTS
# ~~ PYTHON CLASSES/ INHERITANCE ~~
# within the real world we have inheritance
# and real world objects that inherit are usually classed into parent-child relations
# these relations are more specific as you go down a heirarchy
# so for example we have a "car"
# a very generic term but specific enough to know what it is
# but there are cars such as gas cars/ electric cars
# this is a "specialized" car
# so this would be a child of the more general "Car"
# so as we go down in a hierarchy we are "specializing", kind of fine tuning a specific idea
# but as we go up a hierarchy we are "generalizing", kind of lopping off the extra features
# where we go back to the base model
# ~~ PASSING CLASSES/ FUNCTIONS TO THE CHILD ~~
# so just like Java we have inheritance where we reuse code from the parent
# as we make children classes that inherit not just code but features, its parent's has
# remember with inheritance, a electric car "IS" a car, but a car may not necessarily
# "IS" a electric car
# these sub classes, sometimes called derived classes, child class, extended class
# as it is a derivative of the original
# ~~ SUPER CLASS ~~
# the class from which a subclass is derived is its parent, or in inheritance terms
# it is its SUPER class
# in python we practice inheritance as follows
# class DerivedClassName(BaseClassName):
# <statement -1>
# ~~ EXAMPLE OF INHERITANCE ~~
class Book:
def __init__(self, title="", author="", isbn=""): # this is the constructor of book
self.title = title
self.author = author
self.isbn = isbn
# getters
# setters
# ...etc
def __repr__(self):
#object.__repr__(self): called by the repr() built-in function and
# by string conversions (reverse quotes) to compute the "official" string
# representation of an object.
# object.__str__(self): called by the str() build-in
# function and by the print statement to compute the "informal"
# string representation of an object.
return "Book class representing a book"
# ~~ this is too much repeated code ~~
# ~~ so instead we use the inheritance feature of object oriented programming ~~
# to do some of the legwork
#class Textbook(Book):
# pass
#def __init__(self, title="", author="", isbn="",subject=""): # Constructor of Textbook
#self.title = title
#self.author = author
#self.isbn = isbn
#self.subject = subject
# ~~ here we have the above code but using inheritance instead ~~
class Textbook(Book):
# pass
def __init__(self, title="", author="", isbn="",subject=""): # Constructor of Textbook
Book.__init__(self, title, author, isbn)
self.subject = subject
def __repr__(self):
return "Texbook class representing a Textbook"
text_book1 = Textbook()
text_book2 = Textbook("Python", "ISW", "777", "Excellence with Python")
print(text_book1) # prints its def __repr__(self): statement
print(text_book2)
print(text_book2.title)
# EVERYTHING INHERITS FROM OBJECTS
s3 = object()
print(s3)
# Java has a single parent class
# PYTHON YOU CAN INHERIT FROM MORE THAN ONE CLASS
# so a sub-class can have multiple parents
# java has abstract classes
# python also still has it called import ABS
# Question 2
#Group assignment:
#Extend Python's string class to represent a string literal only in a floating point number format.
#Add methods to convert the literal to the corresponding floating point number,
#to convert to an integer number and to split the literal into parts based on a given delimiter
#which default to "." character.
#Copy paste your code here:
class num_string(str):
# no need for initializer
# def __init__(self, strang)
# self.strang = strang
def to_int(self):
return int(float(self))
def to_float(self):
return float(self)
def split_float(self, delimeter = "."):
return super().split(delimeter)
# the super here only works because num_string is a child of the "str" class
# in this case it would be the (string).split(delimiter) method
# return str(self).split(delimiter)
string_float1 = num_string("123.456")
print(string_float1.to_int())
print(string_float1.to_float())
print(string_float1.lower())
print(string_float1.split())
# Question 3
#Create a Python class to represent a Pet. A pet is uniquely identified by its name,
#its owners name its tag number. A Pet also have an age.
class pet: #this is where you would inherit if you wanted to do that
def __init__(self, age, name="", owner_name="",tag_number=""): #default parameters go at the end
self.name = name
self.owner_name = owner_name
self.tag_number = tag_number
self.age = age
def __repr__(self): #tells the USER who is calling this class what, this OBJECT represents
return "This is a pet class object"
#Create another class to represent a mammal.
#Mammal has a description of what are mammals and specify
#how many mammals species have been found so far.
class mammal:
def __init__(self, amount_found, description=""): # default parameters go at the end
self.description = description
self.amount_found = amount_found
def __repr__(self):
return "This is a mammal class object"
#Write Python classes to represent a Pet and a Mammal.
#A Dog is a Pet. as well as a Mammal.
#A dog can be uniquely identified by its name and owners name and the tag name.
#A dog also has the field, breed and state whether the dog is sterilized or not.
#Write a Python Dog class that extends both from Pet and a Mammal.
class dog(pet, mammal): # dog object inherits from pet & mammal parent classes
count = 0 # this is a static variable as it is outside the actual instanced
# variables of an object
def __init__(self, tag_num, breed, sterilized, dog_name, owner_name):
count += 1 # updates the total dogs registered to the clinic (this activates everytime
# the initializer is called for dog, so the static count variable for
# the total counter for the class dog is incremented by 1)
pet.__init__(self, age, dog_name, owner_name, tag_num)
mammal.__init__(self, amount_found, description="")
self.breed = breed
#A veterinary clinic is going to use these class hierarchy for their use.
#Add a way to count all the dogs going to get registered (created) in the clinic. |
be1cae86c7c3dbf3e3ecd9fd619c211c9ff21b39 | Gsynf/PythonProject | /DayDayUp/DayDayUp.py | 508 | 3.578125 | 4 | #!usr/bin/env python3
#coding:utf-8
__author__ = 'hpf'
# 工作日工作进步,双休日休息退步1%,相比于每天都工作进步1%,工作日多努力才能追的上
def dayUP(df):
dayup = 1
for i in range(365):
if i % 7 in [6,0]:
dayup = dayup*(1-0.01)
else:
dayup = dayup*(1+df)
return dayup
dayfactor = 0.01
while dayUP(dayfactor) < round(pow(1+0.01, 365),2):
dayfactor += 0.001
print("工作日努力参数是:{:.3f}".format(dayfactor)) |
dd421baa1790303f151487ef67d5b421434bdae5 | richwandell/lc_python | /easy/21_merge_two_sorted_linked_lists.py | 1,681 | 4.03125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(-1)
current = head
while l1 is not None and l2 is not None:
if l1 is None:
current.next = l2.next
l2 = l2.next
elif l2 is None:
current.next = l1.next
l1 = l1.next
elif l1.val < l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
return head.next
l1 = ListNode(1, ListNode(2, ListNode(3)))
l2 = ListNode(1, ListNode(3, ListNode(4)))
s = Solution()
print(s.mergeTwoLists(l1, l2))
# class Solution:
# def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
#
# d = ListNode(-1)
# h = d
# while l1 is not None or l2 is not None:
# if l1 is None:
# d.next = l2
# l2 = l2.next
# elif l2 is None:
# d.next = l1
# l1 = l1.next
# elif l1.val > l2.val:
# d.next = l2
# l2 = l2.next
# else:
# d.next = l1
# l1 = l1.next
# d = d.next
# return h.next
#
#
#
# l1 = ListNode(1, ListNode(2, ListNode(3)))
# l2 = ListNode(1, ListNode(3, ListNode(4)))
# s = Solution()
# print(s.mergeTwoLists(l1, l2)) |
9f5252e0052f5dfdd3346ba200dae8bd1d372a24 | Donnyvdm/dojo19 | /team_10/haiku.py | 1,278 | 3.671875 | 4 | import wave
import os
import random
import sys
WORDS = {
1: [
'a',
'and',
'the',
'code',
'get',
'dance',
'will',
'fork',
'git',
'snake',
'plant',
'trees',
],
2: [
'python',
'dojo',
'dancing',
'pizza',
'cocos',
'Cardiff',
'London',
'Pycon',
'hurry',
'quickly',
],
3: [
'meditate',
'introspect',
'validate',
'optimist',
'realist',
'happiness',
'indulgence',
'decadence',
'unsponsored',
'reverted',
],
}
def generate_haiku():
lines = []
for syl_count in 5, 7, 5:
this_line = []
while syl_count > 3:
this_syl = random.randint(1, 3)
this_word = random.choice(
WORDS[this_syl]
)
syl_count -= this_syl
this_line.append(this_word)
if syl_count > 0:
this_line.append(random.choice(WORDS[syl_count]))
lines.append(' '.join(this_line))
return lines
def main():
haiku = generate_haiku()
for line in haiku:
print(line)
if __name__ == '__main__':
main() |
a941b266004bf04d6ea4f4a26577c4e0623f46f8 | rohanaurora/daily-coding-challenges | /Problems/running_sum.py | 494 | 3.953125 | 4 | # Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
#
# Return the running sum of nums.
# Input: nums = [1,2,3,4]
# Output: [1,3,6,10]
# Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
#
class Solution:
def runningSum(self, nums):
x = 0
res = []
for i in nums:
x += i
res.append(x)
return res
nums = [3,1,2,10,1]
s = Solution().runningSum(nums)
print(s)
|
2353347781517c3c74dd937959ff3e556b5fd270 | briant0618/Python | /Ch04/p99_example.py | 471 | 4.0625 | 4 | """
날짜 : 2021/04/29
이름 : 김동현
내용 : 딕트 객체 예시
"""
# dict 생성 1
dic = dict(key1=100, key2=200, key3=300)
print(dic)
# dict 생성 2
person = {'name': '홍길동', 'age': '25', 'address': '서울시'}
print(person)
print(person['name'])
print(type(dic), type(person))
# 원소 수정 삭제 추가
person['age'] = 45
print(person) # 수정
del person['address']
print(person) # 삭제
person['pay'] = 250
print(person) # 추가
|
24d24d68e3850740464cacc684cc4f7cebb1910b | Adarbe/opsschool4-coding | /hw.py | 453 | 3.5625 | 4 | import json
sorted_buckets = {}
data_dict = {}
def get_sorted_range():
return sorted(data_dict["buckets"])
with open("hw.json") as json_data:
data_dict = json.load(json_data)
print(data_dict)
sorted_buckets = get_sorted_range()
def if_in_range(min_age, max_age, age):
return min_age <= age <= max_age
for name, age in data_dict["ppl_ages"].items():
for i in range(0,len(sorted_buckets)):
if i = 0 and len
|
4ac453a9abcc30539027fefd20a64346e695ae2d | daniel-reich/ubiquitous-fiesta | /iLLqX4nC2HT2xxg3F_6.py | 245 | 3.6875 | 4 |
def deepest(lst):
count=0
maxi=0
print(str(lst))
for i in range(len(str(lst))):
if(str(lst)[i]=='['):
count+=1
if(count>maxi):
maxi=count
if(str(lst)[i]==']'):
count-=1
print(count)
return(maxi)
|
b65ca02c0d606c471e54e8f53b8bfaeba63919c9 | shoriwe-upb/blackjack | /dependencies/card.py | 624 | 3.734375 | 4 | class Card(object):
def __init__(self, card):
self.__raw_card = card
self.symbol = card[-1]
self.raw_value = card[:-1]
if card[:-1] in "AJQK":
if card[:-1] == "A":
self.value = 11
else:
self.value = 10
else:
self.value = int(card[:-1])
def __iter__(self):
for symbol in self.__raw_card:
yield symbol
def __repr__(self):
return self.__raw_card
def __str__(self):
return str(self.__repr__())
def __add__(self, other):
return self.value + other.value
|
2813ddc764b31204b27ec868f090fcc30041c42a | yuvrajschn15/Source | /Python/26-lambda.py | 372 | 4 | 4 | # If i have to add 21 to a number i can make a function for that like:
def add21_func(x):
return x + 21
print(add21_func(79))
# In python we can do this in just one line
add21 = lambda x: x + 21
print(add21(7))
# We can take two arguments too with a lambda function
divide = lambda x,y: x/y
q = int(input("> "))
w = int(input('(!= 0) > '))
print(divide(q,w))
|
1b59d84626211da1cdb7ba967f5d09e7ea5961eb | manolan1/PythonNotebooks | /Additional/0_Practice_Programs/Solutions/stopwatch.py | 1,168 | 4.09375 | 4 | #! /usr/bin/env python
"""
Script Name: stopwatch.py
Function: This script mimics a stopwatch with a lap timer
The directions are given below.
Make sure you display start when the stopwatch start.
Be sure that for a lap time you give the lap number
the total time and the lap time.
Use a <Ctrl-c> to exit from the script cleanly.
remember that a try: except: block will
capture a <Ctrl-c>
"""
import time
directions = \
"""
Press ENTER to begin.
Afterwards, press ENTER to get lap time.
Press Ctrl-C to quit.
"""
print(directions)
input('Press ENTER to Start')
print('Started.')
startTime = time.time()
lastTime = startTime
lapNum = 1
try:
while True:
input('Press ENTER to get lap time')
lapStopTime = time.time()
lapTime = round(lapStopTime - lastTime, 2)
totalTime = round(lapStopTime - startTime, 2)
print('Lap #%s: %ss (%ss)' % (lapNum, totalTime, lapTime))
lapNum += 1
lastTime = lapStopTime
except KeyboardInterrupt:
print('\nEnd of stopwatch')
|
c9d8014aa4a23ebb3faac92f7f00e847449f8f4b | GMwang550146647/network | /0.leetcode/1.LeetCodeProblems/0.example/未记录/3.PalindromeNumber.py | 1,902 | 4.25 | 4 | '''
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
'''
import time
class Solution():
def __init__(self):
self.num=19235713455431753291
'''我的方法'''
def myFun(self,num):
N = 0
for i in range(100):
if num // 10 ** i == 0:
N = i
break
for i in range(int(N / 2)):
forwardNum = num // 10 ** (N - 1 - i) % 10
backwardNum = num // 10 ** i % 10
if forwardNum != backwardNum:
return False
return True
'''答案方法1'''
'''原理:把数字翻转之后看看和原来的一样不'''
def normalWay(self,x):
z=x
y=0
while x>0:
y=y*10+x%10
x=x//10
return z==y
'''答案方法2'''
def fastWay(self,x):
if x<0 or (x!=0 and x%10==0):
return False
half=0
while x>half:
half=half*10+x%10
x=x//10
return x==half or half/10==x
def testTime(self,fun,num):
# 计时
start = time.process_time()
result = fun(num)
elapsed = (time.process_time() - start)
print(fun.__name__,":")
print("Time used:", elapsed)
print('result:', result)
def main(self):
self.testTime(self.myFun,self.num)
self.testTime(self.normalWay,self.num)
self.testTime(self.fastWay,self.num)
SL=Solution()
SL.main() |
7b9139f0792e83819679dbd61f7e44b7340ac8ae | andymc1/ipc20161 | /lista1/ipc_lista1.15.py | 1,247 | 3.734375 | 4 | #ipc_lista1.15
#Professor: Jucimar Junior
#Any Mendes Carvalho - 1615310044
#
#
#
#
#Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS e 5% para o sindicato, faça um programa que nos dê:
#salário bruto.
#quanto pagou ao INSS.
#quanto pagou ao sindicato.
#o salário líquido.
#calcule os descontos e o salário líquido, conforme a tabela abaixo:
#+ Salário Bruto : R$
#- IR (11%) : R$
#- INSS (8%) : R$
#- Sindicato ( 5%) : R$
#= Salário Liquido : R$
#Obs.: Salário Bruto - Descontos = Salário Líquido.
qHora = input("Quanto voce ganha por hora: ")
hT = input("Quantas horas voce trabalhou: ")
SalBruto = qHora
ir = (11/100.0 * SalBruto)
inss = (8/100.0 * SalBruto)
sindicato = (5/100.0 * SalBruto)
vT = ir + sindicato
SalLiq = SalBruto - vT
print "------------------------"
print "Seu salario bruto e: ",SalBruto
print '------------------------"
print "Valor dos impostos"
print "-------------------------"
print "IR: ",ir
print "INSS: ",inss
print"--------------------------"
print"Se salario liquido e: ",SalLiq
|
f81c910b6462f6beb4b0a6f9aa8a648de8e70a07 | ccalsbeek/python-challenge | /PyBank/main.py | 2,166 | 3.78125 | 4 | #Dependencies
import os
import csv
#define variables
months = 0
net_profitloss = 0
profit = 0
profit_log = []
totalchange = 0
change = 0
avg_change = 0
gincrease = "0"
gdecrease = "0"
i_month = ""
d_month = ""
#define path to csv data
path = os.path.join("Resources", "budget_data.csv")
#read csv
with open (path) as budget_data:
data = csv.reader(budget_data)
#skip header
header = next(data)
#set condition to skip first row in looping
skip = True
#start for loop to iterate through rows
for row in data:
#skip first row and set skip to False for loop calcs
if skip is True:
profit = int(row[1])
skip = False
#start counters and calcs
#calculate total months
months += 1 # <--add month for each loop
#calculate total profits and losses
net_profitloss += profit # <-- totals profits and losses each loop
profit_log = int(row[1]) # <-- tracks profits
date = str(row[0]) # <-- tracks month
change = profit_log - profit # <-- tracks changes between months
#calculate greatest increase in profits/losses
if float(gincrease) < change: # <-- stores value of change if it's larger than gincrease variable
gincrease = change
i_month = date
#calculate greatest decrease in profits/losses
if float(gdecrease) > change:
gdecrease = change
d_month = date
totalchange += change # <-- tracks total for avg calc
profit = profit_log # <-- sets value for next loop
#Calculate average change
avg_change = totalchange / (months - 1)
#print and save analysis output
output = (
f"Financial Analysis\n"
f"----------------------------\n"
f"Total Months: {months}\n"
f"Total Profits: ${net_profitloss}\n"
f"Average Change: $ {avg_change:.2f}\n"
f"Greatest Increase: {i_month} (${gincrease})\n"
f"Greatest Decrease: {d_month} (${gdecrease})\n"
)
print(output)
o_path = os.path.join("Analysis", "budget_analysis.txt")
with open(o_path, "w") as analysis:
analysis.write(output)
|
5f7ceffcee8710318b26536ac490428b986e8a19 | Hoouoo/Backjoon_Python | /boj14916.py | 331 | 3.703125 | 4 | '''
date : 2021-02-19
algorithm : math, dynamic programing, greedy, brute force
boj 141916
'''
N = int(input())
mod = N % 5
ans = 0
if N == 1 or N == 3:
ans = -1
print(ans)
elif mod % 2 == 0:
ans = (N // 5) + (N % 5 // 2)
print(ans)
else:
ans = (N // 5 - 1) + ((N - (N // 5 -1 ) * 5 ) // 2)
print(ans)
|
ef541533b69762b0f3f07e3c6005e8b0e489b31b | imzhen/Leetcode-Exercise | /src/divide-two-integers.py | 1,234 | 3.59375 | 4 | #
# [29] Divide Two Integers
#
# https://leetcode.com/problems/divide-two-integers
#
# Medium (15.95%)
# Total Accepted: 96016
# Total Submissions: 601498
# Testcase Example: '0\n1'
#
#
# Divide two integers without using multiplication, division and mod
# operator.
#
#
# If it is overflow, return MAX_INT.
#
#
class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
if divisor == 0:
if dividend >= 0:
return 2 ** 31 - 1
else:
return - 2 ** 31
if dividend == 0:
return 0
if dividend == - 2 ** 31 and divisor == -1:
return 2 ** 31 - 1
if (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0):
signal = False
else:
signal = True
result = 0
a = abs(dividend)
b = abs(divisor)
while a >= b:
shift = 0
while a >= b << shift:
shift += 1
a -= b << (shift - 1)
result += 1 << (shift - 1)
if signal:
return result
else:
return -result
|
e25405765d6013e96a00ec660e2591030217f32d | cuc496/Vulnerability-Analysis-of-Network-Tomography-under-Attacks | /dijkstra.py | 1,429 | 3.65625 | 4 | def edgebetw(u,v):
for e in u.edges():
if e in v.edges():
return e
return -1
def getAdjNodes(node):
nodes = []
for e in node.edges():
if e.node1 != node:
nodes.append(e.node1)
if e.node2 != node:
nodes.append(e.node2)
return nodes
def shortestpath(graph, cost, source, target):
dist = {node:float("inf") for node in graph.nodes()}
dist[source] = 0
#print(dist)
pre = {node:None for node in graph.nodes()}
while dist:
#print("dist:{}".format(dist))
minNode = min(dist, key = lambda x : dist.get(x))
if minNode == target:
break
mindist = dist.pop(minNode)
#print("mindist:{}".format(mindist))
if mindist == float("inf"):
return -1
#print("getAdjNodes(minNode):{}".format(getAdjNodes(minNode)))
for node in getAdjNodes(minNode):
if node not in dist:
continue
#e = edgebetw(minNode, node)
#c=cost(e)
c = 1.0
if dist[node] > (mindist + c):
dist[node] = mindist + c
pre[node] = minNode
pathByEdge = []
current = target
while pre[current]:
pathByEdge.insert(0, edgebetw(pre[current], current))
current = pre[current]
return [pathByEdge] |
b5d887b347ea5a23019afd6e948437009992b38e | Nandan093/Python | /Loop statements.py | 634 | 4.25 | 4 | #with/without vowel check
a = ["hello", "bcd", "gcd", "hhmmm", "python"]
print("Input list ",a)
vowel= []
without_vowel = []
for i in a:
if ("a" in i or "e" in i or "i" in i or "o" in i or "e" in i):
vowel.append(i)
else:
without_vowel.append(i)
print("The list with vowels ", vowel)
print("The list without vowels ",without_vowel)
#Starts with h :
h = []
for i in a:
if(i[0] == "h"):
h.append(i)
print("The list with first letter h ",h)
#Ends with d
d =[]
for i in a:
if(i[-1] == "d"):
d.append(i)
print("The list with last letter d ",d)
|
b86460c42c89f62c7830cde1b2562a9ff9394607 | primeschool-it/Y13 | /classes.py | 1,386 | 4.46875 | 4 | # 1.Classes
# 2. Objects or Instance or Class Members
# 3. Properties of Objects
# 4. Getting Values from Objects
# 5. Setting Values to Objects
# 6. Deleting an object
from datetime import datetime
class Y11():
###Initialization of the class
def __init__(self, student_name, student_age, student_dob):
print("instanciating member....",student_name)
self.name = student_name
self.age = student_age
self.dob = student_dob
self.batch_start_date = '2020-08-01'
def get_age(self):
print("computing Age for ...",self.name)
today_date = datetime.today().date()
student_dob = datetime.strptime(self.dob, "%Y-%m-%d").date()
age = (today_date - student_dob).days
return "%s days"%age
class Y12():
###Initialization of the class
def __init__(self, student_name, student_dob):
self.name = student_name
self.dob = student_dob
self.batch_start_date = '2020-08-01'
## Instance of the class
a = Y11('A', 11, '2000-01-01')
b = Y11('B', 12, '2000-05-04')
e = Y12('E', '2000-01-01')
f = Y12('F', '2000-05-04')
## Set Property of an object
a.address = 'Estoril'
## Get Property of an object
age = a.get_age()
age = b.get_age()
## Error because e is instance of class Y12 which has no method get_age()
## age = e.get_age()
# print(age)
## deleting an object
del a
print() |
cfe676db3a8eb5a0b695a483d55f4c7e0d3c53bc | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/allnas012/question1.py | 448 | 4.0625 | 4 | #Nasiha Ally
#ALLNAS012
#May 2014
def pal(string):
if (string):
if (string[0] == string[-1]):
result =pal(string[1:-1])
if result:
return True
else:
return True
return False
if __name__ == "__main__":
x = input("Enter a string:\n")
result = pal( x )
if not result:
print("Not a palindrome!")
else:
print("Palindrome!")
|
b5df155f9988f5fbe4c49b8af760007806bf9030 | g0v/nowin_core | /nowin_core/memory/audio_stream.py | 5,536 | 3.734375 | 4 |
class AudioStream(object):
"""Audio stream
"""
def __init__(self, blockSize=1024, blockCount=128, base=0):
"""
The bytes is a big memory chunk, it buffers all incoming audio data.
There are blocks in the memory chunk, they are the basic unit to send
to peer.
<-------------- Memory chunk ------------------>
<--Block1--><--Block2--><--Block3--><--Block4-->
^ ^ ^ ^
L1 L2 L3 L4
We map blocks to the real audio stream
<------------------ Audio Stream --------------> ---> time goes
<--Block3--><--Block4--><--Block1--><--Block2-->
Map to
<-------------- Memory chunk ------------------>
<--Block1--><--Block2--><--Block3--><--Block4-->
Every listener got their offset of whole audio stream, so that we can
know which block he got.
------------<------------------ Audio Stream --------------> --->
<--Block3--><--Block4--><--Block1--><--Block2-->
^
L5
When there is a listener point to a out of buffer window place, we
should move the pointer to the first current block.
------------<------------------ Audio Stream --------------> --->
<--Block3--><--Block4--><--Block1--><--Block2-->
^
L5
@param blockSize: size of block
@param blockCount: count of blocks
"""
self._blockSize = blockSize
self._blockCount = blockCount
self._bufferSize = blockSize * blockCount
#: base address of buffering windows
self._base = base
#: total size of written data in blocks (not include chunk pieces)
self._size = base
#: bytes array
self._bytes = bytearray(self.bufferSize)
#: small chunks, they are not big enough to fit a block
self._pieces = []
#: total size of pieces
self._pieceSize = 0
def _getBlockSize(self):
return self._blockSize
blockSize = property(_getBlockSize)
def _getBlockCount(self):
return self._blockCount
blockCount = property(_getBlockCount)
def _getBufferSize(self):
return self._bufferSize
bufferSize = property(_getBufferSize)
def _getBase(self):
return self._base
base = property(_getBase)
def _getSize(self):
return self._size
size = property(_getSize)
def _getBuffer(self):
return str(self._bytes)
buffer = property(_getBuffer)
def _getMiddle(self):
"""Address of middle block
"""
return self.base + (((self.size - self.base) / self.blockSize) / 2) * \
self.blockSize
middle = property(_getMiddle)
def _getData(self):
"""Get current audio data we have in correct order
for example, we have 3 blocks
<--Block 3--><--Block 1--><--Block 2-->
and some extra not integrated data pieces
<--Chunk-->
Then we should get
<--Block 1--><--Block 2--><--Block3--><--Chunk-->
as result
"""
# total bytes we have in the buffer (as blocks)
total = self.size - self.base
# the begin offset of first block in buffer
begin = self.base % self.bufferSize
# the tail part
tail = self._bytes[begin:total]
# the head part
head = self._bytes[0:begin]
# not integrated chunk
chunk = ''.join(self._pieces)
return tail + head + chunk
data = property(_getData)
def write(self, chunk):
"""Write audio data to audio stream
@param chunk: audio data chunk to write
"""
# append chunk to pieces
self._pieces.append(chunk)
self._pieceSize += len(chunk)
while self._pieceSize >= self.blockSize:
whole = ''.join(self._pieces)
block = whole[:self.blockSize]
# there is still some remaining piece
if self._pieceSize - self.blockSize > 0:
self._pieces = [whole[self.blockSize:]]
self._pieceSize = len(self._pieces[0])
else:
self._pieces = []
self._pieceSize = 0
# write the block to buffer
begin = self.size % self.bufferSize
oldSize = len(self._bytes)
self._bytes[begin:begin + self.blockSize] = block
assert len(self._bytes) == oldSize, "buffer size is changed"
self._size += len(block)
delta = self.size - self.base
# if the base out of buffer window, move it to begin of window
if delta > self.bufferSize:
self._base = self.size - self.bufferSize
def read(self, offset, no_copy=False):
"""Read a block from audio stream
@param offset: offset to read block
@return: (block, new offset)
"""
# we don't have new data
if offset >= self.size:
return None, offset
# out of window
if offset < self.base:
offset = self.middle
begin = offset % self.bufferSize
assert begin >= 0
assert begin < self.bufferSize
if no_copy:
block = buffer(self._bytes, begin, self.blockSize)
else:
block = str(self._bytes[begin:begin + self.blockSize])
offset += self.blockSize
return block, offset
|
1be1170d58665ca75e143231abc438d3954a8021 | piphind/MyPython | /User Functions.py | 138 | 3.609375 | 4 | def mean(mylist):
calcmean = sum(mylist) / len(mylist)
return calcmean
print("The mean of my list is", mean([1,2,3,4,5]))
|
434dd644617117f863d8210439ef532f3d537816 | padampadampadam/MLD-HandsOn | /Session-4/src/feature-3.py | 1,540 | 3.5625 | 4 | #!/usr/bin/env python
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
# defining global variable
dataset_path = "../dataset/train.csv"
selected_variables = ["YearBuilt", "BedroomAbvGr", "KitchenAbvGr", "SalePrice"]
target_varibale = ["SalePrice"]
def data_selection(data, selected_variables):
# function to select data
data = data[selected_variables]
return data
def data_validation(data, quantile1=0.25, quantile2=0.75):
# function to select data
message = "function for data validation"
Q1 = data.quantile(quantile1)
Q3 = data.quantile(quantile2)
IQR = Q3 - Q1
# remove outlier from each columns
data = data[~((data < (Q1 - 1.5 * IQR)) | (data > (Q3 + 1.5 * IQR)))]
data = data.dropna()
return data
def data_preprocessing():
# function for data pre-processing
message = "function for data preprocessing"
def feature_extractor():
# function for feature_extractor
message = "function for feature extractor"
def data_split():
# function for splitting data into training and testing
message = "function for data split"
if __name__ == '__main__':
# read data
data = pd.read_csv(dataset_path)
print(data.shape)
print(data.head(5))
# data selection
data = data_selection(data, selected_variables)
print(data.shape)
print(data.head(5))
# data validation
data = data_validation(data)
print(data.shape)
print(data.head(5)) |
4466641c4704999ece18d7cb34a8acb3e3f6d02d | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/kristoffer_jonson/lesson3/strformat_lab.py | 1,793 | 3.859375 | 4 | #!/usr/bin/env python3
#task one
task_one_string = 'file_{:0>3} : {:.2f}, {:.2e}, {:.3g}'
input_tuple = ( 2, 123.4567, 10000, 12345.67)
print(task_one_string.format(*input_tuple))
#task two
task_two_string = 'file_{file_name:0>3} : {file_attr_1:.2f}, {file_attr_2:.2e}, {file_attr_3:.3g}'
print(task_two_string.format(file_name=2, file_attr_1 = 123.456, file_attr_2 = 10000, file_attr_3 = 12345.67))
#task three
def formatter(in_tuple):
l = len(in_tuple)
format_string = ', '.join(['{:d}']*l)
format_string = 'the {} numbers are: ' + format_string
return format_string.format(l,*in_tuple)
#task four
input_tuple = ( 4, 30, 2017, 2, 27)
format_string = '{3:02d} {4} {2} {0:02d} {1}'
print(format_string.format(*input_tuple))
#task five
input_list = ['oranges', 1.3, 'lemons', 1.1]
print(f'The weight of an {input_list[0][:-1].upper()} is {input_list[1]*1.2:.1f} and the weight of a {input_list[2][:-1].upper()} is {input_list[3]*1.2:.1f}')
#task six
'''
Write some Python code to print a table of several rows, each with a name, an age and a cost. Make sure some of the costs are in the hundreds and thousands to test your alignment specifiers.
And for an extra task, given a tuple with 10 consecutive numbers, can you work how to quickly print the tuple in columns that are 5 charaters wide? It can be done on one short line!
'''
input_table = [ ['kris', 37, 10],
['yiling', 37, 100],
['chase', 36, 1000],
['torey', 34, 10000],
['lina', 82, 100000]]
format_string = '{:>10} {:>3} {:>6d}'
print(' name age cost')
for i in input_table:
print(format_string.format(i[0],i[1],i[2]))
#task extra
input_tuple = list(range(995,1005))
print("\n".join(["{:>5}"]*len(input_tuple)).format(*input_tuple)) |
2f962b44ccd2c3e829885e3f549de7bbeff41f41 | jogusuvarna/jala_technologies | /smaller_lyarge.p.py | 300 | 4.09375 | 4 | # Print the smaller and larger number
l=[1,5,4,8,6,9,10]
print(max(l))
print(min(l))
#and
a=[]
n=int(input("Enter size of a:"))
for i in range(n):
num=int(input("Enter the number:"))
a.append(num)
print("the largest number in a is:", max(a))
print("the smallest number in a is:",min(a))
|
ad2fe989d4b82221c5552f108986b0984fe67373 | Edvinauskas/Project-Euler | /nr_017_python.py | 1,485 | 3.703125 | 4 | #########################################
# Problem Nr. 17
# If the numbers 1 to 5 are written out in
# words: one, two, three, four, five, then
# there are 3 + 3 + 5 + 4 + 4 = 19 letters
# used in total.
#
# If all the numbers from 1 to 1000 (one thousand)
# inclusive were written out in words, how many
# letters would be used?
#
# NOTE: Do not count spaces or hyphens. For
# example, 342 (three hundred and forty-two)
# contains 23 letters and 115 (one hundred and fifteen)
# contains 20 letters. The use of "and" when
# writing out numbers is in compliance with British usage.
#########################################
ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
teens = ["", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
tens = ["", "ten", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"]
hundred = ["hundred"]
def numbers_to_words(num):
in_words = []
num_int = [int(i) for i in str(num)][::-1]
print num_int
if num < 10:
return ones[num]
i = 1
for i in range(1, len(num_int)):
if num_int[i] == 1 and num_int[i - 1] != 0:
in_words.append(teens[num_int[i - 1]])
else:
in_words.append(tens[i])
return in_words
letter_count = 0
for i in range(1, 25):
written_out = numbers_to_words(i)
letter_count += len(written_out)
print written_out
print letter_count |
3e9a5b97743173f7ec8394bf1f22c889a0827df2 | crashoverloaded/Data-Structures-and-Algos | /Day1/Stack/Convert_int2bin.py | 261 | 3.75 | 4 | #!/usr/bin/python3
from stack import Stack
def div_by2(dec_num):
s = Stack()
while dec_num > 0:
r = dec_num % 2
s.push(r)
dec_num = dec_num // 2
bin_str=""
while not s.is_empty():
bin_str += str(s.pop())
return bin_str
print(div_by2(242))
|
78646abd065b5cea6c564d4a0c778c0d4c6accce | thunde47/CTCI | /1-arrays-and-strings/1.4-palindrome_permutation.py | 303 | 3.6875 | 4 | def palindrome(s):
s=s.lower().replace(' ','')
d=dict()
for a in s: #O(N)
if a in d:
d[a]+=1
else:
d[a]=1
odds=0
for key in d: #worst O(N)
if d[key]%2==1:
odds+=1
if odds>1:
return False
return True
s="taCttt ca o ooooooioo"
print(palindrome(s))
|
1c842a895fb006714d45b934a546e03bb5939167 | Kaiepi/py-Hangman | /hangman.py | 3,497 | 4.1875 | 4 | #!/usr/bin/env python3
from random import choice
class Hangman:
"""
self.target - the progress of the guessed word
self.guessed - guessed letters
self.guessed_words - guessed words
self.wrong_answers - number of mistakes made, a maximum of 6 allowed
self.ended - whether or not the game is finished
self.__word - the full word you're attempting to guess
"""
def __init__(self):
self.target = ''
self.guessed = set()
self.guessed_words = set()
self.wrong_answers = 0
self.ended = False
self.__word = ''
def run(self):
while True:
print('The Hangman game has started!')
self.get_random_word()
self.update_word()
while not self.ended:
self.print_info()
guess = self.get_guess()
self.check_guess(guess)
print()
response = ''
while response != 'y' and response != 'n':
response = input('Would you like to play again? [y/n]: ')
if response == 'y':
self.reset()
print()
else:
break
def reset(self):
self.target = ''
self.guessed.clear()
self.guessed_words.clear()
self.wrong_answers = 0
self.ended = False
self.__word = ''
def get_random_word(self):
with open('dictionary', 'r') as fh:
lines = fh.readlines()
self.__word = choice(lines).rstrip()
def update_word(self):
target = ''
for ch in self.__word:
if ch in self.guessed:
target += ch
else:
target += '_'
self.target = target
def print_info(self):
print(self.target)
guessed = sorted(self.guessed)
guessed = ' '.join(guessed)
print(f'Guessed letters: {guessed}')
guessed_words = sorted(self.guessed_words)
guessed_words = ' '.join(guessed_words)
print(f'Guessed words: {guessed_words}')
def get_guess(self):
guess = '';
while guess == '':
guess = input('Guess a letter or word: ')
guess = guess.upper()
return guess
def check_guess(self, guess):
if guess in self.guessed:
print(f'{guess} has already been guessed.')
return False
if len(guess) > 1 and len(guess) < len(self.__word):
print(f'{guess} does not match the current word.')
return False
if len(guess) == 1:
self.guessed.add(guess)
else:
self.guessed_words.add(guess)
if guess not in self.__word:
print(f'{guess} is not in or is not the current word.')
if self.wrong_answers < 5:
self.wrong_answers += 1
print(f'You currently have {6 - self.wrong_answers} wrong answers remaining.')
else:
self.ended = True;
print(f'You have lost the game. The word was {self.__word}.')
return False
print(f'You correctly guessed {guess}!')
self.update_word()
if self.target == self.__word or guess == self.__word:
self.ended = True
print('You have won the game!')
return True
if __name__ == '__main__':
hangman = Hangman()
hangman.run()
|
d73b41abbdd6f1425d9b55ace4aac40268d3c0ca | mailsonalidhru/SATScore | /SATScore/SATScore.py | 3,445 | 3.65625 | 4 | ##### Import Libraries Section #####
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
##### Variables Initialization #####
data = pd.read_csv("C:\\Personal\\Data\\scores.csv")
##### Processing Section #####
print('Highest average SAT Math score {} Lowest score {}.'.format(
int(data['Average Score (SAT Math)'].max()), int(data['Average Score (SAT Math)'].min())))
print('\t')
print('Highest average SAT Reading score {} Lowest Score {}.'.format(
int(data['Average Score (SAT Reading)'].max()), int(data['Average Score (SAT Reading)'].min())))
print('\t')
print('Highest average SAT Writing score {} Lowest {}.'.format(
int(data['Average Score (SAT Writing)'].max()), int(data['Average Score (SAT Writing)'].min())))
print("Best School with Overall Average SAT Math Score {}.".format(
data.loc[data['Average Score (SAT Math)']==754, 'School Name'].values[0]))
print('\t')
print("Worst School with Overall Average SAT Math Score {}".format(
data.loc[data['Average Score (SAT Math)']==317, 'School Name'].values[0]))
print("Best School with Overall Average SAT Reading Score {}.".format(
data.loc[data['Average Score (SAT Reading)']==697, 'School Name'].values[0]))
print('\t')
print("Worst School with Overall Average SAT Reading Score {}".format(
data.loc[data['Average Score (SAT Reading)']==302, 'School Name'].values[0]))
print("Best Shool with Overall Average SAT Writing Score {}.".format(
data.loc[data['Average Score (SAT Writing)']==693, 'School Name'].values[0]))
print('\t')
print("Worst School with Overall Average SAT Writing Score was {}".format(
data.loc[data['Average Score (SAT Writing)']==284, 'School Name'].values[0]))
#### Label Bars in the Barplots
def barlabel(b, i):
for bar in bars:
height = bar.get_height()
ax[i].text(bar.get_x()+bar.get_width()/2., 0.90*height,
'%d' % int(height), color='white', ha='center', va='bottom')
fig, ax = plt.subplots(3, figsize=(8, 12))
ind = np.arange(5)
width = 0.35
bars = ax[0].bar((ind+width), data.groupby('Borough')['Average Score (SAT Math)'].max())
ax[0].set_facecolor("white")
ax[0].set_title("Max Average SAT Math Score by Borough (2014-2015)", fontsize=18)
ax[0].set_xlabel('')
ax[0].set_xticks(ind+width/1.0)
ax[0].set_xticklabels(labels=data.groupby('Borough')['Average Score (SAT Math)'].max().index)
ax[0].set_yticklabels("")
barlabel(bars, 0)
bars[1].set_color('#f45c42')
bars[2].set_color('#41f4d9');
bars = ax[1].bar((ind+width), data.groupby('Borough')['Average Score (SAT Reading)'].max())
ax[1].set_facecolor("white")
ax[1].set_title("Max Average SAT Reading Score by Borough (2014-2015)", fontsize=18)
ax[1].set_xlabel('')
ax[1].set_xticks(ind+width/1.0)
ax[1].set_xticklabels(labels=data.groupby('Borough')['Average Score (SAT Reading)'].max().index)
ax[1].set_yticklabels("")
barlabel(bars, 1)
bars[1].set_color('#f45c42')
bars[2].set_color('#41f4d9')
bars = ax[2].bar((ind+width), data.groupby('Borough')['Average Score (SAT Writing)'].max())
ax[2].set_facecolor("white")
ax[2].set_title("Max Average SAT Writing Score by Borough (2014-2015)", fontsize=18)
ax[2].set_xlabel('')
ax[2].set_xticks(ind+width/1.0)
ax[2].set_xticklabels(labels=data.groupby('Borough')['Average Score (SAT Writing)'].max().index)
ax[2].set_yticklabels("")
barlabel(bars, 2)
bars[1].set_color('#f45c42')
bars[2].set_color('#41f4d9')
plt.tight_layout();
plt.show();
|
06802b6e78e07a921d8c46b6dcab60252494d698 | 1oss1ess/HackBulgaria-Programming101-Python-2018 | /week-7/engin/unit.py | 3,655 | 3.546875 | 4 | from weapon import Weapon
from spell import Spell
class Unit:
def __init__(self, health, mana):
if self.validate_value(health):
raise TypeError('Value must be a number!')
if self.validate_value(mana):
raise TypeError('Value must be a number!')
self.health = health
self.mana = mana
self.__max_hp = health
self.__max_mana = mana
self.weapon = None
self.spell = None
@staticmethod
def validate_value(val):
if val < 0:
raise ValueError('Value cannot be negative!')
if not isinstance(val, (int, float)):
return True
return False
def get_health(self):
return self.health
def get_mana(self):
return self.mana
def is_alive(self):
if self.health <= 0:
return False
return True
def can_cast(self):
if not self.has_spell():
return False
if self.spell.mana_cost > self.mana:
return False
return True
def has_weapon(self):
return self.weapon is not None
def has_spell(self):
return self.spell is not None
def take_damage(self, damage):
if self.validate_value(damage):
raise TypeError('Enter valid damage!')
if self.health - damage < 0:
self.health = 0
else:
self.health -= damage
def take_healing(self, healing_points):
if self.validate_value(healing_points):
raise TypeError('Enter valid healing points!')
if not self.is_alive():
return 'Cannot heal a corpse!'
if self.health + healing_points > self.__max_hp:
self.health = self.__max_hp
else:
self.health += healing_points
def take_mana(self, mana_points):
if self.validate_value(mana_points):
raise TypeError('Enter valid mana points!')
if self.mana + mana_points > self.__max_mana:
self.mana = self.__max_mana
else:
self.mana += mana_points
def equip_weapon(self, weapon):
if not isinstance(weapon, Weapon):
raise TypeError('Weapon must be instance of Weapon!')
else:
self.weapon = weapon
def learn_spell(self, spell):
if not isinstance(spell, Spell):
raise TypeError('Spell mist be instance of Spell!')
else:
self.spell = spell
def get_damage_source(self):
if self.has_spell() and self.has_weapon():
if self.spell.damage >= self.weapon.damage:
if self.can_cast():
return 'spell'
return 'weapon'
elif self.has_spell():
if self.can_cast():
return 'spell'
elif self.has_weapon():
return 'weapon'
else:
return None
def attack(self, by=''):
if by not in ('weapon', 'spell', ''):
raise Exception('Enter valid attack type!')
if by == 'weapon':
if self.weapon is None:
raise Exception('No Weapon!')
return self.weapon.damage
if by == 'spell':
if not self.has_spell():
raise Exception('No Spell Learned!')
if self.can_cast():
self.mana -= self.spell.mana_cost
return self.spell.damage
else:
raise Exception('Not Enough Mana!')
else:
return None
|
35cfc54ffaa0eb4abeff43f73faef737722d3b8b | smswajan/mis-210 | /Chapter-5/5.09-Financial-application--compute-future-tuition.py | 448 | 3.75 | 4 | tuitionFee = 10000
year = 0
total = 0
while year < 10:
tuitionFee = tuitionFee * 1.05
year = year + 1
tuitionFee = round(tuitionFee, 2)
print("Tuition at the end of 10 years is ${0}".format(tuitionFee))
while year < 14:
tuitionFee = tuitionFee * 1.05
year = year + 1
total = total + tuitionFee
total = round(total, 2)
print("After 10 years, total cost of four years' tuition will be ${0}".format(total))
|
c559cde2cb28756ee7c4c4614819bd8d3f388c5a | zhouli01/python3 | /List.py | 145 | 3.828125 | 4 | #!/usr/bin/python3
#coding:UTF-8
list1=['hello','world','zhouli']
list2=list(range(5))
list1.extend(list2)
print ("扩展后的列表:", list1) |
d80e44a169d155e4e11e4c2df431bf8c846448fa | juanmunoz22-bit/python-intermedio | /list_dicts.py | 735 | 3.75 | 4 | def run():
my_list = [1, 'Hello', True, 4.5]
my_dict = {'firstname': 'Juan', 'lastname': 'Muñoz'}
super_list = [
{'firstname': 'Juan', 'lastname': 'Muñoz'},
{'firstname': 'Pedro', 'lastname': 'Perez'},
{'firstname': 'Maria', 'lastname': 'Gonzalez'},
{'firstname': 'Jose', 'lastname': 'Gomez'},
{'firstname': 'Ana', 'lastname': 'Lopez'}
]
super_dict = {
'natural_nums': [1, 2, 3, 4, 5],
'integer_nums': [-1, -2, 0, 1, 2],
'floating_nums': [1.1, 2.2, 3.3, 4.4, 5.5],
}
#for key, value in super_dict.items():
# print(key, '-', value)
for value in super_list:
print(value['firstname'])
if __name__ == '__main__':
run() |
c0326e9fc27cf1f4bcf863c98e3d611d10968b66 | yinglang/MyCodeInUse | /MLInAction/base/pythonModeTest.py | 2,648 | 3.828125 | 4 | # coding=utf-8
import operator
def sortedTest():
# list tuple 排序, key的参数是 for key in students
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]
print sorted(students, key=lambda student : student[2]) # sort by age
print sorted(students, key=lambda student : student[2], reverse=True) # sort by age
# dict 排序 由于 for key in dict ,只会返回key,没有value,无法通过index获得key
# 所以对于key 我们使用 iteritems(), for item in ages.iteritems() 返回的是键值对
ages = {'john': 15, 'jane': 12, 'dave': 10}
print sorted(ages.iteritems(), key=lambda ageItem : ageItem[1])
# 等价于
print sorted(ages.iteritems(),key=operator.itemgetter(1))
import random
def dictTest():
keys = ['A', 'B', 'C']
dic = {}
for i in range(50):
index = random.randint(0, 2) # [0, 2]
key = keys[index]
dic[key] = dic.get(key, 0) + 1 # get(key, defaultValue) 获取value, 如果在树上没有找到key,默认为0
print dic
dictTest()
def classAttrTest():
testobj = dict()
testobj["abc"] = 100
if hasattr(testobj, "abc"): print "has abc" # dict的属性在keys中不再dir出的对象属性中
# setattr(testobj, "edf", 10)对于这种基本数据类型,不能添加属性
for attr in dir(testobj):
if attr[0] != "_":
print attr, getattr(testobj,attr)
classAttrTest()
def frange(start, end, step):
alist = []
num = start
while num <= end:
alist.append(num)
num += step
return alist
# python extend 和 append是对原list操作,而返回none
def extend_append():
a = [1,2,3]
print a
print a.append([1,2])
print a
print a.extend([1,2])
print a
# 删除某个元素
def delete1(alist, index):
del(alist[index])
return alist
# 由于list是引用传递的,所以在写并行程序或递归程序时经常要求保留原list不变,而返回修改后的copy list
def delete2(alist, index):
newlist = alist[:] # 深拷贝
del(newlist[index])
return newlist
def delete3(alist, index):
newlist = alist[:index]
newlist.extend(alist[index+1:])
return newlist
# 重新设置编码
import sys
def reloadCoding():
reload(sys)
sys.setdefaultencoding('utf-8')
reloadCoding()
# 测试函数属性的作用域
def testFuncAttri():
def testfinvoke():
print testf.a
def testf():
testf.a = 1
print testf.a # 该变量和函数同一个作用域
testfinvoke()
testf()
print testf.a
testFuncAttri() |
8783819041d1e27cb760785179dd036abf533bd5 | mapu77/todo-list-kata-python | /src/Todo.py | 744 | 3.703125 | 4 | from Item import Item
class Todo(object):
def __init__(self):
self.items = []
def add(self, description):
self.items.append(Item(description))
def check(self, index):
try:
self.items[index].check()
except IndexError:
pass
def print(self):
print("TODO list:")
print("----------")
for i in range(len(self.items)):
print(str(i) + ": " + self.items[i].representation())
print()
def remove(self, index):
try:
self.items.pop(index)
except IndexError:
pass
def uncheck(self, index):
try:
self.items[index].uncheck()
except IndexError:
pass
|
8a159f51bb1d239e6c613c375049434eb8b3f6e0 | cianjinks/Python-Misc | /SectionOne/20.py | 108 | 3.671875 | 4 | d = {"a": 1, "b": 2, "c": 3}
i = 0
for k in d:
i += d[k]
print(i)
# also
j = sum(d.values())
print(j) |
85e5dd1596f72e231ec69674487146d978d7dd29 | pengiun501/python | /烏龜 特殊圖形1.py | 167 | 3.546875 | 4 | import turtle
t=turtle.Turtle()
t.screen.reset()
t.color('blue')
t.shape('circle')
t.pensize('5')
i=1
while True:
t.forward(i)
t.left(30)
i=i+1 |
2830be49b3ac85f14d2b31b17bfa43239aa4e5c6 | devscheffer/SenacRS-Algoritmos-Programacao-3 | /task_1/main/ex_1.py | 804 | 4.09375 | 4 | """
Escreva uma classe “Lampada” as quais suas características referem-se à
- um modelo
- um supermercado.
"""
"""
Após, crie uma classe “TestaLampada”
- onde os atributos são inicializados e mostrados na tela.
- desenvolva os métodos para ligar e desligar a lâmpada
"""
class cls_Lampada:
def __init__(self, modelo, mercado,status="desligado"):
self.modelo = modelo
self.mercado = mercado
self.status = status
class cls_Testa_Lampada:
def __init__(self, Lampada):
self.atributos = Lampada.__dict__
self.status = Lampada.status
print(self.atributos)
def mtd_switch(self):
if self.status == "desligado":
self.status = "ligado"
else:
self.status = "desligado"
print(self.status)
|
352b643aa76bc4140a6dd4949c26c707a79e1c8a | upsmancsr/Algorithms | /stock_prices/stock_prices.py | 1,671 | 3.734375 | 4 | #!/usr/bin/python
import argparse
# first attempt: create array of all possible buy/sell spreads, then find the largest
# def find_max_profit(prices):
# possible_spreads = []
# for i in prices:
# # for idx, s in enumerate(prices, start = b ):
# for j in prices[prices.index(i):]:
# if j - i != 0:
# possible_spreads.append(j - i)
# print('******************')
# print('possible spreads:', possible_spreads)
# print('possible_spreads n:', len(possible_spreads))
# print('max profit:', max(possible_spreads))
# return max(possible_spreads)
# # return(possible_spreads)
# 2nd attempt: same as first but with different loop syntax
# ----- Best solution so far -----
# I think this is O(n) linear
def find_max_profit(prices):
possible_spreads = []
for i in range(0, (len(prices) - 1)):
for j in range((i + 1), (len(prices) - 1)):
possible_spreads.append(prices[j] - prices[i])
print('******************')
print('possible spreads:', possible_spreads)
print('possible_spreads n:', len(possible_spreads))
print('max profit:', max(possible_spreads))
return max(possible_spreads)
find_max_profit([100, 90, 80, 50, 20, 10])
find_max_profit([10, 7, 5, 8, 11, 9])
# if __name__ == '__main__':
# # This is just some code to accept inputs from the command line
# parser = argparse.ArgumentParser(description='Find max profit from prices.')
# parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price')
# args = parser.parse_args()
# print("A profit of ${profit} can be made from the stock prices {prices}.".format(profit=find_max_profit(args.integers), prices=args.integers)) |
c6c2604e2e0e719fd28d386d7e7e7d51b11f548a | Teemakornsamsen633050338-2/python | /test.py | 2,404 | 3.75 | 4 | '''print("กรุณาเลือกรายการ\n")
print("กด 1 เลือกเหมาจ่าย \nกด 2 เลือกจ่ายเพิ่ม")
x =int(input(""))
if x==1 :
s =int(input("กรุณาบอกระยะทาง"))
if s <=25:
print("ค่าใช้จ่ายทั้งหมด 25 บาท")
else :
print("ค่าใช้จ่ายรวมทั้งหมด 55 บาท")
elif x==2:
s =int(input("กรุณาบอกระยะทาง"))
if s <25:
print("ค่าใช้จ่ายทั้งหมด 25 บาท")
else:
print("ค่าใช้จ่ายทั้งหมด 25 บาท")'''
'''i=0
sum=0
print("กรุณากรอกจำนวนครั้งการรับค่า\n")
n =int(input(""))
while(i<n) :
x=int(input("กรอกตัวเลข "))
i+=1
sum=sum+x
print("ผลรวมทั้งหมด",sum)'''
'''c=1
print("ป้อนชื่ออาหารสุดโปรดของคุณ หรือ exit เพื่อออกจากโปรแกรม")
u =str(input(""))
while(True) :
print("อาหารโปรดอันดับที่ คือ ",c,u)
c+=1
if u =exit
break
print("อาหารโปรดของคุณมีดังนี้ .",c,u)'''
'''a=[]
while True:
b = input('----ร้านคุณหลินบิวตี้----\n เพิ่ม [a]\n แสดง [s]\n ออกจากระบบ [x]\n')
b = b.lower()
if b=='a':
c = input('\nป้อนรายการลูกค้า('รหัส':'ชื่อ':'จังหวัด'\n)
a.append(c)
print('\n******ข้อมูลได้เข้าสู่ระบบแล้ว******\n')
elif b== 's' :
print('{0:-<6}{0:-<10}{0:-<10}'.format(""))
print('{0:-<8}{1:-<10}{2:-<10}'.format('รหัส','ชื่อ','จังหวัด'))
print('{0:-<6}{0:-<10}{0:-<10}'.format(""))
for d in a:
e = d.split(":")
print('{0[0]:<6} {0[1]:<10}({0[2]:<18})'.format(e))
continue
elif b == 'x':
break
print('ทำคำสั่งถัดไป')'''
|
3aa85ee4dec8aa89fd646d4d9ad111bfa6ca9437 | Washirican/pcc_2e | /chapter_07/tiy_7_5_movie_tickets.py | 525 | 3.875 | 4 | # --------------------------------------------------------------------------- #
# D. Rodriguez, 2020-05-02
# --------------------------------------------------------------------------- #
age = ''
while age != 'done':
prompt = '\nWhat is your age? (Enter \'done\' when done)'
age = input(prompt)
if age == 'done':
break
elif int(age) <= 3:
print(f'Your ticket is free!')
elif 3 < int(age) <= 12:
print('Your ticket is $10')
elif int(age) > 12:
print('Your ticket is $15')
|
c6d199d1fb5d6b3ea55819a11edfccd3cd122aaa | rafaelri/coding-challenge-solutions | /python/fibonacci-dp/fibonacci_dp.py | 256 | 3.921875 | 4 |
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
memo = (n+1) * [0]
memo[0] = 0
memo[1] = 1
for i in range(2,n+1):
memo[i]=memo[i-2]+memo[i-1]
return memo[n]
|
d4f6d39ad20eb3c0d8b6c508e365f3f15df0b8cf | nzh1992/Interview | /py_language/file_operate/01_traverse_dir.py | 1,307 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Author: niziheng
Created Date: 2021/6/4
Last Modified: 2021/6/4
Description:
"""
# 问题
# 设计实现遍历目录与子目录,抓取.py文件
# 方法一
import os
def traverse_dir(dir, suffix):
tmp_list = []
for root, dirs, files in os.walk(dir):
for file_name in files:
name, suf = os.path.splitext(file_name)
if suf == suffix:
tmp_list.append(os.path.join(root, file_name))
return tmp_list
# 方法二
def pick(fp, suffix):
if fp.endswith(suffix):
print(fp)
def traverse_dir2(dir, suffix):
file_list = os.listdir(dir)
for file in file_list:
fp = os.path.join(dir, file)
if os.path.isfile(fp):
pick(fp, suffix)
else:
traverse_dir2(fp, suffix)
# 方法三
from glob import iglob
def traverse_dir3(dir, suffix):
for fp in iglob(f"{dir}/**/*{suffix}", recursive=True):
print(fp)
if __name__ == '__main__':
# 比如找到py_language目录中所有的py文件
dir = "/Users/niziheng/python_code/Interview/py_language"
# 方法一:
# py_file_list = traverse_dir(dir, '.py')
# print(py_file_list)
# 方法二:
# traverse_dir2(dir, '.py')
# 方法三:
traverse_dir3(dir, '.py')
|
d61b581c2d611d5f735010631de5e87b1f1328c7 | cristiancmello/python-learning | /3-informal-intro-python/3.3-lists/script-1.py | 1,172 | 4.46875 | 4 | # Listas
lista = [1, 2, 4, 5, 8]
print(lista) # [1, 2, 4, 5, 8]
# Indexação e Slicing
print(lista[0]) # 1
print(lista[2:]) # [4, 5. 8]
print(lista[:]) # lista <=> lista[:] => [1, 2, 4, 5, 8]
# Concatenação
print(lista + [-2, -4])
# IMPORTANTE!
# Diferentemente das Strings, Listas SÃO MUTÁVEIS
lista[2] = 2 ** 3
print(lista)
# Função append()
# Coloca novos itens ao final da lista
lista.append(7 ** 3)
print(lista)
# Atribuição a slices
# É possível modificar o tamanho da lista ou apagá-la inteiramente
letters = ['a', 'b', 'c', 'd']
letters[1:3] = ['B', 'C']
print(letters) # ['a', 'B', 'C', 'd']
# Remoção de itens
letters[1:3] = []
print(letters) # ['a', 'd']
# Removendo todos os elementos
letters[:] = []
print(letters)
# Função len()
# Da mesma forma feita com Strings, é possível calcular comprimento da lista
letters = ['a', 'b', 'c', 'd']
print('Comprimento de letters = ' + str(len(letters)) + ' elementos')
# Definindo Nested Lists (Listas aninhadas)
A = [1, 2, 3]
B = [A, 5, 6, 7]
print(B) # [[1, 2, 3], 5, 6, 7]
C = [A, B]
print(C) # [[1, 2, 3], [[1, 2, 3], 5, 6, 7]]
# Mostrar por linha e coluna
print(C[0][2]) # 3
|
b8650cbed04d2e40b8ddf6723f87b320dd5f73b0 | DanielJmz12/Evidenicas-Programacion-avanzada | /Evidencia38_for_notas.py | 291 | 3.765625 | 4 | aprobados = 0
reprobados = 0
for f in range (10):
nota = int(input("ingresa la nota: "))
if nota>=7:
aprobados = aprobados+1
else:
reprobados = reprobados+1
print("alumnos aprobados: " + str(aprobados))
print("alumnos reprobados: " + str(reprobados))
|
a0e46063d68e34652dbb6b8b98582cac25783c2d | ANEP-ET/sorting-visualizer | /sorting/monkeysort.py | 1,119 | 3.671875 | 4 | # Script Name : monkeysort.py
# Author : Howard Zhang
# Created : 14th June 2018
# Last Modified : 14th June 2018
# Version : 1.0
# Modifications :
# Description : Monkey sorting algorithm which can do nothing but be funny.
import copy
import random
from .data import Data
def monkey_sort(data_set, frame_count):
# FRAME OPERATION BEGIN
frames = [data_set]
# FRAME OPERATION END
dataes = [data.value for data in data_set]
flag = False
while not flag:
flag = True
for i in range(Data.data_count - 1):
# FRAME OPERATION BEGIN
ds = [Data(d) for d in dataes]
frames.append(ds)
ds[i].set_color('r')
ds[i+1].set_color('k')
if len(frames) == frame_count:
return frames
# FRAME OPERATION END
if dataes[i] > dataes[i+1]:
flag = False
break
if not flag:
random.shuffle(dataes)
# FRAME OPERATION BEGIN
frames.append(Data(d) for d in dataes)
return frames
# FRAME OPERATION END |
3856f1f9afc2d5aa494ca522d649d9a0a025e29c | OmkarGangan/Cash-Counting-Notes-counting | /Count Notes in Amount.py | 1,657 | 3.984375 | 4 | # Count Total Number Of Notes required in Entered Amount.
# List to store notes
c = [2000,1000,500,200,100,50,20,10,5,2,1]
# User entered amount stored in variable n
n = int(input("Enter Amount:"))
# storing user entered amount in temporary variable rs
rs = n
# variable i as a counter
i=0
# creating empty list
cash = []
# finite loop while
while i<=len(c)-1:
# integer of quotient stored in q i.e amount divided by cash
q = n//c[i]
# if q>0 means that much cash is required
if q>0:
# amount - cash
n = n-c[i]
# store that cash in list
cash.append(c[i])
# set counter again to 0
i = 0
# if amount = 0 then break the while loop-stop
if n == 0:
break
else:
# increment counter
i +=1
# creating dict for notes required
notes = {}
for i in cash:
# add note in dict with count
notes[i] = cash.count(i)
# print required output
print('*************************************')
print("To pay ₹{}/- you will require: ".format(rs))
# iterating into dict of notes
for k,v in notes.items():
if k>=10:
# for more than 1 notes
if v>1:
print("{} notes of {}".format(v,k))
# for one note
else:
print("{} note of {}".format(v,k))
else:
# for more than 1 coins
if v>1:
print("{} coins of {}".format(v,k))
# for one coin
else:
print("{} coin of {}".format(v,k))
|
a4342f9321594f380f210ed005b2ef79279f8043 | zlodeyrip38/python_lessons | /rodjer.py | 5,273 | 3.703125 | 4 | from time import sleep
from timeit import default_timer
from random import randint, choice
def select_mode():
print('''
Режимы:
1 - тренировка
0 - выход
''')
mode = ''
while not mode.isdigit():
print('Выбери режим:')
mode = input()
while not mode.isdigit():
print('Должна быть цифра')
mode = input()
return mode
# функция возврата временных окончаний
def time_endings(digit):
last_digit = int(digit[-1])
if 10<int(digit)<15:
return ''
else:
if last_digit == 1:
return 'у'
elif 1<last_digit<5:
return 'ы'
else:
return ''
# функция возврата временных окончаний
def time_spent(time_in_seconds):
if time_in_seconds < 60:
seconds = str (time_in_seconds)
time_spent = seconds + ' секунд' + time_endings(seconds)
else:
minutes = time_in_seconds // 60
seconds = str(time_in_seconds - (minutes*60))
if int(seconds) > 0:
time_spent = str(minutes) + ' минут' + time_endings(str(minutes)) + ' и ' + str(seconds) + ' секунд' + \
time_endings(str(seconds))
else:
time_spent = str(minutes) + ' минут' + time_endings(str(minutes))
return time_spent
# функция вывода примеров и их проверки
def count():
answers_quantity = '' # количество примеров
count_to = '' # до скольки будем считать
correct_answers = 0 # количество правильных ответов
fails = 0 # количество ошибок
answers_time = 0 # затраченое время на все ответы
sleep(1)
print('Давай проверим твои знания в математике.')
while not answers_quantity.isdigit():
print('Сколько примеров ты готов решить?')
answers_quantity = input()
if answers_quantity.isdigit():
while int(answers_quantity) < 1:
print('Введи число больше 0')
answers_quantity = input()
while not answers_quantity.isdigit():
print('Должна быть цифра')
answers_quantity = input()
else:
print('Должна быть цифра')
while not count_to.isdigit():
print('До скольки будем считать? Например, до 100 ')
count_to = input()
if count_to.isdigit():
while int(count_to) < 2:
print('Введи число больше 1')
count_to = input()
while not count_to.isdigit():
print('Должна быть цифра')
count_to = input()
else:
print('Должна быть цифра')
print('Хорошо, тогда начинаем...')
sleep(1)
answers_quantity = int(answers_quantity)
count_to = int(count_to)
for question in range(answers_quantity):
numder1 = randint(1, count_to)
numder2 = randint(1, count_to)
sign = choice('+-')
if sign == '+':
while numder1 + numder2 > count_to:
numder1 = randint(1, count_to)
numder2 = randint(1, count_to)
correct_answer = numder1 + numder2
if sign == '-':
while numder1 < numder2:
numder1 = randint(1, count_to)
numder2 = randint(1, count_to)
correct_answer = numder1 - numder2
print('пример ' + str(question+1))
student_answer = ''
while not student_answer.isdigit():
print(numder1, sign, numder2)
start = default_timer()
student_answer = input()
stop =default_timer()
answers_time += round(stop-start)
if not student_answer.isdigit():
print('Должна быть цифра')
if correct_answer == int(student_answer):
print('Правильно, молодец')
correct_answers += 1
else:
print('Неправильно')
print('Правильныый ответ: ' + str (correct_answer))
fails += 1
if fails == 0:
print('Молодец ты ответил на все вопросы провильно за ' + time_spent(answers_time))
else:
print()
print('Правильных ответов: ' + str (correct_answers))
print('Ошибок: ' + str(fails))
print('Затраченое время ' + time_spent(answers_time))
# основной блок программы
print('Привет меня зовут Роджер. А тебя как ?')
name = input()
name = name.title()
print('Приятно пазнакомиться, ' + name)
sleep(1)
while True:
mode = select_mode()
if mode == '1':
count()
elif mode == "0":
break
else:
pass |
e6bc8d27c28cce359a88aa0501f926ae74f49921 | DCtheTall/pygame-tutorial | /src/draw_circle.py | 654 | 4.03125 | 4 | """
PyGame tutorial: First sample program
https://realpython.com/pygame-a-primer/
"""
import pygame
from typing import Callable
def run_until_quit(func: Callable):
running = True
while running:
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
running = False
func()
def draw_circle(screen: pygame.Surface):
"""Draw a blue circle in the center of the screen."""
screen.fill((255, 255, 255))
pygame.draw.circle(screen, [0, 0, 255], [250, 250], 75)
pygame.display.flip()
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode([500, 500])
run_until_quit(lambda: draw_circle(screen))
|
0925b2027b163d5f9ace48b29d2241572e275669 | VakinduPhilliam/Python_Argparse_Interfaces | /Python_Argparse_Dest.py | 1,939 | 3.890625 | 4 | # Python argparse
# argparse Parser for command-line options, arguments and sub-commands.
# The argparse module makes it easy to write user-friendly command-line interfaces.
# The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv.
# The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments
#
# dest:
# Most ArgumentParser actions add some value as an attribute of the object returned by parse_args(). The name of this attribute is determined by the dest
# keyword argument of add_argument(). For positional argument actions, dest is normally supplied as the first argument to add_argument():
#
parser = argparse.ArgumentParser()
parser.add_argument('bar')
parser.parse_args(['XXX'])
# OUTPUT: 'Namespace(bar='XXX')'
#
# For optional argument actions, the value of dest is normally inferred from the option strings.
# ArgumentParser generates the value of dest by taking the first long option string and stripping away the initial -- string.
# If no long option strings were supplied, dest will be derived from the first short option string by stripping the initial - character.
# Any internal - characters will be converted to _ characters to make sure the string is a valid attribute name.
#
# The examples below illustrate this behavior:
#
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--foo-bar', '--foo')
parser.add_argument('-x', '-y')
parser.parse_args('-f 1 -x 2'.split())
# OUTPUT: 'Namespace(foo_bar='1', x='2')'
parser.parse_args('--foo 1 -y 2'.split())
# OUTPUT: 'Namespace(foo_bar='1', x='2')'
#
# dest allows a custom attribute name to be provided:
#
parser = argparse.ArgumentParser()
parser.add_argument('--foo', dest='bar')
parser.parse_args('--foo XXX'.split())
# OUTPUT: 'Namespace(bar='XXX')'
|
08c191a4a2bf97cc76eeb6dba40380d73498ae4b | Abusagit/practise | /Stepik/pycourse/Matrix_transposition.py | 656 | 3.828125 | 4 | import numpy as np
def matrix_build(rows):
matrix = []
for row in range(rows):
matrix.append([int(i) for i in input().split()])
return matrix
def matrix_transpose(matrix, rows, columns):
matrix2 = []
for column in range(columns):
tmp = []
for row in range(len(matrix)):
tmp.append(matrix[row][column])
matrix2.append(tmp)
return matrix2
if __name__ == '__main__':
n, m = (int(_) for _ in input().split())
a = matrix_build(n)
b = matrix_transpose(a, n, m)
# print(a)
# print(b)
for i in enumerate(b):
print(*i[1], sep=' ') |
bf083e441af58686000d92b0753882e8dff6cbe1 | msheshank1997/Hashing-1 | /group_Anagrams.py | 832 | 3.5 | 4 | #Time Complexity : O(NK), where K is the length of each string and N is the length of the List.
# Space Complexity = O(1)
# Yes it ran on Leetcode.
class Solution(object):
def groupAnagrams(self, strs):
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
dic = {}
for word in strs:
if self.CalculatedP(word, primes) not in dic:
dic[self.CalculatedP(word, primes)] = [word]
else:
dic[self.CalculatedP(word, primes)].append(word)
res = []
for i in dic.values():
res.append(i)
return res
def CalculatedP(self, word, primes):
mult = 1
for char in word:
mult = mult * primes[ord(char) - ord('a')]
return mult |
af7421236d0323f647a3a6e7136d37d01f77542e | Aditya1108/akhileshwork | /demo8.py | 3,675 | 3.8125 | 4 | from tkinter import *
root = Tk()
root.title("story's")
root.geometry("500x2000")
scrollbar = Scrollbar(root)
scrollbar.pack(side = RIGHT, fill = Y)
scrollbar.config(command = root)
label = Label(root, text="story 1 Never tell lie")
label.config(font=("Arial", 30))
label.pack()
label_2 = Label(root, text="There is a boy and has a sheep. He took the sheep to farm land. Hewould like to play with other friends, but nobody is there to play with him ")
label_2.config(font=("Arial", 20))
label_2.pack()
label_3 = Label(root, text="he would like to play with everyone but no one know's that he alway's lie")
label_3.config(font=("Arial", 20))
label_3.pack()
label_4 = Label(root, text="And the boy said to everyone that a lion is coming and they come to beat and ran away the lion but there is no lion")
label_4.config(font=("Arial", 20))
label_4.pack()
label_5 = Label(root, text="the boy said again to everyone that a lion is coming and they come to beat and ran away the lion but there is no lion")
label_5.config(font=("Arial", 20))
label_5.pack()
label_6 = Label(root, text="the boy said again and agian to to everyone that a lion is coming and they come to beat and ran away the lion but there is no lion")
label_6.config(font=("Arial", 20))
label_6.pack()
label_7 = Label(root, text="But this time lion really came and he was shouting for help, help. But no one ")
label_7.config(font=("Arial", 20))
label_7.pack()
label_8 = Label(root, text="came to protect him and sheep and the lion eat both the boy and sheep")
label_8.config(font=("Arial", 20))
label_8.pack()
label_10 = Label(root, text="Moral of the story: Never tell lie to anyone")
label_10.config(font=("Arial", 20))
label_10.pack()
label_11 = Label(root, text="")
label_11.config(font=("Arial", 20))
label_11.pack()
label_12 = Label(root, text="story 2 lion and the animals")
label_12.config(font=("Arial", 30))
label_12.pack()
label_13 = Label(root, text="there is a lion and it's very hungry it will eat so many animals ")
label_13.config(font=("Arial", 20))
label_13.pack()
label_14 = Label(root, text="1 bay the lion saw a deer it jest run and run to eat the deer and it ate up the deer ")
label_14.config(font=("Arial", 20))
label_14.pack()
label_15 = Label(root, text="and after 50 days the lion didn't ate any animal")
label_15.config(font=("Arial", 20))
label_15.pack()
label_16 = Label(root, text="and 1 day lion saw sa many animals")
label_16.config(font=("Arial", 20))
label_16.pack()
label_17 = Label(root, text="and lion thought i can eat all of the animals at once ")
label_17.config(font=("Arial", 20))
label_17.pack()
label_11 = Label(root, text="")
label_11.config(font=("Arial", 20))
label_11.pack()
label_11 = Label(root, text="")
label_11.config(font=("Arial", 20))
label_11.pack()
label_11 = Label(root, text="")
label_11.config(font=("Arial", 20))
label_11.pack()
label_11 = Label(root, text="")
label_11.config(font=("Arial", 20))
label_11.pack()
label_11 = Label(root, text="")
label_11.config(font=("Arial", 20))
label_11.pack()
label_11 = Label(root, text="")
label_11.config(font=("Arial", 20))
label_11.pack()
label_11 = Label(root, text="")
label_11.config(font=("Arial", 20))
label_11.pack()
label_11 = Label(root, text="")
label_11.config(font=("Arial", 20))
label_11.pack()
label_11 = Label(root, text="")
label_11.config(font=("Arial", 20))
label_11.pack()
label_11 = Label(root, text="")
label_11.config(font=("Arial", 20))
label_11.pack()
label_11 = Label(root, text="")
label_11.config(font=("Arial", 20))
label_11.pack()
label_11 = Label(root, text="")
label_11.config(font=("Arial", 20))
label_11.pack()
root.mainloop()
|
fd3d470d54b6f8714cbfab175765420f4bb4518b | jennypeng/python-practice | /TurtleArena/catmouse.py | 3,153 | 4.3125 | 4 | """
step - moves forward one step in the simulator,
-- asks each turtle to get its next state
-- -- new_state = turtle.getnextstate()
-- asks each turtle to set their state to next state
-- -- turtle.setstate(new_state) *simulates parallel behavior
run - loops over step over and over again
stop - stop running
quit - quit the program
"""
from Tkinter import * # Import everything from Tkinter
from Arena import Arena # Import our Arena
from Circle import Circle # Import our Turtle
from Mouse import Mouse
from Cat import Cat
from Vector import * # Import everything from our Vector
from random import randrange, uniform
tk = Tk() # Create a Tk top-level widget
arena = Arena(tk, width = 1000, height = 400) # Create an Arena widget, arena
arena.pack() # Tell arena to pack itself on screen
'''
Turtle(position, heading, outline, fill, width)
position - vector telling where turtle to be placed
heading - degrees, north = 0, east 90
outline - color, default to black
fill - color of turtle, default white
width - width of outline
'''
def initializeStatue(center_x, center_y, radius):
"""
Creates a circular statue centered at CENTER_X and CENTER_Y
with a radius of RADIUS.
Returns the statue
>>> statue = initializeStatue(200, 200, 2)
>>> print(str(statue.radius))
2
>>> print(str(statue.scale))
30
>>> print(str(statue.position.x))
200.0
"""
statue = Circle(Vector(center_x, center_y), 0, radius = radius)
arena.add(statue)
return statue
def initializeMouse(orbit, offset, speed):
"""
Creates a mouse which runs around ORBIT, with an OFFSET.
Returns the mouse.
>>> statue = initializeStatue(200, 200, 2)
>>> mouse = initializeMouse(statue, 0, 1)
>>> print(str(mouse.orbit.position.x))
200.0
"""
#deg = 396
deg = randrange(0, 360, 1) # create a random degree for mouse to start orbit at
mouse_start = unit(orbit.heading + deg) # what degree to initialize mouse
mouse = Mouse(orbit.position + mouse_start * (orbit.radius + offset) * orbit.scale, speed = speed, orbit = orbit, debug_flag = True, degree = deg)
arena.add(mouse)
return mouse
def initializeCat(mouse, statue, speed):
"""
Creates a cat to follow MOUSE around STATUE with speed of SPEED.
>>> statue = initializeStatue(200, 200, 2)
>>> mouse = initializeMouse(statue, 0, 1)
>>> cat = initializeCat(mouse, statue, 1)
>>> print(str(cat.moved))
-1
>>> print(str(cat.orbit.position.x))
200.0
"""
#cat_rad = 0 # should be one less than test
cat_rad = uniform(0, 8.1) # the cat starts at a random radius
cat_deg = randrange(0, 360, 1) # the cat starts at a random degree
#cat_deg = 35
cat_start = unit(statue.heading + cat_deg)
cat = Cat(statue.position + cat_start * (statue.radius + cat_rad) * statue.scale, speed = speed, orbit = statue, mouse = mouse, arena = arena, radius = statue.radius + cat_rad, debug_flag = True, degree = cat_deg)
arena.add(cat)
return cat
statue = initializeStatue(500, 350, 1.0)
mouse = initializeMouse(statue, 0, 1)
cat = initializeCat(mouse, statue, 1)
tk.mainloop()
|
7f3279d96fd8f2404ac47c69880084e2cc7051f0 | romanannaev/python | /STEPIK/Stepic_module2/iterating.py | 448 | 3.828125 | 4 | # x = input().split()
# xs = (int(i) for i in x)
#
#
# # def even(x):
# # return x % 2 == 0
#
# evens = list(filter(lambda x: x % 2 == 0, xs))
# print(evens)
x = [
("Guido", "van", "Rossum"),
("Haskell", "Curry"),
("John", "Backus")
]
import operator as op
from functools import partial
sort_by_last = partial(list.sort, key=op.itemgetter(-1))
print(x)
sort_by_last(x)
print(x)
y = ["abc", "cba", "abb"]
sort_by_last(y)
print(y) |
5bb4ee246ad579704863059764f7248761864463 | GeorgiTodorovDev/Python-Basic | /working_hours.py | 216 | 4.125 | 4 | hour = int(input())
day_from_week = input()
result = ""
if day_from_week == "Sunday":
result = "closed"
else:
if 10 <= hour <= 18:
result = "open"
else:
result = "closed"
print(result)
|
81b4048741d9adcd981ec471c9a94b4775336ac1 | JeanSavary/Genetic-Algo | /main.py | 7,483 | 3.859375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# -- External imports -- #
import os
import numpy as np
import pandas as pd
from random import uniform, sample
import matplotlib.pyplot as plt
# -- Internal imports -- #
from src.city import City
from src.population import Population
from src.population import Route
from var.variables import *
# -- Main functions -- #
def selection(ranked_population, elite_size):
'''
Description: Perform a roulette wheel selection, including an elite population
Params: ranked_population ( list( (Route, fitness_score) ) )
Output: list( Route )
'''
selection_results = [elem[0] for elem in ranked_population[:elite_size]] # We directly select our 'elite' population
fitness_list = [elem[1] for elem in ranked_population] # Then we'll perform the "roulette wheel selection"
df = pd.DataFrame(fitness_list, columns = ['fitness'])
df['cum_sum'] = df.cumsum()
df['cum_%'] = 100 * df['cum_sum'] / df['fitness'].sum()
for iteration in range(len(fitness_list) - elite_size):
threshold = uniform(0, 100)
for index, _ in enumerate(fitness_list) :
if threshold <= df.iloc[index]['cum_%'] :
chosen_route = ranked_population[index][0]
selection_results.append(chosen_route)
break
return selection_results
def crossOver(first_parent, second_parent):
'''
Description: Create a child after mixing information from the 2 parents
Params: first_parent (Route), second_parent (Route)
Output: child (Route)
'''
# print("\nParents : \n")
# print(first_parent.describe())
# print(second_parent.describe())
child = [None] * len(first_parent.cities)
first_gene_index = int(uniform(0,1) * len(first_parent.cities))
second_gene_index = int(uniform(0,1) * len(second_parent.cities))
start_point = min(first_gene_index, second_gene_index) #index between which we will perform the cross-over
end_point = max(first_gene_index, second_gene_index)
#print("\nStart : {} / End : {}\n".format(start_point, end_point))
for index in range(start_point, end_point + 1):
child[index] = first_parent.cities[index].name
queue_second_parent_cities = [city.name for city in second_parent.cities if city.name not in child]
for index, city_name in enumerate(child) :
if city_name is None :
child[index] = queue_second_parent_cities.pop(0)
#print(Route([City(city_name, CITIES[city_name][0], CITIES[city_name][1]) for city_name in child]).describe())
return Route([City(city_name, CITIES[city_name][0], CITIES[city_name][1]) for city_name in child])
def mutation(route, mutation_rate) :
'''
Description: Perfom a random mutation (with low probability) to an individual to avoir local convergence
Params: route (Route), mutation_rate (float between 0 and 1)
Output: route (Route)
'''
if (uniform(0,1) < mutation_rate) : # if the condition is valid then we will expose the individual to mutations
mutation_index = sample([i for i in range(len(route.cities))], 2)
mutated_cities = route.cities
#print("Perform mutation between city {} and {} !".format(route.cities[mutation_index[0]].name, route.cities[mutation_index[1]].name))
mutated_cities[mutation_index[0]], mutated_cities[mutation_index[1]] = mutated_cities[mutation_index[1]], mutated_cities[mutation_index[0]]
return Route(mutated_cities)
else :
#print("No mutation performed !")
return route
def makeCouples(parents):
'''
Description: Each parent will be involved in 2 couples, so that each parent will contribute to the next generation
respecting the previous generation size
Params: parents (list(Route))
Output: couples (list(tuple(Route, Route)))
'''
parents_pool = []
for iteration in range(2):
iteration_parents_pool = np.array(parents)
np.random.shuffle(iteration_parents_pool)
parents_pool += list(iteration_parents_pool)
parents_pool = np.array(parents_pool).reshape(len(parents_pool) // 2, 2)
couples = [(first_parent, second_parent) for (first_parent, second_parent) in parents_pool]
return couples
def nextPopulation(current_population, elite_size, mutation_rate):
'''
Description: Generate a new generation (population)
Params:
Output:
NB: We can also directly pass the elite population to the next gen without using them in crossOver()
'''
ranked_current_population = current_population.rankRoutes() #rank individuals inside our current population
selected_routes = selection(ranked_current_population, elite_size) #list of routes
couples = makeCouples(selected_routes)
children = []
for (first_parent, second_parent) in couples :
child = crossOver(first_parent, second_parent)
mutated_child = mutation(child, mutation_rate)
children.append(mutated_child)
return Population(children)
def bestRoute(population):
'''
Description: Compute and retrieve the best individual (route) of the generation
Params: population (Population)
Output: best_route (Route)
'''
best_route = population.rankRoutes()[0][0]
return best_route
def plotEvolution(best_fitness_scores):
'''
Description: Display the evolution of our best individual's fitness score for each generation
Params: best_fitness_scores (list)
Output: None
'''
generations = [i for i in range(1, len(fitness_scores) + 1)]
plt.plot(generations, best_fitness_scores)
plt.xlabel("Generation number")
plt.ylabel("Best fitness score")
plt.title("Evolution of the best fitness scores")
plt.show()
return
if __name__ == '__main__' :
# -- Initialize our first population -- #
cities_list = [city_name for city_name in CITIES.keys()]
initial_routes = []
for iteration in range(POPULATION_SIZE) :
iteration_cities = [City(city_name, CITIES[city_name][0], CITIES[city_name][1]) for city_name in sample(cities_list, len(cities_list))]
route = Route(iteration_cities)
initial_routes.append(route)
initial_population = Population(initial_routes)
# -- Enter the evolution process -- #
fitness_scores = []
current_population = initial_population
for generation in range(GENERATIONS) :
print("Generation {}\n".format(generation + 1))
current_population = nextPopulation(current_population, ELITE_SIZE, MUTATION_RATE)
current_best_individual = bestRoute(current_population).describe()
print("""
\tCurrent best distance : {}\n
\tCurrent best fitness : {}\n
\tCurrent best path : {}\n
""".format(
current_best_individual["Distance"],
current_best_individual["Fitness"],
current_best_individual["Cities"]
))
fitness_scores.append(current_best_individual["Fitness"])
print("""
We have our champion !\n
\tHere is the best path : {}\n
\tWith a distance of : {}\n
\tAnd a fitness of : {}
""".format(
current_best_individual["Cities"],
current_best_individual["Distance"],
current_best_individual["Fitness"])
)
plotEvolution(fitness_scores) |
574b21b7ced58f8884e71860c45d04eae4f67fb3 | jacob-liberty/area-and-perimiter-calculation- | /area_perimiter_calculation.py | 508 | 3.765625 | 4 | # Created by: Jacob Liberty
# Created on: September 17 2017
# Created for: ICS3U
# This program calculates the perimiter and area of a rectangle
import ui
def calculate_perimiter_touch_up_inside(sender):
#calculate the perimiter of the shape
view['perimiter_label'].text = 'The perimiter is ' + str(5+3+5+3) + 'm'
def calculate_area_touch_up_inside(sender):
#calculate the area of the shape
view['area_label'].text = 'The area is ' + str(5*3) + 'm'
view = ui.load_view()
view.present('sheet')
|
50d2e40d899ddac62b5b0bddc00bfab1eb9e1dc9 | bartkowiaktomasz/algorithmic-challenges | /LeetCode - Top Interview Questions/Pow.py | 706 | 3.796875 | 4 | """
Implement `pow(x, n)`, which calculates `x` raised to the power `n`
"""
from typing import Dict
class Solution:
def myPowRec(self, x: float, n: int, memo: Dict[int, float]) -> float:
if n in memo:
return memo[n]
elif n == 1:
return x
else:
res = self.myPowRec(x, n // 2, memo) * self.myPowRec(x, n - n // 2, memo)
memo[n] = res
return res
def myPow(self, x: float, n: int) -> float:
if n < 0:
return 1/self.myPowRec(x, -n, {})
elif n == 0:
return 1
else:
return self.myPowRec(x, n, {})
sol = Solution()
x = 2
n = -2
print(
sol.myPow(x, n)
) |
d2815f2cd8ad0e8951245d15b5d1d4b6cab6b646 | gregoriovictorhugo/Curso-de-Python | /Mundo-01/pydesafio Mundo01/des011.py | 267 | 3.828125 | 4 | l = float(input('Largura da parede em metros: '))
a = float(input('Altura da parede em metros: '))
print('A área da parede é: {}'.format((l*a)))
print('Considerando que um litro de tinta pinta dois metros quadrados, serão necessários {} litros'.format(((l*a)/2))) |
74f252feaa14a8c481925f2fa048377aeb68b2ac | ddmin/CodeSnippets | /PY/DailyProgrammer/easy5.py | 190 | 3.640625 | 4 | # [Easy] Challenge 5
import sys
import getpass
pw = getpass.getpass("Enter your password: ")
if not (pw == "password"):
print("Wrong Password!")
sys.exit()
print("Hello World!")
|
2be3df714343ef414d9e72a6dd6e6ed459f0c9bf | piochelepiotr/crackingTheCode | /chp2/ex6.py | 1,079 | 4.03125 | 4 | import linked_list
class Stack:
def __init__(self):
self.l = None
def pop(self):
if self.l is None:
return None
x = self.l.value
self.l = self.l.next
return x
def push(self, x):
self.l = linked_list.Node(x, self.l)
def is_palindrome2(head):
first_half = Stack()
slow_runner = head
fast_runner = head
while fast_runner:
fast_runner = fast_runner.next
if fast_runner:
fast_runner = fast_runner.next
first_half.push(slow_runner.value)
slow_runner = slow_runner.next
while slow_runner:
if slow_runner.value != first_half.pop():
return False
slow_runner = slow_runner.next
return True
print(is_palindrome2(linked_list.from_list([7, 1, 5, 1, 7])))
print(is_palindrome2(linked_list.from_list([7, 1, 5, 1, 8])))
def _reverse_list(L):
r = None
while L is not None:
r = linked_list.Node(L.value, r)
L = L.next
return r
def is_palindrome(L):
return _reverse_list(L) == L
|
78a4dd740962ae092bb6d3458546dda23ac9ec58 | LeeHeejae0908/python | /Day04/module_basic03.py | 513 | 3.578125 | 4 |
'''
* 사용자 정의 모듈
- 하나의 모듈 파일에 너무 많은 코드가 들어있다면
편집이 힘들어지고, 코드를 유지, 보수 하는데 어려움이 발생
- 관리 편의상 비슷한 기능들을 가진 코드를 여러개의 모듈에
나누어서 작성하는 것이 좋다.
'''
import calculator as cal
print(f'1인치: {cal.inch}cm')
print('1~10 누적합: ', cal.calc_sum(10))
n1, n2 = map(int, input('정수 2개 입력: ').split())
print(f'{n1} + {n2} = {cal.add(n1, n2)}') |
d2c6e2b38c20e6844c6e69103d3464f308032594 | yami-five/SPOJ | /_1289.py | 455 | 3.78125 | 4 | while True:
try:
line=input()
if line.count('>')>1 or line.count('<')>1:
i,j=-1,0
for x in range(len(line)):
if line[x] is '>':
i=x+1
elif line[x] is '<' and i>0:
j=x
break
print(line[:i].upper()+line[i:j]+line[j:].upper())
else:
print(line.upper())
except EOFError:
exit(0)
|
76bcb4d33dccaa16a0446c2e2617452b1c6122db | facedesk/prg1_homework | /hw6.py | 1,722 | 4.21875 | 4 | '''
For this homework, your code must match the area called specs.
This means you must use the correct function names, correct parameter names,
and fulful the function needs.
Good luck and happy sorting!
'''
'''
Problem 1
Create a function called swap.
This function will take in as parameters two variables a, and b.
It will then replace a and b
specs:
function name: swap
description: replace a with b and be with a
parameters: a and b
returns: a and b
pseudo code:
swap a,b:
set temp to a
set a to b
set b to temp
return a,b
x = 10
y = 30
swap x,y
print(x,y)
30 10
'''
'''
Problem 2
Create a function called bubble
this function will take in as a parameter a list called items
it will loop through the list using a while loop and swap using the function
(from problem 1) the first two values that are out of order and return false
If no two items are out of order, then return true
specs:
function name: bubble
description:
parameters: items
returns: True or False
pseudo code:
bubble list
set itemFound to false
set index = 0
while not itemFound and index is less than the length of list:
if index -1 > 0 and item at index-1 > item at index:
swap item at index-1,item at index
increase index by one
'''
'''
Problem 3
Create a function called bubble_sort that takes in as a parameter a list called items
it will continue to loop and call bubble until all items are successfully placed in order
specs:
function name: bubble_sort
description: perform the algorithm bubble sort using the functions from problem 1 and 2
parameters: items
returns: nothing
''' |
ce9a266327931cce5db9c89e01992d5efc80adbd | Luccifer/PythonCourseraHSE | /w05/e15.py | 231 | 3.703125 | 4 | # Количество положительных
def number_of_positive(nums):
i = 0
for num in nums:
if num > 0:
i += 1
print(i)
nums = list(map(int, input().split()))
number_of_positive(nums)
|
fc8166124078b0a1ae8b859b6dc44c83edfb2576 | dawtom/mikroKodRPi | /sqllite.py | 545 | 3.609375 | 4 | import sqlite3
def create_connection(db_file):
""" create a database connection to a SQLite database """
try:
return sqlite3.connect(db_file)
except Error as e:
print(e)
def main():
connection = create_connection("/home/pi/Desktop/NRF24L01/pythonsqlite.db")
c = connection.cursor()
c.execute('''INSERT INTO Arduino_devices VALUES (1234, 2345)''')
c.execute('''INSERT INTO Arduino_devices VALUES (1234, 2345)''')
connection.close()
if __name__ == '__main__':
main()
|
5439a1f86ebe96ff2c67ea0fa5e132b229a7cc76 | tjmacphee/COP-1500-Integration | /Main (2).py | 7,402 | 4.25 | 4 | #Tyler MacPhee, Integration Project, COP-1500
#Import modules
import turtle
import wikipedia
#Class creation for question system
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
user = input("What is your name? ")
while True:
if user.isalpha():
break
else:
print("No numbers or symbols please")
user = input("What is your name ? ")
# Initialization stuff
total_score = 0 # The global variable that keeps track of the total score throughout the game.
#I later got rid of this global variable an changed it to a returning variable down below
def run_test(question_list):
"""
Function that tests the user given a list of questions.
:param question_list: A list of questions
:return: The score achieved for this round of questions.
"""
current_score = 0
for question in question_list:
answer = input(question.prompt)
if answer == question.answer:
current_score += 1
print("You got " + str(current_score) + "/" + str(len(question_list)) + " correct")
return current_score
##Had help from a youtube video on this,
#https://www.youtube.com/watch?v=SgQhwtIoQ7o
print("Welcome, " + user + ", to my integration project!\nWe'll be enjoying trivia, fun with symbols, and finally watch a turtle draw.")
answer = input("Continue? Type Y/N: ")
while answer != "Y":
print("Sorry, but you wont be able to advance further unless you type Y.")
answer = input("Continue? Type Y/N: ")
# This can let me manipulate user input to only allow the following code to be executed when the answer is "Y"
print("Ok, " + user + ", today we will be going through four topics, with 3 questions each.")
print("First, we'll be begin with 2000's Movies")
# I created a file that contains some rules so i can do things a little easier without interfering with my own code
# from Question import Question
question_prompts = [
"What movie features the great adventure of a lone robot?\n (A) Robo dog's escape\n (B) Wall-E\n (C) Tomorrowland\n (D) Jimmy Neutron\n\n",
"Who was Cpt. Jack Sparrow in the hit movie series Pirates of the Caribbean?\n (A) Johnny Depp\n (B) Tom Cruise\n (C) George Clooney\n (D) Will Smith\n\n",
"Who won at the end of The Dark Knight?\n (A) Batman\n (B) Joker\n (C) Harley Quinn\n (D) No one, this movie is a cliffhanger.\n\n",
]
questions = [
Question(question_prompts[0], "B"),
Question(question_prompts[1], "A"),
Question(question_prompts[2], "A"),
]
# I'm keeping track of their score and adding 1 to it each time they get one correct
total_score += run_test(questions)
print("Alright, round 2 will be asking questions about basic math")
question_prompts2 = [
"What would be the answer if I took 20% of 365?\n (A) 64.53\n (B) 73\n (C) 18.25\n\n",
"A mile is 5,280 feet, a plane is flying at at 400mph: How many miles does the plane travel every 10 seconds?\n (A) .93\n (B) .1\n (C) This sucks :(\n\n",
"What is the cube root of 50, divided by 18, then rounded to the nearest whole number?\n (A) 13\n (B) 9\n (C) 0\n (D) Can't be simplified.\n\n",
]
questions2 = [
Question(question_prompts2[0], "B"),
Question(question_prompts2[1], "B"),
Question(question_prompts2[2], "C"),
]
total_score += run_test(questions2)
print("Okay, final round! This time, it won't be multiple choice, good luck! (Answers are case-sensitive)")
question_prompts3 = [
"My first name in binary code is this - |01010100|01111001|01101100|01100101|01110010|00001101|\nWhat's my name?: ",
"I'm hotter the more you feed me, but die if you give me a drink.\nWhat am I?: ",
"If you mix blue and orange paint together, what color is the result?: ",
]
questions3 = [
Question(question_prompts3[0], "Tyler"),
Question(question_prompts3[1], "Fire" or "Phone"),
Question(question_prompts3[2], "Brown"),
]
total_score += run_test(questions3)
if (total_score) >= 4.5:
print("Congratulations!, " + user + ", you earned a total score of: " + str(total_score) + "/9" + " correct!")
else:
print("Well, " + user + ", you still got a score of: " + str(total_score) + "/9" + " correct, better luck next time!")
print("Thanks for playing!\nGoodbye.\n\n")
print("The next part of the program will be about the arrangement of symbols")
print("This is a just a test for you to get the feel of how it works.")
#This allows the user to play around with their own input and create a big, or small table of symbols.
user_row = int(input("\nHow many rows would you like? "))
user_column = int(input("How many columns would you like? "))
for y in range(user_row):
for y in range(user_column):
print(end = " * ")
print()
print("\nNow we can play around with it a little more...")
print("I took whatever you entered for the numbers, then printed out a display of what that looks like in terms of asteriks.")
user_row2 = int(input("How many rows would you like? "))
user_column3 = int(input("How many columns would you like? "))
user_choice = input("Type the kind of symbol you would like, or anything words you'd like. ( * , # , ! , etc.): ")
for y in range(user_row2):
for y in range(user_column3):
print(end = user_choice + " ")
print()
print("\nThis should be a little more obvious, but I did the same thing, but printed whatever you wanted instead of just asteriks.")
print("We'll next be allowing you to have three go's at searching whatever you'd like to know... be safe.")
#Making use of a cool module called wiki, does it what you expect it to do.
wikiuser = str(input("What would you like to know more about? - Type an unambiguous keyword or name. "))
#print(wikipedia.search(wikiuser, results = 5))
print(wikipedia.summary(wikiuser, sentences = 2))
wikiuser2 = input("What next? ")
#print(wikipedia.search(wikiuser2, results = 5))
print(wikipedia.summary(wikiuser2, sentences = 2))
wikiuser3 = input("And finally... ")
#print(wikipedia.search(wikiuser3, results = 5))
print(wikipedia.summary(wikiuser3, sentences = 2))
print("\nSo now lets watch a turtle draw some nice shapes for us.")
print("\nPlease note to exit the window after the shape has been completed to continue")
#While looking into graphic applications in Python, I discovered "Turtle"
#A relatively easy to use graphics package
loadWindow = turtle.Screen()
thor = turtle.Turtle()
#I'm now using more than just stating a color, i'm converting my colors to the RGB 255 scale for more accurate colors
turtle.colormode(255)
#Draw speed
thor.speed(0)
#setting shape of turtle
thor.shape("turtle")
#Function that draws continues circles in a figure 8
for i in range(127):
thor.circle(5*i)
thor.circle(-5*i)
thor.left(i)
b = i
if b > 51:
b = 51
thor.color(i, 2*i, 3*b)
#This function should be a fast generating graphic that goes from black to blue and then to green/light green quickly
turtle.resetscreen()
hex = turtle.Turtle()
hex.speed(0)
num_sides = 6
side_length = 70
angle = 360.0 / num_sides
for i in range(num_sides*30):
hex.forward(side_length-5)
hex.right(angle)
hex.right(i)
turtle.done()
#This creates a basic hexagon with a twist, a big twist
loadWindow.bye() #Closes window
|
cc297c955e8e16b5abbbb7a62465da38a0f6cef0 | yassh-pandey/Data-Structures | /reverseString.py | 194 | 4.15625 | 4 | from stack1 import Stack
print('Enter the string')
string = input()
s = Stack()
for char in string:
s.push(char)
print("Reversing string")
while not s.isEmpty():
print(s.pop(), end="") |
b6c8e35763297978471c6a454524caafdd06051b | mickey-is-codin/OrbitCalculations | /manualArrayBleb.py | 8,272 | 3.96875 | 4 | #https://github.com/smit2300/OrbitCalculations
import math
import numpy as np
class GetInput(object):
def get_eye(self):
self.eye_radius = float(input("Radius of the eyeball in mm: ")) #Method for getting eyeball radius input
return self.eye_radius
def get_bleb(self):
#self.bleb_radius = float(input("Radius of the bleb in mm: ")) #Method for getting bleb radius input
self.bleb_radius = input("List of radii of the bleb in mm separated by spaces: ").split(' ')
for i in range(0,len(self.bleb_radius)):
self.bleb_radius[i] = float(self.bleb_radius[i])
return self.bleb_radius
def get_dx(self):
self.dx = float(input("Space division for integration (dx), recommended 0.001 or smaller: ")) #Method for getting space division input
return self.dx
def main():
#----Start Main Function----#
#----General Notation: R = Eyeball radius, r = bleb_radius----#
fetch_input = GetInput() #Create an instance of the input getting class so we can use it for further input
#eye_radius = fetch_input.get_eye() #Eyeball radius in mm
eye_radius = 11.55
bleb_radius = fetch_input.get_bleb() #Bleb radius in mm
print(bleb_radius)
#dx = fetch_input.get_dx() #Get the desired time division for integration
dx = 0.0001
#----Can hard code eye, bleb, and integration interval here----#
#eye_radius = 45.0
#bleb_radius = 23.0
#dx = 0.001
bleb_volume = [0 for i in range(0,len(bleb_radius))]
bleb_area = [0 for i in range(0,len(bleb_radius))]
meet_point_x = [0 for i in range(0,len(bleb_radius))]
meet_point_y = [0 for i in range(0,len(bleb_radius))]
quad1_area = [0 for i in range(0,len(bleb_radius))]
rev_volume = [0 for i in range(0,len(bleb_radius))]
surface_area = [0 for i in range(0,len(bleb_radius))]
for i in range(0,len(bleb_radius)):
eye_volume = get_volume(eye_radius) #Eyeball volume in mm^3
bleb_volume[i] = get_volume(bleb_radius[i]) #Bleb volume in mm^3
#print("Volume of the eye: %.2f cubic mm" % eye_volume)
#print("Volume of the bleb (including region outside of eye: %.2f cubic mm" % bleb_volume)
#print("\n-----------------------------------------------------------------\n")
eye_area = get_area(eye_radius) #Eyeball surface area in mm^2
bleb_area[i] = get_area(bleb_radius[i]) #Bleb surface area in mm^2
#print("Surface area of the eye: %.2f square mm" % eye_area)
#print("Surface area of the bleb: %.2f square mm" % bleb_area)
#print("\n-----------------------------------------------------------------\n")
#Bleb Equation: y = sqrt(r^2 - x^2) or x = sqrt(r^2 - y^2)
#Eyeball Equation: x = sqrt(y) * sqrt(2*R - y)
meet_point_x[i] = intersection_x(bleb_radius[i], eye_radius) #The x location of the intersection of the two circles
meet_point_y[i] = intersection_y(bleb_radius[i], eye_radius) #The y locaiton of the intersection of the two circles
quad1_area[i] = quad1_x_section(bleb_radius[i], eye_radius, meet_point_x[i], dx) #The cross sectional area between the two circles contained in quadrant I
rev_volume[i] = rev_integral(bleb_radius[i], eye_radius, meet_point_x[i], meet_point_y[i], dx) #Volume of the cross section revolved around the y axis
surface_area[i] = surface_integral(bleb_radius[i], eye_radius, meet_point_x[i], meet_point_y[i], dx) #Surface of the volume created by revolution
print("Volume of blebs: ")
for i in range(0,len(bleb_radius)):
print("Radius: {}, Volume: {}".format(bleb_radius[i],rev_volume[i]))
def get_volume(r):
volume = (4/3) * math.pi * r**3 #Using the generic volume of a sphere equation
return volume
def get_area(r):
area = 4 * math.pi * r**2 #Using the generic surface area of a sphere equation
return area
def intersection_x(r, R):
meet_point = math.sqrt((-1)*r**4 + 4 * r**2 * R**2)/(2 * R) #Solve both circle equations for y and set them equal. Wolfram Alpha used for algebra.
return meet_point
def intersection_y(r, R):
meet_point = r**2 / (2 * R) #Solve both circle equations for x and set them equal. Wolfram Alpha used for algebra.
return meet_point
def quad1_x_section(r, R, meet_point, dx):
N = int(meet_point / dx) #Number of points along x axis that we will use as solutions of integration
nums = [x*dx for x in range(0,N)] #Setting an array to iterate through for all of the solution points of integration
eye_points = [] #Blank array for all of the points solved along the eyeball's curve
bleb_points = [] #Blank array for all of the points solved along the bleb's curve
area = 0 #Will build the area by iteratively multiplying the point by dx to give incremental solution
for n in range(0,N-1):
eye_points.append(R - math.sqrt(R**2 - nums[n]**2))
bleb_points.append(math.sqrt(r**2 - nums[n]**2))
area = area + bleb_points[n]*dx - eye_points[n]*dx
#print("Cross sectional area in the first quadrant: %.2f square mm" % area)
#print("\n-----------------------------------------------------------------\n")
return area
def rev_integral(r, R, meet_point_x, meet_point_y, dx):
#----Volume of the shape made by both curves rotated about y-axis----#
'''Made with the understanding that
V = integral from 0 to meet_point_y of pi * bleb equation^2
+ integral from meet_point_y to r of pi * eye equation^2'''
N_1 = int(meet_point_y / dx) #Using two different ranges because of two integration bounds
N_2 = int((r - meet_point_y) / dx) #First range is 0 to meet_y, second is meet_y to r because we integrate wrt y
nums_1 = [y*dx for y in range(0,N_1)] #Create an array of all the y-axis solution points
nums_2 = [y*dx for y in range(0,N_2)] #Create another array of the y-axis solution points for the eyeball curve
eye_integral = [] #Blank array for all of the points solved along the eyeball's curve
bleb_integral = [] #Blank array for all of the points solved along the bleb's curve
volume_eye = 0 #Will build the integral by iteratively multiplying the point by dx to give incremental solution
volume_bleb = 0 #Will build the integral by iteratively multiplying the point by dx to give incremental solution
for n in range(0,N_2-1):
eye_integral.append(math.pi * (math.sqrt(nums_2[n]) * math.sqrt(2 * R - nums_2[n]))**2)
volume_eye = volume_eye + eye_integral[n]*dx
for n in range(0,N_1-1):
bleb_integral.append(math.pi * (math.sqrt(r**2 - nums_1[n]**2))**2)
volume_bleb = volume_bleb + bleb_integral[n]*dx
rev_volume = volume_eye + volume_bleb #Sum of the two integrals shoudl be the volume
#print("Volume of the bleb contained in the eye (displacement of the eye): %.2f cubic mm" % rev_volume)
#print("\n-----------------------------------------------------------------\n")
return rev_volume
def surface_integral(r, R, meet_point_x, meet_point_y, dx):
#----Surface area of the shape made by both curves rotated about y-axis----#
'''Made with the understanding that
Area = integral from 0 to meet_point_y of 2 * pi * bleb equation
+ integral from meet_point_y to r of 2 * pi * eye equation'''
#----Function is the same as that used to gather volume of revolution values, but using 2 * pi * radius to drive the equations----#
N_1 = int(meet_point_y / dx)
N_2 = int((r - meet_point_y) / dx)
nums_1 = [y*dx for y in range(0,N_1)]
nums_2 = [y*dx for y in range(0,N_2)]
eye_integral = []
bleb_integral = []
surface_eye = 0
surface_bleb = 0
for n in range(0,N_2-1):
eye_integral.append(2 * math.pi * (math.sqrt(nums_2[n]) * math.sqrt(2 * R - nums_2[n])))
surface_eye = surface_eye + eye_integral[n]*dx
for n in range(0,N_1-1):
bleb_integral.append(2 * math.pi * (math.sqrt(r**2 - nums_1[n]**2)))
surface_bleb = surface_bleb + bleb_integral[n]*dx
surface_area = surface_eye + surface_bleb
#print("Full surface area of the bleb contained in the eye: %.2f square mm" % surface_area)
#print("Surface area of the bleb receiving drug: %.2f square mm" % surface_eye)
#print("Surface area of the eye that the bleb is underneath: %.2f square mm" % surface_bleb)
#print("\n-----------------------------------------------------------------\n")
return surface_area
if __name__ == '__main__':
main()
|
a3c77cb583fc920629823bc6b1bf13d6d0663bc4 | oskarmcd/project_euler | /problem_007_Python/problem7.py | 512 | 4 | 4 | """
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?s
"""
def is_number_prime(number):
if number % 2 == 0:
return False
for x in range ((number-1), 2 ,-1):
if (number % x) == 0:
return False
return True
counter = 1
prime_counter = 1
while prime_counter != 10001:
counter += 1
print(prime_counter)
if is_number_prime(counter):
prime_counter += 1
print(counter)
|
673c03547f729556e01cf8396d5d324745b1cdba | Trlan2723/My_Python | /0-100(2).py | 1,285 | 3.984375 | 4 | def instruction():
print("Задано число от 0 до 100.")
print("Вам дано 7 попыток. Попробуйте отгадать ;)")
def make_number():
"""Загадывает число"""
import random
number = random.randrange(0,101)
return number
def ask_number():
"""Спрашивает мнение"""
guess = int(input("Ваше предложение "))
return guess
def winner():
"""Определяет победителя"""
guess = ask_number()
number = make_number()
while guess != number:
if guess < number:
print("Больше")
elif guess>number:
print("Меньше")
guess = ask_number()
print("Вы отгадали! Это действительно было число ", number)
import os
def main():
choice = "1"
while choice != "2":
if choice == "1":
instruction()
winner()
print("\n1 - начать занаво || 2 - выйти")
choice = input("Ваш выбор: ")
if choice != ("1","2"):
print("Вы ввели недопустимое значение")
os.system("cls")
main()
|
dcd45be8bf35850359bfea6b453667a9ea880aa9 | steffenerickson/humanitiesTutorial | /08_loops1_while.py | 532 | 4.5 | 4 | # Loops allow you to execute code over and over again, which
# is where much of the power of programmming lies
# While loops execute as long as the condition is true.
# Be careful with these, because it is easy to create an
# infinite loop!
i = 0
while i < 10:
print(f"{i} is not yet 10.")
# increment i. if i doesn't change, you will get an
# infinite loop
i = i + 1
# it is more common to increment i with i += 1:
i = 0
while i < 10:
print(f"{i} is not yet 10.")
# increment i using shorthand
i += 1 |
e1ce89300e70c6edfef2976babcaf445104a782a | raunakshakya/PythonPractice | /numpy/10_arithmetic_operations.py | 2,666 | 4.5625 | 5 | # https://www.tutorialspoint.com/numpy/numpy_arithmetic_operations.htm
import numpy as np
a = np.arange(9, dtype=np.float_).reshape(3, 3)
print('First array:')
print(a)
print()
print('Second array:')
b = np.array([10, 10, 10])
print(b)
print()
print('Add the two arrays:')
print(np.add(a, b))
print()
print('Subtract the two arrays:')
print(np.subtract(a, b))
print()
print('Multiply the two arrays:')
print(np.multiply(a, b))
print()
print('Divide the two arrays:')
print(np.divide(a, b))
print()
"""
numpy.reciprocal() - returns the reciprocal of argument, element-wise. For elements with absolute values larger than 1,
the result is always 0 because of the way in which Python handles integer division. For integer 0, an overflow warning is issued.
"""
a = np.array([0.25, 1.33, 1, 0, 100])
print('Our array is:')
print(a)
print()
print('After applying reciprocal function:')
print(np.reciprocal(a))
print()
b = np.array([100], dtype=int)
print('The second array is:')
print(b)
print()
print('After applying reciprocal function:')
print(np.reciprocal(b))
print()
"""
numpy.power() treats elements in the first input array as base and returns it raised to the power of the corresponding element
in the second input array.
"""
a = np.array([10, 100, 1000])
print('Our array is:')
print(a)
print()
print('Applying power function:')
print(np.power(a, 2))
print()
print('Second array:')
b = np.array([1, 2, 3])
print(b)
print()
print('Applying power function again:')
print(np.power(a, b))
print()
"""
numpy.mod() - returns the remainder of division of the corresponding elements in the input array. Same as function numpy.remainder().
"""
a = np.array([10, 20, 30])
b = np.array([3, 5, 7])
print('First array:')
print(a)
print()
print('Second array:')
print(b)
print()
print('Applying mod() function:')
print(np.mod(a, b))
print()
print('Applying remainder() function:')
print(np.remainder(a, b))
print()
# Performing operations on array with complex numbers - numpy.real(), numpy.imag(), numpy.conj(), numpy.angle()
a = np.array([-5.6j, 0.2j, 11., 1 + 1j])
print('Our array is:')
print(a)
print()
print('Applying real() function:')
print(np.real(a)) # returns the real part of the complex data type argument
print()
print('Applying imag() function:')
print(np.imag(a)) # returns the imaginary part of the complex data type argument
print()
print('Applying conj() function:')
print(np.conj(a)) # returns the complex conjugate
print()
print('Applying angle() function:')
print(np.angle(a)) # returns the angle of the complex argument
print()
print('Applying angle() function again (result in degrees)')
print(np.angle(a, deg=True))
|
ae8c9d8194cc3b8df50095a6e2daf950c3c60afe | IlievaDayana/SOFTUNI | /Fundamentals/nikuldens meals.py | 1,080 | 3.96875 | 4 | preferences = {}
dislikes = 0
command = input()
while command != "Stop":
command = command.split("-")
guest = command[1]
meal = command[2]
if command[0]=="Like":
if guest not in preferences.keys():
preferences[guest] = [meal]
elif guest in preferences.keys() and meal not in preferences[guest]:
preferences[guest].append(meal)
elif command[0]=="Unlike":
if guest not in preferences.keys():
print(f"{guest} is not at the party.")
elif meal not in preferences[guest]:
print(f"{guest} doesn't have the {meal} in his/her collection.")
elif meal in preferences[guest]:
dislikes+=1
preferences[guest].remove(meal)
print(f"{guest} doesn't like the {meal}.")
command = input()
sorted_preferences = dict(sorted(preferences.items(),key=lambda a:(-len(a[1]),a[0])))
for k,v in sorted_preferences.items():
preferred_meals = ", ".join(v)
print(f"{k}: {preferred_meals}")
print(f"Unliked meals: {dislikes}") |
dca55144e32a2173818f8858dceb410d20dc0e06 | guosaichong/personnel-management-system | /managerSystem.py | 4,987 | 3.671875 | 4 | from person import *
class PersonManager(object):
"""人员管理类"""
def __init__(self):
# 存储数据所用的列表
self.person_list = []
# 程序入口函数
def run(self):
# 加载文件里面的人员数据
self.load_person()
while True:
# 显示功能菜单
self.show_menu()
# 用户输入目标功能序号
menu_num = int(input("请输入需要的功能序号:"))
# 根据用户输入的序号执行不同的功能
if menu_num == 1:
# 添加人员
self.add_person()
elif menu_num == 2:
# 删除人员
self.del_person()
elif menu_num == 3:
# 修改人员
self.mod_person()
elif menu_num == 4:
# 查询人员
self.search_person()
elif menu_num == 5:
# 显示所有人员信息
self.show_person()
elif menu_num == 6:
# 保存人员信息
self.save_person()
elif menu_num == 7:
# 退出系统
break
else:
print("输入错误,请重新输入")
# 系统功能函数
# 显示功能菜单 静态方法
@staticmethod
def show_menu():
print("请选择如下功能:")
print("1.添加人员")
print("2.删除人员")
print("3.修改人员信息")
print("4.查询人员信息")
print("5.显示所有人员信息")
print("6.保存人员信息")
print("7.退出系统")
# 添加人员
def add_person(self):
"""添加人员信息"""
# 输入人员信息
name = input("请输入姓名:")
# 遍历人员列表,如果存在则报错,如果不存在则添加
for i in self.person_list:
if i.name == name:
print("人员已存在")
break
else:
gender = input("请输入性别:")
tel = input("请输入电话:")
# 创建人员对象
person = Person(name, gender, tel)
# 添加到人员列表
self.person_list.append(person)
print(person)
def del_person(self):
"""删除人员信息"""
# 输入要删除的人员姓名
name = input("请输入要删除的人员姓名:")
# 遍历人员列表,如果存在则删除,如果不存在则报错
for i in self.person_list:
if i.name == name:
self.person_list.remove(i)
print("删除成功")
break
else:
print("要删除的人员不存在")
def mod_person(self):
"""修改人员信息"""
# 输入要修改的人员姓名
name = input("请输入要修改的人员姓名:")
# 遍历列表,如果要修改的人员存在则修改,否则报错
for i in self.person_list:
if i.name == name:
tel = input("请输入新手机号:")
i.tel = tel
print("修改成功")
print(i)
break
else:
print("要修改的人员不存在")
def search_person(self):
"""查询人员信息"""
# 请输入要查询的人员姓名
name = input("请输入要查询的人员姓名:")
# 遍历列表,如果要查询的人员存在则显示,否则报错
for i in self.person_list:
if i.name == name:
print(i)
break
else:
print("要查询的人员不存在")
def show_person(self):
"""显示所有人员信息"""
print("姓名\t性别\t手机号")
for i in self.person_list:
print(f"{i.name}\t{i.gender}\t{i.tel}")
def save_person(self):
"""保存人员信息"""
# 打开文件
f = open("person.data", "w")
# 文件写入数据
# 人员对象转换成字典
new_list = [i.__dict__ for i in self.person_list]
f.write(str(new_list))
# 关闭文件
f.close()
print("保存成功")
def load_person(self):
"""加载人员信息"""
# 尝试以“r”模式打开数据文件,如果文件不存在,则提示用户;文件存在则读取数据
try:
f = open("person.data", "r")
except:
f = open("person.data", "w")
else:
data = f.read()
print(data)
# 读取的文件是字符串,需要转换。【{}】转换【人员对象】
new_list = eval(data)
self.person_list = [
Person(i["name"], i["gender"], i["tel"]) for i in new_list]
finally:
f.close()
|
d034787fe1923d60626fb15e9d45e44d6da358a0 | dan8919/python | /class/Dog.py | 701 | 3.96875 | 4 | class Dog:
a,b=0,0
def __init__(self,name):
self.name = name
print(self.name,"Dog was Born")
def speak(self,a,b):
print("yelop!",self.name,a,b)
def wag(self):
print("Dog's wag tail")
def __q(self):
print("__붙이면 비밀공간. 밖에서 못부름")
def __del__(self):
print("destry!!")
#dog 를 상속받음
#class 는 명세에 있음,static 명세에 있음
#class Puppy(Dog):
# def __init__(self):
#
# # def __q(self):
# print("__붙이면 비밀공간. 밖에서 못부름")
#
# def __del__(self):
puddle = Dog("puddle")
sheperd = Dog("sheperd")
puddle.speak(1,2)
#self 진짜 나 instence |
2f118aa1863514eb8bcf6fc8ad46503b0648f1d8 | abinesh1/pythonHackerRank | /strings/prob19.py | 605 | 4 | 4 | ## https://www.hackerrank.com/challenges/string-validators/problem
if __name__ == '__main__':
s = input()
print(True if any([x.isalnum() for x in s]) else False)
print(True if any([x.isalpha() for x in s]) else False)
print(True if any([x.isdigit() for x in s]) else False)
print(True if any([x.islower() for x in s]) else False)
print(True if any([x.isupper() for x in s]) else False)
# print any(c.isalnum() for c in str)
# print any(c.isalpha() for c in str)
# print any(c.isdigit() for c in str)
# print any(c.islower() for c in str)
# print any(c.isupper() for c in str) |
1fe7f3ac457d602c5d319f3617484e866d511134 | seclay2/ML_FinalProject | /LinearRegression/Tasks/Q_12.py | 2,755 | 3.578125 | 4 | def Q_12(self, X_train_scaled, X_test_scaled, y_train, y_test, learning_rate=0.001, nIteration=7000):
# Task 12: Given the (X_train, y_train) pairs denoting input matrix and output vector respectively,
# Fit a linear regression model using the stochastic gradient descent algorithm you learned in class to obtain
# the coefficients, beta's, as a numpy array of m+1 values (Please recall class lecture).
# Please use the learning_rate and nIteration (number of iterations) parameters in your implementation
# of the gradient descent algorithm.
# Please measure the cpu_time needed during the training step. cpu_time is not equal to the wall_time. So,
# use time.perf_counter() for an accurate measurement. Documentation on this function can be found here:
# https://docs.python.org/3/library/time.html
# Then using the computed beta values, predict the test samples provided in the "X_test_scaled"
# argument, and let's call your prediction "y_pred".
# Compute Root Mean Squared Error (RMSE) of your prediction.
# Finally, return the beta vector, y_pred, RMSE, cpu_time as a tuple.
# PLEASE DO NOT USE ANY LIBRARY FUNCTION THAT DOES THE LINEAR REGRESSION.
import random
random.seed(554433)
beta = []
y_pred = []
RMSE = -1
cpu_time = 0
## YOUR CODE HERE ###
import numpy as np
# np.random.seed(554433)
from time import perf_counter
x_temp = np.c_[np.ones((len(np.array(X_train_scaled)), 1)), np.array(X_train_scaled)] # m+1
# Using built in Numpy stuff
# beta = np.random.rand(len(x_temp.columns), 1) # Don't use this (not a dataframe)
# beta = np.random.rand(len(x_temp[0]), 1) # use this because numpy array
# Using the random seed
beta = np.empty([len(x_temp[0]), 1])
for i in range(len(x_temp[0])):
beta[i][0] = random.random()
m = len(np.array(X_train_scaled))
# Start time
t_start = perf_counter()
# Stochastic gradient descent
for i in range(nIteration):
random_index = random.randint(0, m)
x_indi = x_temp[random_index:random_index+1]
y_indi = y_train[random_index:random_index+1]
gradient = x_indi.T.dot(x_indi.dot(beta) - y_indi)
beta = beta - learning_rate * gradient
# End time
t_stop = perf_counter()
# Total time
cpu_time = t_stop - t_start
# x_temp = X_test_scaled
x_temp = np.c_[np.ones((len(np.array(X_test_scaled)), 1)), np.array(X_test_scaled)] # m+1
# Predictions
y_pred = x_temp.dot(beta)
# Some error checking for RMSE
if np.array(y_pred).shape == np.array(y_test).shape:
RMSE = np.sqrt(np.mean((np.array(y_pred) - np.array(y_test)) ** 2))
return (beta, y_pred, RMSE, cpu_time)
|
bae0dcab2a84ee00200ef4ed9716a0d591ea3396 | Senbagakumar/SelfLearnings | /Demos/InterviewPrepration/Prepration/Prepration/HackerRank/Implementation/Manasa and Stones/Solution.py | 550 | 3.546875 | 4 | #!/bin/python3
import sys
"""
The final stones are the values included in the range [a * (n - 1), b * (n - 1)] with step (b - a).
"""
if __name__ == '__main__':
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
a = int(input().strip())
b = int(input().strip())
stones = set()
final_stone = a * (n - 1)
stones.add(final_stone)
while final_stone != b * (n - 1):
final_stone += b - a
stones.add(final_stone)
print(*sorted(stones))
|
0096981248d518f9a592d5dd1579a5af929e0ada | danilogazzoli/estudopython | /cursoolist/aula02-01.py | 987 | 4.0625 | 4 | kind = "blank"
def test_kind():
print("Test Kind:", kind)
class Dog:
kind = 'canine' #campo estático à classe
def __init__(self, name):
#definir todos os atributos no __init__
self.name = name
def what_kind(self):
print("Name:", self.name)
print("Geral:", kind)
print("Self:", self.kind)
Dog.kind = 'Lassie'
# Testes...
d = Dog('Fido')
e = Dog('Buddy')
test_kind()
print('-' * 40)
#d.kind = 'Shitzu'
d.what_kind()
print('-' * 40)
e.what_kind()
print('-' * 40)
print(Dog)
print(Dog.what_kind)
print(e)
print(e.what_kind)
# para chamar um método de uma classe pai:
#BaseClassName.methodname(self, arguments)
#ou
#super().methodname(arguments)
#variaveis privadas = __nomedavariavel ou _nomedavariavel
class Reverse:
""" Iterator for looping ober a sequence backwards"""
def __init__(self):
def _next_:
def __iter__(self):
''' Returns the Iterator object '''
return self;
|
c08c35134e83ec5b22e8afd0881a4fd996090668 | lumafragoso/Basico_Condicionais_Triangulo_Retangulo_Isoceles | /main.py | 229 | 4.09375 | 4 | import turtle
from math import sqrt, pow
t = turtle.Turtle()
x = int(input('Digite o tamanho do lado do triângulo: '))
hipotenusa = sqrt(pow(x,2)+pow(x,2))
t.forward(x)
t.left(135)
t.forward(hipotenusa)
t.left(135)
t.forward(x)
|
67136615b5d15b679e9dc7ae40b473fe2c4a1444 | VeraSa785/Python_practice | /object_oriented_programming_methods.py | 589 | 3.53125 | 4 | # Object oriented programming. Methods.
class BankAccount:
def __init__(self,client_id, client_first_name, client_last_name):
self.client_id = client_id
self.client_first_name = client_first_name
self.client_last_name = client_last_name
self.balance = 0.0
def add(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
user_number_one = BankAccount(23456, "Jon", "Wilson")
user_number_one.add(3578)
print (user_number_one.balance)
user_number_one.withdraw(44)
print (user_number_one.balance)
|
538b553dfa370f9510d1264252198b864225d4bb | Geeky-har/Python-Files | /generators.py | 432 | 4.25 | 4 | # --------------Generators in python----------------
def gen(n):
for i in range(1, n):
yield i # it will provide value of i
a = gen(2000) # a function for generatin no upto 2000 created
print(a.__next__()) # will print 1 since it starts from 1
print(a.__next__()) # will print 2 as next function will iterate it to one
print(a.__next__()) # --do--
print(a.__next__()) # --do--
|
f6fe0f8a5ba04963ef860a5dd42ea9d43ace7955 | Kanrin-Cyou/BasicPY | /Class/test.py | 2,387 | 3.640625 | 4 | # 面向对象:封装(私有),继承(父子),多态(一种接口,多种形态,实现接口的重用)
# 封装:把一些功能的实现细节不对外暴露
# 继承:代码的重用
#单继承 调用父类的方法 super(自身,self).__init__(name,age)
#多继承
#组合 self.person = Person(self,job) 直接继承功能
# 多态:接口重用
#对象:实例化一个类之后的对象
#类:
#属性:实例变量,类变量,私有属性(__var)
#方法:构造方法(__init__),析构函数(__del__),私有方法(__method)
#静态方法 @staticmethod 只是名义上归类管理,实际上切断了和类的关联,作为独立的内容
#类方法 @classmethod #类方法只能访问类变量,不能访问实例变量
#属性方法 @property #变成一个属性了,函数不能再传入额外参数了
class role(object):
n = 123 #类变量,大家共用的属性,节省开销(防止每一次都赋值)
def __init__(self,name,role,weapon,life_value=100,money=15000):
#构造函数
#在实例化时做一些类的初始化的工作
self.name = name #实例变量(静态属性),作用域就是实例本身
self.role = role
self.weapon = weapon
self.__life_value = life_value #私有属性
self.money = money
def __del__(self):
#析构函数
#在实例释放、销毁的时候执行
#通常用于做一些收尾工作,如关闭一些数据库链接,打开的临时文件
#print('{:s} is dead'.format(self.name))
pass
def show_statues(self):
print('name:{}\nlife_value:{}'.format(self.name,self.__life_value))
def __gotname(self): #私有方法
print("nice try")
def shot(self): #类的方法,功能(动态属性)
print('{:s} is shooting'.format(self.name))
def get_shot(self):
print('{:s}: ah..., I got shot.'.format(self.name))
def buy_gun(self, gun_name):
print('{:s} just brought {:s}'.format(self.name,gun_name))
r1=role('alex','police','ak47')
r1.show_statues()
r2=role('jack','terrorist','B22')
# r1.name = '陈荣华'
# r1.bulletproof = True
# r1.n = 'abc'
# #r1.shot(),r1.get_shot(),
# #print(r1.name,'has bulletproof is',r1.bulletproof)
# r2.name = '徐良伟'
#r2.shot(),r2.get_shot()
|
e15f023b2c499b049e7375e4f16d8da7376018c2 | dmachibya/one_algorithm_a_day | /old/day2/linear_search.py | 487 | 4.1875 | 4 | """
Linear search algorithm
When to use this Algorithm
- When searching a short array which may be unsorted.
"""
#algorithm function
def linear_search(array, target):
for i in range(0, len(array)):
if(array[i] == target):
return i
return None
#testing function
def verify(algorithm):
if(algorithm) == None:
print("Element not found")
else:
print("Element found at index: "+str(algorithm))
verify(linear_search([1,2,45,67,5,9], 2)) |
743a8d18768fdb4bfc269d20b5d3e16ab3586bef | scorpio-su/zerojudge | /python/c420.py | 307 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 7 17:03:07 2020
@author: Username
"""
n=int(input())
for i in range(n):
for j in range(n-i-1): print('_',end='')
for j in range(i+1): print('*',end='')
for j in range(i): print('*',end='')
for j in range(n-i-1): print('_',end='')
print() |
58158f47d5a8737e93d8d8c2a9f5a988ef50f973 | VitorAlvess/Estudos | /Arquivos/Curso Python Gustavo Guanabara/ex080.py | 104 | 3.8125 | 4 | numeros = []
for c in range(0, 5):
numeros.append(int(input('Digite um valor')))
print(len(numeros)) |
5b783b0844b4058b07db542a074c5272b4ea78c4 | Muhammadilhammubarok170/Tugas-Praktikum-pertemuan-ke-6 | /Latihan 1.Lab 6.py | 840 | 3.828125 | 4 | import math
def a(x):
return x ** 2
def b(x, y):
return math.sqrt(x ** 2 + y ** 2)
def c(*args):
return sum(args) / len(args)
def d(s):
return "".join(set(s))
# Dirubah menggunakan Lambda
aa = lambda x: x ** 2
bb = lambda x, y: math.sqrt(x ** 2 + y ** 2)
cc = lambda *args: sum(args) / len(args)
dd = lambda s: "".join(set(s))
# output
print("Latihan a")
print("=========")
print("Fungsi")
print(a(4))
print("Lambda")
print(aa(4))
print()
print("Latihan b")
print("=========")
print("Fungsi")
print(b(4, 7))
print("Lambda")
print(bb(4, 7))
print()
print("Latihan c")
print("=========")
print("Fungsi")
print(c(10))
print("Lambda")
print(cc(10))
print()
print("Latihan d")
print("=========")
print("Fungsi")
print(d("abcde"))
print("Lambda")
print(dd("abcde")) |
11dda33d844093d9ddca1e6b4bcbf1ec23d428d4 | dabiri1377/DS-AL_in_python3 | /Chapter_1/1.4.1_test.py | 404 | 3.890625 | 4 | # Control flow
####
# Conditionals
# if first_condition :
# first_body
# elif second_condition:
# second_condition
# elif third_condition:
# third_body
# else:
# fourth_body
if 1 == 2:
print("WTF!! 1 is not equal to 2!!")
elif 2 == 3:
print("wo wo wo WTF?!! 2 == 3?")
elif 3 == 4:
print("what are you doing man? 3 is 4?")
else:
print("non of your shite condition is true!!!")
|
f133f82aff1b4b7fa688405a0d06d2a084933cf5 | ArthurZheng/python_hard_way | /functions_files.py | 658 | 3.859375 | 4 | from sys import argv
script, input_file = argv
def print_all(file_name):
print file_name.read()
return
def rewind(file_name):
return file_name.seek(0)
def print_a_line(line_count, file_name):
print line_count, file_name.readline()
return
current_file = open(input_file)
print "First, let's print the whoel file \n"
print_all(current_file)
print "Now, let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print 3 lines."
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
print "\nEnd of the program." |
4cdee01ed32199814055f190829a99bf4b7252c8 | yzl232/code_training | /mianJing111111/Google/给你一串正整数。1,2,3.。。。10, 11,12.。。。 给你一个int n,要你返回哪一位的数。比如 给你10,返回的就是1.给11,返回的就是0.py | 1,841 | 4.375 | 4 | # encoding=utf-8
'''
Imagine you have a sequence of the form 123456789101112131415... where each digit is in a position, for example the digit in the position 5 is 5, in the position 13 is 1, in the position 19 is 4, etc.
Write a function that given a position returns the digit in that position.
(You could think that this sequence is an array where each cell only holds one digit so given an index return what digit is in that index, however you cannot really create an array since the sequence is infinite, you need a way to based on the index calculate the digit that goes there).
The function has to return a single digit.
Other examples:
index = 100, result = 5
index = 30, result = 2
index = 31, result = 0
index = 1000, result = 3
'''
# 先是1~9, 10~99, 100~999
# 先是1~9, 10~99, 100~999
# #规律。 1*9, 2*90, 3*900, 。。。。。
def getDigit(n):
def getSize(i): return (10**i-10**(i-1)) * i
i = 1
while getSize(i)<=n:
n -= getSize(i)
i += 1 # 9*i*(10**(i-1)) #规律。 1*9, 2*90, 3*900, 。。。。。
number, digit = 10**(i-1) + n / i, n % i
return int(str(number)[digit])
for i in range(17):
print getDigit(i)
'''
def getDigit(n):
i = 0
while True:
i += 1
size = (10**i-10**(i-1)) * i # 9*i*(10**(i-1)) #规律。 1*9, 2*90, 3*900, 。。。。。
if size > n: break
n -= size
number, digit = 10**(i-1) + n / i, n % i
return int(str(number)[digit])
'''
# Count the number of digits that in all legal positive numbers below N
# 也是G家
def smallerCnt(x): # x=1005., 9+2*90+3*900+6*4
n=len(str(x))
return sum((10**i-10**(i-1)) * i for i in range(1, n))+(x-10**(n-1))*n
#规律。 1*9, 2*90, 3*900, 。。。。。
print smallerCnt(1005)
print smallerCnt(12) |
8f1b0fa372271509462331a6debeeeeddf865dc4 | wuyongqiang2017/AllCode | /day17/是否.py | 92 | 3.515625 | 4 | # l=["d","f","g","e","r","t","s"]
# l.sort()
# print(l)
# l.sort(reverse=False)
# print(l)
|
d033de683a30b3e964eebd99d7e02b02d416ad38 | allertjan/LearningCommunityBasicTrack | /week 3/homework third part/3.8.py | 185 | 3.859375 | 4 | number_amount = int(input("Which size n would you like? "))
triangle_number = 0
for i in range(1, (number_amount + 1)):
triangle_number += i
print(i," ", triangle_number)
|
ffacd29a9d09672e0833abb2c6d099892d5524c5 | yasharth328/Mini_Python_Projects | /caesar_solver.py | 764 | 4.09375 | 4 | print('caesar cipher solver')
def bruteforce():
print('enter the ciphertext:')
s = input()
s.upper()
for i in range(1,26):
print('--------------------------------------')
print('key = {}'.format(i))
c = ''
for j in s:
c+= chr((ord(j) + i-65) % 26 + 65)
print(c)
def encrypt():
s = input("enter text to encrypt")
k = int(input("enter key"))
c = ''
for j in s:
c+= chr((ord(j) + k-65) % 26 + 65)
print(c)
def decrypt():
s = input("enter text to decrypt")
k = int(input("enter key"))
c = ''
for j in s:
c+= chr((ord(j) + k-65) % 26 + 65)
print(c)
n = int(input("Choose your option:\n[1]Encrypt\n[2]Decrypt\n[3]Bruteforce"))
if n == 1:
encrypt()
elif n == 2:
decrypt()
elif n == 3:
bruteforce()
else:
print("Enter proper value") |
d7512e664647c5120d5d14f727e2c8c32c6cc1ac | jawang35/project-euler | /python/lib/problem67.py | 1,200 | 3.890625 | 4 | '''
Problem 67 - Maximum Path Sum II
By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom in triangle.txt (right click and
'Save Link/Target As...') , a 15K text file containing a triangle with
one-hundred rows.
NOTE: This is a much more difficult version of Problem 18. It is not possible
to try every route to solve this problem, as there are 2**99 altogether! If you
could check one trillion (10**12) routes every second it would take over twenty
billion years to check them all. There is an efficient algorithm to solve it.
;o)
'''
from functools import partial
from lib.config import assets_path
from lib.helpers.runtime import print_answer_and_elapsed_time
from lib.problem18 import maximum_path_sum
def answer():
with open('%s/problem67/triangle.txt' % assets_path) as file:
def parse(row): return [int(n) for n in row.split(' ')]
triangle = [parse(row) for row in file]
return maximum_path_sum(triangle)
if __name__ == '__main__':
print_answer_and_elapsed_time(answer)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.