blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a23386136d97a6d9b58e540ad72feb99d1b5ec03 | barreyo/smash-rl | /framework/games/ssbm/ssbm_observation.py | 3,268 | 3.546875 | 4 | """Observation of a single frame."""
import numpy as np
from framework.observation import Observation
class Position():
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"(x={self.x}, y={self.y})"
class SSBMObservation(Observation):
"""Class denoting the state of a frame."""
@staticmethod
def size():
return len(SSBMObservation().as_array())
def __init__(self,
player_pos: Position = Position(x=0, y=0),
enemy_pos: Position = Position(x=0, y=0),
player_stocks: int = 0,
enemy_stocks: int = 0,
player_percent: float = 0.0,
enemy_percent: float = 0.0):
"""
State of a single frame(timestep).
Arguments:
player_pos -- Tuple(float, float) with the player position
enemy_pos -- Tuple(float, float) with enemy position
player_stocks -- Integer denoting the number of stocks left for the
player
enemy_stocks -- Integer denoting the number of stocks left for the
enemy
player_percent -- The players' knockout percentage (0->inf)
enemy_percent -- Float denoting enemy's knockout percentage (0->inf)
"""
assert player_stocks >= 0 and enemy_stocks >= 0, \
"Stocks cannot be negative"
assert player_percent >= 0.0 and enemy_percent >= 0.0, \
"Player health percentage has to be a positive value"
self.player_position = player_pos
self.enemy_position = enemy_pos
self.player_stocks = player_stocks
self.enemy_stocks = enemy_stocks
self.player_percent = player_percent
self.enemy_percent = enemy_percent
@property
def player_x(self):
return self.player_position.x
@player_x.setter
def player_x(self, val):
self.player_position.x = val
@property
def player_y(self):
return self.player_position.y
@player_y.setter
def player_y(self, val):
self.player_position.y = val
@property
def enemy_x(self):
return self.enemy_position.x
@enemy_x.setter
def enemy_x(self, val):
self.enemy_position.x = val
@property
def enemy_y(self):
return self.enemy_position.y
@enemy_y.setter
def enemy_y(self, val):
self.enemy_position.y = val
def as_array(self) -> np.array:
"""
Return observation as flattened numpy array.
Format:
[px, py, ex, ey, p_stock, e_stock, p_percent, e_percent], where
'p' denotes player
'e' denotes enemy
"""
return np.array([self.player_position.x, self.player_position.y,
self.enemy_position.x, self.enemy_position.y,
float(self.player_stocks), float(self.enemy_stocks),
self.player_percent, self.enemy_percent])
def __str__(self): # noqa
return f'Observation(player_state=({self.player_position}, ' \
f'{self.player_stocks}, {self.player_percent}), ' \
f'enemy_state=({self.enemy_position}, {self.enemy_stocks}, ' \
f'{self.enemy_percent}))'
|
3b0cf9b4245d17d9b34e873b8c2bb14d534d6058 | yinyangguaiji/yygg-C1 | /11-3.py | 861 | 3.828125 | 4 | class Employee():
def __init__(self,f_name,l_name,salary):
self.f_name = f_name.title()
self.l_name = l_name.title()
self.salary = salary
def give_raise(self,other=''):
if other:
self.salary += int(other)
else:
self.salary += 5000
return self.salary
import unittest
class test_Employee(unittest.TestCase):
def setUp(self):
self.employee = Employee('zhang','san',5000)
self.default_salary = 7000
self.custom_salary = 10000
def test_give_default_raise(self):
salary = self.employee.give_raise(2000)
self.assertEqual(salary,self.default_salary)
def test_give_costom_salary(self):
salary = self.employee.give_raise()
self.assertEqual(salary,self.custom_salary)
unittest.main()
|
b33194554a1033cc0a2ab4f3c12338268f9adb50 | Zarwlad/coursera_python_hse | /week7/task4.py | 171 | 3.734375 | 4 | nums = list(map(int, input().split()))
setT = set()
for num in nums:
if setT.__contains__(num):
print("YES")
else:
print("NO")
setT.add(num)
|
3222d77b4e191dfb6bb0f1a41032e8b33484226d | Schnell5/InfSec | /Education/public_private_dec.py | 2,768 | 3.921875 | 4 | """
Public and Private decorators.
Public decorator allows to get and set only attributes that were passed to them during decoration.
Example: @public('data', 'size') - set and get operations will work only for 'data' and 'size'
attributes. All other attributes (if any) are private and cannot be gotten and set.
Private decorator works vice versa.
Example: @private('data', 'size') - set and get operations will prohibited for attributes 'data' and
'size'. All other attributes (if any) are public and can be gotten and set.
P.S. Run this file with -O key to prevent decoration:
#>>> python3 -O public_private_dec.py
"""
trace = False
def tracer(*args):
if trace:
print('[' + ' '.join(map(str, args)) + ']')
def accessControl(failif):
def onDecorator(aClass):
if not __debug__:
return aClass
else:
class OnInstance:
def __init__(self, *args, **kwargs):
self.__wrapped = aClass(*args, **kwargs)
def __getattr__(self, attr):
tracer('get:', attr)
if failif(attr):
raise TypeError('private attribute fetch ' + attr)
else:
return getattr(self.__wrapped, attr)
def __setattr__(self, attr, value):
tracer('set:', attr, value)
if attr == '_OnInstance__wrapped':
self.__dict__[attr] = value
elif failif(attr):
raise TypeError('private attribute change ' + attr)
else:
setattr(self.__wrapped, attr, value)
return OnInstance
return onDecorator
def private(*attributes):
return accessControl(failif=lambda attr: attr in attributes)
def public(*attributes):
return accessControl(failif=lambda attr: attr not in attributes)
if __name__ == '__main__':
trace = True
@private('data', 'size')
class Doubler:
def __init__(self, label, start):
self.label = label
self.data = start
def size(self):
return len(self.data)
def double(self):
for i in range(self.size()):
self.data[i] = self.data[i] * 2
def display(self):
print('{0} => {1}'.format(self.label, self.data))
x = Doubler('x is', [1, 2, 3])
y = Doubler('y is', [-10, -20, -30])
print(x.label)
x.display(); x.double(); x.display()
print(y.label)
y.display(); y.double()
y.label = 'Spam'
y.display()
print(x.size())
# This part will raise exceptions for @private decorator
'''
print(x.size())
print(x.data)
x.data = [1, 1, 1]
x.size = lambda s: 0
print(y.data)
print(y.size())
''' |
6c61f28bc228d1a54de2eb29d0c10f399af88344 | TenzinChemi/TENZIN_DSA | /sequence.py | 207 | 3.796875 | 4 | N=int(input())
number=1
l=1
while l<=N:
for i in range(number,number+5):
print(i,end=" ")
print()
for j in range(i+5,i,-1):
print(j,end=" ")
number=j+5
print()
l+=2
|
209f2f73b3f9182f43bcfeb75a35bfcfab81b029 | JohnHadish/hort503 | /Assignment03/ex22.py | 1,600 | 4.3125 | 4 | print() #Prints out words
+ #adds
/ # divides
- # subtracts
* #multiplies
% #remainder of division
> < # greater than and less than, returns a boolina
<= >= # Less to or equal and more than or equal
= #assign a variable
f"{variable}" # f string, allows for variables to be called in a string
TRUE T # True, a boolian value
FALSE F # False, a boolian value
"{}".format("") # puts format thing in the {}
formatter = "{} {} {} {}" formatter.format(1, 2, 3, 4) # Puts into formatter
\ #exclude this from the string
\n #puts a return in a string
""" """ #allows you to have multiple lines of code readout
\t #tab\
\\ # backslash
end = ' ' # used to end a printy section with a space instead of a return (default is return)
input() #Takes an input from the user, can put text in the input bit
from sys import argv #Imports function argv from sys
script, input, input2, .... = argv # How argv is used to assign variables
open(filename, "w") #opens a file, can be saved as a variable. "w" means write, by default opens as read
filename.read() #reads a filename, can be used with print to print FILE
filename.truncate() #erases a file with name "filename"
filename.write("text") #writes text to a file with name "filename"
filename.close() #closes a file with "filename" as name
from os import exists
exists(filename) #checks to see if file exists
def function_name(input1, input2):
function_operation(input) #This is a function that takes inputs and uses them. Can call function usin anythiong pretty much
filename.seek(0) # seeks a point in the file (in byts)
filename.readline() #reads the next line
|
d8af7a6b54458f438e4b36a571079a768c91372f | lfdyf20/Leetcode | /Word Break II.py | 704 | 3.59375 | 4 | import numpy as np
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
return self.dp(s, wordDict, {})
def dp(self, s, wordDict, memo):
if s in memo:
return memo[s]
if not s:
return []
res = []
for word in wordDict:
if s.startswith(word):
if len(word) == len(s):
res.append(word)
else:
resultOfRest = self.dp( s[len(word):], wordDict, memo )
for item in resultOfRest:
item = word + ' ' + item
res.append(item)
memo[s] = res
return res
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
sl = Solution()
print( sl.wordBreak( s, wordDict ) ) |
e4ea6b0552af138845ee5f146808c73c8edc362a | cjwfuller/quantum-circuits | /quantum-circuits/quantum_gate.py | 2,740 | 3.53125 | 4 | import numpy as np
import gate
import register as r
class QuantumGate(gate.Gate):
"""
super(<name of child class>, self) should be called before any methods in
QuantumGate are called
"""
def __new__(cls, *args, **kwargs):
if cls is QuantumGate:
raise TypeError("quantum gate class may not be instantiated")
return object.__new__(cls, *args, **kwargs)
def __init__(self):
"""Determine whether the gate is quantum
This is done by determining whether the gate has a unitary matrix"""
shape = np.shape(self.matrix)
# unitary matrices will always have dimension n*n
width, height = shape[0], shape[1]
if width != height:
raise Exception("Matrix must have dimension n*n")
# unitary matrices must satisfy U*U = UU* = I
identity = np.identity(width)
conjugate_transpose = self.matrix.getH()
if not (self.matrix * conjugate_transpose).all() == identity.all():
raise Exception("Matrix must be unitary")
def get_symbol(self):
return self.symbol
def get_matrix(self):
return self.matrix
def get_num_qubits(self):
return self.num_qubits
def resize(self, num_qubits, qubit_nums):
"""Resize a gate to act on a given number of qubits.
Gates can act on an arbitrary number of qubits but they must be resized
so they can be applied to the circuit
Arguments:
num_qubits -- number of qubits to resize gate to e.g. 3
qubit_nums -- qubits to act on e.g. [0, 2]
"""
if self.get_num_qubits() != len(qubit_nums):
raise ValueError("Invalid number of qubit numbers given")
resized_dimension = pow(2, num_qubits)
resized = np.zeros((resized_dimension, resized_dimension), dtype=np.complex_)
filtered_bases = r.Register.filter_bases(num_qubits, qubit_nums)
new_bases = r.Register.generate_bases(num_qubits)
for idx, dirac_base in enumerate(filtered_bases):
vector = r.Register.dirac_to_column_vector(dirac_base)
# apply fundamental matrix to column vector
vector = np.squeeze(np.asarray(np.dot(self.get_matrix(), vector)))
# build the new set of bases vectors
new_dirac_bases = r.Register.column_vector_to_possible_dirac_vectors(vector)
for idy, qubit_num in enumerate(qubit_nums):
for new_dirac_base in new_dirac_bases:
new_bases[idx][qubit_num] = new_dirac_base[idy]
row = r.Register.dirac_to_column_vector(new_bases[idx])
# build the resized matrix
resized[idx] = row
self.matrix = resized
|
1fcc2e9a3b2a397f4587fcdf36c85d472b195f0f | kamesh051/django_tutorial-master | /python/testclass.py | 197 | 3.859375 | 4 | while True:
name = input("enter user name:")
if name == 'kamesh':
continue
password =input("Hi kamesh. enter your password:")
if password =='sathya':
break
|
20f54fff95aaf9e2f11adf2395dac23892594c1d | dairantzis/BBK_Introduction-to-Computer-Systems_2021 | /Week 07/lists.py | 1,216 | 4.375 | 4 | # List initialisation
list1 = [0 for i in range(15)]
list2 = [1, 2, 3]
list3 = ["a", "b", "c", "d", "b", "g"]
print("List 1:",list1)
print("List 2:",list2)
print("List 3:",list3)
list1[0:10] = [10] * 10
print("Ammended the first ten values of List 1:",list1)
list1.extend(list3)
print("Extended list1 with the items in list3:",list1)
print("Note the difference in the nature of the elements")
list1.insert(5,'a')
print("Inserted an a at the first location FOLLOWING element 5:",list1)
list1.remove('a')
print("Removed THE FIRST OCCURENCE of a from the list:",list1)
list1.pop(16)
print("Removed the element immediately FOLLOWING the specified position:",list1)
list1.clear()
print("Cleared list1:",list1)
print("Switching to using list3:",list3)
print("The FIRST occurence of the letter b is at position:",list3.index("b"))
print("Letter b appears within list3:",list3.count("b"),"times.")
list3.sort()
print("Sorted list 3:",list3)
list3.reverse()
print("Reveresed list 3:",list3)
list4 = list3.copy()
print("Copied the contents of list3 onto list4:")
print("This is list3:",list3)
print("This is list4:",list4)
print("End of demonstration of list methods offered by Python")
print(list1)
|
8a30c7f828aa62934505a830c255cede2c84306f | vincenttuan/yzu_python_20210414 | /day05/List串列4.py | 237 | 4.25 | 4 | # List串列與Tuple元祖
a = [1, 2, 3, 4, 5] # 可修改
b = (1, 2, 3, 4, 5) # 不可修改
print(type(a), a)
print(type(b), b)
# 轉換
# list 轉 tuple
a = tuple(a)
print(type(a), a)
# tuple 轉 list
b = list(b)
print(type(b), b)
|
468c7eaab970b396005712e6d8daa8cfa70097e0 | best90/learn-python3 | /packages/pillow/pil_resize.py | 270 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PIL import Image
im = Image.open('test.jpg')
w, h = im.size
print('Original image size: %s x %s' % (w,h))
im.thumbnail((w//2, h//2))
print('Resize image to : %s x %s' % (w//2, h//2))
im.save('thumbnail.jpg', 'jpeg') |
9aa42cc24649b875d611a054530f52b09bc88176 | JohnlLiu/Sudoku_solver | /main.py | 1,432 | 3.671875 | 4 |
#Sudoku board
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
def solve(board):
#check if index is empty
indx = is_empty(board)
#board is filled out and program exits
if not indx:
return True
row = indx[0]
col = indx[1]
#check for valid values to fill in for the position (index)
for i in range (1,10):
if is_valid(board, i, indx):
board[row][col] = i
if solve(board):
return True
board[row][col] = 0
return False
def is_valid(board, num, idx):
row = idx[0]
col = idx[1]
#check row
if num in board[row]:
return False
#check column
for i in range(len(board)):
if num == board[i][col]:
return False
#check box
box_x = row//3
box_y = col//3
for i in range(box_x*3, box_x*3 + 3):
for j in range(box_y*3, box_y*3 + 3):
if num == board[i][j]:
return False
return True
def is_empty(board):
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 0:
return [i, j]
return None
solve(board)
for i in board:
print(i) |
584378becf704c33ac7d33013c66d2af4291a3dd | MITZHANG/ThinkPython | /src/ch5/ex3/is_triangle.py | 290 | 4.125 | 4 | def is_triangle(a, b, c):
if a>b+c or b>a+c or c>a+b:
print('No')
else:
print('Yes')
if __name__ == '__main__':
print('请输入三角形的三条边长度:')
a = int(input('a='))
b = int(input('b='))
c = int(input('c='))
is_triangle(a, b, c)
|
bb59539e7565e74414cf5d149c78b34e7ac288ed | ajj/ncnrcode | /bt5view/usans.py | 2,969 | 3.625 | 4 | #!/usr/bin/python
#import Tkinter as Tk
def numeric_compare(x, y):
x = float(x)
y = float(y)
if x < y:
return - 1
elif x == y:
return 0
else: # x>y
return 1
def getBT5DataFromFile(fileName):
'''
Takes a filename and returns a dictionary of the detector values
keyed by varying value (ususally A2 or A5)
'''
detdata = {}
metadata = {}
inputfile = open(fileName, "r")
inputdata = inputfile.readlines()
mdtmp = inputdata[0].split(' ')
print mdtmp
for index in range(13, len(inputdata), 2):
detdata[inputdata[index].split()[0]] = inputdata[index + 1].split(',')
for key in detdata.keys():
for val in range(0, len(detdata[key])):
detdata[key][val] = int(detdata[key][val])
inputfile.close()
return detdata
def printBT5DetData(detdata):
'''
Print the contents of the file in a formatted fashion
Takes a dictionary of data as provided by getBT5DataFromFile() and prints out the contents
in a formatted fashion
'''
motorvals = detdata.keys()
motorvals.sort(cmp=numeric_compare)
for motorval in motorvals:
str = motorval + ":"
str += "\tMon: " + repr(detdata[motorval][0])
str += "\tDet 1-5: " + repr(detdata[motorval][2])
str += "\t" + repr(detdata[motorval][1])
str += "\t" + repr(detdata[motorval][4])
str += "\t" + repr(detdata[motorval][5])
str += "\t" + repr(detdata[motorval][6])
str += "\tTrans: " + repr(detdata[motorval][3])
print str
return 0
def getAlignVals(data, motorval):
'''
Return the values we record in the logbook for a given motor position
Takes a dictionary as provided by getBT5DataFromFile and returns a dictionary with
keys Central, Trans and Sum
'''
alignvals = {}
alignvals['Central'] = data[motorval][1]
alignvals['Trans'] = data[motorval][3]
alignvals['Sum'] = data[motorval][1] + data[motorval][2] + data[motorval][4] + data[motorval][5] + data[motorval][6]
return alignvals
def maxDetCount(data, detector):
'''
Return the maximum value and corresponding motor position for a given detector
Takes a dictionary as provided by getBT5DataFromFile() and returns a dictionary with
keys Position and Value
'''
maxpos = ''
maxval = 0
result = {}
mvals = data.keys()
det = {'1':2, '2':1, '3':4, '4':5, '5':6}[repr(detector)]
for mval in mvals:
if data[mval][det] > maxval:
maxval = data[mval][det]
maxpos = mval
result['Position'] = maxpos
result['Value'] = maxval
return result
if __name__ == '__main__':
import sys
data = getBT5DataFromFile(sys.argv[1])
printBT5DetData(data)
maxinfo = maxDetCount(data, 2)
print maxinfo
avals = getAlignVals(data, maxinfo['Position'])
print avals
|
d5f6d3cc2927f5f67b3c25f92f5c5beec268b2d7 | 101vinayak/UGV | /obstacles.py | 3,904 | 3.5 | 4 | #!/usr/bin/python
#This is the basic obstacle detection module
import matplotlib.pyplot as plt
import numpy as np
import rospy
from time import time
import os
from sensor_msgs.msg import LaserScan
# This program includes the following hardcoded values:
# Smallest cluster to detect as an object
# Critical distance below which an object should be an obstacle
# The values are just placeholders for now. They are subject
# to change with testing
OBJECT_RESOLUTION = 0.03 # Size of the smallest object (in radians)
CRITICAL_DISTANCE = 1 # Set to zero to report all ojects as obstacles
LIDAR_RESOLUTION = 10 # In degrees
def build_object(data, start_index, end_index):
"""This function builds an obstacle object from the LIDAR data"""
data_len = len(data.ranges)
start_bound = (data_len/2 - start_index)*data.angle_increment
end_bound = (data_len/2 - end_index)*data.angle_increment
min_distance = np.min(data.ranges[start_index:end_index+1])
if np.isnan(min_distance):
# Faulty reading
return None
elif abs(start_bound - end_bound) < OBJECT_RESOLUTION:
# Object too small
return None
return {'start_bound': float(start_bound),
'end_bound': float(end_bound),
'distance': float(min_distance),
'start_index': float(start_index),
'end_index': float(end_index)}
def get_obstacles(data, partitions, critical_distance=0):
"""This function returns an array of objects
that are closer than critical_distance.
The array is sorted in increasing order of distance"""
boundaries = np.argwhere(partitions)
if len(boundaries) == 0:
return []
first_bound = boundaries[0]
boundaries = boundaries[1:] # Remove the first_bound from the list
obstacles = []
prev_bound = first_bound
for boundary in boundaries:
obj = build_object(data, prev_bound, boundary)
prev_bound = boundary
if obj is None or (critical_distance > 0 and obj['distance'] >= critical_distance):
continue
else:
obstacles.append(obj)
obstacles.sort(key=lambda x: x['distance'])
return obstacles
def is_obstructed(angle, obstacles):
for obstacle in obstacles:
if angle > obstacle['start_index'] and angle < obstacle['end_index']:
return True
return False
def plot_laser_data(data, partitions, obstacles, threats):
"""This functions plots all the obtained information on a polar graph"""
ax = plt.subplot(111, projection='polar')
plt.cla()
theta = range(len(data.ranges))
theta = [data.angle_min + data.angle_increment*t for t in theta]
ax.scatter(theta, data.ranges, s = 2)
#plt.plot(theta, data.ranges, '#c2c3c4')
#plt.plot(theta, partitions, 'r')
#plt.plot(theta, obstacles, 'g')
res = np.deg2rad(LIDAR_RESOLUTION)/data.angle_increment
obstructed = [0]*len(theta)
free = [0]*len(theta)
for i in range(0, len(theta), np.int(res)):
if is_obstructed(i, threats):
obstructed[i] = 3
else:
free[i] = 3
plt.plot(theta, free, 'g')
plt.plot(theta, obstructed, 'r')
plt.draw()
plt.pause(0.00000000000000000000000000000000000000000001)
def on_laser_scan(a_data):
data = a_data
data.ranges = [data.range_max if np.isnan(x) else x for x in data.ranges]
grads = np.gradient(np.array(data.ranges))
partitions = [1 if abs(i) > CRITICAL_DISTANCE else 0 for i in grads]
obstacles = get_obstacles(data, partitions, CRITICAL_DISTANCE)
obstacle_graph = [0]*len(data.ranges)
for ob in obstacles:
index = (ob['start_index'] + ob['end_index'])/2
obstacle_graph[int(index)] = 1
plot_laser_data(data, partitions, obstacle_graph, obstacles)
def main():
plt.ion()
rospy.init_node('what', anonymous=True)
ret = rospy.Subscriber("scan", LaserScan, on_laser_scan)
print "PRESS CTRL-C TO QUIT"
rospy.spin()
os._exit(0) # This line supresses the stacktrace produced by tkinter
if __name__ == '__main__':
main()
|
650de1ffd6971496e7eb1e53b0b94507c8080e0d | jayajr/EK128-Spring-15 | /EK 128 Spring15/EK128-HW4/topfun.py | 2,778 | 4.0625 | 4 | #Uses ASCII value of character as comparison point.
#E.g. '1'=49 'A'=65 'a'=97,
#Therefore 1AaA1 is a hill, aA1Aa is a valley
#An empty string is always False.n
#A hill first strictly ascends then strictly descends.
#A slope never ascends.
#A valley first strictly descends then strictly ascends.
def is_hill(seq):
diff = []
index = 0
index2 = 1
m = len(seq)
L= list(seq)
if seq == "":
return(False)
while True:
if index2 == m:
break
x = ord(L[index2]) - ord(L[index])
diff.append(x)
index += 1
index2 += 1
index = 0
for i in diff:
index += 1
if i <= 0:
out = False
break
if i > 0:
continue
for i in diff[index-1:]:
if i >= 0:
out = False
break
if i < 0:
out = True
continue
return(out)
def is_plain(seq):
diff = []
index = 0
index2 = 1
m = len(seq)
L= list(seq)
if seq == "":
return(False)
while True:
if index2 == m:
break
x = ord(L[index2]) - ord(L[index])
diff.append(x)
index += 1
index2 += 1
for i in diff:
if i < 0 or i > 0:
out = False
break
if i == 0:
out = True
continue
return(out)
def is_ramp(seq):
diff = []
index = 0
index2 = 1
m = len(seq)
L= list(seq)
if seq == "":
return(False)
while True:
if index2 == m:
break
x = ord(L[index2]) - ord(L[index])
diff.append(x)
index += 1
index2 += 1
for i in diff:
if i > 0:
out = True
continue
if i <= 0:
out = False
break
return(out)
def is_slope(seq):
diff = []
index = 0
index2 = 1
m = len(seq)
L= list(seq)
if seq == "":
return(False)
while True:
if index2 == m:
break
x = ord(L[index2]) - ord(L[index])
diff.append(x)
index += 1
index2 += 1
for i in diff:
if i < 0:
out = True
continue
if i >= 0:
out = False
break
return(out)
def is_valley(seq):
diff = []
index = 0
index2 = 1
m = len(seq)
L= list(seq)
if seq == "":
return(False)
while True:
if index2 == m:
break
x = ord(L[index2]) - ord(L[index])
diff.append(x)
index += 1
index2 += 1
index = 0
for i in diff:
index += 1
if i < 0:
continue
if i >= 0:
out = False
break
for i in diff[index-1:]:
if i > 0:
out = True
continue
if i <= 0:
out = False
break
return(out)
def get_topology(seq):
plain = is_plain(seq)
slope = is_slope(seq)
ramp = is_ramp (seq)
hill = is_hill(seq)
valley = is_valley(seq)
if plain is True:
return("Plain")
if slope is True:
return("Slope")
if ramp is True:
return("Ramp")
if hill is True:
return("Hill")
if valley is True:
return("Valley")
else:
return("None")
|
223388fbb982f44a47c0a3ed31f06a390cc09c1d | SokarWriter/pythonbrodas | /00 intro/tri.py | 148 | 3.75 | 4 | def triangulo (letter, size):
angulo = ""
for u in range (size):
angulo = angulo + letter
print (angulo)
triangulo ("#", 5) |
e8f14b50323f2dd69a415170b0fbf0911c10ca75 | corbosiny/AI-Machine-learning | /MachineLearning/gaussian.py | 6,610 | 3.546875 | 4 | from __future__ import division
import math
import random
import matplotlib.pyplot as plt
class Gaussian():
eps = .00000001
def __init__(self, sigmaSquared, mu = 0, tolerance = .001):
if not isinstance(mu, int) and not isinstance(mu, float):
raise ValueError('Mu must be a numerical value')
if not isinstance(sigmaSquared, int) and not isinstance(sigmaSquared, float): #just checking if proper data types were entered
raise ValueError('The variance must be numerical value')
self.mu = float(mu)
self.sigma2 = float(sigmaSquared)
self.stdEv = math.sqrt(self.sigma2)
self.tolerance = tolerance
self.stepSize = tolerance #this is an arbitrary value we give it before adjusting the step size, the function to adjust needs a prior stepsize
self.stepSize = self.adaptStepSize(mu) #adapts step size for the given tolerance
def evaluate(self, point): #returns prob of getting that exact number
return math.exp(- ((self.mu - point) ** 2) / (self.sigma2 + Gaussian.eps) / 2.0) / math.sqrt(2 * math.pi * self.sigma2 + Gaussian.eps)
def generateGaussianNoise(self):
initialProbabilityScore = random.random() * self.evaluate(self.mu) * 2
probabilityOfScore = 0
while initialProbabilityScore > probabilityOfScore:
choice = random.randrange(int(self.mu - self.stdEv * 5.0), int(self.mu + self.stdEv * 5.0))
probabilityOfChoice = self.evaluate(choice)
initialProbabilityScore -= probabilityOfChoice
return choice
def returnProbDensity(self, num): #returns the prob of getting a value of equal to or less than the given value with the distribution parameters
prob = 0
x = self.mu - self.stdEv * 4.0
while x < num:
prob += self.evaluate(x) * self.stepSize
x += self.stepSize
self.stepSize = self.adaptStepSize(x)
return prob
def adaptStepSize(self, num): #calculates the local truncation error then calculates the new given step size for a certain tolerance
vel = self.evaluate(num)
eulerPos = vel * self.stepSize
eulerVel = self.evaluate(num + self.stepSize)
heunsVel = (eulerVel + vel) / 2
heunsPos = heunsVel * self.stepSize
time = 2 * (self.mu + self.stdEv * 3) / self.stepSize
error = abs(heunsPos - eulerPos) + time * abs(heunsVel - eulerVel)
newStepSize = self.stepSize * math.sqrt(self.tolerance / (error + math.exp(-25)))
if self.stdEv > 1: #this just makes sure our step sizes dont go down too small and bring down computational time when they dont need to go that small
return max(.001, newStepSize)
else:
return max(.00001, newStepSize)
def plotGaussian(self, numPoints = 100): #used to plot and visualize the gaussian
X = []
Y = []
x = self.mu - 4 * self.stdEv
while x < self.mu + 4 * self.stdEv:
X.append(x)
Y.append(self.evaluate(x))
x += (self.mu + 4 * self.stdEv * 2) / numPoints
plt.plot(X,Y)
plt.show()
def __add__(self, b): #merging two gaussians or adding a constant
if isinstance(b, Gaussian):
newMean = self.mu + b.mu #if b is a gaussian we add the means and the variances together
newSigma = self.sigma2 + b.sigma2
result = Gaussian(newSigma, newMean)
return result
elif isinstance(b, int) or isinstance(b, float):
result = Gaussian(self.sigma2, self.mu + b) #if b is a constant we just shift the mean over by the constant
return result
else:
raise ValueError("Unsuppported operation between Gaussian and type %s" % type(b))
def __sub__(self, b):
return self + (-1 * b) #just add the negative of b, used so I dont have to repeat the above add function
def __mul__(self,b):
if isinstance(b, int) or isinstance(b, float): #if int or float, then just shift the mean by multiplying it
newMean = self.mu * b
newSigma2 = math.pow(self.stdEv * b, 2) #the new stdEv is also multiplied so the new var is squared by that
result = Gaussian(newSigma2, newMean)
return result
elif isinstance(b, Gaussian):
newMean = (self.mu * b.sigma2 + self.sigma2 * b.mu) / (self.sigma2 + b.sigma2) #new mean is weighted average based off of variances
newSigma2 = (self.sigma2 * b.sigma2) / (b.sigma2 + self.sigma2) #new variance is smaller than either before it
result = Gaussian(newSigma2, newMean)
return result
else:
raise ValueError("Unsuppported operation between Gaussian and type %s" % type(b))
def __floordiv__(self, b): #just do the mul function with one over b to save me from retyping stuff
if not isinstance(b, int) and not isinstance(b, float):
raise ValueError("Unsuppported operation between Gaussian and type %s" % type(b))
else:
return self * (1.0 / b)
def __truediv__(self, b): #just do the mul function with one over b to save me from retyping stuff
if not isinstance(b, int) and not isinstance(b, float):
raise ValueError("Unsuppported operation between Gaussian and type %s" % type(b))
else:
return self * (1.0 / b)
def __str__(self): #returns all the info about the Gaussian
string = ""
string += "Mean: %.3f\n" % self.mu
string += "Variance: %.3f\n" % self.sigma2
string += "StdDev: %.3f" % self.stdEv
return string
if __name__ == "__main__":
gauss = Gaussian(.667, 14) #test code below to make sure everything is working
gauss2 = Gaussian(1.556, 21.333)
gauss3 = Gaussian(0, 4)
print("Added: \n" + str(gauss + gauss2))
print("Multiplied: \n" + str(gauss * gauss2))
print(gauss.evaluate(18))
print(gauss2.evaluate(18))
print(gauss3.evaluate(18))
print(math.log(gauss.evaluate(18)))
print(math.log(gauss2.evaluate(18)))
print(math.log(gauss3.evaluate(18)))
noise = [gauss.generateGaussianNoise() for i in range(1000)]
noiseMean = sum(noise) / len(noise)
noiseVar = sum([math.pow(x - noiseMean, 2) for x in noise]) / len(noise)
print("Mean of noise:", noiseMean)
print("Variamce of noise:", noiseVar)
numBins = 15
plt.hist(noise, numBins)
plt.show()
|
20aa615db2e53372d9c76ded0a7444da54761673 | StephanieTabosa/Mundo-02 | /aula12desafio039.py | 938 | 3.984375 | 4 | # Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com sua idade:
# Se ele ainda vai se alistar ao serviço militar;
# Se é hora de se alistar;
# Se já passou do tempo do alistamento.
# Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.
from datetime import date
anoAtual = date.today().year
anoNascimento = int(input('Digite o ano do seu nascimento. Ex.: 1992 '))
idade = anoAtual - anoNascimento
if idade == 18:
print('Você tem {} anos e está na hora de se alistar!'.format(idade))
elif idade < 18:
print('Você tem {} anos e ainda irá se alistar em {} ano(s).'.format(idade, 18 - idade))
print('Seu alistamento será em {}.'.format(anoAtual + (18-idade)))
else:
print('Você tem {} anos e já passou {} ano(s) do seu alistamento!'.format(idade, idade - 18))
print('Seu alistamento foi em {}.'.format(anoAtual - (idade - 18)))
|
9091b6fab13f9bca63f0db8143b83dc985b38798 | zhuodannychen/Competitive-Programming | /Kattis/sortofsorting.py | 241 | 3.578125 | 4 | while True:
n = int(input())
if n == 0:
break
names = []
for i in range(n):
names.append(input())
names.sort(key=lambda x: (x[0], x[1]))
for name in names:
print(name)
print()
|
c23aee1c7773377354345ada5d218dbcd835e306 | aineko-macx/python | /ch10/10_1.py | 275 | 3.9375 | 4 | def nested_sum(list):
sum = 0
for i in list:
if type(i) == type([]):
sum += nested_sum(i)
else:
sum += i
return sum
list = [1,2,3,4,5,6]
list1 = [[1,2],3,4,[5,6]]
print(nested_sum(list))
print(nested_sum(list1))
|
bc28a034bbad702c352988e8d59e633dc42c7468 | avinashbhat/similarity-item-based | /engines.py | 5,786 | 3.984375 | 4 | import math
from data import loadData, critics, loadNewData, load1mData
# Takes 3 parameters, data, names of the items
def euclid(itemData,ione,itwo):
# Get what items are shared between two movies
shared = {}
total = 0
#print shared
for person in itemData[ione]:
if person in itemData[itwo]:
shared[person] = 1
# Calculate using Euclid's formula
total += (itemData[ione][person]-itemData[itwo][person])**2
#print shared
# If nothing common return 0
if len(shared) == 0:
return 0
#print shared
# Return
return 1/(1+total)
#d = euclidDistance(critics,'Lisa Rose', 'Gene Seymour')
#print d
#-----------------------------------------------------------------------------------------------------------------------
''' Manhatten distance algorithm
1) Identify the shared objects
2) Calculate difference between the scores
3) Sum the scores
Minimum distance similar the people
'''
def manhattan(itemData,ione,itwo):
shared = {}
total = 0
for person in itemData[ione]:
if person in itemData[itwo]:
shared[person] = 1
total += abs(itemData[ione][person] - itemData[itwo][person])
if len(shared) == 0:
return 0
return 1/(1+total)
#-----------------------------------------------------------------------------------------------------------------------
# formula referred in http://onlinestatbook.com/2/describing_bivariate_data/calculation.html
def pearson(itemData,ione,itwo):
shared = {}
i1sum = i1sq = 0
i2sum = i2sq = 0
prodsum = 0
for person in itemData[ione]:
if person in itemData[itwo]:
shared[person] = 1
i1sum += itemData[ione][person]
i1sq += itemData[ione][person]**2
i2sum += itemData[itwo][person]
i2sq += itemData[itwo][person]**2
prodsum += itemData[ione][person]*itemData[itwo][person]
length = len(shared)
if length == 0:
return 0
numer = prodsum - ((i1sum*i2sum)/length)
denom = ((i1sq-(i1sum**2/length))*(i2sq-(i2sum**2/length)))**0.5
if denom == 0:
return -1
else:
return numer/denom
#p = pearson(critics,'Lisa Rose', 'Gene Seymour')
#print p
#-----------------------------------------------------------------------------------------------------------------------
# http://www.statisticssolutions.com/correlation-pearson-kendall-spearman/
# A function to assign ranks and sort
# the rankings
def spearman_sort(l):
l = [[k,v] for k,v in l.items()]
l.sort(key=lambda l:l[1])
index = 1
for each in l:
each[1] = index
index += 1
l.sort()
return l
''' Spearman Correlation algorithm
1) Find scores of each object
2) Calculate ranks for each object
3) Find the difference between ranks,
to verify - sum of ranks should be 0
4) Calculate sum of squares of ranks
5) Calculate Spearman r = 1 - (6*summ(d**2)/n(n**2-1)) '''
def spearman(itemData,ione,itwo):
shared = {}
# Find scores of each object
x = {}
y = {}
index = 1
for person in itemData[ione]:
if person in itemData[itwo]:
shared[person] = 1
x[index] = itemData[ione][person]
y[index] = itemData[itwo][person]
index += 1
# If no common element return 0
l = len(shared)
if l == 0:
return -1
# Calculate ranks for each object
x = spearman_sort(x)
y = spearman_sort(y)
# Find the difference between ranks
diff = []
for index in range(0,len(x)):
diff.append(x[index][1] - y[index][1])
# Calculate sum of squares of ranks
diffs = 0
for each in diff:
diffs += each**2
# Calculate Spearman r = 1 - (6*summ(d**2)/n(n**2-1))
temp = (6*diffs)/(1+l*((l**2)-1))
r = 1 - temp
return r
#-----------------------------------------------------------------------------------------------------------------------
''' Cosine Similarity
1) Find scores of each object
2) Calculate ||x|| = sqrt(summ(x))
3) Calculate ||y|| = sqrt(summ(y))
4) Dot product x.y = summ(x*y)
5) Cosine Similarity = (x.y)/(||x||X||y||)
'''
def cosine(itemData,ione,itwo):
shared = {}
dot = 0
x = 0
y = 0
for person in itemData[ione]:
if person in itemData[itwo]:
shared[person] = 1
x += itemData[ione][person]**2
y += itemData[itwo][person]**2
dot += itemData[ione][person]*itemData[itwo][person]
if len(shared) == 0:
return 0
x = x**0.5
y = y**0.5
return dot/(x*y)
#-----------------------------------------------------------------------------------------------------------------------
def tanimotoDistance(itemData, ione, itwo):
num_in_both = 0
for person in itemData[ione]:
if person in itemData[itwo]:
num_in_both += 1
denom = len(itemData[ione]) + len(itemData[itwo]) - num_in_both
if denom != 0:
return float(num_in_both)/denom
else:
return 0
#-----------------------------------------------------------------------------------------------------------------------
def minkowskiDistance(itemData, ione, itwo):
shared = {}
total = 0
r = 4
for person in itemData[ione]:
if person in itemData[itwo]:
shared[person] = 1
total += (itemData[ione][person]-itemData[itwo][person])**r
if len(shared) == 0:
return 0
power = float(1)/r
return total**power
#-----------------------------------------------------------------------------------------------------------------------
'''def adjustedCosine(itemData, ione, itwo):
userData = critics
avg = {}
for user in userData:
sum_rating = 0
count = 0
for movie in userData[user]:
sum_rating += userData[user][movie]
count += 1
avg[user] = sum_rating/count
sum_all = 0
sum_first_sq = 0
sum_second_sq = 0
for user in userData:
if (pone in user) and (ptwo in user):
sum_first = (userData[user][pone] - avg[user])
sum_second = (userData[user][ptwo] - avg[user])
sum_num += sum_first * sum_second
sum_first_sq += sum_first ** 2
sum_second_sq += sum_second ** 2
sum_den = (sum_first_sq * sum_second_sq )**0.5
if sum_den != 0:
return sum_num/sum_den
else
return 0
''' |
1e9a6f3a48d1eea874d7be49ffdf0fa2f3418393 | mxie622/LEETCODE_EASY | /easy_Question_solution.py | 16,372 | 3.75 | 4 | #https://leetcode.com/problems/rotate-array/description/
# Input: [-1,-100,3,99] and k = 2
# Output: [3,99,-1,-100]
# Explanation:
# rotate 1 steps to the right: [99,-1,-100,3]
# rotate 2 steps to the right: [3,99,-1,-100]
nums = [1,2,3,4,5,6,7]
k = 3
class Solution:
def rotate(self, nums, k):
n = k
inp = nums
i = 1
while k > 0:
nums.insert(0, inp[len(nums) - i])
i += 1
k -= 1
return nums[:-3]
print(Solution().rotate(nums, k))
#https://leetcode.com/problems/majority-element/description/
# Input: [2,2,1,1,1,2,2]
# Output: 2
class Solution:
def majorityElement(self, nums):
L = set(nums)
C = list(L)
n = len(nums)
for i in C:
if nums.count(i) > int(n/2):
element = i
return element
#https://leetcode.com/problems/climbing-stairs/description/
# Input: 3
# Output: 3
# Explanation: There are three ways to climb to the top.
# 1. 1 step + 1 step + 1 step
# 2. 1 step + 2 steps
# 3. 2 steps + 1 step
#method 1: Fibonacci formula. a**2 - a - 1 = 0
class Solution:
def climbStairs(self, n):
output = 1 / (5 ** 0.5) * (((1 + (5 ** 0.5)) / 2) ** (n + 1) - ((1 - (5 ** 0.5)) / 2) ** (n + 1))
return int(output)
#method2: Fibonacci series
class Solution:
def climbStairs(self, n):
if n == 1:
return 1
else:
one = 1
two = 2
for i in range(2, n):
three = one + two
one = two
two = three
return two
# method3: General
class Solution:
def climbStairs(self, n):
way_list = [1,1]
if n < 2:
return 1
for i in range(2,n+1):
ways = way_list[i-2]+way_list[i-1]
way_list.append(ways)
return way_list[-1]
#https://leetcode.com/problems/house-robber/description/
# Input: [2,7,9,3,1]
# Output: 12
# Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
# Total amount you can rob = 2 + 9 + 1 = 12.
class Solution:
def rob(self, nums):
if not nums:
return 0
for i in range(len(nums)):
if i ==1:
nums[i] = max(nums[0],nums[1])
if i > 1:
nums[i] = max(nums[i]+nums[i-2],nums[i-1])
return max(nums)
#https://leetcode.com/problems/range-sum-query-immutable/description/
# Given nums = [-2, 0, 3, -5, 2, -1]
# sumRange(0, 2) -> 1
# sumRange(2, 5) -> -1
# sumRange(0, 5) -> -3
class NumArray:
def __init__(self, nums):
self.nums = nums
def sumRange(self, i, j):
return sum(self.nums[i : j+1])
#https://leetcode.com/problems/maximum-subarray/description/
# Input: [-2,1,-3,4,-1,2,1,-5,4],
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
class Solution:
def maxSubArray(self, nums):
for i in range(1, len(nums)):
if nums[i-1] > 0:
nums[i] += nums[i-1]
return max(nums)
# https://leetcode.com/problems/divide-two-integers/description/
# Input: dividend = 7, divisor = -3
# Output: -2
class Solution:
def divide(self, dividend, divisor):
if dividend == -2147483648 and divisor == -1:
return 2147483648 - 1
elif 0 <= dividend * divisor:
return dividend // divisor
else:
return (abs(dividend) // abs(divisor))*(-1)
# https://leetcode.com/problems/invert-binary-tree/description/
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return
tmp=root.right
root.right=self.invertTree(root.left)
root.left=self.invertTree(tmp)
return root
# https://leetcode.com/problems/balanced-binary-tree/description/
class Solution(object):
def get_height(self, root):
if not root: return 0
left = self.get_height(root.left)
right = self.get_height(root.right)
if left == -1 or right == -1 : return -1
if abs(left - right) > 1: return -1
return max(left, right) + 1
def isBalanced(self, root):
height = self.get_height(root)
return height != -1
# https://leetcode.com/problems/implement-queue-using-stacks/description/
# MyQueue queue = new MyQueue();
#
# queue.push(1);
# queue.push(2);
# queue.peek(); // returns 1
# queue.pop(); // returns 1
# queue.empty(); // returns false
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.queue.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if self.queue != []:
a = self.queue[0]
self.queue = self.queue[1:]
return a
def peek(self):
"""
Get the front element.
:rtype: int
"""
if self.queue != []:
return self.queue[0]
def empty(self):
if self.queue == []:
return True
return False
# https://leetcode.com/problems/valid-parentheses/description/
# Input: "([)]"
# Output: false
# Input: "{[]}"
# Output: true
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
str_dict = {'(':-1,')':1,'[':-2,']':2,'{':-3,'}':3}
str_list = []
for i in s:
val = str_dict[i]
if val<0:
str_list.append(val)
else:
if str_list== []: return False
check = str_list.pop()
if check != -val:
return False
if str_list!= []: return False
return True
# https://leetcode.com/problems/move-zeroes/description/
# Input: [0,1,0,3,12]
# Output: [1,3,12,0,0]
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if len(nums) == 0:
return nums
dq = collections.deque()
for i in range(len(nums)):
if nums[i] == 0:
dq.append(i)
else:
if len(dq) != 0 and i > dq[0]:
tidx = dq.popleft()
nums[i], nums[tidx] = nums[tidx], nums[i]
dq.append(i)
# https://leetcode.com/problems/ugly-number/description/
# Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
# Input: 8
# Output: true
# Explanation: 8 = 2 × 2 × 2
# Input: 14
# Output: false
# Explanation: 14 is not ugly since it includes another prime factor 7.
class Solution:
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num == 0:
return False
else:
while num % 2 == 0:
num = num / 2
while num % 3 == 0:
num = num / 3
while num % 5 == 0:
num = num / 5
if num == 1 or num == 2 or num == 3 or num == 5:
return True
else:
return False
# https://leetcode.com/problems/contains-duplicate/description/
# Input: [1,2,3,4]
# Output: false
# Input: [1,2,3,1]
# Output: true
class Solution:
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return len(set(nums)) != len(nums)
# https://leetcode.com/problems/search-insert-position/description/
# Input: [1,3,5,6], 2
# Output: 1
# Input: [1,3,5,6], 0
# Output: 0
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
a = 0
if target == 0:
return 0
else:
for i in nums:
if target <= i:
a = nums.index(i)
break
else:
a = len(nums)
return a
# https://leetcode.com/problems/valid-mountain-array/description/
# A[0] < A[1] < ... A[i-1] < A[i]
# A[i] > A[i+1] > ... > A[B.length - 1]
# Input: [0,3,2,1]
# Output: true
# Input: [3,5,5]
# Output: false
class Solution:
def validMountainArray(self, A):
"""
:type A: List[int]
:rtype: bool
"""
h = 0
g = 0
i = 0
output = True
d = []
f = []
if len(A) <= 2 or A[1] <= A[0] or A[len(A)-2] <= A[len(A)-1]:
return False
else:
for i in range(0, A.index(max(A))):
if 0 < A[i+1] - A[i]:
h += 1
else:
output = False
break
if h == A.index(max(A)):
for k in range(h, len(A)-1):
if 0 > A[k+1] - A[k]:
g += 1
else:
output = False
break
return output
# https://leetcode.com/problems/excel-sheet-column-title/description/
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
s = ''
while n>0:
s += chr((n-1)%26 + ord('A'))
n = (n-1)//26
return s[::-1]
# https://leetcode.com/problems/backspace-string-compare/description/
class Solution(object):
def backspaceCompare(self, S, T):
def build(S):
ans = []
for c in S:
if c != '#':
ans.append(c)
elif ans:
ans.pop()
return "".join(ans)
return build(S) == build(T)
# https://leetcode.com/problems/number-of-recent-calls/description/
# Input: inputs = ["RecentCounter","ping","ping","ping","ping"], inputs = [[],[1],[100],[3001],[3002]]
# Output: [null,1,2,3,3]
class RecentCounter(object):
def __init__(self):
self.q = collections.deque()
def ping(self, t):
self.q.append(t)
while self.q[0] < t-3000:
self.q.popleft()
return len(self.q)
# https://leetcode.com/problems/power-of-two/description/
# Example 2:
#
# Input: 16
# Output: true
# Explanation: 24 = 16
# Example 3:
#
# Input: 218
# Output: false
class Solution:
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n<=0:
return False;
while n>0:
if n == 1:
return True;
if n%2!=0:
return False;
n = n/2;
# https://leetcode.com/problems/power-of-three/description/
# Input: 9
# Output: true
# Example 4:
#
# Input: 45
# Output: false
class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
while n > 0:
if n == 1:
return True
if n % 3 != 0:
return False
n = n / 3
# https://leetcode.com/problems/power-of-four/description/
# Input: 16
# Output: true
# Example 2:
# Input: 5
# Output: false
class Solution:
def isPowerOfFour(self, n):
while n > 1:
n /= 4.0
return n == 1
# https://leetcode.com/problems/single-number/description/
# Input: [2,2,1]
# Output: 1
# Example 2:
#
# Input: [4,1,2,1,2]
# Output: 4
## Method1: hash table
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
hash_table = {}
for i in nums:
try:
hash_table.pop(i)
except:
hash_table[i] = 1
return hash_table.popitem()[0]
## Method2: My solution:...bad time consumed
# class Solution:
# def singleNumber(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# a = set()
# b = set()
# for i in nums:
# if i not in a:
# a.add(i)
# else:
# b.add(i)
# a = list(a)
# b = list(b)
# print(b)
#
# for j in a:
# if j not in b:
# a = j
# return a
## Method3: Regular expression
# class Solution(object):
# def singleNumber(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# a = 0
# for i in nums:
# a ^= i
# print(a)
# return a
# https://leetcode.com/problems/missing-number/description/
# Input: [9,6,4,2,3,5,7,0,1]
# Output: 8
class Solution:
def missingNumber(self, nums):
num_set = set(nums)
n = len(nums) + 1
for number in range(n):
if number not in num_set:
return number
# https://leetcode.com/problems/hamming-distance/description/
# Input: x = 1, y = 4
#
# Output: 2
#
# Explanation:
# 1 (0 0 0 1)
# 4 (0 1 0 0)
# Method1: Use 'bin' function
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')
# Method2: Bit manipulation
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
res = 0
while x or y:
if (x & 1) ^ (y & 1) == 1:
res += 1
x >>= 1
y >>= 1
return res
# -----------Quick Sort Method------------
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
print(quicksort([3,6,8,10,1,2,1]))
# https://leetcode.com/problems/valid-perfect-square/description/
# Example 1:
#
# Input: 16
# Output: true
# Example 2:
#
# Input: 14
# Output: false
class Solution:
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
a = 1
while a*a < num:
a += 1
if a*a == num:
return True
else:
return False
# https://leetcode.com/problems/perfect-number/description/
# Input: 28
# Output: True
# Explanation: 28 = 1 + 2 + 4 + 7 + 14
class Solution:
def checkPerfectNumber(self, num):
if num<=1:
return False
a=int(num**0.5)
b=1
for i in range(2,a+1):
if num % i==0:
b=b+i+num/i
return int(b)==num
# https://leetcode.com/problems/letter-case-permutation/description/
# Input: S = "3z4"
# Output: ["3z4", "3Z4"]
#
# Input: S = "12345"
# Output: ["12345"]
class Solution:
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
res = [S]
for i, c in enumerate(S):
if c.isalpha():
res.extend([s[:i] + s[i].swapcase() + s[i + 1:] for s in res])
return res
# https://leetcode.com/contest/weekly-contest-116/problems/n-repeated-element-in-size-2n-array/
# Input: [5,1,5,2,5,3,5,4]
# Output: 5
class Solution:
def repeatedNTimes(self, A):
"""
:type A: List[int]
:rtype: int
"""
size = len(A)
N = size / 2
for i in A:
if A.count(i) == N:
return i
break
# https://leetcode.com/problems/two-sum/
# Given nums = [2, 7, 11, 15], target = 9,
#
# Because nums[0] + nums[1] = 2 + 7 = 9
class Solution:
def twoSum(self, nums, target):
table = {}
for index, v in enumerate(nums):
if not v in table:
table[v] = index
if target - v in table:
if index != table[target - v]:
return [table[target - v], index]
return None
|
0af4fa88d5abdca2d8fa08a8919db3174888f277 | maplekiru/python-ds-practice | /fs_04_reverse_vowels.py | 494 | 4.28125 | 4 | def reverse_vowels(s):
"""Reverse vowels in a string.
Characters which re not vowels do not change position in string, but all
vowels (y is not a vowel), should reverse their order.
>>> reverse_vowels("Hello!")
'Holle!'
>>> reverse_vowels("Tomatoes")
'Temotaos'
>>> reverse_vowels("Reverse Vowels In A String")
'RivArsI Vewols en e Streng'
reverse_vowels("aeiou")
'uoiea'
reverse_vowels("why try, shy fly?")
'why try, shy fly?''
""" |
12a8896ff4c149d9746a5989cae56b92071e004b | lukdz/KursPython | /3lista/2zad.py | 363 | 3.859375 | 4 | import math
def squareRoot(n):
for j in range(0,n+2):
sum = 0
for i in range(1,j+1):
sum += (2*i-1)
if sum > n:
return j-1
return 0
for i in range(0,100):
if squareRoot(i) != math.floor(math.sqrt(i)):
print("number: ", i, "\tsquareRoot: ", squareRoot(i), "\tmath: ", math.floor(math.sqrt(i))) |
58200818ee0cf651ab2a9605cd815eca075dfb8f | RiyaPatricia/ShapeAI | /md5.py | 123 | 3.578125 | 4 | import hashlib
hash=input("Enter Input:")
last = hashlib.md5(hash.encode())
print("This is md5 Hash :",last.hexdigest()) |
af379974c07a29556d22a7d92a570e242677fa1f | Bjcurty/PycharmProjects | /Python-Refresher/01_variables/code.py | 239 | 3.5625 | 4 | # x = 15
# price = 9.99
#
# discount = 0.2
#
# result = price * (1-discount)
#
# print(result)
# name = "Rolf"
# # name = "Bob"
#
# print(name)
# print(name * 2)
# a = 25
# b = a
#
# print(a)
# print(b)
#
# b = 17
#
# print(a)
# print(b) |
c7cdfd7e8b74184f41bc96b138f450ae32671c26 | PolopTechnology/Algorithms | /Python/Tortoise and Hare/TandH.py | 244 | 3.859375 | 4 | Tortoise = 0
Hare = 0
while True:
Tortoise += 1
Hare += 2
if Tortoise == Hare:
print(Tortoise)
print(Hare)
break
if Tortoise == 10:
Tortoise = 0
if Hare >= 10:
Hare = 0
|
ad781de1b926fb941da1ec441d7f302820993d00 | kokitsune/nichirin | /uEnkrypt.py | 14,101 | 3.75 | 4 | '''
Project ala Pegeant:
Encryption and Decryption.
'''
from Tkinter import *
class XOR:
'''
For operation concerning XOR method.
Attribute : A sequence of character.
'''
def __init__(self, original='Default', rawkey='00000000', auto=False, filename='untitled'):
self.root = Tk()
if auto:
self.filename = StringVar()
self.filename.set(filename)
self.load()
self.root.resizable(width=FALSE, height=FALSE)
self.root.geometry('{}x{}'.format(300, 400))
self.root.title('XOR Cipher')
Label(self.root, text='').grid(row=3)
Label(self.root, text=' XOR cipher uses its namesake logic gate ').grid(row=1)
Label(self.root, text=' to switch binary from 0 to 1 and vice versa. ').grid(row=2)
Label(self.root, text='Enter sequence of characters you wish to decrypt below.').grid(row=4)
self.original = StringVar(self.root)
self.original.set(original)
Entry(self.root, textvariable=self.original).grid(row=5,columnspan=100, sticky=W+E+N+S)
self.stat = StringVar(self.root)
self.stat.set("Binary") # initial value
option = OptionMenu(self.root, self.stat, "Binary", "Number", "ASCII Character").grid(row=7)
Label(self.root, text='Select key type from below.').grid(row=6)
Label(self.root, text='Insert a key according to the type you choose.').grid(row=8)
self.rawkey = StringVar(self.root)
self.rawkey.set(rawkey)
Entry(self.root, textvariable=self.rawkey).grid(row=9,column=0)
Button(self.root, text=" Begin Encryption/Decryption ", command=self.encryption).grid(row=10)
Label(self.root, text='').grid(row=100)
Label(self.root, text='Filename').grid(row=101)
self.filename = StringVar(self.root)
self.filename.set('untitled')
Entry(self.root, textvariable=self.filename).grid(row=105)
Button(self.root, text=" Save ", command=self.save).grid(row=106)
Button(self.root, text=" Load ", command=self.load).grid(row=107)
Label(self.root, text='').grid(row=108)
Button(self.root, text=" Back ", command=self.quitting).grid(row=200)
self.root.mainloop()
def __str__(self):
return self.original
def get_key(self):#Maximum MUST be 00111111
print self.rawkey.get()
if self.stat.get() == 'Number':
self.key = bin(int(self.rawkey.get()))[-6:]
elif self.stat.get() == 'ASCII Character':
self.key = bin(ord(self.rawkey.get()))[-6:]
else:
self.key = self.rawkey.get()[-6:]
self.key = '0'*(8-len(self.key.replace('b', '')))+self.key.replace('b', '')
def encryption(self):
'''
It's both the encryption and decryption actually.
'''
self.get_key()
self.encrypted = ''
for longgong in self.original.get():
temp = ''
longgong = '0'*(8-len(bin(ord(longgong.replace('b', '')))))+bin(ord(longgong)).replace('b', '')#OLD-> '%8s' % bin(ord(longgong)).replace('b', '')
for tower, rook in zip(longgong.replace(' ', '0'), self.key):
if tower == rook:
temp += '0'
else:
temp += '1'
print longgong.replace(' ', '0'), self.key, temp
self.encrypted += chr(int(temp, 2))
print self.encrypted
PopupResult('XOR Cipher', self.encrypted)
def decryption(self):
'''
A layout for other methods.
'''
pass
def quitting(self):
self.root.destroy()
mane = Mainmenu()
def save(self):
try:
text = open('%s.txt' % self.filename.get(), 'w')
text.write('bindingofclarke')
text.write('jaaaaiaaayaaaason!jaaaasonjasonjaeeeaason')
text.write(self.key)
text.write('8151321542334longgong5789546512367')
text.write(self.encrypted)
Popup('XOR Save', 'Save completed.')
except:
Popup('XOR Save', 'Save Failed.')
def load(self):
try:
text = open('%s.txt' % self.filename.get(), 'r')
cur = text.read().split('jaaaaiaaayaaaason!jaaaasonjasonjaeeeaason',1)[1]
rawkey, original = cur.split('8151321542334longgong5789546512367', 1)
self.root.destroy()
current = XOR(original, rawkey)
except:
Popup('XOR Load', 'Load Failed.')
###############################################################END OF XOR############################################################################
class CipherDisk:
'''
For operation concerning Cipher Disk method.
Attribute: A sequence of character, number of turns
'''
def __init__(self, original='Default', turn='1', disk='ABCDEFGHIJKLMNOPQRSTUVWXYZ', auto=False, filename=''):
self.root = Tk()
if auto:
self.filename = StringVar()
self.filename.set(filename)
self.load()
self.root.resizable(width=FALSE, height=FALSE)
self.root.geometry('{}x{}'.format(310, 480))
self.root.title('Cipher Disk')
Label(self.root, text='').grid(row=3)
Label(self.root, text=' While not as cool as the German Enigma ').grid(row=1)
Label(self.root, text='There are people who are oblivious to this method.').grid(row=2)
Label(self.root, text='Enter sequence of characters you wish to decrypt below.').grid(row=4)
Label(self.root, text='Any character not in the disk will not be altered.').grid(row=5)
self.original = StringVar(self.root)
self.original.set(original)
Entry(self.root, textvariable=self.original).grid(row=6,columnspan=100, sticky=W+E+N+S)
Label(self.root, text='Specify a number of turn in integer. (Shift)').grid(row=7)
self.turn = StringVar(self.root)
self.turn.set(turn)
Entry(self.root, textvariable=self.turn).grid(row=10,columnspan=1)
Label(self.root, text='Alter the Cipher Disk below.').grid(row=14)
self.disk = StringVar(self.root)
self.disk.set(disk)
Entry(self.root, textvariable=self.disk).grid(row=15,columnspan=2, sticky=W+E+N+S)
Label(self.root, text='').grid(row=16)
Button(self.root, text=" Begin Encryption ", command=self.encryption).grid(row=20)
Button(self.root, text=" Begin Decryption ", command=self.decryption).grid(row=21)
Label(self.root, text='').grid(row=100)
Label(self.root, text='Filename').grid(row=101)
self.filename = StringVar(self.root)
self.filename.set('untitled')
Entry(self.root, textvariable=self.filename).grid(row=105)
Button(self.root, text=" Save ", command=self.save).grid(row=106)
Button(self.root, text=" Load ", command=self.load).grid(row=107)
Label(self.root, text='').grid(row=199)
Button(self.root, text=" Back ", command=self.quitting).grid(row=200)
self.root.mainloop()
def encryption(self):
self.encrypted = ''
for longgong in self.original.get():
if longgong in self.disk.get():
self.encrypted += self.disk.get()[(self.disk.get().index(longgong)+int(self.turn.get()))%len(self.disk.get())]
elif longgong.upper() in self.disk.get():
self.encrypted += self.disk.get()[(self.disk.get().index(longgong.upper())+int(self.turn.get()))%len(self.disk.get())].lower()
else:
self.encrypted += longgong
print self.encrypted
PopupResult('Cipher Disk', self.encrypted)
def decryption(self):
self.decrypted = ''
for longgong in self.original.get():
if longgong in self.disk.get():
self.decrypted += self.disk.get()[(self.disk.get().index(longgong)-int(self.turn.get()))%len(self.disk.get())]
elif longgong.upper() in self.disk.get():
self.decrypted += self.disk.get()[(self.disk.get().index(longgong.upper())-int(self.turn.get()))%len(self.disk.get())].lower()
else:
self.decrypted += longgong
print self.decrypted
PopupResult('Cipher Disk', self.decrypted)
def quitting(self):
self.root.destroy()
mane = Mainmenu()
def save(self):
try:
text = open('%s.txt' % self.filename.get(), 'w')
text.write('Cesareborgia')
text.write('jaaaaiaaayaaaason!jaaaasonjasonjaeeeaason')
text.write(self.disk.get())
text.write('shauunshaunnasdsafyaaaashaunnnnnwaaksdjdisal')
text.write(self.turn.get())
text.write('8151321542334longgong5789546512367')
text.write(self.encrypted)
Popup('CipherDisk Save', 'Save Completed.')
except:
Popup('CipherDisk Save', 'Save Failed.')
def load(self):
try:
text = open('%s.txt' % self.filename.get(), 'r')
cur = text.read().split('jaaaaiaaayaaaason!jaaaasonjasonjaeeeaason',1)[1]
disk, cur = cur.split('shauunshaunnasdsafyaaaashaunnnnnwaaksdjdisal', 1)
turn, original = cur.split('8151321542334longgong5789546512367', 1)
self.root.destroy()
current = CipherDisk(original, turn, disk)
except:
Popup('CipherDisk Load', 'Load Failed.')
def load(filename='untitled'):
text = open('%s.txt' % filename, 'r')
return tuple(text.read().split('jaaaaiaaayaaaason!jaaaasonjasonjaeeeaason'))
class AutoDetect:
def __init__(self, filename):
try:
me = load(filename)
if me[0] == 'bindingofclarke':
Popup('Auto-Detect Report', ' This file uses XOR method. ', 'Taking you there.')
current = XOR('', '', True, filename)
elif me[0] == 'Cesareborgia':
Popup('Auto-Detect Report', ' This file uses Cipher Disk method. ', 'Taking you there.')
current = CipherDisk('', '', '', True, filename)
else:
Popup('Achtung!', 'The program cannot recognize this files.', 'Which makes it near 100% that it can not be decrypted.')
mane = Mainmenu()
except(IOError):
Popup('Achtung!', 'Attention : No such files specified.')
mane = Mainmenu()
class Popup():
def __init__(self, title='Insert something amusing here.', message='This message is intentionally left blank, I guess...', message2='', message3=''):
self.root = Tk()
self.root.title(title)
self.root.resizable(width=FALSE, height=FALSE)
Label(self.root, text='%s%s%s' % (' '*(50-len(message)), message, ' '*(50-len(message)))).grid(row=1)
Label(self.root, text='%s%s%s' % (' '*(50-len(message2)), message2, ' '*(50-len(message2)))).grid(row=2)
Label(self.root, text='%s%s%s' % (' '*(50-len(message3)), message3, ' '*(50-len(message3)))).grid(row=3)
self.root.geometry('{}x{}'.format(400, 150))
##Spaces are disgraces//
Label(self.root, text='').grid(row=4)
Label(self.root, text='').grid(row=0)
##End of disgraces//
Button(self.root, command=self.root.destroy, text='Comprendo').grid(row=800)
class PopupResult():
def __init__(self, title='Insert Title', bunny='A result'):
self.root = Tk()
self.root.resizable(width=FALSE, height=FALSE)
self.root.geometry('{}x{}'.format(400, 150))
self.root.title(title)
Label(self.root, text=' ').grid(row=0)
Label(self.root, text='The result is in.').grid(row=1)
Label(self.root, text='').grid(row=2)
Label(self.root, text='').grid(row=5)
message = StringVar(self.root)
message.set(bunny)
Entry(self.root, textvariable=message).grid(row=4,columnspan=5,rowspan=250, sticky=W+E+N+S)
Button(self.root, command=self.root.destroy, text='Comprendo').grid(row=500)
class Mainmenu:
def __init__(self):
self.root = Tk()
self.root.resizable(width=FALSE, height=FALSE)
self.root.geometry('{}x{}'.format(300, 320))
self.root.title('uDEncrypt')
Label(self.root, text='Welcome to uEncrypt 2000').grid(row=1)
Label(self.root, text='Please select any type of encryption to begin').grid(row=400)
Button(self.root, text=" XOR Encryption/Decryption ", command=self.xor).grid(row=500)
Button(self.root, text=" CipherDisk Encryption/Decryption ", command=self.disk).grid(row=600)
Label(self.root, text='Or insert a saved encrypted filename for ease of access.').grid(row=698)
Button(self.root, text=" Auto Detect ", command=self.detect).grid(row=700)
self.filename = StringVar(self.root)
self.filename.set("untitled")
Entry(self.root, textvariable=self.filename).grid(row=699, column=0)
Button(self.root, command=self.root.quit, text=' Terminate ').grid(row=800)
##Spaces are disgraces//
Label(self.root, text='').grid(row=1)
Label(self.root, text='').grid(row=401)
Label(self.root, text='').grid(row=501)
Label(self.root, text='').grid(row=701)
Label(self.root, text='').grid(row=602)
Label(self.root, text='').grid(row=402)
Label(self.root, text='').grid(row=0)
##End of disgraces//
self.root.mainloop()
def xor(self):
self.root.destroy()
current = XOR()
def disk(self):
self.root.destroy()
current = CipherDisk()
def detect(self):
self.root.destroy()
current = AutoDetect(self.filename.get())
mane = Mainmenu()
|
4a3738a60c7e4d7215d5f236a14ce3f001eff807 | sharikgrg/week4.postcodes-to-txt-exercise | /function_postcodes.py | 635 | 3.703125 | 4 | import requests
import json
# request the data and using .json get the data in a dictionary.
# prints out relevant data using the keys
def importing_functions(postcode):
request_postcode = requests.get('http://api.postcodes.io/postcodes/' + postcode)
retrieving_data = request_postcode.json()
postcode = json.dumps(retrieving_data['result']['postcode'])
return str(postcode)
# to add the data into the .txt file.
def append_to_file(file, postcode = {}):
try:
with open(file,'a') as opened_file:
opened_file.write(postcode + '\n')
except FileNotFoundError:
print('File not found') |
e91b18ca4e4d8684d77d87f140a408fc9a45602c | RainbowTraveller/pythonPranks | /str_rev.py | 650 | 4.21875 | 4 | #!/usr/bin/python
def reverse(mystr):
#Get the length
length = len(mystr);
if(length > 0):
str_list = list(mystr);
begin = 0;
end = length -1;
while (begin < end):
tmp = str_list[begin]
str_list[begin] = str_list[end]
str_list[end] = tmp
begin += 1
end -= 1
mystr = "".join(str_list)
print "Reversed String : ", mystr
else:
print "Please enter a valid string"
def main():
#Accept String
print "Please Enter the string: "
mystr = raw_input()
reverse(mystr)
if __name__ == "__main__":
main()
|
3aa4b30ab759164611a19a06a5625007cbac29ae | katebartnik/katepython | /Book/RepeatWhile/While1.py | 144 | 3.71875 | 4 | tab = [1, 2, 3, 4, 5]
index = 0
x = 3
while index < len(tab):
if x == tab[index]:
print(index)
break
index = index +1
|
6d941c3a25b2946c94c1324912972dff4846c5a8 | Chenbw0/motion_planning | /trajectory_plotting.py | 639 | 3.546875 | 4 | import region
import matplotlib.pyplot as plt
from numpy import *
def PlotBubbles(bubbles):
""" Plots bubbles given by the centers and radii found in bubbles. """
# bubbles is a list
# bubbles[0] is a list of centers: [[x0,y0],[x1,y1],...,[xn,yn]]
# bubbles[1] is a list of radii: [r0,r1,...,rn]
fig = plt.gcf()
for i in range(len(bubbles[0])):
circle = plt.Circle(bubbles[0][i],bubbles[1][i],fill=False)
fig.gca().add_artist(circle)
def PlotTrajectory(P):
""" Plots waypoints and joining edges found in P. """
# P is a numpy array: [[x0,y0],[x1,y1],...,[xn,yn]]
x = P[:,0]
y = P[:,1]
plt.scatter(x,y)
plt.plot(x,y)
|
da864ddadea1fbb442db3f0a3c1ec807bcfbff4b | smiroshnikov/ebaPo4tu | /haim/lecture2/practice2.py | 2,194 | 3.59375 | 4 | long_element_list = [12.5, "abc",
[4, 2, 53, "abnc"], {'one': 'The One', 'two': 'Two Files'},
(1, 'abc', 23, "A"), {'a', 'b', 'c'}, True]
for e in long_element_list:
print(type(e))
str = "hello"
for ix, letter in enumerate(str):
print(str[ix])
for l in str:
print(l)
list = [12, 43, 64, 9]
sum = list[0] + list[1] + list[2] + list[3]
print(sum)
cars = {5324334, "mazda 6", "2014", "2000",
2434343, "mazda 3", "2013", "1600",
5234343, "ford kuga", "2014", "1500"}
print(cars)
total = 0
account = {
5324334: (5324334, 10000, 0.02),
2434343: (2434343, 80000, 0.01),
5234343: (5234343, 30000, 0.02)
}
total += account.get(5324334)[1]
total += account.get(2434343)[1]
total += account.get(5234343)[1]
print(total)
numner = 1232
print(f"{bin(numner)} binary \n")
print(f"{hex(numner)} hexadecimal \n")
print(f"{oct(numner)} octal \n")
from math import fsum
def gimmeFsum(l):
return fsum(l)
print(gimmeFsum([32, 345, 342, 4, 234]))
from fractions import Fraction
def gimmeTotalFraction(list):
t = 0
for e in list:
t += Fraction(*e)
# The * operator simply unpacks the tuple and passes them as the positional arguments to the function.
return t
print(gimmeTotalFraction([(3, 4), (1, 7), (3, 8), (5, 9), (7, 8), (13, 17)]))
def convert_user_to_binary():
return bin(int(input("please enter a number ")))
print(convert_user_to_binary())
def create_love_file(filename):
f = open(filename, 'w')
f.write("we love python!")
f.close()
create_love_file('new_text.txt')
def read_file(filename):
f = open(filename, 'r')
print(f.readlines())
read_file('new_text.txt')
list = [Fraction(1, 2), Fraction(3, 4), Fraction(5, 8), Fraction(7, 8)]
copied_list = list.copy()
copied_list[0] = Fraction(897, 15644)
print(f"{list} original list")
print(f"{copied_list} copied list")
def calculate_sum(l):
r = 0
for n in l:
r += n
return r / len(l)
print(calculate_sum([1, 2, 3]))
from decimal import Decimal
from decimal import getcontext
getcontext().prec=10 # total number of digits
print(f"{Decimal(12002).sqrt()} here it is ")
|
367f515017846773cd2c432c438e0bb34fb8e534 | gyogy/haxx | /music_library/utils.py | 1,588 | 3.515625 | 4 | from random import shuffle
from datetime import datetime
def length_str_to_time_object(length):
if len(length.split(':')) == 2:
song_time = datetime.strptime(length, '%M:%S').time()
else:
song_time = datetime.strptime(length, '%H:%M:%S').time()
return song_time
def total_p_time(songs):
hours = 0
minutes = 0
seconds = 0
for song in songs:
song_time = length_str_to_time_object(song.length_str)
hours += song_time.hour
minutes += song_time.minute
seconds += song_time.second
if seconds > 60:
minutes += seconds // 60
seconds = seconds % 60
if minutes > 60:
hours += minutes // 60
minutes = minutes % 60
return f'{hours}:{minutes}:{seconds}'
def next_up_in(playlist):
if playlist.shuffle:
shuffle(playlist.unplayed_songs)
try:
playlist.played_songs.append(playlist.unplayed_songs[0])
playlist.unplayed_songs.remove(playlist.unplayed_songs[0])
return playlist.unplayed_songs, playlist.played_songs, playlist.played_songs[-1]
except IndexError:
if playlist.repeat:
for song in playlist.played_songs:
playlist.unplayed_songs.append(song)
playlist.played_songs = []
return next_up_in(playlist)
else:
# An IndexError here means that playlist.unplayed_songs list is empty.
return playlist.unplayed_songs, playlist.played_songs, 'Reached end of playlist.'
def main():
pass
if __name__ == '__main__':
main()
|
35b8aaee7a202c475dbd0f6877763ce25d5d4bfd | RamazanAktas1/14.Hafta-Odevler | /14.hafta...1.odev.py | 459 | 3.765625 | 4 | def pageCount():
n = int(input())
p = int(input())
if n == p:
print(n - p)
elif (n - p) >= p : # starting from the beginning of the book
if n % 2 == 0 :
print(int(p / 2))
else:
print(int(p / 2))
elif (n - p) <= p : # starting from the end of the book
if n % 2 == 0 :
print(int(((n - 1) - p) / 2 )+1)
else:
print(int((n - p) / 2))
pageCount()
|
ae298d8195b87febce3e3c1dbec86e4a53950db5 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_209/608.py | 1,007 | 3.640625 | 4 | #!/usr/bin/env python
from math import pi
from operator import itemgetter
import itertools
from multiset import *
def get_area(pancakes):
circle = pancakes[0][0] ** 2 * pi
area = circle + 2 * pi * pancakes[0][0] * pancakes[0][1]
for i in xrange(1, len(pancakes)):
area += pancakes[i][0] ** 2 * pi + 2 * pi * pancakes[i][0] * pancakes[i][1] - circle
circle = pancakes[i][0] ** 2 * pi
return area
def find_max(pancakes, k):
comb = set(itertools.combinations(pancakes, k))
max = 0
for _ in xrange(0, len(comb)):
pan = sorted(comb.pop(), key=itemgetter(0))
value = get_area(pan)
if value > max:
max = value
return max
t = int(raw_input()) # read a line with a single integer
for i in xrange(1, t + 1):
n, k = [int(s) for s in raw_input().split(" ")] # read a list of integers, 2 in this case
pancakes = Multiset()
for j in xrange(1, n + 1):
r, h = [int(s) for s in raw_input().split(" ")]
pancakes.add((r, h))
max = find_max(pancakes, k)
print "Case #{}: {}".format(i, max) |
bfd8ea9bbbf04a1269705b990a7a338f510f84db | xiamengyu/dirtysalt.github.io | /codes/contest/lintcode/first-unique-character-in-a-string.py | 637 | 3.796875 | 4 | #!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
class Solution:
"""
@param str: str: the given string
@return: char: the first unique character in a given string
"""
def firstUniqChar(self, str):
# Write your code here
counter = 0
invalid = 0
for c in str:
idx = ord(c) - ord('a')
if counter & (1 << idx):
invalid |= (1 << idx)
else:
counter |= (1 << idx)
for c in str:
idx = ord(c) - ord('a')
if (invalid & (1 << idx)) == 0:
return c
return None
|
209bcfff04625c5ca624bfede51f33ecf5a05ada | mafdezmoreno/HackerRank_Callenges | /Practice/ProblemSolving/SwapNodes_other.py | 2,296 | 3.9375 | 4 | #https://programs.programmingoneonone.com/2021/03/hackerrank-swap-nodes-algo-solution.html
from collections import deque
from types import new_class
class Node:
def __init__(self, index):
self.left = None
self.right = None
self.index = index
class BinarySearchTree:
def __init__(self):
self.root = Node(1)
self.root.level = 1
def inorderTraversal(self, root):
res = []
if root:
res = self.inorderTraversal(root.left)
res.append(root.info)
res = res + self.inorderTraversal(root.right)
return res
def in_order_traverse(root):
"""Don't use recursion b/c of recursion limit."""
stack = deque([root])
visited = set()
while stack:
node = stack.pop()
if node is None:
continue
if node.index in visited:
print(node.index, end=' ')
continue
visited.add(node.index)
stack.append(node.right)
stack.append(node)
stack.append(node.left)
def swap(root, k):
"""Don't use recursion b/c of recursion limit."""
q = deque([(root, 1)])
while q:
node, level = q.popleft()
if node is None:
continue
if level % k == 0:
node.left, node.right = node.right, node.left
q.append((node.left, level+1))
q.append((node.right, level+1))
with open('SwapNodes_Test_1.txt') as file:
# get number of nodes
N = int(next(file))
# create node list
nodes = [None]*(N+1)
for i in range(1, N+1):
n = Node(i)
n.left_index, n.right_index = [v if v > 0 else 0 for v in map(int, next(file).split())]
nodes[i] = n
# fill out node objects
for n in nodes[1:]:
left = nodes[n.left_index]
right = nodes[n.right_index]
n.left = left
n.right = right
T = int(next(file))
root = nodes[1]
# do the swapping
for _ in range(T):
k = int(next(file))
swap(root, k)
in_order_traverse(root)
print('')
# Expected result for test case 0
print("Expected result for test case 0")
print([14, 8, 5, 9, 2, 4, 13, 7, 12, 1, 3, 10, 15, 6, 17, 11, 16])
print([9, 5, 14, 8, 2, 13, 7, 12, 4, 1, 3, 17, 11, 16, 6, 10, 15]) |
3269fabe6eab3b76ba2a93c6e4a80c1730264d0b | ducnguyen166/aaa | /baikiemtra/bt4.py | 140 | 3.71875 | 4 | tong = 0
n = 1
print("hãy nhập vào số n: ")
n = int(input())
for i in range(0, n + 1):
tong += i
print("Tổng là: ", tong) |
d6acd9f6d97da62feb8140c2c11e22aafe010be4 | PKStuff/task | /Practice_Algo/linked_list.py | 2,219 | 4.21875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def create(self, data):
new_node = Node(data)
if self.head == None:
self.head = new_node
return
else:
new_node.next = self.head
self.head = new_node
return
def insert_at_last(self, data):
new_node = Node(data)
temp_node = self.head
while temp_node.next != None:
temp_node = temp_node.next
temp_node.next = new_node
return
def delete_at_first(self):
if self.head:
temp_node = self.head
if self.head.next == None:
self.head = None
else:
self.head = self.head.next
temp_node.next = None
return temp_node.data
else:
return -1
def delete_at_last(self):
if self.head:
temp_node = self.head
del_node_data = None
if self.head.next == None:
del_node_data = self.head.data
self.head = None
else:
while temp_node.next.next != None:
temp_node = temp_node.next
del_node_data = temp_node.next.data
temp_node.next = None
return del_node_data
else:
return -1
def display(self):
if self.head:
temp_node = self.head
while temp_node.next != None:
print(temp_node.data, end=",")
temp_node = temp_node.next
print(temp_node.data)
else:
print("List is empty...")
def first(self):
if self.head:
return self.head.data
else:
return -1
if __name__ == '__main__':
l1 = LinkedList()
l1.create(1)
l1.create(2)
l1.create(3)
print("Before Deletion:")
l1.display()
l1.delete_at_last()
print("After deletion:")
l1.display()
print("Top is:{}".format(l1.first()))
print("The head is:{}".format(l1.head.data))
|
d9eb46e18c17927192280d1b3cb7579972644573 | anjolinea/Python-for-Everybody | /ch11ex1.py | 242 | 3.96875 | 4 | import re
count = 0
hand = open("mbox-short.txt")
regex = input("Enter a regular expression >> ")
for line in hand:
regex_occurences = re.findall(regex, line)
for occurence in regex_occurences:
count += 1
print(count, regex)
|
9a953a2c5cd0c6604e46560d31b23dedcdee5537 | srihariprasad-r/workable-code | /codeforces/P58A_Chatroom.py | 354 | 3.828125 | 4 | inp_str = str(input())
valid_str = "hello"
concat_str = ""
pos_dict = {valid_str[i]: valid_str.count(valid_str[i]) for i in range(len(valid_str))}
for i in inp_str:
if i in valid_str and (i in pos_dict):
if pos_dict[i] > concat_str.count(i):
concat_str += i
if concat_str == valid_str:
print("YES")
else:
print("NO")
|
1a2dccc84a82c15ccd1ba6664a984dc70240a598 | MuhammadAbbasi/DSA_Semester3 | /Assignments/Assignment 2/All questions/Q5.py | 251 | 3.65625 | 4 | '''What parameters should be sent to the range constructor,to
produce a range with values 8, 6, 4, 2, 0,−2,−4,−6,−8? '''
range( 8, -9, -2 )
# The code below is for testing purpose only
z = range( 8, -9, -2 )
for a in z:
print(a) |
6ec22cb0a5c75c6996aced9bdd59fc2e02dfe591 | gitly110/python_exc | /python从入门到实践/data_download16/highs_lows.py | 2,084 | 3.515625 | 4 | import csv
from datetime import datetime
from matplotlib import pyplot as plt
# 从文件获取最高、最低气温
def read_csv(filename):
# filename = 'sitka_weather_2014.csv'
with open(filename) as f:
reader = csv.reader(f)
hearder_row = next(reader)
# # 查看文件头每个元素的索引及其值
# for index, column_header in enumerate(hearder_row):
# print(index,column_header)
dates, highs, lows = [], [], []
for row in reader: # 遍历文件中余下的各行
try:
# 每行索引为0的是日期,转为日期格式存入列表
date = datetime.strptime(row[0], "%Y-%m-%d")
# 每行索引为1的是最高温度,转为数字存入列表
high = int(row[1])
low = int(row[3])
except ValueError:
print(date, 'missing data')
else:
dates.append(date)
highs.append(high)
lows.append(low)
return dates, highs, lows
dates1, highs1, lows1 = read_csv('sitka_weather_2014.csv')
dates2, highs2, lows2 = read_csv('death_valley_2014.csv')
# 根据数据绘制图`
fig = plt.figure(dpi=128, figsize=(10, 6))
# alpha 指定颜色的透明度。Alpha 值为0表示完全透明,1(默认设置)表示完全不透明
# sitka_weather_2014
plt.plot(dates1, highs1, c='red', alpha=0.5)
plt.plot(dates1, lows1, c='blue', alpha=0.5)
plt.fill_between(dates1, highs1, lows1, facecolor='blue', alpha=0.1)
# death_valley_2014
plt.plot(dates2, highs2, c='yellow', alpha=0.5)
plt.plot(dates2, lows2, c='green', alpha=0.5)
plt.fill_between(dates2, highs2, lows2, facecolor='green', alpha=0.1)
#
# # 设置y轴范围
# plt.ylim(0, 120)
# 设置图形格式
plt.title('Daily high and low temperature 2014', fontsize=24)
plt.xlabel('', fontsize=16)
fig.autofmt_xdate() # 调用了fig.autofmt_xdate() 来绘制斜的日期标签
plt.ylabel("Temperature (F)", fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)
plt.show()
|
daff0f4fb75eb03820a742adb23e82d59879aaab | robingreig/raspi-git | /Python3/PWM/pwm-led01.py | 1,544 | 3.8125 | 4 | # MBTechWorks.com 2016
# Pulse Width Modulation (PWM) demo to cycle brightness of an LED
import RPi.GPIO as GPIO # Import the GPIO library.
import time # Import time library
GPIO.setmode(GPIO.BOARD) # Set Pi to use pin number when referencing GPIO pins.
# Can use GPIO.setmode(GPIO.BCM) instead to use
# Broadcom SOC channel names.
GPIO.setup(12, GPIO.OUT) # Set GPIO pin 12 to output mode.
pwm = GPIO.PWM(12, 100) # Initialize PWM on pwmPin 100Hz frequency
# main loop of program
print("\nPress Ctl C to quit \n") # Print blank line (\n == newline) before and after message.
dc=0 # set dc variable to 0 (will start PWM at 0% duty cycle)
pwm.start(dc) # Start PWM with 0% duty cycle
while True: # Create an infinite loop until Ctl C is pressed to stop program.
for dc in range(0, 101, 5): # Loop with dc set from 0 to 100 stepping dc up by 5 each loop
pwm.ChangeDutyCycle(dc)
time.sleep(0.05) # wait for .05 seconds at current LED brightness level
print(dc)
for dc in range(95, 0, -5): # Loop with dc set from 95 to 5 stepping dc down by 5 each loop
pwm.ChangeDutyCycle(dc)
time.sleep(0.05) # wait for .05 seconds at current LED brightness level
print(dc)
pwm.stop()
GPIO.cleanup() # resets GPIO ports used in this program back to input mode
|
a237d141c07d76a3e778504dbd573af19a3e8342 | karan-jagtap/udemy-python-course | /Section-5/lists.py | 377 | 4.0625 | 4 | x = 'abcd'
print(f'x: {x}')
y = ['a', 'b', 'c', 'd']
print(f'y: {y}')
y = ['a', 5, 'b', 5.7, 'c', 'd']
print(f'y: {y}')
print(len(y))
print(y[2])
print(y[-3])
# delete last item
print(y.pop())
print(y)
# add new item in the end
y.append(9)
print(y)
# remove item
y.remove('c')
print(y)
# all methods of list
print(dir(list))
# or
print(dir(x))
# delete list
del x
del y |
d9834f356be1d2269b853ff5941c8624e0c19282 | KristianHolme/theHardWay | /ex12.py | 182 | 4.03125 | 4 | age = input("What is your age?")
height = input("How tall are you?")
weight = input("How much do you Weigh?")
print(f"So, you are {age} old, {height} tall, and you weigh {weight}.") |
5770949912edf8bb7ba90a9a8b5cea38601da372 | alizenalabdeen/python1 | /functons.py | 200 | 3.625 | 4 | def mainas (number1,number2):
print (int(number1)-int (number2))
frst = input("frist number : ")
second = input ("second number : ")
print(".............................")
mainas(frst,second)
|
99359b2e151c66d931f86536c30fd78d1023a41d | taison2000/Python | /Examples/Change_Stuff_In_Other_file/file_2.py | 1,286 | 3.625 | 4 | #!C:\Python34\python.exe
#!/Python34/python
#!/usr/bin/python
# -*- coding: utf-8 -*-
## ----------------------------------------------------------------------------
"""
Python
~~~~~~~~~~~~~~~~~~~~~~
"""
import os
import time
import file_1
# -----------------------------------------------------------------------------
# Main program - This is the main function
# -----------------------------------------------------------------------------
def main():
"""
Change a variable in other file.
"""
print( "Print value from file_1.PrintValue()" )
file_1.PrintValue()
print(" Get value and print from here: ")
v = file_1.GetValue()
print( v )
print( "Set value to 12345" )
file_1.SetValue( 12345 )
print( "Print value from file_1.PrintValue()" )
file_1.PrintValue()
print(" Get value and print from here: ")
v = file_1.GetValue()
print( v )
return;
# -----------------------------------------------------------------------------
# Code entry
# -----------------------------------------------------------------------------
if __name__ == "__main__":
main()
"""
Note:
- No ++ or --, use a+=1 or a-=1
- print ("Variable %d", %Val)
print ("Variable %d %d", % (Val1, Val2))
"""
'''
3 single quote string
'''
|
af0c3f9fdd00913835810e26fc7d8470bae8d644 | xpansong/learn-python | /对象(2)/6. 特殊属性.py | 931 | 4.125 | 4 | print('--------------特殊方法和特殊属性------------------')
class A(object):
pass
class B:
pass
class C(A,B):
def __init__(self,name):
self.name=name
class D(A):
pass
x=C('张三')
print('------------------获得对象绑定的所有属性和方法------------------------')
print(x.__dir__()) #有特定参数,返回对象的所有有效的属性名
print(dir(x))
print(C.__dir__) #没有参数,返回局部作用域中的名称列表
print('------------------获得类和对象绑定的所有属性和方法的字典------------------')
print(x.__dict__)
print(C.__dict__)
print(C.__bases__)
print(C.__base__)
print(x.__class__)
print('-----------------------------')
print(dir(x))
print('-----------------------------')
class XXXXX:
def __init__(self, x):
self.x = x
def __add__(self, other):
return 2*(self.x + other.x)
a=XXXXX(10)
b=XXXXX(10)
print(a+b)
|
af0b1a032ad0bfcb71362334c0fb5e210f30231e | msksh/pythonBasic2 | /practice.py | 47,744 | 4.46875 | 4 | '''
station = "인천공항"
print(station+"행 열차가 들어오고있습니다.")
'''
'''
#연산자
print(1+1)#2
print(3-1)#2
print(2*5)#10
print(6/3)#2
print(2**3) #2^3=8
print(5%3) #나머지구하기 2
print(10%3) #1
print(5//3) #1
print(10//3) #3
print( 10 > 3) #True
print(4 >= 7)#False
print(10 < 3) #False
print(5 <= 5) #True
print(3 == 3)#true
print(4 == 2)#False
print(3+4 == 7) #True
print( 1!=3)#True
print(not(1!=3))#False
print((3>0) and (3<5)) #True
print((3>0)&(3<5)) #True
print((3>0) or (3<5)) #True
print((3>0)|(3<5)) #True
number = 2 + 3 *4 #14
print(number)
number = number + 2 #16
print(number)
number += 2 #18
print(number)
number *= 2 #36
print(number)
number /= 2 #18
print(number)
number -= 2 #16
print(number)
number %= 5 #1
print(number)
'''
'''
#숫자처리함수
print(abs(-5)) #5 절대값
print(pow(4, 2)) #4^2 = 4*4 =16 제곱
print(max(5, 12)) #12 최댓값
print(min(12, 5))#5 최솟값
print(round(3.14))#3 반올림
print(round(4.99))#5 반올림
from math import *
print(floor(4.99)) #내림. 4
print(ceil(3.14)) #올림 4
print(sqrt(16)) #루트 4
'''
'''
#랜덤함수
from random import *
#print(random()) # 0.0~1.0 미만의 임의의 값 생성
#print(int(random()*10)) #0~10미만의 임의의 값 int : 소수점 제외
#print(random()*10) #0.0~10.0미만의 임의의 값
#print(int(random()*10)+1) #1~10미만의 임의의 값
#print(int(random()*10)+1) #1~10미만의 임의의 값
#print(int(random()*10)+1) #1~10미만의 임의의 값
#print(int(random()*10)+1) #1~10미만의 임의의 값
#print(randrange(1, 46)) #1 ~ 45 미만의 임의의 값 생성
#print(randrange(1, 46)) #1 ~ 45 미만의 임의의 값 생성
#print(randrange(1, 46)) #1 ~ 45 미만의 임의의 값 생성
#print(randrange(1, 46)) #1 ~ 45 미만의 임의의 값 생성
#print(randrange(1, 46)) #1 ~ 45 미만의 임의의 값 생성
#print(randrange(1, 46)) #1 ~ 45 미만의 임의의 값 생성
print(randint(1, 45)) #1~45이하의 임의의값 생성
print(randint(1, 45)) #1~45이하의 임의의값 생성
print(randint(1, 45)) #1~45이하의 임의의값 생성
print(randint(1, 45)) #1~45이하의 임의의값 생성
print(randint(1, 45)) #1~45이하의 임의의값 생성
print(randint(1, 45)) #1~45이하의 임의의값 생성
'''
'''
#퀴즈 당신은 최근에 코딩 스터디 모임을 새로 만들었습니다. 월 4회 스터디를 하는데 3번은 온라인으로 하고 1번은 오프라인으로
#하기로 했습니다. 아래 조건에 맞는 오프라인 모임 날짜를 정해주는 프로그램을 작성하시오
#조건1 : 랜덤으로 날짜를 뽑아야함
#조건2 : 월별 날짜는 다름을 감안하여 최소 일수인 28 이내로 정함
#조건3 : 매월1~3일은 스터디 준비를 해야함으로 제외
#(출력문 예제)
#오프라인 스터디 모임 날짜는 매월 x일로 선정되었습니다.
from random import *
offlinestudy = randint(4,28)
print("오프라인 스터디 모임 날짜는 매월" ,offlinestudy,"일로 선정되었습니다.")
'''
#문자열
#sentence = '나느 소년입니다'
#print(sentence)
#sentence2 = "파이썬은 쉬워요"
#print(sentence2)
#sentence3 = '''
#나는 소년이고,
#파이썬은 쉬워요
#'''
#print(sentence3)
'''
#슬라이싱
jumin = "990120-1234567"
print("성별:" + jumin[7])
print("연:" + jumin[0:2]) # 0 부터 2 직전까지 (0,1)
print("월 : " + jumin[2:4])
print("일 :" + jumin[4:6])
print("생년월일 :" + jumin[:6]) #처음부터 6 직전까지
print("뒤 7자리:" + jumin[7:])
print("뒤 7자리 (뒤에서부터):" + jumin[-7:]) #맨 뒈엇 7번째 끝까지
'''
'''
#문자열 처리 함수
python = "Python is Amazing"
print(python.lower())
print(python.upper())
print(python[0].isupper())
print(len(python))
print(python.replace("Python","Java"))
index = python.index("n")
print(index)
index = python.index("n", index+1)
print(index)
print(python.find("Java"))
#print(python.index("Java"))
print("hi")
print(python.count("n"))
'''
#문자열 포멧
#방법1
#print("나는 %d살입니다." %20)
#print("나는 %s을 좋아해요." % "파이썬")
#print("Apple 은 %c로 시작해요." % "A")
# %s 각 출력을 할수 있다.
#print("나는 %s 살입니다." %20)
#print("나는 %s색과 %s색을 좋아해요" % ("파란","빨간"))
#방법2
#print("나는 {}살 입니다.".format(20))
#print("나는 {}색과 {}색을 좋아해요" .format("파란","빨간"))
#print("나는 {0}색과 {1}색을 좋아해요" .format("파란","빨간"))
#print("나는 {1}색과 {0}색을 좋아해요" .format("파란","빨간"))
#방법3
#print("나는 {age}살이며,{color}색을 좋아해요".format(age=20,color="빨간"))
#print("나는 {age}살이며,{color}색을 좋아해요".format(color="빨간",age=20))
#방법4
#age = 20
#color = "빨간"
#print(f"나는 {age}살이며,{color}색을 좋아해요")
#\n : 줄바꿈
#print("백문이 불여일견 \n 백견이 불여일타")
#\" \' : 문장 내에서 따옴표.
#저는 "나도코딩" 입니다.
#print('저는 "나도코딩" 입니다.')
#print("저는 \"나도코딩\" 입니다.")
# \\ : 문장내에서\
#print("C:\\Users\\kim\\Desktop\\PythonWorkSpace")
# \r : 커서를 맨 앞으로 이동 Apple : str 이동
#print("Red Apple\rPine")
# \b : 백스페이스 (한 글자 삭제)
#print("Redd\bApple")
# \t : 탭
#print("Red\tApple")
#Quiz)사이트별로 비밀번호를 만들어 주는 프로그램을 작성하시오
#예)http://naver.com
#규칙1 : http://부분은 제외 => naver.com
#규칙2 : 처음 만나는점(.)이후 부분은 제와 => naver
#규칙3 : 남는 글자중 처음 세자리 + 글자 갯수 + 글자 내 'e' 갯수 + "!"로 구성
#예)생성된 비밀번호: nav51!
#url = "http://naver.com"
#my_str = url.replace("http://","") #규칙1
#my_str = my_str[:my_str.index(".")] #규칙2
#my_syr[0:5]->0~5직전까지.(0,1,2,3,4)
#password =my_str[:3] + str(len(my_str)) + str(my_str.count("e")) + "!" #규칙3
#print("{0}의 비밀번호는 {1}입니다.".format(url,password))
#리스트[]
#지하철 칸별로 10명, 20명, 30명
#subway = [10 ,20 ,30]
#print(subway)
#subway = ["유재석", "조세호", "박명수"]
#print(subway)
#조세호씨가 몇 번째 칸에 타고 있는가?
#print(subway.index("조세호"))
#하하씨가 다음 정류장에서 다음 칸에 탐
#subway.append("하하")
#print(subway)
#정형돈씨를 유재석씨와 조세호씨 사이에
#subway.insert(1,"정형돈")
#print(subway)
# 지하철에 있는 사람을 한 명씩 뒤에서 꺼냄
#print(subway.pop())
#print(subway)
#print(subway.pop())
#print(subway)
#print(subway)
#print(subway.pop())
# 같은 이름의 사람이 몇 명 있는지 확인
#subway.append("유재석")
#print(subway)
#print(subway.count("유재석"))
# 정렬도 가능
# num_list = [5,2,4,3,1]
# num_list.sort()
# print(num_list)
# #순서 뒤집기 가능
# num_list.reverse()
# print(num_list)
#모두 지우기
# num_list.clear()
# print(num_list)
#다양한 자료형 함께 사용
#num_list=[5,2,4,3,1]
#mix_list=["조세호", 20 , True]
#print(mix_list)
#리스트 확장
#num_list.extend(mix_list)
#print(num_list)
#사전
# cabinet = {3:"유재석", 100:"김태호"}
# print(cabinet[3])
# print(cabinet[100])
# print(cabinet.get(3))
# print(cabinet[5])
# print(cabinet.get(5))
# print(cabinet.get(5, "사용 가능"))
# print("hi")
#print(3 in cabinet) #True
#print(5 in cabinet) #False
# cabinet = {"A-3":"유재석", "B-100":"김태호"}
# print(cabinet["A-3"])
# print(cabinet["B-100"])
# #새 손님
# print(cabinet)
# cabinet["A-3"] = "김종국"
# cabinet["C-20"] = "조세호"
# print(cabinet)
# #간 손님
# del cabinet["A-3"]
# print(cabinet)
# # key 들만 출력
# print(cabinet.keys())
# # value 들만 출력
# print(cabinet.values())
# # key, value 쌍으로 출력
# print(cabinet.items())
# #목욕탕 폐점
# cabinet.clear()
# print(cabinet)
# 튜플
# menu = ("돈까스", "치즈까스")
# print(menu[0])
# print(menu[1])
# name = "김종국"
# age = 20
# hobby = "코딩"
# print(name, age, hobby)
# (name , age, hobby) =( "김종국", 20, "코딩")
# print(name,age,hobby)
# 집합 (set)
# 중복 안됨, 순서없음
# my_set = {1,2,3,3,3}
# print(my_set)
# java = {"유재석", "김태호", "양세형"}
# python = set(["유재석", "박명수"])
# # 교집합(java와 python을 모두 할수 있는 개발자)
# print(java&python)
# print(java.intersection(python))
# #합집합(java 할 수 있거나 python 할 수 있는 개발자)
# print(java | python)
# print(java.union(python))
# #차집합(java는 할수 있지만python은 할 줄 모른느 개발자)
# print(java - python)
# print(java.difference(python))
# #python 할 줄 아는 사람이 늘어남
# python.add("김태호")
# print(python)
# # java를 잊었어요
# java.remove("김태호")
# print(java)
# 자료구조의 변경
# 커피숍
# menu = {"커피","우유","주스"}
# print(menu,type(menu))
# menu = list(menu)
# print(menu,type(menu))
# menu = tuple(menu)
# print(menu,type(menu))
# menu =set(menu)
# print(menu,type(menu))
# Quiz) 당신의 학교에서는 파이썬 코딩 대회를 주최합니다.
# 참석률을 높이기 위해 댓글 이벤트를 진행하기로 하였습니다.
# 댓글 작성자들 중에 추첨을 통해 1명은 치킨, 3명은 커피 쿠폰을 받게 됩니다.
# 추천 프로그램을 작성하시오.
# 조건1 : 편의상 댓글은 20명이 작성하였고 아이디는 1~20 이라고 가정
# 조건2 : 댓글 내용과 상관 없이 무작위로 추첨하되 중복불가
# 조건3: random 모듈의 shuffle과 sample 을 활용
# (출력 예제)
# --당첨자 발표--
# 치킨 당첨자 : 1
# 커피 당첨자 : [2, 3, 4]
# --축하합니다--
# (활용예제)
# from random import *
# lst = [1,2,3,4,5]
# print(lst)
# shuffle(lst)
# print(lst)
# print(sample(lst,1))
#내가한답 틀림 ㅠㅠ
# from random import *
# lst = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
# #print(lst)
# shuffle(lst)
# print(sample(lst,1))
#정답 ------------------
# from random import *
# users = range(1,21)
# users = list(users)
# #print(users)
# shuffle(users)
# winners = sample(users ,4) #4명 중에서 1명은 치킨, 3명은 커피
# print("--당첨자 발표--")
# print("치킨 당첨자 : {0}".format(winners[0]))
# print("커피 당첨자 : {0}".format(winners[1:]))
# print("--축하합니다--")
# #조건문
#날씨
# weather = input("오늘 날씨는 어때요? ")
# if weather == "비" or weather == "눈":
# print("우산을 챙기세요")
# elif weather == "미세먼지" :
# print("마스크를 챙기세요")
# else:
# print("준비물 필요 없어요.")
#기온
# temp = int(input("기온은 어때요? "))
# if 30 <= temp:
# print("너무 더워요. 나가지 마세요")
# elif 10 <= temp and temp < 30:
# print("괜찮은 날씨예요")
# elif 0 <= temp <10 :
# print("외투를 챙기세요")
# else:
# print("너무 추워요.나가지 마세요")
#반복문 for문
# for waiting_no in range(1,6): # 1,2, 3, 4, 5
# print("대기번호 : {0}".format(waiting_no))
# starbucks = ["아이언맨", "토르", "아이엠 그루트"]
# for customer in starbucks:
# print("{0},커피가 준비되었습니다.".format(customer))
#반목문 while문
# customer = "토르"
# index =5
# while index >= 1:
# print("{0},커피가 준비 되었습니다. {1} 번 남았어요".format(customer, index))
# index -= 1
# if index == 0:
# print("커피는 폐기처분되었습니다.")
#문한루프
# customer = "아이언맨"
# index = 1
# while True:
# print("{0},커피가 준비되었습니다.호출 {1} 되었습니다.".format(customer,index))
# index += 1
#조건이 충족됬을때 루프 탈출
# customer = "토르"
# person = "Unknown"
# while person != customer :
# print("{0},커피가 준비되었습니다.".format(customer))
# person = input("이름이 어떻게되세요? ")
#continue 는 밑에 문장을 실행하지 않고 계속 다음 문장을 실행 break는 바로 반복문을 끝냄
# absent = [2, 5] #결석
# no_book =[7]#책을 깜빡했음
# for student in range(1, 11): #1,2,3,4,5,6,7,8,9,10
# if student in absent:
# continue
# elif student in no_book:
# print("오늘 수업 여기까지.{0}는 교무실로 따라와".format(student))
# break
# print("{0},책을 읽어봐".format(student))
# 한 줄 for
#출석번호가 1 2 3 4 , 앞에 100을 붙이기로 함 -? 101, 102, 103, 104, 105
# students= [1,2,3,4,5]
# print(students)
# students = [i+100 for i in students]
# print(students)
# 학생 이름을 길이로 변화
# students = ["Iron man","Thor", "I am groot"]
# students = [len(i) for i in students] #len은 문자열의 길이를 설명함
# print(students)
#학생 이름을 대문자로 변환
# students = ["Iron man","Thor", "I am groot"]
# students = [i.upper() for i in students]
# print(students)
# Quiz) 당신은 Cocoa 서비스를 이요하는 택시 기사님입니다.
# 50명의 승객과 매칭 기회가 있을때, 총 탑승 승객 수를 구하는 프로그램을 작성하시요
# 조건1 : 승객별 운행소요 시간은 5분~50분 사이의 난수로 정해집니다.
# 조건2: 당신은 소요 시간 5분~15분 사이의 승객만 매칭해야 합니다.
# (출력문 예제)
# [o] 1번째 손님 (소요시간 :15분)
# [ ]2번째 손님 (소요시간 : 50분)
# [o]3번째 손님 (소요시간:5분)
# ...
# [ ] 50번째 손님 (소요시간 : 16분)
# 총 탑승승객 : 2분
# from random import *
# cnt = 0 #총 탑승 승객수
# for i in range(1,51): #1~50이라는 수(승객)
# time = randrange(5,51)
# if 5<= time <= 15: #5분 ~ 15분 이내의 손님(매칭성공), 탑승 승객 수 증가 처리
# print("[o]{0}번째 손님(소요시간 : {1}분)".format(i,time))
# cnt += 1
# else:#매칭 실패한 경우
# print("[ ]{0}번째 손님(소요시간 : {1}분)".format(i,time))
# print("총 탑승 승객 : {0}분".format(cnt))
#함수
# def open_account():
# print("새로운 계좌가 생성되었습니다.")
# def deposit(balance,money): #입금
# print("입금이 완료되었습니다. 잔액은 {0}원입니다.".format(balance+money))
# return balance + money
# def withdraw(balance, money): #출금
# if balance >= money: #잔액이 출금보다 많은면
# print("출금이 완료되었습니다.잔액은 {0} 원 입니다.".format(balance-money))
# return balance-money
# else:
# print("출금이 완료되지 않았습니다.잔액은 {0} 원 입니다.".format(balance))
# return balance
# def withdraw_night(balance, money): #저녁에 출금
# commission = 100 #수수료100원
# return commission, balance - money - commission
# balance = 0 #잔액
# balance = deposit(balance,1000)
# #balance = withdraw(balance, 500)
# commission, balance = withdraw_night(balance, 500)
# print("수수료 {0} 원이며, 잔액은 {1}원 입니다.".format(commission, balance))
# 함수 기본값
# def profile(name,age, main_lang):
# print("이름 : {0}\t나이 : {1}\t주 사용 언어{2}".format(name, age, main_lang))
# profile("유재석", 20, "파이썬")
# profile("김태호", 25, "자바")
#같은 학교 같은 학년 같은 반 같은 수업
# def profile(name, age=17, main_lang="파이썬"):
# print("이름 : {0}\t나이 : {1}\t주 사용 언어:{2}".format(name, age, main_lang))
# profile("유재석")
# profile("김태호")
# def profile(name,age, main_lang):
# print(name, age, main_lang)
# profile(name = "유재석", main_lang="파이썬", age=20)
# profile(main_lang="자바", age=25, name="김태호")
#가변인자
# def profile(name,age, lang1, lang2, lang3, lang4, lang5):
# print("이름 : {0}\t나이 : {1}\t".format(name, age), end=" ")
# print(lang1, lang2, lang3, lang4, lang5)
# def profile(name,age,*language):
# print("이름 : {0}\t나이 : {1}\t".format(name, age), end=" ")
# for lang in language:
# print(lang, end="")
# print()
# profile("유재석", 20, "python", "java", "c", "c++", "c#", "javascript")
# profile("김태호", 25, "kotlin", "swift")
#전역변수
# gun = 10
# def checkpoint(soldiers):
# global gun #전역 공간에 있는 gun사용
# gun = gun - soldiers
# print("[함수 내] 남은 총 : {0}".format(gun))
# def checkpoint_ret(gun, soldiers):
# gun = gun - soldiers
# print("[함수 내] 남은 총 : {0}".format(gun))
# return gun
# print("전체 총 : {0}".format(gun))
# #checkpoint(2)# 2명이 경계근무 나감
# gun = checkpoint_ret(gun,2)
# print("남은 총 : {0}".format(gun))
# Quiz) 표준 체중을 구하는 프로그램을 작성하시오
# *표준체중: 각 개인의 키에 적당한 체중
# (성별에 따른 공식)
# 남자 : 키(m) x 키(m) x 22
# 여자 : 키(m) x 키(m) x 21
# 조건1 : 표준 체중은 별도의 함수 내에서 계산
# *함수명 : std_weight
# *전달값 : 키(height), 성별(gender)
# 조건2 : 표준 체중은 소수점 둘째자리까지 표시
# (출력예제)
# 키 175cm 남자의 표준 체중은 67.38kg입니다.
#내답 (틀림)
# height = 100
# man = height*height*22
# girl = height*height*21
# def std_weight(height,gender):
# height = height /= 10
# return height, gender
# print("키{0}\t {1}의 표준체중은{2}입니다.".format(height,gender,std_weight))
# #정닶
# def std_weight(height,gender): #키는 m 단위 (실수), 성별 "남자"/"여자"
# if gender == "남자":
# return height * height * 22
# else :
# return height * height * 21
# height = 175 #cm단위
# gender = "남자"
# weight = round(std_weight(height / 100, gender),2)
# print("키 {0}cm {1}의 표준체중은 {2}kg입니다.".format(height, gender, weight))
#표준 입출력
# print("Python", "Java", sep=",", end="?") #end 는 문장의 끝부분을 ?로 바꾸어달라
# print("무엇이 더 재밌을까요?")
# import sys
# print("Python", "Java", file=sys.stdout) #표준출력으로 찍히는것 ->로그처리를 따로 할때 표준처리로 해서 크게상관없는데
# print("Python", "Java", file=sys.stderr) #에러 같은경우는 따로 로깅을 확인을해서 프로그램코드를 수정
#시험 성적
# scores = {"수학":0, "영어":50, "코딩":100}
# for subject, score in scores.items():
# # print(subject, score)
# print(subject.ljust(8), str(score).rjust(4), sep=":") #왼쪽으로정렬을 하는데 총 8칸의 공간을 확보 #score는 오른쪽4칸
#은행 대기순번표
#001,002,003,...
# for num in range(1,21):
# print("대기번호:" + str(num).zfill(3)) #zfill 뒤에 숫자만큼의 크기를 값을 0으로 채운다.
#표준입력
#answer = input("아무 값이나 입력하세요 : ")
# answer = 10
# print(type(answer))
#print("입력하신 값은 " +answer+ "입니다.") #!!주의 : 사용자 입력을 통해서 받게되면 항상 문자열 형태로 저장됨
# #다양한 출력 포멧
# #빈 자리는 빈공간으로 두고, 오른쪽 정렬을 하되, 총 10자리 공간을 확보
# print("{0: >10}".format(500))
# # 양수일때는 +표시 음수일때는 -로표시
# print("{0: >+10}".format(500))
# print("{0: >10}".format(-500))
# #왼쪽정렬을 하고 빈칸을 밑줄로 채우기
# print("{0:_<10}".format(500))
# # 3자리마다 콤마를 찍어주기
# print("{0:,}".format(100000000))
# # 3자리마다 코마를 찍어주기, +- 부호도 붙이기
# print("{0:+,}".format(100000000))
# print("{0:+,}".format(-100000000))
# # 3자리마다 콤마를 찍어주기,부호도 붙이고, 자릿수도 확보하고 #돈이 낳으면 행복하니 빈자리는^로 채우기
# print("{0:^<+30,}".format(100000000))
# #소수점 출력
# print("{0:f}".format(5/3))
# # 소수점을 특정 자리수 까지만 표시(소수점 3째자리에서 반올림)
# print("{0:.2f}".format(5/3))
#파일 입출력
#파일 쓰기
# score_file = open("score.txt", "w", encoding="utf=8")
# print("수학 : 0", file=score_file)
# print("영어 : 50", file=score_file)
# score_file.close()
#파일 덮어쓰기
# score_file = open("score.txt", "a", encoding="utf=8")
# score_file.write("과학 : 80")
# score_file.write("\n코딩 : 100")
# score_file.close()
#파일 읽기
# score_file = open("score.txt", "r", encoding="utf=8")
# print(score_file.read())
# score_file.close()
#파일 읽기2
# score_file = open("score.txt", "r", encoding="utf=8")
# print(score_file.readline(), end="") #줄별로 읽기, 한 줄 읽고 커서는 다음주로 이동
# print(score_file.readline(), end="")
# print(score_file.readline(), end="")
# print(score_file.readline(), end="")
# score_file.close()
#파일 읽기3
# score_file = open("score.txt", "r", encoding="utf=8")
# while True:
# line = score_file.readline()
# if not line:
# break
# print(line, end="")
# score_file.close()
#파일 읽기4
# score_file = open("score.txt", "r", encoding="utf=8")
# lines =score_file.readlines() #list 형태로 저장
# for line in lines:
# print(line, end="")
# score_file.close()
#pickle
# import pickle
# profile_file = open("profile.pickle","wb")
# profile = {"이름":"박병수", "나이":30, "취미":["축구", "골프", "코딩"]}
# print(profile)
# pickle.dump(profile, profile_file) #proflie에 있는 정보를 file에 저장
# profile_file.close()
# profile_file = open("profile.pickle","rb")
# profile = pickle.load(profile_file) #file에 있는 정보를 profile에 불러오기
# print(profile)
# profile_file.close()
#with - close가 필요없음
# import pickle
# with open("profile.pickle", "rb")as profile_file:
# print(pickle.load(profile_file))
#with 을 이용한 일반적인 파일생성
# with open("study.txt", "w", encoding="utf8") as study_file:
# study_file.write("파이썬을 열심히 공부하고 있어요")
# with open ("study.txt","r", encoding="utf8") as study_file:
# print(study_file.read())
# Quiz) 당신의 회사에서는 매주 1회 작성해야 하는 보고서가 있습니다.
# 보고서는 항상 아래와 같은 형태로 출력되어야합니다.
# -X 주차 주간보고-
# 부서 :
# 이름 :
# 업무 요약 :
# 1주차부터 50주차까지의 보고서 파일을 만드는 프로그램을 작성하시오.
# 조건 : 파일명은 '1주차.txt','2주차.txt',...와 같이 만듭니다.
#with open("i 주차.txt","w", encoding="utf8") as report_file:
# #내답 까비 거의다 맞았는데 ㅠㅠ
# for i in range(1,51):
# report_file = open("i 주차.txt", "w", encoding="utf=8")
# print("-i 주차 주간보고-", file=report_file)
# print("부서 : ", file=report_file)
# print("이름 : ", file=report_file)
# print("업무요약 : ", file=report_file)
# report_file.close()
#모범답안
# for i in range(1,51):
# with open(str(i) + "주차.txt", "w", encoding="utf8") as report_file:
# report_file.write("-{0} 주차 구간보고-".format(i))
# report_file.write("\n부서 :")
# report_file.write("\n이름 :")
# report_file.write("\n업무 요약 :")
#class <- 보통 붕어빵틀이라고 비유함 틀만 있으면 무한생산가능
# #마린 : 공격 유닛, 군인.총을 쓸 수 있음
# name="마린" #유닛의 이름
# hp = 40 #유닛의 체력
# damage = 5 #유닛의 공격력
# print("{0} 유닛이 생성되었습니다.".format(name))
# print("체력 {0}, 공격력 {1}\n".format(hp,damage))
# #탱크 : 공격 유닛, 탱크.포를 쏠 수 있는데, 일반모드/시즈모드.
# tank_name = "탱크"
# tank_hp = 150
# tank_damage = 35
# print("{0} 유닛이 생성되었습니다.".format(tank_name))
# print("체력 {0}, 공격력 {1}\n".format(tank_hp,tank_damage))
# def attack(nmae, location, damage):
# print("{0} : {1} 방향으로 적군을 공격 합니다.[공격력 {2}]".format(\
# name, location, damage))
# attack(name, "1시", damage)
# attack(tank_name, "1시", tank_damage)
# class Unit:
# def __init__(self, name, hp, damage):
# self.name = name
# self.hp = hp
# self.damage = damage
# print("{0} 유닛이 생성 되었습니다.".format(self.name))
# print("체력 {0}, 공격력 {1}".format(self.hp, self.damage))
# marine1 = Unit("마린", 40, 5)
# marine2 = Unit("마린", 40, 5)
# tank = Unit("탱크", 150, 35)
# #레이스 : 공중 유닛, 비행기.클로킹(상대에게 보이지 않음)
# wraith1 = Unit("레이스", 80, 5)
# print("유닛 이름 : {0}, 공격력 : {1}".format(wraith1.name, wraith1.damage))
# #마인드 컨트롤 : 상대방 유닛을 내 것으로 만드는 것 (빼앗음)
# wraith2 = Unit("레이스", 80, 5)
# wraith2.clocking = True
# if wraith2.clocking == True:
# print("{0} 는 현재 클로킹 상태입니다.".format(wraith2.name))
#메소드
# #일반 유닛
# class Unit:
# def __init__(self, name, hp): #damage):
# self.name = name
# self.hp = hp
# #self.damage = damage
# #print("{0} 유닛이 생성 되었습니다.".format(self.name))
# #print("체력 {0}, 공격력 {1}".format(self.hp, self.damage))
# #공격유닛
# class AttackUnit(Unit): #class AttackUnit 안에 Unit를 상속받음
# def __init__(self, name, hp, damage):
# # self.name = name
# # self.hp = hp
# Unit.__init__(self, name, hp)
# self.damage = damage
# def attack(self, location):
# print("{0} : {1} 방향으로 적군을 공격 합니다.[공격력 {2}]"\
# .format(self.name, location, self.damage))
# def damaged(self, damage):
# print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
# self.hp -= damage
# print("{0} : 현재 체력은 {1} 입니다.".format(self.name, self.hp))
# if self.hp <= 0:
# print("{0} : 파괴되었습니다.".format(self.name))
# #매딕 : 의무병
# #파이어뱃 : 공격 유닛, 화염방사기.
# firebat1 = AttackUnit("파이어뱃", 50, 16)
# firebat1.attack("5시")
# #공격 2번 받는다고 가정
# firebat1.damaged(25)
# firebat1.damaged(25)
#다중상속
# #일반 유닛
# class Unit:
# def __init__(self, name, hp): #damage):
# self.name = name
# self.hp = hp
# #self.damage = damage
# #print("{0} 유닛이 생성 되었습니다.".format(self.name))
# #print("체력 {0}, 공격력 {1}".format(self.hp, self.damage))
# #공격유닛
# class AttackUnit(Unit):
# def __init__(self, name, hp, damage):
# # self.name = name
# # self.hp = hp
# Unit.__init__(self, name, hp)
# self.damage = damage
# def attack(self, location):
# print("{0} : {1} 방향으로 적군을 공격 합니다.[공격력 {2}]"\
# .format(self.name, location, self.damage))
# def damaged(self, damage):
# print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
# self.hp -= damage
# print("{0} : 현재 체력은 {1} 입니다.".format(self.name, self.hp))
# if self.hp <= 0:
# print("{0} : 파괴되었습니다.".format(self.name))
# # 드랍쉽 : 공중유닛, 수송기. 마린/파이엇뱃/탱크 등을 수송 공격불가
# # 날 수 있는 기능을 가진 클래스
# class Flyable:
# def __init__(self, flying_speed):
# self.flying_speed = flying_speed
# def fly(self, name, location):
# print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]"\
# .format(name, location, self.flying_speed))
# #공중 공격 유닛 클래스
# class FlyableAttackUnit(AttackUnit, Flyable): #다중상속함
# def __init__(self, name, hp, damage, flying_speed):
# AttackUnit.__init__(self, name, hp, damage)
# Flyable.__init__(self, flying_speed)
# #발키리 : 공중 공격유닛. 한번에 14발 미사일 발사.
# valkyrie = FlyableAttackUnit("발키리", 200, 6, 5)
# valkyrie.fly(valkyrie.name, "3시")
# #메소드 오버라이딩
# #일반 유닛
# class Unit:
# def __init__(self, name, hp, speed): #damage):
# self.name = name
# self.hp = hp
# self.speed = speed
# def move(self, location):
# print("[지상 유닛 이동]")
# print("{0} : {1} 방향으로 이동합니다.[속도 {2}]".format(self.name, location, self.speed))
# #self.damage = damage
# #print("{0} 유닛이 생성 되었습니다.".format(self.name))
# #print("체력 {0}, 공격력 {1}".format(self.hp, self.damage))
# #공격유닛
# class AttackUnit(Unit):
# def __init__(self, name, hp, speed, damage):
# # self.name = name
# # self.hp = hp
# Unit.__init__(self, name, hp, speed)
# self.damage = damage
# def attack(self, location):
# print("{0} : {1} 방향으로 적군을 공격 합니다.[공격력 {2}]"\
# .format(self.name, location, self.damage))
# def damaged(self, damage):
# print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
# self.hp -= damage
# print("{0} : 현재 체력은 {1} 입니다.".format(self.name, self.hp))
# if self.hp <= 0:
# print("{0} : 파괴되었습니다.".format(self.name))
# # 드랍쉽 : 공중유닛, 수송기. 마린/파이엇뱃/탱크 등을 수송 공격불가
# # 날 수 있는 기능을 가진 클래스
# class Flyable:
# def __init__(self, flying_speed):
# self.flying_speed = flying_speed
# def fly(self, name, location):
# print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]"\
# .format(name, location, self.flying_speed))
# #공중 공격 유닛 클래스
# class FlyableAttackUnit(AttackUnit, Flyable): #다중상속함
# def __init__(self, name, hp, damage, flying_speed):
# AttackUnit.__init__(self, name, hp, 0, damage) #지상 스피드는 0으로처리
# Flyable.__init__(self, flying_speed)
# def move(self, location):
# print("[공중유닛이동]")
# self.fly(self.name, location)
# #pass
# #건물
# class BuildingUnit(Unit):
# def __init__(self, name, hp, location):
# # Unit.__init__(self, name, hp , 0)
# super().__init__(name, hp, 0)
# self.location = location
# #스타크래프트
# from random import *
# #일반 유닛
# class Unit:
# def __init__(self, name, hp, speed): #damage):
# self.name = name
# self.hp = hp
# self.speed = speed
# print("{0} 유닛이 생성되었습니다.".format(name))
# def move(self, location):
# print("{0} : {1} 방향으로 이동합니다.[속도 {2}]".format(self.name, location, self.speed))
# #self.damage = damage
# #print("{0} 유닛이 생성 되었습니다.".format(self.name))
# #print("체력 {0}, 공격력 {1}".format(self.hp, self.damage))
# def damaged(self, damage):
# print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
# self.hp -= damage
# print("{0} : 현재 체력은 {1} 입니다.".format(self.name, self.hp))
# if self.hp <= 0:
# print("{0} : 파괴되었습니다.".format(self.name))
# #공격유닛
# class AttackUnit(Unit):
# def __init__(self, name, hp, speed, damage):
# # self.name = name
# # self.hp = hp
# Unit.__init__(self, name, hp, speed)
# self.damage = damage
# def attack(self, location):
# print("{0} : {1} 방향으로 적군을 공격 합니다.[공격력 {2}]"\
# .format(self.name, location, self.damage))
# #마린
# class Marine(AttackUnit):
# def __init__(self):
# AttackUnit.__init__(self, "마린", 40, 1, 5)
# #스팀팩 : 일정 시간 동안 이동 및 공격 속도를 증가, 체력10감소
# def stimpack(self):
# if self.hp > 10:
# self.hp -= 10
# print("{0} : 스팀팩을 사용합니다.(HP 10 감소)".format(self.name))
# else:
# print("{0} : 체력이 부족하여 스팀팩을 사용하지 않습니다.".format(self.name))
# #탱크
# class Tank(AttackUnit):
# #시즈모드 : 탱크를 지상에 고정시켜, 더높은 파워로 공격 가능. 이동불가
# seize_developed = False #시즈모드 개발여부
# def __init__(self):
# AttackUnit.__init__(self, "탱크", 150, 1, 35)
# self.seize_mode = False
# def set_seize_mode(self):
# if Tank.seize_developed == False:
# return
# #현재 시즈모드가 아닐때 -> 시즈모드
# if self.seize_mode == False:
# print("{0} : 시즈모드로 전환합니다.".format(self.name))
# self.damage *= 2
# self.seize_mode = True
# #현재 시즈모드일 -> 시즈모드 해제
# else:
# print("{0} : 시즈모드를 해제합니다.".format(self.name))
# self.damage /= 2
# self.seize_mode = False
# # 드랍쉽 : 공중유닛, 수송기. 마린/파이엇뱃/탱크 등을 수송 공격불가
# # 날 수 있는 기능을 가진 클래스
# class Flyable:
# def __init__(self, flying_speed):
# self.flying_speed = flying_speed
# def fly(self, name, location):
# print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]"\
# .format(name, location, self.flying_speed))
# #공중 공격 유닛 클래스
# class FlyableAttackUnit(AttackUnit, Flyable): #다중상속함
# def __init__(self, name, hp, damage, flying_speed):
# AttackUnit.__init__(self, name, hp, 0, damage) #지상 스피드는 0으로처리
# Flyable.__init__(self, flying_speed)
# def move(self, location):
# self.fly(self.name, location)
# #레이스
# class Wraith(FlyableAttackUnit):
# def __init__(self):
# FlyableAttackUnit.__init__(self, "레이스", 80, 20, 5)
# self.clocked = False #클로킹 모드 (해체 상태)
# def clocking(self):
# if self.clocked == True: #클로킹 모드 -> 모드 해제
# print("{0} : 클로킹 코드 해제합니다.".format(self.name))
# self.clocked = False
# else: #클로킹 모드 해제 -> 모드 설정
# print("{0} : 클로킹 코드 설정합니다.".format(self.name))
# self.clocked = False
# def game_start():
# print("[알림] 새로운 게임을 시작합니다")
# def game_over():
# print("Player : gg")#goodgame
# print("[Player] 님이 게임에서 퇴장하셨습니다.")
# # 실제 게임 진행
# game_start()
# #마린 3기 생성
# m1 = Marine()
# m2 = Marine()
# m3 = Marine()
# #탱크 2기 생성
# t1 = Tank()
# t2 = Tank()
# #레이스 1기 생성
# w1 = Wraith()
# #유닛 일괄 관리(생성된 모든 유닛 append)
# attack_units = []
# attack_units.append(m1)
# attack_units.append(m2)
# attack_units.append(m3)
# attack_units.append(t1)
# attack_units.append(t2)
# attack_units.append(w1)
# # 전군 이동
# for unit in attack_units:
# unit.move("1시")
# #탱크 시즈몯 개발
# Tank.seize_developed = True
# print("[알림] 탱크 시즈 모드 개발이 완료되었습니다.")
# # 공격 모드 준비 ( 마린: 스팀팩, 탱크: 시즈모드, 레이스:클로킹)
# for unit in attack_units:
# if isinstance(unit, Marine):
# unit.stimpack()
# elif isinstance(unit,Tank):
# unit.set_seize_mode()
# elif isinstance(unit, Wraith):
# unit.clocking()
# #전군 공격
# for unit in attack_units:
# unit.attack("1시")
# #전군 피해
# for unit in attack_units:
# unit.damaged(randint(5 ,20)) # 공격은 랜덤으로 받음 (5~20)
# #게임 종료
# game_over()
# Quiz) 주어진 코드를 활용하여 부동산 프로그램을 작성하시오
# (출력예제)
# 총 3대의 매물이 있습니다.
# 강남 아파트 매매 10억 2010년
# 마포 오피스텔 전세 5억 2007년
# 송파 빌라 월세 500/50 2000년
# [코드]
# class House:
# #매물초기화
# def __init__(self, location, house_type, deal_type, price, completion_year):
# self.location = location
# self.house_type = house_type
# self.deal_type = deal_type
# self.price = price
# self.completion_year = completion_year
# #매물 정보 표시
# def show_detail(self):
# print(self.location, self.house_type, self.deal_type, self.price, self.completion_year)
# houses = []
# house1 = House("강남", "아파트", "매매", "10억", "2010년")
# house2 = House("마포", "오피스텔", "전세", "5억", "2007년")
# house3 = House("송파", "빌라", "월세", "500/50", "2000년")
# houses.append(house1)
# houses.append(house2)
# houses.append(house3)
# print("총 {0}대의 매물이 있습니다.".format(len(houses)))
# for house in houses:
# house.show_detail()
#예외처리
# try:
# print("나누기 전용 계산기 입니다.")
# nums = []
# nums.append(int(input("첫 번째 숫자를 입력하세요 : ")))
# nums.append(int(input("두 번째 숫자를 입력하세요 : ")))
# # nums.append(int(nums[0] / nums[1]))
# print("{0} / {1} = {2}".format(nums[0], nums[1], nums[2]))
# # num1 = int(input("첫 번째 숫자를 입력하세요 : "))
# # num2 = int(input("두 번째 숫자를 입력하세요 : "))
# #print("{0} / {1} = {2}".format(num1, num2 ,int(num1/num2)))
# except ValueError:
# print("에러! 잘못된 값을 입력하였습니다.")
# except ZeroDivisionError as err:
# print(err)
# except Exception as err:
# print("알 수 없는 에러가 발생하였습니다.")
# print(err)
# 에러 발생시키기
# try:
# print("한 자리 숫자 나누기 전용 계산기입니다.")
# num1 = int(input("첫 번째 숫자를 입력하세요 : "))
# num2 = int(input("두 번째 숫자를 입력하세요 : "))
# if num1 >= 10 or num2 >= 10:
# raise ValueError
# print("{0} / {1} = {2}".format(num1, num2, int(num1 / num2)))
# except ValueError:
# print("잘못된 값을 입력하였습니다. 한 자리 숫자만 입력하세요.")
# #사용자 정의 예외처리
# class BigNumberError(Exception):
# def __init__(self,msg):
# self.msg = msg
# def __str__(self):
# return self.msg
# try:
# print("한 자리 숫자 나누기 전용 계산기입니다.")
# num1 = int(input("첫 번째 숫자를 입력하세요 : "))
# num2 = int(input("두 번째 숫자를 입력하세요 : "))
# if num1 >= 10 or num2 >= 10:
# raise BigNumberError("입력값 :{0}, {1}".format(num1, num2))
# print("{0} / {1} = {2}".format(num1, num2, int(num1 / num2)))
# except ValueError:
# print("잘못된 값을 입력하였습니다. 한 자리 숫자만 입력하세요.")
# except BigNumberError as err:
# print("에러가 발생하였습니다. 한 자리 숫자만 입력하세요.")
# print(err)
# #finally
# class BigNumberError(Exception):
# def __init__(self,msg):
# self.msg = msg
# def __str__(self):
# return self.msg
# try:
# print("한 자리 숫자 나누기 전용 계산기입니다.")
# num1 = int(input("첫 번째 숫자를 입력하세요 : "))
# num2 = int(input("두 번째 숫자를 입력하세요 : "))
# if num1 >= 10 or num2 >= 10:
# raise BigNumberError("입력값 :{0}, {1}".format(num1, num2))
# print("{0} / {1} = {2}".format(num1, num2, int(num1 / num2)))
# except ValueError:
# print("잘못된 값을 입력하였습니다. 한 자리 숫자만 입력하세요.")
# except BigNumberError as err:
# print("에러가 발생하였습니다. 한 자리 숫자만 입력하세요.")
# print(err)
# finally:
# print("계산기를 이용해 주셔서 감사합니다.")
# Quiz) 동네에 항상 대기 손님이 있는 맛있는 치킨집이 있습니다.
# 대기 손님의 치킨 요리 시간을 줄이고자 자동 주문 시스템을 제작하였습니다.
# 시스템 코드를 확인하고 적절한 예외처리 구문을 넣으시오.
# 조건1 : 1보다 작거나 숫자가 아닌 입력값이 들어올때는 ValueError로 처리
# 출력 메세지 : "잘못된 값을 입력하였습니다."
# 조건2 : 대기 손님이 주문할 수 있는 총 치킨량은 10마리로 한정
# 치킨 소진 시 사용자 정의 에러[SoldOutError]를 발생키기고 프로그램 종료
# 출력 메세지 : "재고가 소진되어 더 이상 주문을 받지 않습니다."
# [코드]
#내답
# class SoldOutError(Exception):
# def __init__(self,msg):
# self.msg = msg
# def __str__(self):
# return self.msg
# chicken = 10
# waiting = 1 # 홀 안에는 현재 만석, 대기번호 1부터 시작
# # try :
# while(True):
# print("[남은 치킨 : {0}]".format(chicken))
# order = int(input("치킨 몇 마리 주문하시겠습니까?"))
# if order > chicken : #남은 치킨보다 주문량이 많을때
# raise ValueError
# raise SoldOutError("남은 치킨 : {0}, 주문 할수 있는 치킨{1}".format(chicken, order))
# print("재료가 부족합니다.")
# else:
# print("[대기번호 {0}] {1} 마리 주문이 완료되었습니다.".format(waiting, order))
# waiting += 1
# chicken -= order
# except ValueError:
# print("잘못된 값을 입력하였습니다.")
# except SoldOutError as err:
# print("재고가 소진되어 더 이상 주문을 받지 않습니다.")
# print(err)
#모법답안
# class SoldOutError(Exception):
# pass
# chicken = 10
# waiting = 1 # 홀 안에는 현재 만석, 대기번호 1부터 시작
# while(True):
# try:
# print("[남은 치킨 : {0}]".format(chicken))
# order = int(input("치킨 몇 마리 주문하시겠습니까?"))
# if order > chicken : #남은 치킨보다 주문량이 많을때
# print("재료가 부족합니다.")
# elif order <= 0:
# raise ValueError
# else:
# print("[대기번호 {0}] {1} 마리 주문이 완료되었습니다.".format(waiting, order))
# waiting += 1
# chicken -= order
# if chicken == 0:
# raise SoldOutError
# except ValueError:
# print("잘못된 값을 입력하였습니다.")
# except SoldOutError:
# print("재고가 소진되어 더 이상 주문을 받지 않습니다.")
# break
#모듈
# import theater_module
# theater_module.price(3) #3명이서 영화 보러 갔을때 가격
# theater_module.price_morning(4) #4명이서 조조 할인 영화 보러 갔을 때
# theater_module.price_soldier(5) #5명의 군인이 여화 보러 갔을때
# import theater_module as mv
# mv.price(3)
# mv.price_morning(4)
# mv.price_soldier(5)
# from theater_module import *
# # from random import *
# price(3)
# price_morning(4)
# price_soldier(5)
# from theater_module import price, price_morning
# price(5)
# price_morning(6)
# price_soldier(7)
# from theater_module import price_soldier as price #theater_module에서 price_soldier를 price라고 할꺼야 라고 하는거
# price(5)
#패키지
# import travel.thailland
# trip_to = travel.thailland.TaillandPackage()
# trip_to.detail()
# from travel.thailand import ThailandPackage
# trip_to = ThailandPackage()
# trip_to.detail()
# from travel import vietnam
# trip_to = vietnam.VitenamPackage()
# trip_to.detail()
#__all__
# # from random import *
# from travel import *
# #trip_to = vietnam.VitenamPackage()
# trip_to = thailand.ThailandPackage()
# trip_to.detail()
#모듈 직접 실행
# # from random import *
#from travel import *
# #trip_to = vietnam.VitenamPackage()
# trip_to = thailand.ThailandPackage()
# trip_to.detail()
# import inspect
# import random
# print(inspect.getfile(random))
# print(inspect.getfile(thailand))
# pip install
# from bs4 import BeautifulSoup
# soup = BeautifulSoup("<p>Some<b>bad<i>HTML")
# print(soup.prettify())
#내장함수
#input : 사용자 입력을 받는 함수
# language = input("무슨 언어를 좋아하세요?")
# print("{0}은 아주 좋은 언어입니다.".format(language))
# dir : 어떤 객체를 넘겨줬을때 그 객체가 어떤 변수와 함수를 가지고 있는지 표시
#print(dir())
#import random # 외장함수
#print(dir())
#import pickle
#print(dir(random))
# lst = [1, 2, 3]
# print(dir(lst))
# name = "Jim"
# print(dir(name))
#외장함수
# glob :경로내의 폴더/ 파일 목록 조회 (윈도우dir)
# import glob
# print(glob.glob("*.py")) #확장자가 py 인 모든파일
# os : 운영체제에서 제공하는 기본 기능
# import os
# print(os.getcwd()) #현재 디렉토리
# folder = "sample_dir"
# if os.path.exists(folder):
# print("이미 존재하는 폴더입니다.")
# os.rmdir(folder)
# print(folder,"폴더를 삭제하였습니다.")
# else:
# os.makedirs(folder) #폴더생성
# print(folder, "폴더를 생성하였습니다.")
# time : 시간 관련 함수
#import time
# print(time.localtime())
# print(time.strftime("%Y-%m-%d %H:%M:%S"))
# import datetime
# # print("오늘 날짜는", datetime.date.today())
# #timedelta : 두 날짜 사이의 간격
# today = datetime.date.today() #오늘 날짜 저장
# td = datetime.timedelta(days=100) #100일 저장
# print("우리가 만난지 100일은", today + td) #오늘 부터 100일 후
# Quiz)프로젝트 내에 나만의 시그니처를 남기는 모듈을 만드시오
# 조건: 모듈 파일명은 byme.py 로 작성하시오
# (모듈 사용 예제)
import byme
byme.sign()
# (출력 예제)
# 이 프로그램은 성훈이에 의해 만들어졌습니다.
# 유튜브 : http://youtube.com
# 이메일 : fangbe@naver.com
|
6d81fdf2566623fbd25defcdc4d1030bf528afc2 | Stephen-Kamau/july_work | /form_entry_GUI_app/form_entry.py | 833 | 3.5 | 4 | import tkinter as tk
from tkinter import ttk
app = tk.Tk()
class LabelInput(tk.Frame):
'''A frame containing labels and input'''
def __init__(self,label='',input_class=ttk.Entry,input_var=None,input_args=None,label_args=None,**kwargs):
super.__init__(parent,**kwargs)
input_args=input_args or {}
label_args=input_var or {}
self.variable=input_var
if input_class in (ttk.Checkbutton,ttk.Button,ttk.Radioibutton):
input_args["text"]=label
input_args["variable"]=input_var
else:
self.label = ttk.Label(self, text=label, **label_args)
self.label.grid(row=0, column=0, sticky=(tk.W + tk.E))
input_args["textvariable"] = input_var
self.input = input_class(self, **input_args)
self.input.grid(row=1, column=0, sticky=(tk.W + tk.E))
columnconfigure(0,weight=)
app.mainloop() |
b96b2965229dc167df01f0e272d221a9a9b0f5fb | zaeyon/algorithm-source-code | /20201121/baekjoon5543.py | 312 | 3.8125 | 4 | import sys
minHam = 0
minBev = 0
for i in range(3):
price = int(input())
if(i == 0): minHam = price
if minHam > price:
minHam = price
for i in range(2):
price2 = int(input())
if(i == 0): minBev = price2
if minBev > price2:
minBev = price2
print(minHam+minBev-50)
|
51cdf72aa32c23835e67dfd7fa862c5fb9bb6d17 | MustafaSaber/Genetic-Algorithms | /fuzzy_logic/variable.py | 254 | 3.515625 | 4 | class Variable:
def __init__(self, name, value, sets=[]):
self.name = name
self.value = value
self.sets = sets
def __str__(self):
return '(' + str(self.name) + ', ' + str(self.value) + ', ' + str(self.sets) + ')'
|
a742e98c86e6c38f4e5b0c2089f652d9e215c6a5 | NikhilGupta1997/Machine_Learning_Models | /Linear Regression/Linear_Regression.py | 4,266 | 3.5 | 4 | '''
=================
Linear Regression
=================
'''
from mpl_toolkits.mplot3d import axes3d
import numpy as np
import matplotlib.pyplot as plt
import math
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.animation as animation
import time
# Global variables
iteration = 0
LearningRate = 2.5
Epsilon = 1e-25
Saved_Theta = []
''' This provides the analytical solution '''
def analytical_solution(X, Y):
return np.linalg.inv(X.T * X) * X.T * Y
''' To Read the X values '''
def Xread():
return np.matrix([map(float, line.strip().split()) for line in open('x.dat')])
''' To Read the Y values '''
def Yread():
return np.matrix([[float(line.strip())] for line in open('y.dat')])
''' To create a theta vector based on dimension of input '''
def initialize_theta(x):
return np.matrix([[float(0)]] * (x))
''' Returns the value of J(theta) '''
def create_J(X, Y, Theta):
return ((Y - X * Theta).T * (Y - X * Theta) / (2*X.shape[0])).item(0)
''' Returns the gradient of J(theta) '''
def create_gradJ(X, Y, Theta):
return X.T * (X * Theta - Y) / X.shape[0]
''' The Gradient Descent Algorithm '''
def gradient_descent(X, Y):
global iteration
global LearningRate
global Saved_Theta
Theta = initialize_theta(X.shape[1])
J = create_J(X, Y, Theta)
Saved_Theta.append([item for sublist in Theta.tolist() for item in sublist] + [J])
while(True):
print LearningRate
iteration += 1;
gradJ = create_gradJ(X, Y, Theta)
newTheta = Theta - LearningRate * gradJ
newJ = create_J(X, Y, newTheta)
if math.fabs(J - newJ) < Epsilon: # Value has converged
break
elif newJ > J: # Overshoot condition
if iteration > 8:
break
else: # Normal Gradient Descent
LearningRate *= 1.0001
Theta = newTheta
J = newJ
Saved_Theta.append([item for sublist in Theta.tolist() for item in sublist] + [J])
return Theta
''' Equation of the hypothesis function '''
def linear(Theta, x):
return (Theta.item(1) * x) + Theta.item(0)
# Read input values
X = Xread()
Y = Yread()
# Normalize
X_mean = np.mean(X, axis=0)
X_std = np.std(X, axis=0)
X = (X - X_mean)/X_std
X = np.c_[np.ones((X.shape[0], 1)), X]
# Perform Gradient Descent
FinalTheta = gradient_descent(X, Y)
# Print Output
print 'Analytical Solution\n', analytical_solution(X,Y)
print 'Gradient Decent Solution\n', FinalTheta
print 'Iterations used = ', iteration
### 2D plot of the hypothesis function ###
X_plot = [item[1] for item in X.tolist()]
Y_plot = [item[0] for item in Y.tolist()]
x = np.arange(min(X_plot)-1, max(X_plot)+1, 0.1)
# Plot
plt.plot(X_plot, Y_plot, 'ro')
plt.plot(x, linear(FinalTheta, x))
plt.axis([min(X_plot)-0.2, max(X_plot)+0.2, min(Y_plot)-0.2, max(Y_plot)+0.2])
# Label
plt.ylabel('Prices')
plt.xlabel('Area')
plt.title('House Prices')
plt.show()
### 3D plot of the J(theta) function ###
# Returns the value of J(theta)
def create_J_plot(Theta_0, Theta_1):
Theta = np.matrix([[Theta_0],[Theta_1]])
return ((Y - X * Theta).T * (Y - X * Theta) / (2*X.shape[0])).item(0)
# Create 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_zlim(-100, 200)
# Plot the 3D curve
A = []; B = []; C = []
theta_0_plot = np.arange(-15, 20, 0.5)
theta_1_plot = np.arange(-15, 20, 0.5)
theta_0_plot, theta_1_plot = np.meshgrid(theta_0_plot, theta_1_plot)
Z = np.vectorize(create_J_plot)(theta_0_plot, theta_1_plot)
ax.plot_surface(theta_0_plot, theta_1_plot, Z, rstride=1, cstride=1, alpha=0.3, linewidth=0.1, cmap=cm.coolwarm)
# Animation
for line in Saved_Theta:
# Plot the new wireframe and pause briefly before continuing
A.append(line[0]); B.append(line[1]); C.append(line[2])
wframe = ax.plot_wireframe(A, B, C, rstride=1, cstride=1)
point = ax.plot([line[0]],[line[1]],[line[2]], 'ro')
plt.pause(.02)
# Draw Contours
A = []; B = []; C = []
cont = plt.figure()
CS = plt.contour(theta_0_plot, theta_1_plot, Z)
plt.title('Contour Plot Showing Gradient Descent')
# Animation
for line in Saved_Theta:
# Plot the new wireframe and pause briefly before continuing
A.append(line[0]); B.append(line[1]); C.append(line[2])
point = plt.plot([line[0]],[line[1]], 'ro')
point = plt.plot(A,B)
plt.pause(.02)
plt.show() |
6de148ca131198ec2431d117b51ccde8bf781efa | CescWang1991/LeetCode-Python | /simulation/MerchantsBank/SelectNumbersInterval.py | 1,520 | 3.5 | 4 | # 挑选代表
# 我们有很多区域,每个区域都是从a到b的闭区间,现在我们要从每个区间中挑选至少2个数,那么最少挑选多少个?
# 输入描述:
# 第一行是N(N<10000),表示有N个区间,之间可以重复
# 然后每一行是ai,bi,持续N行,表示现在区间。均小于100000
# 输出描述:
# 输出一个数,代表最少选取数量。
# 解题思路:
# 贪心,按右端点排序(左端点一样可以),如果每个区间至少一个点,那么这个点一定是在右端点,这样子可以让后续的区间更容
# 易覆盖到这个点,从而减少选点的数量;同理,如果每个区间至少两个点,那个这个两个点一定也在右端点和右端点前一个点,原因是一样的。
# 答案正确:恭喜!您提交的程序通过了所有的测试用例
def minNumbers(intervals):
intervals.sort(key=lambda x:x[1], reverse=False)
nums = []
for i in range(len(intervals)):
if not nums or intervals[i][0] > nums[-1]:
nums.append(intervals[i][1]-1)
nums.append(intervals[i][1])
elif intervals[i][0] == nums[-1]:
nums.append(intervals[i][1])
return len(nums)
while True:
try:
n = int(input())
intervals = []
for i in range(n):
line = input().split(" ")
a = int(line[0])
b = int(line[1])
intervals.append([a, b])
print(minNumbers(intervals))
except:
break |
6cef77bacbd50915b59e5109f588d3de0414c57a | bn-d/project_euler | /000-100/025/main.py | 295 | 3.5 | 4 | #!/usr/bin/env python3
import math
if __name__ == '__main__':
digit = 1000
cur = 1
pre = 1
indx = 2
while True:
if math.log10(cur) >= digit - 1:
print(indx)
break
cur = cur + pre
pre = cur - pre
indx += 1
|
e9674b28788a86b19b31d580205339517b9752d6 | gabriellaec/desoft-analise-exercicios | /backup/user_009/ch27_2019_08_17_02_55_04_532945.py | 66 | 3.546875 | 4 | c = int(input('c: '))
a = int(input('a: '))
print(c*a*10*365/1440) |
8a824549e12cf18fb59da9ab426bbbc6462c8167 | qionouwens/TicTacToe | /main.py | 3,207 | 4.09375 | 4 | from Board_class import Board
from ai import *
def player_turn():
print("What do you play?")
has_played = False
while not has_played:
# TODO implement try_except block if user does not input an integer
play_cell = int(input())
if playing_board.turn(play_cell-1):
has_played = True
else:
print('That square was already taken please choose a new square')
playing_board.print_board()
return playing_board.is_winner()
def computer_turn(which_ai):
play_cell = which_ai(playing_board)
playing_board.turn(play_cell)
playing_board.print_board()
return playing_board.is_winner()
if __name__ == "__main__":
playing_board = Board()
print("How do you want to play")
print("1. Player vs Player")
print("2. Player vs Computer")
print("3. Computer vs Computer")
game_mode = input("I want to play number ")
# Player vs Player
if game_mode == "1":
player1 = input("What is the name of player 1? ")
player2 = input("What is the name of player 2? ")
winner = ""
while winner == "":
if playing_board.whose_turn == playing_board.ex:
print(f"it is {player1}'s turn")
else:
print(f"it is {player2}'s turn")
winner = player_turn()
if winner == playing_board.ex:
print(f"Congratulations {player1}! You have won!")
elif winner == playing_board.o:
print(f"Congratulations {player2}! You have won!")
else:
print("It is a draw!")
# Player vs Computer
if game_mode == "2":
print("Which Computer Ai do you want to use")
for i in range(len(ai_types)):
print(f"{i+1}. {ai_type_string[i]}")
ai_choice = ai_types[int(input())-1]
turn_choice = input("Do you want to go first or second (f or s)? ")
first_turn = "computer"
second_turn = "player"
if turn_choice == 'f':
first_turn = "player"
second_turn = "computer"
winner = ''
while winner == '':
turn = second_turn
if playing_board.whose_turn == playing_board.ex:
turn = first_turn
if turn == "computer":
winner = computer_turn(ai_choice)
else:
winner = player_turn()
if winner == playing_board.ex:
print(f"{first_turn} is the victor")
else:
print(f"{second_turn} is the victor")
# Computer vs Computer
if game_mode == "3":
print("Which Computer Ai do you want to use for the first computer")
for i in range(len(ai_types)):
print(f"{i + 1}. {ai_type_string[i]}")
ai_choice1 = ai_types[int(input()) - 1]
print("Which Computer Ai do you want to use for the second computer")
ai_choice2 = ai_types[int(input()) - 1]
winner = ""
while winner == "":
turn = ai_choice2
if playing_board.whose_turn == playing_board.ex:
turn = ai_choice1
winner = computer_turn(turn)
if winner == playing_board.ex:
print(f"") |
a1065b26c6cf47a1d8c8e401c8b1cc737e94269f | mohammedkadiri/Python-Exercises | /Classes/exercise1.py | 320 | 3.828125 | 4 |
class Person:
def __init__(self, firstname, age):
self.firstname = firstname
self.age = age
joe = Person("joe", 20)
#use the setattr method to set the lastname without hardcoding
setattr(joe, "lastname", "walsh")
firstname = getattr(joe, "firstname", None)
print(firstname + " " + joe.lastname) |
3f2abf820ce17b90d0db721cf08878ec8fd787b1 | shiki7/Atcoder | /ABC144/D.py | 231 | 3.640625 | 4 | import math
a, b, x = map(int, input().split())
v = a*a*b
# 台形
if v/2 < x:
c = (v - x) * 2 / (a ** 2)
print(math.atan2(c, a)/math.pi*180)
# 三角形
else:
c = x * 2 / (a*b)
print(math.atan2(b, c)/math.pi*180)
|
add7c8902274e701cc5e732663febdad91d1ac50 | gabriellaec/desoft-analise-exercicios | /backup/user_057/ch84_2020_06_21_01_35_43_046531.py | 248 | 3.703125 | 4 | def inverte_dicionario(dic):
dic2 = {}
for nome in dic.keys():
idade = dic[nome]
if nome not in dic2.vallues():
dic2[idade] = [nome]
else:
dic2[idade].append(nome)
return dic2 |
0131d16957478af7137dee164f7edea6b8db1be1 | yuishizhume/noname | /day2.2.py | 6,061 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 20:29:29 2019
@author: Administrator
"""
#高级特性
#掌握了Python的数据类型、语句和函数,基本上就可以编写出很多有用的程序了。
#构造一个1, 3, 5, 7, ..., 99的列表
L = []
n = 1
while n <= 99:
L.append(n)
n = n + 2
#在Python中,代码不是越多越好,而是越少越好
#代码不是越复杂越好,而是越简单越好。
#切片
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
#取前3个元素
r = []
n = 3
for i in range(n):
r.append(L[i])
r
#这种操作用循环十分繁琐,因此可以使用切片(slice)操作符
L[0:3]#从索引0开始取,直到索引3为止,但不包括索引3
L[:3]#如果第一个索引是0,还可以省略
L[-2:]#['Bob', 'Jack']
L[-2:-1]#['Bob']
L = range(100)
L[:10]
L[-10:]
L[10:20]#前11-20个数
L[:10:2]#前10个数,每两个取一个
L[::5]#所有数,每5个取一个
L[:]#甚至什么都不写,只写[:]就可以原样复制一个list
#tuple也可以用切片操作
(0, 1, 2, 3, 4, 5)[:3]
#字符串
'ABCDEFG'[:3]
'ABCDEFG'[::2]
#迭代
#通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration)。
#在Python中,迭代是通过for ... in来完成的
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print key
#因为dict的存储不是按照list的方式顺序排列,所以,迭代出的结果顺序很可能不一样。
#默认情况下,dict迭代的是key。
#如果要迭代value,可以用for value in d.itervalues()
#如果要同时迭代key和value,可以用for k, v in d.iteritems()
for ch in 'ABC':
print ch
#如何判断一个对象是可迭代对象呢?
#通过collections模块的Iterable类型判断
from collections import Iterable
isinstance('abc', Iterable)
isinstance([1,2,3], Iterable)
isinstance(123, Iterable)
#如何对list实现类似Java那样的下标循环
#Python内置的enumerate函数可以把一个list变成索引-元素对
for i, value in enumerate(['A', 'B', 'C']):
print i, value
for x, y in [(1, 1), (2, 4), (3, 9)]:
print x, y
#小结
#任何可迭代对象都可以作用于for循环,包括我们自定义的数据类型,
#只要符合迭代条件,就可以使用for循环。
#列表生成式
#列表生成式即List Comprehensions
#是Python内置的非常简单却强大的可以用来创建list的生成式
range(1, 11)
[x * x for x in range(1, 11)]
[x * x for x in range(1, 11) if x % 2 == 0]
#筛选出仅偶数的平方
#还可以使用两层循环,可以生成全排列
[m + n for m in 'ABC' for n in 'XYZ']
#三层和三层以上的循环就很少用到了。
import os # 导入os模块,模块的概念后面讲到
[d for d in os.listdir('.')] # os.listdir可以列出文件和目录
#for循环其实可以同时使用两个甚至多个变量
#比如dict的iteritems()可以同时迭代key和value
d = {'x': 'A', 'y': 'B', 'z': 'C' }
for k, v in d.iteritems():
print k, '=', v
#因此,列表生成式也可以使用两个变量来生成list
d = {'x': 'A', 'y': 'B', 'z': 'C' }
[k + '=' + v for k, v in d.iteritems()]
#把一个list中所有的字符串变成小写:
L = ['Hello', 'World', 'IBM', 'Apple']
[s.lower() for s in L]
#小结
#运用列表生成式,可以快速生成list,可以通过一个list推导出另一个list,而代码却十分简洁。
#生成器
#受到内存限制,列表容量肯定是有限的
#如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了
#如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?
#这样就不必创建完整的list,从而节省大量的空间。
#在Python中,这种一边循环一边计算的机制,称为生成器(Generator)。
#要创建一个generator,有很多种方法。
#把一个列表生成式的[]改成(),就创建了一个generator:
L = [x * x for x in range(10)]#list
g = (x * x for x in range(10))#generator
L,g#<generator object <genexpr> at 0x0000000009B992D0>
#怎么打印出generator的每一个元素呢?
#可以通过generator的next()方法
g.next()
#generator保存的是算法,每次调用next(),就计算出下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration的错误。
#正确的方法是使用for循环
g = (x * x for x in range(10))
for n in g:
print n
#基本上永远不会调用next()方法,而是通过for循环来迭代它。
#著名的斐波拉契数列(Fibonacci)
#除第一个和第二个数外,任意一个数都可由前两个数相加得到:
#1, 1, 2, 3, 5, 8, 13, 21, 34, ...
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print b
a, b = b, a + b
n = n + 1
fib(6)
#要把fib函数变成generator,
#只需要把print b改为yield b就可以了:
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
fib(6).next()#<generator object fib at 0x0000000009B99360>
#如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator
#这里,最难理解的就是generator和函数的执行流程不一样。
#变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
#函数改成generator后,我们基本上从来不会用next()来调用它
#而是直接使用for循环来迭代:
for n in fib(6):
print n
'''
小结:
generator是非常强大的工具,在Python中,可以简单地把列表生成式改成generator,也可以通过函数实现复杂逻辑的generator。
要理解generator的工作原理,它是在for循环的过程中不断计算出下一个元素,并在适当的条件结束for循环。对于函数改成的generator来说,遇到return语句或者执行到函数体最后一行语句,就是结束generator的指令,for循环随之结束。
'''
|
778482417c7b4a03c51032515ed2a3cd794381d5 | l-rushton/Financial-Asset-Beta-Tool | /BETA STONK CALCULATOR/EXCELVARCOVAR.py | 764 | 3.734375 | 4 | #EXCEL VARIANCE AND COVARIANCE CALCULATOR
def variance(timeSeries):
mean = 0
sum = 0
for i in range(len(timeSeries)):
mean += timeSeries[i]
mean = mean/len(timeSeries)
for i in range(len(timeSeries)):
sum += (timeSeries[i] - mean)*(timeSeries[i] - mean)
return sum/(len(timeSeries) - 1)
def covariance(timeSeries1, timeSeries2):
mean1 = 0
mean2 = 0
sum = 0
for i in range(len(timeSeries1)):
mean1 += timeSeries1[i]
mean2 += timeSeries2[i]
mean1 = mean1/len(timeSeries1)
mean2 = mean2/len(timeSeries2)
for i in range(len(timeSeries1)):
sum += (timeSeries1[i]-mean1)*(timeSeries2[i]-mean2)
return sum/(len(timeSeries1) - 1)
|
b0a8b4a70b61381d0af0bb20adf6d4e7feb79a98 | da-ferreira/uri-online-judge | /uri/1962.py | 266 | 3.5 | 4 |
casos = int(input())
for i in range(casos):
ano = int(input())
if ano == 2015:
print('1 A.C.')
else:
if ano > 2015:
print(f'{(ano + 1) - 2015} A.C.')
else:
print(f'{2015 - ano} D.C.')
|
4cc834b7d2342c01a848c427a2f8c133da0df55a | Vekselsvip/HW-Python | /homework5.9.py | 162 | 3.5 | 4 | List = []
for i in range(2, 100):
y = 2
while y < i:
if i % y == 0:
break
y += 1
else:
List.append(i)
print(List)
|
70365b712c0a3b386020229fc86d3b7ffe9ce6da | saikiran03/competitive | /CodeChef/Python/Fit_squares_in_triangle.py | 251 | 3.609375 | 4 | t = input()
while(t):
t -= 1
base = input()
squares = 0
layer = 1
while ((base-(2*layer))/2 > 0) :
number_of_squares = (base - 2*layer)/2
squares += number_of_squares
layer += 1
print squares
|
6c35b63ec64fdae860e39a0f668de231d75fdb51 | ddbff9/polygon-area-calculator | /shape_calculator.py | 2,057 | 3.78125 | 4 | class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
pass
def __str__(self):
width = self.width
height = self.height
output = self.__class__.__name__ + f"(width={width}, height={height})"
return output
def set_height(self, height):
self.height = height
return height
def set_width(self, width):
self.width = width
return width
def get_area(self):
width = self.width
height = self.height
area = width * height
return area
def get_perimeter(self):
width = self.width
height = self.height
perimeter = (2 * width) + (2 * height)
return perimeter
def get_diagonal(self):
width = self.width
height = self.height
diagonal = (width ** 2 + height ** 2) ** .5
return diagonal
def get_amount_inside(self, shape):
return(self.width//shape.width * self.height//shape.height)
def get_picture(self):
picture = ""
if self.width > 50:
return "Too big for picture."
exit
if self.height > 50:
return "Too big for picture."
exit
for lines in range(self.height):
line = "*" * self.width + "\n"
picture += str(line)
return picture
class Square(Rectangle):
def __init__(self, side):
super().__init__(width=side, height=side)
self.side = side
def __str__(self):
side = self.side
output = self.__class__.__name__ + f"(side={side})"
return output
def set_side(self, side):
self.side = side
super().__init__(width=side, height=side)
def set_width(self, side):
self.side = side
super().set_width(width=side)
def set_height(self, side):
self.side = side
super().set_height(height=side)
# rect = Rectangle(10, 5)
# print(rect.get_area())
# rect.set_height(3)
# print(rect.get_perimeter())
# print(rect)
# sq = Square(9)
# print(sq.get_area())
# sq.set_side(4)
# print(sq.get_diagonal())
# print(sq)
# rect.set_height(8)
# rect.set_width(16)
# print(rect.get_amount_inside(sq)) |
76afe763e624a2026f4460a09eb527cf5996eeef | DoubleDPro/practice | /numbers/task_2.py | 481 | 4.03125 | 4 | '''
С клавиатуры вводят три числа. Вывести в консоль произведение этих чисел.
'''
first_number = int(input('Введите первое число\n'))
second_number = int(input('Введите второе число\n'))
third_number = int(input('Введите третье число\n'))
mult = (first_number * second_number * third_number)
print('Произведение чисел равно ' + str(mult))
|
51bd0ac32719fd3f83862f6cd0b41cc5e131ca5b | saiarvind1997/noob | /task_2.py | 269 | 3.6875 | 4 | c=ord('a')
d=ord('z')+1
while c<d:
i=1
while i<10:
print'{}{}'.format(chr(c),i)
i+=1
c+=1
#alternate code with for loops:
"""
x= ord("a")
y= ord("z")+1
for c in range(x,y):
for i in range(1,10):
print "{}{}".format(chr(c),i)
""" |
92d17e9be140576aebada1d86b77bd50f3a0e96c | diegopnh/AulaPy2 | /Aula 14/Ex060.py | 155 | 3.828125 | 4 | a = int(input('Insira o fatorial: '))
result = 1
n = 1
while n <= a:
result = result*n
n = n + 1
print('O fatorial de {} é {}'.format(a,result)) |
1beb6289f76f6709c8a8f25a1540b0e8c226e27d | DavidFontalba/DAW-Python | /secuenciales/20dinero.py | 1,096 | 3.75 | 4 | # Programa para decirte el total de euros y céntimos que tienes cuándo le insertes la cantidad de monedas
# Autor: David Galván Fontalba
# Fecha: 12/10/2019
#
# Algoritmo
# Pido monedas
# Calculo
# total en centimos <- 2e*200 + 1e*100 + 50c*50 + 20c*20 + 10c*10
# separo euros y centimos
# Muestro el resultado
print("Bienvenido a este programa para sumar monedas")
print("---------------------------------------------\n")
#Pido las monedas
eu2 = int(input("¿Cuántas monedas de 2 euros tienes? "))
eu1 = int(input("¿Cuántas monedas de 1 euro tienes? "))
ce50 = int(input("¿Cuántas monedas de 50 céntimos tienes? "))
ce20 = int(input("¿Cuántas monedas de 20 céntimos tienes? "))
ce10 = int(input("¿Cuántas monedas de 10 céntimos tienes? "))
#Calculo
totalcent = eu2*200 + eu1*100 + ce50*50 + ce20*20 + ce10*10
#Divido en euros y céntimos
euros = totalcent/100
centimos = (totalcent/100 - totalcent//100)*100
#Muestro el resultado
print("---------------------------------------------\n")
print(f"Con esas monedas juntas un total de {int(euros)} euros y {round(centimos)} céntimos")
|
5dd5444c4787c2d6f58c0b699549c465612ed848 | rhythm1011/MNIST-Data- | /DataReader.py | 1,443 | 3.796875 | 4 | import tensorflow as tf
"""This script implements the functions for reading data.
"""
def load_data():
"""Load the MNIST dataset and normalize pixel values into [0,1].
Returns:
x_train: An array of shape [60000, 784].
y_train: An array of shape [60000,].
x_test: An array of shape [10000, 784].
y_test: An array of shape [10000,].
"""
# Load the dataset
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
# Flatten: reshape images into a 1D array
x_train = x_train.reshape((x_train.shape[0], -1))
x_test = x_test.reshape((x_test.shape[0], -1))
# Normalization: change pixel values from [0,255] to [0,1]
x_train, x_test = x_train / 255.0, x_test / 255.0
return x_train, y_train, x_test, y_test
def train_valid_split(x_train, y_train, split_index=50000):
"""Split the original training data into a new training dataset
and a validation dataset.
Args:
x_train: An array of shape [60000, 784].
y_train: An array of shape [60000,].
split_index: An integer.
Returns:
x_train_new: An array of shape [split_index, 784].
y_train_new: An array of shape [split_index,].
x_valid: An array of shape [60000-split_index, 784].
y_valid: An array of shape [60000-split_index,].
"""
x_train_new = x_train[:split_index]
y_train_new = y_train[:split_index]
x_valid = x_train[split_index:]
y_valid = y_train[split_index:]
return x_train_new, y_train_new, x_valid, y_valid
|
d9e7b8334a0c1458dc75bb9abe75fc3822dda206 | izaycarter/6.1.1-number-guesser | /level_3.py | 538 | 4.09375 | 4 | from random import randint
number_of_guess = 0
number = int(input("pick a number between 1 and 100.. bet i can guess it: "))
high = 100
low = 1
guess = (high + low) // 2
while number_of_guess < 5:
number_of_guess += 1
print(guess)
if guess < number:
low = guess
guess = randint(low,high)
elif guess > number:
high = guess
guess = randint(low,high)
elif guess == number:
print("BOOM! your number is: "+number)
break
else:
print("at least i dont have bills...")
|
3f1538748018ab8f29c43cf13491afc20cb26120 | abawchen/leetcode | /solutions/054_spiral_matrix.py | 1,515 | 3.859375 | 4 | # Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
# For example,
# Given the following matrix:
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
# ]
# You should return [1,2,3,6,9,8,7,4,5].
class Solution:
# @param {integer[][]} matrix
# @return {integer[]}
def spiralOrder(self, matrix):
if not matrix or not matrix[0]:
return []
total = len(matrix) * len(matrix[0])
spiral = []
l, r, u, d = -1, len(matrix[0]), 0, len(matrix)
s, i, j = 0, 0, 0
for c in range(total):
spiral.append(matrix[i][j])
s, i, j, l, r, u, d = self._next(s, i, j, l, r, u, d)
return spiral
def _next(self, s, i, j, l, r, u, d):
if s == 0: # step right
j += 1
if j == r:
i, j = i+1, r-1
r -= 1
s = 1
elif s == 1: # step down
i += 1
if i == d:
i, j = d-1, j-1
d -= 1
s = 2
elif s == 2: # step left
j -= 1
if j == l:
i, j = i-1, l+1
l += 1
s = 3
else: # step up
i -= 1
if i == u:
i, j = u+1, j+1
u += 1
s = 0
return s, i, j, l, r, u, d |
ca0b52d189b285e83c3583b4c81d1f29a7d8b2bc | GGbits/CryptoPals | /Set2/challenge11.py | 2,174 | 3.6875 | 4 | # Python Version: 3.5
# Creator - GGbits
# Set: 2
# Challenge: 11
# https://cryptopals.com/sets/2/challenges/11
#
# Description:
# Now that you have ECB and CBC working:
# Write a function to generate a random AES key; that's just 16 random bytes.
#
# Write a function that encrypts data under an unknown key --- that is,
# a function that generates a random key and encrypts under it.
# The function should look like:
# encryption_oracle(your-input)
# => [MEANINGLESS JIBBER JABBER]
# Under the hood, have the function append 5-10 bytes (count chosen randomly)
# before the plaintext and 5-10 bytes after the plaintext.
#
# Now, have the function choose to encrypt under ECB 1/2 the time,
# and under CBC the other half (just use random IVs each time for CBC). Use rand(2) to decide which to use.
# Detect the block cipher mode the function is using each time.
# You should end up with a piece of code that, pointed at a block box that might be encrypting ECB or CBC,
# tells you which one is happening.
from challenge8 import chunks
from challenge10 import encrypt_cbc, encrypt_ecb
import os
from random import randint
test_message = b"ABC" * 80
def random_aes_key(size):
return os.urandom(size)
def randomize_message(message):
return b"".join([random_aes_key(randint(5, 10)), message, random_aes_key(randint(5, 10))])
def encrypt_ecb_or_cbc(message, key, blocksize):
rand_msg = randomize_message(message)
random_enc = (randint(0, 1))
if random_enc == 0:
iv = random_aes_key(16)
return encrypt_cbc(rand_msg, key, iv, blocksize)
else:
return encrypt_ecb(rand_msg, key)
def detect_cbc_or_ebc(encrypted_string):
blocks = chunks(encrypted_string, 16)
num_blocks = len(blocks)
# count number of distinct blocks
distinct_blocks = {}
for b in blocks:
distinct_blocks[b] = 1
num_distinct_blocks = len(distinct_blocks)
if num_distinct_blocks < num_blocks:
return "ECB"
else:
return "CBC"
if __name__ == '__main__':
encrypt_string = encrypt_ecb_or_cbc(test_message, random_aes_key(16), 16)
print(encrypt_string)
print(detect_cbc_or_ebc(encrypt_string))
|
9c7bd2696e31ca4818f932bbe0c201009819aede | Ashishkapil/python-runs | /numbers-with-a-sum/sum-array.py | 479 | 3.578125 | 4 |
def main():
alist = [1, 2, 4, 7, 11, 15]
start = 0
end = len(alist) - 1
num = 28
while (1):
if start >= end:
print 'no such numbers found'
break
asum = alist[start] + alist[end]
if asum == num:
print 'the two numbers are: %d and %d'%(alist[start], alist[end])
break
if asum > num:
end -= 1
else:
start += 1
if __name__ == '__main__':
main() |
bddc145f009cbbb528ebdd1644b833a12b334ca4 | dagute/Coding_Interview | /Python/Find pair that sums up to k/sumpair1.py | 357 | 3.609375 | 4 |
# Find pair that sums up to k
# By checking all pairs (brute force solution):
# arr = [4, 1, 5, 7, 2]
# k = 3
# Time complexity: O(n²)
# Space complexity: O(1)
def findPair(arr, k):
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] + arr[j] == k:
print(str(arr[i]), str(arr[j]))
return True
return False
|
472cbc52aebe4eb7cf5c94eb09b1862d1a221bfc | harshad90/pythonHardWay | /Exercise11.py | 541 | 3.921875 | 4 | print ("How old are you", end = ' ')
age = input()
print ("How tall are you", end =' ')
height = input()
print ("How much do you weigh", end = ' ')
weight = input()
print (f"So you are {age} year old and {height} cm tall and weigh about {weight} kg")
print ("Which Car do you like?", end = '')
car = input()
print ("Which model do you like?", end = '')
model = input()
print ("Which colour do you like?", end = '')
colour = input()
print (f"So you like '{car}' car and the model is '{model}' and you\"r favourite colour is '{colour}'")
|
b2ca003ff94c3ea9d532e11382537c257d0ae22e | fabricio123/lista2python | /Questao3.py | 189 | 3.96875 | 4 |
letra = str(input('digite a letra'))
F = 'F'
M = 'M'
if letra == 'F':
print('sexo feminino')
if letra == 'M':
print('sexo masculino')
if letra != F and M:
print('sexo inválido')
|
6cbf38a2b3a543ed21e8597e245c97d9c801f4a8 | Octember/Euler | /python/29.py | 892 | 3.5 | 4 | # Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5:
# 2^2=4, 2^3=8, 2^4=16, 2^5=32
# 3^2=9, 3^3=27, 3^4=81, 3^5=243
# 4^2=16, 4^3=64, 4^4=256, 4^5=1024
# 5^2=25, 5^3=125, 5^4=625, 5^5=3125
# If they are then placed in numerical order, with any repeats removed,
# we get the following sequence of 15 distinct terms:
# 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
# How many distinct terms are in the sequence generated by ab for
# 2 <= a <= 100 and 2 <= b <= 100?
import time
def solve():
nums = set([a**b for a in range(2, 101) for b in range(2, 101)])
solution = len(nums)
print "Solution: {}".format(solution)
if __name__ == "__main__":
start_time = time.time()
solve()
elapsed_time = time.time() - start_time
print "Elapsed time: {} seconds".format(elapsed_time)
# Solution: 9183
# Elapsed time: 0.0190000534058 seconds |
e352c14794332033d37353d382b041b20c10da9f | Diegooualexandre/PycharmProjects | /pythonCaelum/adivinhacao.py | 405 | 3.84375 | 4 | print('*'*24)
print(f'*'*2+'Jogos de adivinhação'+'*'*2)
print('*'*24)
secret_number = 42
c = int(input('Write number: '))
print(f'Number submitted: {c}')
if c == secret_number:
print('Congratulations! You discover the number.')
elif c > secret_number:
print('Failed. Appointment is bigger than secret number')
elif c < secret_number:
print('Failed.Appointment is minor than secret number')
|
c68fd7d86a9d42585bf2baf50f2ecbdc061c840e | siliconcortex/curiousweb | /electronics/floyd.py | 26,383 | 3.859375 | 4 | import random
class template:
def __init__(self):
choice_a = ''
choice_b = ''
choice_c = ''
choice_d = ''
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f""""""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_1:
def __init__(self):
choice_a = 'p, n, p'
choice_b = 'n, p, n'
choice_c = 'input, output, ground'
choice_d = 'base, emitter, collector #'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The three terminals of a bipolar transistor are called"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_2:
def __init__(self):
choice_a = 'base and emitter'
choice_b = 'base and collector'
choice_c = 'emitter and collector #'
choice_d = 'base, collector, and emitter'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""In a pnp transistor, the p regions are"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_3:
def __init__(self):
choice_a = 'positive with respect to the emitter #'
choice_b = 'negative with respect to the emitter'
choice_c = 'positive with respect to the collector'
choice_d = '0 V'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""For operation as an amplifier, the base of an npn transistor must be"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_4:
def __init__(self):
choice_a = 'greater than the base current'
choice_b = 'less than the collector current'
choice_c = 'greater than the collector current'
choice_d = 'two of the choices #'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The emitter current is always"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_5:
def __init__(self):
choice_a = 'current gain #'
choice_b = 'voltage gain'
choice_c = 'power gain'
choice_d = 'internal resistance'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The beta_DC of a transistor is its"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_6:
def __init__(self):
choice_a = '0.02'
choice_b = '100'
choice_c = '50 #'
choice_d = '500'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""If IC is 50 times larger than IB, then beta_DC is """
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_7:
def __init__(self):
choice_a = '0 V'
choice_b = '0.7 V #'
choice_c = '0.3 V'
choice_d = 'VBB'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The approximate voltage across the forward-biased base-emitter junction of a silicon BJT is """
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_8:
def __init__(self):
choice_a = 'forward-reverse #'
choice_b = 'forward-forward'
choice_c = 'reverse-reverse'
choice_d = 'collector bias'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The bias condition for a transistor to be used as a linear amplifier is called"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_9:
def __init__(self):
choice_a = '5'
choice_b = '500'
choice_c = '50 #'
choice_d = '100'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""If the output of a transistor amplifier is 5Vrms and the input is 100mVrms, the voltage gain is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_10:
def __init__(self):
choice_a = 'a low resistance'
choice_b = 'a wire resistance'
choice_c = 'an internal ac resistance #'
choice_d = 'a source resistance'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""When a lowercase r' is used in relation to a transistor, it refers to """
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_11:
def __init__(self):
choice_a = '2.2'
choice_b = '110 #'
choice_c = '20'
choice_d = '44'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""In a given transistor amplifier, RC = 2.2 kohms and re = 20 ohms, the voltage gain is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_12:
def __init__(self):
choice_a = 'linear amplifier'
choice_b = 'switch #'
choice_c = 'variable capacitor'
choice_d = 'variable resistor'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""When operated in cutoff and saturation, the transistor acts like a """
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_14:
def __init__(self):
choice_a = '0.7 V'
choice_b = 'equal to VCC'
choice_c = 'minimum #'
choice_d = 'maximum'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""In saturation, VCE is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_15:
def __init__(self):
choice_a = 'IB = IC(sat)'
choice_b = 'VCC must be at least 10 V'
choice_c = 'IB > IC(sat) / beta_DC #'
choice_d = 'the emitter must be grounded'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""To saturate a BJT"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_16:
def __init__(self):
choice_a = 'cause the collector current to increase'
choice_b = 'not affect the collector current #'
choice_c = 'cause the collector current to decrease'
choice_d = 'turn the transistor off'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""Once in saturation, a further increase in base current will"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_20:
def __init__(self):
choice_a = 'VCC #'
choice_b = '0 V'
choice_c = 'floating'
choice_d = '0.2 V'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""In a transistor amplifier, if the base-emitter junction is open, the collector voltage is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_4_20:
def __init__(self):
choice_a = '0 V'
choice_b = '0.7 V'
choice_c = 'OL #'
choice_d = 'VCC'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""A DMM measuring on open transistor junction shows"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_1:
def __init__(self):
choice_a = 'two inputs and two outputs'
choice_b = 'two inputs and one output #'
choice_c = 'one input and one output'
choice_d = 'two of the choices are valid'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""An integrated circuit opamp has"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_2:
def __init__(self):
choice_a = 'High gain'
choice_b = 'Lower power #'
choice_c = 'High input impedance'
choice_d = 'Low output impedance'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""Which of the following characteristics does not necessarily apply to an opamp?"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_3:
def __init__(self):
choice_a = 'is part of an opamp'
choice_b = 'has two outputs'
choice_c = 'has one input and one output'
choice_d = 'two choices are valid #'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""A differential amplifier"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_4:
def __init__(self):
choice_a = 'the output is grounded'
choice_b = 'one input is grounded and a signal is applied to the other #'
choice_c = 'both inputs are connected together'
choice_d = 'the output is not inverted'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""When an opamp is operated in the single-ended differential mode, """
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_5:
def __init__(self):
choice_a = 'a signal is applied between the two inputs #'
choice_b = 'the gain is 1'
choice_c = 'the outputs are different amplitudes'
choice_d = 'only one supply voltage is used'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""In the double ended differential mode"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_6:
def __init__(self):
choice_a = 'both inputs are ground'
choice_b = 'the outputs are connected together'
choice_c = 'an identical signal appears on both inputs #'
choice_d = 'only one supply voltage is used'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""In the common-mode """
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_7:
def __init__(self):
choice_a = 'very high'
choice_b = 'very low #'
choice_c = 'always unity'
choice_d = 'unpredictable'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""Common mode gain is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_8:
def __init__(self):
choice_a = '1225'
choice_b = '80 dB'
choice_c = '10, 000'
choice_d = 'two of the choices are valid #'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""If AOL = 3500 and ACM = 0.35, the CMRR is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_9:
def __init__(self):
choice_a = 'the positive supply voltage'
choice_b = 'zero #'
choice_c = 'the negative supply voltage'
choice_d = 'the CMRR'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""With zero volts on both inputs, an opamp ideally should have an output equal to"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_10:
def __init__(self):
choice_a = '1'
choice_b = '2000'
choice_c = '80 dB'
choice_d = '100,000 #'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""Of the values listed, the most realistic value for open-loop gain of an opamp is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_11:
def __init__(self):
choice_a = '700 nA #'
choice_b = '99.3 uA'
choice_c = '49.7 uA'
choice_d = 'none of the choices '
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""A certain opamp has bias currents of 50uA and 49.3 uA. The input offset current is """
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_12:
def __init__(self):
choice_a = '96 V/us'
choice_b = '0.67 V/us #'
choice_c = '1.5 V/us'
choice_d = 'none of the choices'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The output of a particular opamp increases 8 V in 12 us. The slew rate is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_13:
def __init__(self):
choice_a = 'reduce the gain'
choice_b = 'equalize the input signals'
choice_c = 'zero the output error voltage'
choice_d = 'two of the choices #'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The purpose of offset nulling is to"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_14:
def __init__(self):
choice_a = 'reduces the voltage gain of an opamp'
choice_b = 'makes the opamp oscillate'
choice_c = 'makes linear operation possible'
choice_d = 'two of the choices'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The use of negative feedback """
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_15:
def __init__(self):
choice_a = 'equal to the input'
choice_b = 'increased'
choice_c = 'fed back to the inverting input #'
choice_d = 'fed back to the non-inverting input'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""For an opamp with negative feedback, the output is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_16:
def __init__(self):
choice_a = '100,000'
choice_b = '1000'
choice_c = '101 #'
choice_d = '100'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""A certain non-inverting amplifier has an Ri of 1 kohm and an RF of 100 kohms. The closed loop gain is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_18:
def __init__(self):
choice_a = 'doubles'
choice_b = 'drops to 12.5'
choice_c = 'remains at 25'
choice_d = 'increases slightly #'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""A certain inverting amplifier has a closed loop gain of 25. The opamp has an open loop gain of 100 000. If another opamp with an open loop gain of 200 000 is substituted in the configuration, the closed loop gain"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_19:
def __init__(self):
choice_a = 'has a gain of 1'
choice_b = 'is non-inverting'
choice_c = 'has no feedback resistor'
choice_d = 'all of the choices #'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""A voltage follower"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_21:
def __init__(self):
choice_a = 'Reduces gain'
choice_b = 'Reduces output error voltage #'
choice_c = 'Increases bandwidth'
choice_d = 'Has no effect'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""Bias current compensation"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_22:
def __init__(self):
choice_a = 'extends from the lower critical frequency to the upper critical frequency'
choice_b = 'extends from 0Hz to the upper critical frequency'
choice_c = 'rolls off at 20 dB/decade beginning at 0 Hz'
choice_d = 'two of the choices #'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The midrange open loop gain of an opamp"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_23:
def __init__(self):
choice_a = 'the upper critical frequency'
choice_b = 'the cutoff frequency'
choice_c = 'the notch frequency'
choice_d = 'the unity-gain frequency #'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The frequency at which the open-loop gain is equal to 1 is called"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_24:
def __init__(self):
choice_a = 'the internal RC circuits #'
choice_b = 'the external RC circuits'
choice_c = 'the gain roll-off'
choice_d = 'negative feedback'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""Phase shift through an opamp is caused by"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_25:
def __init__(self):
choice_a = 'causes the gain to roll off at - 6dB/octave'
choice_b = 'causes the gain to roll off at - 20dB/decade'
choice_c = 'reduces the midrange gain by 3 dB'
choice_d = 'two valid choices #'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""Each RC circuit in an opamp"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_26:
def __init__(self):
choice_a = '200,000 Hz'
choice_b = '1 x 10^12 Hz'
choice_c = '5,000,000 Hz #'
choice_d = 'not determinable from the information given'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""If a certain opamp has a midrange open-loop gain of 200,000 and a unity-gain frequency if 5MHz, the gain-bandwidth product is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_27:
def __init__(self):
choice_a = '1 kHz'
choice_b = '9 kHz #'
choice_c = '10 kHz'
choice_d = '11 kHz'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The bandwidth of an ac amplifier having a lower critical frequency of 1kHz and an upper critical frequency of 10kHz is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_28:
def __init__(self):
choice_a = '100 kHz #'
choice_b = 'unknown'
choice_c = 'infinity'
choice_d = '0 kHz'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The bandwidth of a dc amplifier having an upper critical frequency of 100 kHz is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_29:
def __init__(self):
choice_a = 'increases'
choice_b = 'decreases'
choice_c = 'stays the same #'
choice_d = 'fluctuates'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""When negative feedback is used, the gain-bandwidth product of an opamp"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_12_30:
def __init__(self):
choice_a = '200 MHz #'
choice_b = '10 MHz'
choice_c = 'the unity-gain frequency'
choice_d = 'two of the choices'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""If a certain opamp has a closed loop gain of 20 and an upper critical frequency of 10 MHz, the gain-bandwidth product is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_1:
def __init__(self):
choice_a = 'has more gain'
choice_b = 'requires no input signal#'
choice_c = 'requires no dc supply'
choice_d = 'always has the same output'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""An oscillator differs from an amplifier because the oscillator:"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_2:
def __init__(self):
choice_a = 'a phase shift around the feedback loop of 180 degrees.'
choice_b = 'a gain around the feedback loop of 1/3'
choice_c = 'a phase shift around the feedback loop of 0 degrees #'
choice_d = 'a gain around the feedback loop of less than 1'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""One condition for oscillation is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_3:
def __init__(self):
choice_a = 'no gain around the feedback loop'
choice_b = 'a gain of 1 around the feedback loop #'
choice_c = 'the attenuation of the feedback circuit must be one-third'
choice_d = 'the feedback circuit must be capacitive'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The second condition for oscillation is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_4:
def __init__(self):
choice_a = '1'
choice_b = '0.01'
choice_c = '10'
choice_d = '0.02 #'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
gain = random.randint(50, 100)
self.question = f"""In a certain oscillator, Av = 50. The attenuation of the feedback circuit must be"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_5:
def __init__(self):
choice_a = '1'
choice_b = 'less than 1'
choice_c = 'greater than 1 #'
choice_d = 'equal to B'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""For an oscillator to properly start, the gain around the feedback loop must initially be"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_6:
def __init__(self):
choice_a = 'positive feedback #'
choice_b = 'negative feedback'
choice_c = 'the piezoelectric effect'
choice_d = 'high gain'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""Wien-bridge oscillators are based on"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_7:
def __init__(self):
choice_a = 'decreases #'
choice_b = 'increases'
choice_c = 'remains the same'
choice_d = 'wrong'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""In a Wien-bridge oscillator, if the resistances in the positive feedback circuit are decreased, the frequency"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_8:
def __init__(self):
choice_a = 'an RL circuit'
choice_b = 'an LC circuit'
choice_c = 'a voltage divider'
choice_d = 'a lead-lag circuit #'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The Wien-bridge oscillator's positive feedback circuit is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_9:
def __init__(self):
choice_a = 'three RC circuits #'
choice_b = 'three LC circuits'
choice_c = 'a T-type circuit'
choice_d = 'a pi-type circuit'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""A phase shift oscillator has """
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_10:
def __init__(self):
choice_a = 'types of RC oscillators'
choice_b = 'inventors of the transistor'
choice_c = 'types of LC oscillators'
choice_d = 'types of filters'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""Colpitts, Clapp, and Hartley are names that refer to """
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_11:
def __init__(self):
choice_a = 'economy'
choice_b = 'stability #'
choice_c = 'reliability'
choice_d = 'high frequency'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The main feature of a crystal oscillator is"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_12:
def __init__(self):
choice_a = 'a crystal oscillator'
choice_b = 'a VCO #'
choice_c = 'an Armstrong oscillator'
choice_d = 'a piezoelectric device'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""An oscillator whose frequency is changed by a variable dc voltage is known as """
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_13:
def __init__(self):
choice_a = 'the charging and discharging of a capacitor #'
choice_b = 'a highly selective resonant circuit'
choice_c = 'a very stable supply voltage'
choice_d = 'low power consumption'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""The operation of a relaxation oscillator is based on"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
class floyd_16_14:
def __init__(self):
choice_a = 'Clock #'
choice_b = 'Threshold'
choice_c = 'Trigger'
choice_d = 'Discharge'
choices = [choice_a, choice_b, choice_c, choice_d]
random.shuffle(choices)
self.question = f"""Which one of the following is NOT an input or output of a 555 timer?"""
self.answer = f"""A. {choices[0]}
B. {choices[1]}
C. {choices[2]}
D. {choices[3]}"""
|
4e94afe25c884f25ee35c4ca286872d881b8843f | 19-shubho/forsk-coding-shool-challenges | /day46.py | 1,523 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('bluegills.csv')
feat = dataset.iloc[:, 0:1].values
lab = dataset.iloc[:, 1].values
#fitting linear regression -->
from sklearn.linear_model import LinearRegression
linObj = LinearRegression()
linObj.fit(feat, lab)
#plot a graph for feat and lab for visualisation -->
featGrid = np.arange(min(feat), max(feat), 0.1)
featGrid = featGrid.reshape(len(featGrid), 1)
plt.scatter(feat, lab, color = 'yellow')
plt.plot(featGrid, linObj.predict(featGrid), color = 'blue')
plt.title('Bluegill (Linear Regression)')
plt.xlabel('Age')
plt.ylabel('Length')
plt.show()
#fitting polynomial regression -->
from sklearn.preprocessing import PolynomialFeatures
higherDegree = PolynomialFeatures(degree = 2)
featPoly = higherDegree.fit_transform(feat)
regressorPoly = LinearRegression()
regressorPoly.fit(featPoly, lab)
# scatter and plot graph for the polynomial conversion of feat -->
featGrid = np.arange(min(feat), max(feat), 0.1)
featGrid = featGrid.reshape(len(featGrid), 1)
plt.scatter(feat, lab, color = 'yellow')
plt.plot(featGrid, regressorPoly.predict(higherDegree.fit_transform(featGrid)), color = 'blue')
plt.title('Bluegill (Linear Regression)')
plt.xlabel('Age')
plt.ylabel('Length')
plt.show()
print ("prediction using linear regression :"+str(linObj.predict([[5]])))
print ("predicting using polynomial regression :"+str(regressorPoly.predict(higherDegree.fit_transform([[5]]))))
|
c5286553e52e0aa0e3e353ba85eb3584244b2fca | AndrianovaVarvara/algorithms_and_data_structures | /TASK/Хирьянов 16 лекция множества и словари/zzz.py | 548 | 3.546875 | 4 | import sys
import pygame
pygame.init()
width = 500
height = 500
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('YAHOOOO')
clock = pygame.time.Clock()
x = 30
y = 30
vx = 50
vy = 50
while True:
dt = clock.tick(50) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT or event.type == pygame.KEYDOWN:
sys.exit()
x += vx * dt
y += vy * dt
screen.fill((0, 0, 0))
pygame.draw.circle(screen, (150, 10, 50), (int(x), int(y)), 20)
pygame.display.flip() |
633edc68b25a2b0aee5aaf76d82a17fbb8ef6c26 | sendurr/spring-grading | /submission - Homework1/RYAN W BARRS_2234_assignsubmission_file_homework1/homework1/index_nested_list.py | 245 | 3.640625 | 4 | q = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]
print "1)", q[0][0]
print "2)", q[1]
print "3)", q[2][1]
print "4)", q[1][0]
print "5) q[-1][-2] has value 'g' because it is the second value in the first list when counting from the right" |
fd2b3797ef9c1f48ffd50715b78ab107d6076d7e | reichlj/PythonBsp | /Schulung/py01_einführung/f151_list_param.py | 650 | 3.609375 | 4 | def s(liste):
print('sa:',id(liste))
liste += [47,11]
print('sa:',liste)
print('sb:',id(liste))
def s1(liste):
print('s1a:',id(liste))
liste = liste + [47,11]
print('s1a:',liste)
print('s1b:',id(liste))
print('**** in-place ****')
fib=[0,1,1,2,3]
print('m :',fib)
print('m :',id(fib))
s(fib)
print('m :',id(fib))
print('m :',fib)
print('**** concatenate ****')
fib=[0,1,1,2,3,5]
print('m :',fib)
print('m :',id(fib))
s1(fib)
print('m :',fib)
print('m :',id(fib))
print('**** copy ****')
fib=[0,1,1,2,3,5,8]
print('m :',fib)
print('m :',id(fib))
s(fib[:])
print('m :',id(fib))
print('m :',fib)
|
378ec2ee49c706f1fe4c12e26a0e7fdbef85dded | rwspicer/csv_utilities | /utility_test.py | 812 | 3.65625 | 4 | """
ross spicer
2014/08/05
this is an example of how the new utility_base class works
"""
import csv_lib.utility as util
class my_utility(util.utility_base):
def __init__(self, title , r_args, o_args, help):
super(my_utility, self).__init__(title , r_args,("--b",), help)
self.title = " my adder "
def main(self):
self.a = int(self.commands["--a"])
try:
self.b = int(self.commands["--b"])
except ValueError: #<-- int() wont work on '' which is bing returned
self.b = 0
self.my_addition()
def my_addition(self):
ans =self.a +self.b
self.print_center(str(self.a) + " + " + str(self.b) + " = " + str(ans))
a = my_utility("title",("--a",),(),"help")
a.run()
|
6c3651cdd10378be5597e8ec87ff2701d9c9ca37 | tbobm/99problems | /python/lists/P23.py | 392 | 3.609375 | 4 | # encoding: utf-8
# 1.23 (**) Extract a given number of randomly selected elements from a list.
# The selected items shall be put into a result list.
# Example:
# ?- rnd_select([a,b,c,d,e,f,g,h],3,L).
# L = [e,d,a]
import random
def func(data, to_pop):
res = []
for _ in xrange(to_pop):
res.append(data.pop(random.randrange(0, len(data)-1)))
return res
|
32d552c85b096a6e4df239a61fa4be44115d5cbc | mutemibiochemistry/Biopython | /Assignment-1/question1.py | 354 | 4.28125 | 4 | #1converts temparature from degree celcius to degree fahrenheit
def convert_celcius_to_fahrenheit(degree): #function
fahrenheit = 1.8*degree + 32 #conversion formula
print float(degree),"Celcius ->",fahrenheit, "Fahrenheit" #send output
test1=convert_celcius_to_fahrenheit(50.0) #test example
test2=convert_celcius_to_fahrenheit(10.0)
|
d850485556203c065a67246d18ca4019294427c9 | LouisCaixuran/StudyMemo | /problem/migong2.py | 790 | 3.578125 | 4 | import copy
source=[
[0,0,1,0,1],
[1,0,1,0,1],
[0,0,0,1,0],
[0,1,0,0,0],
[0,0,0,1,0]]
class Migong(object):
def __init__(self,source):
self.source=copy.deepcopy(source)
self.success=0
def move(self,x,y):
if x==4 and y==4:
print ("success")
self.success=1
import pdb
pdb.set_trace()
return True
if (x<=4 and x>=0 and y<=4 and y>=0) and self.success==0:
if self.source[x][y]==0:
self.source[x][y]=2
if self.move(x+1,y):
return True
elif self.move(x-1,y):
return True
elif self.move(x,y+1):
return True
elif self.move(x,y-1):
return True
else:
self.source[x][y]=0
obj=Migong(source)
obj.move(0,0)
for i in range(5):
print obj.source[i]
print
for i in range(5):
print source[i]
|
b9eee44a6f11f4168f634a14e8b356a92a216fe3 | stonecyan/Algorithm-Practice | /EPI/DutchNationalFlag.py | 477 | 3.53125 | 4 | def dutchFlagPartition(list,pivot):
smaller = 0
equal = 0
larger = len(list)-1
while equal<larger:
if list[equal]<pivot:
list[smaller], list[equal] = list[equal], list[smaller]
smaller+=1
equal+=1
elif list[equal]==pivot:
equal+=1
elif list[equal]>pivot:
list[larger], list[equal] = list[equal], list[larger]
larger-=1
equal+=1
return list
x = [0,1,2,0,2,1,1]
pivot = 1
y=dutchFlagPartition(x,pivot)
print(y)
|
c9ecafb80fa4f636ce171bf87dd3817b8d9a86f1 | fifa007/Leetcode | /test/test_atoi.py | 745 | 3.515625 | 4 | #!/usr/bin/env python2.7
'''
unit tests for atoi
'''
import unittest
import src.atoi
class atoi_test(unittest.TestCase):
sol = src.atoi.Solution()
def test1(self):
self.failUnless(self.sol.convert_str_to_int('1234') == 1234)
def test2(self):
self.failUnless(self.sol.convert_str_to_int('-1234') == -1234)
def test3(self):
self.failUnless(self.sol.convert_str_to_int('12345678999') == src.atoi.INT32_MAX)
def test4(self):
self.failUnless(self.sol.convert_str_to_int("") == 0)
def test5(self):
self.failUnless(self.sol.convert_str_to_int("2147483648") == 2147483647)
def test6(self):
self.failUnless(self.sol.convert_str_to_int("-2147483648") == -2147483648)
|
52f7e1238efb0668d95ea965738969891d099d7a | dakshitsoni/J.A.R.V.I.S | /python jarvis.py | 8,454 | 3.578125 | 4 | # Commands of J.A.R.V.I.S are -
# It can greet us when it is good morning it says morning and when it is afternoon it will say afternoon and when it is night it will say night.
# It can take our commands and when we do not say anything it does not takes our commands.
# It can turn on camera when we our in any meeting.
# It can search anything on wikipedia.
# It can open youtube , amazon , citibank , discord , whatsapp , python , zoom , skype , lichess , google , flipkart.
# It can play any video or any music on youtube.
# It can tell you the current time.
# It can tell you jokes.
# It can quit whenever we say quit.
# It can tell who he is.
# It can tell answers to questions like hello and fine.
# It can shutdown automatically.
# It can show news.
# It can tell you weather forcast.
# It can restart system.
# It can log out from the system.
# It can set timer.
print("To run the jarvis first you have to wait till when you don't get the word listening and then you have to say the commands that are writen in quotes and then it will run.")
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import pywhatkit
import os
import pyjokes
import cv2 # releated to files.
import winsound
#import python_weather
import datetime
from playsound import playsound
import time
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def wish():
hour = int(datetime.datetime.now().hour)
if hour >= 0 and hour < 12:
speak("Good Morning")
elif hour >= 12 and hour < 18:
speak("Good Afternoon")
else:
speak("Good Evening")
speak("I am jarvis sir , what can I do for you")
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language='en-in')
print(f"User said: {query}\n")
except Exception as e:
print("Say that again please...")
return "None"
return query
def SecurityCamera():
cam = cv2.VideoCapture(0)
while cam.isOpened():
ret,frame1 = cam.read()
ret,frame2 = cam.read()
diff = cv2.absdiff(frame1 , frame2)
gray = cv2.cvtColor(diff , cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
_, thresh = cv2.threshold(blur,20,255,cv2.THRESH_BINARY)
dilated = cv2.dilate(thresh , None , iterations=3)
contours, _ = cv2.findContours(dilated , cv2.RETR_TREE , cv2.CHAIN_APPROX_SIMPLE)
# cv2.drawContours(frame1 , contours, -1 , (0 , 255 , 0) , 2)
for c in contours:
if cv2.contourArea(c) < 5000:
continue
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(frame1 , (x , y) , (x + w , y + h) , (0 , 255 , 0) , 2)
winsound.Beep(500,100)
if cv2.waitKey(10) == ord('q'):
break
cv2.imshow('Dakshit cam' , frame1)
def take_snapshot():
#initializing cv2
videoCaptureObject = cv2.VideoCapture(0,cv2.CAP_DSHOW)
result = True
while(result):
#read the frames while the camera is on
ret,frame = videoCaptureObject.read()
#cv2.imwrite() method is used to save an image to any storage device
cv2.imwrite("C:/Users/Dakshit/Desktop/main folder/whitehat jr/camera/NewPicture1.jpg",frame)
result = False
# releases the camera
videoCaptureObject.release()
#closes all the window that might be opened while this process
cv2.destroyAllWindows()
# take_snapshot()
if __name__ == "__main__":
wish()
while True:
query = takeCommand().lower()
if 'wikipedia' in query:
speak('Searching Wikipedia...')
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences=2)
speak("According to Wikipedia")
print(results)
speak(results)
elif 'open youtube' in query:
webbrowser.open("https://www.youtube.com/")
elif 'snapshot' in query:
take_snapshot()
elif 'hello' in query:
speak("Hello sir How are you ")
elif 'fine' in query:
speak("that great sir please tell me what can I do for you")
elif 'who are you' in query:
speak("I am Jarvis and I am a fictional artificial intelligence that first appeared in the Marvel Cinematic Universe.")
elif 'play' in query:
whatShouldPlay = query.replace('play', '')
speak('playing ' + whatShouldPlay)
pywhatkit.playonyt(whatShouldPlay)
elif 'tell me a joke' in query:
speak(pyjokes.get_joke())
print(pyjokes.get_joke())
elif 'what is the time' in query:
strTime = datetime.datetime.now().strftime("%H:%M:%S")
speak(f"Sir, the time is {strTime}")
elif 'quit' in query:
speak("Bye Sir Have A Nice Day.")
speak("If You Want More Help Please call Me Again.")
speak("Thank You Sir")
exit()
elif 'camera' in query:
SecurityCamera()
elif 'open amazon' in query:
webbrowser.open("https://www.amazon.in/")
elif 'open citibank' in query:
webbrowser.open(".citibank.co.in/ibank/login/IQPin1.jsp?dOfferCode=PAYCCBILL")
elif 'open discord' in query:
webbrowser.open("https://discord.com/channels/777879401990717470/777879401990717473")
elif 'open whatsapp' in query :
codePath = "https://web.whatsapp.com/"
os.startfile(codePath)
elif 'open zoom' in query :
codePath = "https://zoom.us/"
os.startfile(codePath)
elif 'open python' in query :
codePath = "https://www.python.org/"
os.startfile(codePath)
elif 'open skype' in query :
codePath = "https://www.skype.com/en/"
os.startfile(codePath)
elif 'open lichess' in query :
codePath = "https://lichess.org/"
os.startfile(codePath)
elif 'open google' in query :
codePath = "https://www.google.com/"
os.startfile(codePath)
elif 'open flipkart' in query :
codePath = "https://www.flipkart.com/"
os.startfile(codePath)
elif 'shutdown' in query:
speak("Do you really want to shutdown your sysytem sir ?")
relpy = takeCommand().lower()
if 'yes' in relpy:
os.system('shutdown /s /t 1')
else:
speak("As you wish sir ! ")
elif 'show news' in query:
speak("Here are some top headlines ")
webbrowser.open("https://news.google.com/")
elif 'what is the weather today' in query:
speak("Weather for differnt cites today is")
#relpy = takeCommand().lower()
#country = relpy
webbrowser.open("https://www.ndtv.com/weather")
elif 'restart' in query:
speak("Do you really want to restart your sysytem sir ?")
relpy = takeCommand().lower()
if 'yes' in relpy:
os.system('shutdown /r /t 1')
else:
speak("As you wish sir ! ")
elif 'log out' in query:
speak("Do you really want to log out your sysytem sir ?")
relpy = takeCommand().lower()
if 'yes' in relpy:
os.system('shutdown -1')
else:
speak("As you wish sir ! ")
elif 'timer' in query:
speak("How many seconds to wait ")
seconds = int(input("How many seconds to wait ? "))
for i in range(seconds):
print(str(seconds - i) + " seconds remain ")
time.sleep(0.1)
|
aee36074db4ae9e22950597e4e9b3160ccab94cb | hrithikkothari1234/Sem-4 | /Python/exp2/remove_puncs.py | 193 | 4.3125 | 4 | """
To remove punctuations from a string
"""
user_str = input("Enter string to remove puncs")
import string
for c in string.punctuation:
user_str = user_str.replace(c,"")
print(user_str) |
3a12122d4e65fd58d473244fe50a9de3a1339b27 | austinjhunt/dailycodingproblem | /dcp2.py | 1,924 | 4.125 | 4 | #This problem was asked by Uber.
#Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
#For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
#Follow-up: what if you can't use division?
# First use division approach
def dcp2_wDiv(num_array):
product = 1
for num in num_array:
product = product * num
for i in range(len(num_array)):
num_array[i] = product / num_array[i]
return num_array
#print(dcp2_wDiv([1,2,3,4,5]))
# Now, if you cant divide?
def dcp2_woDiv(num_array):
# exclusively multiply everything
count = 0
new_num_array = []
for i in range(len(num_array)):
product = 1
print "\n\ni = " + str(i)
for j in range(0,i): #nums before current num
print "product =" + str(product) + "*" + str(num_array[j])
product = product * num_array[j]
count += 1
for k in range(i+1, len(num_array)):
print "product =" + str(product) + "*" + str(num_array[k])
product = product * num_array[k]
count += 1
print "product = " + str(product)
new_num_array.append(product)
print("Count =", count)
return new_num_array
#print(dcp2_woDiv([1,2,3,4,5]))
def newdcp2(num_array):
temp = 1
products = [None] * len(num_array)
for j in range(0, len(num_array)):
products[j] = 1;
for i in range(0,len(num_array)):
products[i] = temp
temp = temp * num_array[i]
# init temp to one for product on right side
for i in range(len(num_array) - 1, -1,-1):
products[i] = products[i] * temp
temp = temp * num_array[i]
return products
#print(newdcp2([1,2,3,4,5])
|
b9f88338e6f1344a2fd073a2946e304459166dca | meysamrsl/python-homwork-calculator-asistant | /mashghe shab.py | 3,219 | 4.21875 | 4 | num1 = float(input('Enter number one\n'))
num2 = float(input('Enter number two\n'))
opration = input('''What do you want to do:\n + addition\n - subtraction
* multiplication
/ division\n ''')
def calculator(addition):
if opration == '+':
print(f'addition is: {addition}')
addition = num1 + num2
calculator(addition)
def calculator(subtraction):
if opration == '-':
print(f'subtraction is: {subtraction}')
subtraction = num1 - num2
calculator(subtraction)
def calculator(multiplication):
if opration == '*':
print(f'multiplication is: {multiplication}')
multiplication = num1 * num2
calculator(multiplication)
def calculator(division):
if opration == '/':
print(f'division is: {division}')
division = num1 / num2
calculator(division)
###############################################################
command = input('che shekli mikhay?:\n')
if command == 'mosalas':
def Perimeter_Area(mohit_mosalas, masahat_mosalas):
if command2 == 'mohit':
print(f'mohit mosavi ast ba: {mohit_mosalas}')
elif command2 == 'masahat':
print(f'masahat mosavi ast ba: {masahat_mosalas}')
else:
print('not found')
command2 = input('mohit ya masahat?\n')
ghaede = float(input('ghaede ra vared konid\n'))
ertefa = float(input('ertefa ra vared konid\n'))
mohit_mosalas = ghaede * 3
masahat_mosalas = (ghaede * ertefa) / 2
Perimeter_Area(mohit_mosalas, masahat_mosalas)
elif command == 'mostatil':
def Perimeter_Area(mohit_mostatil, masahat_mostatil):
if command2 == 'mohit':
print(f'mohit mosavi ast ba: {mohit_mostatil}')
elif command2 == 'masahat':
print(f'masahat mosavi ast ba: {masahat_mostatil}')
else:
print('not found')
command2 = input('mohit ya masahat?\n')
tol = float(input('tol ra vared konid\n'))
arz = float(input('arz ra vared konid\n'))
mohit_mostatil = (tol + arz) * 2
masahat_mostatil = tol * arz
Perimeter_Area(mohit_mostatil, masahat_mostatil)
elif command == 'dayere':
def Perimeter_Area(mohit_dayere, masahat_dayere):
if command2 == 'mohit':
print(f'mohit mosavi ast ba: {mohit_dayere}')
elif command2 == 'masahat':
print(f'masahat mosavi ast ba: {masahat_dayere}')
else:
print('not found')
command2 = input('mohit ya masahat?\n')
shoa = float(input('shoa ra vared konid\n'))
mohit_dayere = (shoa * 2) * 3.14
masahat_dayere = (shoa ** 2) * 3.14
Perimeter_Area(mohit_dayere, masahat_dayere)
elif command == 'moraba':
def Perimeter_Area(mohit_moraba, masahat_moraba):
if command2 == 'mohit':
print(f'mohit mosavi ast ba: {mohit_moraba}')
elif command2 == 'masahat':
print(f'masahat mosavi ast ba: {masahat_moraba}')
else:
print('not found')
command2 = input('mohit ya masahat?\n')
zele_moraba = float(input('zele moraba ra vared konid\n'))
mohit_moraba = zele_moraba * 4
masahat_moraba = zele_moraba ** 2
Perimeter_Area(mohit_moraba, masahat_moraba)
else:
print('not found')
|
8505454b5478ae3ddaa8196c0a3f70e1e1575403 | leomcp/HackerRank_Solutions | /Problem Solving/Algorithms/Implementation/beautiful_days_at_the_movies.py | 407 | 3.59375 | 4 | def _get_reverse(num):
rev = 0
while(num > 0):
a = num % 10
rev = rev * 10 + a
num = num / 10
return rev
def beautifulDays(i, j, k):
noOfBDs = 0
for day in range(i, j+1):
revday = _get_reverse(day)
diff = abs(revday - day)
if (diff % k) == 0:
noOfBDs = noOfBDs + 1
return noOfBDs
print(beautifulDays(13, 45, 3)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.