blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
2565ed582c19e452caa3ba60edfee24ff0831a50 | kerabatsos/PythonVisual | /VSC/TkInter.py | 598 | 3.515625 | 4 | import tkinter
mainWindow = tkinter.Tk()
mainWindow.title("Main Window")
mainWindow.geometry('640x480+8+400')
label = tkinter.Label(mainWindow, text = 'Hello')
label.pack(side="top")
canvas = tkinter.Canvas(mainWindow, relief = 'raised', borderwidth = 1)
canvas.pack(side = 'top')
button1 = tkinter.Button(mainWindow, text = "Button 1")
button2 = tkinter.Button(mainWindow, text="Button 2")
button3 = tkinter.Button(mainWindow, text="Button 3")
button1.pack(side = 'top', anchor = 'n')
button1.pack(side = 'top', anchor = 's')
button1.pack(side = 'top', anchor='e')
mainWindow.mainloop()
|
f05b2f378aa357770430ab8e36da59c29ef836d6 | damnbhola/Data-Structures-and-Algorithms | /LinkedLists/circular_singly_linked_list.py | 3,026 | 4.03125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = self
class CSll:
root = None
def __len__(self):
return self.length()
def clear(self):
self.root = None
def append(self, value):
temp = Node(value)
if self.root is None:
self.root = temp
return
start = self.root
while start.next is not self.root:
start = start.next
start.next = temp
temp.next = self.root
def insert(self, value, pos):
temp = Node(value)
if self.root is None:
self.root = temp
return
start = self.root
count = 1
while start.next is not self.root and count < pos:
count += 1
start = start.next
if pos == 0:
temp.next = self.root
self.root = temp
else:
temp.next = start.next
start.next = temp
def pop(self, pos=None):
if self.root is not None:
start = self.root
if start.next is self.root:
self.root = None
return start.value
count = 1
if pos is None:
pos = self.length() - 1
while start.next.next is not self.root and count < pos:
count += 1
start = start.next
if pos == 0:
start = start.next
temp = self.root
self.root = temp.next
else:
temp = start.next
start.next = temp.next
return temp.value
print("IndexError: Index out of range")
def display(self):
if self.root is None:
print("c_sll is Empty")
return
start = self.root
while start.next is not self.root:
print(start.value, end=" ")
start = start.next
print(start.value)
def length(self):
count = 0
if self.root is not None:
count += 1
start = self.root
while start.next is not self.root:
count += 1
start = start.next
return count
def index(self, value):
if self.root is not None:
start = self.root
count = 0
while start.value != value:
if start.next is self.root:
break
count += 1
start = start.next
else:
print(count)
return
print("ValueError: Value not in sll")
def loc(self, pos):
if self.root is not None:
start = self.root
count = 0
while count != pos:
if start.next is self.root:
break
count += 1
start = start.next
else:
print(start.value)
return
print("IndexError: Index out of range")
|
4169d6b6efaa155f403fa0e5b64124bc9ea5eeb6 | Tuabuela987/untitled1 | /pasword.py | 201 | 3.6875 | 4 | cog = input ("Dime tu apellido: ")
num = input ("Dime un numero: ")
c= ""
for i in range(len(cog)):
if i%2 !=0:
c +=cog[i]
else:
c+=(num)
c.replace (" ", "")
print (c)
|
8934ee6ae3e3d0d077d5f980b6e122dc8fd62e57 | guoyu07/CLRS | /Calc.py | 3,824 | 3.578125 | 4 | __author__ = 'Tong'
priority = {"+": 0, "-": 0, "*": 1, "/": 1, "mod": 1, "(": -99, ")": -999}
n_operands = {"+": 2, "-": 2, "*": 2, "/": 2, "mod": 2}
def get_next(infix):
# Avoid accidental space
infix = infix.strip()
# Find the most adjacent operator
index = float("inf")
operator = ""
for op in priority:
try:
if index > infix.index(op):
index = int(infix.index(op))
operator = op
except ValueError:
continue
# If operator appears in the first position, return the operator.
# Or, deal with operands first.
if index == 0:
infix = infix[len(operator):]
return operator, "operator", infix
elif index == float("inf"):
return infix, "operand", ""
else:
operand = infix[:index]
infix = infix[index:]
return operand, "operand", infix
def infix_to_postfix(infix):
postfix = []
operator_stack = []
while infix != "":
nxt, typ, infix = get_next(infix)
if typ == "operand":
operand = nxt
postfix.append(operand)
elif typ == "operator":
operator = nxt
if operator == ")":
# Pop elements after "("
ptr = len(operator_stack) - 1
while ptr >= 0:
if operator_stack[ptr] != "(":
postfix.append(operator_stack.pop())
ptr -= 1
else:
operator_stack.pop()
break
elif operator == "(":
operator_stack.append(operator)
# If current operator has lower priority:
elif operator_stack == [] or priority.get(operator_stack[len(operator_stack) - 1]) < priority.get(operator):
operator_stack.append(operator)
else:
postfix.append(operator_stack.pop())
operator_stack.append(operator)
while operator_stack:
postfix.append(operator_stack.pop())
for each in operator_stack:
postfix.append(each)
return postfix
def postfix_calc(postfix):
while len(postfix) != 1:
# Find the most adjacent operator
index = float("inf")
operator = ""
for op in n_operands:
try:
if index > postfix.index(op):
index = int(postfix.index(op))
operator = op
except ValueError:
continue
# Here in the case given, only binary operators are required to deal with.
if n_operands.get(operator) == 2:
# Update the postfix removing dealt operands and operator and put in result.
operand1 = postfix[index - 2]
operand2 = postfix[index - 1]
postfix = postfix[:index - 2] + postfix[index + 1:]
postfix.insert(index - 2, eval(operand1 + operator.replace("mod", "%") + operand2).__str__())
return postfix
# ##################################################### #
# # Test sets # #
# ##################################################### #
def run_tests():
exprs = ["3+4+20-8", "9*8+7", "3-18mod7", "100-30/6", "9*8+7*5", "120/(5+3)", "100+30/(34mod3)", "9*8+(7+6)*5",
"9*8+(7+6*(3+4*5))", "9.6*6+3", "9.5*8+37*5-(7+3*4+5)*4", "9.8*5+((3+1)*4+(2+3)*1.2)*3"]
for expr in exprs:
is_correct = (float(postfix_calc(infix_to_postfix(expr))[0]) == eval(expr.replace("mod", "%")))
print("Test case " + exprs.index(expr).__str__() + ": " + is_correct.__str__())
def run_single_test(expr):
print(">> " + expr + " = " + postfix_calc(infix_to_postfix("3-18mod7"))[0])
run_tests()
run_single_test("9.8*5+((3+1)*4+(2+3)*1.2)*3") |
139fd221c83592618faf1ce9934a0f592873ad06 | guoyu07/CLRS | /LeetCode/SameTree.py | 916 | 4.09375 | 4 | __author__ = 'Tong'
# Given two binary trees, write a function to check if they are equal or not.
#
# Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param p, a tree node
# @param q, a tree node
# @return a boolean
def isSameTree(self, p, q):
if not p and not q:
return True
elif (not p) ^ (not q):
return False
if p.val != q.val or (not p.left) ^ (not q.left) or (not p.right) ^ (not q.right):
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
a = TreeNode(1)
b = TreeNode(1)
a.left = TreeNode(2)
b.left = TreeNode(2)
print(Solution().isSameTree(a, b)) |
4c7045be009bd31fe16273a03e25c4962e000a51 | nixis-institute/practice | /python/bhawna/c.py | 54 | 3.703125 | 4 | st="hello"
l=[]
for i in st:
l.append(i)
print(l)
|
78de36c0caa58cda1da792522db0c88a253a50bd | nixis-institute/practice | /python/bhawna/bp2.py | 155 | 4.125 | 4 | def factorial(a):
c=1
for i in range(1,a+1):
c=c*i
return c
a=int(input("enter the value"))
f=factorial(a)
print("factorial is",f) |
895e4b795c074a0374f19847bab6f355a062f918 | nixis-institute/practice | /python/Rupes/week.py | 336 | 4.03125 | 4 | n=(int(input('Enter the value ')))
if (n==1):
print('Today is Monday')
elif (n==2):
print('Today is Tuseday')
elif (n==3):
print('Today is Wednesday')
elif (n==4):
print('Today is Thasday')
elif (n==5):
print('Today is Friday')
elif (n==6):
print('Today is Starday')
elif (n==7):
print('Today is Sunday')
|
8f6fff733e43ef494a2e18267762edd4dcdbf90f | nixis-institute/practice | /python/bhawna/loop.py | 177 | 3.984375 | 4 | n=int(input("enter the range"))
s=''
for i in range(1,n):
s=s+"*"
print(s)
"""for i in range(1,n):
for j in range(i):
print("*",end="")
print("\n")
""" |
fc74a256feab2521a434af367ca61b3fb6734789 | nixis-institute/practice | /python/bhawna/b.py | 175 | 4.1875 | 4 | a=int(input("enter the value"))
for i in range (1,a):
#print("even values",(a%2 is 0))
if i%2 is 0:
print("no is even",i)
else:
print("no is odd") |
aeab15f7f34cbad76d3a883e44b0883a1666e4d7 | nixis-institute/practice | /python/bhawna/week.py | 352 | 4.125 | 4 | number=int(input("enter the number"))
if number==1:
print("monday")
elif number==2:
print("tuesday")
elif number==3:
print("wednesday")
elif number==4:
print("thursday")
elif number==5:
print("friday")
elif number==6:
print("saturday")
elif number==7:
print("sunday")
else:
print("given input is wrong") |
27fd8430aeadc3d3b9ca14599580ecf14c5ff5fc | nixis-institute/practice | /python/Sunil.py | 591 | 3.890625 | 4 | A=input('Enter the product name ')
B=input('Enter the price of the product ')
C=input('Enter the quantity of the product ')
Total=B*C
if (C>=10):
dis=(Total)*0.05
print('you have got as moch discounte',dis)
elif (C>=15):
dis=(Total)*0.10
print('You have got discounte',dis)
elif (C>=20):
dis=(Total)*0.15
print('you have got discounte',dis)
elif (C>=25):
dis=(Total)*0.20
print('You have got discounte',dis)
elif (C>=30):
dis=(Total)*0.25
print('you have got discounte',dis)
netamout=Total-dis
print('This is your Total amount : ') |
88b9991c67a8ec4f86d27dfceb26092e68e133eb | nixis-institute/practice | /python/even.py | 126 | 4.1875 | 4 | value = int(input("Enter value "))
if(value%2==0):
print("This is even value ")
else:
print("this is odd value ") |
5b29b6b3fc720588197e6a6221137f43be6b845c | nixis-institute/practice | /python/bhawna/1.py | 180 | 4.0625 | 4 | a=input("enter the first value")
b=input("enter the second value")
if a>b:
print("a is greater")
elif(a==b):
print("both are equal")
else:
print("b is greater") |
6df18d079b147a461bda9aeea39718dbe682f6d4 | nixis-institute/practice | /python/insertdata.py | 472 | 3.625 | 4 | import sqlite3 as sql
import pandas as pd
con=sql.connect("new.db") # to open the database in which we have to insert the data
command="insert into stud values('Dhruv',10,99)" #stud is the name of the table
command1="insert into stud values('Raftaar',11,95)"
command2="insert into stud values('Muhfaad',10,99)"
command3="insert into stud values('Divine',10,99)"
con.execute(command)
con.execute(command1)
con.execute(command2)
con.execute(command3)
con.commit() |
f72fcc7790b2a4593cfbf4745994bf59957550b8 | nixis-institute/practice | /python/bhawna/bp.py | 471 | 4.0625 | 4 | def subtraction(a,b):
f=a-b
return f
def addition(a,b):
d=a+b
return d
def multiplication(a,b):
e=a*b
return e
a=int(input("enter the first value"))
b=int(input("enter the second value"))
c=int(input("enter the user choice"))
if c==1:
f=subtraction(a,b)
print("subtraction",f)
elif c==2:
d=addition(a,b)
print("addition",d)
elif c==3:
e=multiplication(a,b)
print("multiplication",e)
else:
print("value is not valid")
|
4e31abc9850d0272cec22aa50e7f52d0375bb342 | nixis-institute/practice | /python/hello.py | 173 | 3.546875 | 4 | v=['Hello world']
#for k in range(0, len(v)):
print(v.index(v,beg=0 end=len(v)))
print("\n")
#j=len(v)
#print(j)
#str.index(str, beg = 0 end = len(string)) |
df160cf2cc81fd5c83faf73cc8e80db114af75dd | nixis-institute/practice | /python/squre.py | 154 | 3.6875 | 4 | from math import *
value = int(input("Enter a value "))
sq = sqrt(value)
print (sq)
# round is global function
#truck is library function |
0afc6c78a477809a276a8de5d4f7bf26a1e46755 | nixis-institute/practice | /python/bhawna/power.py | 163 | 3.859375 | 4 | def power (a,b):
c=1
for i in range (b):
c=c*a
return c
value=int(input("value"))
p=int(input("power"))
z=power(value,p)
print("no is",z) |
768b7b2bb0dd863b28c6ff657a3819fc4ae6162a | akuks/Python3.6---Novice-to-Ninja | /Ch9/09-FileHandling-01.py | 634 | 4.21875 | 4 | import os
# Prompt User to Enter the FileName
fileName = str(input("Please Enter the file Name: "))
fileName = fileName.strip()
while not fileName:
print("Name of the File Cannot be left blank.")
print("Please Enter the valid Name of the File.")
fileName = str(input("Please Enter the file Name: "))
fileName = fileName.strip()
# Check if the file Entered by the User exists
if not os.path.exists(fileName):
print(fileName, " does not exists")
print("Exiting the Program")
exit(1)
print("File Name Entered by the User is : ", fileName)
fh = open(fileName, 'r')
for line in fh:
print(line)
|
848ff8ae6cb99f3f6b768df53ebd4d9fd9486cfe | akuks/Python3.6---Novice-to-Ninja | /Ch8/08-tuple-01.py | 204 | 4.125 | 4 | # Create Tuple
tup = (1, 2, 3, "Hello", "World")
print(tup)
# Looping in Tuple
for item in tup:
print (item)
# in operator
b = 4 in tup
print(b)
# Not in Operator
b = 4 not in tup
print (b)
|
28db87b07427c1847f54e6f159dfc92e4fe0a310 | Bin-ary-Li/MPCS51100AdvProg | /text_compressor/count_vocab.py | 349 | 3.75 | 4 | import sys
assert(len(sys.argv) == 2), "Please pass in the filename to count its unique words."
originalfile = sys.argv[1]
with open(originalfile, 'r') as file:
data = file.read().replace('\n', ' ')
og = data.split(" ")
og = [word.lower() for word in og if word != ""]
og_set = set(og)
print(f"{originalfile} has {len(og_set)} unique words.") |
14d3f48bd0f5a76dcaba33cb3064fe2ef013a3e5 | pbscrimmage/thinkPy | /ch12/letter_freq.py | 877 | 4 | 4 | """
letter_freq.py
Author: Patrick Rummage
[patrickbrummage@gmail.com]
Objective:
Create a function called most_frequent that takes a string
and returns a list of characters found, sorted by frequency.
"""
import sys
def most_frequent(s):
freqs = {}
t = []
for c in s: # Build dict and count letters
if c in freqs:
freqs[c] += 1
else:
freqs[c] = 1
for lttr in freqs: # Build list of (freq, letter) tuples
t.append((freqs[lttr], lttr))
t.sort(reverse=True) # Sort the letter-tuples by freqf
res = [] # Creata list of sorted letters
for freq, lttr in t:
res.append(lttr)
return res
def main():
infile = open(sys.argv[1])
text = ""
for line in infile:
text += line.strip()
frequent = most_frequent(text)
print ''.join(frequent)
main()
|
bbed894c316e17e8cdbde0ed2d0db28ddd6d2285 | pbscrimmage/thinkPy | /ch5/is_triangle.py | 1,108 | 4.46875 | 4 | '''
is_triangle.py
Author: Patrick Rummage
[patrickbrummage@gmail.com]
Objective:
1. Write a function is_triangl that takes three integers as
arguments, and prints either "yes" or "no" depending on
whether a triangle may be formed from the given lengths.
2. Write a function that prompts the user to input three
lengths, converts them to integers, and uses is_triangle
to test whether the given lengths can form a triangle.
'''
def test_lengths():
values = [ ['a', 0], ['b', 0], ['c', 0] ]
for v in values: # get input and validate
valid = False
while not valid:
v[1] = int(raw_input("Enter a value for %s: " % v[0]))
if v[1] < 1:
print "a, b, and c must be positive integers!"
else:
valid = True
is_triangle(values[0][1], values[1][1], values[2][1])
def is_triangle(a, b, c):
var_list = [a, b, c]
for v in var_list:
lcopy = var_list[:]
lcopy.remove(v)
if v > sum(lcopy):
print "No."
print "Yes."
test_lengths()
|
342994426eab183a25362208907f318ef11fc5f6 | pbscrimmage/thinkPy | /ch6/is_power.py | 398 | 4.03125 | 4 | '''
is_power.py
Author: Patrick Rummage
[patrickbrummage@gmail.com]
Objective:
Define a function, is_power, that takes parameters a and b
and returns True if a is a power of b. Returns False otherwise.
'''
def is_power(a, b):
if a == b:
return True
elif a < b:
return False
else:
return is_power(a/b, b)
print is_power(60, 8)
print is_power(8, 8)
print is_power(64, 8)
|
a3338b41d3399b462b32674111f28e465782f6f2 | abbye1093/AFS505 | /AFS505_U1/assignment3/ex16.py | 1,309 | 4.4375 | 4 | #reading and writing files
#close: closes the file, similar to file > save
#read: reads contents of files
#readline: reads just one readline
#truncate: empties the file
#write('stuff') : writes 'stuff' to file
#seek(0): moves the read/write location to the beginning of the files
from sys import argv
script, filename = argv
#getting filename from the argv entry when opening/running py file
print(f"We're goint to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
input("?") #want input from user while script is running
print("Opening the file...")
target = open(filename, 'w') #opening the file in write mode, instead of default read
print("Truncating the file. Goodbye!")
#truncating empties the file
target.truncate()
print("Now I'm going to ask you for three lines.")
#asks for user input for each line
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file.")
#will this work? nope,
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it.")
#close aka file > save
target.close() #run close with no parameter changes on target
|
92557bfd2d9342e17b2155d68e4aacecb2914b43 | KatherineSanchez98/stack | /Python_Stack/stack.py | 3,148 | 4.4375 | 4 | '''
----------------------------------
#Developed by |
@user: Katherine Sánchez |
#id: 201612408 |
#e-mail: sanchezkathy29@gmail.com |
----------------------------------
This example demonstrates how to build a stack,
we only need 2 classes:
1)Node: only has a constructor that assigns the value
to the attribute @data of the node and the link to the next
node.
2)Stack: our Stack class has 4 methods
2.1)push()
2.2)peek()
2.2)pop()
2.2)print_list().
Finally to put our stack to the
test, we instanciate it, we add values, delete the last one and print.
'''
class Node:
def __init__ (self, data): #constructor of class Node
self.data = data #assign the value sent as a parameter to our class atribute
self.next = None #initialize the pointer link to None (null)
class Stack:
def __init__(self): #constructor of class Stack
self.head = None # initialize our stack empty.
#Add method
def push(self, Current_Node):
if self.head is None: #verify if our stack is empty
self.head = Current_Node #if is empty assign the first node to our head (Current_Node)
else:
temp = self.head #assign our head to temp.
while temp.next is not None:#iterate through our list until we reach the end of it
temp = temp.next #assign the pointer link of the last
temp.next = Current_Node #element to our new element
#Peek method
def peek(self):
if self.head is None: #verify if our stack is empty
print("Empty list") #if is empty print(empty)
else:
temp = self.head #assign our head to temp.
while temp.next is not None:#iterate through our list until we reach the end of it
temp = temp.next #assign the pointer link of the last
print(temp.data, end=' ') #print our last element
print("\n")
#Pop method
def pop(self):
if self.head is None: #verify if our stack is empty
return
elif self.head.next is None: #if head next is null
self.head = None #assign null to head
else:
temp = self.head #assign our head to temp.
prev = self.head #assign our head to previous.
while temp.next is not None:#iterate through our list until we reach the end of it
prev = temp #assign temp to previous
temp = temp.next #assign the following temporary to temporary
prev.next = None #assign the following previous null
#Print method
def print_list(self):
if self.head is None: #verify if our stack is empty
print("Empty list") #if is empty print(empty)
else:
temp = self.head #assign our head to temp.
while temp.next is not None:#iterate through our list until we reach the end of it
print(temp.data, end=' ')#print our data
print('->', end=' ')
temp = temp.next #assign the following temporary to temporary
print(temp.data, end=' ') #print our data
print("\n")
newStack = Stack() #create a ner stack
newStack.push(Node("1")) #add element 1
newStack.push(Node("2")) #add element 2
newStack.push(Node("3")) #add element 3
newStack.push(Node("4")) #add element 4
newStack.print_list() #print list
newStack.peek() #peek method
newStack.pop() #pop method
newStack.print_list() #print list
|
72d72c40a3279d64be8b7677e71761aed1b7155f | ggggg/PythonAssignment- | /exchange.py | 452 | 4.1875 | 4 | # get currency
print('enter currency, USD or CAD:')
currency = input().upper()
# get the value
print('Enter value:')
value = float(input())
# usd
if (currency == 'USD'):
# make calculation and output result
print('The value in CAD is: $' + str(value * 1.27))
# cad
elif (currency == 'CAD'):
# make calculation and output result
print('The value in USD is: $' + str(value * 0.79))
# currency not found
else:
print('Currency not found.')
|
a9c9af8c162419f1bcb1e1aa49ce2fdf43ee5397 | hubugui/ds | /sort/insert/insert.py | 529 | 4.03125 | 4 |
#!/usr/bin/env python
import random
import sys
def insert_sort(array):
for i in range(1, len(array)):
j = i - 1
while j > -1 and array[j] > array[i]:
tmp = array[i]
array[i] = array[j]
array[j] = tmp
i = i - 1
j = j - 1
array = []
if len(sys.argv) > 1:
digits = sys.argv[1].split(",")
for digit in digits:
array.append(int(digit))
else:
length = 20
for i in range(length):
array.append(random.randint(0, length))
print "input\t{}".format(array)
insert_sort(array)
print "result\t{}".format(array) |
efea3fc1186254cd2a2b40171114de6af466a8cd | angelaannjaison/plab | /15.factorial using function.py | 312 | 4.21875 | 4 | def fact(n):
f=1
if n==0:print("The factorial of ",n,"is 1")
elif(n<0):print("factorial does not exit for negative numbers")
else:
for i in range(1,n+1):
f=f*i
print("The factorial of ",n,"is",f)
n=int(input("To find factorial:enter a number = "))
fact(n) |
754c02472453ab001c18bb13f5118aa0851ada80 | angelaannjaison/plab | /17.pyramid of numbers.py | 258 | 4.15625 | 4 | def pyramid(n):
for i in range(1,n+1):#num of rows
for j in range(1,i+1):#num of columns
print(i*j,end=" ")
print("\n")#line space
n=int(input("To construct number pyramid:Enter number of rows and columns: "))
pyramid(n) |
e500b5ef5f72359ba07c06ed10ec2b3e12dabfb6 | angelaannjaison/plab | /to find largest of three numbers.py | 297 | 4.1875 | 4 | print("To find the largest among three numbers")
A = int(input("Enter first number = "))
B = int(input("Enter second number = "))
C = int(input("Enter third number = "))
if A>B and A>C:
print(A," is greatest")
elif B>C:
print(B," is greatest")
else:
print(C,"is greatest")
|
8e3aeedca99b9abff8282876fbf5b655c1f10a76 | mtouhidchowdhury/CS1114-Intro-to-python | /Homework 3/hw3q4.py | 787 | 4.46875 | 4 | #homework 3 question 4
#getting the input of the sides
a = float(input("Length of first side: "))
b = float(input("Length of second side: "))
c = float(input("Length of third side: "))
if a == b and b == c and a ==c :# if all sides equal equalateral triangle
print("This is a equilateral triangle")
elif a == b or a == c or b == c:# if two sides equal isosceles triangle
print("this is a isoseles triangle")
elif (a == b or a == c or b == c) and (a**2 + b**2 == c**2 or a**2 + c**2 == b**2 or c**2 + b**2 == a**2):
print("this is an isosceles right triangle ")#if two sides equal and pythagorean formula fits its isosceles right triangle
else:#if none of the conditions apply its neither
print("neither equalateral nor isosceles right triangle")
|
e2836dded795cfd45e297f05d467e04c35901858 | mtouhidchowdhury/CS1114-Intro-to-python | /Homework 7/hw7q3.py | 1,710 | 4.1875 | 4 |
#importing module
import random
#generating a random number and assign to a variable
randomNumber = random.randint(1,100)
#set number of guesses to 0 and how many remain to 5
numberGuesses= 0
guessRemain = 5
#first guess
userGuess = int(input("please enter a number between 1 and 100: "))
# minus from guess remain and adding to number of guesses
guessRemain -= 1
numberGuesses += 1
# making bounds for the ranges
lowerBound = 0
upperBound = 101
#if first guess correct then goes to if otherwise goes to else
if userGuess == randomNumber:
print("Your Correct!")
#loop till guesses remaining is 0 and user's guess is the number
else:
while guessRemain != 0 and userGuess != randomNumber :
if userGuess < randomNumber:
lowerBound = userGuess
userGuessLine = "Guess again between "+ str(lowerBound + 1) + " and " + str(upperBound - 1) + ". You have " + str(guessRemain) + " guesses remaining: "
userGuess = int(input (userGuessLine))
guessRemain -= 1
numberGuesses += 1
elif userGuess > randomNumber:
upperBound = userGuess
userGuessLine = "Guess again between " + str(lowerBound + 1) + " and "+ str(upperBound - 1) + ". You have " + str(guessRemain) + " guesses remaining: "
userGuess = int(input (userGuessLine))
guessRemain -= 1
numberGuesses += 1
#output if won tells how many guesses took if lost then tells user that he/she lost
if userGuess == randomNumber:
line= "Congrats! you guessed the answer in " + str(numberGuesses) + " guesses!"
print(line)
else:
print ("You ran out of guesses")
|
3f73f9b5c399f697fca37a7d62f21fcb01aef3d7 | mtouhidchowdhury/CS1114-Intro-to-python | /Homework 11/hw11.py | 6,436 | 3.578125 | 4 | '''
M. Touhid Chowdhury
CS 1114
mtc405
N14108583
Note: Used updated windows file
First function cleans the data and makes new file with just city, date, high temp, low temp, and precipitation
Second Function converts farenheit to celsius
third function converts inch to centimeter
fourth function uses the last two function to convert the cleaned data into metric units
the last function takes the metric file and a year and prints the average of the highests and the lowests
'''
# Part A
def clean_data(complete_weather_filename, cleaned_weather_filename):
weather = open(complete_weather_filename, "r")
cleaned = open(cleaned_weather_filename, "w")
headers_line = weather.readline()#remove header line
print("City", "Date","High Temp", "Low Temp", "precipitation", sep = ",",file = cleaned) #new header
#loop through file and print into new file only desired information
#convert any alpha into 0
for curr_line in weather:
curr_line = curr_line.strip()
curr_list = curr_line.split(',')
city = curr_list[0]
date = curr_list[1]
highTemp = curr_list[2]
lowTemp = curr_list[3]
precip = curr_list[8]
if highTemp.isalpha():
highTemp = 0
if lowTemp.isalpha():
lowTemp = 0
if precip.isalpha():
precip = 0
print(city, date, highTemp, lowTemp, precip, sep = ",", file = cleaned)
#close files after completing
cleaned.close()
weather.close()
print('done')
# Part B
def f_to_c(f_temperature):
#convert farenheit to celsius
celsius = (float(f_temperature)-32)*(5/9)
return celsius
def in_to_cm(inches):
#convert inches to centimeter
centimeter = float(inches) * 2.54
return centimeter
def convert_data_to_metric(imperial_weather_filename, metric_weather_filename):
#convert all data to metric
imperial = open(imperial_weather_filename, "r")
metric = open(metric_weather_filename, "w")
headline = imperial.readline()
print("city", "date","highTemp", "lowTemp", "precipitation", sep = ",", file = metric)
for curr_line in imperial:
curr_line = curr_line.strip()
curr_list = curr_line.split(',')
city = curr_list[0]
date = curr_list[1]
highTemp = f_to_c(curr_list[2])
lowTemp = f_to_c(curr_list[3])
precip = in_to_cm(curr_list[4])
print(city, date, highTemp, lowTemp, precip, sep = ",", file = metric)
metric.close()
imperial.close()
print("done")
#Part C
def print_average_temps_per_month(city, weather_filename, unit_type):
# prints average highs and lows in each month for the given city
file = open(weather_filename, 'r')
headline = file.readline()
counterMonths= [0,0,0,0,0,0,0,0,0,0,0,0] #keep track of how many times each month occur
valuesForHigh = [0,0,0,0,0,0,0,0,0,0,0,0]# keeps track of the highs of every month
valuesForLow =[0,0,0,0,0,0,0,0,0,0,0,0] #keep track of the lows of every month
countMetric = 0
countImperial = 0
print("Average temperatures for ", city, ":")
for curr_line in file:
curr_line.strip()
curr_list = curr_line.split(',')
cityFile = curr_list[0]
date = curr_list[1]
highTemp = curr_list[2]
lowTemp = curr_list[3]
monthDayYearList = date.split('/')
if cityFile == city:
for number in range(0,13):
if monthDayYearList[0] == str(number):
valuesForHigh [number-1] += float(highTemp)
valuesForLow[number-1] += float(lowTemp)
counterMonths[number-1] += 1
#list of months to print
month =["January", "February", "March", "April","May", "June", "July","August","September", "October", "November", "December"]
if unit_type == "imperial":
for appearance in counterMonths:
print(month[countMetric],":",round(valuesForHigh[countMetric]/appearance,3),"F High",round(valuesForLow[countMetric]/appearance,3), "F low")
countMetric +=1
if unit_type == "metric":
for appearance in counterMonths:
print(month[countImperial],":",round(valuesForHigh[countImperial]/appearance,3),"C High",round(valuesForLow[countImperial]/appearance,3), "C low")
countImperial +=1
file.close()
#Part D
def highest_and_Lowest(metric_weather_file, year):
# Write a function that tells you which year had how much average high tempt and low tempt for the available data
# assume that the unit is metric
# assume that all the data has the complete year for the years available (2010-2015)
# assume user will put a year thats in the file
# Use the metric file that you created in previous function
file = open(metric_weather_file, "r")
header = file.readline()
highest = 0
lowest = 0
occur = 0
yearsAvailable = [2010,2011,2012,2013,2014,2015]
for curr_line in file:
curr_line = curr_line.strip()
curr_list = curr_line.split(',')
cityFile = curr_list[0]
date = curr_list[1]
highTemp = curr_list[2]
lowTemp = curr_list[3]
monthDayYearList = date.split('/')
if str(monthDayYearList[2]) == str(year):
lowest += float(lowTemp)
highest += float(highTemp)
occur += 1
if occur > 0:
print("The average of the lowest temperatures of the year",year,"is", round(lowest/occur, 2),"C", "\n"\
"and average of the highest temperatures is", round(highest/ occur, 2),"C")
else:
print("THE YEAR IS NOT AVAILABLE")
def main():
print ("Running Part A")
clean_data("weatherwindows.csv", "weather in imperial.csv")
print ("Running Part B")
convert_data_to_metric("weather in imperial.csv", "weather in metric.csv")
print ("Running Part C")
print_average_temps_per_month("San Francisco", "weather in imperial.csv", "imperial")
print_average_temps_per_month("New York", "weather in metric.csv", "metric")
print_average_temps_per_month("San Jose", "weather in imperial.csv", "imperial")
print ("Running Part D")
highest_and_Lowest("weather in metric.csv", 2011)
main()
|
3b3f9e1540f090670d043bd72837d3f538ec7fd4 | mtouhidchowdhury/CS1114-Intro-to-python | /Homework 3/hw3q2.py | 1,406 | 4.0625 | 4 | #hw 3 question 2
#getting user input
firstItem = float(input(" Enter price of first item: "))
secondItem = float(input ("Enter price of second item: "))
total = firstItem + secondItem#total before discount
#comparing prices to give 50% discount
if firstItem > secondItem:
secondItem1 = secondItem * 0.5
firstItem1 = firstItem
elif secondItem > firstItem:
firstItem1 = firstItem * 0.5
secondItem1 = secondItem
elif secondItem == firstItem:
secondItem1 = secondItem * 0.5
firstItem1 = firstItem
#first discount total
totalWithFirstDiscount = firstItem1 + secondItem1
#asking user if they are members
membership = input("Does customer have a club card? Enter Y/N: ")
#if member apply 10% discount
if membership == 'Y' or 'y':
secondDiscount = totalWithFirstDiscount * 0.10
totalWithSecondDiscount = totalWithFirstDiscount - secondDiscount
elif membership == 'N' or 'n':
totalWithSecondDiscount = totalWithFirstDiscount
#asking for tax rate
taxrate = float(input("Enter tax rate, e.g. 5.5 for 5.5% tax: "))
#calculating tax
tax = totalWithSecondDiscount * (taxrate/100)
#calculating total with both discounts and tax
totalPrice = totalWithSecondDiscount + tax
#printing results
print("Base price = ",round(total,2))
print("Price after discounts = ",round(totalWithSecondDiscount,2))
print("Total price: ", round(totalPrice,2))
|
e3be918087f3b8dc2da3444990a4d8fd17a14790 | tianzhihen/cv-bringupy | /PIL-cases/converts.py | 349 | 3.515625 | 4 | from PIL import Image
def convert_to_gray_image(image):
return image.convert("L")
if __name__ == '__main__':
image_input_path = "/media/cv-bringupy/test.jpg"
image_output_path = "/media/cv-bringupy/test_gray.png"
img = Image.open(image_input_path)
img_gray = convert_to_gray_image(img)
img_gray.save(image_output_path)
|
aea94ecd2fa9a95ea410453e7c5280b91651864c | mishalzaman/python-tile-engine | /lib/Map.py | 1,891 | 3.5 | 4 | import pygame
import json
import math
class Map:
def __init__(self, filename, display):
self.filename = filename # map filename
self.display = display # pygame.display
self.width = 10 # width of tile
self.height = 10 # height of tile
self.thickness = 0 # thickness (0 = fill)
# Tiles
self.groundTile = pygame.Color(255, 255, 255)
self.wallTile = pygame.Color(0, 0, 0)
# Set map data from json file
with open('map.json') as json_data:
self.mapData = json.load(json_data)
def draw(self):
row = 0
for j in self.mapData['map']:
column = 0
for i in j:
x = column*self.width
y = row*self.height
colour = self.groundTile if i == 0 else self.wallTile
pygame.draw.rect(self.display, colour, (x,y,self.width,self.height), self.thickness)
column += 1
row += 1
# x: integer, x position
# y: integer, y position
def getTile(self,x,y):
row = math.floor(y/10)
column = math.floor(x/10)
return self.mapData['map'][row][column]
# position: tuple, is an x1,y1,x2,y2 value
def isCollision(self,position):
x1 = position[0]
y1 = position[1]
x2 = position[2]
y2 = position[3]
# map borders: right / left / bottom / top
if x1 > self.width*self.mapData['columns'] or x1 < 0 or y1 > self.height*self.mapData['rows'] or y1 < 0:
return True
# if x2 > self.width*self.mapData['columns'] or x2 < 0 or y2 > self.height*self.mapData['rows'] or y2 < 0:
# return True
print('-----')
print('x1: ',x1, 'y1: ',y1)
print('x2: ',x2, 'y2: ',y2)
# map tile
if self.getTile(x1,y1) == 1:
return True
if self.getTile(x2,y2) == 1:
return True
return False
|
1dab6630272ecc34eaa6fd0c6b020f4d386010f8 | cjam3/AutomateTheBoringStuffPractice | /Chapter 20/textFieldToPython.py | 740 | 3.671875 | 4 | #! python3
# textFieldToPython.py - Uses pyautogui to select text in notepad and pyperclip to copy it to a string
import pyautogui, pyperclip
def main():
print(selectAllFromNotepadAndCopy())
def selectAllFromNotepadAndCopy():
# Copies all text in a notepad window to a string and adds that to a list of strings
# Does this for each notepad window currently open
# Returns the list of strings
notepadWindows = pyautogui.getWindowsWithTitle('Notepad')
strings = []
for notepadWindow in notepadWindows:
notepadWindow.activate()
pyautogui.hotkey('ctrl', 'a')
pyautogui.hotkey('ctrl', 'c')
strings.append(pyperclip.paste())
return strings
if __name__ == '__main__':
main() |
dc741bd8af0b3adee9ef05be7cdd494f15db9707 | cjam3/AutomateTheBoringStuffPractice | /Chapter 6/TablePrinter.py | 879 | 3.65625 | 4 | import copy
def main():
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
printTable(tableData)
def printTable(table):
colWidths = [0] * len(table)
for i in range(len(table)):
longest = 0
for j in range(len(table[i])):
if len(table[i][j]) > longest:
longest = len(table[i][j])
colWidths[i] = longest
padList = [""] * len(table[0])
for i in range(len(table)):
for j in range(len(table[i])):
table[i][j] = table[i][j].rjust(colWidths[i])
if len(padList[j]) == 0:
padList[j] = table[i][j]
else:
padList[j] = padList[j] + " " + table[i][j]
print('\n'.join(padList))
if __name__ == '__main__':
main()
|
eabcae3b5fc67a8dda9e3a2dfcf931cf5067ffb4 | cjam3/AutomateTheBoringStuffPractice | /Chapter 4/CommaCode.py | 454 | 3.515625 | 4 | def commaList(spam):
commaListStr = ''
if len(spam) == 0:
return commaListStr
for index, item in enumerate(spam):
if index == len(spam) - 1:
commaListStr = commaListStr + 'and ' + str(item)
else:
commaListStr = commaListStr + str(item) + ', '
return commaListStr
def main():
spam = ['apples', 'bananas', 4, 'cats']
print(commaList(spam))
if __name__ == '__main__':
main()
|
c49d289d5294f3eae75646124e40f9ab1b0cd734 | cjam3/AutomateTheBoringStuffPractice | /Chapter 12/ImageSiteDownloader.py | 1,192 | 3.53125 | 4 | #! python3
# ImageSiteDownloader.py - Downloads the preview images from imgur for a user given search term
import os, bs4, requests
def main():
# Get search term
searchTerm = input('Imgur Search: ')
searchTermForURL = '+'.join(searchTerm.split())
URL = 'https://imgur.com/search?q=' + searchTermForURL
# Create folder
os.makedirs(searchTerm, exist_ok=True)
# Download the page
res = requests.get(URL)
res.raise_for_status()
# Parse the html
soup = bs4.BeautifulSoup(res.text, 'html.parser')
elems = soup.select('img[alt=""]')
# Download each image
for elem in elems:
imageURL = 'https:' + elem.get('src')
print('Downloading image %s' % (imageURL) )
res = requests.get(imageURL)
try:
res.raise_for_status()
except Exception as exc:
print('Unable to download %s. Received error %s.' % (imageURL, exc))
continue
# Write image to memory
imageFile = open(os.path.join(searchTerm, os.path.basename(imageURL)), 'wb')
for chunk in res.iter_content(100000):
imageFile.write(chunk)
if __name__ == '__main__':
main() |
9b5a3195476c5d4c1689f52c7ef76a7a25e36072 | AbhishekMallick/Blackjack | /CardDeck.py | 1,435 | 4.09375 | 4 | '''CardDeck class to represent a deck and pull a card out at random'''
import random
class CardDeck:
nameMap = {
1:'Ace',
2:'Two',
3: 'Three',
4: 'Four',
5: 'Five',
6: 'Six',
7: 'Seven',
8: 'Eight',
9: 'Nine',
10: 'Ten',
11: 'Jack',
12: 'Queen',
13: 'King'
}
def __init__(self):
self.__drawnCards = set() # hold the cards that have been drawn
def __getSuit(self, num):
# change this to switch case later
if (num == 0):
return 'Spades'
elif (num == 1):
return 'Clubs'
elif (num == 2):
return 'Hearts'
elif (num == 3):
return 'Diamonds'
else:
return f'suit is {num}, which is invalid'
def getACard(self):
found = False
while not found:
# choose of suit
suit = random.randint(0, 3)
# choose a card
card = random.randint(1, 13)
if (suit, card) not in self.__drawnCards:
found = True
self.__drawnCards.add((suit, card))
return (suit, card)
def getName(self, suit, card):
return f'{self.nameMap[card]} of {self.__getSuit(suit)}'
|
64f014c7262d7ca044cff2df2292b0b02bb45bd1 | Nishant-15/Python_Projects | /Leap_finder_gui.py | 542 | 3.640625 | 4 | from tkinter import *
from tkinter.messagebox import *
root=Tk()
root.geometry("500x500")
root.title("Leap or Not By Nishant Patil.")
root.iconbitmap("calci.ico")
def Leap():
year=int(ent.get())
if year%4==0:
showinfo("Result","Leap Year.")
else:
showinfo("Result","Not a Leap Year.")
f=("Times new roman",20,"bold")
labl=Label(root,text="Enter Year",font=f)
labl.pack(pady=10)
ent=Entry(root,bd=4,font=f)
ent.pack(pady=10)
btn=Button(root,text="Leap or Not",bd=4,font=f,command=Leap)
btn.pack()
root.mainloop() |
a12107517ff64eb1332b2dcfcbe955419bc5d935 | kelvin5hart/calculator | /main.py | 1,302 | 4.15625 | 4 | import art
print(art.logo)
#Calculator Functions
#Addition
def add (n1, n2):
return n1 + n2
#Subtraction
def substract (n1, n2):
return n1 - n2
#Multiplication
def multiply (n1, n2):
return n1 * n2
#Division
def divide(n1, n2):
return n1 / n2
opperators = {
"+": add,
"-":substract,
"*": multiply,
"/": divide
}
def calculator():
num1 = float(input("What's the first number? \n"))
nextCalculation = True
for i in opperators:
print (i)
while nextCalculation:
operator = input("Pick an operation from the line above: ")
if operator not in opperators:
nextCalculation = False
print("Your entry was invalid")
calculator()
num2 = float(input("What's the next number? \n"))
operation = opperators[operator]
result = operation(num1, num2)
print(f"{num1} {operator} {num2} = {result}")
continueCalculation = input(f"Type 'y' to continue calculating with {result}, or type 'n' to start a new calculation or 'e' to exit. \n").lower()
if continueCalculation == "y":
num1 = result
elif continueCalculation == "n":
nextCalculation = False
calculator()
elif continueCalculation == "e":
nextCalculation = False
else:
print("Invalid Entry")
nextCalculation = False
calculator() |
07a8230657be774930ebc70f39508a9d6e38ebc9 | DaniloDalessandro/PROGRAMAS-EM-PYHTON | /PYTHON BRASIL/LISTA 02/022.py | 202 | 4 | 4 | # POR: DANILO COSTA
# UNIVERSIDADE ESTADUAL DO MARANHÃO
# GRADUANDO EM ENGENHARIA DE COMPUTAÇÃO
n = int(input('DIGITE UM NUMERO: '))
if n % 2 == 0:
print('NUMERO PAR')
else:
print('NUMERO IMPAR') |
d4d899baec5ea0a43009d5ff5fe2adb004459b5b | DaniloDalessandro/PROGRAMAS-EM-PYHTON | /PYTHON BRASIL/LISTA 03/013.py | 216 | 3.8125 | 4 | # POR: DANILO COSTA
# UNIVERSIDADE ESTADUAL DO MARANHÃO
# GRADUANDO EM ENGENHARIA DE COMPUTAÇÃO
n1 = int(input('DIGITE O PRIMEIRO NUMERO: '))
n2 = int(input('DIGITE O SEGUNDO NUMERO: '))
resul = n1 ** n2
print(resul) |
92509f5f8bc79218173660292679d32a6eebe285 | DaniloDalessandro/PROGRAMAS-EM-PYHTON | /PYTHON BRASIL/LISTA 02/013.py | 397 | 4.03125 | 4 | # POR: DANILO COSTA
# UNIVERSIDADE ESTADUAL DO MARANHÃO
# GRADUANDO EM ENGENHARIA DE COMPUTAÇÃO
n = int(input('DIGITE UM NUMERO: '))
if n == 1:
print('DOMINGO')
elif n == 2:
print('SEGUNDA')
elif n == 3:
print('TERÇA')
elif n == 4:
print('QUARTA')
elif n == 5:
print('QUINTA')
elif n == 6:
print('SEXTA')
elif n == 7:
print('SABADO')
else:
print('NUMERO INVALIDO')
|
9ec3eada671c71abb68cc88a8c9b887c28613532 | DaniloDalessandro/PROGRAMAS-EM-PYHTON | /PYTHON BRASIL/LISTA 03/010.py | 316 | 4.03125 | 4 | # POR: DANILO COSTA
# UNIVERSIDADE ESTADUAL DO MARANHÃO
# GRADUANDO EM ENGENHARIA DE COMPUTAÇÃO
n1 = int(input('DIGITE O PRIMEIRO NUMERO: '))
n2 = int(input('DIGITE O SEGUNDO NUMERO: '))
num = []
while n1 < n2 - 1:
n1 = n1 + 1
num.append(n1)
while n1 > n2 + 1:
n1 = n1 - 1
num.append(n1)
print(num) |
0bf6e894c304cc1e39907e4ed762ce597a2047a5 | DaniloDalessandro/PROGRAMAS-EM-PYHTON | /PYTHON BRASIL/LISTA 01/005.py | 179 | 3.890625 | 4 | # POR: DANILO COSTA
# UNIVERSIDADE ESTADUAL DO MARANHÃO
# GRADUANDO EM ENGENHARIA DE COMPUTAÇÃO
n = float(input('DIGITE UM NUMERO: '))
n = n * 100
print('{} CENTIMENTOS'.format(n))
|
22f5a142bc8254a59e276696c411fcf65a2358ab | DaniloDalessandro/PROGRAMAS-EM-PYHTON | /PYTHON BRASIL/LISTA 02/010.py | 314 | 4.03125 | 4 | # POR: DANILO COSTA
# UNIVERSIDADE ESTADUAL DO MARANHÃO
# GRADUANDO EM ENGENHARIA DE COMPUTAÇÃO
turno = input('QUAL TURNO VC ESTUDA: ')
if turno == 'm':
print('ESTUDA PELA MANHÃ!')
elif turno == 't':
print('ESTUDA PELA TARDE!')
elif turno == 'n':
print('ESTUDA PELA NOITE!')
else:
print('ERRO!')
|
0f4e60352e860d45e1d8c32903de20d231900fab | DaniloDalessandro/PROGRAMAS-EM-PYHTON | /PYTHON BRASIL/LISTA 01/014.py | 251 | 3.828125 | 4 | # POR: DANILO COSTA
# UNIVERSIDADE ESTADUAL DO MARANHÃO
# GRADUANDO EM ENGENHARIA DE COMPUTAÇÃO
peso = int(input('QUANTOS DE PEIXE? '))
if (peso <= 50):
print('SEM MULTA!')
elif(peso > 50):
m = (peso - 50)*4
print('MULTA DE {}'.format(m))
|
bf67d4490d69d830015b179e1063ae06d5a34cdf | tteeoo/ctlz | /ctlz/text.py | 1,754 | 3.875 | 4 | from ctlz import exceptions
def color(text, fg=None, bg=None):
"""Function to easily color printed text
fg and bg kwargs can be set to any standard 4 bit terminal color, prefix with bright (as in 'bright_red') for the bright variant"""
if fg == None and bg == None:
return text
elif fg == None:
return "\033[{}m".format(__get_code(bg, mode="bg")) + text + "\033[0m"
elif bg == None:
return "\033[{}m".format(__get_code(fg)) + text + "\033[0m"
else:
return "\033[{};{}m".format(__get_code(fg), __get_code(bg, mode="bg")) + text + "\033[0m"
def underline(text):
"""Function to easily underline printed text"""
return "\033[4m" + text + "\033[24m"
def blink(text):
"""Function to easily make printed text blink"""
return "\033[5m" + text + "\033[25m"
def __get_code(color, mode="fg"):
if color == "black":
code = 30
elif color == "red":
code = 31
elif color == "green":
code = 32
elif color == "yellow":
code = 33
elif color == "blue":
code = 34
elif color == "magenta":
code = 35
elif color == "cyan":
code = 36
elif color == "white":
code = 37
elif color == "bright_black":
code = 90
elif color == "bright_red":
code = 91
elif color == "bright_green":
code = 92
elif color == "bright_yellow":
code = 93
elif color == "bright_blue":
code = 94
elif color == "bright_magenta":
code = 95
elif color == "bright_cyan":
code = 96
elif color == "bright_white":
code = 97
else:
raise exceptions.InvalidColor("No color " + color)
if mode == "bg": code += 10
return str(code) |
b2662a69eedef7be937a9cf18e0413d6a75161b8 | kandarpck/networksecurity2018 | /pytest/pytest_simplewebclient.py | 760 | 3.515625 | 4 | import requests
import argparse
HOST_NAME = 'http://127.0.0.1'
PORT_NUMBER = "9000"
def get_file(path, port):
file = requests.get(HOST_NAME + ":" + port + "/" + path)
print(file.text)
return file
def save_file(file):
with open('web_response_1.txt', 'w') as f:
f.write(file.text)
def get_args():
parser = argparse.ArgumentParser(description='Simple HTTP Server')
parser.add_argument('file', help='File path', nargs='?')
parser.add_argument('port', default=PORT_NUMBER,
help='Port',
nargs='?')
args = parser.parse_args()
return args
if __name__ == '__main__':
arguments = get_args()
file = get_file(arguments.file, arguments.port)
save_file(file)
|
391beb262cd335da36c273513a80b7287d11d6c1 | yuribyk/school-bodmas-rule-on-string-input | /bodmas_main_program.py | 1,023 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 13 23:36:24 2019
@author: yuribyk
"""
#a="+3dcb(-10+5a)"
#a="-3(-10+5a)dcb"
#a= "-(-10+5a)(-2)"
#a= "a-b(c+d)-(a-b)cd-a"
#a= "(-1)(a+b)(a-b)(a+b)(a-b)(-1)"
#a= "-(a+b)(a-b)"
a= "(a-b)(a-b)(a-b)"
def simplify_b(a):
b=""
for i in a:
if i=="(" or i==")":
b+="_"
else:
b+=i
termz= b.split("_")
terms= []
for i in termz:
if i!= "":
terms.append(i)
n= len(terms)
for i in range (n):
if terms[i]=="-":
terms[i]="-1"
#print(terms)
import vector_plus_minus_gamma
import vector_multiply
for i in range (n):
terms[i] = vector_plus_minus_gamma.simplify(terms[i])
#print(terms)
if n==1:
return terms
else:
k= terms[0]
for i in range (1,n,1):
k= vector_multiply.multiply_simplify(k, terms[i])
return k
print(simplify_b(a))
|
98d0f99178b2752857897263a71cdcc2a866fbab | patrickrop-cloud/password_locker-App | /run.py | 4,489 | 4.4375 | 4 | #!/usr/bin/env python3.8
import random
# import string
from user import User
from credentials import Logins #importing credential class.
#create a user account
def create_acc(username,password):
'''
This function creates a new user account.
'''
new_acc = User(username,password)
return new_acc
#save new account
def save_accs(acc):
'''
This is a method to save a newly created account.
'''
acc.save_acc()
#function to verify user account
def verify_acc(username,password):
'''
this is a function to verify an account.
'''
check_acc = Logins.check_acc(username,password)
return check_acc
#display account
def display_acc():
'''
This method displays user accounts.
'''
return User.display_acc()
def main():
print("Hello, welcome to your password locker. Enter your name")
username = input()
print(f"Hello {username}. What would you like to do?")
print('\n')
while True:
print("Use the short codes below: \n ca - create new acc, del - delete, da - display acc, lg - login, exit - exit password locker")
short_code = input().lower().strip()
if short_code == 'ca':
print("Create a new account")
username = input()
print("Create Password")
password = input()
print('Confirm password')
confirm_password = input()
while confirm_password !=password:
print("Wrong password")
print("Enter password")
password = input()
print("confirm password")
confirm_password = input()
# print(f"Succesful! A new account has been created for: {username} with password {password}")
# print('\n')
else:
print(f"Succesful! {username} account created succesfully!")
print('\n')
save_accs(create_acc(username,password))
print('\n')
print(f"New Acc {username} with password {password} created")
print('\n')
print("Welcome to your account. Proceed to login")
print("username")
entered_username = input()
print("Password")
entered_password = input()
while entered_username != username or entered_password != password:
print("Invalid username or password")
print("username")
username = input()
print("password")
password = input()
else:
print("\n")
print("successfull login")
elif short_code =='lg':
print("Welcome")
print("Username")
default_username = input()
print("Password")
default_password = input()
print("\n")
while default_username != 'newuser' or default_password != '12345':
print("Wrong username or password?")
print("Use username newuser and password 12345 to login")
print("\n")
print("Enter Username")
default_username =input()
print("Enter password")
default_password = input()
else:
print('successful login')
elif short_code == 'da':
if display_acc():
print("Here is a list of all your accs created and passwords")
print('\n')
for acc in save_accs():
print(f"{acc.username} {acc.password}")
print('\n')
else:
print('\n')
print("Can't find account")
print('\n')
elif short_code == 'del':
print('Enter the username to delete')
username = input()
User.delete_acc(username)
print(f"Your acc {username} has been deleted successfully")
elif short_code == 'exit':
print("***Thank you for choosing password locker...***")
else:print("I really din't pick that.Please use the short codes")
if __name__=='__main__':
main()
|
c92b9bf7088702e015284eeebc4debdb14b22e00 | CrawfishPress/psp_scan | /src/masks.py | 3,966 | 3.625 | 4 | """
Mask computations
"""
from utils import Rect
def find_intersection_rect(rect_one, rect_two):
""" Given two rectangles, find the common section. """
new_tl_x = max(rect_one.tl_x, rect_two.tl_x)
new_tl_y = max(rect_one.tl_y, rect_two.tl_y)
new_br_x = min(rect_one.br_x, rect_two.br_x)
new_br_y = min(rect_one.br_y, rect_two.br_y)
new_rect = Rect(new_tl_x, new_tl_y, new_br_x, new_br_y)
return new_rect
def apply_mask_to_layer(dest, source, alpha):
"""
:param dest: a set of RGB triples (50, 100, 150), the lower bitmap layer that shows through the transparency
:param source: a set of RGB triples (123, 100, 50), to have the transparency-mask applied to
:param alpha: a single hex value (FF) that represents the transparency:
- 0 is fully transparent, the dest layer shows through completely
- FF is fully opaque, the source layer is all that's visible
- other values are computed
:return: a set of RGB triples (50, 60, 70)
https://en.wikipedia.org/wiki/Alpha_compositing
out_rgb = src_rgb * alpha + dst_rgb (1 - alpha)
"""
# Handle the easy cases first:
if alpha == 0:
return dest
if alpha == 255:
return source
alpha_pct = alpha / 255.0
new_rgb = (int(source[0] * alpha_pct + dest[0] * (1 - alpha_pct)),
int(source[1] * alpha_pct + dest[1] * (1 - alpha_pct)),
int(source[2] * alpha_pct + dest[2] * (1 - alpha_pct)))
return new_rgb
def apply_rect_mask_to_layer(source, alpha):
""" Same as apply_mask_to_layer(), but for single pixels. Also always uses black background,
since it's for greyscale masks.
"""
dest = 0
# Handle the easy cases first:
if alpha == 0:
return dest
if alpha == 255:
return source
alpha_pct = alpha / 255.0
new_rgb = int(source * alpha_pct + dest * (1 - alpha_pct))
return new_rgb
def compute_sub_mask(outer_mask, outer_rect, inner_rect):
""" Given a mask and sub-mask coordinates, extracts the sub-mask. No doubt numpy could do this in one line. :)
outer_rect is the coords for the mask, and inner_rect is the sub-coordinates - contained entirely
inside the outer_rect, nothing outside.
"""
tl_x = inner_rect.tl_x - outer_rect.tl_x
tl_y = inner_rect.tl_y - outer_rect.tl_y
outer_width = outer_rect.width
outer_height = outer_rect.height
width = inner_rect.width
height = inner_rect.height
# If they're the same size, we're done. This is too easy...
if width == outer_width and height == outer_height:
return outer_mask
inner_mask = []
for y in range(height):
for x in range(width):
new_x = x + tl_x
new_y = y + tl_y
pixel_loc = new_x + new_y * outer_width
new_pixel = outer_mask[pixel_loc]
inner_mask.append(new_pixel)
return inner_mask
def expand_rect_mask_debug(gia, bits, abs_rect):
""" Take a rectangle-mask that is smaller than full-size (probably),
and expand it to size of the entire image. Purely for debugging output.
:param gia: general-image attributes - originally a global, contains height/width, etc
:param bits: greyscale bitmap (0, 0, 0, 0, 250, 255, ...)
:param abs_rect: outer-border coordinates of rectangle-mask
:return: greyscale bitmap, with dimensions matching the entire image (0, 0, 0, 0, 250, 255, ...)
"""
pic_width = gia['width']
pic_height = gia['height']
black_bitmap = [0 for _ in range(pic_width * pic_height)]
tl_x = abs_rect.tl_x
tl_y = abs_rect.tl_y
rect_width = abs_rect.width
rect_height = abs_rect.height
for y in range(rect_height):
for x in range(rect_width):
pixel_loc = x + y * rect_width
new_pixel_loc = x + tl_x + (y + tl_y) * pic_width
black_bitmap[new_pixel_loc] = bits[pixel_loc]
return black_bitmap
|
eb6b5ad51d840a9252bcd194b1789ae9e30a8718 | Mutan0105/func2 | /classtest.py | 233 | 3.546875 | 4 | #!/usr/bin/env python
# encoding: utf-8
class RoundFloatManual(object):
def __init__(self,val):
self.value = round (val, 2)
def __str__(self):
return '%.2f' % self.value
a = RoundFloatManual(6.33333)
print a |
18fec51287c02111d516da9512927551d91617d4 | Mutan0105/func2 | /easymath_with_mul&div.py | 1,293 | 3.75 | 4 | #!/usr/bin/env python
# encoding: utf-8
from operator import add, sub, mul, truediv
from random import randint, choice
ops = {'+':add, '-':sub, '*':mul, '/':truediv}
maxtries = 2
def doprob():
op = choice('+-*/')
nums = [randint(1,10) for i in range(2)]
nums.sort(reverse=True)
if op == '/':
nums = [float(x) for x in nums]#转换为float保证结果为浮点数
ans = round(ops[op](*nums),2) #除法运算保留2位小数
else:
ans = ops[op](*nums)
pr = '%d%s%d = ' % (nums[0], op ,nums[1])
opps = 0
while True:
try:
if float(raw_input(pr)) == float(ans): #使用float而不是int是为了保证除法运算能够输入小数,保证结果正确
print 'correct'
break
if opps == maxtries:
print 'answer\n%s%d' % (pr,ans)
else:
print 'wrong'
opps += 1
except (KeyboardInterrupt, EOFError, ValueError):
print 'try again'
def main():
while True:
doprob()
try:
opt = raw_input('Again?[Y]').lower()
if opt and opt[0] == 'n':
break
except (KeyboardInterrupt, EOFError):
break
if __name__ == '__main__':
main()
|
28d76b2fe13a96e9e766eb186e723752f548bd23 | derekmerck/DIANA | /examples/nltk_corpus_analysis.py | 973 | 3.59375 | 4 | """
Example of reading a report corpus and generating a concordance and bi-grams
Create a NLTK plaintext corpus using `examples/nltk_create_report_corpus.py`
"""
from pprint import pprint
import nltk
from nltk.corpus import CategorizedPlaintextCorpusReader, stopwords
import logging
CORPUS_ROOT = "/Users/derek/Data/RADCAT/corpus"
if __name__ == "__main__":
# For reports with category in the f/n abc_def+3.txt
reports = CategorizedPlaintextCorpusReader(CORPUS_ROOT, '.*',
cat_pattern=r'.*\+(.+)\.txt')
logging.basicConfig(level=logging.DEBUG)
logging.debug(reports.categories())
toks = [w.lower() for w in reports.words() if w.isalpha() and w not in stopwords.words('english')]
all = nltk.Text(toks)
print all.concordance('hemodynamically')
# Create your bi-grams and n-grams
# bgs = nltk.bigrams(toks)
tgs = nltk.ngrams(toks, 3)
fdist = nltk.FreqDist(tgs)
pprint(fdist.most_common(20)) |
1028fee3051ff59278ee4feaff67a4738d038f24 | SimonLee118/Project1 | /main.py | 3,368 | 3.796875 | 4 | """
Searches deep inside a directory structure, looking for duplicate file.
Duplicates aka copies have the same content, but not necessarily the same name.
"""
__author__ = "Simon Lee"
__email__ = "lees118@my.erau.edu"
__version__ = "1.0"
# noinspection PyUnresolvedReferences
from os.path import getsize, join
from time import time
# noinspection PyUnresolvedReferences
from p1utils import all_files, compare
lst_of_images = (all_files('images'))
def search(file_list):
"""Looking for duplicate files in the provided list of files
:returns a list of lists, where each list contains files with the same content
Basic search strategy goes like this:
- until the provided list is empty.
- remove the 1st item from the provided file_list
- search for its duplicates in the remaining list and put the item and all its duplicates into a new list
- if that new list has more than one item (i.e. we did find duplicates) save the list in the list of lists
As a result we have a list, each item of that list is a list,
each of those lists contains files that have the same content
"""
lol = []
while 0 < len(file_list):
dups = [file_list.pop(0)]
for i in range(len(file_list) - 1, -1, -1):
if compare(dups[0], file_list[i]):
dups.append(file_list.pop(i))
if 1 < len(dups):
lol.append(dups)
return lol
def faster_search(file_list):
"""Looking for duplicate files in the provided list of files
:returns a list of lists, where each list contains files with the same content
Here's an idea: executing the compare() function seems to take a lot of time.
Therefore, let's optimize and try to call it a little less often.
"""
lol = []
file_sizes = list(map(getsize, file_list))
dups = list(filter(lambda x: 1 < file_sizes.count(getsize(x)), file_list))
for i in dups:
extras = [x for x in dups if compare(i, x)]
if 1 < len(extras):
lol.append(extras)
return lol
def report(lol):
""" Prints a report
:param lol: list of lists (each containing files with equal content)
:return: None
Prints a report:
- longest list, i.e. the files with the most duplicates
- list where the items require the largest amount or disk-space
"""
print("== == Duplicate File Finder Report == ==")
if len(lol) > 0:
m = list(max(lol, key=lambda x: len(x)))
print(f"The file with the most duplicates is {m[0]} \n")
m.pop(0)
print(f"Here are it's {len(m)} copies:", * m, sep="\n")
file_sizes = list(max(lol, key=lambda x: sum([getsize(n) for n in x])))
print(f"\n The most disk space {sum([getsize(n) for n in file_sizes])} could be recovered by"
f"deleting copies of this file:{file_sizes[0]}")
file_sizes.pop(0)
print(f"\n Here are its {len(file_sizes)} copies:")
else:
print("No duplicates found")
if __name__ == '__main__':
path = join(".", "images")
# measure how long the search and reporting takes:
t0 = time()
report(search(all_files(path)))
print(f"Runtime: {time() - t0:.2f} seconds")
print("\n\n .. and now w/ a faster search implementation:")
# measure how long the search and reporting takes:
t0 = time()
report(faster_search(all_files(path)))
print(f"Runtime: {time() - t0:.2f} seconds")
|
7288275733374cd9db40c94ea20cfa716d82041a | barisser/nodeciv | /city.py | 1,785 | 3.5625 | 4 | import economics
import resources
import settings
class City:
def __init__(self, name, x, y, population):
self.x = x
self.name = name
self.y = y
self.population = population
self.commodity_stocks = [0] * len(resources.resources)
self.prices = [0] * len(resources.resources)
self.money = self.population * 1
self.productivity = [1] * len(resources.resources)
self.labor = [1.0 / len(resources.resources)] * len(resources.resources)
def produce(self, data):
resources_n = len(resources.resources)
for i in range(0, resources_n):
production = self.productivity[i] * self.population * self.labor[i]
previous_supply = self.commodity_stocks[i]
self.commodity_stocks[i] += production
self.prices[i] = economics.find_price(previous_supply, self.commodity_stocks[i], self.prices[i], resources.resources[i].base_demand, resources.resources[i].price_elasticity)
return data
def consume(self, data):
for i in range(0, len(resources.resources)):
to_consume = economics.how_much_to_consume(self.money, self.population, resources.resources[i], self.commodity_stocks[i])
if i == 0: #food
if to_consume < self.population * settings.food_per_person:
#kill them off
self.population = self.population * (1.0 - settings.starvation_rate)
else:
self.population = self.population * (1.0 + settings.growth_rate)
self.commodity_stocks[i] = self.commodity_stocks[i] - to_consume
return data
def cycle(self, data):
data = self.produce(data)
data = self.consume(data)
return data
|
634661c3605e7051bfb2f4781f8cdefe111b2aa9 | Ozarrian2026/all-programs- | /Hangman.py | 2,657 | 3.921875 | 4 | import time
import os
ASCII = ['''
+----+
| |
|
|
|
=========''','''
+----+
| |
O |
|
|
=========''','''
+----+
| |
O |
| |
|
=========''','''
+----+
| |
\O |
| |
|
=========''','''
+----+
| |
\O/ |
| |
|
=========''','''
+----+
| |
\O/ |
| |
/ |
=========''','''
+----+
| |
\O/ |
| |
/ \ |
=========''' ]
print(ASCII[0])
word = "minecraft"
word = list(word)
print("Welcome to Hangman!")
guessList = []
missed = []
guessedLetters = []
for letter in word:
guessList.append("_")
print(guessList)
while True:
letter = input("Guess a letter: ")
if letter == "m":
guessList[0] = "m"
print( )
print("Thats a letter")
guessedLetters.append(letter)
print( )
print("Guessed Letters" + str(guessedLetters))
print(guessList)
elif letter == "i":
guessList[1] = "i"
print("Thats a letter")
print("Guessed Letters" + str(guessedLetters))
print(guessList)
elif letter == "n":
guessList[2] = "n"
print("Thats a letter")
print("Guessed Letters" + str(guessedLetters))
print(guessList)
elif letter == "e":
guessList[3] = "e"
print("Thats a letter")
guessedLetters.append(letter)
print("Guessed Letters" + str(guessedLetters))
print(guessList)
elif letter == "c":
guessList[4] = "c"
print("Thats a letter")
guessedLetters.append(letter)
print("Guessed Letters" + str(guessedLetters))
print(guessList)
elif letter == "r":
guessList[5] = "r"
print("Thats a letter")
guessedLetters.append(letter)
print("Guessed Letters" + str(guessedLetters))
print(guessList)
elif letter == "a":
guessList[6] = "a"
print("Thats a letter")
guessedLetters.append(letter)
print("Guessed Letters" + str(guessedLetters))
print(guessList)
elif letter == "f":
guessList[7] = "f"
print("Thats a letter")
guessedLetters.append(letter)
print("Guessed Letters" + str(guessedLetters))
print(guessList)
elif letter == "t":
guessList[8] = "t"
print("Thats a letter")
guessedLetters.append(letter)
print("Guessed Letters" + str(guessedLetters))
print(guessList)
if guessList == word:
print("You win")
break
else:
print("That is not a letter, try again")
missed.append(letter)
print("These are the letters that you guessed so far" + str(guessedLetters))
print(missed)
print(ASCII[len(missed)])
print(guessList)
|
3b50527fa48b73d04d1660ab232e7034064bf382 | Ozarrian2026/all-programs- | /practice1.py | 505 | 3.84375 | 4 | # Ozarrian John, 9/23/2019, B-1, practice1.py
print("Solving equations...")
print("4 * 8 = " + str(4 * 8))
print("12 / 2 = " + str(12 / 2))
print("-5 - 6 * 3 = " + str(-5 - 6 * 3))
age = input("What is your age?")
age = int(age) + 10
print("in ten years you will be... " + str(age))
print("Go Vipers!\n" * 20)
myNum = 20
myNum = myNum + 5
myOtherNum = 10
print("myNum = " + str(myNum))
print("myOtherNum = " + str(myOtherNum))
print("adding...")
print("My Num is...")
print(25 + 10)
|
b5a104236a250896e8518a61d9e8b31dfa96eec0 | nathangiusti/PythonCodingQuestions | /MeetingRoomsNeeded.py | 1,198 | 3.765625 | 4 |
# Given a collection of meetings (each has a start time and an end time, positive integer type, start time is inclusive and end time is exclusive, input is always valid).
# Return how many meeting rooms are needed at least to hold all the meetings.
# [(1,3), (6,8), (4,5)] -> 1
# ##*******
# *****##**
# ***#*****
#
# [(1,2), (4,6), (3,5)] -> 2
# #*********
# ***##*****
# **##******
#
# [(1,7), (2,4), (5,6)] -> 2
# ######****
# *##*******
# ****#*****
#
# [(1,7), (2,5), (4,6)] -> 3
# ######****
# *###******
# ***##*****
NUM_HOURS = 9
def get_number_of_meeting_rooms(schedule):
schedule_block = [0] * NUM_HOURS
for start, end in schedule:
schedule_block[start] = schedule_block[start] + 1
schedule_block[end] = schedule_block[end] - 1
num_rooms = 0
counter = 0
for entry in schedule_block:
counter += entry
num_rooms = counter if counter > num_rooms else num_rooms
return num_rooms
print(get_number_of_meeting_rooms([(1, 3), (6, 8), (4, 5)]))
print(get_number_of_meeting_rooms([(1, 2), (4, 6), (3, 5)]))
print(get_number_of_meeting_rooms([(1, 7), (2, 4), (5, 6)]))
print(get_number_of_meeting_rooms([(1, 7), (2, 5), (4, 6)]))
|
2bcfdf2d2db4d32103e6f4f5bb9c809f7408d191 | uorocketry/Cistern | /code/Format.py | 1,673 | 3.515625 | 4 | #Force gauges calibration
def force1(num):
return num * 1 + 0
def force2(num):
return num * 1 + 0
#Pressure gauges calibration
def press1(num):
return num * 1 + 0
def press2(num):
return num * 1 + 0
def format(data):
out = [0,0,0,0]
#we only want to modify the first four elements. The rest are fine.
for i in range(4):
num = float(data[i])
#do conversion here
if i == 0:
num = force1(num)
if i == 1:
num = force2(num)
if i == 2:
num = press1(num)
if i == 3:
num = press2(num)
out[i] = num
#Append digital inputs and sample count
out.append(int(data[4]))
out.append(int(data[5]))
#Append all 4 temperature probe readings
out.append(float(data[6]))
out.append(float(data[7]))
out.append(float(data[8]))
out.append(float(data[9]))
return str(out).strip().strip("[]")
def pretty(data):
out = ""
#we only want to modify the first four elements. The rest are fine.
for i in range(min(4,len(data))):
num = float(data[i])
#do conversion here
if i == 0:
num = '{: 3.3f} Kg\t'.format( force1(num))
if i == 1:
num = '{: 3.3f} Kg\t'.format( force2(num))
if i == 2:
num = '{: 3.3f} KPa\t'.format( press1(num))
#print("Formatting the third one!")
if i == 3:
num = '{: 3.3f} KPa\t'.format( press2(num))
#print("Formatting the fourth one!")
out =out + num
return str(out) + "\t".join(str(d) for d in data[4:])
|
cb1f1dffb1915de4f2ff1557861afe9072e5747c | MANISH007700/Competitive-Programming | /Problem1.py | 1,803 | 3.53125 | 4 | # Python3 implementation of the approach
DIGITS = 4; MIN = 1000; MAX = 9999;
# Function to return the minimum element
# from the range [prev, MAX] such that
# it differs in at most 1 digit with cur
def getBest(prev, cur) :
# To start with the value
# we have achieved in the last step
maximum = max(MIN, prev);
for i in range(maximum, MAX + 1) :
cnt = 0;
# Store the value with which the
# current will be compared
a = i;
# Current value
b = cur;
# There are at most 4 digits
for k in range(DIGITS) :
# If the current digit differs
# in both the numbers
if (a % 10 != b % 10) :
cnt += 1;
# Eliminate last digits in
# both the numbers
a //= 10;
b //= 10;
# If the number of different
# digits is at most 1
if (cnt <= 1) :
return i;
# If we can't find any number for which
# the number of change is less than or
# equal to 1 then return -1
return -1;
# Function to get the non-decreasing list
def getList(arr, n) :
# Creating a vector for the updated list
myList = [];
# Let's assume that it is possible to
# make the list non-decreasing
possible = True;
myList.append(0);
for i in range(n) :
# Element of the original array
cur = arr[i];
myList.append(getBest(myList[-1], cur));
# Can't make the list non-decreasing
if (myList[-1] == -1) :
possible = False;
break;
# If possible then print the list
if (possible) :
for i in range(1, len(myList)) :
print(myList[i], end = " ");
else :
print("-1");
# Driver code
if __name__ == "__main__" :
arr = [ 1095, 1094, 1095 ];
n = len(arr);
getList(arr, n);
# This code is contributed by AnkitRai01
|
3539e858188a499d9ecda0c90a093a2458dc349a | xiaodongxiexie/python-widget | /PythonWidget/utils/simple_init.py | 2,752 | 3.671875 | 4 | import math
class Structure1:
# Class variable that specifies expected fields
_fields = []
def __init__(self, *args):
if len(args) != len(self._fields):
raise TypeError('Expected {} arguments'.format(len(self._fields)))
# Set the arguments
for name, value in zip(self._fields, args):
setattr(self, name, value)
# Example class definitions
class Stock(Structure1):
_fields = ['name', 'shares', 'price']
class Point(Structure1):
_fields = ['x', 'y']
class Circle(Structure1):
_fields = ['radius']
def area(self):
return math.pi * self.radius ** 2
'''
>>> s = Stock('ACME', 50, 91.1)
>>> p = Point(2, 3)
>>> c = Circle(4.5)
>>> s2 = Stock('ACME', 50)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "structure.py", line 6, in __init__
raise TypeError('Expected {} arguments'.format(len(self._fields)))
TypeError: Expected 3 arguments
'''
class Structure2:
_fields = []
def __init__(self, *args, **kwargs):
if len(args) > len(self._fields):
raise TypeError('Expected {} arguments'.format(len(self._fields)))
# Set all of the positional arguments
for name, value in zip(self._fields, args):
setattr(self, name, value)
# Set the remaining keyword arguments
for name in self._fields[len(args):]:
setattr(self, name, kwargs.pop(name))
# Check for any remaining unknown arguments
if kwargs:
raise TypeError('Invalid argument(s): {}'.format(','.join(kwargs)))
# Example use
if __name__ == '__main__':
class Stock(Structure2):
_fields = ['name', 'shares', 'price']
s1 = Stock('ACME', 50, 91.1)
s2 = Stock('ACME', 50, price=91.1)
s3 = Stock('ACME', shares=50, price=91.1)
# s3 = Stock('ACME', shares=50, price=91.1, aa=1)
class Structure3:
# Class variable that specifies expected fields
_fields = []
def __init__(self, *args, **kwargs):
if len(args) != len(self._fields):
raise TypeError('Expected {} arguments'.format(len(self._fields)))
# Set the arguments
for name, value in zip(self._fields, args):
setattr(self, name, value)
# Set the additional arguments (if any)
extra_args = kwargs.keys() - self._fields
for name in extra_args:
setattr(self, name, kwargs.pop(name))
if kwargs:
raise TypeError('Duplicate values for {}'.format(','.join(kwargs)))
# Example use
if __name__ == '__main__':
class Stock(Structure3):
_fields = ['name', 'shares', 'price']
s1 = Stock('ACME', 50, 91.1)
s2 = Stock('ACME', 50, 91.1, date='8/2/2012')
|
b4d364f33b6724a344007fdedd7f2da568f7d177 | xiaodongxiexie/python-widget | /PythonWidget/utils/delay_calc.py | 984 | 3.859375 | 4 | class lazyproperty:
def __init__(self, func):
self.func = func
def __get__(self, instance, cls):
if instance is None:
return self
else:
value = self.func(instance)
setattr(instance, self.func.__name__, value)
return value
import math
class Circle:
def __init__(self, radius):
self.radius = radius
@lazyproperty
def area(self):
print('Computing area')
return math.pi * self.radius ** 2
@lazyproperty
def perimeter(self):
print('Computing perimeter')
return 2 * math.pi * self.radius
'''
下面在一个交互环境中演示它的使用:
>>> c = Circle(4.0)
>>> c.radius
4.0
>>> c.area
Computing area
50.26548245743669
>>> c.area
50.26548245743669
>>> c.perimeter
Computing perimeter
25.132741228718345
>>> c.perimeter
25.132741228718345
>>>
仔细观察你会发现消息 Computing area 和 Computing perimeter 仅仅出现一次。
'''
|
73295e8eee60e3affa4390a9743935cb4d6ea8d1 | yarden/paper_metachange | /paper_metachange/time_unit.py | 2,872 | 3.96875 | 4 | ##
## Representation of time
##
import numpy as np
import utils
class Time:
"""
Representation of time interval.
Terminology:
- 'bins' represent bins of time interval.
- 'step size' means the duration that is relevant
for an event to occur in.
"""
def __init__(self, t_start, t_end, step_size,
rate_unit=1):
self.t_start = t_start
self.t_end = t_end
self.total_len = float(self.t_end - self.t_start)
self.step_size = step_size
# duration of rate
self.rate_unit = rate_unit
# calculate number of bins to achieve step size
self.num_bins = \
round((t_end - t_start) / float(self.step_size)) + 1
binned_time = np.linspace(t_start, t_end, self.num_bins,
retstep=True)
self.t = binned_time[0]
# get exact step size used
self.step_size = binned_time[1]
self.num_steps = len(self.t)
def __repr__(self):
return self.__str__()
def __str__(self):
return "Time(%.2f, %.2f, step=%.2f)" %(self.t_start,
self.t_end,
self.step_size)
def get_num_bins_to(self, interval_len):
"""
Return number steps (bins) to get to interval
of the given length.
"""
num_steps = \
round((interval_len * (self.num_bins - 1)) / self.total_len)
return int(num_steps)
def iter_interval(self, interval_len):
"""
Iterate by bins of size 'interval_len'
"""
# Need to add 1 to number of bins here
# because of how Python slice indexing works.
# Example: in [0, 1, 2, 3, 4], there are 4 bins.
# To get to 2, we need 2 bins, but the corresponding
# slice is from 0:3
n = self.get_num_bins_to(interval_len) + 1
for curr_interval in utils.grouper_nofill(self.t, n):
yield curr_interval
def iter_interval_ind(self, interval_len, start=0):
"""
Iterate through time by time interval of length 'interval_len'.
Yield the time interval (in time space) as well as the start and
end coordinate of the time interval.
"""
n = self.get_num_bins_to(interval_len)
ind = start
for curr_interval in utils.grouper_nofill(self.t[start:], n):
yield curr_interval, (ind, min(ind + n, self.num_steps))
ind += len(curr_interval)
if __name__ == "__main__":
my_time = Time(0, 5, 1)
print my_time
for n in range(5):
nbins = my_time.get_num_bins_to(n)
print "To get %d need %d bins" %(n, nbins)
assert (nbins == n), "Error"
my_time2 = Time(0, 10, 11)
for c in my_time2.iter_interval(3):
print "time interval: ", c
|
24779aad8a2a15b6b0975734ceb03cbdb7d6433e | vivanov1410/pickled-brain | /002/vivanov/tests.py | 5,372 | 4.0625 | 4 | import unittest
from pickle002 import Calculator
class AddTest(unittest.TestCase):
"""Test for add() function"""
def setUp(self):
self.calc = Calculator()
def test_add_positive_numbers(self):
self.assertEquals(self.calc.add(1, 2), 3)
def test_add_positive_numbers2(self):
self.assertEquals(self.calc.add(10, 25), 35)
def test_add_zeros(self):
self.assertEquals(self.calc.add(0, 0), 0)
def test_add_positive_and_zero(self):
self.assertEquals(self.calc.add(45, 0), 45)
def test_add_zero_and_positive(self):
self.assertEquals(self.calc.add(0, 45), 45)
def test_add_negative_and_zero(self):
self.assertEquals(self.calc.add(-33, 0), -33)
def test_add_zero_and_negative(self):
self.assertEquals(self.calc.add(0, -33), -33)
def test_add_negative_numbers(self):
self.assertEquals(self.calc.add(-3, -15), -18)
def test_add_negative_numbers2(self):
self.assertEquals(self.calc.add(-101, -19), -120)
def test_add_positive_and_negative(self):
self.assertEquals(self.calc.add(21, -7), 14)
def test_add_negative_and_positive(self):
self.assertEquals(self.calc.add(-7, 21), 14)
def test_first_argument_not_number(self):
self.assertEquals(self.calc.add('asd', 2), 'error')
def test_second_argument_not_number(self):
self.assertEquals(self.calc.add(3, 'asd'), 'error')
def test_subtract_positive_numbers(self):
self.assertEquals(self.calc.subtract(10, 6), 4)
def test_subtract_positive_numbers2(self):
self.assertEquals(self.calc.subtract(111, 11), 100)
def test_subtract_zeros(self):
self.assertEquals(self.calc.subtract(0, 0), 0)
def test_subtract_positive_and_zero(self):
self.assertEquals(self.calc.subtract(45, 0), 45)
def test_subtract_zero_and_positive(self):
self.assertEquals(self.calc.subtract(0, 45), -45)
def test_subtract_negative_and_zero(self):
self.assertEquals(self.calc.subtract(-33, 0), -33)
def test_subtract_zero_and_negative(self):
self.assertEquals(self.calc.subtract(0, -33), 33)
def test_subtract_negative_numbers(self):
self.assertEquals(self.calc.subtract(-3, -15), 12)
def test_subtract_negative_numbers2(self):
self.assertEquals(self.calc.subtract(-79, -19), -60)
def test_subtract_positive_and_negative(self):
self.assertEquals(self.calc.subtract(21, -7), 28)
def test_subtract_negative_and_positive(self):
self.assertEquals(self.calc.subtract(-7, 21), -28)
def test_first_argument_not_number(self):
self.assertEquals(self.calc.subtract('asd', 2), 'error')
def test_second_argument_not_number(self):
self.assertEquals(self.calc.subtract(3, 'asd'), 'error')
def test_multiply_positive_numbers(self):
self.assertEquals(self.calc.multiply(10, 6), 60)
def test_multiply_positive_and_negative(self):
self.assertEquals(self.calc.multiply(10, -6), -60)
def test_multiply_negative_numbers(self):
self.assertEquals(self.calc.multiply(-10, -6), 60)
def test_multiply_zeros(self):
self.assertEquals(self.calc.multiply(0, 0), 0)
def test_multiply_positive_and_zero(self):
self.assertEquals(self.calc.multiply(10, 0), 0)
def test_multiply_negative_and_zero(self):
self.assertEquals(self.calc.multiply(-10, 0), 0)
def test_first_argument_not_number(self):
self.assertEquals(self.calc.multiply('asd', 2), 'error')
def test_second_argument_not_number(self):
self.assertEquals(self.calc.multiply(3, 'asd'), 'error')
def test_divide_positive_numbers(self):
self.assertEquals(self.calc.divide(60, 6), 10)
def test_divide_negative_numbers(self):
self.assertEquals(self.calc.divide(-60, -6), 10)
def test_divide_positive_and_negative(self):
self.assertEquals(self.calc.divide(60, -6), -10)
def test_divide_zero_by_number(self):
self.assertEquals(self.calc.divide(0, 123), 0)
def test_divide_number_by_zero(self):
self.assertEquals(self.calc.divide(10, 0), 'error')
def test_first_argument_not_number(self):
self.assertEquals(self.calc.divide('asd', 2), 'error')
def test_second_argument_not_number(self):
self.assertEquals(self.calc.divide(3, 'asd'), 'error')
def test_operations_start_with_zero(self):
calc = Calculator()
self.assertEquals(0, calc.number_of_operations)
def test_operations_increase_when_add_called(self):
calc = Calculator()
calc.add(1, 1)
calc.add(2, 2)
self.assertEquals(2, calc.number_of_operations)
def test_operations_increase_when_subtract_called(self):
calc = Calculator()
calc.subtract(1, 1)
calc.subtract(2, 2)
self.assertEquals(2, calc.number_of_operations)
def test_operations_increase_when_multiply_called(self):
calc = Calculator()
calc.multiply(1, 1)
calc.multiply(2, 2)
self.assertEquals(2, calc.number_of_operations)
def test_operations_increase_when_divide_called(self):
calc = Calculator()
calc.divide(1, 1)
calc.divide(2, 2)
self.assertEquals(2, calc.number_of_operations)
if __name__ == '__main__':
unittest.main() |
1fe99e942fe4f146f1cf006b9098ec0a0ca7431c | vivanov1410/pickled-brain | /002/vivanov/pickle002.py | 1,034 | 3.78125 | 4 | class Calculator:
def __init__(self):
self.number_of_operations = 0
@staticmethod
def _is_number(number):
return type(number) == int
def add(self, number1, number2):
self.number_of_operations += 1
if not self._is_number(number1) or not self._is_number(number2):
return 'error'
return number1 + number2
def subtract(self, number1, number2):
self.number_of_operations += 1
if not self._is_number(number1) or not self._is_number(number2):
return 'error'
return number1 - number2
def multiply(self, number1, number2):
self.number_of_operations += 1
if not self._is_number(number1) or not self._is_number(number2):
return 'error'
return number1 * number2
def divide(self, number1, number2):
self.number_of_operations += 1
if not self._is_number(number1) or not self._is_number(number2) or number2 is 0:
return 'error'
return number1 / number2 |
939ea148a19002e33c1c2cb23fd2a984a8093c48 | TroyArrandale/python-review-questions | /week8_4_panadas.py | 461 | 3.625 | 4 | import pandas as pd
import unittest
nested_dict = {'white_wine': {1998:1, 1999:1, 2000:2},
'red_wine': {1998:3, 1999:2, 2000:0}}
df = pd.DataFrame(nested_dict)
class TestForBasicMath(unittest.TestCase):
def test_df_white_wine_1998(self):
pass
#TODO: Test the value of white wine is expect in the dataframe of 1998 is 1
#self.assertEqual(sum([1, 2, 3]), 6, "Should be 6")
#
if __name__ == '__main__':
unittest.main()
|
caad0af5c1760f227bea65dfc82fd9e863b282af | mramdanf/hackerrank_regex | /alien_username.py | 261 | 3.703125 | 4 | import re
N = int(input())
pattern = '^[_\.]\d+[a-zA-Z]*[_]?'
for n in range(0, N):
text = input()
m = re.search(pattern, text)
if m != None:
if m.end() == len(text):
print('VALID')
else:
print('INVALID')
else:
print('INVALID')
|
694bceb3cea897a3517e1d4420bf299314d4b3d8 | cha63506/767_information_retrieval_project | /llist.py | 1,128 | 3.578125 | 4 | class posting:
def __init__(self):
self.file_name = None # String value
self.word_num = None # List of ints
self.term_f = None # Int value
self.next = None # contains the reference to the next posting
class posting_list:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def add(self, fn, wn):
self.length += 1
nn = posting() # create a new posting
nn.file_name = fn
nn.word_num = [wn]
nn.term_f = 1
# Append new nodes to the back of the list
if self.tail:
self.tail.next = nn
self.tail = nn
else:
self.head = nn
self.tail = nn
def check(self, fn, wn):
n = self.find(fn)
if n:
# have the correct posting
n.term_f += 1
n.word_num.append(wn)
else:
# No posting exists with filename
self.add(fn, wn)
def find(self, fn):
n = self.head
while n:
if n.file_name == fn:
return n
n = n.next
return None
def print_postings(self):
n = self.head # cant point to ll!
while n:
print ("[fn:" + str(n.file_name) + ", wn:" + str(n.word_num) + ", tf:" + str(n.term_f) + "] -> ", end="")
n = n.next
print ("None", end="")
|
5baf869bdf4538c8c57c396b693337c0b4e01184 | IllyaKol/CheckIO-Solutions | /home/most-wanted-letter.py | 1,208 | 3.671875 | 4 | import re
def checkio(text):
text = text.replace(' ', '').lower()
text = re.sub(r'!|,|\.|-|\d', '', text)
new_text = set(text)
if len(new_text) != len(text):
count = 0
letter = []
for i in text:
if text.count(i) > count:
letter = []
count = text.count(i)
letter.append(i)
elif text.count(i) == count:
count = text.count(i)
letter.append(i)
letter.sort()
return letter[0]
else:
text = list(text)
text.sort()
return text[0]
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio("Hello World!") == "l", "Hello test"
assert checkio("How do you do?") == "o", "O is most wanted"
assert checkio("One") == "e", "All letter only once."
assert checkio("Oops!") == "o", "Don't forget about lower case."
assert checkio("AAaooo!!!!") == "a", "Only letters."
assert checkio("abe") == "a", "The First."
print("Start the long test")
assert checkio("a" * 9000 + "b" * 1000) == "a", "Long."
print("The local tests are done.")
|
686069473b4abdc74b821ab90092743069c4fd9b | Alexander-Espinoza/Vehiculo-para-Herencia | /vehiculo.py | 1,787 | 3.90625 | 4 | class Vehiculo():
def __init__(self, marca, modelo):
self.marca=marca
self.modelo=modelo
self.enMarcha=False
self.acelera=False
self.frena=False
def arrancar(self):
self.enMarcha=True
def acelerar(self):
self.acelera=True
def frenar(self):
self.frena=True
def estado(self):
print ("""Marca: {}
\nModelo: {}
\nEn marcha: {}
\nAcelerando: {}
\nFrenando: {}
""".format(self.marca,self.modelo,self.enMarcha,self.acelera,self.frena))
class VElectrico():
def __init__(self):
self.autonomia=100
def cargarEnergia(self):
self.cargando=True
class Furgoneta(Vehiculo):
def carga(self,cargar):
self.cargado=cargar
if(self.cargado):
print("La furgoneta está cargada")
else:
print("La furgoneta no está cargada")
class Moto(Vehiculo):
hacerCaballito=""
def caballito(self):
self.hacerCaballito="Voy haciendo el caballito"
def estado(self):
print ("""Marca: {}
\nModelo: {}
\nEn marcha: {}
\nAcelerando: {}
\nFrenando: {}
\n{}
""".format(self.marca,self.modelo,self.enMarcha,self.acelera,self.frena,self.hacerCaballito))
class BicicletaElectrica(Vehiculo,VElectrico):
pass
miMoto=Moto("Honda","CBR")
miMoto.caballito()
miMoto.estado()
print("----------------------------------")
miFurgoneta=Furgoneta("Renault","Kangoo")
miFurgoneta.arrancar()
miFurgoneta.estado()
miFurgoneta.carga(True)
print("----------------------------------")
miBici=BicicletaElectrica("Bach","LR1")
miBici.estado()
|
278ba3bef7de00916a1959ad1c29fda56b7590c4 | Abob888/Rep2 | /str82-2.py | 698 | 3.84375 | 4 | a = ['Red', 'fox', 'jumped', 'up', 'the', 'low', 'wall', '.']
a = ' '.join(a) # объединение списка в строку
a = a[0:-2] + '.' # срезаем два последних символа и заменяем их точкой
print(a)
print('Children are the mirrow of parents activity'.replace('r', '$'))
''' Замена в строке
буквы r на $.
'''
print('Хемингуэй'.index('м')) # определение позиции буквы "м"
print('five ' + 'five ' + 'five ')
print('five ' * 3) # затроение строки
b = "Don't laught so! I've heard everything."
print(b[0:16]) # срез до восклицательного знака
|
2c194681f72aa01abea343537dda801a6a656bf0 | Abob888/Rep2 | /files09022020-4.py | 127 | 3.53125 | 4 | import csv
with open('st.csv', 'r') as f:
q = csv.reader(f, delimiter=',')
for row in q:
print(','.join(row))
|
10f68ad8ed5fee0683e4eeb171068aa850e910ba | Abob888/Rep2 | /test-p121.py | 174 | 3.75 | 4 | class Square():
def __init__(self, s1):
self.side = s1
def change_size(self):
return self.side + 5
squ = Square(3)
print(squ.change_size())
|
7634afd515684f382a9e9e0afdb4c8d1b719fcbb | saveroz/DTL-AI | /Quiz & Jawaban/Muhammad_Savero_soal1.py | 1,147 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 19 20:57:48 2018
@author: OREVAS
"""
def soal_1():
jumlah_orang=input(" ") #jumlah orang beserta uangnya
lists_orang=[]
lists_duit=[]
for i in range(int(jumlah_orang)):
uang=input(" ")
lists=uang.split(" ")
lists_orang.append(lists[0])
lists_duit.append(lists[1])
jumlah_transaksi=input(" ") #jumlah transaksi yang terjadi
for a in range(int(jumlah_transaksi)):
transaksi=input(" ")
lists_2=transaksi.split(" ")
send=lists_2[0] #pengirim uang
nom=int(lists_2[1]) #nominal uang
receive=lists_2[2] #penerima uang
lists_duit[int(lists_orang.index(send))]=int(lists_duit[int(lists_orang.index(send))])-nom #pengurangan uang terhadap pengirim
lists_duit[int(lists_orang.index(receive))]=int(lists_duit[int(lists_orang.index(receive))])+nom #penambahan uang terhadap penerima
print("----------------")
for j in range(int(jumlah_orang)):
print(lists_orang[j]+" "+str(lists_duit[j]))
if __name__=='__main__': #menjalankan program
soal_1() |
3723764b03c94e60a1432371af503f832e2dd1d4 | zahera-fatima/day2 | /line.py | 443 | 4 | 4 | def word_score(word):
total = 0
for i in word:
i = i.lower()
total += score[i]
return total
score = {"a":1,"b":2,"c":3,"d":4,
"e":5,"f":6,"g":7,"h":8,
"i":9,"j":10,"k":11,"l":12,
"m":13,"n":14,"o":15,"p":16,
"q":17,"r":18,"s":19,"t":20,
"u":21,"v":22,"w":23,"x":24,"y":25,
"z":26}
your_word = input("word score: ")
print(word_score(your_word))
|
ce1dfc1cb226112f3990719587afc4e452cbb81b | fpaezespe37/POO2963 | /WorkShop/Unit 1/WorkShop04_Python/Edades.py | 172 | 3.9375 | 4 | names = ['Stiven', 'Dennis', 'Adrian', 'Jerico','Javier']
ages= [18, 60, 23, 22, 26]
names_with_ages = zip(names,ages)
for student in names_with_ages:
print(student) |
1b75304c772f1d93a1bc86d57cbc021e9a425698 | fpaezespe37/POO2963 | /WorkShop/Unit 1/WorkShop05_FunctoinsPy/Funciones.py | 981 | 3.84375 | 4 | class Student:
university = 'ESPE'
def __init__(self,_id,_name,_age,_career,_cell_number):
self.id = _id
self.name = _name
self.age = _age
self.career = _career
self.cell_number = _cell_number
class Phone:
def __init__(self, _number):
self.number = _number
def __repr__(self):
return 'Phone({})'.format(self.number)
self.phone = Phone(_cell_number)
def __repr__(self):
return 'Student({}, {}, {}, {},{})'.format(self.id, self.name, self.age, self.career, self.phone)
def say_name(self):
print('MY name is {}'.format(self.name))
student = Student(1, 'Stalin',19,'Inginieria de software','098363533')
student1 = Student(1, 'Wilson',18,'software engineering','098335333')
student.say_name()
print(student.university)
print(student.university)
print(student1.university)
#print(Phone)
print(student) |
959c3e5e84a57ca4743383af77219e211673ba85 | Rayyan98/DS2-Project | /Collision_detection.py | 407 | 3.75 | 4 | # Collision Detection class
class Collision_Detection:
def takra(self, rect1, rect2):
if rect1.x > rect2.x:
rect1,rect2 = rect2,rect1
if rect1.x + rect1.w > rect2.x:
if rect1.y + rect1.h < rect2.y:
return False
elif rect1.y > rect2.y + rect2.h:
return False
return True
return False
|
17b11e255a7942dd3d1c383809d421dcf1627761 | Rayyan98/DS2-Project | /QuadTree.py | 5,501 | 3.515625 | 4 | from Collision_detection import Collision_Detection
from MyScreen import MyScreen
from MyRectangle import MyRectangle
from MyRectangle import MyRectangle
import math
class Node(Collision_Detection):
def __init__(self, rect):
self.rect = rect
self.rects = set()
self.tl = None
self.tr = None
self.bl = None
self.br = None
def insert(self, rect):
if self.rect.w <= 100 or self.rect.h <= 100:
self.rects.add(rect)
else:
self.rects.add(rect)
if len(self.rects) > 7:
if self.tl == None:
xmid = self.rect.w // 2 + self.rect.x
ymid = self.rect.h // 2 + self.rect.y
self.tl = Node(MyRectangle(self.rect.x, self.rect.y, self.rect.w // 2, self.rect.h //2))
self.tr = Node(MyRectangle(xmid, self.rect.y, math.ceil(self.rect.w / 2), self.rect.h // 2))
self.bl = Node(MyRectangle(self.rect.x, ymid, self.rect.w // 2, math.ceil(self.rect.h / 2)))
self.br = Node(MyRectangle(xmid, ymid, math.ceil(self.rect.w / 2), math.ceil(self.rect.h / 2)))
self.children = [self.tl, self.tr, self.bl, self.br]
else:
r = [i for i in self.rects]
for j in r:
if j.x + j.w < self.rect.x + self.rect.w // 2:
if j.y + j.h < self.rect.y + self.rect.h // 2:
self.tl.insert(j)
self.rects.remove(j)
elif j.y >= math.ceil(self.rect.h / 2) + self.rect.y:
self.bl.insert(j)
self.rects.remove(j)
elif j.x >= self.rect.x + math.ceil(self.rect.w / 2):
if j.y + j.h < self.rect.y + self.rect.h // 2:
self.tr.insert(j)
self.rects.remove(j)
elif j.y >= math.ceil(self.rect.h / 2) + self.rect.y:
self.br.insert(j)
self.rects.remove(j)
# r = [i for i in self.rects]
# for j in r:
# count = 0
# for i in self.children:
# if self.takra(j, i.rect):
# u = i
# count += 1
# if count > 1:
# break
# if(count == 1):
# u.insert(j)
# self.rects.remove(j)
def AddRects(self, rects):
if self.rect.w <= 80 or self.rect.h <= 80 or len(rects) < 5:
for i in rects:
self.rects.add(i)
else:
if self.tl == None:
xmid = self.rect.w // 2 + self.rect.x
ymid = self.rect.h // 2 + self.rect.y
self.tl = Node(MyRectangle(self.rect.x, self.rect.y, self.rect.w // 2, self.rect.h //2))
self.tr = Node(MyRectangle(xmid, self.rect.y, math.ceil(self.rect.w / 2), self.rect.h // 2))
self.bl = Node(MyRectangle(self.rect.x, ymid, self.rect.w // 2, math.ceil(self.rect.h / 2)))
self.br = Node(MyRectangle(xmid, ymid, math.ceil(self.rect.w / 2), math.ceil(self.rect.h / 2)))
tl = []
bl = []
tr = []
br = []
for j in rects:
if j.x + j.w < self.rect.x + self.rect.w // 2:
if j.y + j.h < self.rect.y + self.rect.h // 2:
tl.append(j)
elif j.y >= math.ceil(self.rect.h / 2) + self.rect.y:
bl.append(j)
else:
self.rects.add(j)
elif j.x >= self.rect.x + math.ceil(self.rect.w / 2):
if j.y + j.h < self.rect.y + self.rect.h // 2:
tr.append(j)
elif j.y >= math.ceil(self.rect.h / 2) + self.rect.y:
br.append(j)
else:
self.rects.add(j)
else:
self.rects.add(j)
self.tl.AddRects(tl)
self.bl.AddRects(bl)
self.tr.AddRects(tr)
self.br.AddRects(br)
def CheckCollision(self, rects = []):
s = set()
r = [i for i in self.rects]
for i in range(len(r) - 1):
for j in range(i + 1, len(r)):
if self.takra(r[i],r[j]):
s.add(frozenset([r[i],r[j]]))
for i in rects:
for j in self.rects:
if self.takra(i,j):
s.add(frozenset([i,j]))
tlcopy = rects.copy()
blcopy = rects.copy()
trcopy = rects.copy()
brcopy = rects.copy()
for j in self.rects:
if j.x + j.w < self.rect.x + self.rect.w // 2:
if j.y + j.h < self.rect.y + self.rect.h // 2:
tlcopy.append(j)
elif j.y >= math.ceil(self.rect.h / 2) + self.rect.y:
blcopy.append(j)
else:
tlcopy.append(j)
blcopy.append(j)
elif j.x >= self.rect.x + math.ceil(self.rect.w / 2):
if j.y + j.h < self.rect.y + self.rect.h // 2:
trcopy.append(j)
elif j.y >= math.ceil(self.rect.h / 2) + self.rect.y:
brcopy.append(j)
else:
trcopy.append(j)
brcopy.append(j)
else:
if j.y + j.h < self.rect.y + self.rect.h // 2:
trcopy.append(j)
tlcopy.append(j)
elif j.y >= math.ceil(self.rect.h / 2) + self.rect.y:
brcopy.append(j)
blcopy.append(j)
else:
trcopy.append(j)
brcopy.append(j)
tlcopy.append(j)
blcopy.append(j)
if self.tl != None:
s = s.union(self.tl.CheckCollision(tlcopy))
s = s.union(self.bl.CheckCollision(blcopy))
s = s.union(self.tr.CheckCollision(trcopy))
s = s.union(self.br.CheckCollision(brcopy))
return s
class Collision_Detection_Quad_Tree:
def __init__(self):
pass
def CheckCollisions(self, rects):
self.root = Node(MyRectangle(0,0,MyScreen.width, MyScreen.height))
self.root.AddRects(rects)
# for i in rects:
# self.root.insert(i)
return self.root.CheckCollision([])
|
8e1ec16ede56905db61ac18b0002ea4e8e10997b | HoanVanHuynh/InterTools | /accumulate.py | 720 | 4 | 4 | import operator
def accumulate(iterable, func = operator.add, *, initial=None):
it = iter(iterable)
total = initial
if initial is None:
try:
total = next(it)
except StopIteration:
return
yield total
for element in it:
total = func(total, element)
yield total
data = [4,5,7]
#data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
t = accumulate(data, operator.mul)
#print(list(t))
print(next(t))
print(next(t))
def chain(*iterables):
# chain('ABC', 'DEF') --> A B C D E F
for it in iterables:
for element in it:
yield element
result = chain('ABC', 'DEF')
# print(next(result))
# print(next(result))
# print(list(result)) |
7dc2187249f3a8e117cd2c70febc8189dcddc7c4 | benoucakar/programiranje-1 | /razredi.py | 1,203 | 3.53125 | 4 | class Pes():
# Argumenti
def __init__ (self, ime, starost):
self.ime = ime
self.starost = starost
self.sreca = 5
self.lakota = 5
# Metode
def podatki(self):
print("Ime: " + self.ime)
print("Starost: " + str(self.starost) + " let")
print("Sreča: " + str(self.sreca))
print("Lakota: " + str(self.lakota))
def igra(self):
self.lakota += 1
self.sreca += 1
self.podatki()
def nahrani(self):
self.lakota -= 2
self.podatki()
def kreganje(self):
self.sreca -= 2
self.podatki()
def __add__(self, kuza):
self.sreca += 2
kuza.sreca += 2
kuza1 = Pes("Piko", 3)
kuza2 = Pes("Erik", 100)
kuza3 = Pes("Rex", 5)
def tekstura():
print(" &&&")
print(" &&&&&&&&& &&")
print(" && && &&&")
print(" &&&&&&&&&&&&&&&&&&&&&&")
print(" & && &&&&&&& &&&")
print(" && & && &")
print(" & & && &&")
|
36f1263ebdbaf546d5e6b6ad874a0f8fc51ef65a | andredupontg/PythonInFourHours | /pythonInFourHours.py | 1,628 | 4.1875 | 4 | # Inputs and Outputs
"""
name = input("Hello whats your name? ")
print("Good morning " + name)
age = input("and how old are you? ")
print("thats cool")
"""
# Arrays
"""
list = ["Volvo", "Chevrolet", "Audi"]
print(list[2])
"""
# Array Functions
"""
list = ["Volvo", "Chevrolet", "Audi"]
list.insert(1, "Corona")
list.remove("Corona")
list.clear()
list.pop()
list.index("Volvo)
"""
# Functions
"""
def myFirstFunction():
print("Hello this is my first function! ")
print("NEW PROGRAM")
myFirstFunction()
"""
# Return Function
"""
def powerNumber(number):
return number * number
print("NEW PROGRAM")
print(powerNumber(3))
"""
# If & Else
"""
age = 0
if age >= 18:
print("Overage")
elif age < 18 and age > 0:
print("Underage")
else:
print("Not even born")
"""
# While Loops
"""
i = 0
while i < 4:
print("Haha")
i += 1
print("End of the loop")
"""
# For Loopss
"""
fruits = ["apple", "orange", "banana"]
for x in fruits:
print(x)
"""
# Class & Objects
"""
class Student:
def __init__(self, name, age, career):
self.name = name
self.age = age
self.career = career
student = Student("Andre", 22, "systems engineering")
print(student.name)
print(student.age)
print(student.career)
"""
# Class Methods
"""
class Student:
def __init__(self, name, age, career):
self.name = name
self.age = age
self.career = career
def calculateSalaryByAge(self):
if self.age < 60 and self.age >= 18:
return 3000
else:
return 0
student = Student("Andre", 22, "Systems Engineering")
print(student.calculateSalaryByAge())
"""
|
c6a7fad8362397aada270409b30e9f97dd2cff4e | Zapix/mtpylon | /mtpylon/crypto/random_prime.py | 2,321 | 3.984375 | 4 | # -*- coding: utf-8 -*-
import random
first_primes_list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67,
71, 73, 79, 83, 89, 97, 101, 103,
107, 109, 113, 127, 131, 137, 139,
149, 151, 157, 163, 167, 173, 179,
181, 191, 193, 197, 199, 211, 223,
227, 229, 233, 239, 241, 251, 257,
263, 269, 271, 277, 281, 283, 293,
307, 311, 313, 317, 331, 337, 347, 349]
def random_odd(n_bits: int) -> int:
"""
Generates random odd number in range [2 ^ (n_bits - 1), 2 ^ (n_bits) - 1]
Odd number probably is prime number
"""
assert n_bits > 0
value = random.getrandbits(n_bits)
value |= (1 << n_bits) | 1
return value
def is_low_level_test_passed(value: int) -> bool:
"""
Returns True if low level tests has been passed
"""
for prime in first_primes_list:
if prime**2 > value:
break
if value % prime == 0:
return False
return True
TESTS_COUNT = 20
def is_composite_value(value: int, a: int, ec: int, max_pow_2: int) -> bool:
"""
Returns True if value is composite. otherwise false
"""
b0 = pow(a, ec, value)
if b0 == 1 or b0 == value - 1:
return False
b_prev = b0
for _ in range(max_pow_2):
bi = pow(b_prev, 2, value)
if bi == 1:
break
elif bi == value - 1:
return False
b_prev = bi
return True
def is_miller_rabin_passed(value: int) -> bool:
"""
Checks is value a prime number with Fermat theorem
and Miller Rabin algorithm
"""
ec = value - 1
max_pow_2 = 0
while ec % 2 == 0:
ec >>= 1
max_pow_2 += 1
for i in range(TESTS_COUNT):
a = random.randint(2, ec)
if is_composite_value(value, a, ec, max_pow_2):
return False
return True
def random_prime(n_bits: int) -> int:
"""
Returns random primary number
"""
while True:
possible_prime = random_odd(n_bits)
if (
is_low_level_test_passed(possible_prime) and
is_miller_rabin_passed(possible_prime)
):
return possible_prime
|
ddb5306a9f99f64c033cee565dfc3f939a05530a | tqt129/pythonexercise | /pythonexercise/inputexercise.py | 371 | 4.03125 | 4 | user_input = input('What would you like the cat to say')
text_length = len(user_input)
# print underline based on length of user input
print(' {}'.format('_' * text_length))
print(' < {} >'.format(user_input))
print(' {}'.format('-' * text_length))
print(' /')
print(' /\_/\ /')
print(' ( 0.0 ) ' )
print(' > ^ <' ) |
c4f411dc62e5749f1e813da02ff1a89f881b14d0 | jgarrone82/Datacademy | /Python/reto4.py | 1,098 | 4 | 4 | import math
def convertidor():
i=0
while i==0:
opcion=int(input("Por favor,ingre el numero de la opcion que quiera :"))
if opcion == 1:
altura=float(input("Ingrese la altura del cilindro:"))
radio=float(input("Ingrese el radio del cilindro:"))
volumen=math.pi*(radio**2)*altura
print("El volumen del cilindro es :", volumen)
elif opcion == 2:
lado=float(input("Ingrese un lado del cubo:"))
volumen=lado ** 3
print("El volumen del cubo es :", volumen)
elif opcion == 3:
radio=float(input("Ingrese el radio de la esfera:"))
volumen=math.pi*(radio**3)*(4/3)
print("El volumen de la esfera es :", volumen)
elif opcion == 4:
break
else:
print("ingresa una opcion valida")
def main():
print("""Selecione la figura la cual quiere obtener el volumen :
1): cilindro
2): cubo
3): Esfera
4): Salir
""")
convertidor()
if __name__=="__main__":
main() |
bb2a319abc3ac552e0bc062b234d1b47b259c3dc | choidslab/teamlab-python-basic | /chapter15/ex_json1.py | 487 | 3.953125 | 4 | """
json 파일은 읽은 후, dict type으로 처리하면 됨!
"""
import json
with open('json_example.json', 'r', encoding='utf-8') as f:
contents = f.read()
json_data = json.loads(contents)
print(json_data)
print(json_data['employees'])
print(json_data['employees'][0])
print(json_data['employees'][1])
print(json_data['employees'][2])
print(json_data['employees'][0]['firstName'])
emp1 = json_data['employees'][0]
print(emp1['firstName'])
|
8b2ca4958725ab3c88bdd7f1cd17cb5244303a7c | heiretodemon/python_interview_question | /python_code/39.py | 354 | 4 | 4 | '''
def multi():
return [lambda x: i*x for i in range(4)]
print([m(3) for m in multi()])
'''
# 关于闭包的理解:https://zhuanlan.zhihu.com/p/22229197
# 但仍存在疑问
from six.moves import xrange
flist = []
for i in xrange(3):
def func(x):
return i*x;
flist.append(func)
print(flist)
for f in flist:
print(f(2)) |
2c82ae9fe4a4d93aba3cde1e778b9d4afdad117a | heiretodemon/python_interview_question | /python_code/32.py | 181 | 3.890625 | 4 | def even_list(nums):
return [i for i in nums if i%2 == 0 and
nums.index(i)%2 == 0]
if __name__ == "__main__":
nums = [0,1,2,3,4,5,6,7,8,9,10]
print(even_list(nums)) |
bc52d9a2dad43d3f38c9a92e199d66d69537279c | heiretodemon/python_interview_question | /python_code/6.py | 279 | 4 | 4 | # 字典推导式
A = {'a':1, 'b':2, 'c':3}
d = {key:value for (key, value) in A.items()}
print(d)
# 列表推导式
ls = [i**2 for i in range(10) if i % 3 == 0]
print(ls)
# 集合推导式(输出结果集合中不会出现重复的)
sq = {i*3 for i in [1,2,2,3,4,5]}
print(sq) |
43e5b0370029071ff5170f48a25a18d1c1899c89 | heiretodemon/python_interview_question | /python_code/44.py | 522 | 3.515625 | 4 | class Test:
__list = []
def __init__(self):
print("construction")
def __del__(self):
print("destruct")
def __str__(self):
return "a string version of Test"
def __getitem__(self, key):
return self.__list[key]
def len(self):
return len(self.__list)
def Add(self, value):
self.__list.append(value)
def Remove(self, index):
del self.__list[index]
def DisplayItems(self):
for i in self.__list:
print(i)
|
dc9f803ea9c259d7e2da8443a7c3dc09e4fe081f | codebyzeb/Part-II-Project | /analysis/plotting.py | 13,661 | 3.546875 | 4 | """
Analysis module used for plotting graphs of the simulation
"""
import argparse
import matplotlib.pyplot as plt
from matplotlib import style
from scipy.stats import pearsonr
import sys
import pickle
import numpy as np
class Plotter:
""" Represents a simulation environment for a population of entities.
Attributes:
generations: The x-axis, the generation number
average_entities: The y-axis, the average energy of the population over generation count
ax: The axis plotted
"""
generations = []
average_fitness = []
ax = None
def __init__(self):
"""
Initialise the plot
"""
plt.ion()
fig = plt.figure()
self.ax = fig.add_subplot(1, 1, 1)
plt.show()
def add_point_and_update(self, generation, average_energy):
"""
Add a point and update the graph
Args:
generation: The generation number
average_energy: The average energy of the population
"""
self.generations.append(generation)
self.average_fitness.append(average_energy)
self.ax.clear()
self.ax.plot(self.generations, self.average_fitness)
plt.draw()
plt.pause(0.01)
def plot_one(foldername, num=1000):
# Set up plot
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# ax.set_title("Average Fitness")
ax.grid(linestyle='-')
# Get data
fitness_file = open(foldername + "/fitness.txt", "r")
average_fitness = []
lines = fitness_file.readlines()
fitness_file.close()
for j, line in enumerate(lines):
if j >= num:
break
average_fitness.append(float(line))
# Show plot
ax.plot(list(range(len(average_fitness))),
average_fitness,
label="Average Fitness",
linewidth=1.0)
plt.show()
def plot_ten(foldername, num=1000):
fig = plt.figure()
ax = fig.add_subplot(1111)
# ax.set_title("Average fitness for ten replicas")
ax.set_xlabel("Generations")
ax.set_ylabel("Fitness")
# Plot ten subgraphs
for i in range(10):
# Set up axis
ax = fig.add_subplot(5, 2, i + 1)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.grid(linestyle='-')
# Get data
for language_type in ["none", "evolved", "external"]:
fitness_file = open(foldername + "/" + language_type + str(i) + "/fitness.txt", "r")
average_fitness = []
lines = fitness_file.readlines()
fitness_file.close()
for j, line in enumerate(lines):
if (j >= num):
break
average_fitness.append(float(line))
# Plot data
ax.plot(list(range(len(average_fitness))),
average_fitness,
label=language_type,
linewidth=1.0)
# Show graph
plt.legend()
plt.show()
def time_average(foldername, num=1000):
# Set up plot
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.set_xlabel("Generations")
ax.set_ylabel("Time (seconds)")
# ax.set_title("Average Fitness")
ax.grid(linestyle='-')
for optimisation in [
"No Optimisations", "Detect Looping", "Skip None", "Skip Edge", "All Optimisations"
]:
# Get data
times = np.zeros(num + 1)
for i in range(10):
filename = "{}/{}/None{}/time.txt".format(foldername, optimisation.lower(), i)
time_file = open(filename, "r")
lines = time_file.readlines()
lines = [float(line) / 10 for line in lines][:num + 1]
lines = np.array(lines)
times = times + lines
time_file.close()
# Plot time line
ax.plot(list(range(len(times))), times, linewidth=1.0, label=optimisation)
plt.legend()
plt.show()
def plot_ten_language(foldername, language, num):
# Set up figure
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.set_xlabel("Generations")
ax.set_ylabel("Fitness")
# ax.set_title("Average fitness for ten replicas of {0} language".format(language))
ax.grid(linestyle='-')
# ax.set_ylim([0, 450])
# Get data
for i in range(10):
fitness_file = open(foldername + "/" + language + str(i) + "/fitness.txt", "r")
lines = fitness_file.readlines()
average_fitness = [0 for i in range(num)]
totalNum = num
if len(lines) <= totalNum:
totalNum = len(lines)
average_fitness = average_fitness[:totalNum]
fitness_file.close()
for j, line in enumerate(lines):
if (j >= totalNum):
break
average_fitness[j] += float(line)
# Plot graph
ax.plot(list(range(len(average_fitness))), average_fitness, linewidth=0.6, label=i)
plt.legend()
plt.show()
def plot_average(foldername, num=1000):
# Set up plot
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# ax.set_title("Average fitness")
ax.set_xlabel("Generations")
ax.set_ylabel("Fitness")
ax.grid(linestyle='-')
# ax.set_ylim([0, 450])
# Get data
for language_type in ["None", "Evolved", "External"]:
average_fitness = [0 for i in range(num)]
totalNum = num
for i in range(10):
fitness_file = open(foldername + "/" + language_type + str(i) + "/fitness.txt", "r")
lines = fitness_file.readlines()
if len(lines) < totalNum:
totalNum = len(lines)
average_fitness = average_fitness[:totalNum]
fitness_file.close()
for j, line in enumerate(lines):
if (j >= totalNum):
break
average_fitness[j] += (float(line) / 10)
# Plot line
ax.plot(list(range(len(average_fitness))),
average_fitness,
label=language_type,
linewidth=1.0)
plt.legend()
plt.show()
def plot_language_distributions_bar(foldername, increment, num):
generations = [i * increment for i in range(int(num / increment) + 1)]
width = 0.35
labels = [str(bin(i))[2:].zfill(3) for i in range(8)]
x = np.arange(len(labels))
fig = plt.figure()
# Set up main axis for title and labels
axmain = fig.add_subplot(111)
axmain.spines['top'].set_color('none')
axmain.spines['bottom'].set_color('none')
axmain.spines['left'].set_color('none')
axmain.spines['right'].set_color('none')
axmain.tick_params(labelcolor='w', top=False, bottom=False, left=False, right=False)
# axmain.set_title('Language Frequency Distribution')
# Get data
language = pickle.load(open(foldername + "/language.p", 'rb'))
# Plot a frequency distribution for each generation in the list
for j, gen in enumerate(generations):
# Create subplot and remove ticks
ax = fig.add_subplot(len(generations), 1, j + 1)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
axmain.set_ylabel('Generation')
axmain.set_xlabel('Signal')
# Set label and ticks
ax.set_ylabel(str(gen),
rotation="horizontal",
verticalalignment="center",
horizontalalignment="right",
size="small")
ax.set_xticks(x)
ax.set_xticklabels(labels, size="small")
plt.setp(ax.get_yticklabels(), visible=False)
ax.get_yaxis().set_ticks([])
if j < len(generations) - 1:
plt.setp(ax.get_xticklabels(), visible=False)
# Set axis height
ax.set_ylim([0, 1])
# Plot data
rects = ax.bar(x + pow(-1, 1) * width / 2,
language[gen]["edible"],
width,
label="Edible",
color='red')
rects = ax.bar(x + pow(-1, 2) * width / 2,
language[gen]["poisonous"],
width,
label="Poisonous",
color='blue')
# Plot legend half way up
if gen == generations[len(generations) // 2]:
ax.legend()
plt.gcf().subplots_adjust(left=0.15)
plt.show()
def get_QI(foldername, generations, k=1):
""" Calculates the quality index for each generation where k is a constant
to weigh the effect of the internal dispersion value of poisonous or edible mushrooms.
"""
qis = []
# Get data
language = pickle.load(open(foldername + "/language.p", 'rb'))
for gen in generations:
# Calculate the dispersion values
d_edible = sum([abs(frequency - 0.125) for frequency in language[gen]["edible"]])
d_poisonous = sum([abs(frequency - 0.125) for frequency in language[gen]["poisonous"]])
# Calculate quality index
qi = sum(
[abs(language[gen]["edible"][i] - language[gen]["poisonous"][i])
for i in range(8)]) + k * min(d_edible, d_poisonous)
qis.append(qi * 100 / 3.75)
return qis
def frequency_and_qi(foldername, increment, num):
generations = [i * increment for i in range(int(num / increment) + 1)]
# Get QI scores for each generation
qis = get_QI(foldername, generations)
# Get fitness scores
fitness_file = open(foldername + "/fitness.txt", "r")
average_fitness = []
lines = fitness_file.readlines()
fitness_file.close()
for i, line in enumerate(lines):
if i in generations:
average_fitness.append(float(line))
# Calculate correlation
print("Correlation:", pearsonr(average_fitness, qis))
# Plot average fitness
fig, ax1 = plt.subplots()
l1, = ax1.plot(generations, average_fitness, label="Average fitness", linewidth=1.0, color='r')
ax1.set_ylabel("Fitness")
ax1.set_xlabel('Generation')
# Plot QI score
ax2 = ax1.twinx()
ax2.set_ylim([0, 100])
l2, = ax2.plot(generations, qis, label="Quality Index", linewidth=1.0, color='b')
ax2.set_ylabel("Quality")
plt.legend([l1, l2], ["Average fitness", "Quality Index"])
plt.show()
def qi_all(foldername, increment, num):
generations = [i * increment for i in range(int(num / increment) + 1)]
# Get QI scores for each generation for each repeat
qis_all = []
fitness_all = []
for i in range(10):
qis = get_QI(foldername + str(i), generations)
qis_all.extend(qis)
# Get fitness scores
fitness_file = open(foldername + str(i) + "/fitness.txt", "r")
average_fitness = []
lines = fitness_file.readlines()
fitness_file.close()
for i, line in enumerate(lines):
if i in generations:
average_fitness.append(float(line))
fitness_all.extend(average_fitness)
# Calculate correlation
print("Correlation:", pearsonr(average_fitness, qis))
# Calculate correlation
print("Full Correlation:", pearsonr(fitness_all, qis_all))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Conduct Analysis of Simulation')
parser.add_argument('type',
type=str,
choices=[
'average', 'ten', 'ten-language', 'single', 'language', 'qi', 'qi-all',
'time-average'
],
help='type of graph to display')
parser.add_argument('foldername', type=str, help="where data is stored")
parser.add_argument('-n',
'--num_gen',
action='store',
type=int,
default=2000,
help='number of generations to display')
parser.add_argument('-l',
'--language',
action='store',
type=str,
default="Evolved",
help='language type to display')
parser.add_argument('-i',
'--increment',
action='store',
type=int,
default=100,
help='language increment')
args, unknown = parser.parse_known_args()
#style.use('fivethirtyeight')
style.use('seaborn-bright')
if args.type == "average":
plot_average(args.foldername, args.num_gen)
elif args.type == "ten":
plot_ten(args.foldername, args.num_gen)
elif args.type == "single":
plot_one(args.foldername, args.num_gen)
elif args.type == "ten-language":
plot_ten_language(args.foldername, args.language, args.num_gen)
elif args.type == "language":
plot_language_distributions_bar(args.foldername, args.increment, args.num_gen)
elif args.type == "qi":
frequency_and_qi(args.foldername, args.increment, args.num_gen)
elif args.type == "qi-all":
qi_all(args.foldername, args.increment, args.num_gen)
elif args.type == "time-average":
time_average(args.foldername, args.num_gen)
|
180d0d036d95e7129f6db72bf8116eb6079cd6f5 | AIHackerTest/Gouwal_Py101-004 | /Chap0/project/ex09.py | 681 | 4 | 4 | # Advanced Task
from random import randint
data = randint(0,21)
guess = int(input("> "))
if guess > data:
print ("What you guess is bigger")
elif guess < data:
print ("What you guess is smaller")
else:
print ("Excellent, you are right")
i = 0
while guess != data and i < 9:
times = 9 - i
print ("You only have %d times" % times)
i+=1
guess = int(input("> "))
if guess > data:
print ("What you guess is bigger")
elif guess < data:
print ("What you guess is smaller")
else:
print ("Excellent, you are right")
if guess != data:
print ("Sorry, you are so....")
print ("And the answer is %d" % data)
|
fa292c7008d58f6b294cce00b87a642cd18a8e87 | AIHackerTest/Gouwal_Py101-004 | /Chap0/project/ex05.py | 586 | 3.828125 | 4 | # Tase5 Previous 19
def cheese_and_cracker(cheese_count, boxes_of_crackers):
print("You have %d chesses!" % cheese_count) #when I use %d, it always have a warning"TypeError: %d format: a number is required, not str"
print("You have %d boxes of crackers!" % boxes_of_crackers)
print("Man that's enough for a party!")
print("Get a blanket. \n")
print ("We can just give the function numbers directly")
#cheese_and_cracker(input("We have cheese "), input("We have crackers "))
cheese_and_cracker(int(input("We have cheese ")), int(input("We have crackers "))) # resovled
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.