blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f22beaf7e83ebd005ef175266dec05dd3e942aca | priyaVora/pythonProjects | /SimpleProjects/SimpleCalculator.py | 1,316 | 4.15625 | 4 | operations = {1: "Add", 2: "Subtract", 3: "Multiply", 4: "Divide"}
loop = True
user_selection = ""
while loop == True:
try:
for key, values in operations.items():
print(str(key) + ". " + values)
user_input = input("Please enter one of the operation types from above: ")
size = len(operations)
if int(user_input) > size:
loop = True
else:
user_selection = operations[int(user_input)]
print("User's Selection: " + user_selection)
loop = False
except ValueError:
print("\nInvalid Input!")
loop2 = True
a_Value = 0
b_Value = 0
while loop2 == True:
try:
a = input("Please enter the first number: ")
b = input("Please enter the second number: ")
a_Value = int(a)
b_Value = int(b)
c = ""
loop2 = False
except ValueError:
print("\nInvalid Input Error!")
loop2 = True
if user_selection == "Add":
c = a_Value + b_Value
loop2 = False
elif user_selection == "Subtract":
c = a_Value - b_Value
loop2 = False
elif user_selection == "Multiply":
c = a_Value * b_Value
loop2 = False
elif user_selection == "Divide":
c = a_Value / b_Value
loop2 = False
result = float(c)
print("\tResult: " + str(result))
|
f9af27555e1cf1a158d257a98d290fbdadf31861 | Laurensvaldez/PythonCrashCourse | /CH3: Introducing Lists/lists.py | 2,113 | 4.71875 | 5 | # a list is made with square brackets -> []
# for example:
names = ['Laurens', 'Elba', 'Jonathan', 'Vanessa', 'Domingo']
# if you want to access an item from the list you can use the index number
print (names[:2] )
# in this case you print the first two items given
# because in Python the first item in a data structure begins with the 0
# with thd : in front of the 2, you indicate you want every item to be print that comes before the index 2
# 'Jonathan' is index number 2 but in Python the given index will not be printed, its used as "until index number"
# with the second part of the code .title() you can use the title function to give the value a title output
# remember the stored value will not be changed, it will only be shown that way
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = "My first bicycle was a " + bicycles[0].title() + "."
print (message)
bicycles.append("mountainbike")
bicycles.insert(0,"gazelle")
# with the insert(0, "gazelle") you place the bicycle "gazelle" at the index number 0
print (bicycles)
bicycles.pop()
print (bicycles)
# with the del statement you can use the index number to delete a certain value
del bicycles[0]
print(bicycles)
# if we want to save the popped object you can use the next code
popped_bicycle = bicycles.pop()
print(bicycles)
print(popped_bicycle)
# you can also use the indexing method to pop a certain object from the list
first_owned = bicycles.pop(0)
print("The first bicycle I owned was a " + first_owned.title() + ".")
# you can use the "remove" method to remove an item by name, for example
bicycles.remove("cannondale")
print(bicycles)
# with the bicycles.sort() you can sort the permanently sort the order of a list
# with sorted(bicycles) you can temporarily sort the order of a list
# with the following statement you can reverse the order: bicycles.sort(reverse=True)
# for the temp solution you can you use
namen_lijst = ['Elba', 'Laurens', 'Estefania', 'Lopez', 'Salcedo', 'Valdez']
print(sorted(namen_lijst))
namen_lijst.reverse()
print(namen_lijst.sort())
print(len(namen_lijst)) |
ec8d02ebef9984e314adb2aa451dd261f3b24f10 | SkyfengBiuBiu/Introduction-to-Audio-Processing | /sgn2017/ex0/exercise0.py | 2,155 | 3.546875 | 4 | # coding: utf-8
# import Python modules
import sys
import numpy as np
import matplotlib.pyplot as plt
import scipy
from scipy.io import wavfile
from scipy import signal
# Read the wavefile: sound of plucking a guitar string
#This is my own audio file
#fs,x = wavfile.read('hall.wav')
fs,x = wavfile.read('gtr55.wav')
# For Windows, you can use winsound to play the audio file
# uncomment the following two line if you are on windows and want to play the audio file
# import winsound
# winsound.PlaySound('gtr55.wav', winsound.SND_FILENAME)
# Your code here: print out type, length of x, length of audio signal in seconds
# Hint: help()
print(type(x))
print(len(x))
print(len(x)/fs)
# Time-domain visualization of the signal
# Your code here: make the x-axis or time scale, should be same shape as x.
# Hint: use numpy.linspace to make an array containing the numbers you want
t = np.linspace(0,len(x)/fs,num=len(x))
# plotting
plt.subplot(3, 1, 1)
plt.plot( t, x )
plt.title('Time domain visualization of the audio signal')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.axis('tight')
plt.grid('on')
# Frequency domain visualization of the signal, logarithmic magnitude
# Your code here: frequency scale, fft with scipy
# Hint: Nyquist frequency, help()
max_freq = fs/2
X = scipy.fft(x)
winlen = 1024
win2=int(winlen/2)
frq_scale = np.linspace(0, max_freq, win2-1)
mag_scale = 20.0*np.log10(np.abs(X[0:win2-1]))
# plotting
plt.subplot(3, 1, 2)
plt.plot( frq_scale, mag_scale)
plt.title('Frequency domain visualization of the audio signal')
plt.axis('tight')
plt.grid('on')
plt.ylabel('Magnitude (dB)')
plt.xlabel('Frequency (Hz)')
# Your code here: Spectrogram of the audio signal
f,t,X = signal.spectrogram(x, fs)
mag_scale = 20*np.log10(1e-6+np.abs(X))
# plotting
plt.subplot(3, 1, 3)
plt.pcolormesh(t,f, mag_scale)
plt.xlabel('time (s)')
plt.ylabel('Frequency (Hz)')
plt.title('Log-magnitude spectrogram')
plt.colorbar()
# Show the figure.
plt.tight_layout()
plt.savefig('myfig')
plt.show()
plt.close()
# Bonus points: record your own audio file; save the figure
# Please see the previous content, and "hall.wav" is my own audio file
|
c0e632ae148d4bc7346a81f0883e0018f6e5ec88 | jordan-dinwiddy/python-play | /basics/function1.py | 421 | 4.09375 | 4 | #!/usr/bin/python
def fib(n): # write Fibonacci series up to n
"""Print a Fibonacci series up to n."""
# The above line is called the docstring
a, b = 0, 1
while a < n:
print a,
a, b = b, a+b
fib(2000);
f = fib
f(100);
# Some might say that fib is really a procedure not a function
# because it doesn't return a value. In python it is a function
# and it returns a None. It's a special object
print f(0)
|
f2a642e7119e197b3bb4a5ce824c6890be8dee0e | freebz/Python-Cookbook | /ch05/ex5-4.py | 953 | 3.59375 | 4 | # 5.4 바이너리 데이터 읽고 쓰기
# 파일 전체를 하나의 바이트 문자열로 읽기
with open('somefile.bin', 'rb') as f:
data = f.read()
# 바이너리 데이터 파일에 쓰기
with open('somefile.bin', 'wb') as f:
f.write(b'Hello World')
# 토론
# 텍스트 문자열
t = 'Hello World'
t[0]
# 'H'
for c in t:
print(c)
# H
# e
# l
# l
# o
# ...
# 바이트 문자열
b = b'Hello World'
b[0]
# 72
for c in b:
print(c)
# 72
# 101
# 108
# 108
# 111
# ...
with open('somefile.bin', 'rb') as f:
data = f.read(16)
text = data.decode('utf-8')
with open('somefile.bin', 'wb') as f:
text = 'Hello World'
f.write(text.encode('utf-8'))
import array
nums = array.array('i', [1, 2, 3, 4])
with open('data.bin', 'wb') as f:
f.write(nums)
import array
a = array.array('i', [0, 0, 0, 0, 0, 0, 0, 0])
with open('data.bin', 'rb') as f:
f.readinto(a)
# 16
a
array('i', [1, 2, 3, 4, 0, 0, 0, 0])
|
69ddea33daae9524818d3eab1972776568f25f2e | SharminAkter93/Linear_project | /Queue_implementation.py | 2,304 | 4.15625 | 4 | # Initialize a queue
queue_exm = []
# Adding elements to the queue
queue_exm.append('x')
queue_exm.append('y')
queue_exm.append('z')
print("Queue before any operations")
print(queue_exm)
# Removing elements from the queue
print("\nDequeuing items")
print(queue_exm.pop(0))
print(queue_exm.pop(0))
print(queue_exm.pop(0))
print("\nQueue after deque operations")
print(queue_exm)
# Creating the queue class
class Queue:
def __init__(self):
self.queue = list()
def element_add_exm(self,data):
# Using the insert method
if data not in self.queue:
self.queue.insert(0,data)
return True
return False
def leng(self):
return len(self.queue)
Queue_add = Queue()
Queue_add.element_add_exm("Mercedes Benz")
Queue_add.element_add_exm("BMW")
Queue_add.element_add_exm("Maserati")
Queue_add.element_add_exm("Ferrari")
Queue_add.element_add_exm("Lamborghini")
print("Queue's Length: ",Queue_add.leng())
# Creating the queue class
class Queue:
def __init__(self):
self.queue = list()
def element_add_exm(self,data):
# Using the insert method
if data not in self.queue:
self.queue.insert(0,data)
return True
return False
# Removing elements
def element_remove_exm(self):
if len(self.queue)>0:
return self.queue.pop()
return ("Empty Queue")
queu = Queue()
queu.element_add_exm("A")
queu.element_add_exm("B")
queu.element_add_exm("C")
queu.element_add_exm("D")
print(queu)
print(queu.element_remove_exm())
print(queu.element_remove_exm())
# Queue short
import queue
queu = queue.Queue()
queu.put(5)
queu.put(24)
queu.put(16)
queu.put(33)
queu.put(6)
# Using bubble sort algorithm for sorting
i = queu.qsize()
for x in range(i):
# Removing elements
n = queu.get()
for j in range(i-1):
# Removing elements
y = queu.get()
if n > y :
# putting smaller elements at beginning
queu.put(y)
else:
queu.put(n)
n = y
queu.put(n)
while (queu.empty() == False):
print(queu.queue[0], end = " ")
queu.get()
|
9b727d5e6536cce2fc0b734783b755cfdf6be352 | titohayward/Engr-216-Lab-Group-B-Code | /finite diff functions.py | 1,617 | 3.765625 | 4 | # Juan Hayward #
### this is a general finite difference function
import numpy as np
time = np.array([0,2,4,6,8,10,12,14,16])
pos = np.array([0,0.7,1.8,3.4,5.1,6.3,7.3,8.0,8.4])
def velocity(pos_array,time_array):
print("pos length:", len(pos_array), "time length:", len(time_array))
if len(pos_array) != len(time_array):
print("Array length does not match. Please check your data and try again.")
# create vel array
der_list = []
for i in range(len(pos_array)-1):
vel = (( pos_array[i+1] - pos_array[i]) / (time_array[i+1] - time_array[i]))
der_list.append(vel)
derivative = np.array([der_list])
return derivative
def acceleration(vel_array,time_array):
# We want an adjusted time array with a new length in the same time range.
# We assume that the time intervals are evenly spaced.
vel_array = vel_array[0] # we want the first item
newLength = np.array([(np.max(time_array)-np.min(time_array))/(len(vel_array)-1)])
timeArrayNew = np.array(len(vel_array) * [newLength])
print("velocity length:", len(vel_array), "time length:", len(timeArrayNew))
if len(vel_array) != len(timeArrayNew):
print("Array length does not match. Please check your data and try again.")
# create vel array
der_list = []
for i in range(len(vel_array)-1):
der_1 = ( vel_array[i+1] - vel_array[i])
time_1 =timeArrayNew[i]
accel = ( der_1/ time_1)
der_list.append(accel)
derivative = np.array([der_list])
return derivative
vel = velocity(pos,time)
print(vel)
acc = acceleration(vel,time)
print(acc)
|
7801dce80fd2a586745f1e0155cbc6b7079cd849 | dolooo/JS-Projekt-Saper | /Interface.py | 10,801 | 3.640625 | 4 | from tkinter import *
import time
class MainWindow:
"""główne okienko gry"""
def __init__(self, controller):
"""ustawienia parametrów głównego okienka gry"""
self._window = Tk()
self._controller = controller
self._window.title("Saper")
self._window.iconbitmap("images/icon.ico")
# wykrywanie wciskanych przycisków
self._window.bind("<Key>", lambda fun: controller.pressedKey(fun.char))
# menu główne
self.mainMenu = MainMenu(self._window, controller)
# mapa gry
self.gameMap = GameMap(self._window, controller)
# licznik czasu
self.gameMap.timer()
def windowLoop(self):
self._window.mainloop()
class MainMenu:
"""menu główne: 3 pola tekstowe do wprowadzenia parametrów rozgrywki oraz przycisk rozpoczynający nową grę"""
def __init__(self, window, controller):
self._window = window
# tekst oraz pole tekstowe do wprowadzenia szerokosci mapy
self._labelWidth = Label(self._window, text="Szerokość")
self._labelWidth.grid(row=1, column=0, sticky="e")
self._entryWidth = Entry(self._window)
self._entryWidth.grid(row=1, column=1)
# -||- do wprowadzenia wysokości mapy
self._labelHeight = Label(self._window, text="Wysokość")
self._labelHeight.grid(row=2, column=0, sticky="e")
self._entryHeight = Entry(self._window)
self._entryHeight.grid(row=2, column=1)
# -||- do wprowadzenia liczby min na mapie
self._labelMines = Label(self._window, text="Liczba min")
self._labelMines.grid(row=3, column=0, sticky="e")
self._entryMines = Entry(self._window)
self._entryMines.grid(row=3, column=1)
# przycisk rozpoczęcia nowej gry
self._buttonStart = Button(self._window, text="Nowa Gra")
self._buttonStart.grid(columnspan=2)
self._buttonStart.bind("<Button-1>", lambda fun: controller.newGame())
self._labelError = Label(self._window, text="", fg="red")
def getEntrySettings(self):
return self._entryWidth.get(), self._entryHeight.get(), self._entryMines.get()
def showError(self, comment):
self._labelError.config(text=comment)
self._labelError.grid(row=6, columnspan=2)
def clearEntryData(self):
self._labelError.grid_forget()
class GameMap:
"""mapa gry która po prawej stronie wyświetla liczbę min oraz oflagowanych pól, a także licznik czasu"""
def __init__(self, window, controller, positionx=3, positiony=1):
self._controller = controller
self._posX = positionx
self._posY = positiony
self._window = window
self._mapOfButtons = []
self._markedMines = 0
self._timerStarted = False
self._timerRunning = False
self._time = time.time()
self._flagImage = PhotoImage(file='images/flag.png')
self._mineImage = PhotoImage(file='images/mine.png')
self._textNumberOfMines = StringVar()
self._textMarkedMines = StringVar()
self._textTimer = StringVar()
self._textTimer.set("0")
self._labelGameResult = Label(self._window, text="white")
self._labelEmpty = Label(self._window, image='', width="2")
self._labelMarkedMines = Label(self._window, textvariable=self._textMarkedMines)
self._labelMarkedIcon = Label(self._window, image=self._flagImage)
self._labelMines = Label(self._window, textvariable=self._textNumberOfMines)
self._labelMinesIcon = Label(self._window, image=self._mineImage)
self._labelTimer = Label(self._window, textvariable=self._textTimer)
def newMap(self, height, width, mines):
"""tworzenie nowej mapy o określonych wymiarach i liczbie min"""
self._markedMines = 0
self._textNumberOfMines.set(": " + str(mines))
self._textMarkedMines.set(": 0")
self._labelGameResult.config(text="", bg="white")
self._labelGameResult.grid(column=self._posX, row=self._posY, columnspan=width, sticky="news")
self._labelTimer.grid(column=self._posX + width + 1, row=self._posY, columnspan=2)
self._labelEmpty.grid(column=width + self._posX + 1, row=self._posY + 1, rowspan=2)
self._labelMinesIcon.grid(column=width + self._posX + 2, row=self._posY + 1)
self._labelMines.grid(column=width + self._posX + 3, row=self._posY + 1)
self._labelMarkedIcon.grid(column=width + self._posX + 2, row=self._posY + 2)
self._labelMarkedMines.grid(column=width + self._posX + 3, row=self._posY + 2)
self.drawButtons(width, height)
self._timerStarted = True
self._timerRunning = False
def win(self):
"""wyświetla komunikat o wygranej, dezaktywuje wszystkie przyciski i zatrzymuje stoper """
self._labelGameResult.config(text="WYGRALES!", bg="green")
[[x.disable() for x in y] for y in self._mapOfButtons]
self._timerRunning = False
def defeat(self, x, y):
"""wyświetla komunikat o przegranej, dezaktywuje wszystkie przyciski i zatrzymuje stoper """
self._labelGameResult.config(text="PRZEGRALES!", bg="red")
[[xx.disable() for xx in yy] for yy in self._mapOfButtons]
self._mapOfButtons[y][x].mark(marked="minered")
self._timerRunning = False
def setButtonMark(self, pos_x, pos_y, what):
"""funkcja oznaczająca przycisk.
flag - "tu jest mina",
empty - brak oznaczenia,
questionmark - "tu może byc mina".
W przypadku "flag" blokuje możliwość wciśnięcia przycisku."""
if what == "flag":
self._markedMines += 1
self._mapOfButtons[pos_y][pos_x].disable()
self._mapOfButtons[pos_y][pos_x].mark("flag")
elif what == "empty":
self._mapOfButtons[pos_y][pos_x].mark("empty")
elif what == "questionmark":
self._markedMines -= 1
self._mapOfButtons[pos_y][pos_x].active()
self._mapOfButtons[pos_y][pos_x].mark("questionmark")
self._textMarkedMines.set(": " + str(self._markedMines))
def showMinePlace(self, x, y, what=""):
"""funkcja odkrywająca pole, na którym znajduje się mina"""
self._mapOfButtons[y][x].mark(marked="highlight")
if what != "onlyColor":
self._mapOfButtons[y][x].mark(marked="mine")
def uncoverPlace(self, x, y, number):
"""wywołanie odkrycia pojedynczego pola"""
self._mapOfButtons[y][x].uncover(number)
def drawButtons(self, width, height):
"""tworzy siatkę przycisków przy pomocy klasy GameButton"""
self._mapOfButtons = [[GameButton(self._window, i, j, self._controller.LMB, self._controller.RMB,
i + self._posX, j + self._posY + 1)
for i in range(width)] for j in range(height)]
def timer(self):
"""funkcja odpowiedzialna za licznik czasu"""
if self._timerRunning:
self._textTimer.set(str("%3.1f" % (time.time() - self._time)))
elif self._timerStarted:
self._time = time.time()
self._textTimer.set(str(0))
self._timerRunning = True
self._timerStarted = False
self._window.after(100, self.timer)
class GameButton:
"""klasa odpowiedzialna za przyciski na mapie gry"""
def __init__(self, window, i, j, funLMB, funRMB, positionx, positiony):
"""ustawianie podstawowych parametrów przycisków"""
self.window = window
self.posX = positionx
self.posY = positiony
self.questionMark_image = PhotoImage(file='images/question.png')
self.mine_image = PhotoImage(file='images/mine.png')
self.mineRed_image = PhotoImage(file='images/red_mine.png')
self.flag_image = PhotoImage(file='images/flag.png')
self.number_images = {0: PhotoImage(file='images/clear.png'),
1: PhotoImage(file='images/n1.png'),
2: PhotoImage(file='images/n2.png'),
3: PhotoImage(file='images/n3.png'),
4: PhotoImage(file='images/n4.png'),
5: PhotoImage(file='images/n5.png'),
6: PhotoImage(file='images/n6.png'),
7: PhotoImage(file='images/n7.png'),
8: PhotoImage(file='images/n8.png')}
self.empty_image = PhotoImage(file='images/empty.png')
self.thisButton = Button(self.window, bg='grey85', disabledforeground="black", relief=RAISED, overrelief=GROOVE,
width=20, image=self.empty_image, command=(lambda a=i, b=j: funLMB(a, b)))
self.thisButton.bind("<Button-3>", lambda fun, a=i, b=j: funRMB(a, b))
self.thisButton.grid(row=positiony, column=positionx, sticky="news", padx=0, pady=0)
def uncover(self, number=0):
"""odkrywa pojedyncze pole i wyświetla odpowiednią liczbę sąsiadujących min"""
self.thisButton.destroy()
self.thisButton = Label(image=self.number_images[number], bg="grey85", width=20, height=20)
self.thisButton.grid(row=self.posY, column=self.posX, sticky="news")
def mark(self, marked="empty"):
"""minered - dezaktywuje dany przycisk i w jego miejscu wyswietla czerwoną minę
mine - dezaktywuje dany przycisk i wyświetla zwykłą minę
highlight - zmienia kolor pola na jaśniejszy
flag - ustawia grafikę jako flagę
questionmark - ustawia grafikę jako pytajnik
empty - ustawia przycisk jako puste pole (defaultowe wywołanie) """
if marked == "minered":
self.thisButton.destroy()
self.thisButton = Label(image=self.mineRed_image, width=20, height=20)
elif marked == "mine":
self.thisButton.destroy()
self.thisButton = Label(image=self.mine_image, width=20, height=20)
elif marked == "highlight":
self.thisButton.config(bg="grey65")
elif marked == "flag":
self.thisButton.config(image=self.flag_image)
elif marked == "questionmark":
self.thisButton.config(image=self.questionMark_image)
elif marked == "empty":
self.thisButton.config(image=self.empty_image)
self.thisButton.grid(row=self.posY, column=self.posX, sticky="news")
def disable(self):
"""funkcja do dezaktywacji przycisku"""
self.thisButton.config(stat=DISABLED)
def active(self):
"""funkcja do aktywacji przycisku"""
self.thisButton.config(stat=ACTIVE)
|
c8339212ca119a46b22abbae4b0a36a8f1038c28 | HenriqueHideaki/100DaysOfAlgo | /Day 75/LCS.py | 1,400 | 4.09375 | 4 | ''' Problem statement : Given an array of integers, find the length of the longest sub-sequence such that elements in the
subsequence are consecutive integers, the consecutive numbers can be in any order
Algorithm:
Create an empty hash.
Insert all array elements to hash.
Do following for every element arr[i]
Check if this element is the starting point of a subsequence. To check this, simply look for arr[i] – 1 in the hash, if not found, then this is the first element a subsequence.
If this element is the first element, then count the number of elements in the consecutive starting with this element. Iterate from arr[i] + 1 till the last element that can be found.
If the count is more than the previous longest subsequence found, then update this.
Time complexity : O(n)
Space complexity : O(n)
'''
# Python program to find longest contiguous subsequence
from sets import Set
def findLongestConseqSubseq(arr, n):
s = Set()
ans = 0
# Hash all the array elements
for ele in arr:
s.add(ele)
# check each possible sequence from the start
# then update optimal length
for i in range(n):
# if current element is the starting
# element of a sequence
if (arr[i]-1) not in s:
# Then check for next elements in the
# sequence
j = arr[i]
while(j in s):
j += 1
# update optimal length if this length
# is more
ans = max(ans, j-arr[i])
return ans
|
a875ab86b2b7bdb42675b5a9b4004994a9791a62 | mczekajski/15game | /main.py | 2,571 | 3.515625 | 4 | from random import randint, choice
from tkinter import *
class Game():
base_grid = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 0]
]
grid = base_grid
def get_position(self, num):
row = 0
for x in self.grid:
if num in x:
return(row, x.index(num))
row += 1
def is_next_to_zero(self, num):
if num == 0:
return False
num_pos = self.get_position(num)
zero_pos = self.get_position(0)
if abs(num_pos[0] - zero_pos[0]) == 1 and num_pos[1] - zero_pos[1] == 0:
return True
elif num_pos[0] - zero_pos[0] == 0 and abs(num_pos[1] - zero_pos[1]) == 1:
return True
else:
return False
def move(self, num):
if self.is_next_to_zero(num):
num_pos = self.get_position(num)
zero_pos = self.get_position(0)
self.grid[zero_pos[0]][zero_pos[1]] = num
self.grid[num_pos[0]][num_pos[1]] = 0
def shuffle(self, steps):
game.move(15)
game.move(11)
game.move(10)
game.move(6)
nums_to_shuffle = []
chosen_nums = set()
for x in range(steps):
for y in range(1, 16):
if self.is_next_to_zero(y):
nums_to_shuffle.append(y)
if len(chosen_nums) < 15:
for z in range(10):
chosen_num = nums_to_shuffle[randint(1, len(nums_to_shuffle)) - 1]
if chosen_num not in chosen_nums:
break
else: chosen_nums = set()
self.move(chosen_num)
if choice([True, False]):
chosen_nums.add(chosen_num)
# Shuffle buttons according to the grid
def create_buttons():
for x in range(9):
buttons.append(Button(root, text="{}".format(x+1), bg="#99ccff", padx=35, pady=20, font="verdana", command=lambda x=x: button_click(x+1)))
for x in range(9,15):
buttons.append(Button(root, text="{}".format(x+1), bg="#99ccff", padx=30, pady=20, font="verdana", command=lambda x=x: button_click(x+1)))
def redraw_buttons():
for x in range(15):
pos = game.get_position(x+1)
buttons[x].grid(row=pos[0], column=pos[1])
def button_click(num):
game.move(num)
redraw_buttons()
game = Game()
game.shuffle(5000)
root = Tk()
root.title("15 game")
root.resizable(0, 0)
root.iconbitmap('tiles.ico')
buttons = []
create_buttons()
redraw_buttons()
root.mainloop()
|
420902bcaf92c3b054d4819bd1bfa50df4e12977 | marinnaricke/CMSC201 | /Homeworks/hw4/hw4_part3.py | 696 | 4.3125 | 4 | #File: hw4_part3.py
#Author: Marinna Ricketts-Uy
#Date: 9/30/15
#Lab Section: 17
#UMBC Email: pd12778@umbc.edu
#Description: This program asks the user for input to determine whether a
# subject can be studied or not.
def main():
#initialize variable
size = 10
subjects_list = [None]*size
for n in range(size):
subjects_list[n] = input("Please enter a subject: ")
for s in subjects_list:
#check each string in the list
#if the string ends in 'ology',print 'You can study' followed by string
#if not, print the string
if s[-5:] == 'ology' :
print("You can study " + s)
else:
print(s)
main()
|
0f4fb1a54e06d235c4216627a71fc892f9baa42c | rrang004/Backup-Renamer | /backup renamer 2000 v1.py | 1,061 | 3.578125 | 4 | #This script was created to aid me in renaming instrument stem files by removing the backup date and time
#Wanna delete 25 characters, from ( to )
import os
#os.listdir(os.curdir)
print("backup renamer 2000 v1")
for filename in os.listdir("."):
print(filename)
curName = filename
print("curName = " + curName)
newName = [] #we use a list to build the string but we will convert it to a real string once we are done
parensFlag = False
for c in curName: #iterate through the current file so we can find and create a new name
print(c)
if c == "(":
newName = newName[:-1] #remove the space by splicing
print("setting parensFlag to true")
parensFlag = True
continue
if c == ")":
print("setting parensFlag to false")
parensFlag = False
continue
if not parensFlag:
newName.append(c)
newNameStr = ''.join(newName)
print("newName = " + newNameStr)
os.rename(curName, newNameStr) |
d9711cbd3d92a6d1ad6b330c9648813942fb5004 | NickBryson/My_Projects | /Shipping_Cost.py | 1,519 | 4.03125 | 4 | def cost_of_ground_shipping(weight):
cost = 0
if (weight <= 2):
cost = (weight * 1.50) + 20.00
elif (weight > 2) and (weight <= 6):
cost = (weight * 3.00) + 20.00
elif (weight > 6) and (weight <= 10):
cost = (weight * 4.00) + 20.00
else:
cost = (weight * 4.75) + 20.00
return cost
cost_of_premium_shipping = 125.00
def cost_of_drone_shipping(weight):
cost = 0
if (weight <= 2):
cost = weight * 4.50
elif (weight > 2) and (weight <= 6):
cost = weight * 9.00
elif (weight > 6) and (weight <= 10):
cost = weight * 12.00
else:
cost = weight * 14.25
return cost
def cheapest_shipping_cost(weight):
ground_shipping = cost_of_ground_shipping(weight)
drone_shipping = cost_of_drone_shipping(weight)
premium_shipping = cost_of_premium_shipping
if (ground_shipping < drone_shipping) and (ground_shipping < premium_shipping):
return 'The cheapest shipping method is Ground Shipping. It will cost: '+str(ground_shipping)+'.'
elif (drone_shipping < ground_shipping) and (drone_shipping < premium_shipping):
return 'The cheapest shipping method is Drone Shipping. It will cost: '+str(drone_shipping)+'.'
elif (premium_shipping < ground_shipping) and (premium_shipping < drone_shipping):
return 'The cheapest shipping method is Premium Shipping. It will cost: '+str(premium_shipping)+'.'
else:
return 'Unable to calculate shipping cost for you, please try again later.'
print(cheapest_shipping_cost(40.5)) |
3621c1e421286c7a64134cd72d4432868fa8b5d3 | anantkaushik/Competitive_Programming | /Python/GeeksforGeeks/search-in-a-rotated-array.py | 1,428 | 4.09375 | 4 | """
Problem Link: https://practice.geeksforgeeks.org/problems/search-in-a-rotated-array4618/1
Given a sorted and rotated array A of N distinct elements which is rotated at some point, and given an element key.
The task is to find the index of the given element key in the array A.
Example 1:
Input:
N = 9
A[] = {5, 6, 7, 8, 9, 10, 1, 2, 3}
key = 10
Output:
5
Explanation: 10 is found at index 5.
Example 2:
Input:
N = 4
A[] = {3, 5, 1, 2}
key = 6
Output:
-1
Explanation: There is no element that has value 6.
Your Task:
Complete the function search() which takes an array arr[] and start, end index of the array and the K as input parameters,
and returns the answer.
Expected Time Complexity: O(log N).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ N ≤ 107
0 ≤ A[i] ≤ 108
1 ≤ key ≤ 108
"""
class Solution:
def search(self, A : list, l : int, h : int, key : int):
while l < h:
mid = (l+h)//2
if A[mid] == key:
return mid
if A[l] < A[h]:
if A[mid] < key:
l = mid + 1
else:
h = mid - 1
else:
if (A[mid] < A[h] and (key <= A[h] and key > A[mid])) or (A[mid] > A[h] and (key <= A[h] or key > A[mid])):
l = mid + 1
else:
h = mid - 1
return l if A[l] == key else -1
|
4c469013f10bd6093eaf6a907a2039cb3ebc4b7d | dabaicai233/Base-Prooject | /机试题.py | 4,881 | 3.625 | 4 | #第一题:1.设计一个函数,传入两个代表日期的字符串,
# 如“2018-2-26”、“2017-12-12”,计算两个日期相差多少天
def main(str1,str2):
import datetime
str1 = "2018-2-26"
str2 = "2017-12-12"
str1 = str1.split("-")
str2 = str2.split("-")
days =abs(datetime.datetime(int(str2[0]), int(str2[1]), int(str2[2])) - datetime.datetime(int(str1[0]), int(str1[1]),int(str1[2])))
return days
print(main("2018-2-26","2017-12-12"))
#
# #第二题:2.反转密码
#例如:‘123456’ ——> “654321”
#要求:不得利用系统提供的反转方法,逻辑思路自己写
#方式一
str1="123456"
print(str1[::-1])
#方式二
str1="123456"
str2=""
for i in range(len(str1)):
str2+=str1[len(str1)-1-i]
print(str2)
# #第三题:有5个人坐在一起,问第五个人多少岁?
# 他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。
# 问第三个人,又说比第2人大两岁。问第2个人,
# 说比第一个人大两岁。最后问第一个人,他说是10岁。
# 请问第五个人多大?
def func(per):
if per==1:
return 10
else:
return func(per-1)+2
print(func(5))
#第四题:4.给定一个字符串 返回对字符串进行压缩的结果
#例如:“aaabcaaddbbc” ——> “a3b1c1a2d2b2c1”
def zip(str1):# 声明一个变量记录个数:
count = 1# 从第一个字符开始记录
ch = str1[0]# 声明一个变量用于记录最后的压缩结果
res = ""# 从第二个字符开始遍历字符串开始
for index in range(1, len(str1)):
if str1[index] == ch:
count += 1
else:# 把结果拼接在 res 上
res = "%s%s%d" % (res, ch, count) # 继续向下查询下一个字符
ch = str1[index] # 计数器归1
count = 1# 将最后一个遍历的字符添加上
res = "%s%s%d" % (res, ch, count)
return res
print(zip("aabbccaabcd"))
#第五题:
"""
设计一个函数,对传入的字符串(假设字符串中只包含小写字母和空格)
进行加密操作,
加密的规则是a变d,b变e,c变f,……,x变a,y变b,z变c,
空格不变,返回加密后的字符串
97 98 99 100 x = 120(97) y = 121(98) z = 122(99)
"""
def encryption(str1):
#声明一个字符串用于接收最后的结果
res = ""
#遍历每一个字符 x y z 之前都是+3
for s in str1:
value = ord(s)
if 97 <= value < 120:
res += chr(value + 3)
elif 120 <= value < 123:
res += chr(value - 23)
else:
res += chr(value)
return res
print(encryption("abcdxyz efg"))
#第六题
import random
str1=""
for i in range(4):
n=random.randrange(0,3)
if n==0:
num=random.randrange(65,91)
str1+=chr(num)
elif n==1:
j=random.randrange(97,123)
str1+=chr(j)
else:
k=random.randrange(0,10)
str1+=str(k)
print(str1)
#第七题
def func1(str1):
dict1={}
for i in str1:
if i not in dict1:
dict1[i]=1
else:
dict1[i]+=1
for k in dict1.keys():
if dict1[k]==max(dict1.values()):
return k,max(dict1.values())
print(func1("aaaaahuuph"))
#第八题
import re
#方式一
def getsum(str1):
#对字符串使用非数字进行切割
pattern = re.compile(r"[^0-9]")
#切割完成的列表
res_list = pattern.split(str1)
#去除列表中的空字符
count = res_list.count("")
for i in range(count):
res_list.remove("")
#对列表中的数字进行拼接
res = res_list[0]
#记录最后的和
sum = int(res_list[0])
for i in range(1, len(res_list)):
res = "%s + %s" % (res, res_list[i])
sum += int(res_list[i])
return "%s = %d" % (res, sum)
print(getsum("12agdas34hjhfa67"))
#方式二
def getsum(str1):
list1 = re.split(r"[a-zA-Z]+",str1)
s = 0
for num in list1:
if num != "":
s += int(num)
#第九题:
'''
利用装饰器单例模式完成如下程序:(10分)
声明一个用户单例类:
特征描述:用户名,密码,性别
行为描述:发说说,上传照片 点赞 【函数内部功能使用 print 语句打印即可】
实例化对象,调用对应的功能
'''
def single(cls):
instances = {}
def wrapper(*args, **kw):
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return wrapper
@single
class User():
def __init__(self, username, password, sex):
self.username = username
self.password = password
self.sex = sex
def say(self):
print("发表说说")
def upload_pic(self):
print("上传照片")
def price(self):
print("点赞")
user = User("杨阳", "123456", "女")
user.say()
user.upload_pic()
user.price()
|
d20c355670f14a4cddd8c618dc76eb666056c250 | alonso121198/Videogame_FunctionWar | /Ejemplos_arcade/Mecanicas/FunctionWar.py | 5,560 | 3.8125 | 4 | import random
import arcade
SPRITE_SCALING_PLAYER = 0.5
SPRITE_SCALING_COIN = 0.2
SPRITE_SCALING_LASER = 0.8
COIN_COUNT = 50
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BULLET_SPEED_X = 5
BULLET_SPEED_Y = 5
class MyGame(arcade.Window):
""" Main application class. """
def __init__(self):
""" Initializer """
# Call the parent class initializer
# con esto creo la pantalla
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, "Sprites and Bullets Demo")
# Variables that will hold sprite lists
self.player_list = None # mi jugador
self.coin_list = None # las monedas del juego
self.bullet_list = None # las monedas
# Set up the player info
self.player_sprite = None # el sprite
self.score = 0 # contador de puntos
# Don't show the mouse cursor
# para que no se vea el mouse
self.set_mouse_visible(False)
# el color del fondo
arcade.set_background_color(arcade.color.AMAZON)
def setup(self):
""" Set up the game and initialize the variables. """
# inicializamos el juego
# Sprite lists
self.player_list = arcade.SpriteList() # sera lista de personajes
self.coin_list = arcade.SpriteList() # sera lista de monedas
self.bullet_list = arcade.SpriteList() # lista de disparos
# Set up the player
self.score = 0
# Image from kenney.nl
# cargamos el sprite del jugador
self.player_sprite = arcade.Sprite("character.png", SPRITE_SCALING_PLAYER)
# establecemos el inicio de posicion de nuestro jugador
self.player_sprite.center_x = 50
self.player_sprite.center_y = 70
# lo agregamos a la lista de nuestros jugadores
self.player_list.append(self.player_sprite)
# Create the coins
for i in range(COIN_COUNT):
# Create the coin instance
# Coin image from kenney.nl
# cargamos las monedas
coin = arcade.Sprite("coin_01.png", SPRITE_SCALING_COIN)
# Position the coin
coin.center_x = random.randrange(SCREEN_WIDTH)
coin.center_y = random.randrange(120, SCREEN_HEIGHT)
# Add the coin to the lists
# lo agregamos a la lista
self.coin_list.append(coin)
# Set the background color
# esto aun nose para que sirve
arcade.set_background_color(arcade.color.AMAZON)
def on_draw(self):
"""
Render the screen.
"""
# This command has to happen before we start drawing
arcade.start_render()
# Draw all the sprites.
# dibujamos los sprites como lo deseamos
self.coin_list.draw()
self.bullet_list.draw()
self.player_list.draw()
# Render the text
# dibujamos el puntaje en la parte superior derecha
arcade.draw_text(f"Score: {self.score}", 10, 20, arcade.color.WHITE, 14)
# define el movimiento del personaje
def on_mouse_motion(self, x, y, dx, dy):
"""
Called whenever the mouse moves.
"""
# hazlo aparecer donde este mi jugador en el mouse
self.player_sprite.center_x = x
self.player_sprite.center_y = y
# accion cuando se presiona el mouse
def on_mouse_press(self, x, y, button, modifiers):
"""
Called whenever the mouse button is clicked.
"""
# Create a bullet
# carga el disparo
bullet = arcade.Sprite("laserBlue01.png", SPRITE_SCALING_LASER)
# The image points to the right, and we want it to point up. So
# rotate it.
# rotas la imagen
# como parte rotado la imagen
bullet.angle = 45
# Position the bullet
# comienza de la ubicacion del jugador
bullet.center_x = self.player_sprite.center_x
# pero desde la base de la cabeza de mi sprite jugador sale
bullet.bottom = self.player_sprite.top
# la velocidad con que cambia mi disparo automaticamente
bullet.change_y = BULLET_SPEED_Y
bullet.change_x = BULLET_SPEED_X
# Add the bullet to the appropriate lists
# añade un disparo a la lista
self.bullet_list.append(bullet)
# la actualizacion en cada frame
def update(self, delta_time):
""" Movement and game logic """
# Call update on all sprites
# actualiza tanto las monedas como las balas
self.coin_list.update()
self.bullet_list.update()
# Loop through each bullet
for bullet in self.bullet_list:
# Check this bullet to see if it hit a coin
# si disparo(s) choca con moneda(s)
hit_list = arcade.check_for_collision_with_list(bullet, self.coin_list)
# If it did, get rid of the bullet
# si choco eliminalo de la lista
if len(hit_list) > 0:
bullet.remove_from_sprite_lists()
# For every coin we hit, add to the score and remove the coin
for coin in hit_list:
coin.remove_from_sprite_lists()
self.score += 1 # agrega a la puntuacion
# If the bullet flies off-screen, remove it.
# si un disparo se escapo de la pantalla eliminalo
if bullet.bottom > SCREEN_HEIGHT:
bullet.remove_from_sprite_lists()
# inicio
def main():
window = MyGame()
window.setup()
arcade.run()
if __name__ == "__main__":
main()
|
02af04a2cb8d5de1c50241685b200525739e16a8 | Lolirofle/Toabot | /bin/external_commands/wikipedia | 1,806 | 3.796875 | 4 | #!/usr/bin/python
import sys
import codecs
import wikipedia
import sqlite3
# Database tools. Mainly used for caching the results from data fetching
def dbLookupEntry(db,title):
returnValue = None
try:
db.execute('SELECT content FROM wiki_entries WHERE title=?',(title,))
returnValue = db.fetchone()
if returnValue:
returnValue = returnValue[0]
except sqlite3.OperationalError as e:
if e.args[0].startswith("no such table"):
# Create table if it doesn't exist
db.execute('''CREATE TABLE wiki_entries (id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT UNIQUE,content TEXT,last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
connection.commit()
return dbLookupEntry(db,title)
else:
raise e
return returnValue
def dbInsertEntry(db,title,content):
db.execute("INSERT INTO wiki_entries (title,content) VALUES (?,?)",(title,content))
connection.commit()
sys.stdin = codecs.getreader("utf-8")(sys.stdin)
search = sys.stdin.read()
# Open connection to db and initiate
connection = sqlite3.connect('wikipedia.db')
connection.text_factory = str
db = connection.cursor()
# Lookup the entry in the db
output = dbLookupEntry(db,search)
# If the db lookup failed in some way (Entry not found or whatever reason)
if not output:
try:
# Lookup a summary of the article on Wikipedia
output = unicode(wikipedia.summary(search,sentences=2)).encode('utf8')
except wikipedia.exceptions.DisambiguationError as e:
# In case of a ambiguity, list the different options
output = unicode('"' + search + "\" may refer to: " + ", ".join(e.options)).encode('utf8')
finally:
# Finally, insert the fetched data from Wikipedia to our database
dbInsertEntry(db,search,output)
# Print out the data to the user
print output
# Close connection to db when finished
connection.close()
|
c82fef6a9c65f5515aabc02cf02ddcabbf51c9fb | Terry9022/learn_Python | /python_practice/py_14 score.py | 520 | 3.609375 | 4 | n=eval(input())
if 90<=n<=100:
print("4.3")
print("A+")
elif 85<=n<=89:
print("4.0")
print("A")
elif 80<=n<=84:
print("3.7")
print("A-")
elif 77<=n<=79:
print("3.3")
print("B+")
elif 73<=n<=76:
print("3.0")
print("B")
elif 70<=n<=72:
print("2.7")
print("B-")
elif 67<=n<=69:
print("2.3")
print("C+")
elif 63<=n<=66:
print("2.0")
print("C")
elif 60<=n<=62:
print("1.7")
print("C-")
else:
print("0")
print("F")
|
4ed2ffe29bf382b30e6de976d906dfcd359031c8 | daum913/python_project | /assignments/loop-1/loop1-8.py | 810 | 3.90625 | 4 | # 문제 8.(for)
# 두 개의 정수를 입력받아 두 정수 사이(두 정수를 포함)에 3의 배수이거나 5의 배수인 수들의 합과 평균을 출력하는 프로그램을 작성하시오.
# 평균은 반올림하여 소수 첫째자리까지 출력한다.
# 입력 예: 10 15
# 출력 예: sum : 37 avg : 12.3
num_1 = int(input("첫 번째 정수를 입력하세요 : "))
num_2 = int(input("두 번째 정수를 입력하세요 : "))
list = []
sum = 0
if num_1 > num_2 :
for i in range(num_2, num_1+1) :
if i % 3 == 0 or i % 5 == 0 :
sum += i
list.append(i)
elif num_1 < num_2 :
for i in range(num_1, num_2+1) :
if i % 3 == 0 or i % 5 == 0 :
sum += i
list.append(i)
print("sum : {}, avg : {}".format(sum,round(sum/len(list),1))) |
15fd098e391bac7d24b6dfa775f3f0a28b86f956 | yasuki666/UAV-mission-planning-homework | /作业2/linklist.py | 2,925 | 3.765625 | 4 |
class Node:
def __init__(self, key):
self.key = key
self.next = None
class LinkList:
def __init__(self, node=None): # 使用一个默认参数,在传入头结点时则接收,在没有传入时,就默认头结点为空
self.head = node
def isEmpty(self):
if self.head == None:
return True
else:
return False
def travel(self): # 遍历整个列表
cur = self.head
while cur != None:
print(cur.key, end=' ')
cur = cur.next
print("\n")
def add(self, obj): # 链表头部添加元素
node = Node(obj)
node.next = self.head
self.head = node
def append(self, obj): #链表尾部添加元素
node = Node(obj)
node.next = None
a = self.head
if self.head == None:
self.head = node
else:
while(a.next!=None):
a = a.next
a.next = node
def insert(self, pos, obj): #在链表的pos处插入关键字为obj的元素
node = Node(obj)
s = self.head
for i in range(pos-1):
s = s.next
node.next = s.next
s.next = node
def search(self, obj): #查询关键字为obj的结点
s = self.head
k = 1
while (s.key != obj):
s = s.next
k += 1
return k
def remove(self, obj): #删除所有关键字为obj的结点
a = self.head
b = a.next
if a.key == obj:
a = a.next
b = b.next
self.head = self.head.next
while(b.next != None):
if b.key == obj:
b = b.next
a.next = b
else:
a = a.next
b = b.next
if b.key == obj:
a.next = None
def length(self): #求链表长度
length = 0
s = self.head
while (s.next != None):
s = s.next
length += 1
length += 1 #算上尾结点
return length
print("学号 201715262")
student_number_list = [2,0,1,7,1,5,2,6,2]
student_number_linklist = LinkList() #创建链表
student_number_linklist.isEmpty()
for i in student_number_list: #逐个放入链表
student_number_linklist.append(i)
student_number_linklist.travel()
print("是否为空:{}".format(student_number_linklist.isEmpty()))
print("最大值是7,删除7")
student_number_linklist.remove(7)
student_number_linklist.travel()
print("测试add方法")
student_number_linklist.add(3)
student_number_linklist.travel()
print("测试insert方法")
print("在第5位后边插入8")
student_number_linklist.insert(5,8)
student_number_linklist.travel()
print("测试search方法,查询5在第几位")
print(student_number_linklist.search(5))
print("长度是{}".format(student_number_linklist.length()))
|
1df571b0ac6512bdff3b2e3845f1ef2f44ee39a4 | assuran54/UFABC-PI | /Calculadora.py | 860 | 4.0625 | 4 | pedido = input()
operaçao = pedido.split(' ')
# .split() no parenteses está o símbolo que representa o local de divisão, split
funçao = operaçao[0]
x = float(operaçao[1])
#LEMBRE QUE PRA COMPARAÇÃO É O ==
if len(operaçao) == 3:
y = float(operaçao[2])
#Exatamente dois decimais -> '{:.2f}'.format()
# Atenção!
# Atribuição: '='; Comparação: '=='
import math
if funçao =='SUM':
print('{:.2f}'.format(x+y))
elif funçao == 'DIF':
print('{:.2f}'.format(x-y))
elif funçao == 'MULT':
print('{:.2f}'.format(x*y))
elif funçao == 'DIV':
print('{:.2f}'.format(x/y))
elif funçao == 'POT':
print('{:.2f}'.format(x**y))
elif funçao == 'RAIZ':
print('{:.2f}'.format(math.sqrt(x)))
#math.sqrt tem q botar "math."!
elif funçao == 'LOG10':
print('{:.2f}'.format(math.log10(x)))
|
863c71a85c66235fc56adba44e2f5ab53e2da28d | PyRPy/Py4fun | /PythonEdu/game_snow.py | 1,414 | 3.984375 | 4 | # how to simulate a snow
# http://programarcadegames.com/index.php?chapter=example_code
import pygame
import random
# initialize
pygame.init()
BLACK = [0, 0, 0]
WHITE = [255, 255, 255]
# set screen size
SIZE = [400, 400]
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption("Snow animation")
# empty list to hold snow
snow_list = []
# loop 50 times and create (x, y) positions
for i in range(50):
x = random.randrange(0, 400)
y = random.randrange(0, 400)
snow_list.append([x, y])
# start a clock
clock = pygame.time.Clock()
# repeat / loop until you clicks the close botton
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(BLACK)
# process each snow flake in the list
for i in range(len(snow_list)):
pygame.draw.circle(screen, WHITE, snow_list[i], 2) # draw snow flake
snow_list[i][1] += 1 # moving down
if snow_list[i][1] > 400: # move outside
y = random.randrange(-50, -10) # reset to top
snow_list[i][1] = y
x = random.randrange(0, 400) # reset x
snow_list[i][0] = x
# update screen
pygame.display.flip()
clock.tick(20)
# end game
pygame.quit()
|
f5a75f2cc8d75d0e7d6cd141a0286e6486323237 | zhu535/Python_Study | /Neuedu_20200202/day08_propert的使用.py | 856 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/2/6 16:33
# @Author : zhu
# @FileName: day08_propert的使用.py
# @Software: PyCharm
"""
class Girl:
def __init__(self, weight):
self.__weight = weight
def get_weight(self):
print("我的体重是%s" % self.__weight)
def set_weight(self, weight):
self.__weight = weight
p = property(get_weight, set_weight)
xiaohua = Girl(50)
xiaohua.p # 我的体重是50
xiaohua.p = 40
xiaohua.p # 我的体重是40
"""
class Girl:
def __init__(self, weight):
self.__weight = weight
@property
def weight(self):
print("我的体重是%s" % self.__weight)
@weight.setter
def weight(self, weight):
self.__weight = weight
xiaohua = Girl(50)
xiaohua.weight # 我的体重是50
xiaohua.weight = 40
xiaohua.weight # 我的体重是40
|
f30e1b6ab7bb6e7c8329bb19e10f3fd95800e760 | dimaswahabp/Testing | /task6.py | 818 | 3.765625 | 4 | #sebuah function dengan 1 parameter
#function => menentukan value parameter ganjil genap
'''
def gangen(x):
if (x % 2) == 0:
print (f"{x} adalah bilangan genap")
else :
print(f"{x} adalah bilangan ganjil")
gangen(11)
'''
'''
#Sebuah function calc
def calc():
x = float(input('Masukan Angka 1 :'))
op = input('Masukan operator (+-*/) ')
y = float(input('Masukan Angka 2 :'))
if op == '+':
print(x+y)
elif op == '-':
print(x-y)
elif op == '*':
print(x*y)
elif op == '/':
print(x/y)
else:
print("Sori Sori Jek")
calc()
'''
def vocal(kata):
kata = kata.replace("a","o")
kata = kata.replace("i","o")
kata = kata.replace("u","o")
kata = kata.replace("e","o")
print(kata)
vocal(input("masukan kata :"))
|
003228d5f54f7f532609ef0a49adfe456c92d28a | rakesh-chan/Python | /DailyCode/HelloWorld/2.0_Print_Interactive.py | 941 | 4.1875 | 4 | #print with raw input
print("Press 1: To print")
print("Press 2: To combine two strings")
print("Press 3: To print in sperate lines")
print("Press 4: To print your entered string and digit")
print("Press 5: To print multiple times")
x = int(input())
if (x==1):
print(input("Enter the string to combine : "))
elif(x==2):
str1 = input("enter line 1: ")
str2 = input("enter line2: ")
print (str1+" "+str2)
elif(x==3):
str1 = input("enter line 1: ")
str2 = input("enter line2: ")
print (str1+"\n"+str2)
elif(x==4):
str1 = input("enter string : ")
var1 = int(input("enter numeric: "))
print ("your string is %s and number is %d" %(str1,var1))
print("your string is " ,str1, " and your number is " ,var1)
elif (x==5):
str1 = input("Enter string to print: ")
str2 = str1 + " "
var1 = int(input("Number of times to print: "))
print(str2 * var1)
else:
print("Invalid Input")
|
0eedaf83efc4c1729352fd2f71be26ca2314657c | Rochan2001/data-science | /programs/ex2.py | 495 | 4.125 | 4 | """
Read the "churn.csv" data set and
perform the following tasks
1.what is the average monthly charge paid by a customer for the services he/she has signed up for?
2.The data type of the variable tenure from the churn dataframe is
expected output:
average: 62.4734817814
tenure Data type: object
"""
import numpy as np
import pandas as pd
data = pd.read_csv('churn.csv')
print(data.head())
print('average:', np.mean(data['MonthlyCharges']))
print('tenure Data type: ', data['tenure'].dtype)
|
76378368317572e2a67f2dec0d2942ace7e9e839 | raxxar1024/code_snippet | /leetcode 151-200/188. Best Time to Buy and Sell Stock IV.py | 1,350 | 3.75 | 4 | """
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
"""
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if k > len(prices) / 2:
return self.maxProfit_n(prices)
else:
return self.maxProfit_k(k, prices)
def maxProfit_n(self, prices):
profit = 0
for i in xrange(len(prices) - 1):
profit += max(prices[i + 1] - prices[i], 0)
return profit
def maxProfit_k(self, k, prices):
max_buy = [float("-inf") for _ in xrange(k + 1)]
max_sell = [0 for _ in xrange(k + 1)]
for i in xrange(len(prices)):
for j in xrange(1, min(k, i / 2 + 1) + 1):
max_buy[j] = max(max_buy[j], max_sell[j - 1] - prices[i])
max_sell[j] = max(max_sell[j], max_buy[j] + prices[i])
return max_sell[k]
if __name__ == "__main__":
assert Solution().maxProfit(2, []) == 0
|
8f9064f1d89314c2fa8689f68f2517194a5574fd | toxicthunder69/Assignment | /Basic exercises/MultProgram.py | 143 | 4 | 4 | number1=int(input("Enter no. 1: "))
number2=int(input("Enter no. 2: "))
print("The sum of ",number1,"x",number2," is:")
print(number1*number2)
|
ac87b51260f0ddafb1a4bae952eb71db8e453ddd | harip/google-ml-course | /intro_to_pandas_1.py | 746 | 3.828125 | 4 | """Google ML crash course learning exercises"""
import pandas as pd
import numpy as np
CITY_NAMES = pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
POPULATION = pd.Series([852469, 1015785, 485199])
CITIES = pd.DataFrame({'City Name':CITY_NAMES, 'Population':POPULATION})
CITIES['Area square miles'] = pd.Series([46.87, 176.53, 97.92])
CITIES['Population density'] = CITIES['Population'] / CITIES['Area square miles']
CITIES['Large Saint City'] = \
CITIES['City Name'].apply(lambda name: name.startswith('San')) \
&(CITIES['Area square miles'] > 50)
CITIES = CITIES.reindex([2, 0, 1])
print(CITIES)
CITIES = CITIES.reindex(np.random.permutation(CITIES.index))
print(CITIES)
CITIES = CITIES.reindex([5, 0, 1])
print(CITIES)
|
f29663068e65691d68e2b368f061765a99914a3f | venkateshpitta/python-exercism | /acronym/acronym.py | 109 | 3.578125 | 4 | def abbreviate(given: str) -> str:
return ''.join(w[0].upper() for w in given.replace('-', ' ').split())
|
be0e223930e4d8d244358b65cc5f2eb1aa0709af | Sen2k9/Algorithm-and-Problem-Solving | /leetcode_problems/344_Reverse_String.py | 1,453 | 4.09375 | 4 | """
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
"""
class Solution:
def reverseString(self, s):
"""
Do not return anything, modify s in-place instead.
"""
# Solution 1: self
# if len(s) < 2:
# return s
# i = 0
# j = len(s) - 1
# while i <= j:
# temp = s[j]
# s[j] = s[i]
# s[i] = temp
# i += 1
# j -= 1
# print(s)
# return s
# Solution 2: self, fastest but not accepted in coding interview
# s[::] = s[::-1]
# return s
# Solution 3:
i = 0
j = len(s) - 1
while i <= j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
# print(s)
sol = Solution()
s = ["h", "e", "l", "l", "o"]
print(sol.reverseString(s))
"""
corner case:
1. copying an input is not an solution
https://leetcode.com/problems/reverse-string/discuss/332519/Python-1-line-Do-not-return-anything-(greater99-Solutions)
"""
|
0c034fbda4e1bd8afd099fcdd71c694d7960be3b | katel85/Labs-pands | /labsweek03/Lab3.2.1/convert.py | 669 | 4 | 4 | # program takes in a float amount in dollars and outputs abs amount in cent
# Author Catherine Leddy
# ref https://learnandlearn.com/python-programming/python-reference/python-abs-function
# ref https://www.w3schools.com/python/python_datatypes.asp
number = float(input("Enter a number:"))
absoluteValue = abs(int(number*100))
print('The absolute value of {} is {}'.format(number, absoluteValue))
# task 1 is number must be defined as float becasue of decimal point.
# Task 2 to convert the dollars to cents we must multiple the value by 100 which will be an int
# Task 3 in order for the program to give out 599 instead of -599 we must but abs in front of (int(number*100)) |
1d3ce470259821bf35869c694651829ffdfd58b5 | timm/duo | /etc/old/duo2/col.py | 3,061 | 3.53125 | 4 | #!/usr/bin/env python3
# vim: ts=2 sw=2 sts=2 et tw=81 fdm=indent:
"""
col.py : summarize streams of data
(c) 2021, Tim Menzies, MIT license.
https://choosealicense.com/licenses/mit/
USAGE ./col.py [OPTIONS]
-t S run demo functions matching S
-T run all demo functions
-L list all demo functions
-h run help
-C show copyright
"""
from lib import cli,on
from ok import ok
from random import random as r
def column( pos=0,txt=""):
"Factory for generating different kinds of column."
what = (Col if "?" in txt else (Num if txt[0].isupper() else Sym))
return what(pos=pos, txt=txt)
def Col(pos=0, txt=""):
"""Base object for all other columns. `add()`ing items
increments the `n` counter."""
new = on(pos=pos, txt=txt, n=0, w=1)
def add(i,x) :
if x != "?":
x = i.prep(x); i.n+= 1; i.add1(x)
return x
def add1(i,x): return x
def prep(i,x): return x
return new.has(locals())
def Num(pos=0, txt=""):
"""Here, `add` accumulates numbers into `_all`.
`all()` returns that list, sorted. Can report
`sd()` (standard deviation) and `mid()` (median point).
Also knows how to `norm()` normalize numbers."""
new = Col(pos,txt) + on(_all=[], ok=False,
w= -1 if "-" in txt else 1)
def add1(i,x) :
i._all += [x]
i.ok=False
def all(i):
i._all = i._all if i.ok else sorted(i._all)
i.ok = True
return i._all
def mid(i): a=i.all(); return a[int(len(a)/2)]
def norm(i,x): a=i.all(); return (x-a[0])/(a[-1] - a[0])
def prep(i,x): return float(x)
def sd(i): a=i.all(); return (a[int(.9*len(a))] - a[int(.1*len(a))])/2.56
return new.has(locals())
def Sym(pos=0, txt=""):
"Here, `add` tracks symbol counts, including `mode`."
new = Col(pos,txt) + on(_all={}, mode=None, max=0)
def add1(i,x):
tmp = i._all[x] = i._all.get(x,0) + 1
if tmp>i.max: i.max,i.mode = tmp,x
return x
def mid(i): return i.mode
return new.has(locals())
def Some(pos=0, txt="", keep=256):
"This `add` up to `max` items (and if full, sometimes replace old items)."
new = Col(pos,txt) + on(_all=[], keep=keep)
def add1(i,x) :
if len(i._all) < i.keep: i._all += [x]
elif r() < i.keep / i.n: i._all[ int(r()*len(i._all)) ] = x
return new.has(locals())
#----------------------------------------------------------------
def test_num():
"summarising numbers"
n=Num()
for x in ["10","5","?","20","10","5","?","20","10","5",
"?","20","10","5","?","20","10","5","?","20",
"10","5","?","20"]:
n.add(x)
print(n.mid(), n.sd())
def test_sym():
"summariing numbers"
s=Sym()
for x in ["10","5","?","20","10","5","?","20","10","5",
"?","20","10","5","?","20","10","5","?","20",
"10","5","?","20"]:
s.add(x)
ok("10"==s.mid(),"mid working ?")
def test_some():
"summarize very large sample space"
import random
random.seed(1)
n=Some(max=32)
[n.add(x) for x in range(10**6)]
print(sorted(n._all))
if __name__ == "__main__": cli(locals(),__doc__)
|
cec0af2a9ad239e667fd0c83f27e925d6f8f774a | kali786516/PluralsightCourse1 | /webapp/student.py | 438 | 3.84375 | 4 | students=[]
'''self is like this in java'''
class Student:
school_name = "Springfield Elementary"
def __init__(self,name, student_id=332):
self.name=name
self.student_id=student_id
students.append(self)
def __str__(self):
return "Student " + self.name
def get_name_captilize(self):
return self.name.capitalize()
def get_school_name(self):
return self.school_name |
0251f8827a3ba22b3d130526079a3a88c21732fa | kljoshi/Python | /Exercise/Chapter5/List_to_dictonary_function.py | 1,508 | 4.03125 | 4 |
# function to add items into dictionary if it doesnt exist else increment the counter value
# if the item exists.
def addToInventory(inventory, addedItems):
# loop through items in the dragonLoot, which is a list
for item in addedItems:
# condition to check if item in the dragonLoost already exists in inventory
if(inventory.get(item)):
# if item exits increment the counter and update the value
inventory[item] = inventory.get(item)+1
# if item doesn't exits in the dictionary add it to the inventory
else:
inventory[item] = 1
# return the new updated inventory
return inventory
# this function will display all the item in the dictionary along with its value
# and the number of total item present in the dictionary
def displayInventory(inventory):
print('Inventory: ')
# setting a counter
total_item = 0
# loop which get key and value from inventory
for k,v in inventory.items():
# used to count total number of items
total_item = total_item + v;
print(str(v) + ' ' + k)
print("\nTotal number of items: " + str(total_item))
# declared a dictionary
inv = {'gold coin': 42, 'rope': 1}
# declared a list
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
# call the function addToInventory
inv = addToInventory(inv, dragonLoot)
# takes in new inventory dictionary and display items in it
displayInventory(inv)
|
e92f4611329f311a5f42666c084cad617386f336 | tiedye93/Python--COT4930 | /lab01/tbourque2012_lab01.py | 285 | 4.0625 | 4 | # COT 4930 Python Programming
# Tyler Bourque
# tbourque2012
# Lab : 01
def convertMiles( miles ):
kilo = miles * 1.609
print( miles, "Miles is", kilo, "in Kilometers." )
userInput = eval( input( "type in a number to convert Miles to Kilometers: " ) )
convertMiles( userInput )
|
a6a1b4a058f141da2d7780e2213fe03bd3f668bf | tiggers1985/python-learning | /oop_advance/use_super.py | 5,445 | 4.34375 | 4 | #!/usr/local/bin python3
# -*- coding: utf-8 -*-
'''super() method usage samples
https://realpython.com/python-super/
'''
#-------------------------------------------------------------------------------------------------------------------------
#super() returns a delegate object to a parent class, so you call the method you want directly on it: super().area().
#通过调用父类功能实现代码重用, 继承的同时其实已经可以重用父类代码,但是通过super可以实现对父类功能的增强/扩展
#-------------------------------------------------------------------------------------------------------------------------
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * self.length + 2 * self.width
class Square(Rectangle):
def __init__(self,length):
super().__init__(length, length)
class Cube(Square):
def surface_area(self):
face_area = super().area()
return face_area * 6
def volume(self):
return super().area() * self.length
#Here you have implemented two methods for the Cube class: .surface_area() and .volume().
# Both of these calculations rely on calculating the area of a single face,
# so rather than reimplementing the area calculation, you use super() to extend the area calculation.
cube = Cube(3)
print(cube.volume())
#-------------------------------------------------------------------------------------------------------------------------
#带参数的super(subclass, obj) 第一个参数指定从那个类开始向上搜索,第二个参数指定一个类的实例对象
# While the examples above (and below) call super() without any parameters,
# super() can also take two parameters: the first is the subclass, and the second parameter is an object that is an instance of that subclass.
#-------------------------------------------------------------------------------------------------------------------------
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
print('call rectangle area')
return self.length * self.width
def perimeter(self):
return 2 * self.length + 2 * self.width
class Square(Rectangle):
def __init__(self, length):
super(Square, self).__init__(length, length)
def area(self):
print('square area')
super().area()
#In Python 3, the super(Square, self) call is equivalent to the parameterless super() call.
# The first parameter refers to the subclass Square, while the second parameter refers to a Square object which, in this case, is self.
#! You can call super() with other classes as well:
class Cube(Square):
def surface_area(self):
face_area = super(Square, self).area() #从Square的父类开始搜索farea方法,找到第一个并使用
return face_area * 6
def volume(self):
face_area = super(Square, self).area()
return face_area * self.length
#! In this example, you are setting Square as the subclass argument to super(), instead of Cube.
#! This causes super() to start searching for a matching method (in this case, .area()) at one level above Square in the instance hierarchy, in this case Rectangle.
cube = Cube(3)
print(cube.volume())
#-------------------------------------------------------------------------------------------------------------------------
#多继承下的super
#-------------------------------------------------------------------------------------------------------------------------
class Triangle:
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
class RightPyramid(Triangle, Square):
def __init__(self, base, slant_height):
self.base = base
self.slant_height = slant_height
def area(self):
base_area = super().area()
perimeter = super().perimeter()
return 0.5 * perimeter * self.slant_height + base_area
#以上类继承了两个父类,并且都定义了area方法,如果调用会出现错误:
rp = RightPyramid(2,4)
#print(rp.area()) #AttributeError: 'RightPyramid' object has no attribute 'height'
#-------------------------------------------------------------------------------------------------------------------------
#Python中引入了method resolution order 概念来解决这个问题
#-------------------------------------------------------------------------------------------------------------------------
#Every class has an .__mro__ attribute that allows us to inspect the order, so let’s do that:
print(RightPyramid.__mro__) #(<class '__main__.RightPyramid'>, <class '__main__.Triangle'>, <class '__main__.Square'>, <class '__main__.Rectangle'>, <class 'object'>)
#切换继承类的顺序就可以解决上述问题, #!难道python按照继承顺序来搜索 super类的方法???
class RightPyramid(Square, Triangle):
def __init__(self, base, slant_height):
self.base = base
self.slant_height = slant_height
super().__init__(self.base)
def area(self):
base_area = super().area()
perimeter = super().perimeter()
return 0.5 * perimeter * self.slant_height + base_area |
3969c8a0714a259558e48badac630213e4323b55 | YesterdayxD/interesting_idea | /leetcode/257_binary_tree_paths.py | 683 | 4.03125 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def previous(node):
print(node.val)
if node.left != None:
previous(node.left)
if node.right != None:
previous(node.right)
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
previous(root)
if __name__ == '__main__':
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
d = TreeNode(5)
a.left = b
a.right = c
b.right = d
solu=Solution()
solu.binaryTreePaths(a)
|
363ee29780ffa05bcb1051b9126960acafef02d7 | msaqib/DBRO | /PostgreSQL Code/tweet_length.py | 2,244 | 3.5 | 4 | import psycopg2
import csv
import math
#from math import
filename='/home/faban/Downloads/TestJava/tweets.csv'
with open (filename,'rU') as csvfile:
csv_data=csv.reader(csvfile)
csv_data2=csv.reader(csvfile)
#csv_data = csv.reader(file('/home/faban/Python-Postgresql/Crime.csv'))
# database = psycopg2.connect (host= "192.168.40.12",database = "postgres", user="postgres", password="faban")
# cursor = database.cursor()
#cursor.execute("Create Table tweet (name text, city text, country text)")
#print("Table created successfully")
# cursor.execute("create table Tweets(a text,b text, c text, d text, e text, tweet text, g text, h text, i text, j text)")
# print('Table Created Successfully')
count_row=0
max_tweet_length=0
avg_tweet_length=0
max_row=0
min_tweet_length=300
min_row=0
mean_sum=0
total_characters=0
mean_dif=0
for row in csv_data:
# if count>=3:
# break
print(row)
name=row[0]
city=row[1]
country=row[2]
d=row[3]
e=row[4]
tweet=row[5]
tweet_length=len(tweet)
mean_diff=tweet_length-87
print('mean diff is ',mean_diff)
mean_sum=mean_sum+pow(mean_diff,2)
print ("mean_sum is :",mean_sum)
total_characters=tweet_length+total_characters
g=row[6]
h=row[7]
i=row[8]
j=row[9]
# print(tweet_length)
count_row=1+count_row
if tweet_length>max_tweet_length:
max_tweet_length=tweet_length
max_row=count_row
if tweet_length<min_tweet_length:
min_tweet_length=tweet_length
min_row=count_row
avg_tweet_length=total_characters/count_row
# print(count)
# cursor.execute("INSERT INTO Tweets VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", (name,city,country,d,e,tweet,g,h,i,j))
# csv_data.close()
# cursor.close()
# database.commit()
#database.close()
print('Number of rows :',count_row)
#print('Maximum tweet length :', max_tweet_length,'at row no :',max_row)
#print("Total characters :",total_characters)
#print('Number of rows :',count_row)
#print('Minimum tweet length :', min_tweet_length,'at row no :',min_row)
#avg_tweet_length=total_characters/count_row
#print('Average tweet length is:',avg_tweet_length)
#standard_dev=mean_sum/count_row
#standard_dev=standard_dev**(1.0/2)
#print('standard deviation is :',standard_dev)
#print('Mean sum is :',mean_sum)
|
ca2fe1e09d07428093ba36fd91c40ad3c3275744 | merry-hyelyn/Programmers_weekly_challenge | /Week4/answer.py | 982 | 3.65625 | 4 | def make_language_preference_table(languages, preference):
table = {}
for i in range(len(languages)):
table[languages[i]] = preference[i]
return table
def solution(table, languages, preference):
answer = ''
languages_preference = make_language_preference_table(languages, preference)
'''
다른 사람의 풀이를 보고 zip을 이용하여 언어 선호도 테이블 생성
신기방기..
'''
use_zip_language_preference = {lang : pref for lang, pref in zip(languages, preference)}
prev_score = 0
for row in table:
score = 0
data = row.split(' ')
for k, v in languages_preference.items():
if k in data:
grade = 6 - data.index(k)
score += grade * v
if prev_score < score:
prev_score = score
answer = data[0]
if prev_score == score:
answer = data[0] if answer > data[0] else answer
return answer
|
423c902a4d481c40d11eacf7c06e0b976f260a30 | aryandosaj/ScienceCanvasProjects | /Project-4/Straightline.py | 733 | 3.59375 | 4 | import matplotlib.pyplot as plt
x = [1,2,3,4,5,6,7,8]
y = [53807,55217,55209,55415,63100,63206,63761,65766]
c = 50000
m = 100
n = float(len(x))
alpha1 = 0.0001
alpha2 = 0.0001
def update():
der_c = 0
der_m = 0
global c,m,alpha,n
for (i,j) in zip(x,y):
der_m =der_m + i*(m*i + c - j)
der_c =der_c + m*i + c - j
m = m - alpha1 * 2 / n * der_m
c = c - alpha2 * 2 / n * der_c
for i in range(2000):
update()
print("Mean of x =",(sum(x)/n))
print("Mean of y =",(sum(y)/n))
print("Equaton of line : y = ",m,"x + ",c)
print("Prediction of Year 2010 = ",(m*(2010-1994) + c))
print("Prediction of Year 2017 = ",(m*(2017-1994) + c))
plt.plot(x,y,'o')
plt.plot([0,10],[c,10*m+c])
plt.show()
|
74d3ba1f53b07993c228c9b5c27df6ee4589fe7b | simonxu14/LeetCode_Simon | /257.Binary Tree Paths/Solution.py | 966 | 3.828125 | 4 | __author__ = 'Simon'
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if root is None:
return []
list = []
s = str(root.val)
self.DFS(root, list, s)
return list
def DFS(self, root, list, s):
if root.left == None and root.right == None:
list.append(s)
if root.left is not None:
s = s + "->" + str(root.left.val)
self.DFS(root.left, list, s)
s = s[0:len(s) - len(str(root.left.val)) - 2]
if root.right is not None:
s = s + "->" + str(root.right.val)
self.DFS(root.right, list, s)
s = s[0:len(s) - len(str(root.right.val)) - 2]
return |
5078992d6df9125828dec5c78e8557765f7f8162 | daniel-reich/ubiquitous-fiesta | /YA5sLYuTzQpWLF8xP_3.py | 142 | 3.59375 | 4 |
def clean_up_list(lst):
even = [i for i in map(int, lst) if i%2 == 0]
odd = [i for i in map(int, lst) if i%2 == 1]
return [even, odd]
|
2f38acd2c899f6a0cd7d840b75b18abb88f0136a | bryanyaggi/Coursera-Algorithms | /course2/pa1.py | 5,022 | 3.859375 | 4 | #!/usr/bin/env python3
import sys
import threading
import time
# Hitting limits if the following are not modified
sys.setrecursionlimit(800000)
threading.stack_size(67108864)
'''
Programming Assignment 1
Download the following text file: SCC.txt
The file contains the edges of a directed graph. Vertices are labeled as
positive integers from 1 to 875714. Every row indicates an edge, the vertex
label in first column is the tail and the vertex label in second column is the
head (recall the graph is directed, and the edges are directed from the first
column vertex to the second column vertex). So for example, the 11th row looks
like: "2 47646". This just means that the vertex with label 2 has an outgoing
edge to the vertex with label 47646.
Your task is to code up the algorithm from the video lectures for computing
strongly connected components (SCCs), and to run this algorithm on the given
graph.
Output Format: You should output the sizes of the 5 largest SCCs in the given
graph, in decreasing order of sizes, separated by commas (avoid any spaces). So
if your algorithm computes the sizes of the five largest SCCs to be 500, 400,
300, 200 and 100, then your answer should be "500,400,300,200,100" (without the
quotes). If your algorithm finds less than 5 SCCs, then write 0 for the
remaining terms. Thus, if your algorithm computes only 3 SCCs whose sizes are
400, 300, and 100, then your answer should be "400,300,100,0,0" (without the
quotes). (Note also that your answer should not have any spaces in it.)
WARNING: This is the most challenging programming assignment of the course.
Because of the size of the graph you may have to manage memory carefully. The
best way to do this depends on your programming language and environment, and we
strongly suggest that you exchange tips for doing this on the discussion forums.
'''
'''
Class to store graph information.
'''
class Graph:
def __init__(self):
self.nodes = {}
self.nodeOrder = []
self.sccs = {}
'''
Adds node to graph.
node is integer node ID
'''
def addNode(self, node):
if node not in self.nodes:
self.nodes[node] = {'in': set(), 'out': set()}
'''
Adds edge to graph.
srcNode is integer node ID of source node
destNode is integer node ID of destination node
'''
def addEdge(self, srcNode, destNode):
self.addNode(srcNode)
self.addNode(destNode)
self.nodes[srcNode]['out'].add(destNode)
self.nodes[destNode]['in'].add(srcNode)
'''
Calculates valid node order for finding SCCs. This function runs the first
"DFS-Loop" discussed in lecture.
'''
def calcNodeOrder(self):
self.nodeOrder = [] # reset
explored = set()
def dfs(node):
explored.add(node)
for srcNode in self.nodes[node]['in']:
if srcNode not in explored:
dfs(srcNode)
self.nodeOrder.append(node)
for node in self.nodes:
if node not in explored:
dfs(node)
'''
Calculates SCCs. This function runs the second "DFS-Loop" discussed in
lecture.
'''
def calcSccs(self):
self.sccs = {} # reset
explored = set()
leader = -1
def dfs(node):
explored.add(node)
if node == leader:
self.sccs[leader] = set()
else:
self.sccs[leader].add(node)
for destNode in self.nodes[node]['out']:
if destNode not in explored:
dfs(destNode)
for i in range(len(self.nodeOrder)-1, -1, -1):
if self.nodeOrder[i] not in explored:
leader = self.nodeOrder[i]
dfs(leader)
'''
Prints 5 largest SCC sizes.
'''
def printSccSizes(self):
sccSizes = []
for scc in self.sccs:
sccSizes.append(len(self.sccs[scc])+1)
sccSizes.sort(reverse=True)
for i in range(4):
sccSizes.append(0)
print('5 largest SCCs: %s' %(sccSizes[:5]))
def readFile(filename):
graph = Graph()
with open(filename) as f:
lines = f.readlines()
for line in lines:
line = line.split()
graph.addEdge(int(line[0]), int(line[1]))
return graph
def testGraph():
graph = Graph()
graph.addEdge(7,1)
graph.addEdge(5,2)
graph.addEdge(9,3)
graph.addEdge(1,4)
graph.addEdge(8,5)
graph.addEdge(3,6)
graph.addEdge(8,6)
graph.addEdge(4,7)
graph.addEdge(9,7)
graph.addEdge(2,8)
graph.addEdge(6,9)
return graph
def main():
t0 = time.time()
graph = readFile('SCC.txt')
#graph = testGraph()
#print(graph.nodes)
graph.calcNodeOrder()
#print(graph.nodeOrder)
graph.calcSccs()
#print(graph.sccs)
graph.printSccSizes()
print('total time = %f' %(time.time() - t0))
if __name__ == '__main__':
thread = threading.Thread(target=main)
thread.start()
|
5852cb7f842079eecce9403c5d09f2ba09bdab3d | ectom/Coding-Dojo-Python-Stack | /1 - python_fundamentals/hello_world.py | 363 | 3.65625 | 4 | words = "It's thanksgiving day. It's my birthday,too!"
x = [2,54,-2,7,12,98]
y = ["hello",2,54,-2,7,12,98,"world"]
z = [19,2,54,-2,7,12,98,32,10,-3,6]
print words.find('day')
print words.replace('day','month')
print min(x)
print max(x)
print y[0]
print y[len(y)-1]
a = [y[0], y[len(y)-1]]
print a
z.sort()
b = len(z)/2
c = z[:b]
d = z[b:]
d.insert(0, c)
print d
|
e4c59b39baefb1052f6bd7d848e1d37ab92fe2bb | alikslee/Python-itheima-2019 | /01-Python核心编程/代码/04-数据序列/04-字典/hm_08_字典的遍历之键值对.py | 97 | 3.84375 | 4 | dict1 = {'name': 'TOM', 'age': 20, 'gender': '男'}
for item in dict1.items():
print(item)
|
9bb5edb135c6ba83995bd29369d70dad615e76ad | Saiden125/demo_py | /age_matome.py | 361 | 3.75 | 4 | text = input('年齢入力')
if text.isdigit():
age = int(text)
if age < 20:
if 0 <= age < 6:
print('未成年(幼児)')
elif age >= 6 and age <= 15:
print('未成年(義務教育期間)')
else:
print('未成年')
elif age < 65:
print('成人')
else:
print('高齢者') |
a6687917f41c88d7a0bbbad272878f497be77caf | richherr/richherr.github.io | /data8/_build/jupyter_execute/chapters/05/1/Arrays.py | 6,106 | 3.84375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
from datascience import *
path_data = '../../../assets/data/'
# # Arrays
#
# While there are many kinds of collections in Python, we will work primarily with arrays in this class. We've already seen that the `make_array` function can be used to create arrays of numbers.
#
# Arrays can also contain strings or other types of values, but a single array can only contain a single kind of data. (It usually doesn't make sense to group together unlike data anyway.) For example:
# In[2]:
english_parts_of_speech = make_array("noun", "pronoun", "verb", "adverb", "adjective", "conjunction", "preposition", "interjection")
english_parts_of_speech
# Returning to the temperature data, we create arrays of average daily [high temperatures](http://berkeleyearth.lbl.gov/auto/Regional/TMAX/Text/global-land-TMAX-Trend.txt) for the decades surrounding 1850, 1900, 1950, and 2000.
# In[3]:
baseline_high = 14.48
highs = make_array(baseline_high - 0.880,
baseline_high - 0.093,
baseline_high + 0.105,
baseline_high + 0.684)
highs
# Arrays can be used in arithmetic expressions to compute over their contents. When an array is combined with a single number, that number is combined with each element of the array. Therefore, we can convert all of these temperatures to Fahrenheit by writing the familiar conversion formula.
# In[4]:
(9/5) * highs + 32
# 
# Arrays also have *methods*, which are functions that operate on the array values. The `mean` of a collection of numbers is its average value: the sum divided by the length. Each pair of parentheses in the examples below is part of a call expression; it's calling a function with no arguments to perform a computation on the array called `highs`.
# In[5]:
highs.size
# In[6]:
highs.sum()
# In[7]:
highs.mean()
# ## Functions on Arrays
# The `numpy` package, abbreviated `np` in programs, provides Python programmers with convenient and powerful functions for creating and manipulating arrays.
# In[8]:
import numpy as np
# For example, the `diff` function computes the difference between each adjacent pair of elements in an array. The first element of the `diff` is the second element minus the first.
# In[9]:
np.diff(highs)
# The [full Numpy reference](http://docs.scipy.org/doc/numpy/reference/) lists these functions exhaustively, but only a small subset are used commonly for data processing applications. These are grouped into different packages within `np`. Learning this vocabulary is an important part of learning the Python language, so refer back to this list often as you work through examples and problems.
#
# However, you **don't need to memorize these**. Use this as a reference.
#
# Each of these functions takes an array as an argument and returns a single value.
#
# | **Function** | Description |
# |--------------------|----------------------------------------------------------------------|
# | `np.prod` | Multiply all elements together |
# | `np.sum` | Add all elements together |
# | `np.all` | Test whether all elements are true values (non-zero numbers are true)|
# | `np.any` | Test whether any elements are true values (non-zero numbers are true)|
# | `np.count_nonzero` | Count the number of non-zero elements |
#
# Each of these functions takes an array as an argument and returns an array of values.
#
# | **Function** | Description |
# |--------------------|----------------------------------------------------------------------|
# | `np.diff` | Difference between adjacent elements |
# | `np.round` | Round each number to the nearest integer (whole number) |
# | `np.cumprod` | A cumulative product: for each element, multiply all elements so far |
# | `np.cumsum` | A cumulative sum: for each element, add all elements so far |
# | `np.exp` | Exponentiate each element |
# | `np.log` | Take the natural logarithm of each element |
# | `np.sqrt` | Take the square root of each element |
# | `np.sort` | Sort the elements |
#
# Each of these functions takes an array of strings and returns an array.
#
# | **Function** | **Description** |
# |---------------------|--------------------------------------------------------------|
# | `np.char.lower` | Lowercase each element |
# | `np.char.upper` | Uppercase each element |
# | `np.char.strip` | Remove spaces at the beginning or end of each element |
# | `np.char.isalpha` | Whether each element is only letters (no numbers or symbols) |
# | `np.char.isnumeric` | Whether each element is only numeric (no letters)
#
# Each of these functions takes both an array of strings and a *search string*; each returns an array.
#
# | **Function** | **Description** |
# |----------------------|----------------------------------------------------------------------------------|
# | `np.char.count` | Count the number of times a search string appears among the elements of an array |
# | `np.char.find` | The position within each element that a search string is found first |
# | `np.char.rfind` | The position within each element that a search string is found last |
# | `np.char.startswith` | Whether each element starts with the search string
#
#
|
ca92f3ebe4bfc73271d75dcf004b0d8a881e12c8 | CalebBorwick/CS-1026 | /Textbook/Chapter 6/6.2 List Operations.py | 1,189 | 4.34375 | 4 | #adding elements to a list
family = []
family.append('Hayden')
family.append('Nicole')
family.append('Bruce')
family.append('Lauren')
family.append('Sparky')
print(family[4])
#adding in a specific loction
family.insert(5,'Merlin')
print(family[5])
#Finding an element
if 'Nicole' in family :
print('She is my mother')
#removing an element
family.insert(6,'Tim')
family.pop(6)
print(family)
#combinding lists
extendedFamily = ['Hope', 'Pa', 'Moemoe', 'Grandma', 'Papa', 'Erin', 'Brian']
wholeFamily = extendedFamily + family
print(wholeFamily)
#replication
monthInQuarter = [1,2,3] * 4
print(monthInQuarter)
#Equality and inequality testing
if [1,2,3]==[1,2,3] :
print('True')
if [1,2,3] == [3,2,1] :
print('False')
if [1,2,3] != [3,2,1] :
print('True')
#Sum, Max and Min
numList = [12,45,98,45,67,32,59]
print(sum(numList))
print(min(numList))
print(max(numList))
#sorting
print(sorted(numList))
#copying lists
prices = list(numList)
print(prices)
#Slicing a list
#if you only want to use part of a list
people = family[0:4]
print(people)
pets = family[4:6]
print(pets)
otherFamily = wholeFamily[ :7]
print(otherFamily)
myFamily = wholeFamily[7:]
print(myFamily)
|
7de765f684317a31ec1dafac117b353cbc6f9577 | FordTang/ICS32_ProgrammingSoftwareLibraries | /Project4/Project4.py | 7,803 | 3.84375 | 4 | # Ford Tang / 46564602
# Project #4: The Width of a Circle (Part 1)
# Project4.py
# This is the main file for Project 4 that will create an othello game on the console.
import Othello
import othello_ai
def play_game() -> None:
"""
This function runs the othello game on the console.
:rtype : None
"""
while True:
_banner()
while True:
try:
game = Othello.Game(_get_rows(), _get_columns(), _black_plays_first(), _white_in_top_left(),
_win_with_most())
break
except Othello.IncorrectNumberOfRows:
print("\nNumber of rows is incorrect, please try again.")
except Othello.IncorrectNumberOfColumns:
print("\nNumber of columns is incorrect, please try again.")
black_ai = _yes_no_to_bool('Would you like the computer to control Black? ')
white_ai = _yes_no_to_bool('Would you like the computer to control White? ')
while game.win_result() == "":
_score_board(game)
_board(game)
if black_ai and game.current_player() == Othello.BLACK:
move = othello_ai.move(game)
game.move(move[0],move[1])
print("Black plays Row {}, Column {}.".format(move[0], move[1]))
elif white_ai and game.current_player() == Othello.WHITE:
move = othello_ai.move(game)
game.move(move[0],move[1])
print("White plays Row {}, Column {}.".format(move[0], move[1]))
else:
try:
game.move(_play_row(), _play_column())
except Othello.InvalidMove:
print('\nInvalid selection, please try again.')
_win_board(game)
_board(game)
if not _yes_no_to_bool('Would you like to play again?'):
break
def _banner() -> None:
"""
This function prints the game banner.
:rtype : None
"""
print("""\nThe Game of
______ ______ __ __ ______ __ __ ______
/\ __ \ /\__ _\ /\ \_\ \ /\ ___\ /\ \ /\ \ /\ __ \\
\ \ \/\ \ \/_/\ \/ \ \ __ \ \ \ __\ \ \ \____ \ \ \____ \ \ \/\ \\
\ \_____\ \ \_\ \ \_\ \_\ \ \_____\ \ \_____\ \ \_____\ \ \_____\\
\/_____/ \/_/ \/_/\/_/ \/_____/ \/_____/ \/_____/ \/_____/""")
def _board(game:Othello) -> None:
"""
This function prints the game board to the console.
:rtype : None
:param game: Othello
"""
rows = game.rows()
columns = game.columns()
for column in range(columns):
if column < 1:
print('{:>5}'.format(column + 1), end='')
else:
print('{:>3}'.format(column + 1), end='')
print()
for row in range(rows):
print('{:>2}'.format(row + 1), end='')
for column in range(columns):
print('{:>3}'.format(game.cell(row + 1, column + 1)), end='')
print()
def _score_board(game:Othello) -> None:
"""
This function prints out the score board with the current player.
:rtype : None
:param game: Othello
"""
blackscore = 'Black: ' + str(game.black_score())
whitescore = "White: " + str(game.white_score())
print()
print(''.center(50, '-'))
print('|' + blackscore.center(24, ' ') + whitescore.center(24, ' ') + '|')
if game.current_player() == Othello.BLACK:
print('|' + "Black's turn".center(48, ' ') + '|')
else:
print('|' + "White's turn".center(48, ' ') + '|')
print(''.center(50, '-'))
def _win_board(game:Othello) -> None:
"""
This function prints out the winner (or Tie) and the scores.
:rtype : None
:param game: Othello
"""
blackscore = 'Black: ' + str(game.black_score())
whitescore = "White: " + str(game.white_score())
winner = game.win_result()
print()
print(''.center(50, '-'))
print('|' + blackscore.center(24, ' ') + whitescore.center(24, ' ') + '|')
if winner == Othello.BLACK:
print('|' + "Black Won!".center(48, ' ') + '|')
elif winner == Othello.WHITE:
print('|' + "White Won!".center(48, ' ') + '|')
elif winner == 'Tie':
print('|' + "Tie!".center(48, ' ') + '|')
print(''.center(50, '-'))
def _get_rows() -> int:
"""
This function gets the desired rows for the othello game.
:rtype : int
"""
while True:
try:
return int(input("\nPlease enter the desired number of rows.\nNumber must be even and between 4 and 16: "))
except:
print("Invalid input, please try again.")
def _get_columns() -> int:
"""
This function gets the desired columns for the othello game.
:rtype : int
"""
while True:
try:
return int(
input("\nPlease enter the desired number of columns.\nNumber must be even and between 4 and 16: "))
except:
print("Invalid input, please try again.")
def _play_row() -> int:
"""
This function ask the player for the row they would like to play.
:rtype : int
"""
while True:
try:
return int(input("Please enter the row you would like to play: "))
except:
print('\nInvalid input, please try again.')
def _play_column() -> int:
"""
This function ask the player for the column they would like to play.
:rtype : int
"""
while True:
try:
return int(input("Please enter the column you would like to play: "))
except:
print('\nInvalid input, please try again.')
def _black_plays_first() -> bool:
"""
This function determines who should play first.
:rtype : bool
"""
while True:
black_first = input("\nShould [B]lack or [W]hite play first?\n(Default is Black): ").strip().upper()
if black_first == '' or black_first == Othello.BLACK:
return True
elif black_first == "W":
return False
else:
print("Invalid input, please try again.")
def _white_in_top_left() -> bool:
"""
This function determines how the board's initial layout should be.
:rtype : bool
"""
while True:
white_top = input(
"\nFor the initial board layout, Should [W]hite or [B]lack take the upper left corner?\n(Default is White): ").strip().upper()
if white_top == '' or white_top == Othello.WHITE:
return True
elif white_top == "B":
return False
else:
print("Invalid input, please try again.")
def _win_with_most() -> bool:
"""
This function determines which rule the game should use for the winning condition.
:rtype : bool
"""
while True:
win_most = input("\nWin with [M]ost points or [L]east?\n(Default is Most): ").strip().upper()
if win_most == '' or win_most == 'M':
return True
elif win_most == "L":
return False
else:
print("Invalid input, please try again.")
def _yes_no_to_bool(question:str) -> bool:
"""
This function ask the user a Yes or No question and returns the True or False.
:rtype : bool
"""
while True:
try:
answer = input("\n" + question + ' (Y/N): ').strip().upper()
if answer == 'Y':
return True
elif answer == 'N':
return False
else:
print('Invalid choice, please try again.')
except:
print('Invalid input, please try again.')
if __name__ == '__main__':
play_game()
|
1c502406600a191106569a8945ea6ca3bbe2133d | Geeksten/guessing-game | /guessing_game.py | 1,247 | 4.03125 | 4 | import random
prior_guesses = [] #use snakecase for python
guess_found = 0
guesses_taken = 0
number = random.randint(1, 100)
username = raw_input("Hi there! What is your name? ")
print "%s I'm thinking of a number from 1-100. Try to guess my number!" % username
while guess_found < 1:
guess = raw_input('Please take a guess. ')
if guess.isdigit(): #use this isdigit to make sure the user is entering a number
guesses_taken = guesses_taken + 1
guess = int(guess)
if guess in prior_guesses:
print("Oopsie, you've already guessed this!")
if guess < number:
print('Your guess is too low.')
prior_guesses.append(guess)
elif guess > number:
print('Your guess is too high.')
prior_guesses.append(guess)
elif guess == number:
guesses_taken = str(guesses_taken) #changed guesses_taken into str to concatanate
print('You are super awesome! You solved this in ' + guesses_taken + ' guesses!')
guess_found = 1 #this is to break out of the while loop
else:
print("That's not a number!")
#use ctrl+h for the replace all function
#python supports boolean values, so we an set while True
|
89f340cac84f6037a5b75393940de0d12ac258bc | emblu3/Sorter | /sorter/Sorter.py | 3,945 | 3.984375 | 4 | # How many items to rank
def inputNumber(message):
while True:
try:
user_input = int(input(message))
if user_input < 2:
print('Please enter 2 or more.')
continue
except ValueError:
print("Please enter a whole number.")
continue
else:
return user_input
# Rank items
def rank(albums):
list1 = list(albums.keys())
while True:
while len(list1) > 1: #repeat until no more keys to compare
choice = input('(1) "{}" VS (2) "{}" : '.format(list1[0], list1[1])) #display options
if choice == '1': #decrease value by -1 for second option
albums[list1[0]] += 0
albums[list1[1]] -= 1
same_value = albums[list1[0]] #get value of first object
list2 = [k for k,v in albums.items() if v == same_value] #list 2 will have keys for additional items with value of the first option (referenced option)
list1 = list2
elif choice == '2': #increase value by 1 for second option
albums[list1[0]] += 0
albums[list1[1]] += 1
same_value = albums[list1[0]] #get value of first object
list2 = [k for k,v in albums.items() if v == same_value] #list 2 will have keys for additional items with value of the first option (referenced option)
list1 = list2
else:
print('Please choose "1" or "2".')
# Make dictionary with values (rank) as the keys and keys (entries) as the values
duplicates = {}
for key, value in albums.items():
if value not in duplicates:
duplicates[value] = [key]
else:
duplicates[value].append(key)
# Get list of current ranks in ascending order
total_values = []
for key in duplicates.keys():
total_values.append(key)
total_values.sort()
# End function if each entry has own rank
if len(entries) == len(total_values):
return False
# Get keys of lowest duplicated value
global duplicates_k
for k, v in duplicates.items():
for i in range(len(total_values)):
if len(v) > 1 and k == total_values[i]:
duplicates_k = [val for key, val in duplicates.items() if key == k]
duplicates_k = duplicates_k[0]
break
else:
pass
# Adjust dictionary values that aren't being ranked
lowest_value = albums[duplicates_k[0]]
for k, v in albums.items():
if v > lowest_value: #if value is greater than current duplicate value, increase by 1
albums[k] += 1
elif v < lowest_value: #if value is less than current duplicate value, decrease by 1
albums[k] -= 1
else: #don't change value of current duplicate
pass
# Keys of lowest duplicate value will be compared
list1 = duplicates_k
# Introduction
print('Welcome to the sorter!\n')
# Entries to rank
entries_amount = inputNumber('How many items do you need to rank? ')
# Entry names
print('\nWrite each entry then press enter.')
k = 1
entries = []
for i in range(entries_amount):
entry = input('Entry #{}: '.format(k))
entries.append(entry)
k += 1
# Make a dictionary from entries and set values to 0
rank_dict = dict.fromkeys(entries, 0)
# Start Ranking
print('\nTime to rank!')
rank(rank_dict)
# Sort entries according to rank
ranked_items = {k: v for k, v in sorted(rank_dict.items(), key=lambda x: x[1])}
#Display Ranks
print('\nHERE\'S HOW YOU RANKED THE FOLLOWING\n')
# Reverse the rank order (highest to lowest value)
i = 1
for k, v in reversed(ranked_items.items()):
print('{}. {}'.format(i, k))
i += 1
print(' ') |
ec7f43bb91161ec2dbf875cd92d0e262bf907185 | HongyuS/Vegetable-Market | /CSC1001/Assignment_2/q3.py | 1,092 | 4 | 4 | # Return true if the card number is valid
def isValid(number):
_sum = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)
if _sum % 10 == 0:
return True
else:
return False
# Get the result from Step 2
def sumOfDoubleEvenPlace(number):
_sum = 0
for i in range(2, len(number)+1, 2):
evenPlace = int(number[len(number) - i])
if evenPlace < 5:
_sum += evenPlace * 2
else:
_sum += getDigit(evenPlace * 2)
return _sum
'''
Return this number if it is a single digit,
otherwise, return the sum of the two digits
'''
def getDigit(n):
n = str(n)
return int(n[0]) + int(n[1])
# Return sum of odd place digits in number
def sumOfOddPlace(number):
_sum = 0
for i in range(1, len(number), 2):
_sum += int(number[len(number) - i])
return _sum
def main():
number = input('Please enter card number >')
if number.isdigit() and isValid(number):
print('The card number is valid.')
else:
print('The card number is invalid.')
if __name__ == "__main__":
main()
|
99f806453e8894fd7060761c947371e984a967e5 | Xnaivety/pat | /pat(advanced)python/1022(advanced)need_to_fix.py | 2,343 | 3.609375 | 4 | class book():
def __init__(self, seven_digit_id_number, book_title, author, key_words, publisher, published_year):
self.seven_digit_id_number = seven_digit_id_number
self.book_title = book_title
self.author = author
self.key_words = key_words
self.publisher = publisher
self.published_year = published_year
if __name__ == '__main__':
number_book = int(input())
books_list = []
for i in range(number_book):
index_seven_digit_id_number = input()
index_book_title = input()
index_author = input()
index_key_words = input().split()
index_publisher = input()
index_published_year = input()
books_list.append(
book(index_seven_digit_id_number, index_book_title, index_author, index_key_words, index_publisher,
index_published_year))
books_list = sorted(books_list, key=lambda x: x.seven_digit_id_number)
for i in range(int(input())):
input1 = input()
print(input1)
index_line = input1.split(': ') # 请求编号
request_number = int(index_line[0])
request_text = index_line[1]
count = 0
if (request_number == 1):
for i in books_list:
if (i.book_title == request_text):
count += 1
print(i.seven_digit_id_number)
elif (request_number == 2):
for i in books_list:
if (i.author == request_text):
count += 1
print(i.seven_digit_id_number)
elif (request_number == 3): # 进行列表查询
for i in books_list:
for x in i.key_words:
if (x == request_text):
print(i.seven_digit_id_number)
count += 1
break
elif (request_number == 4):
for i in books_list:
if (i.publisher == request_text):
count += 1
print(i.seven_digit_id_number)
elif (request_number == 5):
for i in books_list:
if (i.published_year == request_text):
count += 1
print(i.seven_digit_id_number)
if (count == 0):
print('Not Found')
|
7bc9162ba10295da568377e2328a2bd0313539c4 | PansulBhatt/NeuralNetworks | /exercise_3.py | 4,041 | 4.15625 | 4 | # Keras uses the Sequential model for linear stacking of layers.
# That is, creating a neural network is as easy as (later)
# defining the layers!
from tensorflow.keras.models import Sequential
# Everything we've talked about in class so far is referred to in
# Keras as a "dense" connection between layers, where every input
# unit connects to a unit in the next layer
# We will go over specific activation functions throughout the class.
from tensorflow.keras.layers import Dense
# SGD is the learning algorithm we will use
from tensorflow.keras.optimizers import SGD
def build_one_output_model():
model = Sequential()
### YOUR CODE HERE ###
# Add a input hidden layer with appropriate input dimension
# 1+ lines
model.add(Dense(2**10, input_shape=(2,), activation = 'relu'))
# Add a final output layer with 1 unit
# 1 line
model.add(Dense(1, activation='sigmoid'))
######################
sgd = SGD(lr=0.001, decay=1e-7, momentum=0.9) #Stochastic gradient descent
model.compile(loss="binary_crossentropy", optimizer=sgd)
return model
def build_classification_model():
model = Sequential()
### YOUR CODE HERE ###
# First add a fully-connected (Dense) hidden layer with appropriate input dimension
model.add(Dense(10, input_shape=(2,), activation = 'relu'))
# Now our second hidden layer
model.add(Dense(5, input_shape=(10,), activation = 'relu'))
# Finally, add a readout layer
model.add(Dense(2, activation = 'softmax'))
######################
sgd = SGD(lr=0.001, decay=1e-7, momentum=.9) # Stochastic gradient descent
model.compile(loss='categorical_crossentropy',
optimizer=sgd, metrics=["accuracy"])
return model
def build_final_model():
model = Sequential()
### YOUR CODE HERE ###
model.add(Dense(1024, input_shape=(2,), activation = 'relu'))
model.add(Dense(5, input_shape=(1024,), activation = 'relu'))
model.add(Dense(2, activation = 'softmax'))
######################
sgd = SGD(lr=0.001, decay=1e-7, momentum=.9) # Stochastic gradient descent
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=["accuracy"])
# we'll have the categorical crossentropy as the loss function
# we also want the model to automatically calculate accuracy
return model
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
import numpy as np
def logistic_regression_model(tune_model = False, X_train = None, y_train = None):
logreg = LogisticRegression()
if not tune_model:
return logreg
param_grid = {
'penalty' : ['l1', 'l2'],
'C' : np.logspace(-4, 4, 20),
'solver' : ['liblinear']
}
grid_search = GridSearchCV(estimator = logreg, scoring='f1', param_grid = param_grid,
cv = 3, n_jobs = -1, verbose = 2)
grid_search.fit(X_train, y_train)
print("Logistic Regession parameters: ", grid_search.best_params_)
return LogisticRegression(**grid_search.best_params_)
def random_forest_model(tune_model = False, X_train = None, y_train = None):
rf = RandomForestClassifier(random_state=26)
if not tune_model:
return rf
param_grid = {
'max_depth': [i for i in range(1, 10, 3)],
'max_features': ['sqrt'], # Since we only have 2 features at max for the training data
'min_samples_leaf': [i for i in range(2, 10, 2)],
'min_samples_split': [i for i in range(2, 15, 2)],
'n_estimators': [i for i in range(5, 30, 5)]
}
grid_search = GridSearchCV(estimator = rf, scoring='f1', param_grid = param_grid,
cv = 3, n_jobs = -1, verbose = 2)
grid_search.fit(X_train, y_train)
print("Random Forest parameters: ", grid_search.best_params_)
return RandomForestClassifier(random_state=26, **grid_search.best_params_) |
c95ebc785e5e95fa790ed88e19b06686fbdde881 | DimpleOrg/PythonRepository | /Python Crash Course/vAnil/Chapter-5/5-5.py | 1,028 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 4 18:20:08 2021
@author: ANIL
"""
alien_color = 'green'
if alien_color == 'green':
print('The player just earned 5 points for shooting the alien.')
elif alien_color == 'yellow':
print('The player just earned 10 points.')
elif alien_color == 'red':
print('The player just earned 15 points.')
else:
print('Invalid color.')
alien_color = 'yellow'
if alien_color == 'green':
print('The player just earned 5 points for shooting the alien.')
elif alien_color == 'yellow':
print('The player just earned 10 points.')
elif alien_color == 'red':
print('The player just earned 15 points.')
else:
print('Invalid color.')
alien_color = 'red'
if alien_color == 'green':
print('The player just earned 5 points for shooting the alien.')
elif alien_color == 'yellow':
print('The player just earned 10 points.')
elif alien_color == 'red':
print('The player just earned 15 points.')
else:
print('Invalid color.')
|
bf7208591a93625b1b39989a3dda03e839a85567 | Vincebye/CTF-Tools | /Decrypt-Caesar.py | 496 | 4.0625 | 4 | def encrypt():
pass
def decrypt(key,str):
decrypt_str=''
for i in str:
decrypt_words=ord(i)+key
if decrypt_words>ord('Z'):
decrypt_words=decrypt_words-26
decrypt_str=decrypt_str+chr(decrypt_words)
return decrypt_str
if __name__=="__main__":
decrypt_list=[]
str=raw_input('Please enter the string to be decrypted:')
for i in range(1,26):
decrypt_list.append(decrypt(i,str))
for i in decrypt_list:
print i+'\n'
|
3f18980af9c0018b88966f07a81dcc2503160116 | sunanth123/Genetic-Algorithm | /ga.py | 4,143 | 4.03125 | 4 | import random
from Queue import PriorityQueue
##Sunanth Sakthivel
##CS541 Program 2
##this program is a genetic algorithim that will find the solution to the knapsack problem. Note that the
##optimality of the solution will depend on the number of iterations and population size of the sample.
MaxWeight = 100 ##max weight for knapsack problem
population = 16 ##the population size (will always remain constant)
objects = [[45,3], [40,5], [50,8], [90,10]] ##this is a list of lists (first element is weight, second is value)
PopulationSize = [] ##this will hold the current population members
NumIterations = 100 ##number of breeding, mutation and death cycles
##this function will return the fitness value of a member in the population based on their list
def fitnessfunction(templist,objects,MaxWeight):
totalvalue = 0
totalweight = 0
for i in range(len(templist)):
if templist[i] == 1:
totalvalue += objects[i][1]
totalweight += objects[i][0]
if totalweight > MaxWeight:
totalvalue = 0
return totalvalue
##this function will return the total weight of a member in the population based on their list
def weight(templist,objects):
totalweight = 0
for i in range(len(templist)):
if templist[i] == 1:
totalweight += objects[i][0]
return totalweight
##randomize the initial population with members
for i in range(population):
templist = []
for i in range(len(objects)):
templist.append(random.randint(0,1))
fitness = fitnessfunction(templist,objects,MaxWeight)
PopulationSize.append((fitness,templist))
##this is the breeding, mutation and death cycle iterations
for x in range(NumIterations):
##determine which two parents in current population will breed
parent1 = random.randint(0,population-1)
parent2 = parent1
while parent1 == parent2:
parent2 = random.randint(0,population-1)
##determine where crossover will happen
crossover = random.randint(1,len(objects)-1)
tempchild1 = PopulationSize[parent1][1]
tempchild2 = PopulationSize[parent2][1]
child1 = []
child2 = []
##apply crossover
for i in range(crossover):
child1.append(tempchild1[i])
child2.append(tempchild2[i])
for i in range(crossover,len(objects)):
child1.append(tempchild2[i])
child2.append(tempchild1[i])
##apply mutation on random gene (if selected by chance) on the two children
mutationchance = random.randint(0,1)
if mutationchance == 1:
mutation = random.randint(0,len(objects)-1)
if child1[mutation] == 0:
child1[mutation] = 1
else:
child1[mutation] = 0
mutationchance = random.randint(0,1)
if mutationchance == 1:
mutation = random.randint(0,len(objects)-1)
if child2[mutation] == 0:
child2[mutation] = 1
else:
child2[mutation] = 0
##get the fitness values of the two children
fitness1 = fitnessfunction(child1,objects,MaxWeight)
fitness2 = fitnessfunction(child2,objects,MaxWeight)
PopulationSize.append((fitness1, child1))
PopulationSize.append((fitness2, child2))
queue = PriorityQueue()
##load memebers of population into priority queue and pop off the lowest valued members
##this is the Killing process to keep total population size the same constant number
for i in range(len(PopulationSize)):
queue.put((PopulationSize[i][0], PopulationSize[i]))
queue.get()[1]
queue.get()[1]
PopulationSize = []
while queue.qsize():
PopulationSize.append(queue.get()[1])
max = 0
index = 0
##get the best member and display its values
for member in PopulationSize:
if max < member[0]:
max = member[0]
for i in range(len(PopulationSize)):
if PopulationSize[i][0] == max:
index = i
break
totweight = weight(PopulationSize[index][1],objects)
print ""
print "Best remaining member of population:"
print (PopulationSize[index])
print ""
print "Actual weight: %d" % totweight
print "Value: %d" % (PopulationSize[index][0])
|
f811b9393ae59c9cd34d20aebb4c7f4ea367ea22 | jbnicolai/code-eval | /240/main.py | 190 | 3.703125 | 4 | #!/usr/bin/env python3
import fileinput
primes = [ 3, 7, 31, 127, 2047 ]
for line in fileinput.input():
n = int(line)
print(', '.join(str(prime) for prime in primes if prime < n))
|
5277434b6d85a5db1eef2bee0136ecdf9dac421b | ankitkundra/PythonGettingStarted | /if.py | 275 | 4.0625 | 4 | num1 = input("Enter first number")
num2 = input("Enter second number")
if num1 > num2:
print("First number is greater than second number")
elif num2 > num1:
print("Second number is greater than first number")
else:
print("Both numbers are equal")
|
4208309dfccbc8af936e370140ded48d467638be | jocelinoFG017/IntroducaoAoPython | /01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_1_ao_21/S06_Ex17.py | 271 | 4.0625 | 4 | """
.17.Faça um programa que leia um número inteiro positivo N e calcule a soma dos N primeiros
números naturais.
"""
n = int(input('Informe um numero: '))
soma = 0
for i in range(0, n+1):
print(i)
soma = soma + i
print(f'soma de todos os Nº pares = {soma}')
|
ee4f6d83ea9242846e641e3a4de954dffccd6553 | lukasbystricky/ISC-3313 | /lectures/chapter6/code/Fraction.py | 1,632 | 3.625 | 4 | from gcd import gcd
class Fraction:
def __init__(self, numerator = 1, denominator = 1):
if denominator == 0:
self._top = 0
self._bottom = 0
else:
factor = gcd(abs(numerator), abs(denominator))
if denominator < 0:
factor = -factor
self._top = numerator // factor
self._bottom = denominator // factor
def __str__(self):
return str(self._top) + "/" + str(self._bottom)
def __float__(self):
return self._top/self._bottom
def __add__(self, other):
return Fraction(self._top * other._bottom +
self._bottom * other._top, self._bottom * other._bottom)
def __sub__(self, other):
return Fraction(self._top * other._bottom -
self._bottom * other._top, self._bottom * other._bottom)
def __mul__(self, other):
return Fraction(self._top * other._top, self._bottom * other._bottom)
def __truediv__(self, other):
return Fraction(self._top * other._bottom, self._bottom * other._top)
def __eq__(self, other):
return self._top == other._top and self._bottom == other._bottom
def __lt__(self, other):
return float(self) < float(other)
def __neg__(self):
return Fraction(-self._top, self._bttom)
def __abs__(self):
return Fraction(abs(self._top), self._bottom)
|
823fdd45a182f150332def0624a36e73d341505b | lemonzoe/python_origin | /d1/class2.py | 810 | 4.46875 | 4 | movies=[
"the holy grail",1975,"terry jones&terry gilliam",91,
["graham chapman",
["michael palin","john cleese","terry gilliam","eric idle","terry jones"]]]
print(movies[4][1][3])
print(movies)
for each_item in movies:
print(each_item)
# 显示嵌套列表
for each_item in movies:
if isinstance(each_item,list):
for nested_item in each_item:
print(nested_item)
else:
print(each_item)
# 只显示一个嵌套
for each_item in movies:
if isinstance(each_item,list):
for nested_item in each_item:
if isinstance(nested_item,list):
for deeper_item in nested_item:
print(deeper_item)
else:
print(nested_item)
else:
print(each_item)
# 可以将循环语句变为一个函数,使代码更精简 |
5e34b40d139e3ff6a730b1f33002792527401c41 | ramit29/Algorithms-Rosalind | /bfs.py | 356 | 3.84375 | 4 | #!/usr/bin/env python3
#requires graph represented as an adjacency list
def bfs(adlist,start):
visited=[]
queue=[start]
while queue:
vertex=queue.pop(0)
if vertex not in visited:
visited.append(vertex)
edges=adlist[vertex]
for i in edges:
queue.append(i)
return visited
|
8c1e38086ced083b43e3d4f3a9f16585ebd7d566 | Nibroo/PythonBootcamp | /whileColt/functions.py | 3,379 | 4.03125 | 4 | def product(a,b):
return a*b
print(product(5,6))
#*-------------------------------------------
days = ['None','Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
def return_day(num):
if 1 <= num <= 7:
return days[num]
return None
print(return_day(5))
print(return_day(10))
#*-------------------------------------------
nums = [1,2,3,4,5,6,7]
def last_element(which):
if which:
return which[-1]
return None
print(last_element(nums))
#*-------------------------------------------
def number_compare(a,b):
if a > b:
return 'First is Greater'
elif a < b:
return 'Second is Greater'
return 'Numbers are equal'
print(number_compare(10,1))
print(number_compare(199,199))
#*-------------------------------------------
def single_letter_count(string, ltr):
if ltr.lower() in string.lower():
return string.lower().count(ltr.lower())
return 0
print(single_letter_count('Python Bootcamp', 'p'))
print(single_letter_count('Iftekhar Nibir', 'p'))
#*-------------------------------------------
def multiple_letter_count(string):
return {l:string.count(l) for l in string}
print(multiple_letter_count('awesome'))
#*-------------------------------------------
def list_manipulation(collection, command, location, value=None):
if(command == "remove" and location == "end"):
return collection.pop()
elif(command == "remove" and location == "beginning"):
return collection.pop(0)
elif(command == "add" and location == "beginning"):
collection.insert(0,value)
return collection
elif(command == "add" and location == "end"):
collection.append(value)
return collection
print(list_manipulation([1,2,3], "remove", "end"))
print(list_manipulation([1,2,3], "remove", "beginning"))
print(list_manipulation([1,2,3], "add", "beginning", 20))
print(list_manipulation([1,2,3], "add", "end", 30))
#*-------------------------------------------
def is_palindrome(string):
string = string.replace(' ','').lower()
if string == string [::-1]:
return True
return False
print(is_palindrome('a man a plan a canal Panama'))
print(is_palindrome('Nibir'))
#*-------------------------------------------
def frequency(lis, search):
if search in lis:
return lis.count(search)
return 'Not Found'
print(frequency([1,2,3,3,'True','False','True'], 'True'))
#*-------------------------------------------
def multiply_even_numbers(nums):
total = 1
for n in nums:
if n%2==0:
total = total * n
return total
print(multiply_even_numbers([1,2,3,4,5,6,7,8,9]))
#*-------------------------------------------
def capitalize(string):
cap = string[0].upper()
low = string[1:]
return cap+low
print(capitalize('iftekhar'))
#*-------------------------------------------
def compact(lis):
return [v for v in lis if v]
print(compact([0,1,2,"",[], False, {}, None, "All done"]))
#*-------------------------------------------
def intersection(l1, l2):
return [val for val in l1 if val in l2]
print(intersection([1,4,6,9],[2,5,8,9]))
#*-------------------------------------------
def isEven(num):
return num % 2 == 0
def partition(lst, fn):
return [[val for val in lst if fn(val)], [val for val in lst if not fn(val)]]
print(partition([1,2,3,4], isEven)) |
5c18ce38e2c5cbe6e3ef0de775a3ecdc95cde468 | 99ashr/PyCode | /Infytq/Ass22.py | 678 | 4.3125 | 4 | #!/use/bin/python3
def find_leap_years(given_year):
"""A python Program to find a list of next 15 leap years"""
list_of_leap_years=[]
while len(list_of_leap_years)<15:
if given_year%4==0:
if given_year%100==0:
if given_year%400==0:
list_of_leap_years.append(given_year)
given_year+=1
else:
given_year+=1
else:
list_of_leap_years.append(given_year)
given_year+=1
else:
given_year+=1
return list_of_leap_years
list_of_leap_years=find_leap_years(1000)
print(list_of_leap_years) |
32f3c552360bb86f5a3217e376f107c31b5e60b3 | BadrChoujai/hacker-rank-solutions | /Python/04_Sets/Symmetric Difference.py | 355 | 3.65625 | 4 | # Problem Link: https://www.hackerrank.com/challenges/symmetric-difference/problem
# --------------------------------------------------------------------------------
a = int(input())
m = set(map(int, input().split()))
b = int(input())
n = set(map(int, input().split()))
c = m.difference(n)
d = n.difference(m)
e = c.union(d)
print(*sorted(e), sep='\n') |
89d59517290c85e07289d8d2173b9e4e0cf1f3d7 | ddot159/Python_Hw | /calculator.py | 1,486 | 4.4375 | 4 | def calculator(number1, number2, operator):
"""
Calculator uses the following operators on numbers 1 and 2:
addition (+),
subtraction(-),
multiplication(*)
division(/),
integer division (//)
power(**) operation
If the operator is invalid, the program exits
"""
output = 0
if operator == '+':
output = number1 + number2
return float(output)
elif operator == '-':
output = number1 - number2
return float(output)
elif operator == '*':
output = number1 * number2
return float(output)
elif operator == '/':
output = number1 / number2
return float(output)
elif operator == '//':
output = number1 // number2
return float(output)
elif operator == '**':
output = number1 ** number2
return float(output)
else:
return False #this condition makes it so that anything other than a string passes
def input_output():
'''
Asks if the user wishes to continue, if not, the program exits
'''
i = 0
while i == 0: #this statement is for an infinite loop
input1 = input('Enter the first number: ')
input2= input('enter the second number: ')
operation = input('enter the operator: ')
exit = ('Do you wish to exit? ')
if exit == y:
break #breaks the loop
|
126cbccf3efd4bd0f969aae2539a383154d5b7be | hoybyte/python | /ZeroToMastery/catseverywhere.py | 562 | 4.3125 | 4 | class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
def get_oldest_cat(*args):
return max(args)
Cat1 = Cat('Cat1', 2)
Cat2 = Cat('Cat2', 3)
Cat3 = Cat('Cujo', 4)
print(Cat1)
print(Cat2)
print(Cat3)
print(f"The oldest cat is {get_oldest_cat(Cat1.age, Cat2.age, Cat3.age)} years old.")
# 1 Instantiate the Cat object with 3 cats
# 2 Create a function that cinds the oldest cat
# 3 Print out: "The Oldest cat is x years old." x will be the oldest cat age by
# using the function in #2 |
e9be765e21c3437eb561b09c4403079b78892c04 | daniel-vv/ops | /S12/day1/string_format.py | 374 | 3.59375 | 4 | #!/usr/bin/env python
# coding:utf-8
name = input("name:")
age = input("age:")
job = input("job:")
#print("Information of []: \nName:["+ name +"]\nAge:["+ age +"]\nJob:["+ job +"]")
#print("Information of []: \nName:[%s] \nAge:[%s] \nJob:[%s]" %(name,age,job))
msg = '''
Information of:
Name:[%s]
Age:[%s]
Job:[%s]
''' %(name,age,job)
print(msg) |
16f23dd4c52d9c484c5f7688c2ca783ee87eb2bf | arovit/Coding-practise | /practise/dropbox.py | 583 | 4.09375 | 4 | #!/usr/bin/python
# binary search
def binary(startindex, endindex, elements, target):
if startindex > endindex:
return False
middleindex = (endindex + startindex)/2
if elements[middle] > target:
return binary(middleindex, endindex, elements, target)
elif elements[middle] < target:
return binary(startindex, middleindex, elements, target)
else:
return middleindex
def inorder_traversal(node):
if node.left:
inoder_traversal(node.left)
print node.data
if node.right:
inoder_traversal(node.right)
|
25873344a59a020a20271546ceb8840d862e29a7 | zhanghaipeng-alt/demo-python | /ck01/Demo/元组列表.py | 3,268 | 3.515625 | 4 | # 元组:值不能改变。
# 定义方式 a = (1,2,3)
# t = (2, 5, 6, 2, 8, 0, 54, 32, 'a', 8.9, '中国')
# # 分片
# print(t[2:12:1])
#
# # 倒序
# print(t[::-1])
#
# # 索引
# print(t.index('中国'))
#
# # 计数 元素出现的次数
# print(t.count(2))
data = ((1,'张三',4500.00),(2,'李四',7800.00),(3,'小黑',3599.00))
#循环打印所有员工信息
# for i in data:
# for j in i:
# print(j)
# 打印每个员工的工资
# count = 0
# for i in data:
# count += i[-1]
# print(f'平均工资是{(count/len(data)):.2f}')
# 打印工资最高工资及员工姓名
data1 = (('技术部',(367,500,45)),
('人力资源部',(247,368,1280)),
('财务部',(87,100,24,50)))
# 统计出费用总额
# count = 0
# for a in data1:
# for b in a[-1]:
# count += b
# print(f'本月总的打车费用为 ¥{count}')
# count = 0
# for a in data1:
# count += sum(a[-1])
# print(f'本月总的打车费用为 ¥{count}')
# 统计加班最少的部门
# total = 100000
# index = 0
# for x,y in enumerate(data1):
# if sum(y[-1]) < total:
# total = sum(y[-1])
# index = x
# print(data1[index][0])
# B中元素落入A中区间的次数
# A = ((5,7),(18,20),(35,37),(56,58),(3,89),(1,87))
# # B = (6,15,47,57,86)
# #
# # count = 0
# # for i in A:
# # for j in B:
# # if j >= i[0] and j <= i[-1]:
# # count +=1
# # print(count)
# 列表
# 列表的常用方法
# append extend
# list1 = ['fdop','合法你激活',[8.7,5]]
# list2 = [3,7,'fopd']
# list1.append(['fa',34])
# print(id(list2))
# list2.append(9)
# print(list2)
# print(id(list2))
#
# list2.extend([0])
# print(list2,id(list2))
# insert:在固定位置插入,第一个参数是索引位置
# list1 = [7,9,'for ',6,9,10]
# list1.insert(2,'pop')
# print(list1)
# pop函数,弹出list中的某些元素,不写参数则默认从最后一位
# list1 = [1,2,3,4,5,6,7]
# print(list1,id(list1))
#
# list1.pop()
# print(list1,id(list1))
#
# a = list1.pop(3)
# print(list1,id(list1))
# print(a)
# remove 删除:是按内容删除的。
# list1 = ['a','b','c','d','e','f']
# # print(list1,id(list1))
# # list1.remove('b')
# # print(list1,id(list1))
#
# for i in list1:
# list1.remove(i)
# print(list1, id(list1)) #会报错,越界了,list不能一边循环一边删除操作 python3不会,
#
# #可以从后往前循环
# list2 = ['a', 'b', 'c', 'd', 'e', 'f']
# print(list2, id(list2))
# for i in list2[::-1]:
# list2.remove(i)
# print(list2, id(list2))
#reverse:列表的翻转,相当于执行[::-1],是没返回值的
#sort排序函数和系统函数sorted reverse=True 默认为false true是倒序排列
# list1 = [3,2,7,9,2,5,8,0]
# # list1.sort(reverse=True)
# #
# # print(list1, id(list1))
#
# #系统内置的排序函数,带有返回值
# list2 = sorted(list1,reverse=True)
# print(list1,id(list1))
# print(list2,id(list2))
#列表去重
list1 = [3,4,8,1,2,3,4,6,8,2,5,4]
# 经典方法
# list2 = []
# for i in list1:
# if i not in list2:
# list2.append(i)
# print(list2)
# set方法
# list2 = set(list1)
# print(list2)
# 利用字典功能:先将list转成空字典,然后在转成list
list3 = list((dict.fromkeys(list1)).keys())
print(list3)
|
9286b7aee24767905921149295773769ed7e6643 | hakosaj/PygameAI | /snake/snek.py | 3,172 | 3.71875 | 4 | import sys
import os
import random
import time
import pygame
import math
from constants import *
from pygame.locals import *
from grid import *
class Snek:
def __init__(self, x, y, gr):
"""Initialize the snake
Args:
x (int): start position
y (int): start position y
gr (Grid): game grid
"""
self.x0 = x
self.y0 = y
self.grid = gr
self.squares = []
self.squares.append(self.grid.elementAt(x, y))
self.grid.elementAt(x, y).snake = True
# self.movement=0
self.movement = random.randrange(0, 7, 2)
self.dead = False
self.indexTable = [[0] * gr.x0 for i in range(gr.y0)]
def hed(self):
"""Snake head
Returns:
Square: first square of the snake
"""
return self.squares[0]
def resetIndexTable(self):
"""Reset hamiltionian path index table"""
self.indexTable = [[0] * self.grid.x0 for i in range(self.grid.y0)]
def tail(self):
"""Snake tail
Returns:
Square: last square of the snake
"""
return self.squares[-1]
def body(self):
"""Snake body excluding head and tail
Returns:
[Square]: list of squares the body consists of
"""
return self.squares[1:-1]
def length(self):
"""Length of the snake
Returns:
int: length
"""
return len(self.squares)
def moveSnake(self):
"""Move snake and do all the collision/food checks
Returns:
bool: snake ate food or not
"""
eaten = False
newSquare = self.grid.neighborAt(self.squares[0], self.movement)
if self.grid.walls:
if newSquare == None:
self.dead = True
if importantPrints:
print("Snek crashed into a wall")
return eaten
if (abs(self.squares[0].xcoord - newSquare.xcoord) > 2) or (
abs(self.squares[0].ycoord - newSquare.ycoord) > 2
):
self.dead = True
if importantPrints:
print("Snek crashed into a wall")
return eaten
if self.grid.checkCollision(self.squares, newSquare):
self.dead = True
if importantPrints:
print("Snek is dead:( \nYou tried to cross over yourself.")
return eaten
else:
if newSquare.food:
self.grid.randomFood()
eaten = True
else:
self.squares[-1].snake = False
self.squares.pop(-1)
self.squares.insert(0, newSquare)
newSquare.snake = True
return eaten
def changeOrientation(self, orientation):
"""Make sure snake cannot turn backwards
Args:
orientation (int): orientatio
Returns:
bool: can turn or not
"""
if abs(self.movement - orientation) != 4:
self.movement = orientation
return True
return False
|
28385b5c373d0d8fa55a2bbf4138db807b508457 | Janis90/snlp | /Project/implementation/Word.py | 7,213 | 4.03125 | 4 | import numpy as np
class Word():
"""The Word class represents simple words consisting of a prefix, a stem and a suffix
"""
def __init__(self, prefix, stem, suffix):
"""Creates a Word object out of the given parameters. To split up a string into prefix, stem and suffix, use
a splitting algorithm like levinstein distance
Parameters
----------
prefix : string
stem : string
suffix : string
"""
self.prefix = prefix
self.stem = stem
self.suffix = suffix
def to_string(self):
return "{}{}{}".format(self.prefix, self.stem, self.suffix)
def __str__(self):
return "{}{} - {} - {}{}".format("{", self.prefix, self.stem, self.suffix, "}")
class WordSplitter():
def __init__(self):
pass
def split_word(self, source, target):
pass
class LevinsteinPartition(WordSplitter):
def __init__(self):
super().__init__()
def split_word(self, source, target):
"""Splits a word into two Word objects with prefix, stem and suffix based on levenshtein distance.
E.g. schielen + geschielt => "" + "schiele" + "n" and "ge" + "schielt" + ""
Parameters
----------
source : string
Source word.
target : string
Target word.
Returns
-------
Word, Word
The Word object instances of the source and the target word with applied prefix, stem and suffix partition
"""
if source == target:
return Word("", source, ""), Word("", target, "")
s_len = len(source) + 1
t_len = len(target) + 1
matrix = np.zeros((s_len, t_len))
# calulate levenshtein distance matrix
for i in range(s_len):
for j in range(t_len):
if i == 0:
matrix[i][j] = j
elif j == 0:
matrix[i][j] = i
else:
case_1 = matrix[i - 1][j] + 1
case_2 = matrix[i][j - 1] + 1
equal = 0 if source[i - 1] == target[j - 1] else 1
case_3 = matrix[i - 1][j - 1] + equal
matrix[i][j] = min(case_1, case_2, case_3)
# create annotated words
source_word = ''
target_word = ''
i = s_len - 1
j = t_len - 1
# matrix backtracking
while i != 0 or j != 0:
if i == 0:
source_word = '_' + source_word
target_word = target[j - 1] + target_word
j = j - 1
elif j == 0:
target_word = '_' + target_word
source_word = source[i - 1] + source_word
i = i - 1
else:
above_e = matrix[i - 1][j]
left_above_e = matrix[i - 1][j - 1]
min_e = min(above_e, above_e, left_above_e)
if min_e == above_e:
target_word = '_' + target_word
source_word = source[i - 1] + source_word
i = i - 1
elif min_e == left_above_e:
source_word = source[i - 1] + source_word
target_word = target[j - 1] + target_word
i = i - 1
j = j - 1
else:
source_word = '_' + source_word
target_word = target[j - 1] + target_word
j = j - 1
source_word_a = np.array(list(source_word))
target_word_a = np.array(list(target_word))
stem_mask = np.zeros(len(source_word), dtype=bool)
prefix_mask = np.zeros(len(source_word), dtype=bool)
suffix_mask = np.zeros(len(source_word), dtype=bool)
for i in range(len(source_word)):
if source_word_a[i] != "_" and target_word_a[i] != "_":
stem_mask[i] = True
for i in range(len(source_word)):
if (source_word_a[i] == "_" and target_word_a[i] != "_") or (source_word_a[i] != "_" and target_word_a[i] == "_"):
prefix_mask[i] = True
else:
break
for i in reversed(range(len(source_word))):
if (source_word_a[i] == "_" and target_word_a[i] != "_") or (source_word_a[i] != "_" and target_word_a[i] == "_"):
suffix_mask[i] = True
else:
break
# generate source word
stem = "".join(source_word_a[stem_mask])
prefix = "".join(source_word_a[prefix_mask])
suffix = "".join(source_word_a[suffix_mask])
prefix = prefix.replace("_", "")
suffix = suffix.replace("_", "")
new_source_word = Word(prefix, stem, suffix)
# generate target word
stem = "".join(target_word_a[stem_mask])
prefix = "".join(target_word_a[prefix_mask])
suffix = "".join(target_word_a[suffix_mask])
prefix = prefix.replace("_", "")
suffix = suffix.replace("_", "")
new_target_word = Word(prefix, stem, suffix)
return new_source_word, new_target_word
class KhalingXFixPartition(WordSplitter):
def __init__(self):
super().__init__()
self.prefix_list = ["ʔi", "mu", "mʌ"]
self.suffix_lists = [["ŋ", "i", "k", "n"],
["de", "tʰer", "kʰʌ"],
["ŋʌ", "nɛ", "ʌ", "u", "i", "k"],
["t", "w"],
["ʌkʌ", "iki", "ŋʌ", "ki", "ɛ", "ʌ", "u", "i"],
["si", "su", "n"],
["su", "nu", "ni"]]
def __check_and_cut_prefix(self, input_str):
for pos_prefix in self.prefix_list:
if input_str.startswith(pos_prefix):
# return prefix and the remaining word
return pos_prefix, input_str[len(pos_prefix):]
# if no prefix from the list found, return empty prefix
return "", input_str
def __check_and_cut_suffixes(self, input_string):
res_suffixes = []
for suffix_list in reversed(self.suffix_lists):
for pos_suffix in suffix_list:
# save suffix and cut off from word
if input_string.endswith(pos_suffix):
res_suffixes.append(pos_suffix)
input_string = input_string[:len(input_string) - len(pos_suffix)]
return input_string, reversed(res_suffixes)
def split_word(self, source, target):
src_prefix, scr_stem_suffix = self.__check_and_cut_prefix(source)
src_stem, src_suffix_list = self.__check_and_cut_suffixes(scr_stem_suffix)
source_word = Word(src_prefix, src_stem, "".join(src_suffix_list))
tgt_prefix, tgt_stem_suffix = self.__check_and_cut_prefix(target)
tgt_stem, tgt_suffix_list = self.__check_and_cut_suffixes(tgt_stem_suffix)
target_word = Word(tgt_prefix, tgt_stem, "".join(tgt_suffix_list))
# print("SOURCE: {} - TARGET: {}".format(source_word, target_word))
return source_word, target_word
|
8dabcfc69f0676da9dd1828d99c19c69c79c4cd7 | hellicott/hangman | /word.py | 1,184 | 3.84375 | 4 | import random
from alphabet import Alphabet
class Word(object):
possible_words = ['quack', 'aardvark', 'rhythm']
def __init__(self, alphabet: Alphabet):
self.word_to_guess = self.pick_word()
self.alphabet = alphabet
def pick_word(self):
return random.choice(self.possible_words)
def get_letters(self):
return set(self.word_to_guess)
def guess_letter(self, letter):
self.alphabet.cross_off(letter)
return letter in self.get_letters()
def guess_word(self, word):
return word == self.word_to_guess
def check_win(self):
return self.get_letters().issubset(self.alphabet.guessed_letters)
def get_info(self):
info_string = "Here's your word: {}\n".format(str(self)) + str(self.alphabet)
return info_string
def __len__(self):
return len(self.word_to_guess)
def __str__(self):
hidden_word = self.word_to_guess
for letter in self.get_letters():
if letter not in self.alphabet.guessed_letters:
hidden_word = hidden_word.replace(letter, '_')
return hidden_word
|
12348f3f5d28eae3709395ed29d90be217e4ea6d | DilLip-Chowdary-Codes/100DaysOfCode | /Python/Loops/print_Chars_in_a_Word.py | 190 | 3.65625 | 4 | #25
"""
__author__ = DilLip_Chowdary ❤️ Rayapati
"""
a = input()
counter = 0
length_of_a = len(a)
while counter < (length_of_a):
print(a[counter])
counter = (counter + 1)
|
41be49e4cdd1c99d77e0d9cdcf54f47f42a16130 | RossMcKay1975/Python_Day2 | /generators.py | 234 | 3.8125 | 4 | # numbers = range(11)
#
# for number in numbers:
# print(number)
def generate_evens(n):
i = 0
while i < n:
if i % 2 == 0:
yield i
i += 1
for number in generate_evens(10):
print(number)
|
ed46b1526ec191f1f9dfb88efbeb2f4e58773d98 | Aasthaengg/IBMdataset | /Python_codes/p02722/s439672872.py | 394 | 3.5 | 4 | import numpy as np
N = int(input())
def divisor(N):
x = np.arange(1, int(N**(1/2))+1, dtype=np.int64)
div = set(x[N % x == 0])
return div | set(N // x for x in div)
cand = divisor(N) | divisor(N - 1)
def test(N, K):
if K == 1:
return False
while N % K == 0:
N //= K
return N % K == 1
answer = sum(test(N, d) for d in cand)
print(answer) |
4ed10deca016d883ce5d1c86bb9bdbdeb6801267 | SACHSTech/ics2o1-livehack-2-keira-h | /problem1.py | 880 | 4.40625 | 4 | """
----------------------------------------------------------
Name: problem1.py
Purpose: Write a program that tells the user whether they are over or under the given speed limit. If they are over the speed limit, they will be given a fine.
Author: Hosey.K
Created: date in 23/02/2021
----------------------------------------------------------
"""
# Get the information
spd_limit = float(input("Enter the speed limit: "))
driver_spd = float(input("Enter the recorded speed of the car: "))
# Compute and Output
if driver_spd >= spd_limit:
if driver_spd - spd_limit <= 20:
print("You are speeding and your fine is $100")
elif driver_spd - spd_limit <= 30:
print("You are speeding and your fine is $270")
elif driver_spd - spd_limit >= 31:
print("You are speeding and your fine is $570")
else:
print("Congratulations, you are within the speed limit!")
|
4d35019f85a173fba6e120586a4d1779a4638ed2 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/allergies/25c039a0d30246abbf53c79ea832b51a.py | 472 | 3.75 | 4 | class Allergies(object):
def __init__(self, score):
self.score = score
self.check_allergies()
def check_allergies(self):
self.list = []
possible = "eggs peanuts shellfish strawberries tomatoes chocolate pollen cats".split()
results = bin(self.score)[:1:-1].ljust(8,'0')
for i in range(len(possible)):
if results[i] == '1':
self.list.append(possible[i])
def is_allergic_to(self, food):
if food in self.list:
return True
return False
|
052051d8aefac964409a0547d5e6bc521f003fa0 | IlshatVEVO/Data-Analys-Labs | /LAB5/6.py | 317 | 3.78125 | 4 | #Дана случайная матрица. Вычтите среднее значение для каждой строки матрицы.
import numpy as np
a = np.random.randint(10, size=(5,5))
print(a)
sum = int(0)
for i in range(len(a)):
for j in range(len(a)):
sum +=a[i][j]
print(sum/len(a))
|
9a5ba184f874c11a9aa8305aed961603b96a2afc | gurvkm/placement | /make_matrix_zero.py | 963 | 3.640625 | 4 | import numpy as np
#define the array arr
arr=np.array([[0,4,1,0],
[3,2,1,5],
[1,0,7,2]])
row,col=np.shape(arr)
#create flags for row and column
first_row=bool(0)
first_col=bool(0)
#step1: if 0 present in any col or row make entire col or row 0
for i in range(row):
if arr[i][0]==0:
first_col=1
for j in range(col):
if arr[0][j]==0:
first_row=1
#step 2: iterate matrix from a[1][1] till last
# if a[i][j] is 0 make a[i][0] and a[0][j]=0
for i in range(1,row):
for j in range(1,col):
if arr[i][j]==0:
arr[i][0]=0
arr[0][j]=0
#again iterate same as step 2 this time if
#a[i][0] and a[0][j]=0 make a[i][j]=0
for i in range(1,row):
for j in range(1,col):
if arr[i][0]==0 or arr[0][j]==0:
arr[i][j]=0
#check row flag if true make all elements of
#first row 0 and same for col
if first_row==True:
for j in range(col):
arr[0][j]=0
if first_col==True:
for i in range(row):
arr[i][0]=0
print(arr)
|
9f5dd915ab9cf7dacb8f93be4262ad1702afaa6a | simonsben/intent_detection | /utilities/pre_processing/process.py | 2,562 | 3.5 | 4 | from multiprocessing import Pool
from pandas import DataFrame, read_csv
from functools import partial
from config import n_threads
def apply_process(packed_data, processes, get_content, save_content):
"""
Applies the pre-processing filters to a document
:param packed_data: a tuple of document index, document
:param processes: list of processes to be applied
:param get_content: function that acts as an accessor for the dataset
:param save_content: function that acts a mutator (ish..) for the dataset
:return: list of pre-processing values and
"""
index, document = packed_data
values = [index]
content = get_content(document)
for process in processes: # For each pre-processing step to be applied
value, content = process(content if isinstance(content, str) else '')
if value is not None:
values.append(value)
return save_content(content, values, document)
def process_documents(source_filename, dest_filename, processes, get_content, save_content, save_header, options):
"""
Pre-processes all documents within a CSV file.
Assumed that files are too large to fit in memory, file is processed line-by-line.
:param source_filename: Filename for the source CSV file
:param dest_filename: Filename for destination file
:param processes: List of pre-processing functions, (document_content) -> (value, modified_content)
:param get_content: Accessor for source file, (document) -> (document_content)
:param save_content: Mutator for destination file (row) (modified_content, values, document) -> (modified_document)
:param save_header: Header for destination file, List
:param options: Accepts options for document including
delimiter of the source file, (default ',')
max_documents to be pre-processed, (default is entire file)
"""
max_documents = options['max_documents'] if 'max_documents' in options else None
encoding = options['encoding'] if 'encoding' in options else None
dataset = read_csv(source_filename, encoding=encoding, index_col=0, nrows=max_documents).values
workers = Pool(n_threads)
processed_data = workers.map(
partial(apply_process, processes=processes, get_content=get_content, save_content=save_content),
enumerate(dataset)
)
workers.close()
workers.join()
processed_data = DataFrame(processed_data, columns=save_header)
processed_data.to_csv(dest_filename, index=False)
|
d44dbf980fe2867be0269a0b94113da186c8ccc4 | arpitiiitv/PythoN-From-P-to-N | /AH_set.py | 294 | 3.609375 | 4 | s=set()
print(type(s))
s1=set([1,3,4,5,6])
print(s1)
s2=set([12,1,3,44,10])
print(s2)
s1.add(312)
print(s1)
##################
x=s1.union(s2)
print('Union ',x)
y=s1.intersection(s2)
print("intersection ",y)
print("is disjoint ",s1.isdisjoint(s2))
#length of set
print(len(y))
|
6ebf6b111608ce472bcd90e95544beca4aecbe8a | korneyrodionov/pythonbook | /тест эрудит.py | 2,139 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def check_guess(guess, answer):
global score
still_guessing = True
attempt = 0
while still_guessing and attempt < 2:
if guess.lower() == answer.lower():
print('Ответ верный')
score = score + 2 - attempt
still_guessing = False
else:
if attempt < 1:
guess = input ('Ответ НЕВЕРНЫЙ. Попробуйте еще раз. ')
attempt = attempt + 1
if attempt == 2:
print('Правильный ответ: ' + answer)
score = 0
print('тест эрудит')
guess1 = input('Год на Руси называется: \n \
1) лето\n 2) зима\n 3) осень\n 4) весна\n \
Введите 1, 2, 3 или 4. ')
check_guess(guess1, '1')
guess2 = input('Кланяется, кланяется, придет домой - растянется: \n \
1) пила\n 2) человек\n 3) топор\n \
Введите 1, 2 или 3. ')
check_guess(guess2, '3')
guess3 = input('Символ русских муз. инструментов: \n \
1) гусли\n 2) бубен\n 3) балалайка\n \
Введите 1, 2 или 3. ')
check_guess(guess3, '3')
guess4 = input('Сидит девица в темнице, а коса на улице: \n \
1) морковь\n 2) капуста\n 3) пшеница\n \
Введите 1, 2 или 3. ')
check_guess(guess4, '1')
guess5 = input('Старинное название торговца: \n \
1) купец\n 2) городничий\n 3) гость\n \
Введите 1, 2 или 3. ')
check_guess(guess5, '3')
guess6 = input('Число 10.000 в старинном русском счете называлось: \n \
1) куча\n 2) тьма\n 3) много\n \
Введите 1, 2 или 3. ')
check_guess(guess6, '2')
guess7 = input('Какое из этих животных рыба? \n \
1) Кит\n 2) Дельфин\n 3) Акула\n 4) Кальмар\n \
Введите 1, 2, 3 или 4. ')
check_guess(guess7, '3')
print('Вы набрали очков: ' +str(score))
|
39a1ef67fbb24e72dde348950eeb09c63a5fd4f1 | 3-clique/Elements-of-Programming-Interviews-Problems | /6.1.py | 1,739 | 3.84375 | 4 | def swap(A, dest, src):
temp = A[dest]
A[dest] = A[src]
A[src] = temp
return
def dutch_flag_partition (A, pivotIndex):
"""
Given an array of ints and a pivot index,
partition A such that
- all elements of A < A[pivot_index] are at the begining
- all elements of A < A[pivot_index] are at the middle
- all elements of A < A[pivot_index] are at the end
"""
nextL = 0
nextG = len(A)-1
nextM = 0;
pivot = A[pivotIndex]
"""
Keep the following invariants:
- A[0:nextL] < pivot
- A[nextL: nextM] = pivot
- A[nextG: leb(A)] > pivot
"""
while (nextM <= nextG):
if (A[nextM] < pivot):
swap(A, nextL, nextM)
nextL += 1
nextM += 1
elif (A[nextM] == pivot):
nextM += 1
else:
#A[nextM] > pivot
swap(A, nextG, nextM)
nextG -= 1
return A
def test_dutch_flag_partition():
#test for minimum element
A = [4, 5,3,6,99,8,4,5,7,8,25,8,6,457,21,5,6,97,23]
m = min(A)
B = dutch_flag_partition(A, A.index(m))
if (B[0] != m):
return false
for i in range (1, len(B)):
if B[i] <= m:
return False
#test for maximum element
mx = max(A)
B = dutch_flag_partition(A, A.index(mx))
if (B[len(A)-1] != mx):
return False
for i in range (0, len(B)-1):
if B[i] >= mx:
return False
#test for a middle element
B = dutch_flag_partition(A, A.index(25))
for i in range (0, len(B)-1):
if (B[i] >= 25) and (i < len(B)-4):
return False
if (B[len(B)-4] != 25):
return False
return True
print test_dutch_flag_partition()
|
7d1ba2aa5c36f221c7592888192ea15ca6fd6a17 | KotRom/pythonProject1 | /New folder/023_flask/003_http_methods.py | 1,097 | 3.71875 | 4 | from flask import Flask, redirect, url_for, render_template, request
# request is used to get information from forms
app = Flask(__name__)
'''
Files needed:
base2.html
home2.html
login.html
'''
# First let's check what is GET and POST
# Run app, try refreshing, look in command line
# 127.0.0.1 - - [05/May/2021 14:50:42] "GET / HTTP/1.1" 200 -
# GET request is used
@app.route("/")
def home():
return render_template('home2.html')
# POST method is used when we submit form from HTML page
# Check form in login.html
# methods=["POST", "GET"] is a must for pages with forms
@app.route("/login", methods=["POST", "GET"])
def login():
# request.method returns method that is used to load a page
if request.method == "POST":
# request.form['<field_name>'] is used to get data from form inputs
user_name = request.form['nm']
return redirect(url_for('user', usr=user_name))
else:
return render_template("login.html")
@app.route("/<usr>")
def user(usr):
return f"<h1>{usr}</h1>"
if __name__ == "__main__":
app.run(debug=True) |
700eb0990b3bca024730b9d825f3e1377f05d8c0 | petitefille/Python | /innlevering/Cubic_Poly4.py | 1,987 | 3.890625 | 4 | class Line:
def __init__(self, c0, c1):
self.c0 = c0
self.c1 = c1
def __call__(self, x):
y_Line = self.c0+ self.c1*x
print 'Line: %.3f' % (y_Line)
return self.c0+ self.c1*x
def table(self, L, R, n):
"""Return a table with n points for L <= x <= R."""
s = ''
import numpy as np
for x in np.linspace(L, R, n):
y = self(x)
s += '%12g %12g\n' % (x, y)
print s
class Parabola(Line):
def __init__(self, c0, c1, c2):
Line.__init__(self, c0, c1) # let Line store c0 and c1
self.c2 = c2
def __call__(self, x):
y_Parabola = Line.__call__(self, x) + self.c2*x**2
print 'Parabola: %.3f' % (y_Parabola)
return Line.__call__(self, x) + self.c2*x**2
class Cubic(Parabola):
def __init__(self, c0, c1, c2, c3):
Parabola.__init__(self, c0, c1, c2)
self.c3 = c3
def __call__(self, x):
y_Cubic = Parabola.__call__(self, x) + self.c3*x**3
print 'Cubic: %.3f' % (y_Cubic)
return Parabola.__call__(self, x) + self.c3*x**3
class Poly4(Cubic):
def __init__(self, c0, c1, c2, c3, c4):
Cubic.__init__(self, c0, c1, c2, c3)
self.c4 = c4
def __call__(self, x):
y_Poly4 = Cubic.__call__(self, x) + self.c4*x**4
print 'y_Poly4:%.3f' % (y_Poly4)
return Cubic.__call__(self, x) + self.c4*x**4
p = Cubic(2, 4,-5, 6)
p1 = p(x= -4.5)
p = Poly4(1, -2, 2, 3, -3)
p1 = p(x=2.5)
"""
Terminal > Cubic_Poly4.py
Line: -16.000
Parabola: -117.250
Line: -16.000
Cubic: -664.000
Line: -16.000
Parabola: -117.250
Line: -16.000
Line: -4.000
Parabola: 8.500
Line: -4.000
Cubic: 55.375
Line: -4.000
Parabola: 8.500
Line: -4.000
y_Poly4:-61.812
Line: -4.000
Parabola: 8.500
Line: -4.000
Cubic: 55.375
Line: -4.000
Parabola: 8.500
Line: -4.000
"""
|
0f2fd29c8c52ee79a3eb1d635f241e0a6b33ff85 | mc0e/morphio-Australian_Election_Dates | /scraper.py | 1,172 | 3.609375 | 4 | # Closely based on a template for a Python scraper from morph.io (https://morph.io)
import scraperwiki
import lxml.html
# # Read in page data
html = scraperwiki.scrape("http://www.aec.gov.au/Elections/Australian_Electoral_History/Federal_State_and_Territory_elections_dates_1946_Present.htm")
#
# # Find something on the page using css selectors
root = lxml.html.fromstring(html)
for tr in root.cssselect("tbody>tr"):
tds=tr.cssselect("td")
year=tds[0].text_content()
date=tds[1].text_content()
electionType=tds[2].text_content()
#
# # Write out to the sqlite database using scraperwiki library
scraperwiki.sqlite.save(unique_keys=['electionType','year'], data={"year": year, "date": date, "electionType": electionType})
#
# # An arbitrary query against the database
# scraperwiki.sql.select("* from data where 'name'='peter'")
# You don't have to do things with the ScraperWiki and lxml libraries.
# You can use whatever libraries you want: https://morph.io/documentation/python
# All that matters is that your final data is written to an SQLite database
# called "data.sqlite" in the current working directory which has at least a table
# called "data".
|
7cbe8b80f4162ce202585375500a2c1624a4970f | grickoff/GeekBrains_5HW | /1.py | 555 | 4.21875 | 4 | # Создать программно файл в текстовом формате, записать в него построчно
# данные, вводимые пользователем.Об окончании ввода данных свидетельствует пустая строка.
f = open('HW1.txt', 'w')
write = []
while write != (''):
write = input('Вводите построчно данные или оставьте поле ввода пустым для завершения: ')
f.writelines( f'\n {write}')
f.close() |
aee865f308adb873b32abfe59a307e996cc357d4 | Rodelph/VideoManager | /depth.py | 1,440 | 3.671875 | 4 | import numpy as np
"""
To identify outliers in the disparity map, we first find the median using np.median which takes an array as an argument. If the array is of an odd length,
median returns the value that would lie i nthe middle of the array if the array were sorted. If the arrray is of an even length, median returns the average
of the two valeurs that would be sorted nearest to the middle of the array.
"""
def createMedianMask(disparityMap, validDepthMask, rect = None):
"""Return a mask selecting the median layer, plus shadows."""
if rect is not None:
x, y, w, h = rect
disparityMap = disparityMap[y:y+h, x:x+w]
validDepthMask = validDepthMask[y:y+h, x:x+w]
median = np.median(disparityMap)
return np.where((validDepthMask == 0) | \
(abs(disparityMap - median) < 12), 255, 0).astype(np.uint8)
"""
To generate a mask based on per-pixel BOolean operations, we use np.where width three arguments. In the fist arguemetn , where takes an array whose elements are
evaluated for thruth and falsity. An output array of the same dimensions is returned. Wherever an element in the input array is True, the where functions's second
argument is assigned to to the corrrespondig element in the output array. Conversely, wherever an element in the input aray os False, the where function's third
argument is assigned to the corresponding element in the outpyt array.
"""
|
f20bf01193c7e4bc7478bd196b3a41a1576dfbc5 | tanishq-dubey/Tobias | /TobiasPyFiles/enemies.py | 1,156 | 3.765625 | 4 | class Enemy(object):
def __init__(self, name, description, hp, ap, damage):
self.name = name
self.description = description
self.hp = hp
self.ap = ap
self.damage = damage
def __str__(self):
return "{}:\n{}\nHealth: {}\t Armor: {}\n".format(self.name, self.description, self.hp,self.ap)
def is_alive(self):
return self.hp > 0
def uses_armor(self):
return self.ap > 0
class SpacePirate(Enemy):
def __init__(self):
super(SpacePirate, self).__init__(name="Space Pirate", description="A scurvy bandit who just wants your money, and you're in his way", hp= 10, ap=0, damage=2)
class RobotUnderling(Enemy):
def __init__(self):
super(RobotUnderling, self).__init__(name="Robot Underling", description="A simple minded robot that tries its best to aim for you (it really does).", hp=20, ap=0, damage=5)
class RobotOverlord(Enemy):
def __init__(self):
super(RobotOverlord, self).__init__(name="Robot Overlord", description="So this is what those mad scientists were talking about when they said robot annihilation.", hp=75, ap=25, damage=20)
|
3e1f29c50d71853d0aa41b435a1e8e8506d5447f | douzujun/LeetCode | /py74_290_wordPattern.py | 515 | 3.5625 | 4 | # -*- coding: utf-8 -*-
class Solution:
def wordPattern(self, pattern: str, str1: str) -> bool:
pli = list(pattern)
sli = str1.split()
plen = len(pli)
slen = len(sli)
if plen != slen:
return False
for i in range(slen):
if pli.index(pli[i]) != sli.index(sli[i]):
return False
return True
s = Solution()
print(s.wordPattern("abba", "dog cat cat dog"))
print(s.wordPattern("aaa", "aa aa aa aa")) |
b1c863166fcc509a61ec6e7df70babc7d5e2e3e4 | kiryeong/python_basic_study | /Quiz2.py | 2,377 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 22:23:53 2020
@author: SAMSUNG
"""
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:]) #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")) #Python을 Java로 바꾼다.
index = python.index("n")
print(index)
index = python.index("n",index + 1)
print(index)
'''
print(python.find("Java")) #원하는 값이 없을때는 -1
print(python.index("Java")) #원하는 값이 없을때는 오류가 나고 종류됨
print(python.count("n")) #n이 총 몇번 등장하느냐
'''
#방법1
print("나는 %d살입니다." % 20)
print("나는 %s을 좋아해요" % "파이썬") # %s는 문자열
print("Apple 은 %c로 시작해요." % "A") # %c는 한 글자
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 = "빨간"))
#방법4
age = 20
color = "빨간"
print(f"나는 {age}살이며, {color}색을 좋아해요.")
print("백문이 불여일견\n백견이 불여일타") #\n줄바꿈
#저는 "나도코딩" 입니다.
print("저는 \"나도코딩\"입니다.") #\" 또는 \' : 문장 내에서 따옴표
#\\ : 문장 내에서 \
#\r : 커서를 맨 앞으로 이동
print("Red Apple\rPine")
#\b : 백스페이스 (한 글자 삭제)
print("Redd\bApple")
#\t : 탭
print("Red\tApple")
|
9f8c069d48276bc36604e24dca5557f3945e1e1b | VictorCavichioli/Julius | /2) Backend/Conversor.py | 807 | 3.609375 | 4 | from currency_converter import CurrencyConverter
from config import sai_som
def Conversor_Moedas():
c = CurrencyConverter()
sai_som('''
Para realizar a conversão, use os seguintes códigos:
''')
print('''
'EUR' - para Euros;
'CAD' - para dólar Canadense;
'USD' - para dólar americano;
'BRL' - para real brasileiro;
'GBP' - para libra;
''')
sai_som('Qual é a moeda do seu valor? ')
actually = str(input('')).upper()
sai_som('Qual é o seu valor? ')
valor = float(input(''))
sai_som('Qual é a sua moeda final? ')
final = str(input('')).upper()
convert = c.convert(valor, actually, final)
sai_som(f'{valor} {actually} são {convert:.2f} {final}. ')
|
b61fb26a16d1e8af91a97d2c15eb0d1194062738 | ayushchauhan09/Mini | /Projects/Guessing_Game.py | 533 | 3.75 | 4 | import random
winning_number=random.randint(1,100)
guess=1
guessed_number=int(input())
game_over=False
while not game_over:
if winning_number==guessed_number:
print(f"\U0001F973 Congrats! You Won! And You Guessed This Number In {guess} Attempts!!!")
game_over=True
else:
if winning_number>guessed_number:
print("\U0001F61E OOPS! It's Low.")
else:
print("\U0001F61E OOPS! It's High.")
guess+=1
guessed_number=int(input("Guess Again : "))
|
70ff0d816f6ac74fee122e8f48559a66b87e7e9d | oliverschwartz/leet | /ctci/bit_string.py | 123 | 3.5625 | 4 | def bitString(n):
s = ''
for i in range(31, -1, -1):
s += '1' if ((1 << i) & n) != 0 else '0'
return s
|
be23afe8dfce2cbe87833da8cdacc9632e8b2409 | syurskyi/Python_Topics | /115_testing/examples/Github/_Level_1/UnitTesting-master/Proj4/ListsAndTuples/listAndTuples.py | 2,223 | 4.03125 | 4 | import sys
import timeit
# https://www.youtube.com/watch?v=NI26dqhs2Rk
# Tuple is a smaller faster alternative to a list
# List contains a sequence of data surrounded by brackets
# Tuple contains a squence of data surrounded by parenthesis
""" Lists can have data added, removed, or changed
Tuples cannot change. Tuples can be made quickly.
"""
# List example
prime_numbers = [2, 3, 5, 7, 11, 13, 17]
# Tuple example
perfect_squares = (1, 4, 9, 16, 25, 36)
# Display lengths
print("# Primes = ", len(prime_numbers))
print("# Squares = ", len(perfect_squares))
# Iterate over both sequences
for p in prime_numbers:
print("Prime: ", p)
for n in perfect_squares:
print("Square: ", n)
print("")
print("List Methods")
print(dir(prime_numbers))
print(80*"-")
print("Tuple methods")
print(dir(perfect_squares))
print()
print(dir(sys))
print(help(sys.getsizeof))
print()
list_eg = [1, 2, 3, "a", "b", "c", True, 3.14159]
tuple_eg = (1, 2, 3, "a", "b", "c", True, 3.14159)
print("List size = ", sys.getsizeof(list_eg))
print("Tuple size = ", sys.getsizeof(tuple_eg))
print()
list_test = timeit.timeit(stmt="[1, 2, 3, 4, 5]", number=1000000)
tuple_test = timeit.timeit(stmt="(1, 2, 3, 4, 5)", number=1000000)
print("List time: ", list_test)
print("Tuple time: ", tuple_test)
print()
## How to make tuples
empty_tuple = ()
test0 = ("a")
test1 = ("a",) # To make a tuple with just one element you need to have a comma at the end
test2 = ("a", "b")
test3 = ("a", "b", "c")
print(empty_tuple)
print(test0)
print(test1)
print(test2)
print(test3)
print()
# How to make tuples part 2
test1 = 1,
test2 = 1, 2
test3 = 1, 2, 3
print(test1)
print(test2)
print(test3)
print()
# (age, country, knows_python)
survey = (27, "Vietnam", True)
age = survey[0]
country = survey[1]
knows_python = survey[2]
print("Age =", age)
print("Country =", country)
print("Knows Python?", knows_python)
print()
survey2 = (21, "Switzerland", False)
age, country, knows_python = survey2
print("Age =", age)
print("Country =", country)
print("Knows Python?", knows_python)
print()
# Assigns string to variable country
country = ("Australia")
# Here country is a tuple, and it doesnt unpack contents into variable
country = ("Australia",) |
ec5b83e634b38c0b62c7d4ade8382bfdc5559775 | rayjustinhuang/CS175 | /isSigmaAlgebra (Final).py | 2,591 | 3.90625 | 4 | # CS 175: Topics in Computational Science - Probability and Stochastics
# Assignment: Program to check if a set of sets is a sigma-algebra (of some given universal set)
def is_sigma_algebra(space, sets):
"""
This function checks if a given set of sets is a sigma-algebra of a given sample space ("universal set").
:param space: list
An iterable containing the universe of objects (sample space)
:param sets: list of lists
A set of sets to check against the sample space
:return: boolean
True if 'sets' is a sigma-algebra of 'space'
"""
check = []
if [] not in sets:
return False
if not set([element for subset in sets for element in subset]) == set(space):
return False
for i in sets:
i.sort()
for i in sets:
for j in sets:
if not i == j:
m = sorted(list(set(i + j)))
check.append(m in sets)
for i in sets:
temp = sorted(list(set(space).difference(set(i))))
check.append(temp in sets)
if temp in sets:
sets.remove(temp)
return all(check)
test_space1 = ['A', 'B', 'C', 'D', 'E']
test_sets1 = [['A', 'B'], ['C', 'D', 'E'],[],['A','B','C','D','E']]
test_space2 = [1, 2, 3, 4, 5, 6]
test_sets2 = [[1, 2], [4], [5, 6], [4, 3, 5],[],[3,4,5,6],[6,2,3,5,1],[1,2,3,4],[1,2,6],[1,2,3,4,5,6]]
test_space3 = ['chess', 'checkers', 'backgammon']
test_sets3 = [['chess'], ['poker', 'backgammon'], ['chess', 'checkers', 'backgammon'],[],['checkers','backgammon'],['chess','checkers']]
test_space4 = ['Clark', 'Bruce', 'Diana']
test_sets4 = [['Clark', 'Bruce', 'Diana'], []]
test_space5 = ['Superman', 'Green Lantern', 'Flash', 1, 5, 9]
test_sets5 = [['Superman', 1], ['Green Lantern'], [5, 9, 'Flash']]
test_space6 = ['Universal', 'Disney']
test_sets6 = [[]]
test_space7 = ['Green', 'Blue', 'Red', 'Yellow']
test_sets7 = [['Green', 'Blue', 'Red', 'Yellow'],[]]
test_space8 = ['a','b','c','d']
test_sets8 = [[],['a','b'],['c','d'],['a','b','c','d']]
print(is_sigma_algebra(test_space1, test_sets1), "- test 1") # True
print(is_sigma_algebra(test_space2, test_sets2), "- test 2") # False
print(is_sigma_algebra(test_space3, test_sets3), "- test 3") # False
print(is_sigma_algebra(test_space4, test_sets4), "- test 4") # True
print(is_sigma_algebra(test_space5, test_sets5), "- test 5") # False
print(is_sigma_algebra(test_space6, test_sets6), "- test 6") # False
print(is_sigma_algebra(test_space7, test_sets7), "- test 7") # True
print(is_sigma_algebra(test_space8, test_sets8), "- test 8") # True
|
89e4fc713e5f324269f58e4b4ec13ccfdd772174 | yaominzh/CodeLrn2019 | /boboleetcode/Play-Leetcode-master/0064-Minimum-Path-Sum/py-0064/Solution3.py | 860 | 3.5625 | 4 | # Source : https://leetcode.com/problems/minimum-path-sum/
# Author : penpenps
# Time : 2019-07-10
from typing import List
# Use single list to keep accumulate dp result
# Time Complexity: O(n*m)
# Space Complexity: O(n)
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
n = len(grid)
m = len(grid[0])
dp = [0]*m
dp[0] = grid[0][0]
for i in range(1, m):
dp[i] = dp[i-1] + grid[0][i]
for i in range(1, n):
dp[0] += grid[i][0]
for j in range(1, m):
dp[j] = min(dp[j-1], dp[j]) + grid[i][j]
return dp[m-1]
if __name__ == '__main__':
solution = Solution()
grid = [
[1,3,1],
[1,5,1],
[4,2,1]
]
print(solution.minPathSum(grid)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.