blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
c01ae39c310d664a70d13125a91dadcc730b5237 | nkrishnappa/100DaysOfCode | /Python/Day-#40/Ex-47.py | 460 | 3.90625 | 4 | # Write a script to extract the 26 letters from the file and add it to the list only if that letter is in PYTHON
import glob
FILE_PATH = r"C:\Users\nkrishnappa\Desktop\100DaysOfCode\Python\Day-#40\Ex-45"
extract_letter = []
for file in glob.glob(f"{FILE_PATH}\*.txt"):
with open(file, "r") as f:
content = f.read()
if content in "PYTHON":
extract_letter.append(content)
print(extract_letter)
# ['H', 'N', 'O', 'P', 'T', 'Y']
|
ab0148bf436a4a3f24f6abbf7211b3159db92fd6 | Meowse/IntroToPython | /Students/imdavis/session04/mailroom/mailroomfunct.py | 5,103 | 3.75 | 4 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
from textwrap import dedent
import math
"""
A set of functions which support the mailroom main program.
Do:
>>> print functname.__doc__
for the docstring for each.
"""
def prompt1():
"""
This function will prompt the user for one of the available actions:
'send a thank you', 'create a report', or 'exit'. It will keep looping
through until one of those options (or it's shortcut) is given.
"""
request = None
action1 = "send a thank you"
action2 = "create a report"
action3 = "exit"
while ( (request != action1) and (request != action2) and (request != action3) ):
orig_request = raw_input("'(S)end a thank you', '(C)reate a report', or '(E)xit' ?> ")
# let us only deal with lower case versions of the actions to minimize testing.
request = orig_request.lower()
if(request == "s" or request == action1):
print "Ok, let's", action1
return action1
elif(request == 'c' or request == action2):
print "Ok, let's", action2
return action2
elif(request == 'e' or request == action3):
print "Exiting"
return action3
else:
# if the user doesn't enter an available action, let them know where they went astray.
print "You entered: '", orig_request, "'"
print "Please enter '(S)end a thank you' or '(C)reate a report', or '(E)xit'."
# def finddonorindex(donors, adonor):
# """
# This function takes the list of donors and the 'adonor' string, which is either an existing
# donor name or a new one. If 'adonor' is an existing donor name, return the index of that
# donor in our data structure. If the name doesn't exist in our list, add the name to the list of
# donors (along with an empty list to populate with donations) and return the index of the new
# entry.
# """
# indexcount = 0
# for name, donations in donors:
# if name == adonor:
# return indexcount
# indexcount += 1
# print "Requested donor :'", adonor, "' not found in existing list."
# print "Adding donor :'", adonor, "' to the list..."
# donors.append((adonor, []))
# return indexcount
def whichdonor(donors):
"""
This function will prompt the user if they want a print out of the existing user list and if so,
print it, or return the index of a given donor.
This makes use of the 'finddonorindex' function above.
"""
action1 = "list donor"
donor = ""
request = action1
while ( request == action1 ):
request = raw_input("Enter an existing donor name or select '(l)ist donor' to see a list of donors > ")
if(request.lower() == "l" or request.lower() == action1):
print "The existing donors are:"
for name,donations in donors.items():
print name
request = action1
elif(request in donors):
donor = request
else:
print "Requested donor :'%s' not found in existing list."%request
print "Adding donor :'%s' to the list..."%request
donor = request
donors.update({ donor : [] })
return donor
def newdonation(donorname):
"""
This function check that the new amount entered for a donor is a valid float.
If so, it returns the amount, if not, it tells you so and asks again.
This makes use of the 'is_number' function above.
"""
message = "Enter a new donaton amount for donor '" + donorname + "' > "
while (True):
amount = raw_input(message)
try:
return float(amount)
except ValueError:
print "You entered: '%s' which is not a valid donation amount."%amount
def composemail(donorname, recentdonation):
"""
Compose a message to the donor thanking them and rounding the donation amount to the penny.
Uses string formatting.
"""
message = dedent('''
Dear {donor},
Thank you very much for your most recent donation of ${donation:.2f}
Please consider donating to our charity again in the future.
Sincerely,
Ian Davis
'''.format(donor=donorname, donation=recentdonation))
print message
# write the message to a file also
filename = donorname+"-mail.txt"
try:
mailfile = open(filename, 'w')
mailfile.write(message)
mailfile.close()
except IOError:
print "Sorry...couldn't open %s"%filename
def formattable(donor, total, ndonations, ave):
print"{:^20}{:^20}{:^20}{:^20}".format(donor, total, ndonations, ave)
def print_donor_row(donorname, donationlist):
"""
Simple function that gets passed the donor name and list of donations for that donor,
and computes the total donation amount, the average donation, and prints a table.
"""
total_donated = sum(donationlist)
ave_donation = total_donated/len(donationlist)
formattable(donorname, total_donated, len(donationlist), ave_donation)
|
57e4340ab364ed612996d75a764b3d58cd8bac4e | Khalid-Sultan/Phase-2-Algorithms-Prep | /Leetcode/Depth-First_Search,Breadth-First_Search/2_-_Medium/79._Word_Search.py | 1,008 | 3.78125 | 4 | class Solution:
def exist(self, board, word):
for row in range(len(board)):
for col in range(len(board[row])):
if board[row][col] == word[0]:
if self.dfs(board, word, (row, col), set(), 0):
return True
return False
def dfs(self, board, word, position, visited, start):
directions = ((-1, 0), (+1, 0), (0, -1), (0, +1))
row, col = position
if start == len(word):
return True
if row < 0 or col < 0 or row >= len(board) or col >= len(board[0]):
return False
if position in visited:
return False
if board[row][col] != word[start]:
return False
visited.add(position)
for dirn_row, dirn_col in directions:
check = self.dfs(board, word, (row + dirn_row, col + dirn_col), visited, start + 1)
if check:
return True
visited.remove(position)
return False |
5b995e9a319400d8ce740f95431cf6faddc2afff | AlinePhDPhysics/studies-pyhton | /test7.5.py | 183 | 4 | 4 | n = input ('Digite um número inteiro qualquer: ')
n = int (n)
if n<= 11:
for n in range(1, 11, 1):
n = n+1
print (n)
else:
if n > 11:
print("Feito!") |
54bbf4618dc60a1224805f8324c980029bf7877d | benny-chou/AI-homework- | /車牌辨識/TkinterTEST.py | 1,231 | 3.890625 | 4 | import tkinter as tk # 使用Tkinter前需要先导入
# 第1步,实例化object,建立窗口
window = tk.Tk() # 第2步,给窗口的可视化起名字
window.title('My Window') # 第3步,设定窗口的大小(长 * 宽)
window.geometry('500x300') # 这里的乘是小x
# 第4步,在图形界面上设定标签
var = tk.StringVar() # 将label标签的内容设置为字符类型,用var来接收hit_me函数的传出内容用以显示在标签上
l = tk.Label(window, textvariable=var , bg='green', font=('Arial', 12), width=30, height=2)
# 说明: bg为背景,font为字体,width为长,height为高
# 这里的长和高是字符的长和高,比如height=2,就是标签有2个字符这么高
# 第5步,放置标签
l.pack() # Label内容content区域放置位置,自动调节尺寸
# 放置lable的方法有:1)l.pack(); 2)l.place();
on_hit = False
def runMain():
global on_hit
if on_hit == False:
on_hit = True
var.set('you hit me')
else:
on_hit = False
var.set('')
b = tk.Button(window, text="run", font=('Arial',12), width=10, height=1, command=runMain)
b.pack()
# 第6步,主窗口循环显示
window.mainloop()
|
966e4e21c71d083d2dda805048780dd01d40aaee | viralsir/python_programs | /arithmeticdemo.py | 587 | 4.03125 | 4 | '''
Arithmetic operators
operator symbol
addition +
substraction -
multiplication *
division /
modual %
exponent **
type covnersion
int(str)
float(str)
str(int)
'''
no1=int(input("Enter No:")) # input will return str "1"
no2=int(input("Enter No:"))
#no1=int(no1)
#no2=int(no2)
total=no1+no2
print("addition",total)
print("substraction",no1-no2)
print("Multiplication :",no1*no2)
print("Division :",no1/no2)
print("Integer Division :",no1//no2)
print("Moudal :",no1%no2)
print("Exponent :",no1**no2)
|
f7aa06c3203bbb72dfbb13bdbbfbb4c3fcabb3fe | Ssatyr/programowanie2021 | /drugie zajecia/lista.py | 2,244 | 3.734375 | 4 | import random
from statistics import median
def menu():
print("Menu:")
print("1. Generowanie listy")
print("2. Sortowanie listy")
print("3. Wyswietlanie liczb")
print("4. Usuwanie liczb")
print("5. Dodawanie liczb")
print("6. Średnia itd")
print("7. Koniec programu")
def generowanie_listy(lista):
print ("ile elementow ma miec lista?")
elementy = int(input())
print ("Czy maja być wygenerowane losowo? [t/n]")
losowosc = input()
if losowosc.lower() == "t":
for i in range (elementy) :
lista.append(random.randint(0,100))
elif losowosc.lower() == "n":
for i in range (elementy) :
lista.append(int(input(f"Wprowadź {i+1} element: ")))
def usuwanie_liczb(lista):
print(f"twoja lista: \n {lista}")
print("Usunac element czy zakres? [e/z]")
x = input()
if x == "e":
print("podaj ktory element usunac:", end = " " )
a = int(input())
lista.pop(a-1)
elif x == "z":
print("podaj zakres elementow do usuniecia:")
a = int(input("od ktorego:"))
b = int(input("do ktorego:"))
del lista[a-1:b-1]
def dodawanie_liczb(lista):
print(f"twoja lista: \n {lista}")
print("Dodac jeden element czy wiecej? [j/w]")
x = input()
if x == "j":
print("podaj jaki element chcesz dodac:", end = " " )
a = int(input())
lista.append(a)
elif x == "w":
print("ile elementow dodad?")
a = int(input())
for i in range (a) :
lista.append(int(input(f"Wprowadź {i+1} element: ")))
print ("Witaj!")
print ("Wybierz co chcesz zrobić:")
menu()
lista_m = []
odpowiedz = int(input())
while odpowiedz != 7:
if odpowiedz == 1:
generowanie_listy(lista_m)
elif odpowiedz == 2:
lista_m.sort()
elif odpowiedz == 3:
print ("lista:")
print (lista_m)
elif odpowiedz == 4:
usuwanie_liczb(lista_m)
elif odpowiedz == 5:
dodawanie_liczb(lista_m)
elif odpowiedz == 6:
print ("Wyswietlanie sumy sredniej itd:")
print (f"srednia: {sum(lista_m)/len(lista_m)}")
print (f"max: {max(lista_m)}")
print (f"min: {min(lista_m)}")
print (f"suma: {sum(lista_m)}")
print (f"liczba elementow: {len(lista_m)}")
print (f"mediana: {median(lista_m)}")
print (f"posortowane: {sorted(lista_m)}")
else:
print ("podaj inny numer")
menu()
print("Co chcesz zrobić?")
odpowiedz = int(input()) |
0659b48bcd129b712d641fabf4daf63fdee8f590 | Megan0145/Sprint-Challenge--Data-Structures-Python | /reverse/reverse.py | 2,314 | 4.15625 | 4 | class Node:
def __init__(self, value=None, next_node=None):
# the value at this linked list node
self.value = value
# reference to the next node in the list
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
# set this node's next_node reference to the passed in node
self.next_node = new_next
class LinkedList:
def __init__(self):
# reference to the head of the list
self.head = None
def add_to_head(self, value):
node = Node(value)
if self.head is not None:
node.set_next(self.head)
self.head = node
def contains(self, value):
if not self.head:
return False
# get a reference to the node we're currently at; update this as we traverse the list
current = self.head
# check to see if we're at a valid node
while current:
# return True if the current value we're looking at matches our target value
if current.get_value() == value:
return True
# update our current node to the current node's next node
current = current.get_next()
# if we've gotten here, then the target node isn't in our list
return False
def reverse_list(self):
# TO BE COMPLETED
# start off at head of the list, declare variable to hold current node and initialize it to the head node
cur_node = self.head
# declare variable to hold the previous node and initialize it to None
prev_node = None
# iterate over the list so long as the current node is not None (this denotes that we've reached the end of the list because tail.next will be None)
while cur_node:
# save the value of the current nodes 'next' to a temp next variable
next_node = cur_node.get_next()
# set the current nodes 'next' to the value of prev
cur_node.set_next(prev_node)
# set the value of prev equal to the value of the current node
prev_node = cur_node
# finally set the value of the current node equal to the value we saved in the temp 'next' variable
cur_node = next_node
# when we get to the very end of the list (cur_node is None) prev_node will be equal to original tail of DLL
# set head == prev_node
self.head = prev_node
|
0798425ff44a2a514bb72b38a219a0be45a757a3 | eshimelis/cpp_practice | /src/license_key_formatting.py | 706 | 3.5 | 4 | class Solution(object):
def licenseKeyformatting(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
# remove all dashes and convert to upper
s = s.replace('-', '')
s = s.upper()
# reverse for easier parsing
result = ""
if len(s) > 0:
while len(s) >= k:
result = s[-k:] + '-' + result
s = s[0:-k]
# cleanup
result = result[0:-1]
if len(s) > 0:
result = s + '-' + result
if result[-1] == '-':
result = result[0:-1]
return result
else:
return s
|
6b947a28141d6a99cec03ad52d2caf94c2af4a5c | psmilovanov/Python_HW_04 | /homework_04_6.py | 740 | 3.96875 | 4 | # Задание 6.
from random import randint
from itertools import count, cycle
x = int(input(
"Введите целое положительное число. Программа выведет все числа, начиная с этого и до числа в три раза большим: "))
for el in count(x):
if el > x * 3:
break
else:
print(el)
first_list_len = randint(2, 10)
print(f"Формируем случаный список длины {first_list_len}")
first_list = []
for i in range(0, first_list_len):
first_list.append(randint(1, 100))
print(first_list)
i = 0
for el in cycle(first_list):
if i >= len(first_list):
break
else:
print(el)
i += 1
|
e99a7babec55602a1d8e72ea50607311fb305187 | porosya80/stepic | /python373.py | 389 | 3.609375 | 4 | exList = []
chkText1 = []
for i in range(int(input())):
exList.append(input().lower())
for i in range(int(input())):
chkText1.extend(input().lower().split())
# exList = ["a","bb","cCc"]
# chkText1 = ["a","bb","aab","aba","ccc","c","bb","aaa"]
chkText = set(chkText1)
for i in set(exList).intersection(chkText):
chkText.remove(i)
print("\n".join(chkText))
|
64d843dfe5c609f15d773df19130339b2974e5b7 | Darcy382/code-breakers | /3.hash-maps/lru-cache.py | 1,895 | 3.78125 | 4 | # First attempt and second attempt, O(1) time and space
class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
self.prev = None
def remove(self):
self.prev.next = self.next
self.next.prev = self.prev
self.prev = None
self.next = None
return self
# Make a set method for value
class doublyList:
def __init__(self):
self.front = Node("front", "front")
self.back = Node("back", "back")
self.front.next = self.back
self.back.prev = self.front
def insertFront(self, new_node):
old_first = self.front.next
self.front.next = new_node
new_node.prev = self.front
new_node.next = old_first
old_first.prev = new_node
def removeLast(self):
return self.back.prev.remove()
class LRUCache:
def __init__(self, capacity: int):
self.deque = doublyList()
self.hash_table = {}
self.capacity = capacity
self.size = 0
def get(self, key: int) -> int:
if key in self.hash_table:
node = self.hash_table[key]
node.remove()
self.deque.insertFront(node)
return node.val # Use a getter method
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.hash_table:
node = self.hash_table[key]
node.val = value # Use a set method
node.remove()
self.deque.insertFront(node)
else:
if self.size == self.capacity:
old_node = self.deque.removeLast()
del self.hash_table[old_node.key]
else:
self.size += 1
new_node = Node(key, value)
self.hash_table[key] = new_node
self.deque.insertFront(new_node)
|
7c4bdaeab4fcb72a63131495f7fcdfa0dc622313 | lqktz/python_practice | /ex25.py | 1,018 | 4.375 | 4 | # -*- codind: utf-8 -*-
def break_words(stuff):
"""This function will break up words for us"""
words = stuff.split(' ')
return words
def sort_words(words):
"""sort the words"""
return sorted(words)
def print_first_word(words):
"""prints the first word after popping it off."""
word = words.pop(0)
print word
return
def print_last_word(words):
"""prints the last word after popping it off."""
word = words.pop(-1)
print word
return
def sort_sentence(sentence):
"""takes a full sentence and return the sorted words"""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last_word(sentence):
"""print first and last word about sentence"""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""sorts the wprds then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
|
c0bb2af84cf42b7b2a1bfe54f30d7deccb9daef9 | codingxnusret/learning-python | /LearningVariables.py | 787 | 4.375 | 4 | #Variables and Data Types review
#1.create a variable called intVal and assign it an integer value
intVal=5
#2.create a variable called floatVal and assign it a float value
floatVal= 6.5
#3 create a variable called boolVal and assign it a Boolean value
boolVal=False
#4 use a print() to display the Blooean value assigned to boolVal in the output of the program
print(boolVal)
#5.reassign blooVal a different value than the one assigned to it in step 3
boolVal=True
#6.use print() to display the integer value assigned to inVal in the output of the program
print(intVal)
#7.use print() to displae the float value assigned to floatVal in the output of the program
print(floatVal)
#8.use print() to the boolean value reassigned to boolVal in the output of the program
print(boolVal)
|
9b5c67fde50c74604e6eb4b0d13a5334e242fc01 | ed-cetera/project-euler-python | /001_solution.py | 410 | 3.75 | 4 | #!/usr/bin/env python3
import time
def main():
noninclusive_upper_limit = 1000
total_sum = 0
for number in range(1, noninclusive_upper_limit):
if number % 3 == 0 or number % 5 == 0:
total_sum += number
print("Solution:", total_sum)
if __name__ == "__main__":
start = time.time()
main()
end = time.time()
print("Duration: {0:0.6f}s".format(end - start))
|
2e6e93feed0a4c5244810e7088095af24dab44ea | apugithub/Programming-for-Everybody-Python- | /Week-5/finding the largest number.py | 207 | 4.0625 | 4 | ### Findiding the largest number
largest=None
for value in [3,50,1,78,5]:
if largest is None:
largest=value
elif value>largest:
largest=value
print (" Largest is: "), largest
|
b1096f59fff43c841813ce21405b242762c6115c | ES2Spring2020-ComputinginEngineering/project-1-liv-and-soham | /Step 3/logger.py | 1,071 | 3.75 | 4 | ##################
# FILL IN HEADER
#################
import microbit as mb
import radio # Needs to be imported separately
# Change the channel if other microbits are interfering. (Default=7)
radio.on() # Turn on radio
radio.config(channel=7, length=100)
print('Program Started')
mb.display.show(mb.Image.HAPPY)
while not mb.button_a.is_pressed(): # wait for button A to be pressed to begin logging
mb.sleep(10)
radio.send('start') # Send the word 'start' to start the receiver
mb.sleep(1000)
mb.display.show(mb.Image.HEART) # Display Heart while logging
# Read and send accelerometer data repeatedly until button A is pressed again
while not mb.button_a.is_pressed():
######################################################
# FILL In HERE
# Need to collect accelerometer and time measurements
# Need to format into a single string
# Send the string over the radio
######################################################
radio.send(message)
mb.sleep(10)
mb.display.show(mb.Image.SQUARE) # Display Square when program ends |
eb1723b7ac80d90154f48e1698fe4f7e310ef784 | hickeroar/project-euler | /040/solution042.py | 1,100 | 3.90625 | 4 | """
The nth term of the sequence of triangle numbers is given by, t(sub)n = 1/2n(n+1); so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its alphabetical position and adding these values
we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle
number then we shall call the word a triangle word.
Find how many triangle words there are in the text file
"""
words = open('solution042.txt', "r").read().replace('"','').split(',')
wordValues = []
for word in words:
wordValue = 0
for letter in word:
wordValue += (ord(letter) - 64)
wordValues.append(wordValue)
triangleNumbers = {}
number = 0
maxWordValue = max(wordValues)
while True:
number += 1
value = int((0.5*float(number))*(number+1))
triangleNumbers[value] = value
if (value > maxWordValue):
break
triangleWords = 0
for wordValue in wordValues:
if wordValue in triangleNumbers:
triangleWords += 1
print triangleWords |
3837feef9b7baabd45186ef4956883477ead0f67 | josezm/python-excercises | /ejercicios 1.py | 555 | 3.53125 | 4 | def retornar(x):
lista=[]
for i in range(0,x+1):
lista.append(i)
return lista
print retornar(5)
def retornar2(x):
lista=[]
if x==-1:
return lista
else:
lista=retornar2(x-1)
lista.append(x)
return lista
print retornar2(5)
def suma(x):
suma=0
for i in range(0,x+1):
suma=suma+i
return suma
print suma(5)
def suma2(x):
suma=0
if x==-1:
return suma
else:
suma=suma2(x-1)
suma=suma+x
return suma
print suma2(5) |
b7906daa08bb154006b5bc26d8ed724f39fe895f | cliffjsgit/chapter-17 | /exercise17.1.py | 548 | 4.1875 | 4 | #!/usr/bin/env python3
__author__ = "Your Name"
###############################################################################
#
# Exercise 17.1
#
#
# 1. Download the code from this chapter from :
# http://thinkpython2.com/code/Time2.py.
# Change the attributes of Time to be a single integer representing seconds
# since midnight. Then modify the methods (and the function int_to_time) to work
# with the new implementation. You should not have to modify the test code in
# main. When you are done, the output should be the same as before.
# |
bd985886bdb5cdfab5b335f02c64fc1c6527ae59 | rthunoli/PythonRepo | /num2word.py | 1,542 | 3.8125 | 4 | #!/usr/bin/python3
def n2w(number):
words = ''
NumWord = \
{
0:'zero',
1:'one',
2:'two',
3:'three',
4:'four',
5:'five',
6:'six',
7:'seven',
8:'eight',
9:'nine',
10:'ten',
11:'eleven',
12:'twelve',
13:'thirteen',
14:'fourteen',
15:'fifteen',
16:'sixteen',
17:'seventeen',
18:'eighteen',
19:'nineteen',
20:'twenty',
30:'thirty',
40:'forty',
50:'fifty',
60:'sixty',
70:'seventy',
80:'eighty',
90:'ninety',
}
word = NumWord.get(number,'')
if word == '':
if number < 100:
rem = number % 10
number -= rem
word = n2w(rem)
word = n2w(number) + " " + word
elif number < 1000:
rem = number % 100
number //= 100
if rem > 0:
word = n2w(rem)
word = n2w(number) + " hundred " + word
elif number < 1000000: #Less than one million
rem = number % 1000
number //= 1000
if rem > 0:
word = n2w(rem)
word = n2w(number) + " thousand " + word
elif number < 1000000000: #Less than one billion
rem = number % 1000000
number //= 1000000
if rem > 0:
word = n2w(rem)
word = n2w(number) + " million " + word
elif number < 1000000000000: #Less than one trillion
rem = number % 1000000000
number //= 1000000
if rem > 0:
word = n2w(rem)
word = n2w(number) + " billion " + word
else:
return word
return word
if __name__ == "__main__":
while True:
number_string = input("Enter a number (q to quit) : ")
if number_string == 'q' or number_string == 'Q':
break
number = int(number_string)
print(n2w(number))
|
b6a7cd513bc9d9fd85a3581108f265f62278d84d | Joepolymath/dictionary | /main.py | 171 | 3.859375 | 4 | import json
data = json.load(open('original.json')
def diction(word):
result = data[word]
return result
word = input("enter your word: ")
print(diction(word)) |
ddff16a3c85da287a03fd674ec84d224fdbb919b | itkasumy/PythonGrammer | /day05/12-循环嵌套里的break.py | 194 | 3.5625 | 4 | i = 0
while i < 10:
j = 0
while j < 10:
print("j = %d " % j, end="")
j += 1
if j == 7:
break
print("i = %d" % i)
i += 1
print("over...")
|
cb1f1f55e87ee5c06f4bbf444a8bd529a10d49fd | AlinaDiaz21/Python-Essetials | /Tarea funciones 2.3.py | 639 | 3.84375 | 4 | """
@author: Alina Díaz
"""
def isYearLeap(yr):
if yr%4 == 0 and yr%100 !=0 or yr%400 == 0:
return True
else:
return False
def daysInMonth(yr, month):
if yr<1900 or month>12:
return None
if month==1 or 3 or 5 or 7 or 8 or 10 or 12:
return 31
elif month==2 and isYearLeap(yr):
return 29
else:
return 28
def dayOfYear(yr, month, day):
diasn=yr,month,day
if yr<1900 or month>12 or month<1 or day<1 or day>32:
return None
else:
return diasn
print(dayOfYear(2000, 12, 31))
for x in range(6,2):
print(x) |
2a28b6f0af5207b7bec6e19b1aebc676bf9d1597 | NewAlice/python-code | /exceptions/except3.py | 221 | 3.71875 | 4 | def main():
try:
fh=open('file1.txt')
for line in fh:
print(line.strip())
except IOError as e:
print('could not open this file',e)
#else:
# for line in fh: print(line.strip())
main() |
1193cd3f1e82f956729ec90ce8128bd1ff20633d | suryak24/python-code | /85.py | 169 | 3.984375 | 4 | n=input("Enter the string:")
even=""
odd=""
l=len(n)
for i in range(1,l+1):
if(i%2==0):
even=even+n[i-1]
else:
odd=odd+n[i-1]
print(odd,"",even)
|
ab1536cd4a742842118cffbe0d1882e5bceac801 | paulmedeiros92/AdventOfCode2019 | /day4/d4.py | 663 | 3.71875 | 4 | rawInput = input()
ranges = rawInput.split('-')
count = 0
doubles = ['00', '11', '22', '33', '44', '55', '66', '77', '88', '99']
triples = ['000', '111', '222', '333', '444', '555', '666', '777', '888', '999']
def twoAdjacent(num):
strNum = str(num)
for i, double in enumerate(doubles):
if double in strNum and triples[i] not in strNum:
return True
return False
def neverDecrease(num):
strNum = str(num)
for i, digit in enumerate(strNum):
if i !=5 and int(digit) > int(strNum[i + 1]):
return False
return True
for i in range(int(ranges[0]), int(ranges[1])):
if twoAdjacent(i) and neverDecrease(i):
count += 1
print(count) |
c6f1afc5afb79e72485b06da0994d4d844e58b85 | weiliu93/PythonMiniInterpreter | /test/test_packages/class_usage/example.py | 200 | 3.703125 | 4 | class A(object):
def __init__(self):
self.name = "haha"
self.id = "hehe"
def print(self):
print("name is {}, id is {}".format(self.name, self.id))
a = A()
a.print()
|
a82fb12f1781b700d9d262fccdd5ae8bb703de17 | PutkisDude/Developing-Python-Applications | /week10-11/pygame/game.py | 2,744 | 3.578125 | 4 | # Author Lauri Putkonen
# Create a small pygame game: e.g. moving objects on a screen.
# Video - https://youtu.be/7vtKaASa0oY
import pygame
from mobs import Mob
# PRESS ARROW OR WASD KEYS TO PASS MOBS
# ESC EXIT
# Initialize the pygame
pygame.init()
clock = pygame.time.Clock()
mobs = []
# Create screen
width = 580 # Width of the window
height = 360 # Height of the window
background = pygame.image.load("background.png")
screen = pygame.display.set_mode((width,height))
# Title and Icon (Seems icon doesn't work on linux)
pygame.display.set_caption("The Buggy game")
icon = pygame.image.load('logo.png')
pygame.display.set_icon(icon)
#Music
music = pygame.mixer.music.load("bensound-dance.mp3") #Music from www.bensound.com
pygame.mixer.music.play(-1)
win_sound = pygame.mixer.Sound("mixkit_win.wav") # Sound from mixkit.co
lose_sound = pygame.mixer.Sound("mixkit_long_roar.wav") # Sound from mixkit.co
# Player character
player_pic = pygame.image.load("bug.png")
playerX = 280
playerY = 310
player_speed = 10
def win():
print("You passed the game")
win_sound.play()
pygame.time.delay(500)
exit(0)
def draw_player(x, y):
screen.blit(player_pic, (x, y))
# If player go out of the screen
def playerBounds():
global playerX, playerY
if playerX <= 0:
playerX = 0
if playerX >= (width - 50):
playerX = (width - 50)
if playerY >= 320:
playerY = 320
if playerY == -50:
win()
# Create mobs - screen, y, width, height)
mobs.append( Mob(screen, 30, width, height))
mobs.append( Mob(screen, 110, width, height))
mobs.append( Mob(screen, 190, width, height))
mobs.append( Mob(screen, 270, width, height))
# Game Loop
while True:
clock.tick(60)
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP or event.key == pygame.K_w:
playerY -= player_speed
if event.key == pygame.K_DOWN or event.key == pygame.K_s:
playerY += player_speed
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
playerX -= player_speed
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
playerX += player_speed
if event.key == pygame.K_ESCAPE:
exit()
for x in mobs:
x.draw()
x.move()
if x.isCollided(playerX, playerY):
lose_sound.play()
playerX = 280
playerY = 310
playerBounds() # IF player go outs of screen
draw_player(playerX, playerY)
pygame.display.update()
|
6160ad951fc77aa840af373befaad7c5fb69a8be | dchtexas1/projectEuler | /pythonEuler/projectEuler5,6,7,8.py | 4,660 | 3.921875 | 4 | ###############################################################################
# Name: Dax Henson
# Date: 2017/02/09
# Description: Solves problems 5, 6, 7, and 8 of Project Euler.
###############################################################################
from math import sqrt
from fractions import gcd
# PLEASE NOTE THAT ALL INLINE COMMENTS ARE REFERENCING THE LINE BELOW THEM
# solves problem 5
'''
I noticed that the "smallest positive number that is evenly divisible" is the
same as "least common multiple," which is equal to the product of two numbers
divided by the greatest common divisor of the two. So I used fraction.gcd()
lambda allows me to use small functions without defining them, and reduce()
lets me repeatedly find the least common multiple of the given range.
'''
def problem5():
return reduce(lambda x, y: x * y / gcd(x, y), xrange(1, 21))
# solves problem 6
'''
It's simple math. I'm just looking for the sum of the natural numbers and the
the sum of the squared natural numbers, up to a target number, in this case
100. Then I square the sum of natural numbers and subtract the sum of the
squares from it.
'''
def problem6():
# sets target max number
n = 100
# sum of natural numbers formula, squared
sns = ((n * (n + 1)) / 2) * ((n * (n + 1)) / 2)
# sum of squared natural numbers formula
ssn = (n * (n + 1) * (2 * n + 1)) / 6
# finds the difference
return sns - ssn
# solves problem 7
'''
It just runs through and checks all of the odd numbers (two is already counted)
for primality with a helper function. The helper function skips the base cases
of any number less than two and any even number, since the main function begins
at three and increments i by two.
'''
def isPrime(n):
for i in xrange(3, int(sqrt(n)) + 1):
# if n is evenly divisible by a natural number, it is not prime.
if n % i == 0:
return False
break
return True
def problem7():
# number to check
i = 1
# tracks how many primes have been found
primes = 1
while (primes < 10001):
# must be before primality check or i will go too far
i += 2
if (isPrime(i) is True):
primes += 1
return i
# solves problem 8
'''
The function travels through the string and multiplies each digit within each
instance of 13 characters not containing zero and then returns the largest
product.
'''
def problem8():
string = "73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
62229893423380308135336276614282806444486645238749\
30358907296290491560440772390713810515859307960866\
70172427121883998797908792274921901699720888093776\
65727333001053367881220235421809751254540594752243\
52584907711670556013604839586446706324415722155397\
53697817977846174064955149290862569321978468622482\
83972241375657056057490261407972968652414535100474\
82166370484403199890008895243450658541227588666881\
16427171479924442928230863465674813919123162824586\
17866458359124566529476545682848912883142607690042\
24219022671055626321111109370544217506941658960408\
07198403850962455444362981230987879927244284909188\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450"
# tracks the largest product of 13 characters
finalProduct = 1
for i in xrange(0, len(string) - 13):
# ignores all zeros in every slice of 13 characters
if ("0" not in string[i:i + 13]):
# creates a variable to easier manipulate the current 13 characters
window = string[i:i + 13]
# tracks the product of the current window
product = 1
# runs through and multiplies each digit in the window
for j in xrange(0, len(window)):
product *= int(window[j])
if (product > finalProduct):
finalProduct = product
return finalProduct
# the main part of the program
sol5 = problem5()
print "The smallest positive number that is evenly divisible by all of the "\
"numbers from 1 to 20 is {}".format(sol5)
sol6 = problem6()
print "The difference between the sum of squares and square of sum of the "\
"first 100 natural numbers is {}".format(sol6)
sol7 = problem7()
print "The 10,001st prime number is {}".format(sol7)
sol8 = problem8()
print "The greatest product of thirteen adjacent digits is {}".format(sol8)
|
6e5378745299af63897c16c757836f1fd2e53531 | 116581658/QA | /Python/TestCases/Message_Boxes.py | 784 | 3.515625 | 4 | import tkinter
#import ctypes # Another library for message boxes, but simple one
##### The following code works with ctypes BEGIN #########
# def mbox(title, text, style):
# ctypes.windll.user32.MessageBoxW(0, text, title, style)
# mbox('Your title', 'Your text', 1)
# ## Styles:
# ## 0 : OK
# ## 1 : OK | Cancel
# ## 2 : Abort | Retry | Ignore
# ## 3 : Yes | No | Cancel
# ## 4 : Yes | No
# ## 5 : Retry | No
# ## 6 : Cancel | Try Again | Continue
##### The following code works with ctypes END #########
from tkinter import *
# if you are working under Python 3, comment the previous line and comment out the following line
#from tkinter import *
root = Tk()
w = LabelFrame(root, text="Hello Tkinter!")
# w.pack()
root.mainloop()
|
a0da6f49dea7a8a0a53809ba15759eeb12c7423e | minsuklee80/aggie | /turtle/turtle_도형에컬러채우기.py | 145 | 3.640625 | 4 | import turtle as t
t.speed(0)
t.color('red')
t.begin_fill()
for i in range(108):
# t.pensize(i)
t.circle(i*2)
t.lt(10)
t.end_fill()
|
ff517e35c73eb3ea5663a64d2748e01f16f297e1 | Valink16/primer | /primer.py | 845 | 3.703125 | 4 | from time import time
def primeList(limit,getTime=False):
if(getTime):
s=time()
primes=[2,3]
for act in range(5,limit,2):
isPrime=True
for i in range(3,act):
if(act%i==0):
isPrime=False
break
if(isPrime):
primes.append(act)
if(getTime):
e=time()
return {"primes":primes,"time":e-s}
return {"primes":primes}
def factorize(nb):
primes=primeList(1000)["primes"]
originalNb=nb
factorized=[]
states=[]
loop=True
while(loop):
for fact in primes:
if(nb%fact==0):
factorized.append(fact)
nb/=fact
states.append(nb)
break
if(int(nb)==1):
loop=False
return {"factors":factorized, "states":states}
|
6e57527a49c4076311a58895cdee29fe8cf3769f | BJV-git/leetcode | /array/monotonic_array.py | 855 | 3.5 | 4 | # logic:
def isMonotonic(A):
flagg = 0
flag_set = 0
prev = A[0]
for i in A:
curr = i
diff = prev-curr
if flag_set ==0:
if diff < 0:
flagg -= 1
flag_set = 1
if diff > 0:
flagg+=1
flag_set = 1
if (flagg ==1 and diff < 0) or (flagg==-1 and diff >0):
return False
prev = curr
return True
# if flag_dec <2:
# if prev > curr:
# flag_inc = 2
# if prev < curr and flag_inc ==2:
# return False
# if flag_inc < 2:
# if prev < curr:
# flag_inc = 2
# if prev > curr and flag_dec ==2:
# return False
# prev = curr
# return True
print(isMonotonic([-1000,1,1,-1])) |
48eeb74579632828f6a2ccacd00014c3ff7020a0 | jaygoyani1/Solved_Leetcode_Python | /insert-delete-getrandom-o1/insert-delete-getrandom-o1.py | 1,252 | 4.15625 | 4 | class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.dic = {}
self.list = []
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
"""
if val in self.dic:
return False
self.dic[val] = len(self.list)
self.list.append(val)
return True
def remove(self, val: int) -> bool:
"""
Removes a value from the set. Returns true if the set contained the specified element.
"""
if val in self.dic:
last_val,curr_index = self.list[-1], self.dic[val]
self.dic[last_val] , self.list[curr_index] = curr_index, last_val
self.list.pop()
del self.dic[val]
return True
return False
def getRandom(self) -> int:
"""
Get a random element from the set.
"""
return random.choice(self.list)
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom() |
84999ee2907b3a68737f00a2652e641e41412da3 | idep-nter/rock-paper-scissors | /RockPaperScissors.py | 2,686 | 4.15625 | 4 | import random
def main():
"""
The main function starts by printing an intro as usual, then asks for a player's
move, generates opponent's move and evaluates a result.
If it's a tie, it automatically starts over again.
At the end it asks the player if he wants play again and if not, it prints his
score.
"""
intro()
global score
score = 0
while True:
pMove = playerMove()
aiMove = superAIMove()
if result(pMove, aiMove):
continue
if repeat():
continue
else:
break
print(f"Your score for today is: {score}\nBye!")
def intro():
print("""
=================================
WELCOME TO THE GAME!
You already know the rules, so let's begin!
Have fun!
=================================
""")
def playerMove():
"""
Asks the player for a move and returns it after it checks if it's correct.
"""
moves = ['p', 'r', 's']
while True:
try:
move = input("Enter 'p' for paper, 'r' for rock or 's' for "
"scissors\n")
if move not in moves:
raise ValueError
else:
return move
except ValueError:
print("Please follow the instructions!")
continue
def superAIMove():
"""
Generates a random move.
"""
moves = ['p', 'r', 's']
move = random.choice(moves)
return move
def result(pMove, aiMove):
"""
Compares both moves and adds up score if player wins. If it's a tie, it
returns True.
"""
moves = {'p' : 'paper', 'r' : 'rock', 's' : 'scissors'}
print(f"Your move is {moves[pMove]} and opponent's move is {moves[aiMove]}")
print("And...")
if (pMove == 'r' and aiMove == 's') or (pMove == 'p' and aiMove == 'r') \
or (pMove == 's' and aiMove == 'p'):
print("You have won!")
global score
score += 10
elif pMove == aiMove:
print("It's a tie!")
return True
else:
print("You have lost!")
def repeat():
"""
Asks the player if he wants to repeat the game and checks if the answer is correct.
"""
while True:
try:
r = input("Want to play again? y/n\n")
if r == "y":
return True
elif r == "n":
return False
else:
raise ValueError
except ValueError:
print("Please enter 'y' for yes or 'n' for no.")
continue
if __name__ == '__main__':
main()
|
43569b22088e989eb4239ab9e7d4927aef23bc3c | mohitbishnoi/Basic-Python | /datatypes.py | 1,157 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 10:48:09 2019
@author: Mohit
"""
#datatype = different type od values python can store
#1 integer - numeric values
#2 float - numeric values with decimal
#3 string - character or any types of value
#4 complax - a+bj where 'a' is real value and 'b' is imaginary values
#placeholder
#1 list
#2 tuple
#3 dictionary
x = 10
y = 10.0
#type() - return data types of a variable
type(x)
#bool - boolean value - it is a subtype of integer
z = True
type(z)
student_id = 'A101'
com = 1+2j
type(com)
a = 1+2j
b = 2+3j
c=a+b #3+5j
d = a*b #2*(1+2j)+3j*(1+2j) = 2+4j+3j+6 = -4+7j
print(c,d)
b1=True #1
b2=False #0
b1+b2
b1*b2
b1&b2 #b1 and b2
b1|b2 #pipeline - b1 or b2
learn = "python"
learn = learn.upper()
learn
len(learn)
new = learn+" learning" #concatination
new
#Python learning
newr = new[0]+new[1:6].lower()+' '+new[7].upper()+new[8:]
print(newr)
#pyTon
learn[0:2].lower()+learn[2].upper()+learn[4:6].lower()
#list slicing
listname[start:stop] - #extract value from start and stop position excluding stop position
|
ad41cbc550bd46e96ee6aa153cf71095fb580a60 | EricksonGC2058/all-projects | /practice3.py | 652 | 4.40625 | 4 | day = input("What is today? ")
if day == "Monday" or day == "monday":
print("It's Monday, the weekend is over")
elif day == "Friday" or day == "friday":
print("It's Friday, the weekend is close")
elif day == "Saturday" or day == "saturday":
print("It's the weekend, time to relax")
elif day == "Tuesday" or day == "tuesday":
print("It's not the weekend yet")
elif day == "Wednesday" or day == "wednesday":
print("It's not the weekend yet")
elif day == "Thursday" or day == "thursday":
print("It's not the weekend yet")
elif day == "Sunday" or day == "sunday":
print("The weekend is almost over")
else:
print("Follow directions") |
f71f8833f6efd00ea8197899a514ada8f7ab5eea | alehpineda/python_morsels | /add/add.py | 453 | 3.953125 | 4 | """ add function """
from typing import List
from itertools import zip_longest
def add(*args: List) -> List:
"""
Function that accepts two lists-of-lists of numbers and returns one
list-of-lists with each of the corresponding numbers in the two given
lists-of-lists added together.
"""
try:
return [list(map(sum, zip_longest(*t))) for t in zip_longest(*args)]
except TypeError:
raise ValueError
|
23641cdc0b3dd4cba891380a3a6a775c51099a4d | mahavenkatvas/my_coding | /strspecial.py | 162 | 3.546875 | 4 | n=input()
c=0
for i in n:
if i.isnumeric():
c=c
elif i.isalpha():
c=c
elif i.isspace():
c=c
else:
c=c+1
print(c)
|
c994854ce1a6988295994714b94ba4ca005f1a66 | jamesedchristie/calculator | /check.py | 1,667 | 4.1875 | 4 | # Function to check input is valid operation
def valid_input(prefix, all_variables):
valid_ops = ['+', '-', '*', '/', '^']
# Check that expression doesn't end in operator
if prefix[-1] in valid_ops:
print("Invalid expression")
return False
# Check that there is only one = sign
if prefix.count('=') > 1:
print("Invalid assignment")
return False
# Check for valid parentheses
if '(' in prefix or ')' in prefix:
if prefix.index('(') > prefix.index(')') or prefix.count('(') != prefix.count(')'):
print("Invalid expression")
return False
# If only a variable is inputted, check it is known
if '=' not in prefix:
if len(prefix) == 1 and prefix[0].isalpha() and prefix[0] not in all_variables:
print("Unknown variable")
return False
# If operation is to assign value to variable...
if prefix.count('=') == 1:
# Separate left and right side of operation to variable and value respectively
variable = prefix[0]
value = prefix[2:]
# Check variable is only letters
if not variable.isalpha():
print("Invalid identifier")
return False
# Check value is either a number or only letters
elif not valid_input(value, all_variables):
print("Invalid assignment")
return False
# If it's letters, check it is a known variable
else:
for i in value:
if i.isalpha() and i not in all_variables:
print("Unknown variable")
return False
return True |
fc245a88dbc9f2a740e8b193ac13786bba81a861 | Uyouii/TPS-SLG-GAME | /server/storage/accountTable.py | 1,962 | 3.78125 | 4 | import sqlite3
from table import Table
class AccountTable(Table):
def __init__(self, db_connect, table_name='Account'):
super(AccountTable, self).__init__(db_connect, table_name)
self.columns = ['name', 'password']
def create_table(self):
db_cursor = self.db_connect.cursor()
# create table
try:
db_cursor.execute("create table Account("
"name char(50) primary key not null, "
"password char(50) not null);")
except sqlite3.OperationalError as e:
print e
self.db_connect.commit()
def table_init(self):
db_cursor = self.db_connect.cursor()
self.drop_table()
self.create_table()
# create default user
try:
db_cursor.execute("insert into Account (name, password) values ('test1', 163);")
db_cursor.execute("insert into Account (name, password) values ('test2', 163);")
db_cursor.execute("insert into Account (name, password) values ('test3', 163);")
except sqlite3.IntegrityError as e:
print e
self.db_connect.commit()
def query_password(self, name):
db_cursor = self.db_connect.cursor()
query_stat = "select name, password from " + self.table_name + " where name = '" + name + "';"
result_cur = db_cursor.execute(query_stat)
result = result_cur.fetchone()
if result is None:
return result
else:
return result[1].encode('utf-8')
def find_name(self, name):
db_cursor = self.db_connect.cursor()
query_stat = "select name from " + self.table_name + " where name = '" + name + "';"
result_cur = db_cursor.execute(query_stat)
result = result_cur.fetchone()
if result is None:
return result
else:
return result[0].encode('utf-8')
|
65d199e50408aef54a361447a59d8f87639d48ba | mandamg/Exercicios-de-Python-do-Curso-em-Video | /mundo 3/aula 16/desafio3.py | 447 | 3.953125 | 4 | # from random import sample
# numeros = (sample(range (0,11), 5))
# print(f'a sequencia de 5 numeros: {numeros}')
# print(f'o maior numero é: {max(numeros)}')
# print(f'o menor numero é: {min(numeros)}')
from random import randint
numero = (randint(0,11), randint(0,11), randint(0,11), randint(0,11), randint(0,11))
for c in range (0,5):
print(numero[c], end = ' ')
print(f'\nmaior valor {max(numero)}')
print(f'maior valor {min(numero)}') |
89e3165e5921ca69fa0e4119e5f19918f12f2ae9 | mxdzi/hackerrank | /problem_solving/algorithms/bit_manipulation/q2_maximizing_xor.py | 452 | 3.65625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the maximizingXor function below.
import itertools
import operator
def maximizingXor(l, r):
return max(operator.xor(*i) for i in list(itertools.combinations_with_replacement(range(l, r + 1), 2)))
def main():
l = int(input())
r = int(input())
result = maximizingXor(l, r)
print(str(result), sep='\n')
if __name__ == '__main__':
main()
|
19b3e87b3384c564e400f469b1f8ae5698ee9404 | ANGIE0077/python_turtle_homework | /homework.py | 722 | 3.75 | 4 | import turtle as tt
def star():
tt.pensize(1)
tt.color('black','pink')
tt.begin_fill()
for i in range(5):
tt.forward(20)
tt.right(144)
tt.end_fill()
def tree(length):
if length>=5:
tt.speed(0)
tt.forward(length)
tt.right(20)
tree(length-10)
star()
tt.left(40)
tree(length-10)
tt.right(20)
tt.backward(length)
def write():
tt.penup()
tt.goto(-300,-150)
tt.color('violet')
tt.write("for_my_beloved_QY",font=('Arial',20))
tt.hideturtle()
def main():
tt.left(90)
tt.penup()
tt.backward(150)
tt.pendown()
tree(100)
write()
tt.done()
if __name__=="__main__":
main() |
f5bb5e7a4cfa1091a643032e9533da3a2e3aa2de | JuliandresCanon/MISION_TIC_2022 | /1. Python/Clases/clase_11.5.py | 1,664 | 3.875 | 4 | precio_manzana = 2500
cant_manzana = 5
precio_panes = 1500
cant_panes = 3
precio_salchichas = 1200
cant_salchichas = 7
precio_salsas = 3000
cant_salsas = 2
subtotal = 0
cantidad = 0
print("Calculando el total del mercado... ")
total_manzana = precio_manzana * cant_manzana
print("El valor total de las manzanas es: $" + str(total_manzana))
subtotal = subtotal + total_manzana
print("... El Subtotal sería de: $"+ str(subtotal))
cantidad = cantidad + cant_manzana
print("Se han comprado "+ str(cantidad) + " Productos")
total_panes = precio_panes * cant_panes
print("El valor total del panes es: $" + str(total_panes))
subtotal = subtotal + total_panes
print("... El Subtotal sería de: $"+ str(subtotal))
cantidad = cantidad + cant_panes
print("Se han comprado "+ str(cantidad) + " Productos")
total_salchichas = precio_salchichas * cant_salchichas
print("El valor total del salchichas es: $" + str(total_salchichas))
subtotal = subtotal + total_salchichas
print("... El Total de mercado es de: $"+ str(subtotal))
cantidad = cantidad + cant_salchichas
print("Se han comprado "+ str(cantidad) + " Productos")
total_salsas = precio_salsas * cant_salsas
print("El valor total del salsas es: $" + str(total_salsas))
subtotal = subtotal + total_salsas
print("... El Total de mercado es de: $"+ str(subtotal))
cantidad = cantidad + cant_salsas
print("Se han comprado "+ str(cantidad) + " Productos")
pago = int(input("Ingrese el monto recibido del cliente: "))
cambio = pago - subtotal
if cambio > 0:
print("El pago fue realizado efectivamente: \n Cambio: $" + str(cambio))
else:
print("El monto recibido es insuficiente: \n Faltan $"+ str(cambio*-1))
|
ecc99c87b78cc97046f4602cf1aab11c8f0ad44d | boh-prog/More-Projects | /WAR cardGame/WarGame.py | 5,201 | 3.796875 | 4 | ## War Game
## ver1
import random
class Card:
'''build card object'''
##every card object have ranking and alliance2666
def __init__(self, rank, alliance, value):
self.rank = rank
self.alliance = alliance ##
self.value = value ##card numeric value
def __repr__(self):
return f"{self.rank}{self.alliance}"
class Deck:
'''creates a collectioin of card objects'''
##a deck consist of card objects
def __init__(self):
self.deck = []
for alliance in ["black","heart","clover","spades"]:
##create of list of card objects: 52cards
self.deck.append(Card("A",alliance,14))
self.deck.append(Card('2',alliance,2))
self.deck.append(Card('3',alliance,3))
self.deck.append(Card('4',alliance,4))
self.deck.append(Card('5',alliance,5))
self.deck.append(Card('6',alliance,6))
self.deck.append(Card('7',alliance,7))
self.deck.append(Card('8',alliance,8))
self.deck.append(Card('9',alliance,9))
self.deck.append(Card('10',alliance,10))
self.deck.append(Card("Joker",alliance,11))
self.deck.append(Card("Queen",alliance,12))
self.deck.append(Card("King",alliance,13))
def shuffle(self):
'''shuffle the deck of cards'''
random.shuffle(self.deck) ##shuffle deck of cards
def __len__(self):
return len(self.deck)
def pop(self):
return self.deck.pop()
class Player:
''' defines the player object
Each player has a name and hold a set of cards
'''
def __init__(self, playerName):
self.name = playerName
self.cards = []##cards up
self.faceDown = []
self.faceUp = []
def playCard(self):
'''return card from player's set '''
if self.faceDown:
return self.faceDown.pop()##play a card from player faceDown deck
elif self.faceUp:
##faceUp cards to faceDown Deck and suffle
self.addCards(self.faceUp, "down")
self.shuffle()
return self.faceDown.pop()
def shuffle(self):
'''shuffles card in faceDown deck'''
random.shuffle(self.faceDown)
def addCards(self, arrayOfCards, deck=None):
if deck == 'down':##add cards to player deck of faceDown cards
self.faceDown = self.faceDown + arrayOfCards
else: ##add win cards to players deck of win plays
self.faceUp = self.faceUp + arrayOfCards
def countCards(self):
##count total number of cards player holds
return len(self.faceDown + self.faceUp)
def __repr__(self):
return f"name {self.name}\n cards {self.cards}"
def Board(player1, player2, card1, card2, warCards):
'''compare the cards played on baord'''
if card1.value > card2.value:
cards = [card1,card2] + warCards
player1.addCards(cards)
elif card1.value < card2.value:
cards = [card1,card2] + warCards
player2.addCards(cards)
else:
return "tie"
def shareCards(player1, player2, deck):
deck = deck.deck
set1, set2 = [], []
for c in range(len(deck)-1): ##distribute cards to players, 26 cards each
set1.append(deck[c])
set2.append(deck[c+1])
player1.addCards(set1)
player2.addCards(set2)
def PlayGame():
player1 = Player(input("Enter name of player1: ")) ##get name of player 1
player2 = Player(input("Enter name of player2: ")) ##get name of player 2
Dk = Deck() ## get deck of cards
Dk.shuffle() ## shuffle cards
warCards = [] ##instantiate cards resulting from warPlay
shareCards(player1, player2, Dk) ##distribute cards to players
while True:
if player1.countCards() == 52:
return f"{player1.name} Wins!"
elif player2.countCards()==52:
return f"{player2.name} Wins!"
##check case when player does not have cards to play and the other does not have 52 cards
elif player1.countCards()==0:
return f"{player2.name} Wins!"
elif player2.countCards()==0:
return f"{player1.name} Wins!"
##proceed to playe
card1 = player1.playCard()
card2 = player2.playCard()
print(card1.value,card2.value) ##debugging purpose
if Board(player1, player2, card1, card2, warCards) == "tie":
##players play faceDown Cards from their deck
##check if each player still has cards to play
if player1.countCards()==0:
return f"{player2.name} Wins!"
elif player2.countCards()==0:
return f"{player1.name} Wins!"
downCard1, downCard2 = player1.playCard(), player2.playCard()
warCards = warCards + [card1, card2, downCard1, downCard2] ##add cards resulting from war play to War Deck
##proceed to next play
|
e899908dde01b08114cc3c268ed89eb5ee4e1d23 | rafalwilk4ti1/Projekt2020 | /TheArtOfDoing-basic/Lists/Different Types of Lists Program.py | 1,882 | 3.8125 | 4 | import math
import cmath
import datetime
from math import sqrt
import random
# Lists Challenge 7 - Different Types of Lists Program
# Making 4 lists
num_strings = ["15","100","55","42"]
num_ints = [15,100,55,42]
num_floats = [1.2, 2.3, 3.4, 4.5]
num_lists = [[1,2,3,],[4,5,6],[7,8,9]]
# First 3 sentenceses
num_strings = type(num_strings)
print("\t\t\t Summary Table")
print("\nThe variable num_strings is a " +str(num_strings) +".")
num_strings = ["15","100","55","42"]
print("It contains the elements: ", num_strings ,".")
num1 = type(num_strings[0])
print("The element", num_strings[0], "is a ", num1 , "." )
# Second 3 sentences
num_ints = type(num_ints)
print("\nThe variable num_ints is a ",str(num_ints) ,".")
num_ints = [15,100,55,42]
print("It contains the elements: ",num_ints,".")
num2 = type(num_ints[0])
print("The element",num_ints[0],"is a",num2,".")
# Third 3 sentences
num_floats = type(num_floats)
print("\nThe variable num_floats is a", str(num_lists),".")
num_floats = [0.2, 2.3, 3.4, 4.5]
print("It contains the elements: ",num_floats ,".")
num3 = type(num_floats[0])
print("The element",num_floats[0],"is a ",num3,".")
# Fourth 3 sentences
num_lists = type(num_lists)
print("\nThe variable num_lists is a ",str(num_lists),".")
num_lists = [[0,2,3,],[4,5,6],[7,8,9]]
print("It contains the elements: ",num_lists,".")
num4 = type(num_lists[0])
print("The element", num_lists[0], "is a ",num4,".")
num_strings = ["15","100","55","42"]
num_ints = [15,100,55,42]
num_floats = [1.2, 2.3, 3.4, 4.5]
num_lists = [[1,2,3,],[4,5,6],[7,8,9]]
num_strings.sort()
num_ints.sort()
print("\nNow sorting num_strings and num_ints...")
print("Sorted num_strings: ", num_strings,".")
print("Sorted num_ints: ",num_ints, ".")
print("\nStrings are sorted alphabetically while integers are sorted numerically!")
|
745ef9a1fab4e92f2c043ae040081f2ac13e88d2 | CodeInDna/CodePython | /Basics/20_functions_part2.py | 4,322 | 4.5 | 4 | #------------functions part 2--------------#
# *args (it can be named anything like *nums) operator (it is used to pass a variable
# number of arguments to a fn)
# In the below example, it treat the first param as num1 and rest of them treated
# as the list of tuples
def sum_nums(num1, *args):
print(num1) #3
total = 0
for nums in args:
total += nums
return total
print(sum_nums(3,4,5,7,8,0,2,3,4)) #33 (4+5+7+8+0+2+3+4)
# **kwargs (A special operator we can pass to fn, gathers remaining keywords arguments as a dictionary)
def fav_colors(**kwargs):
# return (kwargs)
for person, color in kwargs.items():
print(f"{person} favourite color is : {color}")
fav_colors(emmel="red",jina="black",simba="white")
# parameter ordering (Important to remember the ordering)
# 1. parameters
# 2. *args
# 3. default paramters
# 4. **kwargs
def display_info(a, b, *args, instructor="Pummy", **kwargs):
return [a,b, args, instructor, kwargs]
print(display_info(1,2,3, last_name="Doe", job="Teacher")) #[1, 2, (3,), 'Pummy', {'last_name': 'Doe', 'job': 'Teacher'}]
# a = 1
# b = 2
# args = (3,)
# instructor = "Pummy"
# kwargs = {'last_name':"Doe", 'job':"Teacher"}
# tuple unpacking(*) (adding * when passing list as an argument)
# **************error error error********************#
# def sum_all_values(*args):
# print(args) #([1,2,3,4,5,6],)
# total = 0
# for num in args:
# total += num
# print(total)
# nums = [1,2,3,4,5,6]
# print(sum_all_values(nums)) #as argument is a list, it will throw an error
# **************error error error********************#
def sum_all_values2(*args):
print(args) #([1,2,3,4,5,6],)
total = 0
for num in args:
total += num
return total
nums = [1,2,3,4,5,6]
print(sum_all_values2(*nums)) #*num - unpack the list
# Dictionary Unpacking(adding ** when passing dictionary as an argument)
def fav_colors2(**kwargs):
for person, color in kwargs.items():
print(f"{person} favourite color is : {color}")
details = {"emmel":"red","jina":"black","simba":"white"}
fav_colors2(**details)
#Exercises
# *args Exercise: The Purple Test
# contains_purple : accepts any no of args, should return True if any of the args are "purple"
# otherwise returns False
def contains_purple(*args):
if "purple" in args:
return True
return False
print(contains_purple(25, "purple")) #True
print(contains_purple("green", False, 37, "blue", "hello world")) #False
print(contains_purple("purple")) #True
print(contains_purple("a", 99, "blah blah blah", 1, True, False, "purple")) #True
print(contains_purple(1,2,3)) #False
# **kwargs Exercise: Combine Words
# combine_words : accepts single word and any no of additional key word args
# if the prefix is provided, return prefix followed by the word
# if the suffix is provided, return the word followed by the suffix
# if neither is provided, just return the word
def combine_words(word, **pre_or_suff):
if 'prefix' in pre_or_suff:
return f"{pre_or_suff['prefix']}{word}"
elif 'suffix' in pre_or_suff:
return f"{word}{pre_or_suff['suffix']}"
return word
print(combine_words("child"))
print(combine_words("child", prefix="man"))
print(combine_words("child", suffix="ish"))
print(combine_words("work", suffix="er"))
print(combine_words("work", prefix="home"))
# *Unpacking Exercise: Count Sevens
def count_sevens(*args):
return args.count(7)
nums = [90,34,2,7,4,2,1,4,7,34,23,2,4,5,7,8,7,8,5,7,5,6,4,5,7,5,7,6,7,8,9,8,6,7,8,7,6,4,6,7,8,8,67,7]
result1 = count_sevens(1,4,7)
result2 = count_sevens(*nums)
print(result1)
print(result2)
#calculate
def calculate(**kwargs):
operation_lookup = {
'add': kwargs.get('first', 0) + kwargs.get('second', 0),
'subtract': kwargs.get('first', 0) - kwargs.get('second', 0),
'divide': kwargs.get('first', 0) / kwargs.get('second', 0),
'multiply': kwargs.get('first', 0) * kwargs.get('second', 0)
}
is_float = kwargs.get('make_float', False)
operation_val = operation_lookup[kwargs.get('operation', '')]
if is_float:
final = f"{kwargs.get('message', 'The result is ')}{float(operation_val)}"
else:
final = f"{kwargs.get('message', 'The result is ')}{int(operation_val)}"
return final
print(calculate(make_float=False, operation='add',message='You just added ',first=1,second=2))
print(calculate(make_float=True, operation='divide',first=3.5,second=5))
|
487aa606c22118ec61378c256f8803991a1b5d3e | uathena1991/Leetcode | /Interview coding problems/google/dp_possible_path.py | 1,180 | 4.03125 | 4 | """
第一题:矩阵从左上角到右下角有多少种走法
给定一个矩形的长宽,用多少种方法可以从左上角走到右上角 (每一步,只能向正右、右上 或 右下走)
Follow up 1:如果给矩形里的三个点,要求解决上述问题的同时,经过这三个点
Follow up 2:如何判断这三个点一定是合理的,即存在路径
Follow up 3:如果给你一个H,要求你的路径必须向下越过H这个界,怎么做 --- (All - those without H)
Follow up 4:要经过某些特定row怎么走?要先经过一个row再经过另一个row怎么走? -- (SAME as asking Follow up 3, H = max(row_i)
"""
"""
The idea is: segment the matrix"""
def dp_path(num_rows, num_columns):
if num_rows * num_columns == 0:
return 0
if num_rows == 1 or num_columns == 1:
return 1
dp = [[0 for _ in range(num_columns)] for _ in range(num_rows)]
dp[0][0] = 1
for c in range(1, num_columns):
dp[0][c] = dp[0][c-1] + dp[1][c-1]
for r in range(1, num_rows-1):
dp[r][c] = dp[r-1][c-1] + dp[r][c-1] + dp[r+1][c-1]
dp[num_rows-1][c] = dp[num_rows-1][c-1] + dp[num_rows-2][c-1]
print(dp)
return dp[0][-1]
print(dp_path(4,6))
|
43b9d86b2279178db0515035eec05863165c5805 | rupaku/Leetcode-solutions | /May/08CheckItsStraightLine.py | 789 | 4.03125 | 4 | '''
You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
Example 1:
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
'''
# Solution::::::::::::::::::::::
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
slope=self.get_slope(coordinates[0],coordinates[1])
for i in range(2,len(coordinates)):
m=self.get_slope(coordinates[i],coordinates[0])
if m != slope:
return False
return True
def get_slope(self,p1:List[int],p2:List[int]):
if p1[0] == p2[0]:
return 100000
return (p2[1]-p1[1])/(p2[0]-p1[0])
|
2e254a70e2300225d8ab8101183ce30db4b5532c | ritwiktiwari/AlgorithmsDataStructures | /LinkedList/Problems/problem-3.py | 932 | 4.09375 | 4 | # Find Loop in the Linked List
from LinkedList import Node
# Creating Circular Linked List
h = Node(8)
g = Node(7, h)
f = Node(6, g)
e = Node(5, f)
d = Node(4, e)
c = Node(3, d)
b = Node(2, c)
a = Node(1, b)
h.next_node = c
def tortoise_hare(head):
"""
Also known as Floyd Cycle Finding Algorithm
:param head:
:return:
"""
tortoise = hare = head
while hare is not None:
tortoise = tortoise.next_node
hare = hare.next_node.next_node
if hare is tortoise:
print(f"Cycle found at {tortoise.data}")
break
def hash_table(head):
my_address_hash = set()
current = head
while current is not None:
if id(current) not in my_address_hash:
my_address_hash.add(id(current))
current = current.next_node
else:
print(f"Cycle found at {current.data}")
break
tortoise_hare(a)
hash_table(a)
|
32ce65d0ed2d59e6bc2ff12d4fa360f40cddd2c2 | KhaterehMohajery/DataScience-PythonProjects | /dataquestexcer/dataquestexcercise.py | 2,106 | 4.15625 | 4 | # This is an excercise to handle data base from SQl and basic manipulation of data base in python
import os
import pandas as pd
import math
import sqlite3
import numpy as np
os.chdir('/Users/khaterehmohajery1/Documents/DataScience/DataScience-PythonProjects/dataquestexcer')
conn = sqlite3.connect('factbook.db')
query = "select * from facts;"
df = pd.read_sql_query(query, con = conn)
conn.close()
# To calculate the population of a a country in n years from now based on current population and growth rate
def pop_growth(country, year):
db = df[['name','population', 'population_growth']]
#db = df.loc[:, ['name','population', 'population_growth']] does the same thing
# drops the row if values in one of these two columns is nan
db = db.dropna(subset = ['population','population_growth'])
data = db.loc[db['name'] == str(country),:]
future_pop = float(data['population'] * math.exp(data['population_growth'] /100 * year))
print("The futur population of " + str(country) + " is " + str(future_pop) + " in " + str(year) + " years.")
# This function gives out the name of countries which have lower population in 35 years form now
def lower(df):
db = df[['name','population', 'population_growth']]
db = db.dropna(subset = ['population','population_growth'])
db['35_population'] = db['population'] * np.exp(db['population_growth'] /100 * 35)
#db = db.loc[db['35_population'] < db['population']]
return db
#highest and lowest population density counties
def density(df):
db = df[["name",'population','area_land']]
db = db.dropna(subset = ["population",'area_land'])
db = db.loc[db['area_land'] != 0]
db['density'] = db['population'] / db['area_land']
db = db.sort(columns= 'density')
lowest_density = db.iloc[0:10, 0]
highest_density = db.iloc[len(db)-11:len(db)-1,0]
# or instead of refering by position reset index
#db = db.reset_index(drop = True, inplace =True)
#lowest_density = db.loc[0:10, 'name']
#highest_density = db.loc[len(db)-11:len(db)-1,'name']
return(highest_density,lowest_density)
|
7c8f80866b517fb409e34c9b3da3a6574858550f | jbeast/Doomtown-for-OCTGN | /o8g/Scripts/card.py | 333 | 3.578125 | 4 | def is_outfit(card):
"""
Returns True or False on whether card is an Outfit.
:param card: A Card
:return: bool
"""
return card.type == 'Outfit'
def is_joker(card):
"""
Returns True or False on whether card is a Joker.
:param card: A Card
:return: bool
"""
return card.type == 'Joker' |
f7198b2ea2bcd59a0640aad92c8647e73b70e2e8 | kaskirana01/Myproject | /01刘/Day17/代码/turtleUsage/textDemo04.py | 540 | 3.6875 | 4 | #绘制五角星
import turtle,time
turtle.pensize(10)
turtle.color("yellow")
turtle.fillcolor("red")
turtle.speed(1)
#开始填充
turtle.begin_fill()
for i in range(5):
#向前移动
turtle.forward(200)
#按照顺时针移动,参数表示移动的角度,left表示逆时针
turtle.right(144)
#turtle.left(100)
#结束填充
turtle.end_fill()
time.sleep(2)
turtle.penup()
turtle.goto(-150,-120)
turtle.color("purple")
turtle.write("OVER",font=("宋体",50,"italic"))
turtle.done()
|
9aa8895673191a653a91adbc4e73e25451803abd | leosantosx/exercicios-em-python | /exercicios/ex54.py | 483 | 3.921875 | 4 | """
EXERCÍCIO 055: Maior e Menor da Sequência
Faça um programa que leia o peso de cinco pessoas.
No final, mostre qual foi o maior e o menor peso lidos.
"""
maior = 0
menor = 0
for i in range(1,6):
peso = int(input('Digite o peso da {}° pessoa: '.format(i)))
if peso > maior:
maior = peso
if i == 1:
menor = peso
if peso < menor:
menor = peso
print('O maior peso foi {}'.format(maior))
print('O menor peso foi {}'.format(menor)) |
73eb3f15d8e3b4eb58de4d8444edc3f9a500f111 | in-s-ane/easyctf-2014 | /Python Basics 10-75/solution.py | 532 | 3.90625 | 4 | # This question was initially extremely vague as to the format of the answer, but it was soon clarified
'''
args[0] is a result of XOR encryption on two hexadecimal strings. You only know one of the two original strings, args[1], can you find the other?
Clarification: after finding the second string you should print the ascii representation of it as the answer in the Python Editor.
'''
a = hex(int(args[0], 16) ^ int(args[1], 16))[2:][:-1]
b = ""
i = 0
while i < len(a) - 1:
b += chr(int(a[i] + a[i+1], 16))
i += 2
print b
|
10192827b3ad0e36647b9318ba410de0c9bb5ccb | wangjianming/CodeBase | /呼叫转移小编程题目/forward.py | 4,620 | 3.53125 | 4 | #coding=UTF-8
import re
import sys
"""
假定从文件input.txt读入记录,文件内容同题目要求
主入口main共调两个函数getRecords和calculate,一个读取记录,另一个计算
1.getRecords读取文件并解析内容,通过一个正则表达式来匹配每一行呼转记录,如果匹配可以直接得到各个值,如果不匹配,报错并返回
2
2.1 calculate中首先找到“包含要计算日期的呼转记录”
2.2 然后将呼转记录保存到一个map(key=设置了呼转的号码,value=被转移到的号码),<此时就得到当天设置的实际的呼转个数,题目要求之一>
保存到map的另一个额外好处:因为map的key唯一,所以出现同一人的多条呼转记录只能记录一条,那么此时map的大小必然比原纪录个数少
2.3再对所有记录出现过的每一个号码循环查找呼转链(通过map.get一直迭代),直到没有记录(记录呼转链的长度,如果超过之前的最长记录则更新之)或者超过总记录数(说明出现环路则报错并返回)
"""
inputFile = "input.txt"
f = open(inputFile)
def handle_error(errmsg):
"""
异常检测的处理,直接打印错误信息后退出
"""
print errmsg
sys.exit(0)
def getRecords():
"""
返回结果需包含两个值
第一个值是要计算的日期
第二个值是list,其中每个元素是一个tuple表示一条记录,内含4个元素,分别是被叫号码,呼转至的号码,呼转开始日,呼转结束日(含)
"""
#通过一个正则表达式来匹配一行呼叫转移记录是否正确,如果匹配,就可以直接通过匹配组找出需要的记录
dataPattern = re.compile(r"""^\s*
(?P<first>\d{4})\s+ #the first number
(?P<second>\d{4})\s+ #the second number
(?P<startForwardDate>\d+)\s+ #start date
(?P<length>\d+)\s* #len
$""",re.VERBOSE)
theDate = 1
records = []
for index,data in enumerate(f.xreadlines()):
if index == 0: # 第一行,呼叫转移的记录数
try:
recordNum = int(data)
except:
handle_error(u"data format error:<%s> at line %d" %(data.strip(),index+1))
elif recordNum > 0:#普通呼叫转移记录
matcher = dataPattern.match(data)
if matcher:
#直接通过匹配组找出需要的记录
first = matcher.group("first")
second = matcher.group("second")
startForwardDate = int(matcher.group("startForwardDate"))
length = int(matcher.group("length"))
records.append((first,second,startForwardDate,startForwardDate+length-1))
else:
handle_error(u"data format error:<%s> at line %d" %(data.strip(),index+1))
recordNum = recordNum - 1
else:#这里是最后一行了
try:
theDate = int(data)
except:
handle_error(u"data format error:<%s> at line %d" %(data.strip(),index+1))
return theDate,records
def calculate(theDate,records):
"""
根据题目给定条件计算并打印结果
"""
#找出符合如下条件的记录:如果要统计的天数在记录的开始和结束日中间
theRecordsToday = [item for item in records if item[2] <=theDate<=item[3]]
#结果组成一个map,key是呼入号,value是呼出号,如果出现一个人呼转至多个人的情况,后面的覆盖前面的数据
recordsMap = dict([(item[0],item[1]) for item in theRecordsToday] )
if len(theRecordsToday) != len(recordsMap):
handle_error(u"A same number have been forward more than once,pls check")
#找出所有的号码,用set去掉重复
allNumbers = set([item[0] for item in theRecordsToday] + [item[1] for item in theRecordsToday])
maxForwardCallDepth = 0
#从每个号码开始查找转移记录,并记录哪个最长
for currentNumber in allNumbers:
currentDepth = 0
callee = recordsMap.get(currentNumber,None)
while callee != None:
callee = recordsMap.get(callee,None)
currentDepth = currentDepth + 1
if currentDepth > len(recordsMap):
#如果最大深度是否超过总记录,那么一定出现环路,由于set无序,所以很可能检测到的开始号码不是第一个出现环路的
handle_error(u"loop occurred,pls check from number %s" %currentNumber)
if currentDepth > maxForwardCallDepth:
maxForwardCallDepth = currentDepth
print u"第%d天共有%d条呼叫转移设置" %(theDate,len(recordsMap))
print u"第%d天最长的呼叫转移是%d次" %(theDate,maxForwardCallDepth)
if __name__ == "__main__":
theDate,records = getRecords()
calculate(theDate,records) |
aa785c3d96ad750c707fab79f72dc385b0ff2830 | thompestmanhu/tpestmanProgv1p | /les 4/opdrles4_3.py | 214 | 3.609375 | 4 |
uurloon = input('Wat verdien je per uur: ')
uurgewerkt = input('Hoeveel uur heb je gewerkt: ')
salaris = float(uurloon) * int(uurgewerkt)
print(uurgewerkt + ' uur werken levert ' + str(salaris) + ' Euro op')
|
9a3e5eb2507544374fdda02210122e10ade7f389 | codingninja614/python | /zip2.py | 131 | 3.921875 | 4 | my_strings = ['a', 'b', 'c', 'd', 'e']
my_numbers = [5,4,3,2,1]
reverse=my_numbers.sort()
print(list(zip(reverse,my_strings)))
|
e34cdb16cf3a0fd2a4ca3ff3e4038907651b59ea | Ali-Jahromi/Game-of-Life | /main.py | 2,070 | 3.859375 | 4 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import os
import random
import time
#Fucntion to draw the world of cells
def draw(u, h, w):
#Draw in terminal
print("------------------------------")
for x in range(30):
for y in range(30):
if y != 29:
print(u[x][y], end='')
else:
print(u[x][y])
print("------------------------------")
#Draw 2d plot of matrix
plt.imshow(u)
plt.draw()
plt.ion()
plt.pause(0.001)
plt.clf()
#Function to evolve the world based on Conway's defined rules
def evolution(u, h, w):
#Drawing a temporary world to evolve
NewWorld = [[0 for x in range(w)] for y in range(h)]
for x in range(30):
for y in range(30):
alivecells = 0
#Checking all surrouding cells to cound alive ones
for xd in range(x-1, x+2):
for yd in range(y-1, y+2):
if u[(yd + h) % h][(xd + w) % w] == 1:
alivecells += 1
#If the centering cell is alive reduce the number of alive cells by 1
if u[y][x] == 1:
alivecells -= 1
#Rules 2, and 4 from Wikipedia
if alivecells == 3 or (alivecells == 2 and u[y][x] == 1):
NewWorld[y][x] = 1
draw(NewWorld, h, w)
#Copying temporary world to the main world
for x in range(30):
for y in range(30):
worldnum [x][y] = NewWorld[x][y]
if __name__ == "__main__":
w = 30
h = 30
#Generating the main world by 30*30 dimension with random values
world = [[int((random.random()*100)%10) for x in range(w)] for y in range(h)]
worldnum = [[0 for x in range(w)] for y in range(h)]
for x in range(30):
for y in range(30):
if world[x][y] > 1:
worldnum[x][y] = 0
else:
worldnum[x][y] = 1
draw(worldnum, h , w)
while 1:
evolution(worldnum, w, h)
time.sleep(.2)
os.system('clear')
|
c0f6610699a7dfc82f91e900a59e0bd85e08ca25 | zhujiecong/shiyanlou-000 | /cal_01_02.py | 1,135 | 3.75 | 4 | #!/usr/bin/env python3
import sys
#config
premium_rate = 0.165
Threshold = 3500
def pay(salary):
taxable_income = salary*(1- premium_rate) -3500
if taxable_income <= 1500:
tax = taxable_income * 0.03
elif 1500 < taxable_income <= 4500:
tax = taxable_income * 0.10 - 105
elif 4500 < taxable_income <= 9000:
tax = taxable_income * 0.20 - 555
elif 9000 < taxable_income <= 35000:
tax = taxable_income * 0.25 - 1005
elif 35000 < taxable_income <= 55000:
tax = taxable_income * 0.30 - 2755
elif 55000 < taxable_income <= 80000:
tax = taxable_income * 0.35 - 5505
elif 80000 < taxable_income:
tax = taxable_income * 0.45 - 13505
return format(salary*(1- premium_rate) - tax,".2f")
#salary = int(sys.argv[1])
#print(salary)
#salary_d = dict()
pay_d = dict()
#print(sys.argv[1])
for arg in sys.argv[1:]:
try:
pay_d[int(arg.split(':')[0])] = pay(int(arg.split(':')[1]))
except ValueError:
print("Parameter Error")
for key,value in pay_d.items():
print(str(key)+':'+str(value))
#print(format(pay(salary), ".2f"))
|
f6a2ef05c4148402f11c52f5fc6a1d1e7dbbd040 | DidactsOrg/graph_learning | /minimizer.py | 3,775 | 3.578125 | 4 | '''Minimizer routine based on scipy.optimize.minimize'''
import pickle
import numpy as np
from scipy.optimize import minimize
from numpy import linalg as LA
class Minimizer():
"""
A class to minimize an objective function
give an f(0) and constraints
"""
def __init__(self, n_sensors=127, alpha=0.01, S=None):
self.n_sensors = n_sensors
self.alpha = alpha
self.S = S
"""
scipy uses a list of objects specifying constraints
to the optimization problem.
Inequality means that it is to be non-negative
"""
con1 = {'type': 'ineq', 'fun': self.constraint1}
con2 = {'type': 'ineq', 'fun': self.constraint2}
con3 = {'type': 'ineq', 'fun': self.constraint3}
self.cons = ([con1, con2, con3])
def to_vector(self, L):
"""
scipy.optimize.minmize uses 1D vectors,
therefore we flat the matrix
(this is just a workaround, please provide input if you can)
param L: Laplacian
return: flatten Laplacian
"""
assert L.shape == (self.n_sensors, self.n_sensors)
return L.flatten()
def to_matrix(self, vec):
"""
scipy.optimize.minmize uses 1D vectors
param vec: 1D vector
return: matrix
"""
assert vec.shape == (self.n_sensors*self.n_sensors, )
return vec[:self.n_sensors*self.n_sensors].reshape(self.n_sensors, self.n_sensors)
def objective_function(self, L):
"""
objective function
param L: Laplacian (see, https://arxiv.org/abs/1601.02513)
return: objective_function
"""
if L.shape != (self.n_sensors, self.n_sensors):
L = self.to_matrix(L)
# off diagonal elements
i = np.ones((self.n_sensors, self.n_sensors))
np.fill_diagonal(i,0)
L_off = L*i
tr = np.trace(np.matmul(L, self.S))
return tr + self.alpha*LA.norm(L_off, 1)
def constraint1(self, L):
"""
constraint trace(L)>0, on https://arxiv.org/abs/1601.02513
trace(L)>s where s is the number of nodes
param L: Laplacian
return: trace(L)
"""
if L.shape != (self.n_sensors, self.n_sensors):
L = self.to_matrix(L)
return np.trace(L) - self.n_sensors
def constraint2(self, L):
"""
constraint tr + alpha*LA.norm(L, 'fro')>0,
objective function must be positive
param L: Laplacian
return: constraint function
"""
if L.shape != (self.n_sensors, self.n_sensors):
L = self.to_matrix(L)
# off diagonal elements
i = np.ones((self.n_sensors, self.n_sensors))
np.fill_diagonal(i,0)
L_off = L*i
tr = np.trace(np.matmul(L, self.S))
return tr + self.alpha*LA.norm(L_off, 1)
def constraint3(self, L):
"""
constraint L must be a symmetric matrix
param L: Laplacian
return: 1, if is symmetric, -999 if is not
"""
if np.allclose(L, L.T, atol=1e-06):
return 1.0
else:
return -999.0
def Optimization(self, L0, maxiter):
"""
Optimization, method a Trust region
param L0: initial guess
param maxiter: maximum of iterations
return: result (Laplacian)
"""
result = minimize(self.objective_function, self.to_vector(L0),
method='trust-constr',
constraints=self.cons,
options={'maxiter': maxiter, 'verbose': 3, 'gtol': 1e-8})
result.x = self.to_matrix(result.x)
return result
|
e8760147773d9bbb109a5a2dc7a3310fc08eb89b | Sanzhar26/Chapter4 | /task2.py | 920 | 3.796875 | 4 | class Airplane:
def __init__(self,mark,model,year,max_speed):
self.mark = mark
self.model = model
self.year = year
self.max_speed = max_speed
self.odometer = 0
self.is_flying = False
def take_off(self):
self.is_flying = True
message_take = f"{self.mark} {self.model} was take off."
return message_take
def fly(self, km):
self.odometer += km
message_fly = f"{self.mark} {self.model} is flying now {self.odometer}km during the flying {self.max_speed} km/h."
return message_fly
def land(self):
self.is_flying = False
message_land = f"{self.mark} {self.model} landed, the odometer shows {self.odometer}km."
return message_land
start = Airplane("Boeing","TU-154","2020",2000)
print(start.take_off())
print(start.fly(400))
print(start.fly(500))
print(start.land()) |
c88b5b73458260dbed90e6e0207fd016a77b2e8e | nishio/atcoder | /abc194/a.py | 205 | 3.671875 | 4 | MUSHI, NYUSHI = map(int, input().split())
NYUKO = MUSHI + NYUSHI
if NYUKO >= 15 and NYUSHI >= 8:
print(1)
elif NYUKO >= 10 and NYUSHI >= 3:
print(2)
elif NYUKO >= 3:
print(3)
else:
print(4) |
2ee3c334ec38d1b0c478d5c99ce48f39d385aa35 | Nain08/Python-Codes | /occurence of given character.py | 172 | 4.3125 | 4 | #count the occurence of a given character
s1=input("Enter a string:")
c=input("Enter a character:")
for x in s1:
n=s1.count(c)
print("Occurence of given character:",n)
|
b879e428442e6c5b9716dfc11732bd86549ca30c | ryumaggs/ryumaggs.github.io | /downloads/changeMaker.py | 484 | 3.953125 | 4 | # This program takes an amount of change from the user, and computes the
# numbers of each coin using the smallest total number of coins possible.
remainder = eval(input("Enter the total amount in cents (<100) "))
quarters = remainder // 25
remainder = remainder % 25
dimes = remainder // 10
remainder = remainder % 10
nickels = remainder // 5
pennies = remainder % 5
print("pennies: ", pennies)
print("nickels: ", nickels)
print("dimes: ", dimes)
print("quarters: ", quarters)
|
917c9f2d37fb10ff4167ba094d422abed8d9883c | Riturajvats/Python-Codes | /if.py | 174 | 4 | 4 | num1 = 100
num2 = 100
if num1>num2:
print("num1 is greater than num2")
elif num2>num1:
print("num1 and num2 are equal")
else:
print("Both number are equal")
|
fc0ef6a13249f60d9100ef8837ae193ee8aed349 | MinenoLab/ict-ai-seminar1-2019 | /03/ex3-6_func.py | 452 | 3.765625 | 4 | def div(bunshi_value, bunbo_value):
answer = bunshi_value / bunbo_value
return answer
while True:
print("分子を入力してください: ", end="")
bunshi = input()
print("分母を入力してください: ", end="")
bunbo = input()
if float(bunbo) == 0:
print("分母0を検知しました")
else:
answer = div(float(bunshi), float(bunbo))
print("答え: " + str(answer))
|
35fa5431ecda5cc5da3a3f28f6d652359bd1bb74 | slott56/building-skills-oo-design-book | /demo/tests/test_hw_1.py | 991 | 3.65625 | 4 | """
Mastering Object Oriented Design, 4ed.
Example tests using :class:`unittest.TestCase`
"""
from io import StringIO
from unittest import TestCase
from unittest.mock import Mock, patch
import hw
class TestGreeting(TestCase):
def test(self):
g = hw.Greeting("x", "y")
self.assertEqual(str(g), "x y")
class TestMain(TestCase):
def setUp(self):
self.mock_greeting = Mock(
name="Greeting",
return_value=Mock(
name="Greeting instance", __str__=Mock(return_value="mock str output")
),
)
self.mock_stdout = StringIO()
def test(self):
with patch("hw.Greeting", new=self.mock_greeting):
with patch("sys.stdout", new=self.mock_stdout):
hw.main()
self.mock_greeting.assert_called_with("hello", "world")
self.mock_greeting.return_value.__str__.assert_called_with()
self.assertEqual("mock str output\n", self.mock_stdout.getvalue())
|
b8e702ac9b94cec513fa556145f50b64173bdc30 | RicardoBernal72/CYPRicardoBS | /libro/ejemplo1_13.py | 233 | 3.546875 | 4 | CAL1=int(input("calificacion 1"))
CAL2=int(input("calificacion 2"))
CAL3=int(input("calificacion 3"))
CAL4=int(input("calificacion 4"))
CAL5=int(input("calificacion 5"))
PROMEDIO= (CAL1 + CAL2 + CAL3 + CAL4 + CAL5)/5
print(PROMEDIO)
|
fdc3194901afcd31173461b2d874acce07fb51b5 | SatrioPratama75/Lab2 | /Menentukanbilanganterbesar.py | 393 | 3.9375 | 4 | #Menentukan bilangan terbesar menggunakan statement if
print("~"*39)
kelereng_udin = input("Udin memiliki kelereng sebanyak : ")
kelereng_budi = input("Budi memiliki kelereng sebanyak : ")
if kelereng_udin == kelereng_udin:
if kelereng_udin > kelereng_budi:
print("Benar, kelereng Udin lebih banyak ")
else :
print("Salah, keleren Budi lebih banyak")
|
f168262e84a4eeeedc955e6ca6924df5820ce06a | aoakes356/CS351A4 | /wah.py | 7,555 | 3.546875 | 4 | ### ###
# Assignment 4 | by Andrew Oakes | WAH compression test #
# #
### ###
import os # This is imported ONLY to get file size. before and after compressions
# Did this to match the sort that seems to be done in animals_test
def sortKey(arr):
return str(arr[0])+','+str(arr[1])+','+str(arr[2])+'\n'
# stylish method of turning each line of text text into bitmap.
#['cat','dog','turtle','bird',1-10,11-20,21-30,31-40,41-50,51-60,61-70,71-80,81-90,91-100,True, False]
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
def encode(data_points): # takes a list, 0 being the name, 1 being the age, and 2 being true/false
encoded = {'cat':0,'dog':0,'turtle':0,'bird':0,0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,'True':0,'False':0}
encoded[data_points[0]] = 1
encoded[int((int(data_points[1])-1)/10)] = 1
encoded[data_points[2]] = 1
return list(encoded.values())
# WAH | COMPRESS 32-BIT WORD SIZE
# General WAH algorithm
# function for getting all of the words from a column
def getWords(column, word_size):
# Get all of the word_size-1 words, turn them into strings
words = ([''.join(column[i*(word_size-1):(i+1)*(word_size-1)]) for i in range(0,int((len(column))/(word_size-1)))])
# Get the last word that is sub-word_size
words.append(''.join(column[-(len(column)%(word_size-1)):]))
return words
def classifyWord(word, word_size):
# Classify a word as a run of zeroes, a run of ones, or a literal.
if(len(word) < word_size-1): # Partial word, by convention a literal.
return 2
count = sum([int(num) for num in word])
if(count == word_size-1):
return 1
elif(count == 0):
return 0
else:
return 2
def compress(runs,ones_or_zeroes,word,word_size):
# Generates the compressed word from the given information.
if(runs == 0): #literal, add header bit
return '0'+word
else: # runs
b ="{0:b}".format(runs)
return '1'+str(ones_or_zeroes)+'0'*(word_size-2-len(b))+b
def compressCol(words,word_size):
# State variables
run_count = 0
run_type = -1
o_runs = 0
z_runs = 0
literals = 0
compressed = []
for word in words:
res = classifyWord(word,word_size)
if res == 0 or res == 1: # Indicates a run.
if res == 1:
o_runs += 1
elif res == 0:
z_runs += 1
if run_type == -1 or run_type == res:
run_type = res
run_count += 1
else: # run of a different kind
compressed.append(compress(run_count,run_type,word, word_size))
run_count = 1
run_type = res
# start new word store other one.
else: # literal
literals += 1
if run_type == -1: # no runs yet.
compressed.append(compress(run_count,run_type,word, word_size))
# add this word with header bit 0
else: # currently counting runs
compressed.append(compress(run_count,run_type,word, word_size))
run_count = 0
run_type = -1
compressed.append(compress(run_count,run_type,word, word_size))
# add current runs
# add this word with header bit 0
# return a tuple containing the run and literal counts
return (compressed, z_runs,o_runs, literals)
def wah(columns, word_size):
current = ''
o_runs = 0
z_runs = 0
literals = 0
for col in columns:
comp = compressCol(getWords(col,word_size),word_size)
z_runs += comp[1]
o_runs += comp[2]
literals += comp[3]
current += (''.join(comp[0]))+'\n'
return (current, z_runs, o_runs, literals)
#print(compress(7,0,'0'*31))
# Open the file that contains the data
animals_size = os.path.getsize("./animals.txt")
with open('animals.txt','r') as f:
# split by comma, then split by new line
text = [line.split(',') for line in ((f.read()).split('\n')) if len(line) > 0]
# Array for storing columns of data. Will make it easier to compress later.
col = [[] for i in range(0,16)]
# Function to make a string for a given row in the column array.
rowStr = lambda columns, row: (''.join([str(columns[i][row]) for i in range(0,16)]))+'\n'
# Function to make a string for the whole column array.
wholeStr = lambda columns: ''.join([rowStr(columns,i) for i in range(0,len(columns[0]))])
# Function to add a row to the column array.
addRow = lambda columns, data: [columns[i].append(str(data[i])) for i in range(0,16)]
# CREATE UNSORTED ANIMAL BITMAP ####
# Populate the column arrays.
[addRow(col,encode(data)) for data in text]
# CREATE SORTED ANIMAL BITMAP
# Now do it with the sorted data.
col2 = [[] for i in range(0,16)]
text.sort(key = sortKey)
[addRow(col2,encode(data)) for data in text]
o_runs = 0
z_runs = 0
literals = 0
# compress everything using the functions above, and write to the files.
# write unsorted data
with open('unsorted_bitmap_animals.txt','w') as f:
f.write(wholeStr(col))
# Get size of the file to check compression rates.
bitmap_size = os.path.getsize("./unsorted_bitmap_animals.txt")
# write sorted data
with open('sorted_bitmap_animals.txt','w') as f:
f.write(wholeStr(col2))
# Write sorted 32-bit word compressed data
with open('sorted_bitmap_compressed32_animals.txt','w') as f:
res = wah(col2, 32)
z_runs += res[1]
o_runs += res[2]
literals += res[3]
f.write(res[0])
sorted_compressed_32_size = os.path.getsize("./sorted_bitmap_compressed32_animals.txt")
print("----Sorted 32----\n0-Runs: "+str(z_runs)+"\n"+"1-Runs: "+str(o_runs)+"\n"+"Literals: "+str(literals)+"\n"+"Ratio: "+str(sorted_compressed_32_size/bitmap_size)+"\n\n")
z_runs = 0
o_runs = 0
literals = 0
# Write unsorted 32-bit word compressed data
with open('unsorted_bitmap_compressed32_animals.txt','w') as f:
res = wah(col, 32)
z_runs += res[1]
o_runs += res[2]
literals += res[3]
f.write(res[0])
unsorted_compressed_32_size = os.path.getsize("./unsorted_bitmap_compressed32_animals.txt")
print("----Unsorted 32----\n0-Runs: "+str(z_runs)+"\n"+"1-Runs: "+str(o_runs)+"\n"+"Literals: "+str(literals)+"\n"+"Ratio: "+str(unsorted_compressed_32_size/bitmap_size)+"\n\n")
z_runs = 0
o_runs = 0
literals = 0
# write sorted 64-bit word compressed data.
with open('sorted_bitmap_compressed64_animals.txt','w') as f:
res = wah(col2, 64)
z_runs += res[1]
o_runs += res[2]
literals += res[3]
f.write(res[0])
sorted_compressed_64_size = os.path.getsize("sorted_bitmap_compressed64_animals.txt")
print("----Sorted 64----\n0-Runs: "+str(z_runs)+"\n"+"1-Runs: "+str(o_runs)+"\n"+"Literals: "+str(literals)+"\n"+"Ratio: "+str(sorted_compressed_64_size/bitmap_size)+"\n\n")
o_runs = 0
z_runs = 0
literals = 0
# write unsorted 64-bit word compressed data.
with open('unsorted_bitmap_compressed64_animals.txt','w') as f:
res = wah(col, 64)
z_runs += res[1]
o_runs += res[2]
literals += res[3]
f.write(res[0])
unsorted_compressed_64_size = os.path.getsize("unsorted_bitmap_compressed64_animals.txt")
print("----Unsorted 64----\n0-Runs: "+str(z_runs)+"\n"+"1-Runs: "+str(o_runs)+"\n"+"Literals: "+str(literals)+"\n"+"Ratio: "+str(unsorted_compressed_64_size/bitmap_size)+"\n\n")
|
2daed4b9dc32fdcbdcb726771ed4bd9150a207b1 | Davidhfw/algorithms | /python/binarysearch/33_searchRevolveOrderArray.py | 1,693 | 3.625 | 4 | # 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
#
# ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
#
# 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
#
# 你可以假设数组中不存在重复的元素。
#
# 你的算法时间复杂度必须是 O(log n) 级别。
# 解题思路
# 使用二分发查找数组,可能会找到一个有序的数组,如果没有,可以继续二分,最终一定可以找到一个有序数组,
class Solution(object):
def search(self, nums, target):
if not nums or len(nums) == 0:
return -1
left = 0
right = len(nums) - 1
while left < right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
# [left, mid]连续递增
elif nums[left] <= nums[mid]:
# target位于左侧区间
if nums[left] <= target < nums[mid]:
right = mid - 1
# 否则去右侧区间查找
else:
left = mid + 1
# (mid, right]连续递增
else:
# target位于右侧,在右侧区间查找
if nums[mid] <= target < nums[right]:
left = mid + 1
# 否则去左侧区间查找
else:
right = mid - 1
return left if nums[left] == target else -1
if __name__ == '__main__':
target = 0
nums = [3, 4, 5, 6, 9, 0, 1, 2]
result = Solution().search(nums, target)
print(result)
|
8d84f3832420496eeced2c041c0ae5e1c04778a2 | almirderland/pp2 | /1attestation/sis1/5.py | 165 | 3.96875 | 4 | x1 = int(input())
x2 = int(input())
x3 = int(input())
if x1 == x3 == x2 :
print('3')
elif x2 == x3 or x1 == x2 or x1 == x3 :
print('2')
else:
print('0')
|
d6ac6516fa911cc4d1ddcd988d4983ae167b9245 | Hoop77/PythonSimplexAlgorithm | /linearProgram.py | 15,260 | 3.796875 | 4 | from fractions import Fraction
import numpy
import math
class LinearProgram:
def __init__( self, targetFunction, restrictions, baseVariables, nonBaseVariables, lexicographic ):
"""
targetFunction: Array of numbers having the form: [ b, c_1, ..., c_n ]
representing the function: b + c_1*x_1 + ... + c_n*x_n
restrictions: Array of restrictions. A restriction has the form: [ b, a_1, ..., a_n ]
representing the equation a_1*x_1 + ... + a_n*x_n <= b.
baseVariables: Array of strings representing the variable names for base-variables.
nonBaseVariables: Array of string representing the variable names for non-base-variables.
lexicographic: Boolean which states whether the lexicographic version of the algorithm is used.
"""
self.targetFunction = targetFunction
self.restrictions = restrictions
self.baseVariables = baseVariables
self.nonBaseVariables = nonBaseVariables
self.lexicographic = lexicographic
self.prepareTableau()
self.numGeneratedVariables = 0
def printTableau( self ):
print( "\t", end = "" )
for c in range( len( self.colVariables ) ):
print( self.colVariables[ c ], end = "\t" )
print( "" )
for r in range( self.numRows ):
for c in range( self.numCols ):
if( c == 0 ):
print( self.rowVariables[ r ], end = "\t" )
fraction = Fraction.from_float( self.tableau[ r ][ c ] ).limit_denominator()
print( fraction, end = "\t" )
print( "" )
print( "" )
def maximize( self ):
self.printTableau()
pivotCol = self.findPivotCol()
while pivotCol > 0:
pivotRow = self.findPivotRow( pivotCol )
# output pivot row and column
print( "pivot-row: " + self.rowVariables[ pivotRow ] )
print( "pivot-column: " + self.colVariables[ pivotCol ] )
self.createNewTableau( pivotCol, pivotRow )
self.printTableau()
pivotCol = self.findPivotCol()
if pivotCol == -2:
print( "The linear program is not solvable!" )
return False
return True
def maximizeInteger( self ):
print( "Calculate relaxation" )
print( "====================" )
self.maximize()
nonIntegerRow = self.findNonIntegerRow()
while nonIntegerRow != -1:
self.addGomorySchmittRow( nonIntegerRow )
print( "Minimize" )
print( "========" )
if not self.minimize():
return False
nonIntegerRow = self.findNonIntegerRow()
return True
def findNonIntegerRow( self ):
for r in range( self.numRows ):
if not self.isInteger( self.tableau[ r ][ 0 ] ):
return r
return -1
def isInteger( self, floatVal ):
fraction = Fraction.from_float( floatVal ).limit_denominator()
if fraction.denominator == 1:
return True
else:
return False
def addGomorySchmittRow( self, targetRow ):
newRow = []
for val in self.tableau[ targetRow ]:
gomorySchmittVal = -(val - math.floor( val ))
newRow.append( gomorySchmittVal )
self.addRows( [ newRow ] )
self.numGeneratedVariables += 1
genVariable = "g" + str( self.numGeneratedVariables )
self.addRowVariables( [ genVariable ] )
def remaximize( self, additionalRestrictions, additionalBaseVariables ):
"""
Only non-lexicographic way supported!
"""
self.addRows( additionalRestrictions )
self.addRowVariables( additionalBaseVariables )
self.minimize()
def minimize( self ):
"""
Only non-lexicographic way supported!
"""
self.printTableau()
pivotRow = self.findPivotRowDual()
while pivotRow > 0:
pivotCol = self.findPivotColDual( pivotRow )
# output pivot row and column
print( "pivot-row: " + self.rowVariables[ pivotRow ] )
print( "pivot-column: " + self.colVariables[ pivotCol ] )
self.createNewTableau( pivotCol, pivotRow )
self.printTableau()
pivotRow = self.findPivotRowDual()
if pivotRow == -2:
print( "The linear program is not solvable!" )
return False
return True
def addRows( self, rows ):
for row in rows:
self.tableau.append( row )
self.numRows += 1
def addRowVariables( self, additionalBaseVariables ):
for baseVariable in additionalBaseVariables:
self.rowVariables.append( baseVariable )
def prepareTableau( self ):
self.numRows = self.getNumRows()
self.numCols = self.getNumCols()
self.rowVariables = self.getRowVariables()
self.colVariables = self.getColVariables()
self.tableau = []
self.createFirstRowOfTableau()
self.createBodyOfTableau()
def createFirstRowOfTableau( self ):
# first row = target function
row = []
row.append( self.targetFunction[ 0 ] )
if self.lexicographic:
for b in self.baseVariables:
row.append( 0 )
for c in range( 1, len( self.targetFunction ) ):
row.append( -self.targetFunction[ c ] )
self.tableau.append( row )
def createBodyOfTableau( self ):
for r in range( 0, self.numRows - 1 ):
row = []
row.append( self.restrictions[ r ][ 0 ] )
if self.lexicographic:
for c in range( len( self.baseVariables ) ):
if r == c:
row.append( 1 )
else:
row.append( 0 )
for c in range( len( self.nonBaseVariables ) ):
row.append( self.restrictions[ r ][ c + 1 ] )
self.tableau.append( row )
def findPivotCol( self ):
"""
return
> 0: valid pivot column found
-1: all values in row 0 are positive -> linear program is solved
-2: there exists rows where value in row 0 is < 0 but all elements inside those columns are also < 0
"""
nonValidColFound = False
for c in range( 1, self.numCols ):
val = self.tableau[ 0 ][ c ]
if val < 0:
for r in range( 1, self.numRows ):
if self.tableau[ r ][ c ] > 0:
return c
nonValidColFound = True
if nonValidColFound:
return -2
return -1
def findPivotColDual( self, pivotRow ):
possiblePivotCols = self.getColsWherePivotElementIsSmallerThanZero( pivotRow )
if len( possiblePivotCols ) == 0:
return -1
tuples = self.getTuplesFromRow( 0, pivotRow, possiblePivotCols )
return self.extractPossiblePivotColsFromTuplesInLexicographicOrder( tuples )[ 0 ]
def findPivotRow( self, pivotCol ):
if self.lexicographic:
return self.findPivotRowByLexicographicSearch( pivotCol )
return self.findPivotRowByNormalSearch( pivotCol )
def findPivotRowDual( self ):
"""
return
> 0: valid pivot row found
-1: all values in col 0 are positive -> linear program is solved
-2: there exists rows where value in column 0 is < 0 but all elements inside those columns are also > 0
"""
nonValidRowFound = False
for r in range( 1, self.numRows ):
val = self.tableau[ r ][ 0 ]
if val < 0:
for c in range( 1, self.numCols ):
if self.tableau[ r ][ c ] < 0:
return r
nonValidRowFound = True
if nonValidRowFound:
return -2
return -1
def findPivotRowByLexicographicSearch( self, pivotCol ):
possiblePivotRows = self.getRowsWherePivotElementIsGreaterThanZero( pivotCol )
tuples = self.getTuplesFromCol( 0, pivotCol, possiblePivotRows )
for c in range( self.numCols ):
possiblePivotRows = self.extractPossiblePivotRowsFromTuplesInLexicographicOrder( tuples )
if len( possiblePivotRows ) == 1:
break
tuples = self.getTuplesFromCol( c, pivotCol, possiblePivotRows )
if len( possiblePivotRows ) == 0:
return -1
return possiblePivotRows[ 0 ]
def findPivotRowByNormalSearch( self, pivotCol ):
possiblePivotRows = self.getRowsWherePivotElementIsGreaterThanZero( pivotCol )
if len( possiblePivotRows ) == 0:
return -1
tuples = self.getTuplesFromCol( 0, pivotCol, possiblePivotRows )
return self.extractPossiblePivotRowsFromTuplesInLexicographicOrder( tuples )[ 0 ]
def getRowsWherePivotElementIsGreaterThanZero( self, pivotCol ):
rows = []
for r in range( 1, self.numRows ):
pivotElement = self.tableau[ r ][ pivotCol ]
if pivotElement > 0:
rows.append( r )
return rows
def getColsWherePivotElementIsSmallerThanZero( self, pivotRow ):
cols = []
for c in range( 1, self.numCols ):
pivotElement = self.tableau[ pivotRow ][ c ]
if pivotElement < 0:
cols.append( c )
return cols
def getTuplesFromCol( self, currCol, pivotCol, possiblePivotRows ):
"""
currCol, pivotCol are indices
returns a list of tuples where each tuple represents:
(lexicographic value, row)
"""
tuples = []
for r in possiblePivotRows:
val = self.tableau[ r ][ currCol ] / self.tableau[ r ][ pivotCol ]
t = ( val, r )
tuples.append( t )
return tuples
def getTuplesFromRow( self, currRow, pivotRow, possiblePivotCols ):
"""
currRow, pivotRow are indices
returns a list of tuples where each tuple represents:
(lexicographic value, column)
"""
tuples = []
for c in possiblePivotCols:
val = self.tableau[ currRow ][ c ] / abs( self.tableau[ pivotRow ][ c ] )
t = ( val, c )
tuples.append( t )
return tuples
def extractPossiblePivotRowsFromTuplesInLexicographicOrder( self, tuples ):
tuples.sort()
possiblePivotRows = []
firstTuple = tuples[ 0 ]
firstVal = firstTuple[ 0 ]
for t in tuples:
val = t[ 0 ]
row = t[ 1 ]
if val != firstVal:
break
possiblePivotRows.append( row )
return possiblePivotRows
def extractPossiblePivotColsFromTuplesInLexicographicOrder( self, tuples ):
tuples.sort()
possiblePivotCols = []
firstTuple = tuples[ 0 ]
firstVal = firstTuple[ 0 ]
for t in tuples:
val = t[ 0 ]
col = t[ 1 ]
if val != firstVal:
break
possiblePivotCols.append( col )
return possiblePivotCols
def createNewTableau( self, pivotCol, pivotRow ):
newTableau = self.createEmptyTable()
# mind the swap of column in lexicographic mode
pivotRowVariable = self.rowVariables[ pivotRow ]
swappedCol = 0
if self.lexicographic:
swappedCol = self.colVariables.index( pivotRowVariable )
else:
swappedCol = pivotCol
self.swapBase( pivotCol, pivotRow )
pivotElement = self.tableau[ pivotRow ][ pivotCol ]
for r in range( self.numRows ):
for c in range( self.numCols ):
if c == swappedCol and r == pivotRow:
newTableau[ r ][ c ] = 1 / pivotElement
elif c == swappedCol and r != pivotRow:
newTableau[ r ][ c ] = self.tableau[ r ][ pivotCol ] / pivotElement * -1
elif c != swappedCol and r == pivotRow:
newTableau[ r ][ c ] = self.tableau[ r ][ c ] / pivotElement
else:
newTableau[ r ][ c ] = (self.tableau[ r ][ c ] - \
( (self.tableau[ r ][ pivotCol ] * self.tableau[ pivotRow ][ c ]) / pivotElement ))
self.tableau = newTableau
def createEmptyTable( self ):
newTableau = []
for r in range( self.numRows ):
row = []
for c in range( self.numCols ):
row.append( 0 )
newTableau.append( row )
return newTableau
def swapBase( self, pivotCol, pivotRow ):
pivotRowVariable = self.rowVariables[ pivotRow ]
pivotColVariable = self.colVariables[ pivotCol ]
self.rowVariables[ pivotRow ] = pivotColVariable
if not self.lexicographic:
self.colVariables[ pivotCol ] = pivotRowVariable
def getRowVariables( self ):
rowVariables = [ "" ]
for b in self.baseVariables:
rowVariables.append( b )
return rowVariables
def getColVariables( self ):
colVariables = [ "" ]
if( self.lexicographic ):
for b in self.baseVariables:
colVariables.append( b )
for n in self.nonBaseVariables:
colVariables.append( n )
return colVariables
def getNumRows( self ):
return len( self.baseVariables ) + 1
def getNumCols( self ):
if self.lexicographic:
return len( self.nonBaseVariables ) + len( self.baseVariables ) + 1
else:
return len( self.nonBaseVariables ) + 1
if __name__ == '__main__':
# # maximize
# targetFunction = [ 8, -9, -4 ]
# restrictions = [
# [ 2, 2, 3 ],
# [ 5, 8, 9 ]
# ]
# baseVariables = [ "x1", "x2" ]
# nonBaseVariables = [ "x1", "u2" ]
# lp = LinearProgram( targetFunction, restrictions, baseVariables, nonBaseVariables, False )
# lp.maximize()
# # remaximize
# additionalRestrictions = [
# [ -1, -2, 1 ]
# ]
# additionalBaseVariables = [ "u3" ]
# lp.remaximize( additionalRestrictions, additionalBaseVariables )
############################################################
# # maximize
# targetFunction = [ 0, 3, -5, 4 ]
# restrictions = [
# [ 6, 3, 1, 1 ],
# [ 6, 1, 2, 3 ],
# [ 3, 1, -1, 2 ]
# ]
# baseVariables = [ "u1", "u2", "u3" ]
# nonBaseVariables = [ "x1", "x2", "x3" ]
# lp = LinearProgram( targetFunction, restrictions, baseVariables, nonBaseVariables, False )
# lp.maximizeInteger()
###############################################################
# maximize
targetFunction = [ 0, 3, -2, 2 ]
restrictions = [
[ 7, 2, 1, 2 ],
[ 13, 3, 4, 2 ]
]
baseVariables = [ "u1", "u2" ]
nonBaseVariables = [ "x1", "x2", "x3" ]
lp = LinearProgram( targetFunction, restrictions, baseVariables, nonBaseVariables, False )
lp.maximizeInteger() |
5227674ac6fae53f5c88ad759dbc6fef9948fc7b | jjypainter/Pygame | /draw_circle2.py | 586 | 3.640625 | 4 | import pygame
pygame.init()
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
size = [400, 300]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Drawing Rectangle")
done = False
clock = pygame.time.Clock()
while not done:
clock.tick(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
screen.fill(WHITE)
pygame.draw.circle(screen, BLUE, [60, 250], 40, 2)
pygame.draw.circle(screen, BLUE, [60, 100], 40)
pygame.display.flip()
pygame.quit() |
bd77362a8168950cdd93aeaf922b3272ca4119d0 | mysourcese/shiyanlou-code | /jump7.py | 83 | 3.625 | 4 | for i in range(101):
if i%7==0 or i%10==7 or i//10==7:
continue
else: print(i)
|
e9eb8b20f5e9a3341343764d7a9fb79fea1f3857 | asanelnur/2021pp2 | /TSIS1/If else/6.py | 52 | 3.53125 | 4 | a=2
b=2
c=5
d=5
if a==b and c==d:
print("Hello") |
2673db128dbfb64109f1543fe1f9c11fe10fd979 | jeet23/AI-Game-Trees | /tree.py | 3,048 | 3.65625 | 4 | import random
import pdb
INFINITY = 10001
class Node(object):
def __init__(self, data):
self.data = data
self.children = []
self.reordered_children = []
def add_child(self, obj):
self.children.append(obj)
self.reordered_children.append(obj)
def insertNodes(root, branching, height, approx):
level = height - 1
if (height == 0) or (branching == 0):
return
# Delta is 0 for leaf nodes and between +approx and -approx for internal nodes
delta = random.randint(-approx, approx) if height != 1 else 0
addDaughtersAtEachLevel(root, branching, delta, level)
# Calculating chance of branching factor for all but root node
branchingFactor = calculateBranchingFactorChance(branching)
branching = branchingFactor
recurseForEachChild(root, branching, height, approx)
def recurseForEachChild(root, branching, height, approx):
for daughters in root.children:
if daughters.data == INFINITY:
break
insertNodes(daughters, branching, height-1, approx)
def addDaughtersAtEachLevel(root, branchingFactor, delta, level):
randomlyChosenDaughter = random.randint(0, branchingFactor-1)
for branches in range(0, branchingFactor):
negatedValue = -(root.data)
# pdb.set_trace()
if branches == randomlyChosenDaughter:
E = negatedValue + delta
print("Copying parent Negated node ----> Adding child node at level {} : {}".format(level, E))
root.add_child(Node(E))
else:
randomNumberGreaterThanNegatedValue = random.randint(negatedValue+1,INFINITY)
E = randomNumberGreaterThanNegatedValue + delta
print("Creating random node ----> Adding child node at level {} : {}".format(level, E))
root.add_child(Node(E))
def printTree(root, branching, height):
print("----------------------- T R E E ---------------------")
for level in range(0, height + 1):
# if level > 1:
# branchingFactor = calculateBranchingFactorChance(branching)
# else:
# branchingFactor = branching
# flagBranchChanged = True if branching != branchingFactor else False
# TODO :: Printing tree with branching factor b+1 or b-1 is BUGGY right now. (>90% chance cases)
printGivenLevel(root, level, branching)
print("\n")
def printGivenLevel(root, level, branchingFactor):
if root is None:
return
elif level == 0:
print(root.data, end=" ")
elif level > 0:
for j in range(0, branchingFactor):
printGivenLevel(root.children[j], level-1, branchingFactor)
print(end = " ")
def calculateBranchingFactorChance(branching):
if (90 < branching % 100 < 95):
branchingFactor = branching + 1
elif ( branching % 100 > 95):
branchingFactor = branching - 1
else:
branchingFactor = branching
return branchingFactor
def main():
# Input branching factor b , Height h and approximation approx
b = 2 #int(input("Enter Branching factor: "), 10)
h = 3 #int(input("Enter Height: "), 10)
approx = 5 #int(input("Enter Approximation: "), 10)
root = Node(random.randint(-2500,2500))
print("Adding root node at height {}: {}".format(h, root.data))
insertNodes(root, b ,h, approx)
printTree(root, b, h)
main()
|
b4b29aac560fafbf9f559c30878b15ebf84a00e5 | anaxronik/Eulers-tasks-python | /7.py | 610 | 3.796875 | 4 | # Выписав первые шесть простых чисел, получим 2, 3, 5, 7, 11 и 13.
# Очевидно, что 6-ое простое число - 13.
#
# Какое число является 10001-ым простым числом?
from is_simple import is_simple
n = 10001
i = 2
simple_list = []
print(len(simple_list))
while True:
if is_simple(i):
simple_list.append(i)
print('Find new simple num = ', i, '\tAmount of simple = ', len(simple_list))
elif len(simple_list) >= n:
print('Biggest simple number is ', simple_list[-1])
break
i += 1
|
086b20cb7aee749937790b366ce618338dfde7e7 | sharmapradyumn/PYTHON-Adhoc | /removechar.py | 172 | 3.859375 | 4 | #!/usr/bin/python3
s = input("enter a string")
i=0
s1=""
for x in s:
if s.index(x)==i:
s1+=x
i+=1
print("removed character string is")
print("\n")
print(s1) |
af377640fbda906b74595bc685cfaf2b25e57ce2 | CHALASS770/WorldOfGame | /CurrencyRouletteGame.py | 1,299 | 3.71875 | 4 | from random import *
from time import sleep
#in this game we must find the trust conversion from USD to ILS
class CurrencyRouletteGame:
def __init__(self, difficult):
self.total_money = int(randint(5,1000)) #random the money in USD that the player must fnd the convert in ils
self.intermin = 0
self.intermax = 0
self.difficult = difficult
self.useramount = 0
#this function create an interval of error for the convert
#the intervall depend of the difficulty of the game
def get_money_interval(self):
self.intermin=self.total_money - (5 - self.difficult)
self.intermax=self.total_money + (5 - self.difficult)
#the player enter the conversion
def get_guess_from_user(self):
print(self.total_money,' USD')
self.useramount=int(input('enter a value in ILS'))
def play(self):
#call function create money
self.get_money_interval()
#call function enter value by th player
self.get_guess_from_user()
#verify if the player entered is in between the interval for win
if self.intermin<self.useramount<self.intermax:
print('you win')
else:
print('you lost')
print(self.intermin,'< ',self.useramount,'< ',self.intermax) |
cb1d7bd79a59b43a5d077081a3599788444574e2 | ruddysimon/HackerRank-solutions | /Python/Introduction/Python If-Else.py | 223 | 4.0625 | 4 | n = int(input())
w = "Weird"
nw = "Not Weird"
# if n is odd
if n % 2 == 1:
print(w)
# if n is even
else:
if 2 <= n <= 5:
print(nw)
elif 6 <= n <= 20:
print(w)
elif n >= 20:
print(nw) |
afce544deb8c096068401586b3c7b883d6b91856 | alexander-colaneri/python | /studies/curso_em_video/ex027-primeiro-e-ultimo-nome-de-uma-pessoa.py | 1,440 | 4.1875 | 4 | # Primeiro e Último Nome de Uma Pessoa.
# Descrição: Faça um programa que leia o nome completo de uma pessoa, mostrando em
# seguida o primeiro e o último nome separadamente.
class AnalisadorDeNomes():
'''Indica separadamente qual é o primeiro e o último sobrenome no nome completo indicado.'''
def _init__(self):
self.nome_completo = ''
self.nome = ''
self.sobrenome = ''
def iniciar(self):
'''Início do programa.'''
print(f'{" ANALISADOR DE NOMES COMPLETOS ":*^41}')
self.receber_nome_completo()
self.analisar_nome_completo()
self.mostrar_resultados()
print('\nTenha um bom dia!')
def receber_nome_completo(self):
'''Recebe o nome completo a ser analisado.'''
print('Digite o nome completo:')
self.nome_completo = input()
return None
def analisar_nome_completo(self):
'''Separa o nome e o último sobrenome do nome completo indicado.'''
nome_completo = self.nome_completo.title().strip().split()
self.nome = nome_completo[0]
self.sobrenome = nome_completo[-1]
return None
def mostrar_resultados(self):
'''Exibe o nome e o último sobrenome.'''
nome = self.nome
sobrenome = self.sobrenome
print(f'\nO primeiro nome é {nome} e o último sobrenome é {sobrenome}.')
analisador = AnalisadorDeNomes()
analisador.iniciar()
|
1466772355c4666d8937e95413898a560c7039e7 | bupthl/Python | /Python从菜鸟到高手/chapter9/demo9.08.py | 1,449 | 3.875 | 4 | '''
--------《Python从菜鸟到高手》源代码------------
欧瑞科技版权所有
作者:李宁
如有任何技术问题,请加QQ技术讨论群:264268059
或关注“极客起源”订阅号或“欧瑞科技”服务号或扫码关注订阅号和服务号,二维码在源代码根目录
如果QQ群已满,请访问https://geekori.com,在右侧查看最新的QQ群,同时可以扫码关注公众号
“欧瑞学院”是欧瑞科技旗下在线IT教育学院,包含大量IT前沿视频课程,
请访问http://geekori.com/edu或关注前面提到的订阅号和服务号,进入移动版的欧瑞学院
“极客题库”是欧瑞科技旗下在线题库,请扫描源代码根目录中的小程序码安装“极客题库”小程序
关于更多信息,请访问下面的页面
https://geekori.com/help/videocourse/readme.html
'''
def fun1():
try:
print("fun1 正常执行")
finally:
print("fun1 finally")
def fun2():
try:
raise Exception
except:
print("fun2 抛出异常")
finally:
print("fun2 finally")
def fun3():
try:
return 20
finally:
print("fun3 finally")
def fun4():
try:
x = 1/0
except ZeroDivisionError as e:
print(e)
finally:
print("fun4 finally")
try:
del x
except Exception as e:
print(e)
fun1()
fun2()
print(fun3())
fun4() |
daa86189a47dca4b0984417f13457f7f9065f95a | Minglee2018/Data_science | /Data_science_with_python/week1/bai6.py | 126 | 3.515625 | 4 | s = input("Enter string : \n ")
w = int (input("Enter width : \n "))
k = 0
while k < len(s):
print (s[k:(w+k)])
k +=w
|
9a42ded35525817559e7dbf41f96eb292a59c1b6 | Nakibaman/python | /10.05.2019/odd_even_from_list.py | 181 | 3.75 | 4 | x=[1,2,3,4,5,9,10]
even=0
odd=0
for i in range(0,len(x),1):
if x[i]%2==0:
even=even+1
else:
odd=odd+1
print "No of even is ",even
print "No of odd is ",odd
|
9bc8f399a141167165ae4da19395a49822ce5710 | rajeshsvv/Lenovo_Back | /1 PYTHON/2 COREY SCHAFER/PART 2/38_class_variables.py | 1,697 | 4.59375 | 5 | # class variables that are shared among all instances of a class
# instance variables contain data that is unique to each instance
class Employee:
raise_amount = 2.36 # class variable
num_of_emps = 0
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = "first" + "." + "last" + "@company.com"
Employee.num_of_emps += 1
# method creation for diplay full name
def fullname(self):
return ("{} {}".format(self.first, self.last))
# method creation for class variable example
def apply_raise(self):
# self.pay = int(self.pay * Employee.raise_amount) #this is through class variable
self.pay = int(self.pay * self.raise_amount) # this is through instance variable
print(Employee.num_of_emps) # before instantiation of employees it becomes 0
emp1 = Employee("Corey", "Schafer", 30000)
emp2 = Employee("test", "user", 10000)
emp3 = Employee("Jony", "Walker", 10000)
print(Employee.num_of_emps) # after instantiation of employees it becomes 3
# print(emp1.first)
# print(emp2.email)
# print(emp1.fullname())
# print(Employee.fullname(emp2)) # call by using class but we need to mention which instance is called
# print(emp2.pay)
# emp2.apply_raise()
# print(emp2.pay)
print(emp1.__dict__) # __dict__ useful for what the attributes it contains this is instance level
print(Employee.__dict__) # this is class level what the attributes it have
# Employee.raise_amount = 1.05
# emp1.raise_amount = 2.36
# print(emp1.__dict__)
# print(Employee.raise_amount)
# print(emp1.raise_amount)
# print(emp2.raise_amount)
|
82125770d13475ea42a916030ca0ac8ec2f326fc | WinrichSy/HackerRank-Solutions | /Python/CollectionsNamedtuple.py | 389 | 4.03125 | 4 | #Collections.namedtuple()
#https://www.hackerrank.com/challenges/py-collections-namedtuple/problem
from collections import namedtuple
times = int(input())
Students = namedtuple('Students', ' '.join(input().split()))
total = 0
for i in range(times):
data = input().split()
student = Students(data[0], data[1], data[2], data[3])
total += int(student.MARKS)
print(total/times)
|
252020c337b849657069c2b920d4aaf50240392f | enxicui/Python | /PythonAssignments/p4.5/p4-5p3.py | 330 | 3.921875 | 4 | while True:
amount=float(input('please enter your amount', ))
tax_larger=amount * 0.6 * 0.135
tax_smaller=amount * 0.4 * 0.23
total =amount + tax_larger + tax_smaller
if amount >= 0:
print('total amount=',total)
else:
print('Amount of income must be >= 0. Please try again.')
break
|
6391bd2eb4bdb85c1f9b4d9fccf7b5b799135807 | akshaykhadse/matlab-usage-stats | /parser/pop_ldap.py | 817 | 3.578125 | 4 | def pop_ldap(ip, active_csv, archive_csv):
"""
Finds LDAP UID for given IP from Portal Log Files. For multiple entries in
log, latest UID will be returned.
First active file will be queried followed by archived file.
**Args:**
*ip: String*
IP address of client.
*active_csv: String*
Path to CSV file for active users.
*archive_csv: String*
Path to CSV file for previous users.
Returns:
*uid: String*
Latest UID from Database matching with the input IP Address
"""
for file in [active_csv, archive_csv]:
with open(file) as data:
for line in data:
fields = line.split(',')
if fields[1].replace('"', '') == ip:
return fields[0].replace('"', '')
return 'NA'
|
a9b11031143f0d4f1aff6ba3f7c9c0badaf470d6 | herojelly/Functional-Programming | /Chapter 6/6_13.py | 355 | 3.765625 | 4 | # Gregory Jerian
# Period 4
def main():
print("This program converts a list of strings to a list of ints.")
Input = input("Enter a list of numbers separated by commas: ")
strList = Input.split(",")
print(toNumbers(strList))
def toNumbers(strList):
for i in range(len(strList)):
strList[i] = int(strList[i])
return strList
main()
|
a788fc1caffc05a3425000b04c8381110ccea6b9 | DainDwarf/AdventOfCode | /2020/Day06/day06.py | 841 | 3.9375 | 4 | #!/usr/bin/python3
from collections import Counter
def part_one(inp):
count = 0
for group in inp.split('\n\n'):
count += len(set(group.replace('\n', '')))
return count
def part_two(inp):
count = 0
for group in inp.split('\n\n'):
group_len = len(group.split('\n'))
for letter, occurrence in Counter(group).items():
if occurrence == group_len:
count += 1
return count
if __name__ == '__main__':
from argparse import ArgumentParser, FileType
args = ArgumentParser()
args.add_argument("input", help='Your input file', type=FileType('r'))
options = args.parse_args()
inp = options.input.read().strip()
print("Answer for part one is : {res}".format(res=part_one(inp)))
print("Answer for part two is : {res}".format(res=part_two(inp)))
|
4ff322a8ecd874baefd5cc6b58fc3b18049beaf7 | cebrusfs/kattis-examples | /en/revadd/output_validators/python2_judge.py | 1,136 | 3.546875 | 4 | #!/usr/bin/env python
# ./validator input judge_answer feedback_dir [additional_arguments] < team_output [ > team_input ]
from sys import stdin, argv
import os
import sys
import re
input_file = argv[1]
ans_file = argv[2]
feedback_dir = argv[3]
judge_feedback = open(os.path.join(feedback_dir, 'judgemessage.txt'), 'w')
team_feedback = open(os.path.join(feedback_dir, 'teammessage.txt'), 'w')
def check(res, msg='Wrong Answer', judge_msg=''):
if not res:
print >>team_feedback, msg
print >>judge_feedback, judge_msg
# Wrong Answer
sys.exit(43)
integer = "(0|-?[1-9]\d*)"
line = stdin.readline()
check(re.match(integer + " " + integer + "\n", line), judge_msg='format error')
# Check for trailing input
check(len(stdin.readline()) == 0, judge_msg='format error')
# check ans
a, b = [int(x) for x in line.split(" ")]
x = int(open(input_file).readline())
check(0 <= a <= 1000, judge_msg='a = {} is out of range'.format(a))
check(0 <= b <= 1000, judge_msg='b = {} is out of range'.format(b))
check(a + b == x, judge_msg='a + b = {}, but should be {}'.format(a + b, x))
# Correct
sys.exit(42)
|
415320df9c59395d859c2fa07e32582ed6bffc80 | pwang867/LeetCode-Solutions-Python | /0205. Isomorphic Strings.py | 1,272 | 3.859375 | 4 | # time/space O(n)
# similar to #290 word pattern
from collections import defaultdict
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
s_dict = defaultdict() # s_dict is {s: t}
t_dict = defaultdict() # t_dict is {t: s}
for i in range(len(s)):
if s[i] in s_dict and s_dict[s[i]] != t[i]:
return False
if t[i] in t_dict and t_dict[t[i]] != s[i]:
return False
s_dict[s[i]] = t[i]
t_dict[t[i]] = s[i]
return True
"""
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving
the order of characters. No two characters may map to the same character but a character may map to itself.
Example 1:
Input: s = "egg", t = "add"
Output: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "paper", t = "title"
Output: true
Note:
You may assume both s and t have the same length.
"""
|
20173b8dcd3bd7b39b13f2f072340b1a6725ed2b | olagesin/Algorithm-Interview-Questions | /binary_tree.py | 1,839 | 4.1875 | 4 | """
implementing a binary tree using Classes and References
"""
class BinaryTree(object):
def __repr__(self):
return "Root of tree is {0} \n" \
"Left child is {1}\n" \
"Right Child is {2}\n" .format(self.key, self.leftChild, self.rightChild)
def __init__(self, root):
self.key = root
self.leftChild = None
self.rightChild = None
def insertLeft(self, newNode):
if self.leftChild is None:
self.leftChild = BinaryTree(newNode)
else:
temp = BinaryTree(newNode)
temp.leftChild = self.leftChild
self.leftChild = temp
def insertRight(self, newNode):
if self.rightChild is None:
self.rightChild = BinaryTree(newNode)
else:
temp = BinaryTree(newNode)
temp.rightChild = self.rightChild
self.rightChild = temp
def getLeftChild(self):
return self.leftChild
def getRightChild(self):
return self.rightChild
def setRootValue(self, value):
self.key = value
def getRootValue(self):
return self.key
# Function to traverse the tree using preorder method
def preorder(tree):
if tree:
print(tree.getRootValue())
preorder(tree.getLeftChild())
preorder(tree.getRightChild())
else:
print("debug")
# Function to traverse the tree using inorder method
def inorder(tree):
inorder(tree.getLeftChild)
print(tree.getRootValue)
inorder(tree.getRightChild)
# Function to traverse the tree using postorder method
def postorder(tree):
postorder(tree.getLeftChild)
postorder(tree.getRightChild)
print(tree.getRootValue)
tree1 = BinaryTree(23)
tree1.insertLeft(12)
tree1.insertLeft(14)
tree1.insertRight(78)
print(preorder(tree1))
|
7e61db983ebf4594d7f75b2a18274748a91f8cc7 | shua-ti/Binsearch | /查找右边区间.py | 594 | 3.75 | 4 | #-*-coding=utf-8-*-
#/usr/bin/env python
"Ҽ"
import bisect
intervals=[[3,4],[2,3],[1,1.2]]
def findRightInterval(intervals):
intvl = sorted([(x[0], i) for i, x in enumerate(intervals)], key=lambda x: x[0])
starts, idx = [x[0] for x in intvl], [x[1] for x in intvl]
res = []
for x in intervals:
pos = bisect.bisect_left(starts, x[1])#start[pos]>=x[1]
print pos,
if pos == len(starts):
res.append(-1)
else:
res.append(idx[pos])
return res
if __name__=="__main__":
print findRightInterval(intervals)
|
80f69e7a2f542cd7ff7357d936b6e9fdd3782b35 | justin-ho/security-tools | /crypto/vigenere.py | 2,479 | 4.21875 | 4 | #!/usr/bin/python
"""Python script to decrypt a vigenere cipher
Uses the given key to shift the letters in the given message.
-m,
The message to encrypt using the key
-k,
The key to encrypt the message with
-a,
enumerate vigenere using keys in the dictionary
-f,
dictionary file
-e,
encrypt the message
-d,
decrypt the message
Example:
python vigenere.py -m 'This is my secret message' -k 'mykey'
"""
import sys
import getopt
from substitution import vigenere
from util import mquit
def enumerate_vigenere(message, filename, encrypt):
"""Enumerates the filename file performing a vigenere shift
on the message using each line from the file as the key"""
fileobj = open(filename, 'r')
iterator = 0
user = ''
viewnumber = 10
# print the enumeration 10 entries at a time
while iterator != viewnumber or user != 'q':
temp = fileobj.readline().rstrip()
if temp == '':
break
print vigenere(message, temp, encrypt)
iterator += 1
# When the enumeration pauses ask the user if they want to continue
if iterator == viewnumber:
user = raw_input('Press Enter to continue or q to quit: ')
if user != 'q':
iterator = 0
fileobj.close()
def main():
"""Main function to run the script"""
argv = sys.argv[1:]
qmessage = 'vigenere.py -m <message> -k <key to use for shifting> ' \
'[-a -f -d -e]'
try:
opts, args = getopt.getopt(argv, "m:k:f:aed")
except getopt.GetoptError:
mquit(qmessage)
# All options must be specified
if len(opts) < 2:
mquit(qmessage)
# get and set all the user defined options
message = ''
key = ''
dictionary = ''
enum = False
encrypt = True
for opt, arg in opts:
if opt == '-m':
message = arg
elif opt == '-k':
key = arg
elif opt == '-f':
dictionary = arg
elif opt == '-a':
enum = True
elif opt == '-e':
encrypt = True
elif opt == '-d':
encrypt = False
# quit if the user did not define a mandatory option
if message == '' or (not enum and key == '') or (enum and dictionary == ''):
mquit(qmessage)
if enum:
enumerate_vigenere(message, dictionary, encrypt)
else:
print vigenere(message, key)
if __name__ == "__main__":
main()
|
a0fdb7711af550ff86faf975c61d7e4fd0a8e5db | coolxv/DL-Prep | /04_Algorithms/Leetcode/JZ15 反转链表.py | 1,586 | 3.890625 | 4 | import json
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def stringToIntegerList(input):
# print('input',input)
return json.loads(input)
# list 转换成链表
def stringToListNode(input):
# Generate list from the input
# numbers = stringToIntegerList(input)
numbers = input
# print('numbers', numbers)
# Now convert that list into linked list
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in numbers:
ptr.next = ListNode(number)
ptr = ptr.next
ptr = dummyRoot.next
return ptr
# 给定头节点,打印链表
def prettyPrintLinkedList(node):
while node and node.next:
print(str(node.val) + "->", end='')
node = node.next
if node:
print(node.val)
else:
print("Empty LinkedList")
# 每次找到前面的一个,并接上,注意自己每次接的结点是什么,里面的next会不会是不需要的
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if not pHead:
return pHead
else:
tmp = ListNode(pHead.val) # 如果直接等于 pHead 的话,会导致也接上了pHead的next,这是不希望有的
nextnode = pHead.next
while nextnode:
prev = nextnode.next
nextnode.next = tmp
tmp = nextnode
nextnode = prev
return tmp
sol = Solution()
head = stringToListNode([0, 1, 2])
prettyPrintLinkedList(head)
prettyPrintLinkedList(sol.ReverseList(head))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.