blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5f0e99461a268874a31f97da98f754bba2a2d9ff | peaisge/NN_digit | /predict.py | 542 | 3.59375 | 4 | import numpy as np
from sigmoid import sigmoid
def predict(Theta, X):
# Takes as input a number of instances and the network learned variables
# Returns a vector of the predicted labels for each one of the instances
# Useful values
m = X.shape[0]
num_layers = len(Theta) + 1
p = np.zeros((1, m))
for i in range(m):
a = X[i, :]
for h in range(num_layers - 1):
a = np.append([1], a)
a = sigmoid(np.dot(a, Theta[h].T))
p[0][i] = np.argmax(a)
return p
|
c39d3eb3bc32fd08299399b87df61ffcb1ca54d3 | Parkhyunseo/PS | /baekjoon/algo_1652.py | 582 | 3.546875 | 4 | N = int(input())
room = []
for i in range(N):
room.append(list(input()))
horizontal = 0
vertical = 0
for i in range(N):
count = 0
for j in range(N):
if room[j][i] == 'X':
count = 0
else:
count += 1
if count == 2:
horizontal += 1
for i in range(N):
count = 0
for j in range(N):
if room[i][j] == 'X':
count = 0
else:
count += 1
if count == 2:
vertical += 1
print(vertical, horizontal)
|
ce25717acb4a7f3a43386d75dd0c883d78490b31 | gjmingsg/Code | /leetcode/Remove Duplicates from Sorted List.py | 933 | 3.828125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def show(self):
t = self
st = ''
while t!=None:
st = st + '%d->' %t.val
t = t.next
print st
class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
t = head
pre = head
s = set()
while t!=None:
if s.__contains__(t.val):
pre.next = t.next
del t
t = pre.next
else:
s.add(t.val)
pre = t
t = t.next
return head
c = Solution()
l = ListNode(1)
t = l
t.next = ListNode(1)
t = t.next
t.next = ListNode(2)
t = t.next
t.next = ListNode(3)
t = t.next
t.next = ListNode(3)
l.show()
c.deleteDuplicates(l).show()
c.deleteDuplicates(None).show()
|
a4afcd31bd0b346a88fa467ecb8ba9efee9c3eb8 | Blacky91/info175_JuanContreras | /cen-pol.py | 296 | 3.609375 | 4 |
if __name__== "__main__":
cenit = "cenit"
polar = "polar"
cad = raw_input("Palabra a encriptar: ")
for i in range(len(cad)):
if cad[i] in polar:
print cenit[polar.find(cad[i])]
elif cad[i] in cenit:
print polar[cenit.find(cad[i])]
|
ad0c7d5c30fe2f1b68a93c63859431fc7ba38deb | vivek3141/RandomProblems | /Python Projects/Lib cataloging.py | 2,834 | 3.90625 | 4 | #Project 2 : Library Book Stocking System
#A library is in the process of updating its system and cataloguing all the books. The following
#coding scheme is followed. Code is a 5 digit number.
#Code starts with 1 – Magazine
#Code starts with 2 – Fiction
#Code starts with 3 – Non Fiction
#Code starts with 4 – Reference
#Code starts with 5 – Regional, non English
#Accept the code number, and if code does not start with 1-5 display invalid message and go
#back to accepting code. If code number is not 5 digits do the same.
#If the code number entered is 99999 stop accepting book codes.
#In the end print a report
# Report of Number of each type of book entered
#Number of Magazines: 34
#Number of Fiction books: 20
#Number of Non-Fiction books: 2
#Number of Reference books:0
#Number of Regional books:12
#Thank you for using our Book Stocking System
#author:Vivek Verma
#17.10.14
h1 = 0
h2 = 0
h3 = 0
h4 = 0
h5 = 0
i = 0
while(True):
print("A library is in the process of updating its system and cataloguing all the books. The following")
print("coding scheme is followed. Code is a 5 digit number.")
print("\t\nCode starts with 1 – Magazine")
print("\tCode starts with 2 – Fiction")
print("\tCode starts with 3 – Non Fiction")
print("\tCode starts with 4 – Reference")
print("\tCode starts with 5 – Regional, non English")
while(True):
cde = int(input("Enter your code:"))
if(cde == 99999):
break
cde = cde//10000
if(cde == 1):
a = input("Press any key to continiue:")
h1 = h1 + 1
break
print("You have selected a book from the category-Magazines")
elif(cde == 2):
a = input("Press any key to continiue:")
h2 = h2 + 1
print("You have selected a book from the category-Fiction")
break
elif(cde == 3):
a = input("Press any key to continiue:")
h3 = h3 + 1
print("You have selected a book from the category-Non-Fiction")
break
elif(cde == 4):
a = input("Press any key to continiue:")
h4 = h4 + 1
print("You have selected a book from the category-Reference")
break
elif(cde == 5):
a = input("Press any key to continiue:")
h5 = h5 + 1
print("You have selected a book from the category-Regional, non English")
break
else:
print("Invalid Input")
continue
print("\n"*30)
print("\nReport of Number of each type of book entered")
print("\tNumber of Magazines:",h1)
print("\tNumber of Fiction books:",h2)
print("\tNumber of Non-Fiction books:",h3)
print("\tNumber of Reference books:",h4)
print("\tNumber of Regional books:",h5)
|
29fb5c6c721aa8b830e96a4e63fbf65583e87d36 | tpracser/PracserTamas-GF-cuccok | /week-03/day-1/07a.py | 140 | 3.9375 | 4 | g1 = 123
g2 = 345
# tell if g1 is bigger than g2
if g1 > g2:
print("g1 is bigger than g2")
else:
print("g1 is not bigger than g2")
|
55453b6cefa879cc7a3db4731152640ad3b1fe8c | bradmdesign/PY4E-UoM | /Course 4 - Databases/emaildb.py | 1,146 | 3.6875 | 4 | import sqlite3
conn = sqlite3.connect('emaildb.sqlite')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Counts')
cur.execute('CREATE TABLE Counts (email TEXT, count INTEGER)')
fname = input('Enter File Name: ')
if (len(fname)<1):
fname = 'mbox-short.txt'
fh = open(fname)
for line in fh:
if not line.startswith('From: '): #This is a great line of code, remember it. If it doesn't start with this, skip it.
continue
pieces = line.split()
email=pieces[1]
cur.execute('SELECT count FROM Counts WHERE email = ?', (email,))
row = cur.fetchone() #All information found in the database that fetches the above info
if row is None:
cur.execute('''INSERT INTO Counts (email, count) VALUES (?, 1)''', (email,))
else:
cur.execute('UPDATE Counts SET count = count + 1 WHERE email = ?', (email,))
conn.commit()
# https://www.sqlite.org/lang_select.html
sqlstr = 'SELECT email, count FROM Counts ORDER BY count DESC LIMIT 5'
for row in cur.execute(sqlstr):
print(row[0],row[1]) #In the explainer video he converted to str but I didn't see it as necessary so I removed.
cur.close() |
d585e16b37eee153b4ff110de015d65968843426 | Loran425/2018AdventOfCode | /Day_2/Part_1.py | 570 | 3.5 | 4 | from collections import Counter
def main():
twos = 0
threes = 0
with open("./input.txt", mode="r") as input:
for line in input:
c = Counter(line)
two = three = False
for char in c:
if not two and c[char] == 2:
two = True
if not three and c[char] == 3:
three = True
if two:
twos += 1
if three:
threes += 1
print(twos, threes, twos * threes)
if __name__ == "__main__":
main()
|
32b4865ac119135149bbd940f4388ccef6b1d907 | sandblue/Advent_of_code_2020 | /05/adven2020_5.py | 3,786 | 3.609375 | 4 | import sys
import math
def find_highest_seat_id(path):
file = open(path)
highest_id = 0
for line in file:
current_line_value = int(find_id(str(line)))
if(int(highest_id) < int(current_line_value)):
highest_id = int(current_line_value)
file.close()
print(highest_id)
return
# triple loop
def find_missing_seat_triple_loop(path):
file = open(path)
all_value = {}
for line in file:
current_line_value = int(find_id(str(line)))
all_value[current_line_value] = current_line_value
file.close()
sorted_val = dict(sorted(all_value.items(), key=lambda item: item[1]))
prev = None
for i in sorted_val:
if(prev is None):
prev = int(i)
else:
if(prev+1 != int(sorted_val[i])):
print(i-1)
break
else:
prev = int(i)
return
# double loop
def find_missing_seat_double_loop(path):
file = open(path)
all_value = {}
highest_id = 0
lowest_id = None
for line in file:
current_line_value = int(find_id(str(line)))
all_value[current_line_value] = current_line_value
if(int(highest_id) < int(current_line_value)):
highest_id = int(current_line_value)
if(lowest_id is None):
lowest_id = current_line_value
else:
if(int(current_line_value) < int(lowest_id)):
lowest_id = int(current_line_value)
file.close()
for i in range(lowest_id, highest_id, 1):
if(i not in all_value):
print(i)
return i
return
#find number that not found -1 +1
def find_un_near_seat(path):
file = open(path)
found = {}
not_found = {}
for line in file:
current_line_value = int(line)
flag = False
# xyx z xyx --> result = z
if(current_line_value + 1 in found or current_line_value - 1 in found):
found[current_line_value] = current_line_value
flag = True
if(current_line_value + 1 in not_found):
found[current_line_value + 1] = not_found.pop(current_line_value + 1)
found[current_line_value] = current_line_value
flag = True
if(current_line_value - 1 in not_found ):
found[current_line_value - 1] = not_found.pop(current_line_value - 1)
found[current_line_value] = current_line_value
flag = True
if(not flag):
not_found[current_line_value] = current_line_value
file.close()
print(not_found)
return
def find_id(code):
code = code.replace("\n", "")
row_code_init = code[:-3]
column_code_init = code[-3:]
row_id = find_row(row_code_init, 0, 127)
column_id = find_column(column_code_init, 0, 7)
return int(row_id * 8) + int(column_id)
def find_row(column_code, min, max):
if(len(column_code) > 1):
if(column_code[0] == "F"):
max = max - math.floor((max - min)/2) - 1
else:
min = min + math.floor((max - min)/2) + 1
return find_row(column_code[1:], min , max)
else:
if(column_code[0] == "F"):
return min
else:
return max
def find_column(row_code, min, max):
if(len(row_code) > 1):
if(row_code[0] == "L"):
max = max - math.floor((max - min)/2) - 1
else:
min = min + math.floor((max - min)/2) + 1
return find_column(row_code[1:], min , max)
else:
if(row_code[0] == "L"):
return min
else:
return max
#find_highest_seat_id(str(sys.argv[1]))
find_missing_seat_double_loop(str(sys.argv[1]))
#find_missing_seat_triple_loop(str(sys.argv[1])) |
fafbd90ea020b9ed84e0d585bb0d400516060f19 | Chen-Yiyang/CompetitiveProgramming | /Lesson1/01_01_Fibonacci_DP.py | 351 | 4.21875 | 4 | # Fibonacci using Recursion
# by Yiyang 17_01_18
fiboValues = {1:1, 2:1}
def _Fibonacci(N):
if N in fiboValues:
return fiboValues[N]
else:
fiboValues[N] = _Fibonacci(N-1) + _Fibonacci(N-2)
return fiboValues[N]
N = int(input("Enter an integer: "))
for i in range(1, N+1+1):
print(i, _Fibonacci(i))
|
27ee889ee5ee7065c11f401ae0f3f21920227239 | sweetysweets/Algorithm-Python | /microsoft/4.py | 587 | 3.8125 | 4 | class Node:
def __init__(self,v):
self.val = v
self.next = None
def set_next(self,next):
self.next = next
def get_length(node):
if node is None:
return 0
p = node
q = node
while p.next is not None and q.next is not None and q.next.next is not None:
p = p.next
q = q.next.next
if p == q:
break
if p!=q or p == node : ##无环
return 0
length = 1
q = p.next
while q!=p:
q = q.next
length += 1
return length
if __name__ == '__main__':
pass |
2a85119097060a6b215c3fee2a5555320a4b3983 | Shimon-W/bioprojekt | /Sequence.py | 9,698 | 3.875 | 4 | """This module contains classes that represent sequences of a 4x4 tile."""
import random
class Sequence(list):
"""
Represents a DNA sequence.
Enhances String class with useful methods for sequences.
"""
def get_part(self, part):
"""
Get specific numbered part of sequence.
For use in specific class (e.g. SequenceC, SequenceNE) only.
If there is no number, use "head" and "tail".
Args:
part (int or string): numbered part of sequence or "head"/"tail"
"""
assert part in self._partition.keys()
start, end = self._partition[part]
return Sequence(self[start:end])
def set_part(self, part, new_seq):
"""
Set specific numbered part of sequence.
For use in specific class (e.g. SequenceC, SequenceNE) only.
If there is no number, use "head" and "tail".
Args:
part (int or string): numbered part of sequence or "head"/"tail"
new_seq (string): new sequence
"""
assert part in self._partition.keys()
start, end = self._partition[part]
assert len(new_seq) == end-start
self[start:end] = new_seq
def rev_comp(self):
"""
Calculate the reverse complement of the sequence.
Returns:
string: reverse complement of the sequence
"""
complements = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
return Sequence(map(lambda b: complements[b], self[::-1]))
def check_q_uniqueness(self, q):
"""
Check, if the sequence is q-unique.
Returns a tuple (a, b) where a and b are indices of q-grams which
violate against the conditions of q-uniqueness:
1. Each q-gram is unique in the sequence.
2. The reverse complement is not in the sequence.
3. There is no reverse complement in the sequence. (a = b)
If the sequence is q-unique, a and b are None.
Args:
q (int): positive number for q-uniqueness
Returns:
(int, int): indices of q-grams that violate agains q-uniqueness
"""
assert type(q) is int
assert q > 0
qgrams = dict()
for i in range(0, len(self)-q+1):
qgram = self[i:i+q]
qgram_rc = reverse_complement(qgram)
if qgram in qgrams.keys():
return (qgrams[qgram], i)
qgrams[qgram] = i
if qgram_rc in qgrams.keys():
return (qgrams[qgram_rc], i)
qgrams[qgram_rc] = i
return (None, None)
def melting_temperature(self):
"""
Calculate melting temperature of the seqence.
Returns the melting temperature of sequence with following formular:
tm = 2*(#AT) + 4*(#GC)
Returns:
float: melting temperature of subsequence
"""
base_count = {base:self.count(base) for base in "ATGC"}
return 2*(base_count["A"] + base_count["T"]) + 4*(base_count["G"] + base_count["C"])
def base_amounts_absolute(self):
"""
Calculate the absolute amount of each base in the sequence.
Returns:
dict(char -> int): absolute amount of each base
"""
return {b:self.count(b) for b in 'ATGC'}
def base_amounts_relative(self):
"""
Calculate the relative amount of each base in the sequence.
Returns:
dict(char -> float): relative amount of each base
"""
return {b:self.count(b)/len(self) for b in 'ATGC'}
@classmethod
def from_random(cls, length, freqs={b:1 for b in "ATGC"}):
"""
Generate a random sequence.
Generate a random sequence with given base frequencies.
Args:
length (int): lengths of the sequence
freq (dict(char -> float)): frequencies of the bases (default all 1)
Returns:
Sequence: random sequence
"""
bounds = []
maxbound = 0
for base, freq in freqs.items():
maxbound += freq
bounds.append((base, maxbound))
def get_base(value):
for base, bound in bounds:
if value < bound:
return base
seq = ""
for i in range(0, length):
seq += get_base(random.uniform(0, maxbound))
return cls(seq)
def __str__(self):
"""Get string representation of sequence."""
return ''.join(self)
def __repr__(self):
"""Get string representation of sequence."""
return str(self)
class SequenceC(Sequence):
"""Represents the center sequence of a 4x4 tile."""
length = 100
_partition = {
"head": (None,5),
12: (5,15),
7: (19,30),
9: (30,40),
6: (44,55),
13: (55,65),
8: (69,80),
11: (80,90),
"tail": (94,None)
}
def get_part(self, part):
"""See Sequence.get_part."""
# special case for 4 because end of C is inside of 4
if 4 == part:
return super().get_part("tail") + super().get_part("head")
else:
return super().get_part(part)
@staticmethod
def from_nw_ne_se_sw(nw, ne, se, sw):
"""
Generate from the four outer sequences of 4x4 tile.
Args:
nw (SequenceNW): nw sequence of 4x4 tile
ne (SequenceNE): nw sequence of 4x4 tile
se (SequenceSE): nw sequence of 4x4 tile
sw (SequenceSW): nw sequence of 4x4 tile
Returns:
SequenceC
"""
assert type(nw) is SequenceNW
assert type(ne) is SequenceNE
assert type(se) is SequenceSE
assert type(sw) is SequenceSW
nw_rc = nw.rev_comp()
ne_rc = ne.rev_comp()
se_rc = se.rev_comp()
sw_rc = sw.rev_comp()
seq = ne_rc[29:34] + nw_rc[8:18] + list('TTTT')
seq += nw_rc[18:29] + sw_rc[8:18] + list('TTTT')
seq += sw_rc[18:29] + se_rc[13:23] + list('TTTT')
seq += se_rc[23:34] + ne_rc[13:23] + list('TTTT')
seq += ne_rc[23:29]
return SequenceC(seq)
class SequenceN(Sequence):
"""Represents the northern sequence of a 4x4 tile."""
length = 26
_partition = {
"tail": (None,5),
10: (5,13),
15: (13,21),
"head": (21,None)
}
@staticmethod
def from_nw_ne_random(nw, ne, freq={b:1 for b in "ATGC"}):
"""Generate new N-sequence from NW, NE and random head/tail."""
n_seq = SequenceN.from_random(SequenceN.length, freq)
n_seq.set_part(10, nw.get_part(10).rev_comp())
n_seq.set_part(15, ne.get_part(15).rev_comp())
return n_seq
class SequenceE(Sequence):
"""Represents the east sequence of a 4x4 tile."""
length = 36
_partition = {
"tail": (None,5),
5: (5,18),
2: (18,31),
"head": (31,None)
}
@staticmethod
def from_ne_se_random(ne, se, freq={b:1 for b in "ATGC"}):
"""Generate new E-sequence from NE, SE and random head/tail."""
e_seq = SequenceE.from_random(SequenceE.length, freq)
e_seq.set_part(5, ne.get_part(5).rev_comp())
e_seq.set_part(2, se.get_part(2).rev_comp())
return e_seq
class SequenceS(Sequence):
"""Represents the south sequence of a 4x4 tile."""
length = 36
_partition = {
"tail": (None,5),
3: (5,18),
1: (18,31),
"head": (31,None)
}
@staticmethod
def from_se_sw_random(se, sw, freq={b:1 for b in "ATGC"}):
"""Generate new S-sequence from SE, SW and random head/tail."""
s_seq = SequenceS.from_random(SequenceS.length, freq)
s_seq.set_part(3, se.get_part(3).rev_comp())
s_seq.set_part(1, sw.get_part(1).rev_comp())
return s_seq
class SequenceW(Sequence):
"""Represents the western sequence of a 4x4 tile."""
length = 26
_partition = {
"tail": (None,5),
16: (5,13),
14: (13,21),
"head": (21,None)
}
@staticmethod
def from_sw_nw_random(sw, nw, freq={b:1 for b in "ATGC"}):
"""Generate new N-sequence from NW, NE and random head/tail."""
w_seq = SequenceW.from_random(SequenceW.length, freq)
w_seq.set_part(16, sw.get_part(16).rev_comp())
w_seq.set_part(14, nw.get_part(14).rev_comp())
return w_seq
class SequenceOuter(Sequence):
"""Represents an outer sequence of a 4x4 tile."""
length = 42
@classmethod
def from_random(cls, freq={b:1 for b in "ATGC"}):
"""
Generate a random sequence.
For details see Sequence.from_random.
"""
return cls(Sequence.from_random(cls.length, freq))
class SequenceNW(SequenceOuter):
"""Represents the northern west outer sequence of a 4x4 tile."""
length = 37
_partition = {
14: (None,8),
7: (8,19),
12: (19,29),
10: (29,None)
}
class SequenceNE(SequenceOuter):
"""Represents the northern east outer sequence of a 4x4 tile."""
length = 42
_partition = {
15: (None,8),
4: (8,19),
11: (19,29),
5: (29,None)
}
class SequenceSE(SequenceOuter):
"""Represents the south east outer sequence of a 4x4 tile."""
length = 47
_partition = {
2: (None,13),
8: (13,24),
13: (24,34),
3: (34,None)
}
class SequenceSW(SequenceOuter):
"""Represents the south west outer sequence of a 4x4 tile."""
length = 42
_partition = {
1: (None,13),
6: (13,24),
9: (24,34),
16: (34,None)
}
|
570d3e92d657ade7c8b7a2c3c9ad09d3b35f1f1e | TonyXia2001/ICS3UI | /ICS3UI/palindrome.py | 579 | 4.125 | 4 | '''
Tony(Tanglin) Xia
4/9/2018
Palindrome
take an input, detect whether it's a palindrome, return True or False
'''
def isPalindrome(userInput):
tempList = list(userInput)
for i in range(len(tempList)): tempList[i] = tempList[i].upper()
if tempList == tempList[::-1]: return True
else: return False
userInput = input("Please type in your word:")
while userInput.upper() != "END":
Itis = isPalindrome(userInput)
print(userInput + " is a palindrome") if Itis else print(userInput + " is not a palindrome")
userInput = input("Please type in your word:")
|
0b4d29ea0d9ff9758dfce1d8f8369df88511090a | daks001/py102 | /5/Lab5b_a.py | 835 | 4.1875 | 4 | # By submitting this assignment, I agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
#
# Name: DAKSHIKA SRIVASTAVA
# Section: 532
# Assignment: LAB 5b ACTIVITY a
# Date: 26 SEPTEMBER 2019
print("This program prints Collatz Conjecture sequence upto 1")
#taking input for n
n = int(input("Enter a number: "))
count = 0 #to count the number of iterations
#while loop to calculate the consecutive terms
print(n, end=', ')
while (n>1):
# print(n, end=', ')
#checking if n is even or odd
if n%2 == 0: #even
n = n // 2
count += 1
print(n, end=', ')
else: #odd
n = (3 * n) + 1
count += 1
print(n, end=', ')
print("The operation took", count, "number of iterations") |
555273eccb98de31ee19693fe50a9e36ab056cce | bvick/RubikPhotoSolve | /Rcube.py | 19,468 | 3.875 | 4 | '''
Created on Oct 30, 2017
@author: bob vick
These are structures and functions for managing a Rubik's Cube. A cube is an object of class Rcube.
Terminology:
side - one of the 6 faces of a cube.
facet - one of the 54 (9 for each side) surfaces. (Lars Petrus calls them "stickers")
corner - one of the 8 corner pieces, each having 3 facets
edge - one of the 12 pieces between corners, each having 2 facets
center- the piece in the middle of each side, having 1 facet
turn- usually a turning of a single side, but can also be a reorientation of the cube, about a side (or better said, about an axis normal to a side)
'''
import numpy as np
from util import *
import copy
# the side turns are done by multiplying the location of each affected facet by a rotation matrix.
# this creates a matrix for a particular axis and rotation amount
def rotMat(axis,amt):
amt=amt%4
use=np.array([[1,2],[0,2],[0,1]],np.int8)
# 2x2 's for each turn amount. these get expanded to 3x3 depending on axis of rotation
r22 = np.array([
[[1,0],[0,1]],
[[0,1],[-1,0]],
[[-1,0],[0,-1]],
[[0,-1],[1,0]]],np.int8)
rmat=np.identity(3,np.int8)
for i in [0,1]:
for j in [0,1]:
rmat[use[axis,i],use[axis,j]] = r22[amt,i,j]
return(rmat)
rotMats=np.array([[rotMat(j,i) for i in range(4)] for j in range(3)],np.int8)
class Rcube(object):
'''
classdocs
'''
'''
STRUCTURE
3 ways of addressing facets:
addresses (adr) view the cube centered, with x,y,z in +/-[0,1,2]:
a +/- 2 for the side coordinate , otherwise location on side
These are mainly used for rotations (done by matrix multiplication) and rendering
side,pos (referred to as spos or loc) is another scheme. sides are numbered 0-5: UFRBLD in standard parlance.
pos is 0-8 where 8 is center facet, 0 is facet closest to the
lower front left vertex, and the rest are numbered clockwise from 0.
This scheme is the primary scheme for solving the cube
for simplification purposes facets are numbered sequentially. This is just a compression
of the side,pos scheme into a single number.
turns is a list of turn elements [side,amt,slice] where amt is 0-3 clockwise rotations
and slice is 1 for normal side turn and 3 for turning entire cube about a side
redTurns reduce turns by compressing or eliminating consecutive turns of the same
side and also normalize away whole cube reorientations, so these are the actual side turns
required to solve the cube.
'''
facetHomes=np.array([[i,j] for i in range(6) for j in range(9)],np.int8)
facetColors=np.array([[i+1]*9 for i in range(6)],np.int8).flatten()
oppositeSide=np.array([5,3,4,1,2,0])
@staticmethod
def invertFloc(floc):
fal=np.empty([6,9],np.int8)
for i in range(54):
s,p=floc[i]
fal[s,p]=i
return(fal)
def __init__(self, startingFacetLoc=facetHomes):
# facetLoc is the current location of a facet, the latter identified by it's "home" location
self.facetLoc = np.copy(startingFacetLoc)
# inverse of above, i.e. what facet is at a given location
self.facetAtLoc=Rcube.invertFloc(self.facetLoc)
# list of all turns that have been applied to a cube since it's initial configuration
self.turns=[ ]
# reduced turns are the above turns, but ignoring reorientations and reducing sequential
# turns of the same side down to 1 or possible zero net turns
self.redTurns= [ ]
# each phase in a solution may append len(redTurns) here. Used in rendering phase-by-phase
self.phase=[ ]
self.rawPhase=[ ]
# also used in rendering. Identifies how much pausing to do
self.replayLevel=0
# for debugging. If true, output each turn as it is done
self.printRot=False
def copy(self):
newCube=Rcube(self.facetLoc)
newCube.turns=copy.deepcopy(self.turns)
newCube.redTurns=copy.deepcopy(self.redTurns)
newCube.phase=copy.deepcopy(self.phase)
newCube.replayLevel = self.replayLevel
newCube.printRot=self.printRot
return(newCube)
# make a cube with random turns applied to it
@staticmethod
def mkRandom(turns=30):
a=Rcube()
for _ in range(turns):
f=np.random.randint(0,6)
d=np.random.randint(1,4)
a.rotateSide(f,d)
a.turns= [ ]
a.redTurns=[ ]
return(a)
def markPhase(self):
self.phase.append(len(self.redTurns))
self.rawphase.append(len(self.turns))
'''
ADDRESS MANIPULATION
'''
@staticmethod
def facetHome(facet):
return(facet//9,facet%9)
@staticmethod
def home2facet(spos):
return(spos[0]*9+spos[1])
@staticmethod
def facetSide(facet):
return(facet//9)
@staticmethod
def facetPos(facet):
return(facet%9)
@staticmethod
def adr2spos(adr):
side,nonSide=Rcube.adrSplitSide(adr)
pos=Rcube.pos2xy(side).index(list(nonSide))
return(side,pos)
@staticmethod
def spos2adr(spos):
side,pos=spos
xy=Rcube.pos2xy(side)[pos]
ipoint=[2,1,0,1,0,2][side]
fval=[2,-2,2,2,-2,-2][side]
#print("f2",side,pos,xy,ipoint,fval)
xy.insert(ipoint,fval)
#print("f2",side,pos,xy,ipoint,fval)
return(np.array(xy,np.int8))
@staticmethod
def facet2adr(facet):
return(Rcube.spos2adr(Rcube.facetHome(facet)))
@staticmethod
def adr2facet(adr):
return(Rcube.home2facet(Rcube.adr2spos(adr)))
def homeAdr2cur(self,adr):
facet = Rcube.adr2facet(np.array(adr,np.int8))
nfp=tuple(self.facetLoc[facet])
return(Rcube.spos2adr(nfp))
def curAdr2home(self,adr):
sp = Rcube.adr2spos(np.array(adr,np.int8))
facet=self.facetAtLoc[sp]
return(Rcube.facet2adr(facet))
def sposAtSpos(self,spos):
return(Rcube.facetHome(self.facetAtLoc[spos]))
def sposOfSpos(self,spos):
return(tuple(self.facetLoc[Rcube.home2facet(spos)]))
# returns the side number given an address
@staticmethod
def adrSide(adr):
side=[[4,1,5],[2,3,0]]
coord=np.argmax(abs(adr))
s = (np.sign(adr[coord])+1)//2
return(side[s][coord])
@staticmethod
def adrSplitSide(adr):
return(Rcube.adrSide(adr),np.array([x for x in adr if abs(x)!=2],np.int8))
@staticmethod
def joinSide(side,xy):
sideZ=[2,-2,2,2,-2,-2][side]
if side in [2,4]: return([sideZ,xy[0],xy[1]])
elif side in [1,3]: return([xy[0],sideZ,xy[1]])
else: return(np.array([xy[0],xy[1],sideZ],np.int8))
@staticmethod
def sliceDist(toAdr,fromAdr): # assumes common side
_,toWW=Rcube.adrSplitSide(toAdr)
_,fromWW=Rcube.adrSplitSide(fromAdr)
rmat=np.array([[0,-1],[1,0]],np.int8)
r1=fromWW
for i in [1,2,3]:
r1=np.matmul(rmat,r1)
if np.array_equal(r1,toWW): return(i)
return(None)
@staticmethod
def pos2xy(side):
if side <3: return([[-1,-1],[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[0,0]])
else: return([[-1,-1],[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[0,0]])
# how are positions on side0 rotated if side0,side1 are now at 0, 1
# 9 for impossible pairs
posRot0=[
[9,0,2,4,6,9],
[4,9,2,9,6,0],
[4,6,9,2,9,0],
[2,9,4,9,0,6],
[2,0,9,4,9,6],
[9,6,4,2,0,9]
]
posRot1=[
[9,0,0,6,6,9],
[4,9,2,9,4,2],
[6,6,9,0,9,0],
[0,9,6,9,0,6],
[2,2,9,4,9,4],
[9,4,4,2,2,9]
]
@staticmethod
def side2center(side):
return(Rcube.spos2adr((side,8)))
def sideAdr(self,side):
cside,_=Rcube.adr2spos(self.homeAdr2cur(Rcube.side2center(side)))
return(cside)
def sideAtSide(self,side):
cside,_=Rcube.adr2spos(self.curAdr2home(Rcube.side2center(side)))
return(cside)
@staticmethod
def edgeOtherLoc(spos):
adr=Rcube.spos2adr(spos)
for i in range(3):
if abs(adr[i])==1: adr[i] = 2*adr[i]
elif abs(adr[i])==2: adr[i] = adr[i]//2
return(Rcube.adr2spos(adr))
@staticmethod
def edgeOtherFacet(facet):
adr=Rcube.facet2adr(facet)
for i in range(3):
if abs(adr[i])==1: adr[i] = 2*adr[i]
elif abs(adr[i])==2: adr[i] = adr[i]//2
return(Rcube.adr2facet(adr))
@staticmethod
def cornerOtherLocs(spos):
adr=Rcube.spos2adr(spos)
aadr=abs(adr)
sadr=np.sign(adr)
rsign=np.prod(sadr)
return(Rcube.adr2spos(np.roll(aadr,-rsign)*sadr),Rcube.adr2spos(np.roll(aadr,rsign)*sadr))
@staticmethod
def cornerOtherFacets(facet):
adr=Rcube.facet2adr(facet)
aadr=abs(adr)
sadr=np.sign(adr)
rsign=np.prod(sadr)
return(Rcube.adr2facet(np.roll(aadr,-rsign)*sadr),Rcube.adr2facet(np.roll(aadr,rsign)*sadr))
# for corner piece of facet return other facet of corner that is on side
@staticmethod
def cornerSideLoc(spos,side):
if spos[0]==side: return(spos)
for loc in Rcube.cornerOtherLocs(spos):
# printvars("loc","spos")
if loc[0]==side: return(loc)
return(None)
@staticmethod
def cornerSideFacet(facet,side):
if Rcube.facetHome(facet)[0]==side: return(facet)
for f in Rcube.cornerOtherFacets(facet):
if Rcube.facetHome(f)[0]==side: return(f)
return(None)
# 3 sides of a corner piece, and facets between them clockwise
@staticmethod
def cornerSidesPlus(cfHome):
cfHome=np.array(cfHome)
signs=np.sign(cfHome)
rotdir = -np.sign(np.prod(signs))
side0,_ = Rcube.adr2spos(cfHome)
cfAbs=np.abs(cfHome)
side1,_ = Rcube.adr2spos(signs*np.roll(cfAbs,rotdir))
center1=np.array(Rcube.side2center(side1))
side2,_= Rcube.adr2spos(signs*np.roll(cfAbs,2*rotdir))
center2=np.array(Rcube.side2center(side2))
facet1=center1+center2//2
facet2=center2+center1//2
return(side0,side1,side2,facet1,facet2)
#facet on side1 of corner between 3 sides
def side3facet(self,side1,side2,side3):
#print("faf",side1,cube.sideAtSide(side1),side2,cube.sideAtSide(side2),side3,cube.sideAtSide(side3))
adr=Rcube.side2center(self.sideAtSide(side1)) + \
Rcube.side2center(self.sideAtSide(side2))//2 + \
Rcube.side2center(self.sideAtSide(side3))//2
return(Rcube.adr2facet(adr))
#facet on side1 of edge between side1 and side2
def side2facet(self,side1,side2):
adr=Rcube.side2center(self.sideAtSide(side1)) +\
Rcube.side2center(self.sideAtSide(side2))//2
return(Rcube.adr2facet(adr))
# facets of corner between 3 sides
def side3facets(self,side1,side2,side3):
sides=[side1,side2,side3]
facets=[ ]
for i in range(3):
rsides=tuple(sides[i:]+sides[:i])
facets.append(self.side3facet(*rsides))
return(facets)
# the other facets of edges on side
# i.e. those edge facets that also move when a side is turned
@staticmethod
def attachedEdgeFacets(side):
def listRot(l,r):
return(l[-r:]+l[:-r])
center=Rcube.side2center(side)
k = np.argwhere(abs(center)==2)[0][0]
off=center[k]//2
radr=np.array(list(map(lambda x: x[-k:]+x[:-k], [[off,0,-2],[off,0,2],[off,-2,0],[off,2,0]])),np.int8)
facets = [Rcube.adr2facet(adr) for adr in radr]
return(facets)
@staticmethod
def attachedEdgeLocs(side):
def listRot(l,r):
return(l[-r:]+l[:-r])
center=Rcube.side2center(side)
k = np.argwhere(abs(center)==2)[0][0]
off=center[k]//2
radr=np.array(list(map(lambda x: x[-k:]+x[:-k], [[off,0,-2],[off,0,2],[off,-2,0],[off,2,0]])),np.int8)
sps = [Rcube.adr2spos(adr) for adr in radr]
return(sps)
# all facets not on side that also move when side is turned
@staticmethod
def attachedFacets(side):
def listRot(l,r):
return(l[-r:]+l[:-r])
center=Rcube.side2center(side)
k = np.argwhere(abs(center)==2)[0][0]
off=center[k]//2
adr=[[off,i,-2] for i in [-1,0,1]]+[[off,i,2] for i in [-1,0,1]]+[[off,-2,i] for i in [-1,0,1]]+[[off,2,i] for i in [-1,0,1]]
radr=np.array(list(map(lambda x: x[-k:]+x[:-k], adr)),np.int8)
facets = [Rcube.adr2facet(adr) for adr in radr]
return(facets)
# facets of corners of side rotated CW
@staticmethod
def attachedCorner1Facets(side):
return([Rcube.cornerFacets((side,i))[0] for i in [0,2,4,6]])
# facets of corners of side rotated CCW
@staticmethod
def attachedCorner2Facets(side):
return([Rcube.cornerFacets((side,i))[1] for i in [0,2,4,6]])
# rotation is amt*90 degrees clockwise about axis(0,1,2=x,y,z resp)
# slices is 1 for just side, 2(not implemented) for side and center slice, 3 for whole cube
def rotateSide(self,side,amt,slices=1):
amt=amt%4
if self.printRot: print("rotating",side,amt,"R" if slices==3 else "")
if amt==0: return()
gt = [3,.5,-.5,-3][slices] # identifies which facets are moved
sideSign=[1,-1,1,1,-1,-1][side]
rotSign=[1,1,1,-1,-1,-1][side]
axis=[2,1,0,1,0,2][side]
self.turns.append([side,amt,slices])
# normalized turns - compresses away consecutive turns of same side, and
# adjusts away cube reorientations
if (slices==1):
nSide=self.sideAtSide(side)
if len(self.redTurns)>0 and self.redTurns[-1][0]==nSide:
newAmt=(self.redTurns[-1][1] + amt) %4
if newAmt>0:
self.redTurns[-1][1] =newAmt
else:
self.redTurns.pop()
else:
self.redTurns.append([nSide,amt])
amt = (rotSign*amt)%4
wFacetLoc=np.copy(self.facetLoc)
rotMat=rotMats[axis,amt]
# # the actual turn is done with matrix multiplication on addresses that are affected
for i in range(54):
adr=Rcube.spos2adr(self.facetLoc[i])
if sideSign*adr[axis]>gt:
wFacetLoc[i]=Rcube.adr2spos(np.matmul(rotMat,adr))
self.facetLoc=wFacetLoc
self.facetAtLoc=Rcube.invertFloc(self.facetLoc)
def collapseTurns(self):
cturns=[ ]
for turn in self.turns:
side,amt,slices=turn
if len(cturns)>0 and cturns[-1][0]==side and slices==cturns[-1][2]:
newAmt=(cturns[-1][1] + amt) %4
if newAmt>0:
cturns[-1][1] =newAmt
else:
cturns.pop()
else:
cturns.append(turn)
# print("collapse",len(self.turns),len(cturns),cturns)
return(cturns)
def rotateSides(self,famts):
for fa in famts:
self.rotateSide(*fa)
# rotate a side to get facet from one position to another
def rotatePos(self,side,fromPos,toPos):
self.rotateSide(side,(toPos-fromPos)//2)
return(toPos)
# given facet colors, construct a cube with facet locations that result in those colors
@staticmethod
def cubeFromColors(facetColors):
fLoc=np.copy(Rcube.facetHomes)
cube=Rcube()
for side in range(6):
for pos in range(9):
spos=(side,pos)
sideOfFacet=facetColors[spos]-1
if pos==8:
fLoc[sideOfFacet*9+8]=spos
elif pos in [1,3,5,7]:
eoLoc=Rcube.edgeOtherLoc(spos)
eoSide=facetColors[eoLoc]-1
facet=cube.side2facet(sideOfFacet,eoSide)
fLoc[facet]=spos
else:
coLoc1,coLoc2=Rcube.cornerOtherLocs(spos)
coSide1=facetColors[coLoc1]-1
coSide2=facetColors[coLoc2]-1
facet=cube.side3facet(sideOfFacet,coSide1,coSide2)
fLoc[facet]=spos
#print(repr(fLoc))
cube=Rcube(fLoc)
return(cube)
def printTurns(self,norm=True,colors=True):
if colors: t1map = "WGRBOY"
else: t1map="UFRBLD"
t2map=['','','2',"'"]
if (norm): turns=self.redTurns
else: turns=self.turns
print("\n",len(turns),"turns:")
for i,turn in enumerate(turns):
if i%30 == 0:
print()
print(t1map[turn[0]]+t2map[turn[1]],end=' ')
if i%5==4: print(" ",end="")
print()
@staticmethod
def standardToMoves(s):
s=list("".join(s.split()))
moves=[ ]
sides="UFRBLD"
while len(s)>0:
c = s.pop(0)
side=sides.index(c)
if len(s)>0 and s[0] =="2":
moves.append((side,2))
s.pop(0)
elif len(s)>0 and s[0]=="'":
moves.append((side,3))
s.pop(0)
else:
moves.append((side,1))
return(moves)
@staticmethod
def movesToStandard(moves):
sides="UFRBLD"
marks=["","","2","'"]
s = ""
for i,move in enumerate(moves):
s += sides[move[0]]+marks[move[1]]
if i%5==4: s+=" "
return(s)
@staticmethod
def reverseMoves(mv):
newmv=[]
for m in mv[::-1]:
if len(m)==2: newmv.append((m[0],(-m[1])%4))
else: newmv.append((m[0],(-m[1])%4,(-m[2])%4))
return(newmv)
@staticmethod
def mirrorXmoves(mv):
newmv=[]
for m in mv:
if m[0] in [2,4]: side=6-m[0]
else: side=m[0]
if len(m)==2: newmv.append((side,(-m[1])%4))
else: newmv.append((side,(-m[1])%4,(-m[2])%4))
return(newmv)
@staticmethod
def mirrorYmoves(mv):
newmv=[]
for m in mv:
if m[0] in [1,3]: side=4-m[0]
else: side=m[0]
if len(m)==2: newmv.append((side,(-m[1])%4))
else: newmv.append((side,(-m[1])%4,(-m[2])%4))
return(newmv)
# cube is done if all facets are in the right place.
# flists can be reduced to verify partial completion
def checkDone(self,flists= [
[0,[8,0,1,2,3,4,5,6,7]],
[1,[8,5,6,7,0,1,2,3,4]],
[2,[8,5,6,7,0,1,2,3,4]],
[3,[8,0,1,2,3,4,5,6,7]],
[4,[8,0,1,2,3,4,5,6,7]],
[5,[8,0,1,2,3,4,5,6,7]]
]):
for flist in flists:
side,posList = flist
side0,_=self.sposAtSpos((side,posList[0]))
for pos in posList[1:]:
siden,_=self.sposAtSpos((side,pos))
if siden!=side0:
print("mismatch at[",side,pos,"] ", siden,"should be",side0)
return(False)
return(True)
|
3540775dc510153940e19820363c10cd2ecf653a | ajinkyamukherjee98/ElGamal | /ElGamal.py | 680 | 3.5 | 4 |
import math
import keyword
class elGamal():
print("*************************** Simple Program for EL-GAMAL Algorithm ***************************")
print("Enter the value for q :")
q = int(input())
#print("You have chosen "+str(q))
p = (2*q) + 1
print("The value of P is "+ str(p))
def numInGroup(x):
GList=[]
for i in range (1,x):
res = pow(i,2) % x
GList.append(res)
GList.sort()
newGlist= list((dict.fromkeys(GList))) # To remove duplplicates from the list
print (newGlist)
def message():
print("Please Enter the ")
numInGroup(p)
|
f3d3fba96abb6f7dea148106ab357bbff418a4ae | priyankasomani9/basicpython | /Assignment3/basic3.5_primeNumberInRange.py | 170 | 3.625 | 4 | for number in range(1,10000):
count=0
for i in range(1, number + 1):
if number % i == 0:
count+=1
if count==2:
print(number)
|
944c2896f7305b1c6848b13b2aec8f8c882071fb | silverstorm9/Test_keepass | /main.py | 6,818 | 3.546875 | 4 | import sqlite3
import os
import getpass
def add_entry(mem_conn,mem_cursor):
username = input('Enter a username : ')
if username == None:
return
password = ask_password()
if password == None:
return
query = """INSERT INTO keepass (username,password) VALUES ('{}','{}')""".format(username,password)
mem_cursor.execute(query)
# Save (commit) the changes
mem_conn.commit()
return
def ask_password():
password = getpass.getpass('Password : ')
confirm_password = getpass.getpass('Confirm password : ')
if password == confirm_password:
return password
else:
return None
def close_file(mem_conn,mem_cursor,password,file_name):
# Push data from RAM to the database file .db
conn = sqlite3.connect('{}.db'.format(file_name))
cursor = conn.cursor()
query = """CREATE TABLE IF NOT EXISTS keepass (id integer PRIMARY KEY, username TEXT, password TEXT)"""
# Try to execute the query a table
try:
cursor.execute(query)
# Save (commit) the changes
conn.commit()
except Exception as e:
print('Error:', e)
query = """SELECT * FROM keepass"""
try:
mem_cursor.execute(query)
except Exception as e:
print('Error:', e)
entries = []
for row in mem_cursor:
entries.append((row[0],row[1],row[2]))
query = """INSERT OR REPLACE INTO keepass (id,username,password) VALUES (?,?,?)"""
cursor.executemany(query, entries)
conn.commit()
conn.close()
# Encrypt
os.system('openssl enc -e -aes-256-cbc -iter 10 -in {}.db -out {}.db.enc -pass pass:{}'.format(file_name,file_name,password))
os.system('rm {}.db'.format(file_name))
return
def create_file():
# Create a file
file_name = input('Enter the file name (without extension): ')
if file_name == '':
return
print('Enter a password to encrypt {}.db into {}.db.enc'.format(file_name,file_name))
password = ask_password()
if password == None:
return
conn = sqlite3.connect('{}.db'.format(file_name))
cursor = conn.cursor()
query = """CREATE TABLE IF NOT EXISTS keepass (id integer PRIMARY KEY, username TEXT, password TEXT)"""
# Try to execute the query a table
try:
cursor.execute(query)
# Save (commit) the changes
conn.commit()
# Close the connection with the DB
conn.close()
except Exception as e:
print(e)
# Encrypt the file
try:
os.system('openssl enc -e -aes-256-cbc -iter 10 -in {}.db -out {}.db.enc -pass pass:{}'.format(file_name,file_name,password))
os.system('rm {}.db'.format(file_name)) # delete the .db file to keep only the encrypted file
except Exception as e:
print(e)
return(password,file_name)
def del_entry(mem_conn,mem_cursor):
show_entry(mem_cursor)
id = input('Select the ID to delete an entry : ')
query = """DELETE FROM keepass WHERE id={}""".format(int(id))
mem_cursor.execute(query)
# Save (commit) the changes
mem_conn.commit()
return
def display_menu():
print('Enter help command to show all commands.\n')
def show_help():
buffer = """
COMMANDS:
add Add an entry (username/password) to RAM
close Push RAM's entries into the an encrypted file
create Create an encrypted file
del Del an entry from RAM
exit Exit the program
help Show help
open Pull entries from encrypted file to RAM
show Show RAM's entries
"""
print(buffer)
return
def open_file(mem_conn,mem_cursor):
file_name = input('Enter the file name (without extension) : ')
if file_name == '':
return
print('Enter a password to decrypt {}.db.enc '.format(file_name))
password = getpass.getpass('Password : ')
os.system('openssl enc -d -aes-256-cbc -iter 10 -in {}.db.enc -out {}.db -pass pass:{}'.format(file_name,file_name,password))
conn = sqlite3.connect('{}.db'.format(file_name))
cursor = conn.cursor()
query = """SELECT * FROM keepass"""
try:
cursor.execute(query)
except Exception as e:
print('Error:', e)
entries = []
for row in cursor:
entries.append((row[0],row[1],row[2]))
query = """INSERT OR REPLACE INTO keepass (id,username,password) VALUES (?,?,?)"""
mem_cursor.executemany(query, entries)
mem_conn.commit()
conn.commit()
conn.close()
os.system('rm {}.db'.format(file_name))
return(mem_conn,mem_cursor,password,file_name)
def show_entry(mem_cursor):
query = """SELECT * FROM keepass"""
try:
mem_cursor.execute(query)
except Exception as e:
print('Error:', e)
buffer = str()
for row in mem_cursor:
buffer += '{} {} {}\n'.format(row[0], row[1], row[2])
print(buffer)
return
# Program begin here
if __name__ == "__main__":
os.chdir(os.path.abspath(os.path.dirname(__file__))) # Redirect the path into the directory
display_menu()
# Init the local database in the RAM
mem_conn = sqlite3.connect(":memory:")
mem_conn.isolation_level = None
mem_cursor = mem_conn.cursor()
query = """CREATE TABLE IF NOT EXISTS keepass (id integer PRIMARY KEY, username TEXT, password TEXT)"""
try:
mem_cursor.execute(query)
mem_conn.commit() # Save (commit) the changes
except Exception as e:
print(e)
password = str()
# Interface
while True:
choice = '-1'
while not(choice.split()) or choice.split()[0] not in ['add','close','create','del','exit','help','open','show']:
try:
choice = input('>')
except Exception as e:
print(e)
if choice.split() and choice.split()[0] not in ['add','close','create','del','exit','help','open','show']:
print('{}: command not found'.format(choice.split()[0]))
# add
if choice.split()[0] == 'add':
add_entry(mem_conn,mem_cursor)
# close
elif choice.split()[0] == 'close':
close_file(mem_conn,mem_cursor,password,file_name)
# create
elif choice.split()[0] == 'create':
(password,file_name) = create_file()
# del
elif choice.split()[0] == 'del':
del_entry(mem_conn,mem_cursor)
# exit
elif choice.split()[0] == 'exit':
print('QUITTING')
break
# help
elif choice.split()[0] == 'help':
show_help()
# open
elif choice.split()[0] == 'open':
(mem_conn,mem_cursor,password,file_name) = open_file(mem_conn,mem_cursor)
# show
elif choice.split()[0] == 'show':
show_entry(mem_cursor)
mem_conn.close() |
26a4b92aac33d0389c01f554cc7b7e8ce48079cd | akhileshcheguisthebestintheworld/pythonrooom | /crazy.py | 850 | 3.953125 | 4 | input("What is your favorite basketball team?")
if answer == "the warriors":
input("Good, who is your favorite player on the Warriors?")
if answer == "stephen curry":
input("Is he the best player currently in basketball?")
if answer == "yes":
input("I agree with you.")
else:
input("I do not agree with you.")
else:
input("I do not agree with you")
elif answer == "the spurs":
input("Okay, who is your favorite player on the Spurs?")
if answer == "danny green":
input("I agree with you.")
elif answer == "tony parker":
input("I do not agree with you")
else:
input("I do not agree with you.")
elif answer == "the thunder":
input("Okay, who is your favorite player on the Thunder?")
if answer == "kevin durant":
input("I agree with you.")
else:
input("I do not agree with you.")
else:
input("That team is not very good")
|
6f24ac8a11118f09ffbae16c64d5a918f4ec0abf | namhai923/Daily-Problem | /simple-calculator/simple-calculator.py | 1,206 | 3.53125 | 4 | def eval(expression):
result = ''
operations = []
post_fix = []
for x in range(0,len(expression)):
if expression[x].isdigit():
post_fix.append(expression[x])
elif expression[x] == ')':
while(operations[len(operations)-1] != '('):
post_fix.append(operations[len(operations)-1])
operations.pop()
operations.pop()
else:
operations.append(expression[x])
while(len(operations) != 0):
post_fix.append(operations[len(operations)-1])
operations.pop()
x = 0
while(len(post_fix) > 2):
if post_fix[x] == '+':
post_fix[x-2] = str(int(post_fix[x-2]) + int(post_fix[x-1]))
post_fix.pop(x)
post_fix.pop(x-1)
x -= 2
if post_fix[x] == '-':
post_fix[x-2] = str(int(post_fix[x-2]) - int(post_fix[x-1]))
post_fix.pop(x)
post_fix.pop(x-1)
x -= 2
x += 1
if len(post_fix) == 2:
result = post_fix[1] + post_fix[0]
if len(post_fix) == 1:
result = post_fix[0]
return result
print(eval('-(3+(2-1))')) |
9aced73d77b96ae0387427f8b8397cd20ed3d929 | bhchen-0914/PythonCourse | /pattern_json/class8.py | 662 | 4.15625 | 4 | """
group分组
"""
import re
s = "<t>this is a webpage 's title<t> "
r1 = re.search('<t>.*<t>', s)
print(r1.group())
r2 = re.search('<t>(.*)<t>', s) # ()内表示一个分组
print(r2.group(0)) # 0是默认取值,会默认匹配完整的正则表达式结果
print(r2.group(1))
s2 = s = "<t>this is a webpage 's title<t>this is other webpage 's title<t>"
r3 = re.search('<t>(.*)<t>(.*)<t>', s2)
print(r3.group(0))
print(r3.group(1)) # 使用group()方法内参数表示组号
print(r3.group(2))
print(r3.group(0, 1, 2)) # 快捷访问多组数据,返回值是一个元组
print(r3.groups()) # group只会返回普通字符中间的内容 |
472f167f1e5cdf04fa259d74052426982a3ff38c | elchigi/electiva4 | /ejercicio1.py | 332 | 3.90625 | 4 | num = input("Ingrese el numero a calcular")
divisor = 0
contador = 0
Arreglo= []
print("divisores:")
if num % 2 == 0:
iterar = num / 2
else:
iterar = (num - 1) / 2
for i in range(1, int(iterar) + 1):
if num % i == 0:
Arreglo.append(i)
contador = contador + 1
if contador == 10:
break
print Arreglo
|
3c3c9e894535daef8d264951dfc3d00be08b79cf | bestyoucanbe/joyprpr0831urbanplanner2 | /city.py | 873 | 4.5 | 4 | # Instructions
# In the previous Urban Planner exercise, you practiced defining custom types to represent buildings. Now you need to create a type to represent your city. Here are the requirements for the class. You define the properties and methods.
# Name of the city.
# The mayor of the city.
# Year the city was established.
# A collection of all of the buildings in the city.
# A method to add a building to the city.
# Remember, each class should be in its own file. Define the City class in the city.py file.
class City:
def __init__(self, city_name, city_mayor, city_year):
self.city_name = city_name
self.city_mayor = city_mayor
self.city_year_established = city_year
self.buildings_in_city = list()
def add_this_building_to_city(self, building_constructed):
self.buildings_in_city.append(building_constructed)
|
fbc76072d74262691b48377ded955f02cd30a314 | ITNika/advent-of-code-2019 | /test_intcode_computer.py | 1,455 | 3.71875 | 4 | import unittest
import IntcodeComputer
class TestIntcodeComputer(unittest.TestCase):
def test_initialize_memory(self):
f = open("test_initialize_memory.txt", "w+")
f.write("2,2,3,0,99")
f.close()
expected = [2, 2, 3, 0, 99]
intcode_computer = IntcodeComputer.IntcodeComputer(f.name)
self.assertEqual(expected, intcode_computer.memory)
def test_perform_multiplication(self):
f = open("test_perform_multiplication.txt", "w+")
f.write("2,1,2,0,99")
f.close()
intcode_computer = IntcodeComputer.IntcodeComputer(f.name)
intcode_computer.run_program()
self.assertEqual(2, intcode_computer.read_memory(0))
def test_perform_addition(self):
f = open("test_perform_multiplication.txt", "w+")
f.write("1,0,0,0,99")
f.close()
intcode_computer = IntcodeComputer.IntcodeComputer(f.name)
intcode_computer.run_program()
self.assertEqual(2, intcode_computer.read_memory(0))
def test_multiple_instructions(self):
f = open("test_multiple_instructions.txt", "w+")
f.write("1,9,10,3,2,3,11,0,99,30,40,50")
f.close()
intcode_computer = IntcodeComputer.IntcodeComputer(f.name)
intcode_computer.run_program()
expected = [3500, 9, 10, 70, 2, 3, 11, 0, 99, 30, 40, 50]
self.assertEqual(expected, intcode_computer.memory)
|
5617e7bc11f2393322ef152551c56343c75170e9 | dunitian/BaseCode | /javascript/1.ES6/var.py | 6,143 | 3.78125 | 4 | # if 1 < 2:
# b = 1
# print(b)
# ---------------------------------
# age = 20
# def test():
# global age
# print(age)
# test()
# ---------------------------------
# ---------------------------------
# def show(a, b, *args, c):
# print(a, b, args, c)
#
# # 1 2 (4, 5, 6) 3
# show(1, 2, 4, 5, 6, c=3)
# ---------------------------------
# ---------------------------------
# nums = (1, 2, 3, 4)
# nums2 = (0, *nums, 5, 6)
# print(nums2) # (0, 1, 2, 3, 4, 5, 6)
# ---------------------------------
# num_list = [1,2,3,4]
# num_list2 = [0,*num_list,5,6]
# # [0, 1, 2, 3, 4, 5, 6]
# print(num_list2)
# ---------------------------------
# num_list = [1,2,3,4]
# num_list2 = [0,5,6]
# # [1, 2, 3, 4, 0, 5, 6]
# num_list.extend(num_list2)
# # # [1, 2, 3, 4, [0, 5, 6]]
# # num_list.append(num_list2)
# print(num_list)
# ---------------------------------
# ---------------------------------
# scor_list = [100, 28, 38, 64]
# result_list = map(lambda item: item >= 60, scor_list)
# # [True, False, False, True]
# print(list(result_list)) # 不改变scor_list内容,生成新数组
# print(scor_list)
# ---------------------------------
# nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# nums2 = filter(lambda item: item % 2 == 0, nums)
# # [2, 4, 6, 8, 10]
# print(list(nums2)) # nums2:PY2返回的是列表
# ---------------------------------
# import functools
# nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# result = functools.reduce(lambda x, y: print(x, y), nums)
# print(result)
# # 1 2
# # None 3
# # None 4
# # None 5
# # None 6
# # None 7
# # None 8
# # None 9
# # None 10
# # None
# ---------------------------------
# import functools
# nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# result = functools.reduce(lambda x, y: x + y, nums)
# print(result / len(nums)) # 5.5
# ---------------------------------
# import functools
# nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# result = functools.reduce(avg, nums)
# print(result)
# ---------------------------------
# 字符串
# name, age = "小明", 23
# # 我叫小明,今年23
# print(f"我叫{name},今年{age}")
# print("""我叫:
# 小明
# 今年:
# 23
# """)
# ---------------------------------
# url = "https://www.baidu.com"
# if url.startswith("https://") or url.startswith("http://"):
# print("B/S")
# if url.endswith(".com"):
# print(".com")
# ---------------------------------
# ---------------------------------
# OOP
# class People(object):
# def __init__(self, name, age):
# self.name = name
# self.age = age
# def show(self):
# print(f"我叫:{self.name},今年:{self.age}")
# @classmethod
# def hello(cls):
# print("Hello World!")
# xiaoming = People("小明", 23)
# xiaoming.show() # 我叫:小明,今年:23
# # 这个虽然可以访问到,但我一直都不建议这么用(不然用其他语言会混乱崩溃的)
# xiaoming.hello() # Hello World!
# People.hello() # Hello World!
# ---------------------------------
# class Teacher(People):
# def __init__(self, name, age, work):
# self.work = work
# super().__init__(name, age)
# def show_job(self):
# print(f"我是做{self.work}工作的")
# xiaozhang = Teacher("小张", 25, "思想教育")
# xiaozhang.show() # 我叫:小张,今年:25
# xiaozhang.show_job() # 我是做思想教育工作的
# Teacher.hello() # Hello World!
# ---------------------------------
# class Animal(object):
# def __init__(self, name):
# self.name = name
# def run(self):
# print(f"{self.name}会跑")
# class Dog(Animal):
# def run(self):
# print(f"{self.name}会飞快的跑着")
# # 借助一个方法来实现多态
# def run(obj):
# obj.run()
# run(Animal("动物")) # 动物会跑
# run(Dog("小狗")) # 小狗会飞快的跑着
# ---------------------------------
# def show():
# yield "1"
# yield "2"
# return "d"
# gen = show()
# while True:
# try:
# print(next(gen))
# except StopIteration as ex:
# print(f"返回值:{ex.value}")
# break
# for item in show():
# print(item) # 1 2
# ---------------------------------
# def show():
# a = yield "111"
# print(a)
# b = yield a
# print(b)
# c = yield b
# print(c)
# return "over"
# gen = show()
# # 第一个不传参
# print(next(gen)) # gen.send(None)
# print(gen.send("aaa"))
# print(gen.send("bbb"))
# try:
# print(gen.send("ccc"))
# except StopIteration as ex:
# print(ex.value)
# ---------------------------------
# import asyncio
# # 模拟一个异步操作
# async def show():
# await asyncio.sleep(1)
# return "写完文章早点睡觉哈~"
# # 定义一个异步方法
# async def test(msg):
# print(msg)
# return await show()
# # Python >= 3.7
# result = asyncio.run(test("这是一个测试"))
# print(result)
# # Python >= 3.4
# # loop = asyncio.get_event_loop()
# # result = loop.run_until_complete(test("这是一个测试"))
# # print(result)
# # loop.close()
# ---------------------------------
# ---------------------------------
# user = {"name": "dnt", "age": 25, "wechat": "dotnetcrazy"}
# for key in user.keys():
# print(key) # name age wechat
# for value in user.values():
# print(value) # dnt 25 dotnetcrazy
# for key, value in user.items():
# print(key, value) # name dnt age 25 wechat dotnetcrazy
# ---------------------------------
# ---------------------------------
# 格式系列:lstrip(去除左边空格),rstrip(去除右边空格),strip(去除两边空格)美化输出系列:ljust,rjust,center
strip_str = " I Have a Dream "
print("["+strip_str.strip()+"]")
print("["+strip_str.lstrip()+"]")
print("["+strip_str.rstrip()+"]")
test_str = "ABCDabcdefacddbdf"
print("["+test_str.ljust(50)+"]")
print("["+test_str.rjust(50)+"]")
print("["+test_str.center(50)+"]")
# 输出:
# [I Have a Dream]
# [I Have a Dream ]
# [ I Have a Dream]
# [ABCDabcdefacddbdf ]
# [ ABCDabcdefacddbdf]
# [ ABCDabcdefacddbdf ]
# ---------------------------------
|
9f426b0d4313f9e441edd441de42855c9d87e1aa | PaulAlexInc/100DaysOfCode | /projects/Day12_project/main.py | 2,608 | 4.375 | 4 | #Number Guessing Game Objectives:
# Include an ASCII art logo.
# Allow the player to submit a guess for a number between 1 and 100.
# Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer.
# If they got the answer correct, show the actual answer to the player.
# Track the number of turns remaining.
# If they run out of turns, provide feedback to the player.
# Include two different difficulty levels (e.g., 10 guesses in easy mode, only 5 guesses in hard mode).
# import random
# from art import logo
# print(logo)
# def check(user_guess, guess):
# global to_continue
# if user_guess < guess:
# print("Too low\nGuess again.")
# elif user_guess > guess:
# print("Too high\nGuess again.")
# else:
# to_continue=False
# print(f"You got it! The answer was {guess}")
# print("Welcome to the number guessing game!!!")
# guess=random.randint(1,100)
# print(guess)
# user_mode=input("Which mode do you want. Type 'easy' or 'hard' : ").lower()
# user_guess=int(input("Guess a number between 1 and 100 : "))
# def mode(user_mode):
# if user_mode=="easy":
# return 10
# else:
# return 5
# to_continue=True
# n=mode(user_mode)
# while to_continue:
# check(user_guess,guess)
# if to_continue==True and n!=0:
# print(f"You have {n} attempts remaining to guess the number")
# user_guess=int(input("Make a guess : "))
# n=n-1
# elif n==0:
# print("You've run out of turns")
# to_continue=False
####################Alternate method####################
import random
from art import logo
print(logo)
#Global constant
EASY_TURNS = 10
HARD_TURNS = 5
def check(user_guess,guess, turns):
"""checks answer agains guess, returns number of turns"""
if user_guess < guess:
print("Too low\nGuess again.")
return turns-1
elif user_guess > guess:
print("Too high\nGuess again.")
return turns-1
else:
print(f"You got it! The answer was {guess}")
def mode():
user_mode=input("Choose a difficulty. Type 'easy' or 'hard' : ").lower()
if user_mode=="easy":
return EASY_TURNS
else:
return HARD_TURNS
def game():
print("Welcome to the number guessing game!!!")
print("I'm guessing a number between 1 and 100 : ")
guess=random.randint(1,100)
print(guess)
turns=mode()
user_guess=0
while user_guess!=guess:
print(f"You have {turns} turns remaining")
user_guess=int(input("Make a guess : "))
turns=check(user_guess,guess, turns)
if turns==0:
print("You've run out of guesses, you lose")
return
game() |
884ca98ee233d7b3745805a747a469aa639ea4b0 | Janoti/CodeWars-Python | /DataStructures.py | 469 | 3.9375 | 4 | ############ LISTS
my_list = [1, 2, 3, 4, 5]
mix_list = ["A", "B", 1, 2, True, False]
a = mix_list[0:2] ## -- SLICE Print A , B
print(a)
print("\n")
nestlist = [1,2,3,[4,5,6],7,8]
# 4 , 5 and 6 is inside another list
nlist = nestlist[3]
print(nlist)
# access a index inside the another list
nlist2 = nestlist[3][0]
print (nlist2)
#### TABLE
my_table = [[1,2,3],[4,5,6],[7,8,9]]
print(my_table[0]) #Print 1º position (1,2,3)
print(my_table[1][2]) # Print number 6 |
db9a56507bd59c724e3edc5481cbeda6bf313f06 | rjmarshall17/miscellaneous | /matching_parens.py | 985 | 4.125 | 4 | #!/usr/bin/env python3
import sys
MATCHING_PARENTHESES = {
'}': '{',
')': '(',
']': '[',
}
# This is apparently O(N^2) time complexity but O(N) for space
def matchingParentheses(string_in):
parentheses = []
for character in string_in:
if character in MATCHING_PARENTHESES.values():
parentheses.append(character)
elif character in MATCHING_PARENTHESES:
# In case we start off with a closed parentheses and there
# is nothing in the stack
if not parentheses:
return False
if parentheses[-1] != MATCHING_PARENTHESES[character]:
return False
parentheses.pop()
if len(parentheses) > 0:
return False
return True
if __name__ == '__main__':
if matchingParentheses(sys.argv[1]):
print("The parentheses all matched in: %s" % sys.argv[1])
else:
print("There were mismatched parentheses in: %s" % (sys.argv[1])) |
1b6ca4e89dd7d1082eb7d9aba899748ff51c8421 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/SecondDay/es2_numParioDisp.py | 153 | 4.03125 | 4 | num = int(input("Inserisci un numero: "))
if(num % 2 == 0):
print("Il numero", num, " è pari")
else:
print("Il numero", num, " è dispari!") |
1ba4db7e969421cc138c5e2283dd1a44a50d0e98 | zaynesember/CompPhys | /Calculus/integrals.py | 1,375 | 3.765625 | 4 | import numpy as np
def simpson(f, a, b, n):
"""Approximates the definite integral of f from a to b by
the composite Simpson's rule, using n subintervals.
From http://en.wikipedia.org/wiki/Simpson's_rule
"""
h = (b - a) / n
i = np.arange(0,n)
s = f(a) + f(b)
s += 4 * np.sum( f( a + i[1::2] * h ) )
s += 2 * np.sum( f( a + i[2:-1:2] * h ) )
return s * h / 3
def trapezoid(f, a, b, n):
"""Approximates the definite integral of f from a to b by
the composite trapezoidal rule, using n subintervals.
From http://en.wikipedia.org/wiki/Trapezoidal_rule
"""
h = (b - a) / n
s = f(a) + f(b)
i = np.arange(0,n)
s += 2 * np.sum( f(a + i[1:] * h) )
return s * h / 2
def adaptive_trapezoid(f, a, b, acc, output=False):
"""
Uses the adaptive trapezoidal method to compute the definite integral
of f from a to b to desired accuracy acc.
"""
old_s = np.inf
h = b - a
n = 1
s = (f(a) + f(b)) * 0.5
if output == True :
print ("N = " + str(n+1) + ", Integral = " + str( h*s ))
while abs(h * (old_s - s*0.5)) > acc :
old_s = s
for i in np.arange(n) :
s += f(a + (i + 0.5) * h)
n *= 2.
h *= 0.5
if output == True :
print ("N = " + str(n) + ", Integral = " + str( h*s ))
return h * s
|
37fd4a3792eff4a2be3c6d3943302294c89fdb0f | SimonStarling/kyh-practice | /Övning51.py | 2,681 | 3.984375 | 4 | # 51.1 Skriv om funktionen add_as_def som lambda, och lagra i en variabel
'''
add_as_lambda = lambda a,b:a+b
print(add_as_lambda(2,4))
'''
# 51.2 Skriv om obj som en funktion "upper"
'''
# Med lambda
obj = lambda s: s.upper()
print(obj("sträng"))
#Som funktion
def obj(s):
s = s.upper()
return s
x = "hej detta ska vara i upper"
z = obj(x)
print(z)
'''
# 51.3 Översätt denna lambda till en vanlig def funktion
'''
# Som lambda:
join_as_lambda = lambda strings, inbetween: inbetween.join(strings)
print(join_as_lambda("Hej", "Hej"))
print("Hej".join(["H", "e", "j"]))
def join_as_lambda(strings):
ls = ["H", "e", "j"]
print(strings.join(ls))
join_as_lambda("Hej")
'''
#51.4 Vad kommer följande program att skriva ut? Läs och diskutera först.
# Testkör därefter, och förklara varför ni får det resultat ni får...
'''
anna = ("Anna", "Persson", 42)
lova = ("Lova", "Andersson", 35)
alex = ("Alex", "Börjesson", 10)
people = [anna, lova, alex]
on_surname = sorted(people, key=lambda p: p[1]) # värdet i p styr sorteringen av listan.
# 0 är förnamn, 1 efternamn och 2 är ålder
for (first, last, age) in on_surname:
print(f"{first} {last} ({age} år)")
'''
# 51.5 Skriv ett program som utgår ifrån ovanstående, men skriver ut personerna i åldersordning.
'''
anna = ("Anna", "Persson", 42)
lova = ("Lova", "Andersson", 35)
alex = ("Alex", "Börjesson", 10)
people = [anna, lova, alex]
on_surname = sorted(people, key=lambda p: p[2]) # värdet i p styr sorteringen av listan.
# 0 är förnamn, 1 efternamn och 2 är ålder
for (first, last, age) in on_surname:
print(f"{first} {last} ({age} år)")
'''
# 51.6 Utgående ifrån förra programmet, ändra så att en "def age_sorter" funktion används istället med hjälp syntaxen key=age_sorter
# Vilket sätt tycker ni är tydligast?
'''
anna = ("Anna", "Persson", 42)
lova = ("Lova", "Andersson", 35)
alex = ("Alex", "Börjesson", 10)
people = [anna, lova, alex]
def age_sorter():
ett =people[0][2]
tva =people[1][2]
tre =people[2][2]
ls = [ett, tva, tre]
print(sorted(ls))
age_sorter()
'''
# 51.7 Skriv om föregående program som använder sig av en class Person med attributen first, last och age
# istället för tuppler. Vilken form tycker är lättast att läsa enligt er?
class People:
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
def order_by():
people = []
people.append(People("Anna", "Persson", 42))
people.append(People("Lova", "Andersson", 35))
people.append(People("Alex", "Börjesson", 10))
print(people)
order_by() |
be4122d91c51b8b2fd483427161efc4153465e4a | SamuelFlo/Beatchess-Proyecto | /Beatchess/ChessTest.py | 508 | 3.59375 | 4 | import chess
from AlphaBetaPruning import ABPruningAI
import time
def main():
AI = ABPruningAI()
turn = 1
board = chess.Board()
while True:
print(f"Turn {turn}")
print(board)
move = input("Type your move: ")
board.push(chess.Move.from_uci(move))
print(board)
print('-'*60)
#time.sleep(3)
ai_move = AI.BestMove(board)
board.push(ai_move)
print(ai_move)
turn += 1
if __name__ == "__main__":
main()
|
fdae063a2e0d6d401105907918cd8812c49882f4 | iggsilva07/Projet-test | /exercicio/ex03.py | 777 | 3.90625 | 4 | campionato = ('','Palmeiras', 'Flamengo', 'Internacional', 'Grêmio', 'São Paulo',
'Atlético Mineiro', 'Atlético Paranaense', 'Cruzeiro', 'Botafogo',
'Santos', 'Bahia', 'Fluminense', 'Corinthians', 'Chapecoense',
'Ceará', 'Vasco da Gama', 'América Mineiro', 'Sport', 'Vitória',
'Paraná')
print('\nTABELA BRASILEIRAO')
for posicao_times in range(1, 21):
print(f'{posicao_times} - {campionato[posicao_times]}')
print('\nClassificados para a LIBERTADORES DA AMERICA!')
for posicao_times in range(1,6):
print(f'{posicao_times} - {campionato[posicao_times]}')
print('\nOs rebaixados para segunda divisão!')
for posicao_times in range(17,21):
print(f'{posicao_times} - {campionato[posicao_times]}')
|
a4442c8cc1fb02f88aa15912c9f7a1de5487be94 | nahaza/pythonTraining | /ua/univer/HW01/Ch02ProgTrain08.py | 480 | 3.84375 | 4 | # charge for food, tip, tax
tipRate = 0.18
taxFromSalesRate = 0.07
chargeForFood = float(input("Enter charge for the food, UAH: "))
tipAmount: float = chargeForFood * tipRate
taxFromSales: float = chargeForFood * taxFromSalesRate
totalAmountInReceipt: float = chargeForFood + tipAmount + taxFromSales
print("Tip, UAH:", format(tipAmount, '.2f'))
print("Tax from sales, UAH:", format(taxFromSales, '.2f'))
print("Receipt total amount, UAH:", format(totalAmountInReceipt, '.2f'))
|
6578a8dd8971b10709263f769e0205047e6f713f | Haruka0522/AtCoder | /ABC/ABC054-A.py | 333 | 3.890625 | 4 | alice,bob = map(int,input().split())
if(bob == 1 or alice == 1):
if(bob == 1 and alice == 1):
print("Draw")
elif(bob == 1):
print("Bob")
else:
print("Alice")
else:
if(bob < alice):
print("Alice")
elif(alice < bob):
print("Bob")
else:
print("Draw") |
29a2f552127e7d115fb54906bb2b6165565375ca | H4wking/alab2 | /task1.py | 1,498 | 3.671875 | 4 | import math
def distance(a, b):
return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
def construct(p):
px = sorted(p, key=lambda x: x[0])
py = sorted(p, key=lambda x: x[1])
return px, py
def closest_pair(p):
px, py = construct(p)
p0, p1 = closest_pair_rec(px, py)
return distance(p0, p1), (p0, p1)
def closest_pair_rec(px, py):
if len(px) <= 3:
min_distance = [math.inf, 0, 0]
for point1 in px:
for point2 in px:
d = distance(point1, point2)
if d and d < min_distance[0]:
min_distance = [d, point1, point2]
return min_distance[1:]
n = len(px)
qx, qy = px[:n//2], py[:n//2]
rx, ry = px[n//2:], py[n//2:]
q0, q1 = closest_pair_rec(qx, qy)
r0, r1 = closest_pair_rec(rx, ry)
delta = min(distance(q0, q1), distance(r0, r1))
max_x = qx[-1][0]
s = [point for point in px if max_x - point[0] < delta]
sy = construct(s)[1]
min_distance = [math.inf, 0, 0]
for i in range(len(sy)):
for j in range(15):
try:
d = distance(sy[i], sy[i+j])
except:
continue
if d and d < min_distance[0]:
min_distance = [d, sy[i], sy[i+j]]
s0, s1 = min_distance[1], min_distance[2]
if distance(s0, s1) < delta:
return (s0, s1)
elif distance(q0, q1) < distance(r0, r1):
return (q0, q1)
else:
return (r0, r1)
|
a9cd12af22f786b27027aed683f4b95c0352f361 | shreyas008/PokerApp | /poker_new.py | 11,551 | 3.515625 | 4 | from tkinter import *
from PIL import ImageTk, Image
import string
def table(window):
C = Canvas(window, bg="black", height=500, width=1050 ,bd = 0,borderwidth = 0, highlightthickness=0, relief='ridge')
C.pack(side = "top")
C.create_oval(40,40,1000,460,fill= "green",width = 10, outline = "brown")
P = Label(window,textvariable = pot, bg="black", fg="red", font = "Arial 20 bold")
P.pack(side = "right")
def table_cards(window,card1,card2,card3):
#initial 3 cards to display. [Flop]
global card_1_image,card_2_image,card_3_image
card_1_image = Image.open("images/"+card1+".jpg")
card_1_image = card_1_image.resize((70, 80), Image.ANTIALIAS)
card_1_image = ImageTk.PhotoImage(card_1_image)
card_1_image_label = Label(window, image = card_1_image, width =60, height = 70)
card_1_image_label.place(x = 450, y = 250)
card_2_image = Image.open("images/"+card2+".jpg")
card_2_image = card_2_image.resize((70, 80), Image.ANTIALIAS)
card_2_image = ImageTk.PhotoImage(card_2_image)
card_2_image_label = Label(window, image = card_2_image, width =60, height = 70)
card_2_image_label.place(x = 520, y = 250)
card_3_image = Image.open("images/"+card3+".jpg")
card_3_image = card_3_image.resize((70, 80), Image.ANTIALIAS)
card_3_image = ImageTk.PhotoImage(card_3_image)
card_3_image_label = Label(window, image = card_3_image, width =60, height = 70)
card_3_image_label.place(x = 590, y = 250)
gameinfo.set("Flop")
def add_card(window,cardnum,card): #displaying turn and river
global card_4_image,card_river_image
if(cardnum==4):
card_4_image = Image.open("images/"+card+".jpg")
card_4_image = card_4_image.resize((70, 80), Image.ANTIALIAS)
card_4_image = ImageTk.PhotoImage(card_4_image)
card_4_image_label = Label(window, image = card_4_image, width =60, height = 70)
card_4_image_label.place(x = 660, y = 250)
gameinfo.set("Turn")
else:
card_river_image = Image.open("images/"+card+".jpg")
card_river_image = card_river_image.resize((70, 80), Image.ANTIALIAS)
card_river_image = ImageTk.PhotoImage(card_river_image)
card_river_image_label = Label(window, image = card_river_image, width =60, height = 70)
card_river_image_label.place(x = 730, y = 250)
gameinfo.set("River")
def folded():
#send signal to server
gameinfo.set("Player_1 folds")
pass
def called(window): #on button click
l = [str(i) for i in window.winfo_children()] #window.winfo_children() returns list of all widgets in the winodw
if not(any(i.startswith('.!entry') for i in l)): #if entry widget doesn't exist
e = Entry(window)
e.pack(side = "bottom")
e.bind("<Return>", on_change)
def on_change(e):
amount = int(e.widget.get())
if(amount>0 and amount <= player_amt[0].get()): #if valid amount
e.widget.delete(0, END)
player_amt[0].set(player_amt[0].get()-amount)
e.widget.destroy()
gameinfo.set("Player_1 bets "+str(amount))
pot.set(pot.get()+amount)
def players(window,card1,card2):
global player1_card_1_image,player1_card_2_image
global player2_card_1_image,player2_card_2_image
global player3_card_1_image,player3_card_2_image
global player4_card_1_image,player4_card_2_image
global player5_card_1_image,player5_card_2_image
global player_amt
player_amt = [IntVar(),IntVar(),IntVar(),IntVar(),IntVar()]
for i in player_amt:
i.set(100)
call = Button(window, text = "Call", highlightbackground = "red", fg = "black", width = 8, activebackground = "black", activeforeground = "red", command = lambda: called(window))
call.pack(side = "bottom")
fold = Button(window, text = "Fold", highlightbackground = "red", fg = "black", width = 8, activebackground = "black", activeforeground = "red", command = folded)
fold.pack(side = "bottom")
player1_money = Label(window, textvariable = player_amt[0], bg="black", fg="red", font = "Arial 20 bold")
player1_money.pack(side = "bottom")
player1_name = Label(window, text = "Client Player 1", bg="black", fg="red", font = "Arial 20 bold")
player1_name.pack(side = "bottom")
player1_card_1_image = Image.open("images/"+card1+".jpg")
player1_card_1_image = player1_card_1_image.resize((40, 50), Image.ANTIALIAS)
player1_card_1_image = ImageTk.PhotoImage(player1_card_1_image)
player1_card_1_image_label = Label(window, image = player1_card_1_image, width =30, height = 40)
player1_card_1_image_label.place(x = 640, y = 550)
player1_card_2_image = Image.open("images/"+card2+".jpg")
player1_card_2_image = player1_card_2_image.resize((40, 50), Image.ANTIALIAS)
player1_card_2_image = ImageTk.PhotoImage(player1_card_2_image)
player1_card_2_image_label = Label(window, image = player1_card_2_image, width =30, height = 40)
player1_card_2_image_label.place(x = 600, y = 550)
player2_move = Label(window, text = "Move = ", bg="black", fg="red", font = "Arial 20 bold")
player2_move.place(x = 0, y = 530)
player2_money = Label(window, textvariable = player_amt[1], bg="black", fg="red", font = "Arial 20 bold")
player2_money.place(x = 0, y = 500)
player2_name = Label(window, text = "Client Player 2", bg="black", fg="red", font = "Arial 20 bold")
player2_name.place(x = 0, y = 470)
player2_card_1_image = Image.open("images/back.jpg")
player2_card_1_image = player2_card_1_image.resize((40, 50), Image.ANTIALIAS)
player2_card_1_image = ImageTk.PhotoImage(player2_card_1_image)
player2_card_1_image_label = Label(window, image = player2_card_1_image, width =30, height = 40)
player2_card_1_image_label.place(x = 5, y = 420)
player2_card_2_image = Image.open("images/back.jpg")
player2_card_2_image = player2_card_2_image.resize((40, 50), Image.ANTIALIAS)
player2_card_2_image = ImageTk.PhotoImage(player2_card_2_image)
player2_card_2_image_label = Label(window, image = player2_card_2_image, width =30, height = 40)
player2_card_2_image_label.place(x = 45, y = 420)
player5_move = Label(window, text = "Move = ", bg="black", fg="red", font = "Arial 20 bold")
player5_move.place(x = 1120, y = 530)
player5_money = Label(window, textvariable = player_amt[2], bg="black", fg="red", font = "Arial 20 bold")
player5_money.place(x = 1120, y = 500)
player5_name = Label(window, text = "Client Player 5", bg="black", fg="red", font = "Arial 20 bold")
player5_name.place(x = 1120, y = 470)
player5_card_1_image = Image.open("images/back.jpg")
player5_card_1_image = player5_card_1_image.resize((40, 50), Image.ANTIALIAS)
player5_card_1_image = ImageTk.PhotoImage(player5_card_1_image)
player5_card_1_image_label = Label(window, image = player5_card_1_image, width =30, height = 40)
player5_card_1_image_label.place(x = 1120, y = 420)
player5_card_2_image = Image.open("images/back.jpg")
player5_card_2_image = player5_card_2_image.resize((40, 50), Image.ANTIALIAS)
player5_card_2_image = ImageTk.PhotoImage(player5_card_2_image)
player5_card_2_image_label = Label(window, image = player5_card_2_image, width =30, height = 40)
player5_card_2_image_label.place(x = 1160, y = 420)
player3_move = Label(window, text = "Move = ", bg="black", fg="red", font = "Arial 20 bold")
player3_move.place(x = 0, y = 150)
player3_money = Label(window, textvariable = player_amt[3], bg="black", fg="red", font = "Arial 20 bold")
player3_money.place(x = 0, y = 120)
player3_name = Label(window, text = "Client Player 3", bg="black", fg="red", font = "Arial 20 bold")
player3_name.place(x = 0, y = 90)
player3_card_1_image = Image.open("images/back.jpg")
player3_card_1_image = player3_card_1_image.resize((40, 50), Image.ANTIALIAS)
player3_card_1_image = ImageTk.PhotoImage(player3_card_1_image)
player3_card_1_image_label = Label(window, image = player3_card_1_image, width =30, height = 40)
player3_card_1_image_label.place(x = 5, y = 40)
player3_card_2_image = Image.open("images/back.jpg")
player3_card_2_image = player3_card_2_image.resize((40, 50), Image.ANTIALIAS)
player3_card_2_image = ImageTk.PhotoImage(player3_card_2_image)
player3_card_2_image_label = Label(window, image = player3_card_2_image, width =30, height = 40)
player3_card_2_image_label.place(x = 45, y = 40)
player4_move = Label(window, text = "Move = ", bg="black", fg="red", font = "Arial 20 bold")
player4_move.place(x = 1120, y = 150)
player4_money = Label(window, textvariable = player_amt[4], bg="black", fg="red", font = "Arial 20 bold")
player4_money.place(x = 1120, y = 120)
player4_name = Label(window, text = "Client Player 4", bg="black", fg="red", font = "Arial 20 bold")
player4_name.place(x = 1120, y = 90)
player4_card_1_image = Image.open("images/back.jpg")
player4_card_1_image = player4_card_1_image.resize((40, 50), Image.ANTIALIAS)
player4_card_1_image = ImageTk.PhotoImage(player4_card_1_image)
player4_card_1_image_label = Label(window, image = player4_card_1_image, width =30, height = 40)
player4_card_1_image_label.place(x = 1120, y = 40)
player4_card_2_image = Image.open("images/back.jpg")
player4_card_2_image = player4_card_2_image.resize((40, 50), Image.ANTIALIAS)
player4_card_2_image = ImageTk.PhotoImage(player4_card_2_image)
player4_card_2_image_label = Label(window, image = player4_card_2_image, width =30, height = 40)
player4_card_2_image_label.place(x = 1160, y = 40)
def server_listen(window): #listens for messages from server
for i in range(len(flags)):
flags[i]=True
'''
To-Do
Messages from server
flop - done
turn - done
river - done
fold - when someone folds - {change colour of their name, change gameinfo}
call - when someone else calls - {add money to pot, change gameinfo}
round over - {change gameinfo to display winner,display all cards,remove all cards from table, update money of each player, reset pot, change player_name colours back to normal ...}
game over - display winner
'''
if(flags[0] and 'card_1_image' not in globals()): #if flag is set and the image is not yet created
table_cards(window,cards[('clubs','king')],cards[('hearts',2)],cards[('diamonds','ace')] )
if(flags[1] and 'card_4_image' not in globals()):
add_card(window,4,cards[('clubs',2)])
if(flags[2] and 'card_river_image' not in globals()):
add_card(window,5,cards[('clubs',5)])
window.after(10,server_listen,window)
def main():
global gameinfo,pot,flags,cards
flags=[False,False,False] #flags for flop, turn, river
num = list(range(1,11))
num[0] = 'ace';
num.extend(['jack','queen','king'])
suit = ['clubs','spades','diamonds','hearts']
cards = {(i,j):str(j)+" of "+i for i in suit for j in num}
window = Tk()
window.title("Poker")
gameinfo = StringVar()
gameinfo.set("Waiting....")
pot = IntVar()
pot.set(0)
window.configure(background = "black")
center_name = Label(window, textvariable = gameinfo, bg="black", fg="white", font = "Helvetica 30 bold")
center_name.pack(side="top")
table(window)
players(window, cards[('clubs',2)],cards[('hearts','queen')])
window.after(10,server_listen,window)
window.mainloop()
main() |
959f1d82108da99b094e4fd508c3d535121bfc8a | anlancx/leraning | /4-2.py | 91 | 3.6875 | 4 |
items3 = []
for x in 'ABC':
for y in '12':
items3.append(x + y)
print(items3)
|
bebadc8b0746716b27e43fb8c96d1bccc2a9b6ca | cavid-aliyev/HackerRank | /collectionDeque.py | 476 | 3.828125 | 4 | # Collection deque -> https://www.hackerrank.com/challenges/py-collections-deque/problem
from collections import deque
d = deque()
n = int(input())
for i in range(n):
l = input().split()
command = l[0]
if len(l) > 1:
e = l[1]
if command == "append":
d.append(e)
elif command == "pop":
d.pop()
elif command == "appendleft":
d.appendleft(e)
elif command == "popleft":
d.popleft()
print(*d) |
367360115f83c25a757d9a4c009c2f459f9c98ce | Aasthaengg/IBMdataset | /Python_codes/p03477/s896259088.py | 129 | 3.640625 | 4 | a,b,c,d=map(int,input().split())
ab=a+b
cd=c+d
if ab>cd:
print("Left")
elif ab<cd:
print("Right")
else:
print("Balanced") |
0446d6787bda9c1d3ece1a6fe1193109278b03db | tomboo/exercism | /python/sum-of-multiples/sum_of_multiples.py | 495 | 4.4375 | 4 | '''
Write a program that, given a number, can find the sum of all
the multiples of particular numbers up to but not including that
number.
'''
def sum_of_multiples(limit, numbers=None):
if not numbers:
numbers = [3, 5]
multiples = set()
for m in numbers:
if m:
for i in range(m, limit, m):
multiples.add(i)
return sum(multiples)
if __name__ == '__main__':
print(sum_of_multiples(4))
print(sum_of_multiples(20, [0, 3, 5]))
|
9173582ad9a299dcb37244e111beeb9e33e1ed86 | jiangshen95/UbuntuLeetCode | /LongestPalindrome.py | 421 | 3.71875 | 4 | class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
m = [0] * 128
odd = 0
for c in s:
m[ord(c)] += 1
for n in m:
if n % 2:
odd += 1
return len(s) - odd + (odd > 0)
if __name__ == '__main__':
s = input()
solution = Solution()
print(solution.longestPalindrome(s))
|
8323c9a67f6cd2402b902f8f341d89f7ab3ecec7 | sabya14/cs_with_python | /dictonaries/frequency_queries.py | 1,271 | 3.875 | 4 | """
Problem Statement - https://www.hackerrank.com/challenges/frequency-queries/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps
"""
class FrequencyQueries:
state = None
def __init__(self):
self.state = {}
def operation(self, operation_code, operation_value):
if operation_code == 1:
if operation_value in self.state:
self.state[operation_value] += 1
else:
self.state[operation_value] = 1
if operation_code == 2:
if operation_value in self.state:
if self.state[operation_value] == 1:
self.state.pop(operation_value)
else:
self.state[operation_value] -= 1
if operation_code == 3:
for key, value in self.state.items():
if value == operation_value:
return key
return 0
def get_state(self):
return self.state
if "__name__" == "__main__":
n = int(input())
data = []
fq = FrequencyQueries()
for i in range(0, n):
operation_code, operation_value = map(int, input().split())
fq.operation(operation_code, operation_value)
|
2a9ebc9ac1ce049bf2f75fb774af86169b6c40f6 | AbelHristodor/CurrentWeatherApp | /main.py | 1,855 | 3.734375 | 4 | import json,requests
## -------------------------------- Getting data from the city.list.json file and getting the choosen's city id ---------------------------------------------------
city_list_json = open("city.list.json", "r", encoding = "utf-8")
data = json.load(city_list_json)
# Get all the city's names
city_names = [data[i]["name"] for i in range(len(data))]
# User input
choosen_city = input("City name: ")
choosen_city.capitalize()
def findIndex(list_names,city_name):
if city_name in list_names:
city_index = list_names.index(city_name)
return city_index
else:
return "An error has occurred. Did you write the city name right?"
def findID(list, city_index):
return list[city_index]["id"]
city_id = findID(data, findIndex(city_names, choosen_city))
city_list_json.close()
## -----------------------------------------------Weather Data------------------------------------------------------------------
openweather_key = "f908f7c05b3be47e408fbfdf3a3c5be2"
r = requests.get(
f"http://api.openweathermap.org/data/2.5/weather?id={city_id}&units=metric&APPID={openweather_key}")
city_data = r.json()
## ----------------------------------------------Formatting and Printing --------------------------------------------------------
temps = {
'avg' : city_data["main"]["temp"],
'max' : city_data["main"]["temp_max"],
'min' : city_data["main"]["temp_min"]
}
humidity = str(city_data["main"]["humidity"]) + " %"
weather_desc = city_data["weather"][0]["description"]
weather = city_data["weather"][0]["main"]
print(f"City: {choosen_city}\n")
print(f"Temperatures: Average: {temps['avg']} °C\n Maximum: {temps['max']} °C\n Minimum: {temps['min']} °C\n")
print(f"Humidity: {humidity}\n")
print(f"Weather: {weather}:\n {weather_desc}\n\n")
|
1c8fadfdcb180afae8fce56af637be35f2a5bff8 | JoaquinCollazoRuiz/Conceptos-Python | /2TipoDatos.py | 485 | 3.875 | 4 | # coding=utf-8
#Strings
print("Hello world")
#Integer
print(10)
#Float
print(12.9)
#Boolean
True
False
#List(Array)
[10,20,30,40,50]
['Uno','Dos','Tres']
[1,'Dos',True, 9.8] #Se pueden combinar distintos tipos de datos en una lista
[]
#Tuples, la diferencia con la lista es que este no se puede modificar
(10,20,30)
#Diccionario (Agrupar grupo de datos con un nombre clave)
#Key(Nombre,Appelido) y value de la lista(Joaquín,Collazo)
{"Nombre:":"Joaquín",
"Apellido":"Collazo"} |
6cb2e1b5b6afdc56c834bfd91ba1f99cd89854e3 | yujuenianbei/python-test | /string.py | 163 | 3.890625 | 4 | #!/usr/bin/python3
formate = "hello ,%s! %s enough for ya?"
value = ('world','hot')
print (formate %value)
form = "pi is %.3f"
from math import pi
print(form %pi) |
447125b82e6df5af828d560ced099354965eab2f | mjcarter95/MSc-University-of-Liverpool | /Machine Learning and Bioinspired Optimisation/K-Arm Bandit Problem/k-arm_bandit.py | 2,609 | 3.59375 | 4 | import numpy as np
import matplotlib.pyplot as plt
# Colours for plots
colours = ['g', 'r', 'b']
# Paramters
k = 10 # The number of bandits in the problem
exploration_rates = [0, 0.01, 0.1] ## IF YOU ADD MORE VALUES, ADJUST COLOURS ABOVE ##
runs = 2000 # The number of times to run the problem
steps = 1000 # The number of steps to take per run
save_graphs = True # Set to True to save the graph
# Start the K-Bandit problem
for i, epsilon in enumerate(exploration_rates):
print("Starting the k-arm bandit problem with Ɛ = " + str(epsilon))
# Lists to store average a optimal rewards over n runs
average_rewards = np.zeros(steps)
optimal_actions = np.zeros(steps)
for run in range(runs):
# Set Qstar values and initialise Q (estimates) and N (number of times each action is taken)
Qstar = np.random.randn(k)
Q = np.zeros(k)
N = np.zeros(k)
for step in range(steps):
# Determine which action to takerzrrarra
if (np.random.rand() < epsilon):
# Explore the available options
action = np.random.randint(k)
else:
# Exploit the best action
action = np.argmax(Q)
# Calculate the reward
reward = np.random.normal(Qstar[action], 1)
# Update values for N and Q
N[action] += 1
Q[action] += (1 / (N[action] + 1)) * (reward - Q[action])
# Update our average_rewards
average_rewards[step] += reward
# Check if our action was optimal
if (action == np.argmax(Qstar)):
optimal_actions[step] += 1
# Normalise average_rewards and optimal_rewards over n runs
average_rewards /= runs
optimal_actions /= runs
optimal_actions *= 100
# Append these results to our graphs
plt.figure(1)
plt.plot(range(steps), average_rewards, color=colours[i], label="Ɛ: " + str(exploration_rates[i]))
plt.figure(2)
plt.plot(range(steps), optimal_actions, color=colours[i], label="Ɛ: " + str(exploration_rates[i]))
# Plot Figure 1 - Average Reward
plt.figure(1)
plt.xlabel("Steps")
plt.ylabel("Average Reward")
plt.legend(loc="lower right", prop={'size': 10})
if save_graphs == True: plt.savefig("average_reward.png")
# Plot Figure 2 - % Optimal Reward
plt.figure(2)
plt.xlabel("Steps")
plt.ylabel("% Optimal Action")
plt.legend(loc="lower right", prop={'size': 10})
if save_graphs == True: plt.savefig("pct_optimal_reward.png")
plt.show() |
f2b87bd979456dd283ddf655bb932567f7fa1140 | dimpozd13/pythonHomeWork | /3/func.py | 1,227 | 3.625 | 4 | def plusMinus(a, b):
if a > 0 and b > 0:
print(a + b)
elif a < 0 and b < 0:
print(a - b)
else:
print(0)
def twoMax(a, b, c):
list = [a, b, c]
a1 = max(list)
list.remove(a1)
a2 = max(list)
print(a1, a2)
def two(list, bl):
if bl == False:
newList = []
for i in list:
if i % 2 == 0:
newList.append(i)
print(newList)
else:
newList = []
for i in list:
if i % 2 != 0:
newList.append(i)
print(newList)
def sumAll(*numbers):
sum = 0
for i in numbers:
sum = sum + i
return sum
def maxMin(*numbers):
min = numbers[0]
max = numbers[0]
for i in numbers:
if i <= min:
min = i
elif i >= max:
max = i
return min, max
def stringCase(string, case=True):
string = str(string)
if case == True:
return string.upper()
else:
return string.lower()
def allKwargs(*strings, glue=":"):
newString = str()
for i in strings:
if len(i) > 3:
newString += glue + str(i)
return newString.lstrip(":")
print(allKwargs("hi", "magic", "world")) |
12745481e04d75ba328c22df8946bdeb430105c2 | silverflow/python_study | /contains.py | 563 | 3.625 | 4 | class Boundaries:
def __init__(self, width, height) -> None:
self.width = width
self.height = height
def __contains__(self, coord):
x, y = coord
return 0 <= x < self.width and 0 <= y < self.height
class Grid:
def __init__(self, width, height) -> None:
self.width = width
self.heigt = height
self.limits = Boundaries(width, height)
def __contains__(self, coord):
return coord in self.limits
def mark_coordinate(grid, coord):
if coord in grid:
grid[coord] = "MARKED"
|
894215c08575f5b7c3c764f8bc2d88999ee25aba | isemona/codingchallenges | /3-LongestWord.py | 423 | 4.125 | 4 | # https://www.coderbyte.com/information/Longest%20Word
# Difficulty - Easy
# Implemented enumerate
def LongestWord(sen):
i = 0
longestWord = ''
for j, ch in enumerate(sen):
if not ch.isalpha():
i = j + 1
if len(longestWord) < (j-i+1):
longestWord = sen[i:j+1]
return longestWord
# keep this function call here
print LongestWord(raw_input()) |
d9e56551141876c9142cdcb4c69a0ecb2363bcbc | dbms-ops/hello-Python | /1-PythonLearning/3-Python-基础知识/5-循环.py | 1,524 | 4.15625 | 4 | #!/data1/Python2.7/bin/python2.7
# -*-coding:utf-8-*-
# date: 2020-1-16 16:57
# user: Administrator
# description: 循环表达式 While 和 for
#
# 循环:while and for
# while 表达式:
# 语句1
# 语句2
# 如果表达式为真执行允许语句1,执行完成,计算表达式的值;
# 否则执行语句2
#
#
def while_sum_help():
"""
add i from 1 to 99
:return: return the sum from 1 to 99
"""
result = 0
i = 1
while i < 100:
result += i
i += 1
print result
def while_string_help():
"""
print the string from zero to len(string) user index
:return: no value
"""
str1 = "A bully is always a coward"
index = 0
while index < len(str1):
if str1[index] != ' ':
print str1[index]
index += 1
# 死循环:
# 表达式永远为真的循环
#
# while - else
# while 表达式1:
# 语句1
# else:
# 语句2
# for 循环:
# for 变量 in 集合:
# 语句1
#
# 逻辑:
# 按照顺序去集合中的每个元素,赋值给变量
# 然后执行语句;
def for_sum_help():
"""
Calculate the sum of 1 to 10
:return: print the sum of 1 to 10
"""
sum1 = 0
for I in range(1, 10, 1):
sum1 += I
print sum1
# break and continue
# 在循环内部,用于跳出最近一层循环
# continue: 跳过当前循环的剩余语句,继续下一次循环
#
#
def main():
while_sum_help()
if __name__ == '__main__':
main()
|
44541ae7e12f2a124ea6405cb470cb80f691c14d | diana134/afs | /Code/utilities.py | 3,500 | 3.828125 | 4 | """Some useful functions used by several things"""
import re, datetime
def optionalFieldIsGood(mine, theirs):
"""check if optional field theirs matches with mine"""
if (theirs is None or
theirs == "" or
theirs == mine):
return True
else:
return False
def requiredFieldIsGood(mine, theirs):
"""check if required field theirs matches with mine"""
if (theirs is not None and
mine == theirs):
return True
else:
return False
def sanitize(string):
"""Returns string with unsanitary characters (";) removed"""
return string.translate(None, '";')
def validateName(name):
"""Returns False if name looks potentially incorrect"""
if name.count(' ') > 1:
return False
# if has > 2 caps or 0 caps
if sum(1 for c in name if c.isupper()) > 2 or sum(1 for c in name if c.isupper()) == 0:
return False
# if has more than 1 of ' or -
if name.count('\'') > 1:
return False
if name.count('-') > 1:
return False
# if has any chars other than A-Z ' -
if re.match('[A-Za-z\'-]*', name) == None:
return False
return True
def stripPhoneNumber(number):
"""Returns number stripped of any characters other than 0-9, +, and x"""
newNumber = ''
for c in number:
if c.isdigit() or c == '+' or c == 'x':
newNumber += c
return newNumber
def validEmail(email):
"""Returns False if email isn't in valid format"""
# match = re.match("^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$", email)
match = re.match(
r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?",
email)
return match != None
def stripPostal(postal):
"""Returns postal code string stripped of any characters other than A-Z, 0-9"""
newPostal = ''
for c in postal.upper():
if c.isalnum():
newPostal += c
return newPostal
def convertTimeToSeconds(timeString):
"""convert MM:SS to seconds"""
tokens = timeString.split(':')
return int(tokens[0]) * 60 + int(tokens[1])
def convertStringToTimedelta(timeString):
"""convert 'M:SS' to timedelta"""
tokens = timeString.split(':')
minutes = int(tokens[0])
seconds = int(tokens[1])
return datetime.timedelta(minutes=minutes, seconds=seconds)
def humanPostalCodeFormat(postalString):
"""tries to add a space after 3 characters and returns the string"""
result = postalString
if len(postalString) > 3:
result = postalString[0:3] + " " + postalString[3:]
return result
def humanPhoneNumberFormat(phoneString):
"""tries to add "-" to phoneString, returns result"""
result = phoneString
extString = ""
fourDigit = ""
threeDigit = []
if 'x' in phoneString:
extString = phoneString[phoneString.index('x')+1:]
result = phoneString[0:phoneString.index('x')-1]
if len(result) > 4:
fourDigit = result[-4:]
result = result[0:-4]
for i in range(len(result), 0, -3):
threeDigit.append(result[i-3:i])
result = result[0:i-3]
# Now put it all back together
if result != "":
result += "-"
for i in xrange(len(threeDigit)-1, -1, -1):
result += (threeDigit[i] + "-")
if fourDigit != "":
result += (fourDigit)
if extString != "":
result += (" ext. " + extString)
return result
|
8e9b395522fa5204efa7d1f96dd3fce07c841169 | alexkie007/offer | /others/随机概率生成数字.py | 2,737 | 3.5 | 4 | """
rand3()可以随机等概率生成1,2,3
请使用rand3()构造rand7()可以随机等概率生成1,2,3,4,5,6,7
"""
"""
解题思路:
rand3可以随机生成1,2,3;rand7可以随机生成1,2,3,4,5,6,7。
rand3并不能直接产生4,5,6,7,所以直接用rand3去实现函数rand7似乎不太好入手。
如果反过来呢?给你rand7,让你实现rand3,这个好实现吗?
int Rand3(){
int x = ~(1<<31); // max int
while(x > 3)
x = Rand7();
return x;
}
述计算说明Rand3是等概率地生成1,2,3的(1/3的概率)
回到正题,现在题目要求我们要用Rand5来实现Rand7,
只要我们将Rand5 映射到一个能产生更大随机数的Randa,
其中a > 7,就可以套用上面的模板了。 这里要注意一点的是,
你映射后的Randa一定是要满足等概率生成1到a的。比如,
Rand5() + Rand5() - 1
上述代码可以生成1到9的数,但它们是等概率生成的吗?不是。生成1只有一种组合:
两个Rand5()都生成1时:(1, 1);而生成2有两种:(1, 2)和(2, 1);生成6更多。 它们的生成是不等概率的。那要怎样找到一个等概率生成数的组合呢?
我们先给出一个组合,再来进行分析。组合如下:
5 * (Rand5() - 1) + Rand5()
Rand5产生1到5的数,减1就产生0到4的数,乘以5后可以产生的数是:0,5,10,15,20。 再加上第二个Rand5()产生的1,2,3,4,5。我们可以得到1到25,
而且每个数都只由一种组合得到,即上述代码可以等概率地生成1到25。OK, 到这基本上也就解决了。
套用上面的模板,我们可以得到如下代码:
int Rand7(){
int x = ~(1<<31); // max int
while(x > 7)
x = 5 * (Rand5() - 1) + Rand5()
return x;
}
上面的代码有什么问题呢?可能while循环要进行很多次才能返回。
因为Rand25会产生1到25的数,而只有1到7时才跳出while循环,
生成大部分的数都舍弃掉了。这样的实现明显不好。
我们应该让舍弃的数尽量少, 于是我们可以修改while中的判断条件,
让x与最接近25且小于25的7的倍数相比。 于是判断条件可改为x > 21,
于是x的取值就是1到21。 我们再通过取模运算把它映射到1-7即可。代码如下:
int Rand7(){
int x = ~(1<<31); // max int
while(x > 21)
x = 5 * (Rand5() - 1) + Rand5()
return x%7 + 1;
}
因此我们可以先生成rand5 然后用rand5生成rand7
从上面一系列的分析可以发现,如果给你两个生成随机数的函数Randa和Randb, 你可以通过以下方式轻松构造Randab,生成1到a*b的随机数。
Randab = b * (Randa - 1) + Randb
Randab = a * (Randb - 1) + Randa
"""
|
5ec0c725e241b00e6f7f58021ee0fa67f8cac7e4 | Ashi12218604/Python | /regexp/regexp_21_greedy.py | 621 | 4 | 4 | /*
Greedy Search
Description
You’re given the following html code:
<html>
<head>
<title> My amazing webpage </title>
</head>
<body> Welcome to my webpage! </body>
</html>
Write a greedy regular expression that matches the entire code.
Execution Time Limit
10 seconds
*/
import re
import ast, sys
string = sys.stdin.read()
# regex pattern
pattern = "<.*>"
# check whether pattern is present in string or not
result = re.search(pattern, string, re.M) # re.M enables tha tpettern to be searched in multiple lines
if (result != None) and (len(result.group()) > 6):
print(True)
else:
print(False)
|
a6c187a0ea878ff6a798f8f7f61ab1e8f1c6d9d0 | Nanofication/TWC-Naive-Bayes | /TWCNB.py | 9,327 | 3.703125 | 4 | """
Implementing Transformed Weighted Complement Naive Bayes for
classifying sentence.
Following research paper: Tackling the Poor Assumptions of Naive Bayes Text Classifiers
By:
Jason D. M. Rennie
Lawrence Shih
Jaime Teevan
David R. Karger
"""
import math
import nltk
from nltk.stem.lancaster import LancasterStemmer
# Word stemmer. Reduce words to the root forms for better classification
stemmer = LancasterStemmer()
# 3 classes of training data. Play around with this
training_data = []
training_data.append({"class":"greeting", "sentence":"how are you?"})
training_data.append({"class":"greeting", "sentence":"how is your day?"})
training_data.append({"class":"greeting", "sentence":"good day"})
training_data.append({"class":"greeting", "sentence":"how is it going today?"})
training_data.append({"class":"greeting", "sentence":"what's up?"})
training_data.append({"class":"greeting", "sentence":"hi"})
training_data.append({"class":"greeting", "sentence":"how are you doing?"})
training_data.append({"class":"greeting", "sentence":"what's new?"})
training_data.append({"class":"greeting", "sentence":"how's life?"})
training_data.append({"class":"greeting", "sentence":"how are you doing today?"})
training_data.append({"class":"greeting", "sentence":"good to see you"})
training_data.append({"class":"greeting", "sentence":"nice to see you"})
training_data.append({"class":"greeting", "sentence":"long time no see"})
training_data.append({"class":"greeting", "sentence":"it's been a while"})
training_data.append({"class":"greeting", "sentence":"nice to meet you"})
training_data.append({"class":"greeting", "sentence":"pleased to meet you"})
training_data.append({"class":"greeting", "sentence":"how do you do"})
training_data.append({"class":"greeting", "sentence":"yo"})
training_data.append({"class":"greeting", "sentence":"howdy"})
training_data.append({"class":"greeting", "sentence":"sup"})
# 20 training data
training_data.append({"class":"goodbye", "sentence":"have a nice day"})
training_data.append({"class":"goodbye", "sentence":"see you later"})
training_data.append({"class":"goodbye", "sentence":"have a nice day"})
training_data.append({"class":"goodbye", "sentence":"talk to you soon"})
training_data.append({"class":"goodbye", "sentence":"peace"})
training_data.append({"class":"goodbye", "sentence":"catch you later"})
training_data.append({"class":"goodbye", "sentence":"talk to you soon"})
training_data.append({"class":"goodbye", "sentence":"farewell"})
training_data.append({"class":"goodbye", "sentence":"have a good day"})
training_data.append({"class":"goodbye", "sentence":"take care"})
# 10 training datas
training_data.append({"class":"goodbye", "sentence":"bye!"})
training_data.append({"class":"goodbye", "sentence":"have a good one"})
training_data.append({"class":"goodbye", "sentence":"so long"})
training_data.append({"class":"goodbye", "sentence":"i'm out"})
training_data.append({"class":"goodbye", "sentence":"smell you later"})
training_data.append({"class":"goodbye", "sentence":"talk to you later"})
training_data.append({"class":"goodbye", "sentence":"take it easy"})
training_data.append({"class":"goodbye", "sentence":"i'm off"})
training_data.append({"class":"goodbye", "sentence":"until next time"})
training_data.append({"class":"goodbye", "sentence":"it was nice seeing you"})
training_data.append({"class":"goodbye", "sentence":"it's been real"})
training_data.append({"class":"goodbye", "sentence":"im out of here"})
training_data.append({"class":"sandwich", "sentence":"make me a sandwich"})
training_data.append({"class":"sandwich", "sentence":"can you make a sandwich?"})
training_data.append({"class":"sandwich", "sentence":"having a sandwich today?"})
training_data.append({"class":"sandwich", "sentence":"what's for lunch?"})
training_data.append({"class":"email", "sentence":"what's your email address?"})
training_data.append({"class":"email", "sentence":"may I get your email?"})
training_data.append({"class":"email", "sentence":"can I have your email?"})
training_data.append({"class":"email", "sentence":"what's your email?"})
training_data.append({"class":"email", "sentence":"let me get your email"})
training_data.append({"class":"email", "sentence":"give me your email"})
training_data.append({"class":"email", "sentence":"i'll take your email address"})
training_data.append({"class":"email", "sentence":"can I have your business email?"})
training_data.append({"class":"email", "sentence":"your email address?"})
training_data.append({"class":"email", "sentence":"email please?"})
training_data.append({"class":"email", "sentence":"may I have your email?"})
training_data.append({"class":"email", "sentence":"can I get your email?"})
corpus_words = {}
class_words = {}
lemmatized_sentences = []
# Turn a list into a set of unique items and then a list again to remove duplications
classes = list(set([a['class'] for a in training_data]))
for c in classes:
class_words[c] = []
# Loop through each sentence in our training data
for data in training_data:
# Tokenize each sentence into words
sentence = set()
for word in nltk.word_tokenize(data['sentence']):
# ignore some things
if word not in ["?", "'s"]:
stemmed_word = stemmer.stem(word.lower())
# Have we not seen this word already?
if stemmed_word not in corpus_words:
corpus_words[stemmed_word] = 1
else:
corpus_words[stemmed_word] += 1
# Add the word to our words in class list
sentence.add(stemmed_word)
# This is frequency so we need to change this part
class_words[data['class']].extend([stemmed_word])
lemmatized_sentences.append(sentence)
def convertAllFrequencies():
"""
Loop through all the words and convert the frequencies
"""
global corpus_words
for key, value in corpus_words.iteritems():
corpus_words[key] = transformTermFrequency(value)
def transformTermFrequency(freq):
"""
Adjust the given term's frequency to produce a more empirical distribution
Note: We use this after the regular frequencies of all words are figured out
We just adjust them
:return: the terms adjusted frequency
"""
return math.log10(freq + 1)
def inverseDocumentFrequency():
"""
Recalculate frequencies based on the term's number of occurrences in document
:return: Recalculated frequencies
"""
global corpus_words
for key, val in corpus_words.iteritems():
numerator = len(training_data)
denominator = 0 # I need to find a way to avoid this issue
for sentence in lemmatized_sentences:
denominator += wordInDocument(key, sentence)
corpus_words[key] = val * math.log10(numerator/denominator)
# def lengthTransformation():
# """
# Calculate the frequencies based on the terms frequency per document
# And then recalculate the entire frequency.
# :return: Recalculated frequencies
# """
# global corpus_words I"M SKIPPING STEP 3 BECAUSE MULTINOMIAL MODEL DOES IT VERY WELL
# AND CHANGES ARE SUBTLE
def weightNormalizing(score):
"""
Normalize the score from naive bayes
:param score: The score calculated using naive bayes
:return: recalculated score
"""
weight = math.log10(math.fabs(score))
weight = weight / (math.log10(math.fabs()))
return weight
# DOUBLE CHECK THIS FUNCTION IT CURRENTLY DOES NOT WORK PROPERLY!
def calculate_class_score(sentence, class_name, show_details=True):
score = 0
for word in nltk.word_tokenize(sentence):
if stemmer.stem(word.lower()) in class_words[class_name]:
# Treat each word with relative weight
current_score = 1.0 / corpus_words[stemmer.stem(word.lower())] # Frequency of all classes
score += current_score
if show_details:
print (
" match: %s (%s)" % (stemmer.stem(word.lower()), 1.0 / corpus_words[stemmer.stem(word.lower())]))
return score
def wordInDocument(word, sentence):
"""
Check if the word passed in is in the document.
:param word: The word being checked if the document contains it
:return: If word exists in document return 1 else 0
"""
if word in sentence:
return 1
return 0
def classify(sentence):
high_class = None
high_score = 0
# loop through our classes
for c in class_words.keys():
# calculate score of sentence for each class
score = calculate_class_score(sentence, c)
# keep track of highest score
if score > high_score:
high_class = c
high_score = score
return high_class, high_score
# for key,value in corpus_words.iteritems():
# print "Key: ", key," ", "Value: ", value
# convertAllFrequencies()
#
# print "AFTER CONVERSION!"
#
# for key,value in corpus_words.iteritems():
# print "Key: ", key," ", "Value: ", value
# # print("Class words: {0}").format(class_words)
#
# inverseDocumentFrequency()
# print "After Inverse Doc Frequency"
#
# for key,value in corpus_words.iteritems():
# print "Key: ", key," ", "Value: ", value
#
# sentence = raw_input("Type a sentence: ")
#
# print classify(sentence)
for key,val in class_words.iteritems():
print "Key: ", key," ", "Value: ", val |
41da165268912569b241978eeddecfcb0dd29586 | xiangyang0906/python_lianxi | /zuoye5/字典的推导式01.py | 324 | 4.28125 | 4 | # 语法;{表达式1:表达式2 for .... in .....}
dict01 = {"a": 10, "b": 20}
new_dict01 = {}
for key, value in dict01.items():
new_dict01[key] = value
print(new_dict01)
new_dict02 = {key: value for key, value in dict01.items()}
print(new_dict02)
dic01 = {k: v for k, v in zip(list("ABC"), list("123"))}
print(dic01) |
fa2b58b559b104fe2c84abf98383c8724e09ef08 | Samana19/PythonProjectOne | /PythonLabThree/Prob3.py | 258 | 3.625 | 4 | '''Write a function called showNumbers that takes a parameter called limit.It should print all the numbers between 0 and
limit with a label to identify the even and odd numbers. For example, if the limit is 3, it should print:0 EVEN1
ODD2 EVEN''' |
d5fff4279e24a670cbf597f2a3741e0561eaeb75 | rogerssantos/PythonProgramming | /Learning/Lesson 5.py | 1,240 | 3.859375 | 4 | Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:16:59) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> numbers = [20, 50, 29, 87, 45]
>>> numbers[2]
29
>>> numbers[2] = 43
>>> numbers
[20, 50, 43, 87, 45]
>>> numbers + [47, 33, 99]
[20, 50, 43, 87, 45, 47, 33, 99]
>>> numbers
[20, 50, 43, 87, 45]
>>> numbers.append(28)
>>> numbers
[20, 50, 43, 87, 45, 28]
>>> numberns.append(99)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
numberns.append(99)
NameError: name 'numberns' is not defined
>>> numbers.append(99)
>>> numberns
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
numberns
NameError: name 'numberns' is not defined
>>> numbers
[20, 50, 43, 87, 45, 28, 99]
>>> numbers[:3]
[20, 50, 43]
>>> numbers[:2] - [0, 0]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
numbers[:2] - [0, 0]
TypeError: unsupported operand type(s) for -: 'list' and 'list'
>>> numbers[:2] = [0, 0]
>>> numbers
[0, 0, 43, 87, 45, 28, 99]
>>> numbers[:2] = [0, 0]
>>> numbers
[0, 0, 43, 87, 45, 28, 99]
>>> numbers[:2] = []
>>> numbers
[43, 87, 45, 28, 99]
>>> numbers [:] = []
>>> numbers
[]
>>>
|
cdc340410d1a9bacadcc6b90c92865b455685a10 | Nicholas-O-Atkins/Projects | /Courses/CS2004(Intro to OS)/A5/BestfitDynamic.py | 7,309 | 4.3125 | 4 | """
Author: Nicholas Atkins Due Date: 3/4/2018
Purpose: To demonstrate the best fit algorithm with dynamic partitioned memory
Problems: There are a lot of if and else statements making this very hard to understand
just by reading the code, I hope the comments spread throughout the code will help understand the
thought process behind it
How to run the program:
1. Open the file into a python compiler
2. If you wish you can test the test as well, just run it like a normal .py file
3. Enter an int value greater than 20
4. Hold enter until you are satisfied
"""
# Having this module made making the random selections easier
from random import *
def random_job_number():
"""
This will take create a string job integer between two numbers
:return: a string
"""
x = randint(1, 10) # controls the number of different jobs for the program to run
return 'job' + str(x)
def random_size():
"""
This will return a random integer between
:return: an integer
"""
return randint(1, 100) # You can fiddle with this portion, this controls the max and min size of the jobs
def in_or_out():
"""
creates a string in or out
:return: a string
"""
x = randint(1,2) # these are set so don't change them
if x == 1:
return 'in'
else:
return 'out'
def print_memory(listed):
""""
prints the job in the memory and the free space as well
:returns an integer
"""
contained = []
start = 0
for x in range(1, len(listed)):
if x == 1:
start = x-1
elif listed[x-1] != listed[x]:
print(listed[x-1], ' ', start, ' ', x-1)
contained.append(listed[x-1])
start = x
if(x == len(listed)-1 and listed[x] != listed[x-1]): # This had to be added, it wouldn't print last item
print(listed[x], ' ', start, ' ', x)
contained.append(listed[x])
if(x == len(listed)-1 and (listed[x] not in contained or listed[x] is None)): # Not sure if this is
print(listed[x], ' ', start, ' ', x) # Necessary however it may catch something I haven't seen
contained.append(listed[x])
return contained
def count_none(listed): # Just a fancy tool to let you know that there are extra spaces leftover total
"""
Counts the number of free spaces left
:return: an integer
"""
count = 0
for i in range(0, len(listed)):
if listed[i] is None:
count += 1
return count
def main():
job_dict = {} # Where the jobs are stored post allocation
max_size = 19 # my OS takes 20 spaces therefore it can't be smaller than the OS
while(max_size < 20):
max_size = int(input("Enter the size of the the memory: ")) # Anything that isn't an int will break this
# would had used a try statement however, all nighters suck
memory_list = [None] * max_size
for x in range(0,20):
memory_list[x] = 'OS'
again = True
while again:
op = in_or_out()
if op == 'in': # This is the in section of the code
"""
Job in will check the job dict for the job, if not will
attempt to allocate space for the job if there is room otherwise will toss the job
"""
print('In was selected')
job = random_job_number()
size = random_size()
found = job_dict.get(job)
if found is None:
empty_space = []
count = 0
start = 0
"""
A lot of time was spent here trying to find the problem with
the None track and markers
"""
for y in range(0, len(memory_list)):
if count == 0 and memory_list[y] is None:
start = y
count = 1
if (count == 1 and memory_list[y] is not None) or (y == len(memory_list)-1 and
memory_list[len(memory_list)-1] is None):
empty_space.append([start, y])
start = y
count = 0
remainder = []
for y in range(0, len(empty_space)):
space = int(empty_space[y][1]) - int(empty_space[y][0])
remainder.append(space-size)
index = -1
for y in range(0, len(remainder)):
if index < 0: # Added this to make sure we never get a remainder below 0
if remainder[y] >= 0:
index = y
else:
if 0 <= remainder[y] < remainder[index]:
index = y
if index == -1: # Meaning there was not enough space for allocation
print("There is not enough space for ", job)
else: # The job has enough space to be placed
print('Allocating space for ', job)
for i in range(0, size):
memory_list[empty_space[index][0] + i] = job
job_dict[job] = [empty_space[index][0], empty_space[index][0]+size-1]
else:
startnfinish = job_dict.get(job) # checking the dictionary set up at the start to see if it is included
print('it is in the dict file')
blank = True
print(startnfinish)
for x in range(startnfinish[0], startnfinish[1]):
if memory_list[x] is not None:
blank = False # if something is in the spot allocated to it in the dict, it will cause a false
if blank:
for x in range(startnfinish[0], startnfinish[1]):
memory_list[x] = job
else:
print('There is something occupying the space for that job')
else: # This is the out section of the code
"""
Job out will see if there is a process in memory list with that name and remove it
"""
job = random_job_number()
print('Out was selected')
if job in memory_list: # if the job is found it will remove the job from the space it is in
for x in range(0, len(memory_list)):
if memory_list[x] == job:
memory_list[x] = None
print('Cleared ', job)
else: # The job was not found in the memory so it wont remove it
print('The job ', job, 'is not in memory')
# prints off the full list minus the Nones at the end, for some reason they didn't want to print
cookie = print_memory(memory_list)
print(cookie, 'There are ', count_none(memory_list), 'blank spaces\n\n') # blank meaning spares
# Holding down enter will give the same result as typing yes, it is intended
response = str(input("Again? Yes or No: "))
if response == 'No' or response == 'no':
again = False
else:
again = True
print('\n')
if __name__ == '__main__':
main()
|
ea7120d2e9c435e1fc3527024b1828c231ba47d7 | andrhahn/pi-spy | /client/src/example/utils.py | 2,385 | 3.53125 | 4 | import io
import os
def copy_file_to_stream(input_file_name):
"""Copies a file fto a stream"""
input_file = open(input_file_name, 'rb')
stream = io.BytesIO()
l = input_file.read(1024)
while l:
stream.write(l)
l = input_file.read(1024)
stream_size = stream.tell()
stream.write('\r\n\r\n'.encode('UTF-8'))
return stream, stream_size
def copy_file_with_stream(input_file_name, output_file_name):
"""Copies a file from the file system into an output file on the file system using streams"""
input_file = open(input_file_name, 'rb')
stream = io.BytesIO()
l = input_file.read(1024)
with open(output_file_name, 'w') as output_file:
while l:
output_file.write(l)
stream.write(l)
l = input_file.read(1024)
output_file.close()
input_file.close()
assert os.path.getsize(output_file_name) == stream.tell()
def write_bytes_to_socket(socket_connection, file_name):
"""Writes a file's bytes from a file on the file system to a socket connection"""
input_file = open(file_name, 'rb')
l = input_file.read()
while l:
socket_connection.send(l)
l = input_file.read(1024)
input_file.close()
def write_file_to_http_wfile(base_http_request_handler, file_name):
input_file = open(file_name, 'rb')
data = input_file.read()
base_http_request_handler.wfile.write(data)
input_file.close()
def write_file_to_http_wfile_with_streams(base_http_request_handler, file_name):
input_file = open(file_name, 'rb')
l = input_file.read()
while l:
base_http_request_handler.wfile.write(l)
l = input_file.read(1024)
input_file.close()
def write_image_stream_to_http_wfile_with_streams(base_http_request_handler, image_stream):
l = image_stream.read(1024)
with open('/Users/andrhahn/out1.jpg', 'w') as output_file:
while l:
output_file.write(l)
l = image_stream.read(1024)
output_file.close()
write_file_to_http_wfile(base_http_request_handler, '/Users/andrhahn/out1.jpg')
def write_image_stream_to_file(file_name, image_stream):
l = image_stream.read(1024)
with open(file_name, 'w') as output_file:
while l:
output_file.write(l)
l = image_stream.read(1024)
output_file.close()
|
f99c94a3adccac346bf853a83f1724e900d3b56e | ericbgarnick/AOC | /y2019/saved/day10/day10.py | 5,324 | 3.578125 | 4 | import math
import sys
from fractions import Fraction
from functools import partial
from typing import Tuple, Set, List
Point = Tuple[int, int]
ASTEROID = '#'
def day10_part1(puzzle_data: List[List[str]]) -> Tuple[Point, int]:
max_x = len(puzzle_data[0])
max_y = len(puzzle_data)
best_num_visible = 0
best_position = None
asteroid_coords = _find_asteroid_coords(puzzle_data)
for candidate in asteroid_coords:
num_visible = 0
seen_asteroids = {candidate}
for other in asteroid_coords:
if other not in seen_asteroids:
num_visible += 1
seen_asteroids.add(other)
seen_asteroids |= set(_calc_points_in_line(candidate, other,
asteroid_coords,
max_x, max_y))
if num_visible > best_num_visible:
best_num_visible = num_visible
best_position = candidate
return best_position, best_num_visible
def day10_part2(puzzle_data: List[List[str]], origin: Point) -> int:
laser_count = 200
max_x = len(puzzle_data[0])
max_y = len(puzzle_data)
asteroid_coords = _find_asteroid_coords(puzzle_data)
seen_asteroids = {origin}
radii = []
for other in asteroid_coords:
if other not in seen_asteroids:
seen_asteroids.add(other)
radius = _calc_points_in_line(origin, other, asteroid_coords,
max_x, max_y)
radii.append(radius)
seen_asteroids |= set(radius)
ordered_radii = _sort_radii(origin, radii)
lasered = _laser_asteroids(ordered_radii, laser_count)
last_x, last_y = lasered[-1]
return last_x * 100 + last_y
def _find_asteroid_coords(asteroid_map: List[List[str]]) -> Set[Point]:
asteroid_coords = set()
for y, row in enumerate(asteroid_map):
for x, pos in enumerate(row):
if pos == ASTEROID:
asteroid_coords.add((x, y))
return asteroid_coords
def _calc_points_in_line(candidate: Point, other: Point, asteroids: Set[Point],
max_x: int, max_y: int) -> List[Point]:
diff_x = other[0] - candidate[0]
diff_y = other[1] - candidate[1]
last_x = max_x if diff_x > 0 else -1
last_y = max_y if diff_y > 0 else -1
if diff_x != 0:
slope = Fraction(diff_y, diff_x)
diff_y = abs(slope.numerator) if last_y > -1 else -1 * abs(slope.numerator)
diff_x = abs(slope.denominator) if last_x > -1 else -1 * abs(slope.denominator)
else:
diff_y = 1 if last_y > -1 else -1
diff_x = 0
if diff_x and diff_y:
# diagonal
x_vals = [x for x in range(candidate[0], last_x, diff_x)]
y_vals = [y for y in range(candidate[1], last_y, diff_y)]
points_in_line = list(zip(x_vals, y_vals))
elif diff_x:
# horizontal
points_in_line = [(x, candidate[1]) for x in
range(candidate[0], last_x, diff_x)]
else:
# vertical
points_in_line = [(candidate[0], y) for y in
range(candidate[1], last_y, diff_y)]
# skip candidate coords and those that are not asteroids
return [p for p in points_in_line[1:] if p in asteroids]
def _sort_radii(origin: Point, radii: List[List[Point]]) -> List[List[Point]]:
sort_func = partial(_angle_from_origin, origin)
return sorted(radii, key=sort_func)
def _angle_from_origin(origin: Point, radius: List[Point]) -> float:
origin_x, origin_y = origin
point_x, point_y = radius[0]
# Switch y because this coordinate system is upside-down
delta_y = origin_y - point_y
delta_x = point_x - origin_x
if delta_x < 0 < delta_y:
delta_y *= -1
to_add = math.pi
elif delta_x < 0 and delta_y == 0:
to_add = math.pi
elif delta_x < 0 and delta_y < 0:
delta_y *= -1
to_add = math.pi
else:
to_add = 0
try:
angle = math.acos(delta_y / math.sqrt(delta_x ** 2 + delta_y ** 2))
except ZeroDivisionError:
angle = 0
angle += to_add
return angle
def _laser_asteroids(asteroid_radii: List[List[Point]], num_shots: int) -> List[Point]:
cur_radius_idx = -1
shot_asteroids = []
while len(shot_asteroids) < num_shots and len(asteroid_radii):
cur_radius_idx = (cur_radius_idx + 1) % len(asteroid_radii)
try:
cur_radius = asteroid_radii[cur_radius_idx]
except IndexError as e:
raise e
shot_asteroids.append(cur_radius[0])
if len(cur_radius) == 1:
# drop current radius and decrement idx
asteroid_radii = (asteroid_radii[:cur_radius_idx] +
asteroid_radii[cur_radius_idx + 1:])
cur_radius_idx -= 1
else:
cur_radius = cur_radius[1:]
asteroid_radii[cur_radius_idx] = cur_radius
return shot_asteroids
if __name__ == '__main__':
data_file = sys.argv[1]
data = [list(line.strip()) for line in open(data_file, 'r').readlines()]
position, visible = day10_part1(data)
print(f"PART 1:\n{visible} visible asteroids from {position}")
print(f"PART 2:\n{day10_part2(data, position)}")
|
6f73f1c16a277efa0941e96a29ad9a79f35fa00c | zlw241/CodeEval | /Medium/reverse_groups.py | 677 | 3.875 | 4 |
def reverse_intervals(string):
rm_semicolon = string.split(";")
num_list = [int(i) for i in rm_semicolon[0].split(',')]
interval = int(rm_semicolon[1])
remainder = len(num_list)%interval
separated = [list(reversed(num_list[i:i+interval])) for i in range(0,len(num_list), interval)]
if remainder > 0:
separated[-1] = list(reversed(separated[-1]))
flattened = [str(i) for arr in separated for i in arr]
return ','.join(flattened)
test_case1 = "1,2,3,4,5;2"
test_case2 = "1,2,3,4,5;3"
test_case3 = "1,2,3,4,5,6,7,8,9;3"
print(reverse_intervals(test_case2))
print(reverse_intervals(test_case1))
print(reverse_intervals(test_case3)) |
75ccacf88d81abe84a956be18fa2654da2683e50 | LauraBrogan/2021-Computational-Thinking-with-Algorithms-Project | /mergesort.py | 1,459 | 4.5 | 4 | #CTA Project 2021
#Merge Sort
#Resourse used:https://runestone.academy/runestone/books/published/pythonds/SortSearch/TheMergeSort.html
def mergesort(array):
#print is used in testing to see the breakdown of sorting process
print("Splitting ",array)
#This recursive algorithm splits the list in half
if len(array)>1:
mid = len(array)//2
lefthalf = array[:mid]
righthalf = array[mid:]
mergesort(lefthalf)
mergesort(righthalf)
i=0
j=0
k=0
#It continues to divide the array until each item is individual
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] <= righthalf[j]:
array[k]=lefthalf[i]
i=i+1
else:
array[k]=righthalf[j]
j=j+1
k=k+1
#Once it is divided it is them merged into the correct order as it look at each individual sub array
while i < len(lefthalf):
array[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
array[k]=righthalf[j]
j=j+1
k=k+1
#print is used in testing to see the breakdown of sorting process
print("Merging ",array)
#Sample array
array = [54,26,93,17,77,31,44,55,20]
#Run merge sort on the sample array
mergesort(array)
#Print array for testing to see results of running merge sort.
print(array)
#Laura Brogan 11/04/2021 |
dc1c74fff3044a9e75988b6b9cedb42c280e37bb | 314H/competitive-programming | /marathon-codes/Maratonas/U_._R_._I/1. iniciante/iniciante-1176.py | 549 | 3.71875 | 4 | # 1145 - Fibonacci em Vetor
# Exemplo de Entrada
# 3
# 0
# 4
# 2
# Exemplo de Saída
# Fib(0) = 0
# Fib(4) = 3
# Fib(2) = 1
vetor_fibonacci = {}
vetor_fibonacci[0] = 0
vetor_fibonacci[1] = 1
def fib_top_down(f):
if(f in vetor_fibonacci):
return vetor_fibonacci[f]
else:
vetor_fibonacci[f] = fib_top_down(f-1) + fib_top_down(f-2)
return vetor_fibonacci[f]
n = int(input())
lista = []
for i in range(n):
q = int(input())
lista.append( (q, fib_top_down(q)) )
for j in lista:
print("Fib(" + str(j[0]) + ") = " + str(j[1]) ) |
811be7f9fecd5b70949cbe776c3171c9dd73f931 | meetrainier/ManojMath | /Diff_eqn/compute_fourier.py | 344 | 3.703125 | 4 | #Inro: Shows how to compute a fourier series
import math
#B =float(input("Input B="))
import sympy as sy
from sympy import fourier_series, pi, cos, sin
from sympy.abc import t
from sympy.functions.special.delta_functions import Heaviside
T = sy.symbols('T')
s = fourier_series(Heaviside(t) - Heaviside(t-1/4), (t, 0, 1))
print(s.truncate(3))
|
6578a2ecbdd0b7e4d31409e38f8bde4ca74b6d48 | TheGingerNinjaC/Cigar_Party_Python | /CigarParty.py | 1,480 | 4.5625 | 5 | '''
Author: Chane van der Berg
Date: 13/05/2018
When squirrels get together for a party, they like to smoke cigars.
A squirrel party is successful when there were between 40 (inclusive)
and 60 (inclusive) cigars, unless it is weekend when there is no
upper limit on the number of cigars.
Write a function cigar_party() that determines whether the party was
successful or not. The function must receive as parameters an integer
value for the number of cigars as well as an integer value to indicate
a weekend. The function must then determine if it was a successful
party or not and return a true (1) or a false (0) value (true for
successful and false for unsuccessful) to the calling statement in the
main program.
Complete the Python program by asking the user to enter the number
of cigars and indicate whether it is weekend or not. After that, the
program must call the cigar_party() function with the values entered by
the user and display the result
'''
def cigar_party(a,b):
party = ''
if b == 0:
if a >= 40 and a <= 60:
party = 1
else:
party = 0
if b == 1:
if a >= 40:
party = 1
else:
party = 0
if party == 1:
return 'Yes! It was a successful cigar party!!!'
elif party == 0:
return 'No, it was a disappointing cigar party...'
cig = int(input("Enter the number of cigars: "))
day = int(input("Is it weekend? (1=True, 0=False) "))
print(cigar_party(cig,day))
|
de70918cd86e8bd4df2c7451f6f1f1deb697c97d | andrei011011/google-code-sample | /google-code-sample/python/src/video_playlist.py | 1,197 | 3.921875 | 4 | """A video playlist class."""
class Playlist:
"""A class used to represent a Playlist."""
def __init__(self, playlist_title: str):
self._title = playlist_title
self._videos = []
@property
def title(self) -> str:
"""Returns the title of a Playlist."""
return self._title
def add_video(self, video):
self._videos.append(video)
def remove_video(self, video):
self._videos.pop(self._videos.index(video))
def contains_video(self, video):
contains_video = False
for vid in self._videos:
if vid == video:
contains_video = True
break
return contains_video
def clear(self):
self._videos = []
class PlaylistLibrary:
"""A class used to represent a Playlist Library."""
def __init__(self):
self.playlist_list = []
def get_playlist(self, playlist_name):
for playlist in self.playlist_list:
if playlist.title.upper() == playlist_name.upper():
return playlist
return None
def delete_playlist(self, playlist):
self.playlist_list.pop(self.playlist_list.index(playlist)) |
7e678783284f82bd4e867babbf3ebe6253a3538f | abiudmelaku/Inventory-System | /Customer.py | 1,822 | 3.703125 | 4 | class Customer:
def __init__(self):
self.__baughtItems = []
self.__bill = 0
def get_cart(self):
return self.__baughtItems
def get_bill(self):
return f"Your current bill is ${round(self.__bill , 2)}";
def add_to_cart(self , item):
self.__baughtItems.append(item)
def add_to_Bill(self , bill):
self.__bill += bill
def substract_from_Bill(self, bill):
self.__bill -= bill
def update_cart(self,catName,itemName,diffrence,add):
newAmount = None
if add:
for index , i in enumerate(self.__baughtItems):
cat_name, item_name, item_amount = i
if cat_name == catName and item_name == itemName:
newAmount = item_amount
break;
newAmount += diffrence
self.__baughtItems.pop(index)
self.__baughtItems.append((cat_name, item_name, newAmount))
else:
for index, i in enumerate(self.__baughtItems):
cat_name, item_name, item_amount = i
if cat_name == catName and item_name == itemName:
newAmount = item_amount
break;
newAmount -= diffrence
self.__baughtItems.pop(index)
self.__baughtItems.append((cat_name, item_name, newAmount))
def delete_fromCart(self , item , price):
catName,itemName,itemAmount = item[0],item[1],item[2]
for index , i in enumerate(self.__baughtItems):
cat_name, item_name, item_amount = i
if cat_name == catName and item_name == itemName:
break;
self.substract_from_Bill(itemAmount * price) # Subtracts from bill
self.__baughtItems.pop(index) # deletes from cart
return item_amount
|
7b5bc20898ec1359e6fb279118e70fe44307cab2 | sydoky/Python | /python class 7/ClassThing.py | 5,194 | 3.796875 | 4 | class Coin:
def __init__(self, denomination, year, mintage, material, origin, grade, grade_level, price):
self.denomination = denomination
self.year = year
self.mintage = mintage
self.material = material
self.origin = origin
self.grade = grade
self.grade_level = grade_level
self.price = price
def __str__(self):
return self.denomination + ", " + str(self.year) + ", " + str(self.mintage) + ", " + self.origin + ", " \
+ self.grade.abbreviation + str(self.grade_level) + " $" + str(self.price)
def __gt__(self, other):
return self.age() > other.age() #we put () because it's a method , line 18
def age(self):
today = 2020
today = today - self.year
return str(today) + " years old"
class Grade:
def __init__(self, level_of_finest, abbreviation, scale, description):
self.level_of_finest = level_of_finest
self.abbreviation = abbreviation
self.scale = scale
self.description = description
def __gt__(self, other): #self will always be in the left and "other" on the right with comparison
grades_level = {
"VF": 1,
"XF": 2,
"AU": 3,
"MS": 4
}
return grades_level[self.abbreviation] > grades_level[other.abbreviation]
def __str__(self):
return self.abbreviation + ", " + str(self.scale)
class Grades:
def __init__(self):
self.vf = Grade("very fine", "VF", [20, 25, 30, 35], "Moderate wear")
self.xf = Grade("extremely fine", "XF", [40, 45], "well defined")
self.au = Grade("almost uncirculated", "AU", [50, 53, 55, 58], "high points")
self.ms = Grade("mint state", "MS", list(range(60, 71)), "perfect")
class Collection:
def __init__(self, name):
self.name = name
self.coins = []
def add_coin(self, coin):
self.coins.append(coin)
def remove(self, coin):
self.coins.remove(coin) # whatever we are in class, things do not exsit, those are just variables.
def value(self):
dollar = 0
for v in self.coins:
dollar = dollar + v.price
return dollar
def __str__(self):
coins = self.name + ": "
for c in self.coins:
coins += "\n" + str(c) #we added "\n" to move coins in lines seperately each/ to make new lines
return coins
def oldest(self):
oldest_coin = None
for c in self.coins:
if oldest_coin is None:
oldest_coin = c
else:
if c > oldest_coin:
oldest_coin = c
return oldest_coin
def best_grade(self):
highest_quality = None
for q in self.coins:
if highest_quality is None:
highest_quality = q.grade
else:
if q.grade > highest_quality:
highest_quality = q.grade
return highest_quality
def lowest_mintage(self):
more_rare = None
for r in self.coins:
if more_rare is None:
more_rare = r.mintage
else:
if r.mintage < more_rare:
more_rare = r.mintage
return more_rare
def rarest_coin(self):
rc = None #rc is the object/ rarest coin/ real coin
for c in self.coins: #I loop through all coins
if rc is None: #
rc = c
else:
if c.mintage < rc.mintage:
rc = c
return rc
def lowest_mintage2(self):
rarest_coin = self.rarest_coin()
return rarest_coin.mintage
def lowest_mintage3(self):
return self.rarest_coin().mintage
def highest_grade(self):
best_coin = None
for c in self.coins:
if best_coin is None:
best_coin = c.grade_level
else:
if c.grade_level > best_coin:
best_coin = c.grade_level
return best_coin
grades = Grades()
coin1 = Coin("rouble",1913, 2000000,"silver","Russia",grades.ms, grades.ms.scale[2], 100)
print(coin1)
coin2 = Coin("kopek", 1924, 5000, "Copper", "USSR", grades.au, grades.au.scale[2], 15)
print(coin2)
coin3 = Coin("rouble", 1899, 10000, "silver", "Russia", grades.xf, grades.xf.scale[0], 30)
print(coin3)
Mycollection = Collection("My collection")
Mycollection.add_coin(coin1)
Mycollection.add_coin(coin2)
Mycollection.add_coin(coin3)
#Mycollection.coins.append(coin1)
print(Mycollection)
print(Mycollection.value())
#Mycollection.remove(coin2)
print(Mycollection)
print(Mycollection.value())
print(coin1.age())
print(coin2.age())
Mycollection.oldest()
print(Mycollection.oldest())
print("-----------")
print(Mycollection.best_grade())
print(Mycollection.lowest_mintage())
print(Mycollection.rarest_coin())
print(Mycollection.lowest_mintage2())
print(Mycollection.highest_grade())
|
9ea595c378ed6b9165f09fd6ad4450eefa76416b | Minari766/study_python | /Paiza/Rank_D/paizad043_天気の表示.py | 198 | 3.703125 | 4 | # coding: utf-8
# 自分の得意な言語で
# Let's チャレンジ!!
n = int(input())
if n <= 30:
print("sunny")
elif 31 <= n <= 70:
print("cloudy")
elif n >= 71:
print("rainy")
|
cf8fb1afb069690f9e2d946ab0b5d24330327e5d | tfeLdnaH/Python | /sintaxerrorbug.py | 400 | 3.921875 | 4 | '''tuna = int(input("What´s your favorite number?\n"))
print(tuna)'''
while True:
try:
number = int(input("Whats ur fav. number?\n"))
print(18/number)
break
except ValueError:
print("Make sure and enter a number")
except ZeroDivisionError:
print("Dont pick zero")
except:
break
finally:
print("loop complety") |
638d12c564a0399e5811e31352531f4cd023f438 | vandrade88/python-challenge | /PyBank/main.py | 2,157 | 3.71875 | 4 | import os
import csv
# import file
pybank_csv = os.path.join("/Users/valerie/Desktop/DA_VA/homework/3_Python/python-challenge/PyBank/Resources/budget_data.csv")
pybank_text = os.path.join("/Users/valerie/Desktop/DA_VA/homework/3_Python/python-challenge/PyBank/Analysis/financial_analysis.txt")
# open and read csv file
with open(pybank_csv, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
csv_header = next(csv_file)
# define variables
row_count = 0
total_amount = 0
total_change = 0
last_month = 0
largest_increase = ['', 0]
largest_decrease = ['', 0]
# loop through rows starting with conditional to solve header issue
for row in csv_reader:
if row_count != 0:
total_change += int(row[1]) - last_month
average = total_change / row_count
# month counter for total months
row_count += 1
# total amount of profits/losses in column b
total_amount += int(row[1])
# calculate the difference between current and previous month's value
monthly_change = int(row[1]) - last_month
# conditional to find the largest increase and decrease + determine the corresponding date
if monthly_change > largest_increase[1]:
largest_increase[1] = monthly_change
largest_increase[0] = row[0]
if monthly_change < largest_decrease[1]:
largest_decrease[1] = monthly_change
largest_decrease[0] = row[0]
# reset previous row's value for next loop
last_month = int(row[1])
# define function for printing results
results = (
f"\nFinancial Analysis\n"
f"----------------------------------\n"
f"Total Months: {row_count}\n"
f"Total: ${total_amount}\n"
f"Average Change: ${round(average,2)}\n"
f"Greatest Increase in Profits: {largest_increase[0]} (${largest_increase[1]})\n"
f"Greatest Decrease in Profits: {largest_decrease[0]} (${largest_decrease[1]})\n"
)
# print results in terminal
print(results)
# export results to new text file
with open(pybank_text, "w") as text_file:
text_file.write(results) |
709b504aa33e086f76b46da717ea0e122828de3a | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/10-Supervised_Learning_with_scikit-learn/e24_regression_with_categorical_features.py | 889 | 3.671875 | 4 | """
Regression with categorical features
Having created the dummy variables from the 'Region' feature, you can build regression models as you did before.
Here, you'll use ridge regression to perform 5-fold cross-validation.
The feature array X and target variable array y have been pre-loaded.
"""
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
# Read 'gapminder.csv' into a DataFrame: df
df = pd.read_csv('gapminder.csv')
# convert dataframe column to numpy array
X = df['fertility'].to_numpy()
y = df['life'].to_numpy()
X = X.reshape(-1, 1)
y = y.reshape(-1, 1)
# Instantiate a ridge regressor: ridge
ridge = Ridge(alpha=0.5, normalize=True)
# Perform 5-fold cross-validation: ridge_cv
ridge_cv = cross_val_score(ridge, X, y, cv=5)
# Print the cross-validated scores
print(ridge_cv)
|
f7a3a0e610c04456b4f2001189107fa800d3e1f2 | KirutoChan/Leonhard | /leo6.py | 184 | 3.625 | 4 | def sum_square(n):
sum_square = 0
s = 0
for i in range(1, n + 1):
sum_square = sum_square + i**2
s = s + i
result = s ** 2 - sum_square
return result
print (sum_square(100))
|
dbacb229768b0a0e8fe24ff1f16164b0d08837a5 | SuperPipp/PinkProgrammingPython | /Python/counting,user.py | 124 | 3.921875 | 4 | s = int(input("Pick a starting number:\n"))
e = int(input("Pick an ending number:\n"))
for i in range(s, e +1):
print(i) |
d967dd1c05a94ffac4fb29fe7b4b701ba7c2d8af | HugoHugo/pythonplusplus | /pythonplusplus.py | 11,682 | 3.71875 | 4 | import ast,sys
#Global variables
#Sturcture to store the datatypes for variables since the AST does not do this
#may not be an appropriate solution when we start working on functions
varTypeStore = {}
#used for indentation for structures such as if, for, while, and functions
indentationLevel = 0
#used for tracking loop structures
loopStructureNum = 0
arrayCounter=0
outMain = ""
#Set datatype of variable
def setType(var, varType):
varTypeStore[var] = varType
return
#return datatype of node
#at this point, this function should only be used with the ast.Assign datatype
def getType(tree):
if isinstance(tree, ast.Num):
if type(tree.n) == type(0.234): #does not matter what number as long as float
return("float")
return("int")
elif isinstance(tree, ast.Str):
return("string")
elif(tree == True or tree == False):
return("bool")
elif isinstance(tree, ast.BoolOp):
return("bool")
elif isinstance(tree, ast.UnaryOp):
return("bool")
elif isinstance(tree, ast.Compare):
return("bool")
elif isinstance(tree, ast.NameConstant):
return(getType(tree.value))
elif isinstance(tree, ast.BinOp):
return(getType(tree.left))
elif isinstance(tree, ast.Name):
return(varTypeStore[tree.id])
elif isinstance(tree, ast.Return):
return(getType(tree.value))
elif isinstance(tree, ast.Call):
return(varTypeStore[tree.func.id])
else:
return("")
#recusively traverses the AST and checks the datatype of each node.
#Depending on the datatype, translate returns a string corresponding to each node
def translate(tree):
stringTrans = ""
global indentationLevel
global loopStructureNum
global arrayCounter
global outMain
if isinstance(tree, ast.AugAssign):
vIn = translate(tree.target)
stringTrans += vIn + " " + translate(tree.op).split(" ")[1] + "= " + translate(tree.value)
return stringTrans
elif isinstance(tree, ast.List):
Ltype = getType(tree.elts[0])
stringTrans += Ltype + " defArray" + str(arrayCounter) + "[] = {"
arrayCounter += 1
for i in range(0,len(tree.elts)):
if(i== len(tree.elts)-1):
stringTrans += translate(tree.elts[i])
break
stringTrans += translate(tree.elts[i]) + ","
stringTrans += "}"
return stringTrans
elif isinstance(tree, ast.While):
stringTrans = "while("
stringTrans += translate(tree.test)
stringTrans += ") {\n"
stringTrans += translateCodeBlock(tree.body)
stringTrans += "\t"*indentationLevel + "}"
return stringTrans
elif isinstance(tree, ast.For):
if isinstance(tree.iter, ast.Call):#'for var in range' type of loop
setType(tree.target.id, "int")
stringTrans = "for(int " + tree.target.id + " = "
v1 = translate(tree.iter.args[0])
v2 = translate(tree.iter.args[1])
stringTrans += v1 + "; " + tree.target.id + " < " + v2 + "; ++" + tree.target.id + "){\n"
stringTrans += translateCodeBlock(tree.body)
stringTrans += "\t"*indentationLevel + "}"
return stringTrans
if isinstance(tree.iter, ast.Str):#'for var in string' type of loop
loopStructureNum += 1
setType(tree.target.id, "string")
stringTrans += "string loopStruct" + str(loopStructureNum) + " = " + '"' + tree.iter.s + '"' + ";"
stringTrans += "\n" + "\t"*indentationLevel
stringTrans += "for(int n = 0; n < " + str(len(tree.iter.s)) + "; ++n){\n";
stringTrans += "\t"*(indentationLevel+1) + "string " + tree.target.id + "(1, loopStruct" + str(loopStructureNum) + "[n]);\n"
stringTrans += translateCodeBlock(tree.body)
stringTrans += "\t"*indentationLevel + "}"
return stringTrans
return "Not defined"
elif isinstance(tree, ast.Try):
stringTrans = "try{\n"
stringTrans += translateCodeBlock(tree.body)
stringTrans += "\t"*indentationLevel + "}"
if tree.handlers:
stringTrans += "catch(...){\n"
stringTrans += translateCodeBlock(tree.handlers[0].body)
stringTrans += "\t"*indentationLevel + "}"
return stringTrans
return stringTrans
elif isinstance(tree, ast.Expr):
stringTrans += translate(tree.value)
return stringTrans
elif isinstance(tree, ast.ExceptHandler):
stringTrans += translateCodeBlock(tree.body)
return stringTrans
#variables
elif isinstance(tree, ast.Assign):
varType = ""
if(tree.targets[0].id not in varTypeStore.keys()): #if the variable's type is not yet tracked
varType = getType(tree.value)
setType(tree.targets[0].id, varType)
varType += " "
stringTrans += varType + translate(tree.targets[0]) + " = " + translate(tree.value)
return(stringTrans)
elif isinstance(tree, ast.Name):
return(tree.id)
#Integers
elif isinstance(tree, ast.Num):
return(str(tree.n))
elif isinstance(tree, ast.BinOp):
if(isinstance(tree.op, ast.Pow)):
stringTrans += "pow(" + translate(tree.left) + translate(tree.op) + translate(tree.right) + ")"
return stringTrans
stringTrans += translate(tree.left) + translate(tree.op) + translate(tree.right)
return stringTrans
elif isinstance(tree, ast.Add):
return(" + ")
elif isinstance(tree, ast.Sub):
return(" - ")
elif isinstance(tree, ast.Mult):
return(" * ")
elif isinstance(tree, ast.Div):
return(" / ")
elif isinstance(tree, ast.Mod):
return(" % ")
elif isinstance(tree, ast.Pow):
return(",")
#TODO: still need decimal numbers
#TODO: still need these operators:
#elif isinstance(tree, ast.FloorDiv) "//"
#elif isinstance(tree, ast.Pow) "**"
#strings
elif isinstance(tree, ast.Str):
return('"' + tree.s + '"')
#Booleans
elif isinstance(tree, ast.NameConstant):
return(str(tree.value).lower())
elif isinstance(tree, ast.BoolOp):
if(isinstance(tree.op, ast.And) and (isinstance(tree.values[1], ast.BoolOp))):
if isinstance(tree.values[1].op, ast.Or):
stringTrans += translate(tree.values[0]) + translate(tree.op) + "(" + translate(tree.values[1]) + ")"
return(stringTrans)
stringTrans += translate(tree.values[0]) + translate(tree.op) + translate(tree.values[1])
return(stringTrans)
elif isinstance(tree, ast.UnaryOp):
if isinstance (tree.operand, ast.NameConstant): #checking order of operations
stringTrans += translate(tree.op) + translate(tree.operand)
else:
stringTrans += translate(tree.op) + "(" + translate(tree.operand) + ")"
return(stringTrans)
elif isinstance(tree, ast.Compare):
stringTrans += translate(tree.left) + translate(tree.ops[0]) + translate(tree.comparators[0])
return(stringTrans)
elif isinstance(tree, ast.And):
return(" && ")
elif isinstance(tree, ast.Or):
return(" || ")
elif isinstance(tree, ast.Not):
return("!")
elif isinstance(tree, ast.Eq):
return(" == ")
elif isinstance(tree, ast.NotEq):
return(" != ")
elif isinstance(tree, ast.Gt):
return(" > ")
elif isinstance(tree, ast.Lt):
return(" < ")
elif isinstance(tree, ast.GtE):
return(" >= ")
elif isinstance(tree, ast.LtE):
return(" <= ")
#if statements
elif isinstance(tree, ast.If):
stringTrans += "if(" + translate(tree.test) + "){\n"
stringTrans += translateCodeBlock(tree.body) + "\t"*indentationLevel + "}"
stringTrans += translateElseIf(tree.orelse)
return stringTrans
#function statements
elif isinstance(tree, ast.FunctionDef):
stringTrans += tree.name + "("
for i in range(len(tree.args.args)):
datatype = input("Enter datatype for argument " + tree.args.args[i].arg + ":")
setType(tree.args.args[i].arg, datatype)
stringTrans += datatype + " " + tree.args.args[i].arg
if i != len(tree.args.args)-1:
stringTrans += ", "
stringTrans += "){\n"
stringTrans += translateCodeBlock(tree.body) + "}\n\n"
funcType = getType(tree.body[-1])
setType(tree.name, funcType)
stringTrans = funcType + " " + stringTrans
outMain += stringTrans
return ""
elif isinstance(tree, ast.Return):
stringTrans += "return(" + translate(tree.value) + ")"
return stringTrans
elif isinstance(tree, ast.Call):
if tree.func.id == "print":
stringTrans += "cout << "
for i in range(0, len(tree.args)):
stringTrans += translate(tree.args[i])
if i != len(tree.args) - 1:
stringTrans += " << "
stringTrans += " << endl"
return stringTrans
stringTrans += tree.func.id + "("
for i in range(0, len(tree.args)):
stringTrans += translate(tree.args[i])
if i != len(tree.args)-1:
stringTrans += ", "
stringTrans += ")"
return(stringTrans)
else:
print("Error translating")
return("/*Error translating*/")
def translateElseIf(tree): #helper function for if translations
stringTrans = ""
if(not tree): #if there is not else or elif
return stringTrans
elif(isinstance(tree[0], ast.If)): #if there is an elif
stringTrans += "else if(" + translate(tree[0].test) + "){\n"
stringTrans += translateCodeBlock(tree[0].body) + "\t"*indentationLevel + "}"
stringTrans += translateElseIf(tree[0].orelse)
return stringTrans
else: #if there is an else
stringTrans += "else{\n"
stringTrans += translateCodeBlock(tree) + "\t"*indentationLevel + "}"
return stringTrans
#Breaks down code block into lines and translates each line separately
def translateCodeBlock(tree):
transString = ""
global indentationLevel
indentationLevel += 1
for i in tree:
if isinstance(i, ast.If) or isinstance(i, ast.For) or isinstance(i, ast.While) or isinstance(i, ast.Try):
transString += "\t"*indentationLevel + translate(i) + "\n"
elif isinstance(i, ast.FunctionDef):
transString += translate(i)
else:
transString += "\t"*indentationLevel + translate(i) + ";\n"
indentationLevel -= 1
return(transString)
#Fetch python code and create ast
try:
tree = ast.parse(open(sys.argv[1]).read())
translatedCode = translateCodeBlock(tree.body)
finalTranslationFileName = sys.argv[1].split("/")[len(sys.argv[1].split("/")) - 1]
finalTranslationFileName = finalTranslationFileName.split(".")
finalTranslationFileName[len(finalTranslationFileName) - 1] = ".cpp"
finalTranslationFileName = "".join(finalTranslationFileName)
except:
print("Error in finding the given file. Format of input: python3 pythonplusplus.py FILENAME.py")
sys.exit()
fT = open(finalTranslationFileName, 'w')
fT.write("#include <iostream>\n")
fT.write("#include <string>\n")
fT.write("#include <math.h>\n")
fT.write("#include <fstream>\n")
fT.write("using namespace std;\n\n")
fT.write(outMain)
fT.write("int main(){\n")
fT.write(translatedCode)
fT.write("\treturn 0;\n")
fT.write("}")
fT.close()
|
3adddf52fba857a193adf802ad5eab9817eb564b | lizzzcai/leetcode | /python/array/0049_Group_Anagrams.py | 1,872 | 3.84375 | 4 | '''
07/04/2020
49. Group Anagrams - Medium
Tag: Hash Table, String
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
'''
from typing import List
import collections
# Solution
class Solution1:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
'''
Time: O(NKlogK), N is the length of strs, K is the max length of string in strs. O(N)
as we iterate each string.
Space: O(NK)
'''
hmap = collections.defaultdict(list)
for s in strs:
hmap[tuple(sorted(s))].append(s)
return list(hmap.values())
class Solution2:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
'''
Time: O(NK), N is the length of strs, K is the max length of string in strs. O(N)
as we iterate each string.
Space: O(NK)
'''
hmap = collections.defaultdict(list)
for s in strs:
count = [0] * 26
for ch in s:
count[ord(ch)-ord('a')] += 1
hmap[tuple(count)].append(s)
return hmap.values()
# Unit Test
import unittest
class TestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_testCase(self):
for Sol in [Solution1(), Solution2()]:
func = Sol.groupAnagrams
out = func(["eat","tea","tan","ate","nat","bat"])
res = [["eat","tea","ate"],["tan","nat"],["bat"]]
self.assertEqual(set([tuple(sorted(x)) for x in out]), set([tuple(sorted(x)) for x in res]))
if __name__ == '__main__':
unittest.main() |
98beb56f0d0cd99b056b60e2001647e42f7e80fa | rgcosta7/Introduction-Python | /Lab 2.6.1.11.py | 387 | 3.9375 | 4 | '''
Event end time calculator
Name: Raul Costa
Date: 18/10/2021
Version: 1.0
'''
# Ask user for starting time and duration
hour = int(input("Starting time (hours): "))
mins = int(input("Starting time (minutes): "))
dura = int(input("Event duration (minutes): "))
# Calculate the finishing time
mins = (mins + dura)
hour = hour + mins // 60
# Print the result
print(f'{hour}:{mins % 60}')
|
46e3effa9e4ca654da089dad798d933e08fce4c7 | abhigupta4/Competitive-Coding | /Data Structures and ALgorithms/producer_consumer.py | 855 | 3.890625 | 4 | """
Solving producer-consumer problem using semaphores - Solved by mahdavipanah
"""
import threading
# Buffer size
N = 10
# Buffer init
buf = [0] * N
fill_count = threading.Semaphore(0)
empty_count = threading.Semaphore(N)
def produce():
print("One item produced!")
return 1
def producer():
front = 0
while True:
x = produce()
empty_count.acquire()
buf[front] = x
fill_count.release()
front = (front + 1) % N
def consume(y):
print("One item consumed!")
def consumer():
rear = 0
while True:
fill_count.acquire()
y = buf[rear]
empty_count.release()
consume(y)
rear = (rear + 1) % N
producer_thread = threading.Thread(target=producer)
consumer_thread = threading.Thread(target=consumer)
producer_thread.start()
consumer_thread.start() |
92c835d9f359fa90ac10bc4a6100f8296d3c66b9 | webclinic017/valuation_course | /valuation_undergraduate-spring_2021/session10A_quiz/non_cash_income_growth_perp.py | 2,033 | 3.796875 | 4 | # Session 10A post-class test problem 2
# This is the growth of income the firm makes from non-cash equity.
# http://people.stern.nyu.edu/adamodar/pdfiles/eqnotes/postclass/session10Atest.pdf
def non_cash_income_growth_prep(
net_income, book_value,
interest_income, cash_balance,
capital_expenditure, wc_diff,
total_debt_increase):
non_cash_income = net_income - interest_income
non_cash_roe = non_cash_income / (book_value - cash_balance)
equity_reinvestment_rate = \
(capital_expenditure + wc_diff - total_debt_increase) / \
non_cash_income
non_cash_income_growth = equity_reinvestment_rate * non_cash_roe
return non_cash_income_growth
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Net income")
parser.add_argument("-i", "--net_income", help="Net Income",
type=float, default=10)
parser.add_argument("-b", "--book_value", help="Book Value of Equity",
type=float, default=110)
parser.add_argument("-ii", "--interest_income", help="After-tax Interest Income",
type=float, default=1)
parser.add_argument("-cb", "--cash_balance", help="Cash Balance",
type=float, default=20)
parser.add_argument("-ce", "--capital_expenditure", help="Net Capital Expenditure",
type=float, default=4)
parser.add_argument("-wc", "--wc_diff",
help="Working Capital difference (positive for increase)",
type=float, default=2)
parser.add_argument("-di", "--total_debt_increase", help="Total Debt increase",
type=float, default=3)
args = parser.parse_args()
print(non_cash_income_growth_prep(
args.net_income, args.book_value,
args.interest_income, args.cash_balance,
args.capital_expenditure, args.wc_diff,
args.total_debt_increase))
# 0.03333333333333333
|
505033f029807229981f0daad0b62966943509a8 | mustafashakeel/learning | /python/MyScripts/expanded.py | 173 | 3.671875 | 4 | item = 0.70
rate = 1.05
tax = item * rate
total = item + tax
print( 'Item:\t' , '%.20f' % item )
print( 'Tax:\t' , '%.20f' % tax )
print( 'Total:\t' , '%.20f' % total ) |
442a350d085d19d92590a7e0d768d56bea7f7514 | lkrych/cprogramming | /kAndr/ch_1/freq_histogram.py | 774 | 3.890625 | 4 | import re
ALPHA = "abcdefghijklmnopqrstuvwxyz"
ALPHA_COUNT = {}
ALPHA_RE = re.compile('([A-z]+)')
user_input = input("Type in your input and then press enter to print histogram: ")
split_input = list(user_input)
for char in split_input:
if ALPHA_RE.match(char):
lower_char = char.lower()
if lower_char in ALPHA_COUNT:
ALPHA_COUNT[lower_char] = ALPHA_COUNT[lower_char] + 1
else:
ALPHA_COUNT[lower_char] = 1
print("<><><><><><><><><><><><><><><><><><><><><><><><><><><><>");
print("<><> histogram of different characters used in input <><>");
print("<><><><><><><><><><><><><><><><><><><><><><><><><><><><>");
for alpha in ALPHA:
if alpha in ALPHA_COUNT:
print(alpha + "\t", end='')
for i in range(ALPHA_COUNT[alpha]):
print("*", end='')
print()
|
f7cdaf4e28241acc28e42cb40d18f89cf9f89802 | ghostrider77/competitive-programming-skills | /Python/04_straight-flush.py | 1,013 | 3.65625 | 4 | import sys
from collections import namedtuple
Card = namedtuple('Card', ['suit', 'rank'])
def read_cards(line):
cards = []
for s in line.split():
suit = s[-1]
rank = convert_rank(s[:-1])
cards.append(Card(suit, rank))
return cards
def convert_rank(rank):
if rank == 'A':
return 14
if rank == 'K':
return 13
if rank == 'Q':
return 12
if rank == 'J':
return 11
if rank == 'T':
return 10
return int(rank)
def is_straight_flush(cards):
suits = {card.suit for card in cards}
if len(suits) != 1:
return False
ranks = sorted([card.rank for card in cards])
differences = [a - b for a, b in zip(ranks[1:], ranks)]
return (differences == [1, 1, 1, 1] or differences == [1, 1, 1, 9])
def main():
data = sys.stdin.read().splitlines()
cards = read_cards(data[0])
result = is_straight_flush(cards)
print('YES' if result else 'NO')
if __name__ == '__main__':
main()
|
d5c52aa585b5b42ae6a7ad3c883b61faa85be800 | mrmoore6/Module-8 | /Test/test_assign_average.py | 831 | 3.5625 | 4 | import unittest
from more_fun_with_collections import assign_average
class MyTestCase(unittest.TestCase):
def test_average_A(self):
self.assertEqual("You entered A", assign_average.switch_average('A'))
def test_average_B(self):
self.assertEqual("You entered B", assign_average.switch_average('B'))
def test_average_C(self):
self.assertEqual("You entered C", assign_average.switch_average('C'))
def test_average_D(self):
self.assertEqual("You entered D", assign_average.switch_average('D'))
def test_average_E(self):
self.assertEqual("You entered F", assign_average.switch_average('F'))
def test_average_NON_KEY(self):
self.assertEqual("This is grade doesn't exist.", assign_average.switch_average("Z"))
if __name__ == '__main__':
unittest.main()
|
5bb29e31c340ee1983a8aaeecd28cfe10351680f | moonlimb/scheme_to_js_translator | /xml_to_js/helper/decorate.py | 711 | 3.828125 | 4 | # file containing decorator / helper functions
# Q: Use decorators/wrapper function to add curly braces?
def make_fcn(fn):
def wrapper():
return fn() + "()"
return wrapper
def add_parens(fn):
def wrapper():
return "(" + fn() + ")"
return wrapper
def add_curly_braces(content):
def wrapper():
return "{" + content + "; }"
return wrapper
#keywords=['function', 'if', 'for']
"""
content_test= "function content"
@add_curly_braces
def decorator_test():
return content_test
loop_cond_test = "i=0; i<=10; i++"
@add_parens
def paren_test():
return loop_cond_test
fcn_name='square'
@make_fcn
def call_function():
return fcn_name
print decorator_test()
print paren_test()
print call_function()
"""
|
9ac572962c2126f62acd1e3cc576596ff719e950 | erichan1/CS1 | /lab2/lab2a.py | 4,500 | 3.921875 | 4 | '''Module for part a of lab2 of CS1. Various functions depending on the problems.'''
# B.1
def complement(str):
'''Takes in string with only letters A,C,T, and G.
returns DNA complement in the form of a string.'''
str2 = ''
for i in range(len(str)):
if str[i] == 'A':
str2 += 'T'
elif str[i] == 'C':
str2 += 'G'
elif str[i] == 'T':
str2 += 'A'
elif str[i] == 'G':
str2 += 'C'
return str2
# B.2
def list_complement(lst):
'''Takes in list with only letters A,C,T, and G.
Alters list to match complement of DNA.'''
for i in range(len(lst)):
if lst[i] == 'A':
lst[i] = 'T'
elif lst[i] == 'C':
lst[i] = 'G'
elif lst[i] == 'T':
lst[i] = 'A'
elif lst[i] == 'G':
lst[i] = 'C'
# B.3
def product(lst):
'''Takes in a list of numbers and returns the product of
all numbers in the list. If list is empty, will return 1.'''
if len(lst)<1:
return 1
else:
return product(lst[1:len(lst)]) * lst[0]
# B.4
def factorial(num):
'''Takes a non-negative integer and returns the factorial of that integer'''
numList = []
for i in range(1,num + 1):
numList.append(i)
return product(numList)
# B.5
import random
def dice(m,n):
'''simulates the rolling of an n number of m sided die.
Takes m and n as arguments and returns total value of rolled die'''
totalVal = 0
for i in range(n):
totalVal += random.choice(range(1,m + 1))
return totalVal
# B.6
def remove_all(lst,num):
'''removes all instances of num in lst.
Arguments are lst, a list of numbers, and num, the number to be removed.'''
while(lst.count(num)>0):
lst.remove(num)
# B.7
def remove_all2(lst,num):
'''removes all instances of num in lst.
Arguments are lst, a list of numbers, and num, the number to be removed.'''
for i in range(lst.count(num)):
lst.remove(num)
def remove_all3(lst,num):
'''removes all instances of num in lst.
Arguments are lst, a list of numbers, and num, the number to be removed.'''
while(num in lst):
lst.remove(num)
# B.8
def any_in(lst1,lst2):
'''Takes two lists as arguments.
Returns a boolean that checks if any elements in list 1 exist in list 2.'''
i = 0
while(i<len(lst1)):
if(lst1[i] in lst2):
return True
i += 1
return False
# C.1.a
# a=0 is assignment. a==0 will check if a has become a zero.
# C.1.b
# The argument 's' is a one letter string, not the string variable s.
# Because the variable s hasn't been initialized or defined, function will fail.
# Turn the 's' in the argument into just s.
# C.1.c
# 's' + '-Caltech' always equals 's-Caltech'. It doesn't actually use the
# string argument s. Turn 's' into just s.
# C.1.d
# The plus operator doesn't work between lists and strings.
# lst.append('bam') would be a better choice.
# C.1.e
# lst.reverse() doesn't return anything, so lst2 has a null value.
# Docstring for reverse() says it reverses in place.
# lst.append() also doesn't return anything, so nothing will be returned.
# fix would be:
# lst.reverse()
# lst.append(0)
# return lst
# C.1.f
# If you append a list to the end of another list, you get a list
# within another list, like so: ['a','b',['c','d','e']].
# To fix, I would iterate through the string with a for loop and
# append each char in the string to the list.
# Also, in the arguments, a 'list' variable is defined. This overwrites the
# name list. list(str) then fails bc list is now a variable name.
# C.2
# When c is assigned, the values of a and b are 10 and 20. Thus, c=30.
# Changing the value of a after c is assigned does not affect the value of c.
# C.3
# The first line of code would work because add_and_double_1 returns a value.
# That value can be multiplied by 2 and assigned to result.
# On the other hand, add_and_double_2 prints a value and doesn't return it.
# Thus, the function call becomes n = 2 * null, which will cause an error.
# C.4
# Second function call has too many arguments. It's supposed to get x and y through the input function.
# First function call has correct number of arguments.
# C.5
# Strings are immutable once a value is assigned to them. You cannot reassign
# one char in the string.
# C.6
# item is not called by reference. Thus, the item in
# item *= 2 is entirely seperate from the value in the list.
|
9a79a08235f147724935867104de4cd4562f6c98 | staceysara/PythongProgramming | /Project1130/Project1130.py | 4,347 | 3.53125 | 4 | import numpy as np
from matplotlib import pyplot as plt
#data = np.array([[1,2,3],[4,5,6],[7,8,9]])
#print(data+2)#[[3 4 5][6 7 8][9 10 11]]
#print(data-2)#[[-1 0 1][2 3 4][5 6 7]]
#print(data*data)#[[1 4 9][16 25 36][49 64 81]]#not a matrix multiplication
#print(data.dot(data))#[[30 36 42][66 81 96][102 126 150]]
#------------------
#a = np.array([1,2,3,4])
#b = np.array([4,2,2,4])
#c = np.array([1,2,3,4])
##이렇게 하면 각 원소에 대한 비교임.
#print(a==b)#False true false true
#print(a>b)#false false true false
##array전체에 대한 비교
#print(np.array_equal(a,b))#false
#print(np.array_equal(a,c))#true
#----------------
#a = np.array([1,1,0,0],dtype=bool)
#b = np.array([1,0,1,0],dtype=bool)
#print(np.logical_or(a,b))#[true true true false]
#print(np.logical_and(a,b))#[true false false false]
#---------
#print(np.all([True,True,False]))#안에있는게 다 true여야 true임
#print(np.any([True,True,False]))#하나라도 true이면 true임.
#---------
#a = np.arange(5)
#print(np.sin(a))
#print(np.log(a))
#print(np.exp(a))
#-------
#전이행렬
#a = np.triu(np.ones((3,3)),1)#triu: 삼각매트릭스를 만들 수 있음. 상삼각행렬
##전체가 1로 채워진 3 by 3 매트릭스를 삼각행렬로 만들겠다. 1:인덱스번호. 대각선에 해당하는게 1임. 인덱스번호를 어디에다주느냐에따라 어디를 채울지 알려줌.
##-1로 주면 아래부터 채워질거임?
#print(a)#[0. 1. 1.][0. 0. 1.][0. 0. 0.]]
#print(a.T)#[0. 0. 0.][1. 0. 0.][1. 1. 0.]]
#------
#a = np.triu(np.ones((3,3)),0)
#print(a)
#------------
#x = np.array([1,2,3,4])
#print(np.sum(x))#10
#print(x.sum())#10
#-----
#x = np.array([[1,1],[2,2]])
#print(x.sum())#6
#print(x.sum(axis=0))#[3 3]축에해당하는값을더함 0: 열을 위주로 합이 구해짐
#print(x.sum(axis=1))#[2 4]행을위주로 합이 구해짐
#print(x[0,:].sum(),x[1,:].sum())#2 4
#-------------
#x = np.array([1,3,2])
#print(x.min())#1
#print(x.max())#3
#print(x.argmin())#0 #index of minimum
#print(x.argmax())#1 #index of maximum
#-----------
#논리연산이라하더라도 이거 하나만갖고사용되는게아니라 다른연산과 같이 사용됨
#np.all([True, True, False])
#np.any([True, True, False])
#* 배열비교할때주로사용
#a = np.zeros((100,100))
#np.any(a!=0)
#np.all(a==a)
#--------
#x = np.array([1,2,3,1])
#y = np.array([[1,2,3],[5,6,1]])
#print(x.mean())#1.75 평균값구함
#print(np.median(x))#1.5 중간값구함 원소들중에 중간값에 해당하는거
#print(np.median(y,axis=-1))#[2. 5.] #last axis
#print(x.std())#표준편차?
#---------
#pyplot를 import해야.
data = np.loadtxt('data.txt')
year,hares,lynxes,carrots = data.T#데이터를 전이행렬로 받아옴
#plt.plot(year,hares,year,lynxes,year,carrots)#이거에 해당하는데이터들을 그려줘라. 연도와 산토끼, 연도와 시라소니, 연도와 당근 3개의 항목에대해 차트에보여줌.
#3개의 그래프가 나올거임
#plt.show()
#연도별평균?산토끼, 시라소니, 당근에해당하는연도별평균
#print(year)
#전체에 대한 평균, 표준편차 내가구함
#x = np.array(data.T)
#print(x)
#sum1 = np.array(x.sum(axis=0))
#print("전체다더해서 평균,표준편차")
#print(sum1.mean())
#print(sum1.std())
#각각에 해당하는 평균, 표준편차
#산토끼에 대한 평균, 표준편차
#print("산토끼 평균, 표준편차")
#hareMean = hares.mean()
#hareStd=hares.std()
#print(hareMean)
#print(hareStd)
#print("스라소니 평균, 표준편차")
#lynxesMean = lynxes.mean()
#lynxesStd = lynxes.std()
#print(lynxesMean)
#print(lynxesStd)
#print("당근 평균, 표준편차")
#carrotMean = carrots.mean()
#carrotStd = carrots.std()
#print(carrotMean)
#print(carrotStd)
#최대개체수를 갖는 연도
#print("hare가 최소인연도")
#arHARES = hares.argmin()
#print(year[arHARES])
#print("lynxes가 최소인연도")
#arLYNXES = lynxes.argmin()
#print(year[arLYNXES])
#print("carrot이 최소인연도")
#arCARROT = carrots.argmin()
#print(year[arCARROT])
#---------
row = np.array([[0,10,20,30,40,50]])#[이거 하나만 붙이면 벡터임. 배열이 아니고.
row = row.T#T연산은 [[ 이렇게 2개가 있어야.
#row의 shape정보 보기
column = np.array([[0,1,2,3,4,5]])
print(row+column)
|
de94608a24be509d4bc2d1dd693959a860d35b1a | zamirzulpuhar/zamir- | /2 неделя/какое число больше.py | 128 | 3.8125 | 4 | a = int(input())
b = int(input())
if a - b > 0:
print(1)
elif b - a > 0:
print(2)
elif a - b == 0:
print(0)
|
be3fee2096ed71483a7a74e3339b656068a34d73 | MinaMeh/TransformToLD | /plot.py | 2,056 | 3.59375 | 4 | """
===============================
Legend using pre-defined labels
===============================
Defining legend labels with plots.
"""
import numpy as np
import matplotlib.pyplot as plt
def plot_with_x(x, x_label, extract, preprocess, mapping, convert, total, title, legend_pos='upper right'):
# Make some fake data.
# Create plots with pre-defined labels.
fig, ax = plt.subplots()
ax.plot(x, extract, 'r', label='Temps d\'extraction', marker='o')
ax.plot(x, preprocess, 'b', label='Temps de prétraitement', marker='o')
ax.plot(x, mapping, 'g', label='Temps d\'alignement', marker='o')
ax.plot(x, convert, 'm', label='Temps de conversion', marker='o')
ax.plot(x, total, 'c', label='Temps total d\'exécution', marker='o')
plt.set_cmap('Paired')
legend = ax.legend(loc=legend_pos)
plt.grid(b=True, color='#666666', linestyle='dotted')
ax.set_ylim(ymin=0)
ax.set_xlim(xmin=0)
ax.set_ylabel('Temps d\'éxecution (s)')
ax.set_xlabel(x_label)
ax.set_title(title)
plt.show()
def plot_for_nb_triplets(x, x_label, y):
fig, ax = plt.subplots()
ax.plot(x, y, 'r', marker='o')
plt.set_cmap('Paired')
legend = ax.legend(loc='upper left')
plt.grid(b=True, color='#666666', linestyle='dotted')
ax.set_ylim(ymin=0)
ax.set_xlim(xmin=0)
ax.set_ylabel('Nombre de triplets')
ax.set_xlabel(x_label)
ax.set_title(
'Nombre de triplets en fonction du nombre de phrases')
plt.show()
taille = [0.5, 7.4, 39.6, 100]
nb_phrases = [4, 57, 387, 1412]
extract = [200, 1.93, 5.11, 12.67]
preprocess = [3.77, 42.78, 311.71, 1953.23]
mapping = [17.10, 88.14, 480.92, 954.3]
convert = [0.01, 0.02, 0.01, 1.2]
total = [21.71, 132.85, 797.65, 2908.59]
plot_with_x(taille, 'Taille du fichier (kB)', extract,
preprocess, mapping, convert, total, 'le temps d\'exécution en fonction de la taille du fichier', legend_pos="upper left")
nb_triplets = [6, 107, 661, 1542]
plot_for_nb_triplets(
taille, 'Nombre de phrases du fichier', nb_triplets)
|
5e960931ce2ec64a75c45facf245f80f08617ce6 | mikhailburyachenko/lesson2 | /age.py | 346 | 3.9375 | 4 | age=int(input("Введите Ваш возраст "))
def age_condition(age):
if age < 7:
return "Иди в сад"
elif age < 18:
return "Иди в школу"
elif age < 24:
return "Иди в Вуз"
else:
return "Иди работать"
what_to_do=age_condition(age)
print(what_to_do)
|
33bfa681e884a69bb51b1a7453de7537da033a37 | Pascal-tgn/gb-python-basics | /lesson_1/task-01.py | 478 | 3.90625 | 4 | my_int = 1
my_float = 2.0
my_str = "Hello!"
my_bool = True
print(my_int)
print(my_str)
in_str_1 = input("Введите строку: ")
print("Вы ввели", in_str_1)
in_str_2 = input("Введите ещё строку: ")
print("Вы ввели", in_str_2)
in_int = input("Введите число: ")
print("Все строки вместе:", in_str_1, in_str_2)
print("А это число (впрочем, никто это не проверяет):", in_int) |
6fbf8077730e3ea743fa97cd5347d7831a28faf8 | Sharayu1071/Daily-Coding-DS-ALGO-Practice | /Leetcode/Python/reverseInteger.py | 377 | 3.84375 | 4 |
#Problem link : https://leetcode.com/problems/reverse-integer/
def reverse(x):
s = str(abs(x))
ans = int (s[::-1])
if (ans > (pow(2,31)-1) or ans < pow(2,-31)):
return 0
elif (x >= 0):
return ans
return ans - 2*ans
num = int(input())
print(reverse(num))
#Example test case
# Input : 123
# Output : 321
# Input : - 123
# Output : -321
|
48ee5556951e1b26bcce2b9871026e648e312a9f | daniel-reich/ubiquitous-fiesta | /pEozhEet5c8aFJdso_0.py | 210 | 3.53125 | 4 |
def all_about_strings(txt):
return [
len(txt),
txt[0],
txt[-1],
txt[(len(txt)-1)//2:(len(txt)+2)//2],
"@ index {}".format(txt.index(txt[1], 2)) if txt[1] in txt[2:] else "not found"
]
|
105bc4ad31e5116e9f7365391f75de21afb46928 | rafaelperazzo/programacao-web | /moodledata/vpl_data/24/usersdata/87/11092/submittedfiles/av1_m3.py | 229 | 3.734375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
m = input("Digite valor de m: ")
i=2
while i<m:
if i%2==0:
pi=3+(4/(i*(i+1)*(i+2))
if i%2>0:
pi=3-(4/(i*(i+1)*(i+2))
i=i+1
print(i) |
5ddb6c3b40b79c8d188017c67ceefbb1a925ee15 | stammareddi/Fire-Maze | /Static/BFS.py | 1,479 | 3.75 | 4 |
"""
BFS
add start position into queue with distance 1
while queue isn't empty
- Pop of element
- check if they match if so return distance
- set array of directions moves = [up, down , right, left ]
- Traverse directions for loop
- if value == 0 and in bounds add not in visited add to queue with prev dist +1
queue
[(0,0), 0]
"""
from collections import deque
moves = [(-1, 0), (0, -1), (1, 0), (0, 1)] # vist neighbors
def helper_bfs(array, start, end):
q = deque()
# store coordinates and distance
s = [start, 0]
count = 0
q.append(s)
# set as visited
array[start[0]][start[1]] = 2
while q:
curr = q.popleft()
count = count + 1
coordinates = curr[0]
distance = curr[1]
array[coordinates[0]][coordinates[1]] = 2 # mark as visited
# s->g is reached
if coordinates[0] == end[0] and coordinates[1] == end[1]:
return [distance, count]
for x, y in moves:
row = coordinates[0]
col = coordinates[1]
# if in size of 2d array and value is = 0 then add to queue and set as visited
inbounds = 0 <= row + \
x < len(array) and 0 <= col + \
y < len(array) and array[row + x][col + y] == 0
if inbounds:
q.append([[row + x, col + y], distance + 1])
# mark as visited
array[row + x][col + y] = 2
return [0, count]
|
e0a60dcb2299aa6a20f9ad7e1e445826f1e078e0 | mnshkumar931/python-program | /inheritance.py | 811 | 3.703125 | 4 | class Animal():
type='pet'
def __init__(self,dog,cat):
print('parent cons called')
self.dog=dog
self.cat=cat
def speak(self):
print(self.dog +" dog bark")
print(self.cat +" cat meow")
def info(self,name,age):
print(f'{name} {age}')
# x=Animal("felix","pussy")
# y=Animal("mike","pont")
# print(x.type)
# print(y.type)
# print(Animal.type)
class Dog(Animal):
def __init__(self,name,breed):
super().__init__('dog','cat')
print('child cons called')
self.name=name
self.breed=breed
def info(self,name,age):
print(f'{name} {age}')
d=Dog('monty','huskie')
# a=An imal('dog','cat')
# d.info('dog1',2)
# d.info('dog2',4,'M')
# d.info('gog3',5,'F','black')
|
5c45b7a9c162b74e2f8a5a06b7bbed80e8a82bd4 | dfki-ric/pytransform3d | /examples/plots/plot_rotate_cylinder.py | 1,414 | 3.734375 | 4 | """
===============
Rotate Cylinder
===============
In this example, we apply a constant torque (tau) to a cylinder at its
center of gravity and plot it at several steps during the acceleration.
"""
import numpy as np
import matplotlib.pyplot as plt
from pytransform3d.rotations import matrix_from_compact_axis_angle
from pytransform3d.transformations import transform_from, plot_transform
from pytransform3d.plot_utils import plot_cylinder
def inertia_of_cylinder(mass, length, radius):
I_xx = I_yy = 0.25 * mass * radius ** 2 + 1.0 / 12.0 * mass * length ** 2
I_zz = 0.5 * mass * radius ** 2
return np.eye(3) * np.array([I_xx, I_yy, I_zz])
A2B = np.eye(4)
length = 1.0
radius = 0.1
mass = 1.0
dt = 0.2
inertia = inertia_of_cylinder(mass, length, radius)
tau = np.array([0.05, 0.05, 0.0])
angular_velocity = np.zeros(3)
orientation = np.zeros(3)
ax = None
for p_xy in np.linspace(-2, 2, 21):
A2B = transform_from(R=matrix_from_compact_axis_angle(orientation),
p=np.array([p_xy, p_xy, 0.0]))
ax = plot_cylinder(length=length, radius=radius, A2B=A2B, wireframe=False,
alpha=0.2, ax_s=2.0, ax=ax)
plot_transform(ax=ax, A2B=A2B, s=radius, lw=3)
angular_acceleration = np.linalg.inv(inertia).dot(tau)
angular_velocity += dt * angular_acceleration
orientation += dt * angular_velocity
ax.view_init(elev=30, azim=70)
plt.show()
|
66ac79532b9cbf43a35b840f1e6fc3b2506741bf | sendurr/spring-grading | /submission - lab5/set2/KAYLA S REVELLE_9396_assignsubmission_file_Lab 5/Lab 5/Lab5Q3.py | 183 | 3.8125 | 4 | def checkprime(n):
Number= True
for x in range(2,n-1):
if n%x==0:
Number=False
if Number:
print(True)
else:
print(False)
print (checkprime(3))
print (checkprime(255)) |
ab8a42f95b840f1b92735b5a9a42c6976bad5127 | Francisco8NGY/PythonPractice | /conjuntos.py | 311 | 4.15625 | 4 | #Lenguaje de programacion python
# uso de conjuntos
conjunto1 = set # declaracion de un conjnto vacio
type(conjunto1) # vizualizar el tipo de dato de una variable
conjunto2 = (10, "Colima, 12.45")
if 10 in conjunto2:
print("Este elemento si se encuentra")
else:
print("Este elemento no se encuntra")
|
800abedc9165ef65e701cafe5d79eb343645f517 | alexharvey/coursera | /python/exercises/exercise3.py | 217 | 3.78125 | 4 | __author__ = 'alex'
hrs = raw_input("Enter Hours:")
h = float(hrs)
rate = raw_input("Enter Rate:")
r = float(rate)
if hrs > 40:
total = (40 * r) + ((h - 40) * (1.5 * r))
else:
total = (r * h)
print(total)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.