blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
7601d4e5c01fe1e0f377ae459465a4cb0a4f3edf | sam505/Median-of-3-integers | /Median.py | 1,423 | 4.34375 | 4 | # Obtains the median of three integers that the user inputs
def median():
Num_one = input ("Enter your first integer: ")
Num_two = input ("Enter your second integer: ")
Num_three = input("Enter the third integer: ")
if (int (Num_one) < int (Num_two) and int (Num_one) > int (Num_three)):
print ("The Median of the numbers is: " +Num_one)
elif (int (Num_one) > int (Num_two) and int (Num_one) < int(Num_three)):
print("The Median of the numbers is: " + Num_one)
elif (int (Num_two) < int (Num_one) and int (Num_two) > int (Num_three)):
print ("The Median of the numbers is: " +Num_two)
elif (int (Num_two) > int (Num_one) and int (Num_two) < int (Num_three)):
print("The Median of the numbers is: " + Num_two)
elif (int (Num_three) < int (Num_two) and int(Num_three) > int(Num_one)):
print("The Median of the numbers is: " + Num_three)
elif (int (Num_three) > int (Num_two) and int (Num_three) < int (Num_one)):
print("The Median of the numbers is: " + Num_three)
else:
print("Invalid")
# Using an array and sort function the program automatically spits out the median of the numbers
num = [0, 17, 3]
num[0] = input("Enter the first number: ")
num[1] = input("Enter the second number: ")
num[2] = input("Enter the third number: ")
print(num)
num.sort()
print(num)
print("The Median of the numbers is: " +num [1])
median()
|
38ef1f6a57999b2b3dc41b72a7c9339abdfff632 | jiye-ML/tensorflow_study | /study_api/study_matplotlib.py | 7,794 | 4.125 | 4 | '''
学习 matplotlib 图形库
https://morvanzhou.github.io/tutorials/data-manipulation/plt/3-2-Bar/
'''
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.gridspec as gridspec
''' 基本使用 '''
# 开始
def hello_world():
x = np.linspace(-1, 1, 50)
y = 2 * x + 1
plt.plot(x, y)
plt.show()
# figure
def learn_figure():
x = np.linspace(-1, 1, 50)
y1 = 2 * x + 1
y2 = x**2
# 第一个界面
plt.figure()
plt.plot(x, y1)
# 第二个界面
plt.figure(num=3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.show()
# 坐标轴
def learn_axis():
x = np.linspace(-1, 1, 50)
y2 = 2 * x + 1
plt.figure()
plt.plot(x, y2)
# 设置标尺
plt.xlim((-1, 2))
plt.ylim((-2, 3))
# 设置文字显示
plt.xlabel("i am x")
plt.ylabel("i am y")
# 设置坐标文字
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],
[r'$really\ bad$', r'$bad\ \alpha$', 'normal', 'good','real good'])
# gca = get current axis
# 改变坐标轴位置
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
plt.show()
# legend
def learn_legend():
x = np.linspace(-1, 1, 50)
y2 = 2 * x + 1
y1 = x ** 2
plt.figure()
l1, = plt.plot(x, y1, label='up')
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='down')
plt.legend(handles=[l1, l2], labels=['aaa', 'bbb'], loc='best')
plt.show()
# 标注
def learn_annotation():
x = np.linspace(-1, 1, 50)
y = 2 * x + 1
plt.plot(x, y)
x0 = 1
y0 = 2 * x0 + 1
# 画点
plt.scatter(x0, y0, s=50, color='b', )
# 划线
plt.plot([x0, x0], [y0, 0], 'k--', lw=2.5)
plt.annotate(r'$2x+1={}$'.format(y0), xy=(x0, y0), xycoords='data',
xytext=(+30, -30), textcoords='offset points',
fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))
plt.text(-1, 0.5, r'$this\ is\ a\ text$',
fontdict={'size':16, 'color': 'red'})
plt.show()
pass
# tick
def learn_tick():
x = np.linspace(-3, 3, 50)
y = 0.1 * x
plt.figure()
plt.plot(x, y, linewidth=10)
plt.ylim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7))
plt.show()
pass
''' 画图种类 '''
# scatter
def learn_scatter():
n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
# 颜色 , 只为了好看
T = np.arctan2(Y, X)
plt.scatter(X, Y, s=75, c=T, alpha=0.5)
plt.xlim((-1.5, 1.5))
plt.ylim((-1.5, 1.5))
plt.xticks(())
plt.yticks(())
plt.show()
pass
# 柱状图
def learn_bar():
n = 12
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
plt.bar(X, +Y1, facecolor='red', edgecolor='white')
plt.bar(X, -Y2)
for x, y in zip(X, Y1):
# ha: horizontal alignment
plt.text(x, y+0.05, '{:.2f}'.format(y), ha='center',va='bottom')
for x, y in zip(X, Y2):
# ha: horizontal alignment
plt.text(x, -y-0.05, '{:.2f}'.format(y), ha='center',va='top')
plt.xlim(-.5, n)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())
plt.show()
pass
# 等高线
def learn_contours():
def f(x, y):
# the height function
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)
# 等高图, 8 部分
plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)
# 等高线
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=0.5)
plt.clabel(C, inline=True, fontsize=10)
plt.show()
pass
# 图像
def learn_image_2D():
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3, 3)
# http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
plt.imshow(a, interpolation='nearest', cmap='bone', origin='upper')
plt.colorbar(shrink=0.9)
plt.show()
pass
def learn_image_3D():
fig = plt.figure()
ax = Axes3D(fig)
# X, Y value
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y) # x-y 平面的网格
R = np.sqrt(X ** 2 + Y ** 2)
# height value
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
ax.contour(X, Y, Z, zdir='z',offset=-2, cmap='rainbow')
ax.set_zlim(-2, 2)
plt.show()
pass
''' 多图合并显示 '''
def learn_subplot():
plt.figure()
plt.subplot(2, 1, 1)
plt.plot([0,1], [0,1])
plt.subplot(2, 3, 4)
plt.plot([0,1], [0,1])
plt.subplot(2, 3, 5)
plt.plot([0,1], [0,4])
plt.show()
pass
# method 1: subplot2grid
def learn_subplot2grid():
plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
ax1.plot([1, 2], [1, 2])
ax1.set_title("ax1_title")
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))
plt.show()
pass
# method 2: gridspec
def learn_gridspec():
plt.figure()
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])
ax2 = plt.subplot(gs[1, 0:2])
ax3 = plt.subplot(gs[1:, 2])
ax4 = plt.subplot(gs[-1, 0])
ax5 = plt.subplot(gs[-1, -2])
plt.show()
# method 3 : easy to difine structure
def lear_subplots():
f, ((ax11, ax12),(ax21, ax22)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1, 2], [1, 2])
plt.tight_layout()
plt.show()
# 图中图
def learn():
# 初始化figure
fig = plt.figure()
# 创建数据
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1], x, 'g') # 注意对y进行了逆序处理
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')
plt.show()
# 次坐标
def second_axis():
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x ** 2
y2 = -1 * y1
fig, ax1 = plt.subplots()
# 镜面化
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')
ax1.set_xlabel("X_data")
ax1.set_ylabel('Y1', color='g')
ax2.set_ylabel("Y2", color='b')
plt.show()
if __name__ == '__main__':
second_axis() |
f9d5ed731f6aa0badce5bb5528234399a06b7e6d | megulus/code-challenges | /src/cracking_code_interview/one_away.py | 1,193 | 3.953125 | 4 | """
There are three allowable string edits:
- remove a character
- add a character
- replace a character
Given two strings, write a function to determine whether they are one edit
(or zero edits) away
"""
def is_one_away(str1, str2):
if str1 == str2:
return True
if abs(len(str1) - len(str2)) > 1:
return False
else:
same_length = (len(str1) == len(str2))
diff = 0
counter1 = 0 # counter for longer string
counter2 = 0 # counter for shorter string
stop = len(str2) # start by assuming str2 is shorter
longer = str1
shorter = str2
if not same_length:
if len(str1) < len(str2):
stop = len(str1)
longer = str2
shorter = str1
while counter2 < stop:
if not longer[counter1] == shorter[counter2]:
diff += 1
if not same_length:
counter1 += 1
if not longer[counter1] == shorter[counter2]: # more than one difference now
return False
counter1 += 1
counter2 += 1
if not same_length and diff == 0:
diff += 1
if diff > 1:
return False
return True
def main():
print(is_one_away('pale', 'ple'))
if __name__ == "__main__":
main()
|
80738173b7d82f1bf34f3d2a0ce6d081bbf074e5 | megulus/code-challenges | /src/phils_challenges/calendar.py | 1,917 | 3.609375 | 4 | STARTYEAR = 1753
STARTDAY = 1
STARTMONTH = 1
MONTHS = {
1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'
}
DAYS = {
0: 'Monday',
1: 'Tuesday',
2: 'Wednesday',
3: 'Thursday',
4: 'Friday',
5: 'Saturday',
6: 'Sunday'
}
def translateDayNumber(dayNumber):
return DAYS[dayNumber]
def translateMonthNumber(monthNumber):
return MONTHS[monthNumber]
def isLeapYear(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
return False
def countDaysInElapsedYears(elapsedYears):
count = 0
for i in range(elapsedYears):
year = STARTYEAR + i
if isLeapYear(year):
count += 366
else:
count += 365
return count
def countDaysInElapsedMonths(elapsedMonths, year):
count = 0
for i in range(elapsedMonths):
if i == 1:
if isLeapYear(year):
count += 29
else:
count += 28
elif i in [3, 5, 8, 10]:
count += 30
else:
count += 31
return count
def countDaysElapsed(month, day, year):
yearsElapsed = year - STARTYEAR
monthsElapsed = month - STARTMONTH
daysElapsed = day - STARTDAY
daysInElapsedYears = countDaysInElapsedYears(yearsElapsed)
daysInElapsedMonths = countDaysInElapsedMonths(monthsElapsed, year)
return daysInElapsedYears + daysInElapsedMonths + daysElapsed
def whatDayOfTheWeekWas(month, day, year):
numberOfDaysElapsed = countDaysElapsed(month, day, year)
return translateDayNumber(numberOfDaysElapsed % 7)
def main():
month = 3
day = 24
year = 1977
print("{0} {1}, {2} is/was/will be a {3}.".format(translateMonthNumber(month), day, year, whatDayOfTheWeekWas(month, day, year)))
if __name__ == "__main__":
main()
|
2a1b8a2228ce437ac99524607387bf1376c860c3 | sarinat/Project_Algorithm | /model/searchnsort.py | 565 | 3.71875 | 4 |
#=============Classes for searching and sorting =================
class My_searching:
def linear_search(self,pi,source):
for i in source:
if pi in i:
return int(source.index(i))
return False
class My_sorting:
def insertion_sort(self,list_a,index):
for i in range(1,len(list_a)):
save = list_a[i]
j=i
while j>0 and list_a[j-1][index] > save[index]:
list_a[j] = list_a[j-1]
j -= 1
list_a[j] = save
return list_a
|
95a042bf2c0f6a649769615218391e44a88ad8c4 | sdjukic/DataStructuresInPython | /Nodes.py | 498 | 3.625 | 4 | # Node class that is base for all recursive datastructures
class Node(object):
def __init__(self, data=None, next=None):
self._node_data = data
self.next = next
def __str__(self):
return repr(self._node_data)
class BinaryNode(object):
def __init__(self, data=None, right_child=None, left_child=None):
self._node_data = data
self._right_child = right_child
self._left_child = left_child
def __str__(self):
return repr(self._node_data)
|
d63f3014189730c8afbe7f91add852ef729e22f0 | inwk6312fall2019/dss-Tarang97 | /Chapter12-Tuples/Ex12.2.py | 1,579 | 4.21875 | 4 | fin = open('words.txt')
# is_anagram() will take a single text from 'words.txt', sorts it and lower the cases and
# append the original word in the list which will be the default value of sorted_dict() values;
# but, the sorted_word will be in sorted_dict() dictionary along with its value.
def is_anagram(text):
sorted_dict = dict()
for line in text:
original_word = line.strip()
sorting_word = ''.join(sorted(list(original_word.lower())))
sorted_word = sorting_word
sorted_dict.setdefault(sorted_word, []).append(original_word)
anagrams = []
# This for loop will take key and value from sorted_dict() using dict.items().
# the length of no. of words spelled with those letters will be counted and will be stored in 'l'.
# If length > 1, then (count of words formed, key(original word) , value (The words created with letters))
# will append in anagrams[] list.
for k,v in sorted_dict.items():
l = len(v)
if l > 1:
anagrams.append((l,k,v))
return anagrams
def longest_list_anagrams(text):
anagrams = is_anagram(text)
longest_list_anagrams = []
for l,k,v in reversed(sorted(anagrams)):
longest_list_anagrams.append((l,k,v))
return longest_list_anagrams
longest_list_anagrams = longest_list_anagrams(fin)
print(longest_list_anagrams[:5])
# longest_list_anagrams() will take the anagrams from is_anagram() and gets the anagrams[] list
# then it will get reversed and sorted and then it will append in longest_list_anagrams[]. |
94b19019633272e7bd0ddfa1ece221b8a1ae914d | constantinirimia/Stock-Market-Prediction-using-Machine-Learning-Algorithms | /Artificial_Neural_Network_LSTM.py | 4,907 | 3.984375 | 4 | '''
In this program I implemented a artificial neural network to predict the price of Apple stock -AAPL,
of the 13th month using as values the last 12 month averages
'''
import math
import pandas as pd
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
import matplotlib.pyplot as plt
#from StockMarketPredictionbyMonth.Prediction_Months import predictionUpOrDown
plt.style.use('fivethirtyeight')
'''
I have used as data the csv file 'MonthlyAverages', which was computed in the program
by calculating each the average of Adj Close Price in a whole month of transactions
'''
df = pd.read_csv('MonthlyAverage.csv')
# Lets now plot the price history over the last 12 months
plt.figure(figsize=(8,6))
plt.title('Average Monthly Price of AAPL for the last 12 months')
plt.plot(df['Avg Close Price'],color='blue' )
plt.xlabel('Date in Months', fontsize=11)
plt.ylabel('Average Price', fontsize=11)
plt.show()
# create the data set and make it a numpy array
data = df.filter(['Avg Close Price'])
dataset = data.values
# Get the number of rows to train the model on
lengthOfTrainingData = math.ceil(len(dataset) * .8)
# scale the new data
s = MinMaxScaler(feature_range=(0, 1))
dataScaled = s.fit_transform(dataset)
'''
Create the training set
'''
train_data = dataScaled[1:lengthOfTrainingData, :]
# Split the data into x_train and y_train data sets
# create 2 lists
x_train = []
y_train = []
# Populate the x_train and the y_train
for i in range(2, len(train_data)):
x_train.append(train_data[i - 1:i, 0])
y_train.append(train_data[i, 0])
x_train = np.array(x_train)
y_train = np.array(y_train)
# Since the LSTM needs data input in a 3 dimensional form lets reshape the data
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
'''
Create the testing set
'''
test_data = dataScaled[lengthOfTrainingData - 1:, :]
x_test = []
y_test = dataset[lengthOfTrainingData:, :]
for i in range(1, len(test_data)):
x_test.append(test_data[i - 1:i, 0])
x_test = np.array(x_test)
# Since the LSTM needs data input in a 3 dimensional form lets reshape the data
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
'''
Lets now create the Long Short Term Memory Model
'''
prediction_Model = Sequential()
prediction_Model.add(LSTM(50, return_sequences=True, input_shape=(1, 1)))
prediction_Model.add(LSTM(50, return_sequences=False))
prediction_Model.add(Dense(25))
prediction_Model.add(Dense(1))
prediction_Model.compile(optimizer='adam', loss='mean_squared_error')
# Lets train the network model now using fit
prediction_Model.fit(x_train, y_train, batch_size=1, epochs=9, verbose=2)
# Get the models predictions
predictions = prediction_Model.predict(x_test)
predictions = s.inverse_transform(predictions)
# Calculate the RMSE -root mean squared errror
rootMeanSquaredError = np.sqrt(((predictions - y_test) ** 2).mean())
'''
Now lets plot our data
'''
trainingData = data[:lengthOfTrainingData]
print("TRainni", trainingData)
pricePredictions = data[lengthOfTrainingData:]
print("REST", pricePredictions)
pricePredictions['Predictions'] = predictions
plt.figure(figsize=(8, 6))
plt.title('Long Short Term Memory Model on AAPL')
ax = plt.gca()
ax.set_facecolor('xkcd:black')
plt.xlabel('Date in months', fontsize=11)
plt.ylabel('Average Monthly Price', fontsize=11)
plt.plot(trainingData['Avg Close Price'], color='red')
plt.plot(pricePredictions[['Avg Close Price']], color='blue')
plt.plot(pricePredictions[['Predictions']], color='green')
plt.legend(['Data used in Training Set', 'Real Price Values', 'Predictions of Price'], loc='upper left')
plt.show()
# Print the predicted prices to see how they compare with actual ones
print("--------------------------------------------------------")
print("")
print("Predicted Prices: ", pricePredictions)
#
data = pd.read_csv('MonthlyAverage.csv')
avgClosePrice = data.filter(['Avg Close Price'])
lastMonth = avgClosePrice[-1:].values
# We can scale the values again just to make sure we are cautions and not using the real values
lastMonthScaled = s.transform(lastMonth)
X_test = [lastMonthScaled]
# make the X_test data set a numpy array and again reshape it
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predictedPrice = prediction_Model.predict(X_test)
Price = s.inverse_transform(predictedPrice)
print("--------------------------------------------------------")
print("")
print("Predicted Price of the next month is: ")
print("---> using LSTM model: $", Price)
print("----------------------------------------------------------")
print("")
print("The LSTM Model has a RMSE = :")
print("Root Mean Squared Error is: ", (round)((rootMeanSquaredError / 100), 3), " %")
#print(predictionUpOrDown())
|
a8c9c4dde14a815ba977fbabab1c7ed21241a39e | walter-agf/Practica_6 | /Doc/Experimentos/Punto_8.py | 516 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 09:19:25 2020
@author: gualteros
"""
def contar(w):
cont = 0
for i in range (0,len(w)):
if w[i] == "," :
cont += 1
if w[i+1] == ",":
cont -= 1
return cont
word = (input("Ingrese un texto : "))
cant = contar(word)
print ("\n",cant)
a = (input("Ingrese el nombre del archivo: "))
arch = open(a)
t = 0
for i in arch:
t += 1
print (t)
for a in range (0,t):
print (arch.read(a)) |
eda1e4896914b149c0b4d2ebdf9d9897bdad9aba | Skripnikov/K16-1-Skripnikov | /s.py | 110 | 4.03125 | 4 | name = input("What your name?: ")
if name == "Vlad":
print("Ooo, Hello Vlad!")
else:
print("Who are you?") |
003f7100eb14c66e4cb37cc083aead9252cb7446 | mleyfman/abstract-card-game | /AbstractGame.py | 284 | 3.671875 | 4 | class AbstractGame:
"""Abstract class for running a card game"""
def __init__(self, players=[], deck=None):
self.players = list(players)
self.deck = deck
def play_game(self):
"""Override this function for custom game logic"""
pass
|
bf085ec55d43a61557fa7177b0ce85513a03570b | YunaAnn/LearningPython | /Basics/Break&continue.py | 747 | 4.0625 | 4 | def break_statement():
print('Break if "l" -> Hello world!')
for val in 'Hello world!':
if val == 'l':
break
print(val)
print('The end.')
def continue_statement():
print(' ------------------ ')
print('Continue if "l" -> Hello world!')
for val in 'Hello world!':
if val == 'l':
continue
print(val)
print('The end.')
def print_odd_numbers():
print(' ------------------ ')
numbers = list(range(1, 21))
print('All numbers: ', numbers)
print('Odd numbers: ')
for val in numbers:
if val % 2 == 0:
continue
print(val)
if __name__ == '__main__':
break_statement()
continue_statement()
print_odd_numbers()
|
30907a6c7f52b6767dd2e95606e50632a6f440e5 | YunaAnn/LearningPython | /Basics/Loops-for.py | 1,197 | 3.875 | 4 |
def sum_all_numbers_stored_in_a_list():
list_of_numbers = [5, 1, 7, 4, 10, 2, 3, 9, 8]
sum = 0
for val in list_of_numbers:
sum = sum + val
print(5, 1, 7, 4, 10, 2, 3, 9, 8,sep='+')
print('=', sum)
def range_function():
print(range(10))
print(list(range(10)))
print(list(range(10, 21)))
print(list(range(0, 100, 10)))
def for_loop_index():
hobby = ['reading', 'listening to music', 'playing video games', 'watching movies']
string = ''
for i in range(len(hobby)):
print('I like', hobby[i])
for val in hobby:
string = string + ' ' + val
print ('I like', string)
def for_loop_with_else():
data = [1, 4, 7, 2]
for i in data:
print(i)
else:
print ('No items left.')
def for_loop_with_else_and_break():
name = 'Adam'
age = {'John': 45, 'Eva': 27, 'Liz': 53}
for person in age:
if person == name:
print(age[person])
break
else:
print ('No data found.')
if __name__ == '__main__':
sum_all_numbers_stored_in_a_list()
range_function()
for_loop_index()
for_loop_with_else()
for_loop_with_else_and_break()
|
5431f42ec87c58d3c8bb6212361f724a74cb8836 | paarinmodi/PythonBeginner | /Python_NP_Station/F_String.py | 535 | 3.953125 | 4 | print('My Grandfather\'s name is Kanaylal Modi')
print('My Grandfather\'s name is Kanaylal Modi')
("My Grandfather's name is Kanaylal Modi")
name='Paarin Modi \'The Great'
print(name)
Paarin Modi 'The Great
favorite_number=3
type(favorite_number)
<class 'int'>
favorite_number="3"
type(favorite_number)
<class 'str'>
mood="delighted"
print("I'm so {mood} to learn code in Python!!)
print("I'm so {mood} to learn code in Python!!")
I'm so {mood} to learn code in Python!!
print(f"I'm so {mood} to learn code in Python!!")
I'm so delighted to learn code in Python!!
|
6e5e12f4d4d5960e787cb3f43d8262207b4b89ae | u-zii/likelion_week4 | /practice.py | 2,674 | 3.59375 | 4 | ## 1번문제 ##
num=int(input("money를 입력하세요 : "))
def what(x):
if x>=10000:
print("고기를 먹는다")
elif x>=5000:
print("국밥을 먹는다")
else:
print("라면을 먹는다")
what(num)
## 2번문제 ##
fruits=[]
fruits.append(input("1번 과일을 입력하세요"))
fruits.append(input("2번 과일을 입력하세요"))
fruits.append(input("3번 과일을 입력하세요"))
fruits.append(input("4번 과일을 입력하세요"))
fruits.append(input("5번 과일을 입력하세요"))
for i in range(0,5):
print(i+1, "번째 과일은", fruits[i], "입니다.")
## 3번문제 ##
cookies={'탱커':'우유맛쿠키','딜러':'칠리맛쿠키','힐러':'천사맛쿠키','서포터':'석류맛쿠키'}
for key,value in cookies.items():
if key=='탱커':
cookies['탱커']='다크초코맛쿠키'
elif key=='딜러':
cookies['딜러']='라떼맛쿠키'
elif key=='힐러':
cookies['힐러']='허브맛쿠키'
print(cookies)
# 4번문제 ##
def add():
x=int(input("숫자 1을 입력하세요"))
y=int(input("숫자 2를 입력하세요"))
print(x+y)
def sub():
x=int(input("숫자 1을 입력하세요"))
y=int(input("숫자 2를 입력하세요"))
print(x-y)
def mul():
x=int(input("숫자 1을 입력하세요"))
y=int(input("숫자 2를 입력하세요"))
print(x*y)
def div():
x=int(input("숫자 1을 입력하세요"))
y=int(input("숫자 2를 입력하세요"))
print(x/y)
while True:
number=int(input("원하는 숫자를 입력하세요 1. 더하기 2. 빼기 3. 곱하기 4. 나누기 5. 종료"))
if number==1:
add()
elif number==2:
sub()
elif number==3:
mul()
elif number==4:
div()
elif number==5:
break
else:
continue
# 5번문제 ##
class Person:
def __init__(self,name):
self.name=name
def hello(self):
print("안녕 내 이름은", self.name, "이야")
def walk(self):
print("나는 걷는 중")
class Worker(Person):
def __init__(self, name, company):
Person.__init__(self, name)
self.company=company
self.mental=50
def hello(self):
print("안녕 내 이름은", self.name,"이고, 내가 다니는 회사는", self.company)
def work(self):
if self.mental>=0:
print("나는 일하는 중, 내 멘탈 지수 : ",self.mental)
self.mental-=10
else:
print("더는 일 못해")
worker = Worker("빌게이츠", "삼성")
worker.hello()
worker.walk()
for i in range(7):
worker.work() |
2055c96f93ace3ed9e3522707d4534bf678673f5 | Rivals16/dataStructureAndAlgoConcepts | /countingsort.py | 1,084 | 3.828125 | 4 | #! /usr/bin/python3
import time
def countingSort(insertedArray,countArray,sortedArray):
for i in range(len(insertedArray)):
countArray[insertedArray[i]] += 1
print("Counting Array Is : ",countArray)
for i in range(1,len(countArray)):
countArray[i]+=countArray[i-1]
print("Modified Counting Array : ",countArray)
for i in range(0,len(insertedArray),1):
sortedArray[countArray[insertedArray[i]]-1] = insertedArray[i]
countArray[insertedArray[i]]-=1
return sortedArray
if __name__ == "__main__":
insertedArray = list(map(int,input('Enter Numbers Counting Sort : ').split()))
maximumElement = max(insertedArray)
countArray = [0]*(maximumElement+1)
sortedArray = [0]*len(insertedArray)
start = time.process_time()
print("Sorted Array Is:",countingSort(insertedArray,countArray,sortedArray))
print("Time Taken By Counting Sort : ",time.process_time()-start)
start = time.process_time()
insertedArray.sort()
print(insertedArray)
print("Time Taken By Tim Sort : ",time.process_time()-start)
|
8ff14bd737e7d2831108a61ff1c2528969a0ccd0 | akshay-verma/LeetCode | /101_symmetric_tree.py | 1,942 | 3.90625 | 4 | """
Problem 101:
https://leetcode.com/problems/symmetric-tree
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preOrderTraversal(self, root, result):
if root:
result.append(root.val)
if root.left or root.right:
if root.left:
self.preOrderTraversal(root.left, result)
else:
result.append(None)
if root.right:
self.preOrderTraversal(root.right, result)
else:
result.append(None)
def preOrderTraversalRight(self, root, result):
if root:
result.append(root.val)
if root.left or root.right:
if root.right:
self.preOrderTraversalRight(root.right, result)
else:
result.append(None)
if root.left:
self.preOrderTraversalRight(root.left, result)
else:
result.append(None)
def checkNodes(self, p, q):
if p is None and q is None:
return True
if p is None or q is None:
return False
if p.val == q.val:
left = self.checkNodes(p.left, q.right)
right = self.checkNodes(p.right, q.left)
return left and right
else:
return False
def isSymmetric(self, root: 'TreeNode') -> 'bool':
if not root:
return True
# Solution 1
# leftSubTree = []
# self.preOrderTraversal(root.left, leftSubTree)
# rightSubTree = []
# self.preOrderTraversalRight(root.right, rightSubTree)
# return leftSubTree == rightSubTree
# Solution 2
return self.checkNodes(root.left, root.right)
|
bf0a0135e2488aab99bb96c762a95666f25a332e | akshay-verma/LeetCode | /501_Find_Mode_in_Binary_Search_Tree.py | 1,002 | 3.78125 | 4 | """
501. Find Mode in Binary Search Tree
https://leetcode.com/problems/find-mode-in-binary-search-tree/
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def dfs(self, root, mode):
if root:
if root.val in mode:
mode[root.val] += 1
else:
mode[root.val] = 1
if root.left:
self.dfs(root.left, mode)
if root.right:
self.dfs(root.right, mode)
def findMode(self, root: 'TreeNode') -> 'List[int]':
if not root:
return []
mode = {}
self.dfs(root, mode)
maxVal = None
result = []
for key, val in mode.items():
if not maxVal or val > maxVal:
maxVal = val
result = [key]
elif val == maxVal:
result.append(key)
return result
|
cc2b7ad3f8451a0efccef6304ae212c7bebe8000 | simrit321/heap | /heap.py | 6,466 | 3.75 | 4 | # helper functions
def left(index):
'''Return index's left child index.
'''
return index * 2 + 1
def right(index):
'''Return index's left child index.
'''
return index * 2 + 2
def parent(index):
'''Return index's parent index.'''
return (index - 1) // 2
class MinHeap:
def __init__(self, L=None):
'''Create a new MinHeap.
This method is complete.'''
if not L:
self._data = []
else:
self._data = L
self._min_heapify()
def __len__(self):
'''Return the length of the MinHeap.
This method is complete.'''
return len(self._data)
def __str__(self):
'''Return a string representation of the heap.
This method is complete.'''
return str(self._data)
def insert(self, v):
'''Insert v in self. Maintain heap property.'''
self._data.append(v)
self._percolate_up()
return self
def extract_min(self):
'''Remove minimal value in self. Restore heap property.
Raise EmptyHeapException if heap is empty.'''
if len(self._data) == 0:
raise EmptyHeapException()
elif len(self._data) == 1:
return self._data[0]
else:
ind = len(self._data) - 1
a, b = 0, ind
self._data[b], self._data[a] = self._data[a], self._data[b]
m=self._data.pop(len(self._data)-1)
self._percolate_down(i=0)
#self._percolate_up()
self._percolate_down(i=0)
return m
def _percolate_up(self):
'''Restore heap property of self after
adding new item'''
index = len(self._data)
v = self._data[index - 1]
i = parent(index)
p = self._data[i]
while v < p:
a,b = self._data.index(v), self._data.index(p)
self._data[b], self._data[a] = self._data[a], self._data[b]
index = self._data.index(v)
i = parent(index)
p = self._data[i]
if index == 0:
break
return self
def _percolate_down(self, i):
''' Restore heap property of subtree
rooted at index i.
'''
index = i
index_left = left(index)
index_right = right(index)
node_val = self._data[i]
maxL = len(self._data)-1
if (index_left <= maxL) and (index_right <= maxL):
left_val = self._data[index_left]
right_val = self._data[index_right]
if left_val < node_val and right_val < node_val :
if left_val > right_val:
smaller = right_val
x,y = self._data.index(node_val), self._data.index(smaller)
self._data[y], self._data[x] = self._data[x], self._data[y]
index = self._data.index(node_val)
self._percolate_down(i=index)
elif left_val < right_val:
smaller = left_val
x,y = self._data.index(node_val), self._data.index(smaller)
self._data[y], self._data[x] = self._data[x], self._data[y]
index = self._data.index(node_val)
self._percolate_down(i=index)
elif left_val == right_val:
smaller = left_val
x,y = self._data.index(node_val), self._data.index(smaller)
self._data[y], self._data[x] = self._data[x], self._data[y]
index = self._data.index(node_val)
self._percolate_down(i=index)
elif (left_val < node_val) and (right_val >= node_val):
smaller = left_val
x,y = self._data.index(node_val), self._data.index(smaller)
self._data[y], self._data[x] = self._data[x], self._data[y]
index = self._data.index(node_val)
self._percolate_down(i=index)
elif (right_val < node_val) and (left_val >= node_val):
smaller = right_val
x,y = self._data.index(node_val), self._data.index(smaller)
self._data[y], self._data[x] = self._data[x], self._data[y]
index = self._data.index(node_val)
self._percolate_down(i=index)
elif (index_left <= maxL) and (index_right > maxL):
left_val = self._data[index_left]
if left_val < node_val:
smaller = left_val
x,y = self._data.index(node_val), self._data.index(smaller)
self._data[y], self._data[x] = self._data[x], self._data[y]
index = self._data.index(node_val)
self._percolate_down(i=index)
elif (index_right <= maxL) and (index_left > maxL):
right_val = self._data[index_right]
if right_val < node_val:
smaller = right_val
x,y = self._data.index(node_val), self._data.index(smaller)
self._data[y], self._data[x] = self._data[x], self._data[y]
index = self._data.index(node_val)
self._percolate_down(i=index)
return self._data
# while larger than at least one child
# swap with smaller child and repeat
def _min_heapify(self):
'''Turn unordered list into min-heap.'''
length = len(self._data)
mid = length//2
l = list(range(mid))
print(l)
for item in l[::-1]:
self._percolate_down(item)
# for each node in the first half of the list
# percolate down
class EmptyHeapException(Exception):
pass
if __name__ == '__main__':
s = MinHeap()
s.insert(2)
s.insert(4)
s.insert(5)
s.insert(10)
s.insert(1)
s.insert(3)
print('s:')
print(s)
s.extract_min()
print(s)
print('======')
b = MinHeap(L=[33,2,3,55,4,0,1])
#print('MinHeap:')
print(b)
#b.extract_min()
#b.extract_min()
#print(b)
|
244caf73afff5c138a26aed9f68900f7e680d1dc | erik-engel/python_2021 | /mandatory/mandatory-1-erik.py | 3,668 | 4.09375 | 4 | #1. Model an organisation of employees, management and board of directors in 3 sets.
#Board of directors: Benny, Hans, Tine, Mille, Torben, Troels, Søren
#Management: Tine, Trunte, Rane
#Employees: Niels, Anna, Tine, Ole, Trunte, Bent, Rane, Allan, Stine, Claus, James, Lars
bod = {"Benny", "Hans", "Tine", "Mille", "Torben", "Troels", "Søren"}
management = {"Tine", "Trunte", "Rane"}
employees = {"Niels", "Anna", "Tine", "Ole", "Trunte", "Bent", "Rane", "Allan", "Stine", "Claus", "James", "Lars"}
#who in the board of directors is not an employee?
a = bod.difference(employees)
print(a)
#who in the board of directors is also an employee?
b = bod.intersection(employees)
print(b)
#how many of the management is also member of the board?
c = management.intersection(bod)
print(len(c))
#All members of the managent also an employee
d = management.intersection(employees)
print(d)
#All members of the management also in the board?
e = management.intersection(bod)
print(e)
#Who is an employee, member of the management, and a member of the board?
f = set.intersection(bod, management, employees)
print(f)
#Who of the employee is neither a memeber or the board or management?
g = employees.difference(bod, management)
print(g)
#-----------------------------------------------------------------------------
#Code
#-----------------------------------------------------------------------------
#2. Using a list comprehension create a list of tuples from the folowing datastructure
#{‘a’: ‘Alpha’, ‘b’ : ‘Beta’, ‘g’: ‘Gamma’}
#-----------------------------------------------------------------------------
#Code
#-----------------------------------------------------------------------------
dict = {'a' : 'Alpha', 'b' : 'Beta', 'g': 'Gamma'}
print(dict)
list = [(k, v) for k, v in dict.items()]
print(list)
#3. From these 2 sets:
#{'a', 'e', 'i', 'o', 'u', 'y'}
#{'a', 'e', 'i', 'o', 'u', 'y', 'æ' ,'ø', 'å'}
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
h = {'a', 'e', 'i', 'o', 'u', 'y'}
i = {'a', 'e', 'i', 'o', 'u', 'y', 'æ' ,'ø', 'å'}
#Of the 2 sets create a:
#Union:
#----
j = h.union(i)
print(j)
#Symmetric difference
#----
k = h.symmetric_difference(i)
print(k)
#or
print(h^i)
#difference
#----
l = i.difference(h)
print(l)
m = h.difference(i)
print(m)
#or
print (i-h)
print (h-i)
#disjoint
#----
n = h.isdisjoint(i)
print(n)
# 4. Date Decoder
#A date of the form 8-MAR-85 includes the name of the month, which must be translated to a number.
#Create a dict suitable for decoding month names to numbers.
month = {'JAN' : 1, 'FEB' : 2, 'MAR' : 3, 'APR' : 4, 'MAY' : 5, 'JUN' : 6, 'JUL' : 7, 'AUG' : 8, 'SEP' : 9, 'OKT' : 10, 'NOV' : 11, 'DEC' : 12}
#Create a function which uses string operations to split the date into 3 items using the "-" character.
def split_function(s) :
return s.split('-')
#Translate the month, correct the year to include all of the digits.
def trans_month(s) :
i = month.get(s)
return i
def year_all_digt(i) :
if i<=21 and i>=00 :
i += 2000
else :
i += 1900
return i
#The function will accept a date in the "dd-MMM-yy" format and respond with a tuple of ( y , m , d )
def final_function(s) :
l = split_function(s)
a = year_all_digt(int(l[2]))
b = trans_month(l[1])
return (str(a) + ', ' + str(b) + ', ' + l[0])
s1 = '8-MAR-85'
s2 = '23-JAN-77'
s3 = '11-DEC-19'
s4 = '1-OKT-01'
print(final_function(s1))
print(final_function(s2))
print(final_function(s3))
print(final_function(s4))
|
6c2801ad50d50b92fc2b2fd37a423ec731d98612 | chendinghao/ChangeToHTMLorXML | /util.py | 1,483 | 3.828125 | 4 | """
块的收集方法:收集遇到的所有行,直到遇到一个空行,然后返回已经收集到的行,这就是一个块。
之后再次收集,不收集空行和空块。
同时,确保文件的最后一行是空行,否则程序就不知道最后一个块什么时候结束
"""
# coding=utf-8
def lines(file):
“”“
如果去掉 yield '\n' ,并且文件的最后一行不是空行,会发现最后的一个块无法输出
”“”
for line in file: yield line
yield '\n'
# blocks生成器实现了前面说明的方法。当生成一个块后,里面的行会被链接成一个字符串,并且将开始和结尾的中的多余的空格删除,得到一个代表块的字符串
def blocks(file):
"""
读取文件,将文件分成块
"""
block = []
for line in lines(file): # 读取文件的每一行
if line.strip(): # 去掉string的前后端的空格,判断是否为真
block.append(line) # 如果为真,将string添加到block中
elif block: # 如果line为假,判断block是否为空
# 如果不为空,将block中所有元素连接起来成为一个新的string, 元素之间的连接字符为空
# 去掉新的string的前后端空格,将新string添加到生成器中
yield ''.join(block).strip()
block = [] # 重新将block赋值为空,一边读取后面的内容
|
8d4354d890b46e3c68978895e6b3701d3d350661 | thacdtd/AAI | /gradient-descent/ex.py | 425 | 3.765625 | 4 | # From calculation, it is expected that the local minimum occurs at x=9/4
cur_x = 6 # The algorithm starts at x=6
gamma = 0.01 # step size multiplier
precision = 0.00001
previous_step_size = cur_x
def df(x):
return 4 * x**3 - 9 * x**2
while previous_step_size > precision:
prev_x = cur_x
cur_x += -gamma * df(prev_x)
previous_step_size = abs(cur_x - prev_x)
print("The local minimum occurs at %f" % cur_x) |
bc9354af11d56d91d56b017f5fe63bf8af131641 | wanzongqi/-R- | /solve/41.py | 623 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
@author: strA
ProjectEuler-problem-41
"""
def gen_prime(n):
prime = [True]*(n+1)
prime[0] = False
prime[1] = False
for i in range(1,n+1):
if prime[i]:
m = i*2
while m<n:
prime[m] = False
m = m+i
return prime
def check(n):
n_str = str(n)
for i in n_str:
if int(i)>len(n_str) or int(i)==0 or n_str.count(i)>1:
return False
return True
primes = gen_prime(9999999)
for i in reversed(range(9999999)):
if primes[i]:
if check(i):
print(i)
break
|
248f8ab1e8cea4a94af7763762d7aa7b82717937 | wanzongqi/-R- | /solve/44.py | 555 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
@author: strA
ProjectEuler-problem-44
"""
"""
先写个简单的
"""
import math
def check(n):
if int((1+math.sqrt(1+24*n))/6)==(1+math.sqrt(1+24*n))/6:
return True
else:
return False
def Pentagon(n):
return (n*(3*n-1))//2
i = 1
flag = True
while flag:
j = 1
while j<i:
diff = Pentagon(i)-Pentagon(j)
sum = Pentagon(i)+Pentagon(j)
if check(diff) and check(sum):
flag = False
print(diff)
break
j +=1
i += 1
|
35fe96cb91fe25a006e0706444634fc3d23647c3 | wanzongqi/-R- | /solve/12.py | 415 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 4 00:46:34 2018
@author: strA
ProjectEuler-problem-12
"""
import math
def factor_count(n):
t = 0
for i in range(1,int(math.sqrt(n))+1):
if n%i == 0:
t += 1
t = 2*t
if math.sqrt(n) - int(math.sqrt(n))<0.001:
t = t-1
return t
sum = 1
term = 1
while factor_count(sum)<=500:
term += 1
sum = sum+term
print(sum) |
ca06882d790762caa3ac5eb911468aa445b8ede4 | rbstech/520 | /aula 04/ex_func.py | 427 | 3.859375 | 4 | #!/usr/bin/python3
convidados = []
def adicionar():
'''funcao para adicionar convidados na lista'''
global convidados
qtd = int(input("Digite a quantidade de convidados: "))
print(qtd)
for n in range(qtd):
nome = input('Insira o nome do convidado '+str(n+1)+": ")
convidados.append(nome)
adicionar()
print(convidados)
# professor utilizou while true (while com loop infinito) |
40a40ed6d46b5567258631990e697b4b9967862d | zhoushaojun/pythonLearn | /numpyUsage/CodeBeauty/FindAddNumers.py | 1,479 | 3.8125 | 4 | # 寻找快速满足条件两个数
dataList = [5, 6, 1, 4, 7, 9, 8]
# print(dataList)
def heapSort(dataList, start, length):
maxIndex = 0
while start * 2 + 1 < length:
# 查找子节点中最大值
if start * 2 + 2 < length:
maxIndex = start * 2 + 1 if dataList[start * 2 + 1] > dataList[start * 2 + 2] else start * 2 + 2
if dataList[maxIndex] > dataList[start]:
sumValue = dataList[maxIndex] + dataList[start]
dataList[start] = sumValue - dataList[start]
dataList[maxIndex] = sumValue - dataList[start]
start = maxIndex;
else:
break
def heapAdjust(dataList):
length = len(dataList);
for i in reversed(range(length // 2)):
heapSort(dataList, i, length)
print(dataList)
for i in reversed(range(length)):
print(i)
sumValue = dataList[0] + dataList[i]
dataList[0] = sumValue - dataList[0]
dataList[i] = sumValue - dataList[0]
heapSort(dataList, 0, i)
# heapSort(dataList, 1, 7)
heapAdjust(dataList)
print(dataList)
def checkSum(dataList, value):
start=0
end=len(dataList)-1
while start != end:
checkValue = dataList[start] + dataList[end]
print(start,end,checkValue)
if checkValue == value:
print("get it",start, end)
break;
elif checkValue > value:
end-=1
else:
start+=1
checkSum(dataList, 13)
|
9e805a66b2cda4c90afc67c31f2ae9bee5653ec6 | gdsa-upc/K-LERA | /DL_features.py | 729 | 3.71875 | 4 | # -*- coding: utf-8 -*-
#Pseudocódigo Deep Learning
''' 1) Leer una imágen de mxm
im.read()
2) hacerle un reshape para crear un vector transpuesto de m^2 píxels
np.reshape()
3) Declarar el modelo de keras que queramos usar.
Modelo=get_alexnet([500,500],nº de lables, true)
4)Pasar las imágenes de la base de datos diferenciando si son de train o val
if train
A.fit
if val
A.predict
5) La función de get_alexnet nos sacará un vector con las probabilidades de cada "label".5)
6) Habrá que normalizarlas con la función softmax
7) Solo quedará mirar el valor más alto del vector para saber que tipo de imágen es.
|
df2ed521a9a2fe9a1f8bfbdf3deb5f90fce6a63d | sakuragi97/HackerRank-Python-Solutions | /30 Days of Code/Day29_Bitwise_AND.py | 474 | 3.734375 | 4 | #!/bin/python3
# def findBitwise(n,k):
# maxBitwise=0
# i=0
# j=i+1
# for i in range(n-1):
# for j in range(n):
# if i&j>maxBitwise and i&j<k:
# maxBitwise=i&j
# print(maxBitwise)
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
nk = input().split()
n = int(nk[0])
k = int(nk[1])
if (k-1|k)<=n:
print(k-1)
else:
print(k-2) |
1c4430f3be37984e0ae87bde671416b8424cf83e | oren0e/dl-python | /chapter6/word_embeddings.py | 1,556 | 3.75 | 4 | '''
We will work with the IMDB movie reviews data. We will:
1. Prepare the data
2. restrict the movie reviews to the top 10000 most common words
3. Cut off the reviews after only 20 words.
4. The network will learn 8-dimensional embeddings for each of the 10000 words,
turn the input integer sequences (2D integer tensor) into embedded sequences
(3D float tensor of (samples, sequence_length, embedding_size)),
flatten the tensor to 2D, and train a single Dense layer on top for classification.
'''
from keras.datasets import imdb
from keras import preprocessing
from keras import models, layers, Input
max_features = 10000 # Number of words to consider as features
maxlen = 20 # Cuts off the text after this number of words
# (among the max_features most common words)
# read data
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
# turn the lists of integers into a 2D integer tensor of shape (samples, maxlen)
x_train = preprocessing.sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = preprocessing.sequence.pad_sequences(x_test, maxlen=maxlen)
input_tensor = Input((maxlen,))
kmodel = layers.Embedding(10000, 8, input_length=maxlen)(input_tensor)
kmodel = layers.Flatten()(kmodel)
output_tensor = layers.Dense(1, activation='sigmoid')(kmodel)
model = models.Model(input_tensor, output_tensor)
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])
model.summary()
history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_split=0.2)
|
1b8cc21c31b5f381963fc24cff708645b856b333 | 11aki/Blackjack | /blackjack.py | 4,550 | 3.515625 | 4 |
import random
Playing = 'Yes'
bal = 1000
bet = 0
suits = ["Spades", "Clubs","Hearts","Diamonds"]
ranks = ["Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]
values = {"Ace":11,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"Jack":10,"Queen":10,"King":10}
#################### Card Class #######################
class Card():
def __init__(self,suit,rank,value):
self.rank = rank
self.suit = suit
self.value= value
def __str__(self):
return self.rank+" of "+self.suit
####################### Deck Class #########################
class Deck():
def __init__(self):
self.deck = []
for s in suits:
for r in ranks:
self.deck.append(Card(s,r,value=r))
def __str__(self):
deckComp = ""
for c in self.deck:
deckComp +='\n'+c.__str__()
return "the deck has: "+deckComp
def dealfromdeck(self):
singleCard = self.deck.pop()
return singleCard
def shuffle(self):
random.shuffle(self.deck)
########################## Player Class ################
class Player():
def __init__(self,total=1000,bot=False):
self.total = total
self.hand = []
self.bet = 0
self.aces = 0
self.value = 0
self.bot = bot
def __str__(self):
pri='Your total is {}\nYour current bet is {}\nYour value is {}'.format(self.total,self.bet,self.value)+'\nYour hand is \n'+'\n'.join(map(str,self.hand))
return pri
def __repr__(self):
return str(self)
def take_bet(self):
self.bet=input("Enter your bet amount ")
print(f'{self.bet} is how much u bet')
def checkAce(self):
if self.value > 21 and self.aces:
self.value -=10
self.aces -=1
def deal(self,card):
self.hand.append(card)
self.value += values[card.value]
if card.rank == "Ace":
self.aces += 1
def showHand(self):
if self.bot:
print("-------------------------------")
print("\nThis the botss hand ")
print(*self.hand, sep =", ")
print("Value is: "+str(self.value)+"\n----------------------------")
else:
print("This the players hand ")
print(*self.hand, sep =", ")
print("Value is: "+str(self.value)+"\n----------------------------")
############### Important Functions #######################
def checkWin(b,a,bet):
global bal
if a>21:
print("player busted bot won :( ")
bal-=bet
print(bal)
return bal
if b>21:
print("bot bustesd player won :) ")
bal+=bet
print(bal)
return bal
if b>a:
print("bot won, the bot had a value of {}, while ur value was {} :( ".format(b,a))
bal-=bet
print(bal)
return bal
elif a>b:
print("Player won, the bot had a value of {}, while ur value was {} :)".format(b,a))
bal+=bet
print(bal)
return bal
else:
print("tieee")
return bal
def botTurn(bet):
global bal
if bot.value< aki.value:
bot.deal(d.dealfromdeck())
bot.checkAce()
bot.showHand()
botTurn(bet)
else:
checkWin(bot.value,aki.value,bet)
def decision(a,b,bet):
global bal
answer = input("enter what u wanna do. Type hit or stand ")
if answer[0].lower() == 'h':
print("U chose to hit")
aki.deal(d.dealfromdeck())
aki.checkAce()
aki.showHand()
if aki.value<=21:
decision(a,b,bet)
else:
print("game over u busted")
bal-=bet
print(bal)
return
else:
botTurn(bet)
def takebet():
global bal
bet = input("How much u wanna bet, ur balance is {} ".format(bal))
if int(bet)>bal:
print("bet too high, your balance is {}".format(bal))
takebet()
else:
return int(bet)
######################### Start Game ################
while Playing[0].lower() == 'y' and bal >0:
print("Welcome to Blackjack")
d = Deck()
aki = Player()
bot = Player(bot=True)
d.shuffle()
aki.deal(d.dealfromdeck())
bot.deal(d.dealfromdeck())
aki.deal(d.dealfromdeck())
bet = takebet()
bot.showHand()
aki.showHand()
decision(aki.value,bot.value,bet)
Playing = input("u wanna play again? ")
if bal<1:
print("Go home kid, U have no balance. Game over")
|
501bd33d9a67a292b690201842553cbd93e9a1e6 | Brokames/DatabaseVisualizer | /utils/data_gen.py | 5,484 | 3.5 | 4 | import datetime
import enum
import random
from collections import namedtuple
from itertools import islice, starmap
from typing import Any, Dict, Generator, Iterator, Tuple
import pandas as pd
from faker import Faker
class Columns(enum.Enum):
"""Available columns for data generator
NAME[str]: First + Last + optional prefix/sufix
ADDRESS[dict]: {
"address": str,
"state": str,
"city": str,
"zipcode": int, # not actually smart, but good for testing types
}
PHONE_NUMBER[str]
DATE_OF_BIRTH[datetime]: ages between 18 and 77
JOB[str]
BANK_ACCOUNT[str]
SSN[str]
"""
NAME = 1
ADDRESS = 2
PHONE_NUMBER = 3
DATE_OF_BIRTH = 4
JOB = 5
BANK_ACCOUNT = 6
SSN = 7
DEFAULT_COLUMNS = tuple(Columns)
class DataGenerator:
"""Generates tables of data in either row or column format.
Can be used by itself, or within one of the classes to produce
specific data formats.
The return data is generated on the fly and returned as a named tuple of
rows or columns.
gen_rows()
gen_table()
"""
def __init__(
self,
columns: Tuple[Columns] = DEFAULT_COLUMNS,
seed: int = 0,
) -> None:
self.columns = columns
self.headers = self._get_headers()
self.data_generators = self._get_data_generators()
self.faker = Faker(seed=seed)
def _get_headers(self) -> Tuple[str]:
"""Retuns a tuple of headers for the columns"""
header_dict = {
Columns.NAME: "Name",
Columns.ADDRESS: "Address",
Columns.PHONE_NUMBER: "Phone_Number",
Columns.DATE_OF_BIRTH: "Date_of_Birth",
Columns.JOB: "Job",
Columns.BANK_ACCOUNT: "Bank_Account",
Columns.SSN: "SSN",
}
return tuple(header_dict[col] for col in self.columns)
def _get_data_generators(self) -> Tuple[Generator[Any, None, None]]:
"""Returns a tuple of the custom data generators for the columns"""
generator_dict = {
Columns.NAME: self._name_generator(),
Columns.ADDRESS: self._address_generator(),
Columns.PHONE_NUMBER: self._phone_number_generator(),
Columns.DATE_OF_BIRTH: self._birth_date_generator(),
Columns.JOB: self._job_generator(),
Columns.BANK_ACCOUNT: self._bank_account_generator(),
Columns.SSN: self._ssn_generator(),
}
return tuple(generator_dict[col] for col in self.columns)
def _name_generator(self) -> str:
"""Infinite iterator to produce full names"""
while True:
prefix = f"{self.faker.prefix()} " if random.random() < 0.1 else ""
name = self.faker.name()
suffix = f" {self.faker.suffix()}" if random.random() < 0.1 else ""
yield f"{prefix}{name}{suffix}"
def _address_generator(self) -> Dict:
"""Infinite iterator of dictionaries of addresses
{
"address": str,
"state": str,
"city": str,
"zipcode": int, # not actually smart, but good for testing types
}
"""
# fmt: off
states_abbr = (
"AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA",
"HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
"MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
"NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
"SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY",
)
# fmt: on
while True:
yield {
"address": self.faker.street_address(),
"state": random.choice(states_abbr),
"city": self.faker.city(),
"zipcode": self.faker.postcode(),
}
def _phone_number_generator(self) -> str:
"""Infinite iterator to phone numbers"""
while True:
yield self.faker.phone_number()
def _birth_date_generator(self) -> datetime.date:
"""Infinite iterator to produce date of births"""
while True:
yield self.faker.date_of_birth(minimum_age=18, maximum_age=77)
def _job_generator(self) -> str:
"""Infinite iterator to produce jobs"""
while True:
yield self.faker.job()
def _bank_account_generator(self) -> str:
"""Infinite iterator to produce bank account IDs"""
while True:
yield self.faker.bban()
def _ssn_generator(self) -> str:
"""Infinite iterator to produce social security numbers"""
while True:
yield self.faker.ssn()
def gen_rows(self, num_rows: int = None) -> Iterator[namedtuple]:
"""Returns an iterator of size `num_rows` of namedtuples in a row format"""
Row = namedtuple("Row", self.headers)
return starmap(Row, islice(zip(*self.data_generators), num_rows))
def gen_table(self, num_rows: int = None) -> namedtuple:
"""Returns named a namedtuple of header & a tuple of data"""
Table = namedtuple("Table", self.headers)
# fmt: off
return Table(*(tuple(islice(data_generator, num_rows)) for data_generator in self.data_generators))
# fmt: on
def gen_pandas_df(self, num_rows: int = None) -> pd.DataFrame:
"""Returns the data as a pandas dataframe"""
return pd.DataFrame(self.gen_rows(num_rows))
|
6a98e4477b04720c18143b7f93f4c4317ff67a97 | qianxiaodai/Algorithm | /LeetCode/math_highlights.py | 444 | 3.9375 | 4 | # -*- coding: utf-8 -*-
import math
class Solution:
"""超时"""
def countPrimes(self, n: int) -> int:
count = 0
for i in range(2, n):
if self.isPrime(i):
count += 1
return count
def isPrime(self, n: int) -> int:
for i in range(2, int(math.sqrt(n) + 1)):
if n % i == 0:
return False
return True
if __name__ == '__main__':
pass
|
ea5c93d8f01a4851694045ffb8d777558acb0984 | qianxiaodai/Algorithm | /Basic/guess.py | 1,564 | 3.953125 | 4 | # -*- coding: utf-8 -*-
import math
"""
歌德巴赫猜想j
2000以内大于2的偶数能分解为两个素数之和。
"""
def isPrime(n):
for j in range(2, int(math.sqrt(float(n))) + 1):
if n % j == 0:
return False
return True
def getPrime(n):
primes = list()
for j in range(2, n + 1):
if isPrime(j):
primes.append(j)
return primes
# def evenResolution(even, primes):
# n = len(primes)
# ans = []
#
# for i in range(n):
# # print(primes[i])
# j = i
# while j < n:
# if primes[j] == even - primes[i]:
# ans.extend([primes[i], primes[j]])
# return ans
# # print(primes[j])
#
# elif primes[j] > even - primes[i]:
# break
# j += 1
# return ans
def evenResolution(even, primes):
n = len(primes)
left, right = 0, n - 1
# ans = []
while left <= right:
if primes[left] + primes[right] > even:
right -= 1
elif primes[left] + primes[right] < even:
left += 1
else:
return [primes[left], primes[right]]
return []
if __name__ == '__main__':
ans = getPrime(1998)
# print(len(ans))
# print(ans)
i = 4
# res = evenResolution(16, ans)
# print(res)
while i <= 2000:
res = evenResolution(i, ans)
if res:
print(f"{i:3d} = {res[0]: 3d} + {res[1]: 3d}")
else:
print(f"{i} can't be resolved.")
i += 2
|
32118971c5f1acfcd81554eaa09fc9f1e4c48660 | 07Agarg/Course_Programming_Assignments | /Artificial Intelligent/Assignment 1/Solution 1/min_heap.py | 2,589 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 2 04:55:04 2019
@author: ashima
"""
import numpy as np
class Heap:
def __init__(self, Capacity):
self.heap = []
self.length = 0
self.capacity = Capacity
def get_parent(self, index):
return int(index/2)
def isEmpty(self):
if self.length == 0:
return True
return False
def right_child(self, index):
return 2*index + 2
def left_child(self, index):
return 2*index + 1
def get_top(self):
if self.length == 0:
return None
return self.heap[0]
def addNode(self, node):
if self.length >= self.capacity:
return None
self.heap.append(node)
self.length = self.length + 1
self.heapify_up()
def compare(self, a, b):
return a < b
def delNode(self):
if self.length == 0:
print("Empty Heap")
return
elif self.length == 1:
top = self.get_top()
self.__init__(self.capacity)
return top
else :
top = self.get_top()
self.heap[0], self.heap[self.length - 1] = self.heap[self.length - 1], self.heap[0]
del(self.heap[-1])
self.length = self.length - 1
self.heapify_down(0)
return top
def heapify_up(self):
if self.length == 0:
return
else:
i = self.length - 1
while i != 0 and self.compare(self.heap[i].get_f(), self.heap[self.get_parent(i)].get_f()):
self.heap[i] , self.heap[self.get_parent(i)] = self.heap[self.get_parent(i)], self.heap[i]
i = self.get_parent(i)
def heapify_down(self, i):
l = self.left_child(0)
r = self.right_child(0)
smallest = i
if l < self.length and self.compare(self.heap[l].get_f(), self.heap[smallest].get_f()):
self.heap[l], self.heap[smallest] = self.heap[smallest], self.heap[l]
if r < self.length and self.compare(self.heap[r].get_f(), self.heap[smallest].get_f()):
self.heap[r], self.heap[smallest] = self.heap[smallest], self.heap[r]
if smallest != i:
self.heap[i], self.heap[smallest] = self.heap[smallest], self.heap[i]
self.heapify_down(smallest)
def print_heap(self):
for i in range(self.length):
#print(self.heap[i].f)
print(self.heap[i].state_string, self.heap[i].parent)
|
a10c0b370a62e1c80e52f738304304d763055e2d | 07Agarg/Course_Programming_Assignments | /Artificial Intelligent/Assignment 1/Solution 1/AstarNode.py | 865 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 2 05:05:16 2019
@author: ashima
"""
class Node:
def __init__(self, state, parent, g, h):
self.state = state #current_state
self.parent = parent #parent
self.g = g #total cost incurred to reach at current node
self.h = h #heuristic cost from current node
self.f = self.g + self.h
def get_f(self):
return self.f
def get_state(self):
return self.state
def get_g(self):
return self.g
#Working Heap
"""
Heap Test
a = Node()
a.f = 10
b = Node()
b.f = 6
c = Node()
c.f = 1
heap = Heap(100)
heap.addNode(a)
heap.addNode(b)
heap.addNode(c)
heap.print_heap()
print("Here")
print(heap.delNode().f)
print("Remaining")
heap.print_heap()
"""
|
abe22097172d8cc09b071bbbcd5b0114d09946ac | Philippe-Cholet/checkio-mission-next-birthday | /verification/tests.py | 4,895 | 3.6875 | 4 | from datetime import MINYEAR, MAXYEAR, date, timedelta
from random import randint, sample
from string import ascii_uppercase
from my_solution import next_birthday
BASIC_FAMILY = {
'Brian': (1967, 5, 31),
'Léna': (1970, 10, 3),
'Philippe': (1991, 6, 15),
'Yasmine': (1996, 2, 29),
'Emma': (2000, 12, 25),
}
WORLD_WIDE_FAMILY = {
'Emilie': (1990, 7, 31),
'Jean-Baptiste': (1985, 6, 3),
'Cameron': (1995, 11, 12),
'Mia': (1999, 4, 5),
'Elena': (1980, 1, 8),
'Alexei': (1993, 10, 28),
'Youssef': (1992, 4, 5),
'Soraya': (1996, 12, 27),
'Jiao': (1988, 2, 29),
'Kang': (2012, 8, 15),
'Pedro': (1959, 5, 2),
'Manuela': (1961, 3, 18),
'Inaya': (1968, 9, 22),
'Moussa': (1976, 2, 29),
}
_today = date.today()
today = _today.year, _today.month, _today.day
_yesterday = _today - timedelta(days=1)
yesterday = _yesterday.year, _yesterday.month, _yesterday.day
def random_date(min_year: int, diff: int):
while True:
year = randint(min_year, min_year + diff)
result = year, randint(1, 12), randint(1, 31)
# Check if it is a valid date.
try:
date(*result)
except ValueError:
continue
return result
def random_date_after(after_date, max_future: int):
while True:
result = random_date(after_date[0], max_future)
if result > after_date:
return result
def random_input(nb: int, max_range=80, max_future=20):
"""
`nb` people that all lives within `max_range` years, and
we look up to `max_future` years into the future.
"""
start_year = randint(MINYEAR, MAXYEAR - max_range - max_future - 1)
names = sample(ascii_uppercase, nb)
births = [random_date(start_year, max_range) for _ in range(26)]
return random_date_after(max(births), max_future), dict(zip(names, births))
TESTS = {
'1. Basic': [
{
'input': ((2020, 9, 8), BASIC_FAMILY),
'answer': [25, {'Léna': 50}],
},
{
'input': ((2021, 10, 4), BASIC_FAMILY),
'answer': [82, {'Emma': 21}],
'explanation': 'Happy Xmas & Birthday!',
},
{
'input': ((2022, 3, 1), BASIC_FAMILY),
'answer': [0, {'Yasmine': 26}],
'explanation': 'Yasmine was born on a leap day.',
},
],
'2. World Wide Family': [
{
'input': ((2020, 9, 8), WORLD_WIDE_FAMILY),
'answer': [14, {'Inaya': 52}],
},
{
'input': ((2013, 8, 15), WORLD_WIDE_FAMILY),
'answer': [0, {'Kang': 1}],
'explanation': 'Happy Birthday Kang!',
},
{
'input': ((2014, 3, 29), WORLD_WIDE_FAMILY),
'answer': [7, {'Mia': 15, 'Youssef': 22}],
'explanation': 'Two birthdays on April 5th.',
},
{
'input': ((2024, 2, 29), WORLD_WIDE_FAMILY),
'answer': [0, {'Jiao': 36, 'Moussa': 48}],
'explanation': 'Two birthdays on February 29th.',
},
{
'input': ((2025, 3, 1), WORLD_WIDE_FAMILY),
'answer': [0, {'Jiao': 37, 'Moussa': 49}],
'explanation': 'Two birthdays on February 29th, '
'reported to March 1st.',
},
{
'input': (today, WORLD_WIDE_FAMILY),
'answer': next_birthday(today, WORLD_WIDE_FAMILY),
'explanation': 'Today.',
},
],
# If you want to add some tests, do it here, thanks.
'3. More tests': [
{
'input': ((2021, 3, 1), {'A': (2000, 2, 29), 'B': (2000, 3, 1)}),
'answer': [0, {'A': 21, 'B': 21}],
'explanation': 'They did not born the same day '
'but they sometimes celebrate it the same day.',
},
{
'input': ((2017, 3, 1), {'Baby': (2016, 2, 29)}),
'answer': [0, {'Baby': 1}],
'explanation': 'First birthday for this baby '
'who was born on leap day.',
},
{
'input': (today, {'Baby': yesterday}),
'answer': next_birthday(today, {'Baby': yesterday}),
'explanation': 'Baby was born yesterday, '
'his/her birthday is nearly a year after.',
},
# Contribution from vvm70.
{
'input': ((2024, 3, 1), {'Baby': (2020, 2, 29)}),
'answer': [365, {'Baby': 5}],
},
],
'4. Random': [
{'input': data, 'answer': next_birthday(*data)}
for data in map(random_input, range(3, 27, 2))
],
}
if __name__ == '__main__':
for tests in TESTS.values():
for test in tests:
assert next_birthday(*test['input']) == test['answer'], \
test['explanation']
print('Checked')
|
f58a7d93fa29b5801350b4aad34303653ab4a935 | TanapTheTimid/ExpressionSolverExercise | /expression.py | 2,177 | 3.734375 | 4 | def eval(exp):
#algorithm cannot handle 2 signs next to each other
exp = exp.replace("+-","-")
if "(" in exp:
#first open paren
start = exp.find("(")
#find the corresponding closing paren by keeping track of num of open parens until 0 is reached
numparen = 1
i = start
while(numparen > 0):
i += 1
if(exp[i] == "("):
numparen += 1
elif(exp[i] == ")"):
numparen -= 1
#the last closure = index of paren
end = i
subexp = exp[start+1:end] # cut paren
evalsub = eval(subexp) #eval the subexpression in paren
#shove it back into the algorithm to evaluate correct order after paren delt with
return eval(exp[:start] + str(evalsub) + exp[end+1:])
#lowest priority operator becomes highest priority separator
#separate based on reverse order operation because separation means being evaluated last
if "+" in exp or "-" in exp:
divpnt = exp.rfind("+")
divpnt2 = exp.rfind("-")
divpnt = max(divpnt, divpnt2) #plus or minus whichever one appears last
if(exp[divpnt] == "+"):
return eval(exp[:divpnt]) + eval(exp[divpnt+1:])
else:
return eval(exp[:divpnt]) - eval(exp[divpnt+1:])
if "*" in exp or "/" in exp:
divpnt = exp.rfind("*")
divpnt2 = exp.rfind("/")
divpnt = max(divpnt, divpnt2)
if(exp[divpnt] == "*"):
return eval(exp[:divpnt]) * eval(exp[divpnt+1:])
else:
return eval(exp[:divpnt]) / eval(exp[divpnt+1:])
if "^" in exp:
divpnt = exp.find("^") #order of operation is defined weirdly for exponents, back to front
return eval(exp[:divpnt]) ** eval(exp[divpnt+1:])
#finally once simplify to number, return float
return float(exp)
print(eval("3-5-8+3+(3-6)+((2^4)^2+3/2-3*5+((3)))+3*((3+2)+(3+4+(3/4^4)^2/4+(3)))/2+(3-3)*2-3+(3/4*((3)/4))+((3))/2+(3-334444)*2*3+-5+2+(3-3)*2+2+(3+4)+3+(2+3.234234125412234234234234234)*3+2/4/(4/4)+3"))
|
c65858019b12bc00cc9733a9fa2de5fd5dda8d14 | asadali08/asadali08 | /Dictionaries.py | 1,662 | 4.375 | 4 | # Chapter 9. Dictionaries
# Dictionary is like a set of items with any label without any organization
purse = dict()# Right now, purse is an empty variable of dictionary category
purse['money'] = 12
purse['candy'] = 3
purse['tissues'] = 75
print(purse)
print(purse['candy'])
purse['money'] = purse['money'] + 8
print(purse)
lst = list()
lst.append(21)
lst.append(3)
print(lst)
print(lst[1])
abc = dict()
abc['age'] = 21
abc['course'] = 146
print(abc)
abc['age'] = 26
print(abc)
# You can make empty dictionary using curly brackets/braces
print('ccc' in abc)
# When we see a new entry, we need to add that new entry in a dictionary, we just simply add 1 in the dictionary under that entry
counts = dict()
names = ['ali', 'asad','ashraf','ali','asad']
for name in names:
if name not in counts:
counts[name] = 1
else:
counts[name] = counts[name] + 1
print(counts)
if name in counts:
x = counts[name]
else:
counts.get(name, 0)
print(counts)
# Dictionary and Files
counts = dict()
print('Enter a line of text: ')
line = input('')
words = line.split()
print('Words:',words)
print('Counting.........')
for word in words:
counts[word] = counts.get(word, 0) + 1
print('Counts',counts)
# The example above shows how many words are there in a sentence and how many times each word has been repeated in a sentence
length = {'ali': 1, 'andrew': 20, 'jayaram': 32}
for key in length:
print(key, length[key])
print(length.keys())
print(length.values())
for abc,ghi in length.items():
print(abc,ghi)
stuff = dict()
print(stuff.get('candy', -1)) |
2ee0f1e7152ce48dd69c0692fb6648c2b8a23f0a | Eder-Berno/Practica11_EDA1 | /Grágicas_en_tiempo_de_ejecución.py | 1,874 | 3.5625 | 4 | #Importando bibliotecas
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
#Cargando modulos
import random
from time import time
#Cargando las funciones guardadas en los archivos
from insertionSort import insertionSort_time
#Sólo se necesita llamara a la función principal
from quickSort import quickSort_time
#Tamaños de la lista de numero aleatorios a generar
datos = [ii*100 for ii in range(0,21)]
tiempo_is = [] #Lista para guardar el tiempo de ejecución de insert sort
tiempo_qs = [] #Lista para guardar el tiempo de ejcución de quick sort
for ii in datos:
lista_is = random.sample(range(0,10000000),ii)
#Se hace una copia de la lista para que se ejecute el algoritmo con los mismos numeros
lista_qs = lista_is.copy()
t0 = time() #Se queda el tiempo inicial
insertionSort_time(lista_is)
tiempo_is.append(round(time()-t0,6))
t0 = time ()
quickSort_time(lista_qs)
tiempo_qs.append(round(time()-t0,6))
#Imprimiendo tiempos parciales de ejecución
print("Tiempos parciales de ejcución en INSERT SORT {} [s]\n".format(tiempo_is))
print("Tiempos parciales de ejcución en QUICK SORT {} [s]".format(tiempo_qs))
#Imprimiendo tiempos totales de ejecución
#Para calcular el tiempo total se aplica la función sum() a las listas de tiempo
print("Tiempo total de ejcución en INSERT SORT {} [s]\n".format(sum(tiempo_is)))
print("Tiempo total de ejcución en QUICK SORT {} [s]\n".format(sum(tiempo_qs)))
#Generandola gráfica
fig, ax = subplots()
ax.plot(datos, tiempo_is, label ="insert sort", marker="*", color="r")
ax.plot(datos, tiempo_qs, label ="quick sort", marker="o", color="b")
ax.set_xlabel('Datos')
ax.set_ylabel('Tiempo')
ax.grid(True)
ax.legend(loc=2);
plt.tittle('Tiempo de ejcución [s] (insert vs. quick)')
plt.show()
|
1ddb981357e0b4de8031bdb08fbd9820c0e61bed | deepsheth3/phishingdata-Analysis | /2nd_data-spam-ham-email_results/spamPolarityScores.py | 3,634 | 3.578125 | 4 | import sys
import csv
import numpy as np
import nltk.data
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from nltk import sentiment
from nltk import word_tokenize
# Adapted from https://programminghistorian.org/en/lessons/sentiment-analysis
if(len(sys.argv) != 3):
print("Usage: python3 spamPolarityScores.py <pathtodatafile> <pathtowritefile>")
sys.exit()
# Open file to read in data
filename = sys.argv[1]
outfile = sys.argv[2]
# Initialize fields and rows arrays
fields = []
rows = []
# Read data in from csv file
with open(filename, encoding="ISO-8859-1") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
fields = next(csv_reader)
for row in csv_reader:
rows.append(row)
email_type = ["spam", "ham"]
# Analyze sentiment on email contents usign NLTK and tokenizer
sid = SentimentIntensityAnalyzer()
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
# Initalize results dictionary
results = {}
for type in email_type:
results[type] = []
# Go through each row in the dataset
for row in rows:
if(row[0] == "spam" ):
message_text = row[1]
scores = sid.polarity_scores(message_text)
results["spam"].append([message_text, scores['compound'], scores['neg'], scores['neu'], scores['pos']])
# Uncomment this section to tokenize message contents into phrases, make sure to comment out the two lines above this comment
# sentences = tokenizer.tokenize(message_text)
# for sentence in sentences:
# scores = sid.polarity_scores(sentence)
# results["spam"].append([sentence, scores['compound'], scores['neg'], scores['neu'], scores['pos']])
else:
message_text = row[1]
scores = sid.polarity_scores(message_text)
results["ham"].append([message_text, scores['compound'], scores['neg'], scores['neu'], scores['pos']])
# Uncomment this section to tokenize message contents into phrases, make sure to comment out the two lines above this comment
# sentences = tokenizer.tokenize(message_text)
# for sentence in sentences:
# scores = sid.polarity_scores(sentence)
# results["ham"].append([sentence, scores['compound'], scores['neg'], scores['neu'], scores['pos']])
# Write results to outfile
with open("spamResults.csv", mode = 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',')
csv_writer.writerow(['message', 'compound', 'neg', 'neu', 'pos'])
for row in results["spam"]:
csv_writer.writerow(row)
with open("hamResults.csv", mode = 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',')
csv_writer.writerow(['message', 'compound', 'neg', 'neu', 'pos'])
for row in results["ham"]:
csv_writer.writerow(row)
# sumVals["total"] = [0,0,0,0]
# countVals["total"] = 0
# sigfig = 3
# with open("results.txt", mode = 'w') as file:
# for type in email_type:
# sumVals["total"] = np.add(sumVals["total"], sumVals[type])
# countVals["total"] += countVals[type]
# file.write(f"{type}: compound: {round(sumVals[type][0]/countVals[type], sigfig)}, neg: {round(sumVals[type][1]/countVals[type], sigfig)}, neu: {round(sumVals[type][2]/countVals[type], sigfig)}, pos: {round(sumVals[type][3]/countVals[type], sigfig)}\n")
# file.write("Overall Polarity Scores\n")
# file.write(f"compound: {round(sumVals['total'][0]/countVals['total'], sigfig)}, neg: {round(sumVals['total'][1]/countVals['total'], sigfig)}, neu: {round(sumVals['total'][2]/countVals['total'], sigfig)}, pos: {round(sumVals['total'][3]/countVals['total'], sigfig)}")
|
62a73c88a7b6df3fe6741efe00de04792473582a | shreyakupadhyay/furry-spork-latex | /new_PL_project/lineSegments.py | 4,464 | 3.5 | 4 | '''
Description: Detecting squares from a 2D matrix.
Working status: Final working code for detecting line segments in 2-D matrix.
'''
# and start_node != (row,col))
import sys
# import pandas as pd
coordinates = []
#pts = []
lines = []
extra, sides = 0,0
matrix = []
checks = []
# filename = sys.argv[1] # matrix.txt
'''
reading matrix from a file.
'''
def readInput():
raw_mat = []
f = open(filename)
for line in f.readlines():
raw_mat.append(line.split())
f.close()
for row in raw_mat:
matrix.append([i for i in row if i.isdigit()])
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrix[i][j]=int(matrix[i][j])
'''
initialising the checks matrix
'''
def initCheck():
global checks
checks = [[0 for x in range(cols)] for y in range(rows)]
'''
removing duplicates from list and also preserving the order
'''
def removeDuplicates(myList):
newlist = []
for element in myList:
if element not in newlist:
newlist.append(element)
return newlist
'''
Getting number of ones surrounding a point in a matrix.
'''
def numOnes(row,col):
num_ones = 0
if row + 1 < rows and matrix[row + 1][col] == 1:
num_ones = num_ones + 1
if row - 1 >= 0 and matrix[row - 1][col] == 1:
num_ones = num_ones + 1
if col + 1 < cols and matrix[row][col + 1] == 1:
num_ones = num_ones + 1
if col - 1 >= 0 and matrix[row][col - 1] == 1:
num_ones = num_ones + 1
# print num_ones
return num_ones
'''
movement of pointer in a direction at particular coordinate
'''
def motion(next_row,next_col,prev_node,row,col,direction,count,prev_dir,start_node,corner):
global sides
if (extra == 1):
return
count = count+1
next_dir = direction
next_node = (next_row, next_col)
# print pd.DataFrame(checks)
# print "====================="
global coordinates
if next_node != prev_node:
checks[row][col] = checks[row][col] + 1
if (prev_dir != direction or numOnes(row,col)>=3):
sides = sides + 1
coordinates.append((row,col))
prev_corner = corner
corner = (row,col)
# print (prev_corner,corner)
if(prev_corner != corner):
lines.append(tuple((prev_corner,corner)))
# pts.append(tuple((row,col)))
decision(next_row, next_col, next_dir, (row, col), start_node,count,corner)
'''
making decision to go in a direction using various creteria
'''
def decision(row, col, prev_dir, prev_node,start_node,count,corner):
# [row][col] current location
global extra # breaking recursion.
if (start_node == prev_node and count>1):
extra = 1
return extra
if(extra == 1):
return extra
if row + 1 < rows and matrix[row + 1][col] == 1 and checks[row + 1][col]<=(numOnes(row+1,col)-1): # [row+1][col] down
motion(row + 1 , col, prev_node, row, col, 'd',count,prev_dir,start_node,corner)
if row - 1 >= 0 and matrix[row - 1][col] == 1 and checks[row - 1][col]<=(numOnes(row-1,col)-1): # [row-1][col] up
motion(row - 1, col, prev_node, row, col, 'u',count,prev_dir,start_node,corner)
if col + 1 < cols and matrix[row][col + 1] == 1 and checks[row][col+1]<=(numOnes(row,col+1)-1): # [row][col+1] right
motion(row, col+1, prev_node, row, col, 'r',count,prev_dir,start_node,corner)
if col - 1 >= 0 and matrix[row][col - 1] == 1 and checks[row][col-1]<=(numOnes(row,col-1)-1): # [row][col-1] left
motion(row , col-1 , prev_node, row, col, 'l',count,prev_dir,start_node,corner)
'''
Iterating through matrix.
'''
def iterMatrix():
row, col, count = 0,0,0
for row in range(0,rows):
for col in range(0,cols):
if (matrix[row][col] == 0):
continue
elif (matrix[row][col] == 1):
start_node = (row, col)
corner = start_node
decision(row, col, '', (row, col - 1), start_node,0,corner)
break
if (count == 1):
break
# if __name__ == "__main__":
def main(Filename):
global filename
filename = Filename
readInput()
global rows,cols
rows = len(matrix) # number of rows of matrix
cols = len(matrix[0]) # number of columns of matrix
initCheck()
iterMatrix()
# print [line for line in set(lines)]
unique_lines = removeDuplicates(lines)
return [line for line in unique_lines]
# main(sys.argv[1]) |
a3fbe3fa0441f40d6d00fe792dc92e7c0acd2880 | jyj902/Python | /Python/Test_01.py | 286 | 3.734375 | 4 | INPUT =1
while INPUT !=0 :
INPUT = int(input("숫자 입력 :: "))
i=2
while True:
if(INPUT%i == 0):
break
i +=1
if(i == INPUT):
print("소수 입니다.")
else:
print("소수가 아닙니다.")
print("종료 합니다.") |
28dc7a4d6d418166df9a8dad55c7e4beb2d9e5b8 | MichaelCAllan/First-Python-Program | /Michael.py | 158 | 3.984375 | 4 | ints = [1,2,3,4,5]
def listadd(ints):
total = 0
for item in ints:
total += item
return (total)
value = listadd(ints)
print (value)
|
0d49dc317831167e5325ac574df5eafa37dbc73f | Andy-Ho8872/Py-code | /Tkinter/GUI_first.py | 1,793 | 3.5625 | 4 | import tkinter as tk
from PIL import Image, ImageTk
#建立主視窗
win = tk.Tk()
#設定視窗名稱(標題)
win.title("視窗名稱測試")
#設定視窗大小
win.geometry("400x300+800+400") #(寬x高 +X +Y) (用字串表示,後面的 + 前者數字為X軸,後者為Y)---(設定開啟視窗大小預設值及位置)
win.minsize(width=400, height=200) #設定視窗最小值
win.maxsize(width=1024, height=768) #設定視窗最大值
#win.resizable(0, 0) #使視窗無法被縮放
#設定視窗icon
win.iconbitmap("E:\\python-training\\icon\\tomato.ico") #圖檔的副檔名建議用.ico
#設定背景顏色
win.config(background="pink")
#設定透明度
win.attributes("-alpha",0.95) #透明度設定值為 0 ~ 1 0為完全透明,1為不透明
#置頂視窗
win.attributes("-topmost",True)
#建立按鈕圖片
img = Image.open("E:\\python-training\\icon\\0.png") #圖片位置
load_image = ImageTk.PhotoImage(img) #需先將圖片轉換成 Photoimage
show_tomato = Image.open("E:\\python-training\\icon\\tomato.png")
load_tomato_img = ImageTk.PhotoImage(show_tomato)
#建立按鈕功能
def click_open():
show_tomato.show()
#建立與設定按鈕(Button)。
btn01 = tk.Button(text="按鈕1")
btn01.config(image=load_image) #修改按鈕樣式
btn01.config(command=click_open) #設定按鈕功能
btn01.place(relx=0.5, rely=0.5, anchor="center") #放置(封裝、包裝)按鈕,按鈕才會出現。 放置方法: 1 .pack() 2 .place 3 .grid()
#建立與設定輸入物件(Entry)
en01 = tk.Entry()
en01.pack()
#設定與建立標籤(Label)
lb01 = tk.Label(text="這是標籤")
lb01.config(background="white")
lb01.place(relx=0.5, rely=0.8, anchor="center") #此為相對定位 rel值在 0~1之間,anchor為錨點
#常駐主視窗
win.mainloop()
|
d56c7b7cf04a9375cc7ad1811ca483f1fdbf539f | Andy-Ho8872/Py-code | /20200530.py | 394 | 3.8125 | 4 |
class Cat():
def __init__(self, name, age, gender): # 因為self是class本身 所以第一個不用更動
self.name = name # 在這邊self.的設定 就代表你之後可以用的class屬性
self.age = age
self.gender = gender
Cat_info = Cat("來福", 7 ,"male")
print("姓名:",Cat_info.name,"\n" "年齡:",Cat_info.age,"\n" "性別:",Cat_info.gender)
|
f41b1eeae8a40524834d5879310656caae0f9d2a | LucasSoftware12/EjerciciosPy | /Desafios/9_sensos.py | 2,118 | 3.578125 | 4 | # Un censador recopila ciertos datos aplicando encuestas para el último Censo Nacional de Población y Vivienda. Desea obtener de todas las personas que alcance a encuestar en un día, que porcentaje tiene estudios de primaria, secundaria, carrera técnica, estudios profesionales y estudios de posgrado.
inicio = True
primaria = 0
secundaria = 0
carrera = 0
profesionales = 0
posgrado = 0
while inicio:
print('Campaña de senso')
estudios = int(input('Tiene estudios primarios? '
'1) Si'
'2) No'))
if estudios == 1:
primaria = primaria+1
estudios1 = int(input('Tiene estudios secundarios? '
'1) Si'
'2) No'))
if estudios1 == 1:
secundaria = secundaria+1
estudios2 = int(input('Tiene carrera técnica? '
'1) Si'
'2) No'))
if estudios2 == 1:
carrera = carrera+1
estudios3 = int(input('Tiene estudios profesionales? '
'1) Si'
'2) No'))
if estudios3 == 1:
profesionales = profesionales+1
estudios4 = int(input('Tiene estudios posgrado? '
'1) Si'
'2) No'))
if estudios4 == 1:
posgrado = posgrado+1
personas = primaria+secundaria+carrera+profesionales+posgrado
seguimos = (input('\nSeguimos'
'\nSi''\nNo'
'\n'))
if seguimos == "No":
inicio = False
print('cantidad de personas', personas)
print('Porcentaje de personas que tiene estudios primarios %',
(primaria/personas)*100)
print('Porcentaje de personas que tiene estudios secundaria %',
(secundaria/personas)*100)
print('Porcentaje de personas que tiene carrera tecnica %',
(carrera/personas)*100)
print('Porcentaje de personas que tiene estudios profesionales %',
(profesionales/personas)*100)
print('Porcentaje de personas que tiene estudios posgrado %',
(posgrado/personas)*100)
|
edd53043474af7e8aa6c88e60dbafac02d95ace4 | LucasSoftware12/EjerciciosPy | /Desafios/Ejercicios complementarios Condicionales/3_NumeroMayor.py | 453 | 3.921875 | 4 | # Alumno Lucas Medina
print("Ejercicio Número mayor")
numUno = int(input("Ingrese un numero: "))
numDos = int(input("Ingrese un numero: "))
numTres = int(input("Ingrese un numero: "))
if (numUno > numDos) and (numUno > numTres):
print(f"El numero mayor es: {numUno}")
elif (numDos > numUno) and (numDos > numTres):
print(f"El numero mayor es: {numDos}")
elif (numTres > numDos) and (numTres > numUno):
print(f"El numero mayor es: {numTres}")
|
cbdfa681eae3c82c8645345822f9ccfaaa51262f | LucasSoftware12/EjerciciosPy | /Desafios/6_contarSumar.py | 551 | 3.953125 | 4 | while True:
x = int(input("Ingrese el primer numero: "))
z = int(input("Ingrese el segundo numero: "))
if z < x:
print("El segundo numero debe ser mayor al primero, vuelva a ingresarlo")
z = int(input("Ingrese el segundo numero: "))
elif z >= x:
break
cont = 0
cont2 = 0
for i in range(x, z+1, 1):
if i % 2 == 0:
cont += 1
print("Multiplo N°", cont, "es:", i)
cont2 += i
print("Hay", cont, "multiplos de 2 entre esos 2 numeros")
print("La suma de los multiplos de 2 es:", cont2)
|
68376555846fe3e74828dc6ba21da945009484a8 | LucasSoftware12/EjerciciosPy | /Desafios/1_mayorde10.py | 238 | 3.734375 | 4 | # 1) Determinar el número mayor de 10 números ingresados.
mayor = 0
maximo = 10
for i in range(maximo):
num = int(input('Dame un numero: '))
if num > mayor:
mayor = num
print(f"El mayor de los 10 numeros es: {mayor}")
|
da18962e5cab2c784f8cb08336a6bfb61a28772d | SofiaNikolaeva-adey-201/practicheskaya4 | /main2.py | 574 | 3.890625 | 4 | class Person:
def __init__(self, n, s, q = 1):
self.name = n
self.surname = s
self.skill = q
def __del__(self):
print('До свидания, мистер', self.name, self.surname)
def info(self):
return '{1} {0}, {2}'.format(self.name, self.surname, self.skill)
worker = Person('И', 'Котов', 3)
helper = Person('Д', 'Мышев', 1)
maker = Person('О', 'Рисов', 2)
print(worker.info())
print(helper.info())
print(maker.info())
del helper
print('Конец программы')
input()
|
26533d5854323190d839660bb7f41595c9e86789 | justinchen673/Catan-AI | /port.py | 503 | 3.84375 | 4 | """
port.py
This file holds the representation of the Port object, which just holds the
conversion type of the port. resourceType denotes what resource you need to
trade in, and number denotes how many of that resource you need to trade in to
get a resource of your choice.
"""
class Port:
'''
This represents a port, which allows for easier trading.
'''
def __init__(self, number, resourceType):
self.number = number
self.resourceType = resourceType
|
b7152d196dff60a8ee56baf10a77cd434862d6c0 | justinchen673/Catan-AI | /board.py | 31,105 | 3.828125 | 4 | """
board.py
This file holds the representation of the board as well as any functions it may
need. It is comprised of the Vertex and Hex classes, which together along some
other structures makes up the Board class.
"""
import copy
from port import Port
from player import Player
class Vertex:
'''
This represents a single vertex on the board. Its number is designated by
its position in the vertices array. Also, docks will always be on the same
number vertices, so we don't code them in here.
'''
def __init__(self):
self.empty = True
self.playerName = ''
self.city = False
self.port = None
class Hex:
'''
This represents a single hex on the board. Its number is designated by its
position in the hexes array.
'''
def __init__(self, resourceType, number):
self.resourceType = resourceType
self.number = number
# Robber always starts on the sand hex.
if (resourceType == "sand"):
self.robber = True
else:
self.robber = False
def robberFormat(self):
if self.robber:
return "R"
else:
return " "
def debugPrint(self):
'''
This should ONLY be used for degbugging purposes. This prints a non
formatted display of the resource type and number on this hex.
'''
print(self.resourceType, self.number)
class Board:
'''
This is an object of the entire board.
'''
def __init__(self, vertices, hexes):
# List of vertices
self.vertices = vertices
# List of hexes
self.hexes = hexes
# Roads is a dictionary: Key is a tuple of the vertices, value is name
self.roads = {
(0, 3): "//",
(0, 4): "\\\\",
(1, 4): "//",
(1, 5): "\\\\",
(2, 5): "//",
(2, 6): "\\\\",
(3, 7): "||",
(4, 8): "||",
(5, 9): "||",
(6, 10): "||",
(7, 11): "//",
(7, 12): "\\\\",
(8, 12): "//",
(8, 13): "\\\\",
(9, 13): "//",
(9, 14): "\\\\",
(10, 14): "//",
(10, 15): "\\\\",
(11, 16): "||",
(12, 17): "||",
(13, 18): "||",
(14, 19): "||",
(15, 20): "||",
(16, 21): "//",
(16, 22): "\\\\",
(17, 22): "//",
(17, 23): "\\\\",
(18, 23): "//",
(18, 24): "\\\\",
(19, 24): "//",
(19, 25): "\\\\",
(20, 25): "//",
(20, 26): "\\\\",
(21, 27): "||",
(22, 28): "||",
(23, 29): "||",
(24, 30): "||",
(25, 31): "||",
(26, 32): "||",
(27, 33): "\\\\",
(28, 33): "//",
(28, 34): "\\\\",
(29, 34): "//",
(29, 35): "\\\\",
(30, 35): "//",
(30, 36): "\\\\",
(31, 36): "//",
(31, 37): "\\\\",
(32, 37): "//",
(33, 38): "||",
(34, 39): "||",
(35, 40): "||",
(36, 41): "||",
(37, 42): "||",
(38, 43): "\\\\",
(39, 43): "//",
(39, 44): "\\\\",
(40, 44): "//",
(40, 45): "\\\\",
(41, 45): "//",
(41, 46): "\\\\",
(42, 46): "//",
(43, 47): "||",
(44, 48): "||",
(45, 49): "||",
(46, 50): "||",
(47, 51): "\\\\",
(48, 51): "//",
(48, 52): "\\\\",
(49, 52): "//",
(49, 53): "\\\\",
(50, 53): "//"
}
# A matrix that tells what vertices each hex is linked to
self.hexRelationMatrix = [
[0, 3, 4, 7, 8, 12],
[1, 4, 5, 8, 9, 13],
[2, 5, 6, 9, 10, 14],
[7, 11, 12, 16, 17, 22],
[8, 12, 13, 17, 18, 23],
[9, 13, 14, 18, 19, 24],
[10, 14, 15, 19, 20, 25],
[16, 21, 22, 27, 28, 33],
[17, 22, 23, 28, 29, 34],
[18, 23, 24, 29, 30, 35],
[19, 24, 25, 30, 31, 36],
[20, 25, 26, 31, 32, 37],
[28, 33, 34, 38, 39, 43],
[29, 34, 35, 39, 40, 44],
[30, 35, 36, 40, 41, 45],
[31, 36, 37, 41, 42, 46],
[39, 43, 44, 47, 48, 51],
[40, 44, 45, 48, 49, 52],
[41, 45, 46, 49, 50, 53]
]
# A matrix that tells what vertices each vertex is linked to
self.vertexRelationMatrix = [
[3, 4],
[4, 5],
[5, 6],
[0, 7],
[0, 1, 8],
[1, 2, 9],
[2, 10],
[3, 11, 12],
[4, 12, 13],
[5, 13, 14],
[6, 14, 15],
[7, 16],
[7, 8, 17],
[8, 9, 18],
[9, 10, 19],
[10, 20],
[11, 21, 22],
[12, 22, 23],
[13, 23, 24],
[14, 24, 25],
[15, 25, 26],
[16, 27],
[16, 17, 28],
[17, 18, 29],
[18, 19, 30],
[19, 20, 31],
[20, 32],
[21, 33],
[22, 33, 34],
[23, 34, 35],
[24, 35, 36],
[25, 36, 37],
[26, 37],
[27, 28, 38],
[28, 29, 39],
[29, 30, 40],
[30, 31, 41],
[31, 32, 42],
[33, 43],
[34, 43, 44],
[35, 44, 45],
[36, 45, 46],
[37, 46],
[38, 39, 47],
[39, 40, 48],
[40, 41, 49],
[41, 42, 50],
[43, 51],
[44, 51, 52],
[45, 52, 53],
[46, 53],
[47, 48],
[48, 49],
[49, 50]
]
def canPlaceSettlement(self, vertex, playerName, firstPlacement):
'''
Determines if a settlement can be placed at the vertex given the user.
The boolean value firstPlacement determines whether this is the first
placement, meaning that the game is in the setup phase.
'''
# Out of bounds vertex
if (vertex < 0 or vertex > 53):
return False
# Something already there
if not self.vertices[vertex].empty:
return False
# Something at an adjacent vertex
for i in self.vertexRelationMatrix[vertex]:
if not self.vertices[i].empty:
return False
# Checks if it's connected to a road if it isn't the first placement
if not firstPlacement:
for i in self.vertexRelationMatrix[vertex]:
if (i > vertex):
if self.roads[(vertex, i)] == playerName + playerName:
return True
else:
if self.roads[(i, vertex)] == playerName + playerName:
return True
return False
return True
def placeSettlement(self, vertex, player):
'''
Adds a settlement to the board given the vertex and the player's name
'''
self.vertices[vertex].empty = False
self.vertices[vertex].playerName = player.name
player.points += 1
def canPlaceRoad(self, vertex1, vertex2, playerName):
'''
Determines if a road can be placed between the two vertices given the
user.
'''
# Checks if the vertices are next to each other
if not vertex2 in self.vertexRelationMatrix[vertex1]:
return False
# Checks if there is already a road there
if (vertex1 < vertex2):
if self.roads[(vertex1, vertex2)] == "AA" or self.roads[(vertex1, vertex2)] == "BB" or self.roads[(vertex1, vertex2)] == "CC" or self.roads[(vertex1, vertex2)] == "DD":
return False
# Checks if there is a settlement of the same playerName at either
# vertex
if (not self.vertices[vertex1].empty) and (self.vertices[vertex1].playerName == playerName):
return True
if (not self.vertices[vertex2].empty) and (self.vertices[vertex2].playerName == playerName):
return True
# Checks if this connects a road already placed
for i in self.vertexRelationMatrix[vertex1]:
if (vertex1 < i):
if self.roads[(vertex1, i)] == playerName + playerName:
return True
else:
if self.roads[(i, vertex1)] == playerName + playerName:
return True
for i in self.vertexRelationMatrix[vertex2]:
if (vertex2 < i):
if self.roads[(vertex2, i)] == playerName + playerName:
return True
else:
if self.roads[(i, vertex2)] == playerName + playerName:
return True
return False
def placeRoad(self, vertex1, vertex2, player, playerList):
'''
Adds a road to the board given the 2 vertices it is between and the
player's name
'''
if (vertex1 < vertex2):
self.roads[(vertex1, vertex2)] = player.name + player.name
else:
self.roads[(vertex2, vertex1)] = player.name + player.name
self.assignLongestRoad(player, playerList)
def findRoadEdges(self, playerRoads):
'''
Checks to see which road (tuple pair of vertices) is the edge. If there
is no edge, there must be a cycle, which we will account for later.
'''
# The list of edges to be returned
edges = []
for road in playerRoads:
# vertex_ indicates whether that vertex has a connection. If both
# are True, then this road cannot be an edge.
vertex1 = False
vertex2 = False
# Checks for a connection with the first vertex
for vertex in self.vertexRelationMatrix[road[0]]:
if ((road[0], vertex) in playerRoads and (road[0], vertex) != road) or ((vertex, road[0]) in playerRoads and (vertex, road[0]) != road):
vertex1 = True
# Checks for a connection with the second vertex
for vertex in self.vertexRelationMatrix[road[1]]:
if ((road[1], vertex) in playerRoads and (road[1], vertex) != road) or ((vertex, road[1]) in playerRoads and (vertex, road[1]) != road):
vertex2 = True
if not (vertex1 and vertex2):
edges.append(road)
return edges
def dfs(self, visited, globalVisited, player, playerRoads, currentRoad, length, used):
'''
Runs DFS to find the longest road.
'''
visited[currentRoad] = True
# globalVisited is for ensuring all roads are checked, mainly just
# applicable for cycles
globalVisited[currentRoad] = True
length += 1
# Because dictionaries are passed by reference in python, we need to do
# a deepcopy
visited2 = copy.deepcopy(visited)
# Detects if you reached the end of the road, in which case check length
endOfRoad = True
nextRoad = ()
nextUsed = -1
# "used" indicates the vertex it came from. The longest road cannot use
# this vertex for the next road.
if (used != 0):
for vertex in self.vertexRelationMatrix[currentRoad[0]]:
# Our roads are tracked as (x, y) where x < y, so this figures
# out the formatting of the road tuple to check
if (vertex < currentRoad[0]):
nextRoad = (vertex, currentRoad[0])
nextUsed = 1
else:
nextRoad = (currentRoad[0], vertex)
nextUsed = 0
# This checks if the adjacent road is owned by the player and
# has not been visited. If so, recurse.
if nextRoad in playerRoads and visited[nextRoad] == False:
self.dfs(visited2, globalVisited, player, playerRoads, nextRoad, length, nextUsed)
endOfRoad = False
if (used != 1):
for vertex in self.vertexRelationMatrix[currentRoad[1]]:
# Our roads are tracked as (x, y) where x < y, so this figures
# out the formatting of the road tuple to check
if (vertex < currentRoad[1]):
nextRoad = (vertex, currentRoad[1])
nextUsed = 1
else:
nextRoad = (currentRoad[1], vertex)
nextUsed = 0
if nextRoad in playerRoads and visited[nextRoad] == False:
self.dfs(visited2, globalVisited, player, playerRoads, nextRoad, length, nextUsed)
endOfRoad = False
# If you reached the end of the road, check the length to see if it's
# the longest.
if endOfRoad and length > player.longestRoadLength:
player.longestRoadLength = length
def calculateLongestRoadLength(self, player):
'''
Finds the length of the player's longest road, and updates it in
player.longestRoadLength.
'''
playerRoads = {}
for road in self.roads:
if (self.roads[road][0] == player.name):
playerRoads[road] = True
edges = self.findRoadEdges(playerRoads)
visited = {}
globalVisited = {}
for road in playerRoads:
visited[road] = False
globalVisited[road] = False
for edge in edges:
self.dfs(visited, globalVisited, player, playerRoads, edge, 0, -1)
visited = {}
for road in playerRoads:
visited[road] = False
for road in globalVisited:
if globalVisited[road] == False:
self.dfs(visited, globalVisited, player, playerRoads, road, 0, 0)
def assignLongestRoad(self, player, playerList):
'''
Calculates who has the longest road.
'''
# Player just added a road, so update their longest road length. It may
# or may not change.
self.calculateLongestRoadLength(player)
# Figure out if the current player now has the longest road
if (player.longestRoadLength >= 5):
longestRoad = True
for i in playerList:
if (i.name != player.name):
# If anyone has more roads or the same number of roads, the
# current player can't have the longest road.
if (player.longestRoadLength <= i.longestRoadLength):
longestRoad = False
break
if (longestRoad):
# Only one can have the largest army, so make it false for all
# others
for i in playerList:
i.longestRoad = False
player.longestRoad = True
def formatHex(self,resource):
'''
Helper function for formatting when printing.
'''
# Counts extra space if word has an odd length.
extra_space = 0
# 18 total spaces between lines in hex
spaces = 18 - len(str(resource))
left_space = int(spaces/2)
right_space = int(spaces/2)
if spaces%2 == 1:
extra_space = 1
return_val = left_space*" " + str(resource) + right_space*" " + extra_space*" "
return return_val
def formatVertex(self, index):
'''
Helper function for formatting when printing vertices.
'''
returnStr = str(index)
if (self.vertices[index].empty):
# Returns the formatted number
if (len(returnStr) == 1):
return " 0" + returnStr + " "
return " " + returnStr + " "
else:
# Returns the formatted settlement / city
if (self.vertices[index].city):
if (len(returnStr) == 1):
return self.vertices[index].playerName + "C(0"+returnStr+")"
return self.vertices[index].playerName + "C(" + returnStr + ")"
else:
if (len(returnStr) == 1):
return self.vertices[index].playerName + "S(0" + returnStr + ")"
return self.vertices[index].playerName + "S(" + returnStr + ")"
def printBoard(self):
'''
Prints the board
'''
print(" "*10+" Wood Wildcard")
print(" "*10+" "+self.formatVertex(0)+" @4,1 "+self.formatVertex(1)+" @2,6 "+self.formatVertex(2)+"")
print(" "*10+" "+self.roads[(0,3)]+" "+self.roads[(0,4)]+" "+self.roads[(1,4)]+" "+self.roads[(1,5)]+" "+self.roads[(2,5)]+" "+self.roads[(2,6)]+"")
print(" "*10+" "+self.roads[(0,3)]+" "+self.roads[(0,4)]+" "+self.roads[(1,4)]+" "+self.roads[(1,5)]+" "+self.roads[(2,5)]+" "+self.roads[(2,6)]+"")
print(" "*10+" "+self.roads[(0,3)]+" "+self.roads[(0,4)]+" "+self.roads[(1,4)]+" "+self.roads[(1,5)]+" "+self.roads[(2,5)]+" "+self.roads[(2,6)]+"")
print(" "*10+" "+self.roads[(0,3)]+" "+self.roads[(0,4)]+" "+self.roads[(1,4)]+" "+self.roads[(1,5)]+" "+self.roads[(2,5)]+" "+self.roads[(2,6)]+" ")
print(" "*10+" "+self.formatVertex(3)+" "+self.formatVertex(4)+" "+self.formatVertex(5)+" "+self.formatVertex(6)+"")
print(" "*10+" "+self.roads[(3,7)]+self.formatHex(self.hexes[0].resourceType)+self.roads[(4,8)]+self.formatHex(self.hexes[1].resourceType)+ self.roads[(5,9)]+self.formatHex(self.hexes[2].resourceType)+ self.roads[(6,10)])
print(" "*10+" "+self.roads[(3,7)]+self.formatHex(self.hexes[0].number)+self.roads[(4,8)]+self.formatHex(self.hexes[1].number)+self.roads[(5,9)]+self.formatHex(self.hexes[2].number)+self.roads[(6,10)])
print(" "*10+" Brick "+self.roads[(3,7)]+" "+self.hexes[0].robberFormat()+" "+self.roads[(4,8)]+" "+self.hexes[1].robberFormat()+" "+self.roads[(5,9)]+" "+self.hexes[2].robberFormat()+" "+self.roads[(6,10)])
print(" "*10+" @7,11 "+self.formatVertex(7)+" "+self.formatVertex(8)+" "+self.formatVertex(9)+" "+self.formatVertex(10)+"")
print(" "*10+" "+self.roads[(7,11)]+" "+self.roads[(7,12)]+" "+self.roads[(8,12)]+" "+self.roads[(8,13)]+" "+self.roads[(9,13)]+" "+self.roads[(9,14)]+" "+self.roads[(10,14)]+" "+self.roads[(10,15)])
print(" "*10+" "+self.roads[(7,11)]+" "+self.roads[(7,12)]+" "+self.roads[(8,12)]+" "+self.roads[(8,13)]+" "+self.roads[(9,13)]+" "+self.roads[(9,14)]+" "+self.roads[(10,14)]+" "+self.roads[(10,15)])
print(" "*10+" "+self.roads[(7,11)]+" "+self.roads[(7,12)]+" "+self.roads[(8,12)]+" "+self.roads[(8,13)]+" "+self.roads[(9,13)]+" "+self.roads[(9,14)]+" "+self.roads[(10,14)]+" "+self.roads[(10,15)])
print(" "*10+" "+self.roads[(7,11)]+" "+self.roads[(7,12)]+" "+self.roads[(8,12)]+" "+self.roads[(8,13)]+" "+self.roads[(9,13)]+" "+self.roads[(9,14)]+" "+self.roads[(10,14)]+" "+self.roads[(10,15)])
print(" "*10+" "+self.formatVertex(11)+" "+self.formatVertex(12)+" "+self.formatVertex(13)+" "+self.formatVertex(14)+" "+self.formatVertex(15)+"")
print(" "*10+" "+self.roads[(11,16)]+self.formatHex(self.hexes[3].resourceType)+self.roads[(12,17)]+self.formatHex(self.hexes[4].resourceType)+self.roads[(13,18)]+self.formatHex(self.hexes[5].resourceType)+self.roads[(14,19)]+self.formatHex(self.hexes[6].resourceType)+self.roads[(15,20)]+" Wheat")
print(" "*10+" "+self.roads[(11,16)]+self.formatHex(self.hexes[3].number)+self.roads[(12,17)]+self.formatHex(self.hexes[4].number)+self.roads[(13,18)]+self.formatHex(self.hexes[5].number)+self.roads[(14,19)]+self.formatHex(self.hexes[6].number)+self.roads[(15,20)]+" @15,20")
print(" "*10+" "+self.roads[(11,16)]+" "+self.hexes[3].robberFormat()+" "+self.roads[(12,17)]+" "+self.hexes[4].robberFormat()+" "+self.roads[(13,18)]+" "+self.hexes[5].robberFormat()+" "+self.roads[(14,19)]+" "+self.hexes[6].robberFormat()+" "+self.roads[(15,20)])
print(" "*10+" "+self.formatVertex(16)+" "+self.formatVertex(17)+" "+self.formatVertex(18)+" "+self.formatVertex(19)+" "+self.formatVertex(20)+"")
print(" "*10+" "+self.roads[(16,21)]+" "+self.roads[(16,22)]+" "+self.roads[(17,22)]+" "+self.roads[(17,23)]+" "+self.roads[(18,23)]+" "+self.roads[(18,24)]+" "+self.roads[(19,24)]+" "+self.roads[(19,25)]+" "+self.roads[(20,25)]+" "+self.roads[(20,26)])
print(" "*10+" "+self.roads[(16,21)]+" "+self.roads[(16,22)]+" "+self.roads[(17,22)]+" "+self.roads[(17,23)]+" "+self.roads[(18,23)]+" "+self.roads[(18,24)]+" "+self.roads[(19,24)]+" "+self.roads[(19,25)]+" "+self.roads[(20,25)]+" "+self.roads[(20,26)])
print(" "*10+" "+self.roads[(16,21)]+" "+self.roads[(16,22)]+" "+self.roads[(17,22)]+" "+self.roads[(17,23)]+" "+self.roads[(18,23)]+" "+self.roads[(18,24)]+" "+self.roads[(19,24)]+" "+self.roads[(19,25)]+" "+self.roads[(20,25)]+" "+self.roads[(20,26)])
print(" "*10+" "+self.roads[(16,21)]+" "+self.roads[(16,22)]+" "+self.roads[(17,22)]+" "+self.roads[(17,23)]+" "+self.roads[(18,23)]+" "+self.roads[(18,24)]+" "+self.roads[(19,24)]+" "+self.roads[(19,25)]+" "+self.roads[(20,25)]+" "+self.roads[(20,26)])
print("Wildcard"+self.formatVertex(21)+" "+self.formatVertex(22)+" "+self.formatVertex(23)+" "+self.formatVertex(24)+" "+self.formatVertex(25)+" "+self.formatVertex(26))
print("@21,27 "+self.roads[(21,27)]+self.formatHex(self.hexes[7].resourceType)+self.roads[(22,28)]+self.formatHex(self.hexes[8].resourceType)+self.roads[(23,29)]+self.formatHex(self.hexes[9].resourceType)+self.roads[(24,30)]+self.formatHex(self.hexes[10].resourceType)+self.roads[(25,31)]+self.formatHex(self.hexes[11].resourceType)+self.roads[(26,32)])
print(" "*10+self.roads[(21,27)]+self.formatHex(self.hexes[7].number)+self.roads[(22,28)]+self.formatHex(self.hexes[8].number)+self.roads[(23,29)]+self.formatHex(self.hexes[9].number)+self.roads[(24,30)]+self.formatHex(self.hexes[10].number)+self.roads[(25,31)]+self.formatHex(self.hexes[11].number)+self.roads[(26,32)]+"")
print(" "*10+self.roads[(21,27)]+" "+self.hexes[7].robberFormat()+" "+self.roads[(22,28)]+" "+self.hexes[8].robberFormat()+" "+self.roads[(23,29)]+" "+self.hexes[9].robberFormat()+" "+self.roads[(24,30)]+" "+self.hexes[10].robberFormat()+" "+self.roads[(25,31)]+" "+self.hexes[11].robberFormat()+" "+self.roads[(26,32)])
print(" "*8+self.formatVertex(27)+" "+self.formatVertex(28)+" "+self.formatVertex(29)+" "+self.formatVertex(30)+" "+self.formatVertex(31)+" "+self.formatVertex(32))
print(" "*10+" "+self.roads[(27,33)]+" "+self.roads[(28,33)]+" "+self.roads[(28,34)]+" "+self.roads[(29,34)]+" "+self.roads[(29,35)]+" "+self.roads[(30,35)]+" "+self.roads[(30,36)]+" "+self.roads[(31,36)]+" "+self.roads[(31,37)]+" "+self.roads[(32,37)])
print(" "*10+" "+self.roads[(27,33)]+" "+self.roads[(28,33)]+" "+self.roads[(28,34)]+" "+self.roads[(29,34)]+" "+self.roads[(29,35)]+" "+self.roads[(30,35)]+" "+self.roads[(30,36)]+" "+self.roads[(31,36)]+" "+self.roads[(31,37)]+" "+self.roads[(32,37)])
print(" "*10+" "+self.roads[(27,33)]+" "+self.roads[(28,33)]+" "+self.roads[(28,34)]+" "+self.roads[(29,34)]+" "+self.roads[(29,35)]+" "+self.roads[(30,35)]+" "+self.roads[(30,36)]+" "+self.roads[(31,36)]+" "+self.roads[(31,37)]+" "+self.roads[(32,37)])
print(" "*10+" "+self.roads[(27,33)]+" "+self.roads[(28,33)]+" "+self.roads[(28,34)]+" "+self.roads[(29,34)]+" "+self.roads[(29,35)]+" "+self.roads[(30,35)]+" "+self.roads[(30,36)]+" "+self.roads[(31,36)]+" "+self.roads[(31,37)]+" "+self.roads[(32,37)])
print(" "*10+" "+self.formatVertex(33)+" "+self.formatVertex(34)+" "+self.formatVertex(35)+" "+self.formatVertex(36)+" "+self.formatVertex(37))
print(" "*10+" "+self.roads[(33,38)]+self.formatHex(self.hexes[12].resourceType)+self.roads[(34,39)]+self.formatHex(self.hexes[13].resourceType)+self.roads[(35,40)]+self.formatHex(self.hexes[14].resourceType)+self.roads[(36,41)]+self.formatHex(self.hexes[15].resourceType)+self.roads[(37,42)])
print(" "*10+" "+self.roads[(33,38)]+self.formatHex(self.hexes[12].number)+self.roads[(34,39)]+self.formatHex(self.hexes[13].number)+self.roads[(35,40)]+self.formatHex(self.hexes[14].number)+self.roads[(36,41)]+self.formatHex(self.hexes[15].number)+self.roads[(37,42)])
print(" "*10+" "+self.roads[(33,38)]+" "+self.hexes[12].robberFormat()+" "+self.roads[(34,39)]+" "+self.hexes[13].robberFormat()+" "+self.roads[(35,40)]+" "+self.hexes[14].robberFormat()+" "+self.roads[(36,41)]+" "+self.hexes[15].robberFormat()+" "+self.roads[(37,42)]+" Ore")
print(" "*10+" "+self.formatVertex(38)+" "+self.formatVertex(39)+" "+self.formatVertex(40)+" "+self.formatVertex(41)+" "+self.formatVertex(42)+" @37,42")
print(" "*10+" "+self.roads[(38,43)]+" "+self.roads[(39,43)]+" "+self.roads[(39,44)]+" "+self.roads[(40,44)]+" "+self.roads[(40,45)]+" "+self.roads[(41,45)]+" "+self.roads[(41,46)]+" "+self.roads[(42,46)])
print(" "*10+" "+self.roads[(38,43)]+" "+self.roads[(39,43)]+" "+self.roads[(39,44)]+" "+self.roads[(40,44)]+" "+self.roads[(40,45)]+" "+self.roads[(41,45)]+" "+self.roads[(41,46)]+" "+self.roads[(42,46)])
print(" "*10+" "+self.roads[(38,43)]+" "+self.roads[(39,43)]+" "+self.roads[(39,44)]+" "+self.roads[(40,44)]+" "+self.roads[(40,45)]+" "+self.roads[(41,45)]+" "+self.roads[(41,46)]+" "+self.roads[(42,46)])
print(" "*10+" "+self.roads[(38,43)]+" "+self.roads[(39,43)]+" "+self.roads[(39,44)]+" "+self.roads[(40,44)]+" "+self.roads[(40,45)]+" "+self.roads[(41,45)]+" "+self.roads[(41,46)]+" "+self.roads[(42,46)])
print(" "*10+" Wildcard "+self.formatVertex(43)+" "+self.formatVertex(44)+" "+self.formatVertex(45)+" "+self.formatVertex(46))
print(" "*10+" @38,43 "+self.roads[(43,47)]+self.formatHex(self.hexes[16].resourceType)+self.roads[(44,48)]+self.formatHex(self.hexes[17].resourceType)+ self.roads[(45,49)]+self.formatHex(self.hexes[18].resourceType)+ self.roads[(46,50)])
print(" "*10+" "+self.roads[(43,47)]+self.formatHex(self.hexes[16].number)+ self.roads[(44,48)]+self.formatHex(self.hexes[17].number)+ self.roads[(45,49)]+self.formatHex(self.hexes[18].number)+ self.roads[(46,50)])
print(" "*10+" "+self.roads[(43,47)]+" "+self.hexes[16].robberFormat()+" "+self.roads[(44,48)]+" "+self.hexes[17].robberFormat()+" "+self.roads[(45,49)]+" "+self.hexes[18].robberFormat()+" "+self.roads[(46,50)])
print(" "*10+" "+self.formatVertex(47)+" "+self.formatVertex(48)+" "+self.formatVertex(49)+" "+self.formatVertex(50))
print(" "*10+" "+self.roads[(47,51)]+" "+self.roads[(48,51)]+" "+self.roads[(48,52)]+" "+self.roads[(49,52)]+" "+self.roads[(49,53)]+" "+self.roads[(50,53)])
print(" "*10+" "+self.roads[(47,51)]+" "+self.roads[(48,51)]+" "+self.roads[(48,52)]+" "+self.roads[(49,52)]+" "+self.roads[(49,53)]+" "+self.roads[(50,53)])
print(" "*10+" "+self.roads[(47,51)]+" "+self.roads[(48,51)]+" "+self.roads[(48,52)]+" "+self.roads[(49,52)]+" "+self.roads[(49,53)]+" "+self.roads[(50,53)])
print(" "*10+" "+self.roads[(47,51)]+" "+self.roads[(48,51)]+" "+self.roads[(48,52)]+" "+self.roads[(49,52)]+" "+self.roads[(49,53)]+" "+self.roads[(50,53)]+" Wildcard")
print(" "*10+" "+self.formatVertex(51)+" Sheep "+self.formatVertex(52)+" "+self.formatVertex(53)+" @50,53")
print(" "*10+" @48,52 ")
|
59d35a09fe084cabba6da579babeaabded3b71b8 | beaukinstler/ud036_StarterCode | /entertainment_center.py | 3,062 | 3.625 | 4 | import media
import fresh_tomatoes
# wrapping the job of making a list of movies into a function.
# this function statically builds an array of movies, and returns them.
def make_list_of_movies():
''' this function statically builds Movies() objects,
and returns an array of the Movie() objects '''
avatar = media.Movie(
"Avatar",
"Like Minecraft and Alien combined",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_UX182_CR0,0,182,268_AL_.jpg", # NOQA
"https://www.youtube.com/watch?v=5PSNL1qE6VY")
suburbicon = media.Movie(
"Suburbicon",
"A home invasion rattles a quiet family town.",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTA3MjA1NDkxMTReQTJeQWpwZ15BbWU4MDU2Njg3NDMy._V1_UX182_CR0,0,182,268_AL_.jpg", # NOQA
"https://www.youtube.com/watch?v=HegUiva5JzA")
all_i_see_is_you = media.Movie(
"All I See is You",
"""A blind woman's relationship with her
husband changes when she regains her sight and discovers
disturbing details about themselves.""",
"https://images-na.ssl-images-amazon.com/images/M/MV5BNDI5NzU2OTM1MV5BMl5BanBnXkFtZTgwNzU3NzM3MzI@._V1_UX182_CR0,0,182,268_AL_.jpg", # NOQA
"https://www.youtube.com/watch?v=zTTaFg2Sq9Y")
toy_story = media.Movie(
"Toy Story",
"A boy's toys are alive, and secretly watching him.",
"https://upload.wikimedia.org/wikipedia/en/thumb/1/13/Toy_Story.jpg/220px-Toy_Story.jpg", # NOQA
"https://www.youtube.com/watch?v=KYz2wyBy3kc")
crooklyn = media.Movie(
"Crooklyn",
"""Make yourself at home with the Carmichael family as they experience
one very special summer in their Brooklyn neighborhood that
they've affectionately nicknamed 'Crooklyn'.""",
"https://images-na.ssl-images-amazon.com/images/M/MV5BYWEyM2Q3NDktM2E2Ni00OWIyLWIyYmItMWEyOGRmN2FkZjQ3XkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_UX182_CR0,0,182,268_AL_.jpg", # NOQA
"http://www.youtube.com/watch?v=M4ivoM-19yA")
o_brother = media.Movie(
"O Brother, Where Art Thou",
"""In the deep south during the 1930s, three escaped convicts
search for hidden treasure while a relentless lawman pursues them.""",
"https://images-na.ssl-images-amazon.com/images/M/MV5BYmFhNjMwM2EtNGViMy00MTZmLWIzNTYtYzg1NWYwNTE2MGJhXkEyXkFqcGdeQXVyNTI4MjkwNjA@._V1_UX182_CR0,0,182,268_AL_.jpg", # NOQA
"https://www.youtube.com/watch?v=eW9Xo2HtlJI")
return [crooklyn,
o_brother,
avatar,
suburbicon,
all_i_see_is_you,
toy_story]
def main():
'''Main program to run automatically when this module is called directly'''
movies_list = make_list_of_movies()
for movie in movies_list: # print summary to terminal
print(movie.getmoviesummaries(movie))
fresh_tomatoes.open_movies_page(movies_list) # call the web page builder
if __name__ == '__main__':
main()
|
f63e464ce7382566584dd5001f4eb118aa54d20a | Dimitris-Mourtzilas/Plotting-Real-Time-Data | /source_code/main.py | 1,498 | 3.609375 | 4 |
"""
This is program is designed to provide real-time generated data printed
into a csv file.
Further features will include operations on a json file.
"""
from time import *
from random import randint
import csv
class File:
_csv_reader = None
_csv_writer = None
_count = 0
_file = None
def __init__(self):
pass
def openFile(self,filename):
if filename.__eq__("") or not(filename.__contains__(".csv")):
print("File is either empty or not .csv")
exit(1)
self._file= open(filename,"w+")
def readFile(self):
if self._file is None:
print("The file is empty")
return
self.csv_reader = csv.reader(self._file,delimiter=',')
for value in self.csv_file:
print(f"Data:\n{value}")
def writeFile(self,el):
if self._file is None:
print("File either corrupted or empty")
return
self._csv_writer=csv.writer(self._file,delimiter=',')
self._csv_writer.writerow(str(el))
def closeFile(self):
self._file.close()
if __name__ == "__main__":
filename = input("Give the name of the file")
new_csv_file = File()
new_csv_file.openFile(filename)
size = randint(0,100)
size_count =0
while size_count < size:
num= randint(0,100)
print(f"Wrinting {num} to file\n")
sleep(0.35)
new_csv_file.writeFile(num)
size_count+=1
new_csv_file.closeFile()
|
6033f2105199302bec02fae2146999394e3d8194 | AprajitaChhawi/365DaysOfCode.APRIL | /Day 6 possible words from phone.py | 959 | 3.640625 | 4 | #User function Template for python3
class Solution:
def pos(self,a,lst,dit,string,index,N):
if(len(string)==N):
lst.append(string)
return
cur = dit[a[index]]
for i in range(len(cur)):
self.pos(a,lst,dit,string+cur[i],index+1,N)
def possibleWords(self,a,N):
lst = []
dit = {2:"abc",3:"def",4:"ghi",5:"jkl",6:"mno",7:"pqrs",8:"tuv",9:"wxyz"}
self.pos(a,lst,dit,"",0,N)
return lst
##Your code here
#{
# Driver Code Starts
#Initial Template for Python 3
import math
def main():
T=int(input())
while(T>0):
N=int(input())
a=[int(x) for x in input().strip().split()]
ob = Solution()
res = ob.possibleWords(a,N)
for i in range (len (res)):
print (res[i], end = " ")
print()
T-=1
if __name__=="__main__":
main()
# } Driver Code Ends
|
257338117c3623320284083a0a9f640da89d6701 | AprajitaChhawi/365DaysOfCode.APRIL | /Day 7 check if two arrays are equal.py | 969 | 3.890625 | 4 | #User function Template for python3
class Solution:
#Function to check if two arrays are equal or not.
def check(self,A,B,N):
d={}
for i in A:
if i in d:
d[i]=d[i]+1
else:
d[i]=1
for i in B:
if i not in d or d[i]<=0:
return False
else:
d[i]=d[i]-1
return True
#return: True or False
#code here
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__=='__main__':
t=int(input())
for tc in range(t):
N=int(input())
A = [int(x) for x in input().replace(' ',' ').strip().split(' ')]
B = [int(x) for x in input().replace(' ',' ').strip().split(' ')]
ob=Solution()
if ob.check(A,B,N):
print(1)
else:
print(0)
# } Driver Code Ends
|
3e8feecdd8c816820a4f663ad9e96eea068475f5 | vincentei/tic-tac-toe | /test.py | 750 | 3.5 | 4 | import unittest
from board import Board
import numpy as np
class TestBoard(unittest.TestCase):
def test_create(self):
b = Board()
equal_elements = np.sum(b.data == np.ones((3,3))*-1)
self.assertEqual(equal_elements,9)
def test_set_piece(self):
b = Board()
b.set_piece(1,0,0)
result = np.array([[1,-1,-1],[-1,-1,-1],[-1,-1,-1]])
print(b.data)
equal_elements = np.sum(b.data == result)
self.assertEqual(equal_elements,9)
def test_has_won(self):
b = Board()
b.set_piece(1,0,0)
b.set_piece(1,1,1)
b.set_piece(1,2,2)
self.assertEqual(b.has_won(1),True)
if __name__ == '__main__':
unittest.main() |
2ddad7e073dc0e129cb4da58f53b0a385835dfce | izzyevermore/python-built-in-funcs | /main.py | 562 | 3.8125 | 4 | # Exercise 1
# Grades
# Task: Filter the grades to only display everyone above (and including) 70%
grades = [20,10,90,85,40,75,65,64,12,74,71,98,50]
grades = list(filter(lambda x : x >= 70, grades))
print(grades)
# Exercise 2
# Dog ages
# Convert ages into dog years
dog_ages = [12,8,4,1,2,6,4,4,5]
dog_ages = list(map(lambda x : x * 7, dog_ages))
print(dog_ages)
# Exercise 3
# Transactions
# Convert transactions to a single total
transactions = [51.0,49.99,80.99,67.99,120.52,23.49]
transactions = [round(x) for x in transactions]
print(transactions)
|
26e46d71cbcbf9285f893f2c759c9e3bd9732687 | NavairaRosheen/Task1 | /task1Q6.py | 130 | 3.8125 | 4 | list=[1,2,5,-1,6,0,15]
smallest=min(list)
mini=list[0]
for i in list:
if (i<mini) and (i>smallest):
mini=i
print(mini) |
6b5bde2df0f5bded9656f46e222184df9ebb65da | nhpss921111/Leap-year | /function1.py | 1,143 | 4 | 4 | # -------------題目---------------
"""
寫一個function來判斷是不是閏年(二月會多一天的年)
依照 Wikipedia 的定義
1.公元年分除以4不可整除,為平年
2.公元年分除以4可整除但除以100不可整除,為潤年
3.公元年分除以100可整除但除以400不可整除,為平年
4.公元年分除以400可整除但除以3200不可整除,為潤年
同學可以依照這個定義直接翻譯成程式碼。
function 應該要有一個參數值讓使用者投入(傳遞進去)年分
function 的回傳直(return)應該是布林值,如果是閏年就return True,不就是return False。
請把function 取名為 is_sleep ,這樣才可以執行測試。
(P.S. is_sleep就是"是不是閏年"的意思,所以function要取的名副其實)
提示:要用到 % 這個符號 "來求餘數"
"""
# ------------------------------
def is_leap(year):
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
elif year % 400 != 0:
return False
else:
return True
y = input('請輸入年份: ')
y = int(y)
print(is_leap(y))
|
ae90634d89b2add6ed79b04c1675465761be5095 | shakib0/BasicPattterns | /pattern7.py | 229 | 3.703125 | 4 | for r in range(5):
for c in range(r+2):
if c<1 :
print((5-r)*' ',r,end = '')
elif c>1:
print('',r,end = '')
while c==2:
c=0
print()
|
622dfa7610474aac2aa08ca4199e324c5a9bd52a | DS-ALGO-S30/PreCourse_2 | /Exercise_5.py | 1,136 | 4.0625 | 4 | import numpy.random as random
# Python program for implementation of Quicksort
# This function is same in both iterative and recursive
def partition(arr, l, h):
#write your code here
ptr=l
pivot=h
for i in range(l,h):
if arr[i]<arr[pivot]:
arr[i], arr[ptr] = arr[ptr],arr[i] # swap
ptr += 1
arr[ptr] , arr[pivot] = arr[pivot], arr[ptr]
return ptr
def quickSortIterative(arr, l, h):
#write your code here
stack=[l,h]
while True:
print(stack)
if len(stack) == 0:
break
if (stack[-1]-stack[-2]) > 1:
print(arr)
p=partition(arr,stack[-2],stack[-1])
# pop last two and insert l, p-1, p+1,h
h=stack.pop(-1)
l=stack.pop(-1)
stack.append(l)
stack.append(p-1)
stack.append(p+1)
stack.append(h)
else:
stack.pop(-1)
stack.pop(-1)
arr = [1,1,4,4,6,21,5,7, 8,21, 9, 1,6,5,56,32,21,86,88]
n = len(arr)
quickSortIterative(arr,0,n-1)
print ("Sorted array is:")
for i in range(n):
print ("%d" %arr[i])
|
b19a065468ccc7e6db220140e95ff67d8d4bfc9a | Hyun-delv/python-algorithm | /Palindrome.py | 614 | 3.578125 | 4 | from collections import deque
def Palimdrome(s: str) ->bool:
# 리스트 방법을 통해서 풀이
"""
strs = []
for char in s :
if char.isalnum():
strs.append(char.lower())
while len(strs)>1:
if strs.pop(0) != strs.pop():
return False
return True
"""
# deque 방법을 통해서 풀이
strs =deque()
for char in s :
if char.isalnum():
strs.append(char.lower())
while len(strs) >1:
if strs.popleft() != strs.pop():
return False
return True
|
d6bdfd11a791ecdd06062e77a0791eda95f242af | seedor87/pyTexed | /inertion_sort.py | 1,135 | 3.734375 | 4 | from random import randint, uniform
def insertion_sort(list):
ret = list
for j in range(1, len(ret)):
key = ret[j]
i = j
while(i > 0) and ret[i-1] > key:
ret[i] = ret[i-1]
i = i-1
ret[i] = key
return ret
L_than = lambda A, B: A < B
G_than = lambda A, B: A > B
E_to = lambda A, B: A == B or A is B
G_E_to = lambda A, B: G_than(A, B) or E_to(A, B)
L_E_to = lambda A, B: L_than(A, B) or E_to(A, B)
def if_in_order(list, rule=G_E_to):
ret = list
if len(ret) <= 1:
return True
if rule(ret[-1], ret[-2]):
del ret[-1]
return if_in_order(ret)
return False
A=[randint(0,9) for p in range(0,9)]
print insertion_sort(A), if_in_order(A)
B = [uniform(0.0,9.0) for f in range(0,20)]
print insertion_sort(B), if_in_order(B)
C, D, E = [3, 4], [], [500]
print if_in_order(C), if_in_order(D), if_in_order(E)
print ""
F, G = [3, 4], [3, 4]
print if_in_order(F, G_than), if_in_order(G, L_than)
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4]) # toy for interpretation
print ""
print [ordinal(n) for n in F] |
eda2bd25cd6719192df085fc58d82a5330e3a130 | eyangs/transferNILM | /appliance_data.py | 1,432 | 3.515625 | 4 | """ A collection of all appliances available. Each appliance has a consumption mean
and standard deviation, as well as a list of houses containing the appliance. """
appliance_data = {
"kettle": {
"mean": 700,
"std": 1000,
"houses": [2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 19, 20],
"channels": [8, 9, 9, 8, 7, 9, 9, 7, 6, 9, 5, 9],
"test_house": 2,
"validation_house": 5,
},
"fridge": {
"mean": 200,
"std": 400,
"houses": [2, 5, 9, 12, 15],
"channels": [1, 1, 1, 1, 1],
"test_house": 15,
"validation_house": 12
},
"dishwasher": {
"mean": 700,
"std": 1000,
"houses": [5, 7, 9, 13, 16, 18, 20],
"channels": [4, 6, 4, 4, 6, 6, 5],
"test_house": 9,
"validation_house": 18,
},
"washingmachine": {
"mean": 400,
"std": 700,
"houses": [2, 5, 7, 8, 9, 15, 16, 17, 18],
"channels": [2, 3, 5, 4, 3, 3, 5, 4, 5],
"test_house": 8,
"validation_house": 18,
},
"microwave": {
"mean": 500,
"std": 800,
"houses": [4, 10, 12, 17, 19],
"channels": [8, 8, 3, 7, 4],
"test_house": 4,
"validation_house": 17,
},
}
# The std and mean values for normalising the mains data which are used
# as input to the networks
mains_data = {
"mean": 522,
"std": 814
} |
9a3adac0205258627a994d52259dd5e27dda1051 | eyangs/transferNILM | /remove_space.py | 129 | 3.578125 | 4 | # Removes the spaces from a string. Used for parsing terminal inputs.
def remove_space(string):
return string.replace(" ","") |
dc990e6ecd447a0d729461d3910522b11295b211 | Roshan-Ojha/Agro-Hub | /Answer.py | 355 | 3.609375 | 4 | import sqlite3
conn=sqlite3.connect('answer.db')
c=conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS answer (
asked_on text,
answered_on text,
answer text,
photo text,
answerd_by text,
answer_by_email text
)""")
conn.commit()
conn.close() |
14ee4e61bdd207607f67e78ce181252c2e24b03d | VladErm-Data/python | /dz_6.py | 6,861 | 3.53125 | 4 | # 1. Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод running (запуск).
# Атрибут реализовать как приватный. В рамках метода реализовать переключение светофора в режимы: красный, желтый,
# зеленый.
# Доп условие я не понял, поэтому не сделал.
from itertools import islice, cycle
import time
TRAFFIC_COLORS = {'Красный': 7, 'Желтый': 2, 'Зеленый': 3}
class TrafficLight:
def __init__(self, color):
self.__color = islice(cycle(TRAFFIC_COLORS.keys()), list(TRAFFIC_COLORS.keys()).index(color), None)
def running(self, block):
for index, color in enumerate(self.__color):
if index == block:
break
print(color)
time.sleep(TRAFFIC_COLORS[color])
my_traffic = TrafficLight('Желтый')
my_traffic.running(7)
# 2. Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина).
class Road:
def __init__(self, length, width):
self._length = length
self._width = width
def asphalt_mass(self, mass, dense):
print(self._width*self._length*mass*dense)
my_road = Road(5000, 20)
my_road.asphalt_mass(25, 5)
# 3. Реализовать базовый класс Worker (работник), в котором определить атрибуты: name, surname, position (должность),
# income (доход). Последний атрибут должен быть защищенным и ссылаться на словарь, содержащий элементы: оклад и премия,
# например, {"wage": wage, "bonus": bonus}. Создать класс Position (должность) на базе класса Worker. В классе Position
# реализовать методы получения полного имени сотрудника (get_full_name) и дохода с учетом премии (get_total_income).
class Worker:
def __init__(self, name, surname, position, wage, bonus):
self.name = name
self.surname = surname
self.position = position
self._income = {'wage': wage, 'bonus': bonus}
class Position(Worker):
def __init__(self, name, surname, position, wage, bonus):
super().__init__(name, surname, position, wage, bonus)
def get_full_name(self):
return self.surname + ' ' + self.name
def get_total_income(self):
return self._income["wage"] + self._income["bonus"]
ex_1 = Position('Евкакий', 'Самородный', 'Гендир', 10, 5)
print(ex_1.position)
print(ex_1.get_full_name())
print(ex_1.get_total_income())
# 4. Реализуйте базовый класс Car. У данного класса должны быть следующие атрибуты: speed, color, name, is_police
# (булево). А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась,
# повернула (куда). Опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar. Добавьте в базовый
# класс метод show_speed, который должен показывать текущую скорость автомобиля. Для классов TownCar и WorkCar
# переопределите метод show_speed. При значении скорости свыше 60 (TownCar) и 40 (WorkCar) должно выводиться
# сообщение о превышении скорости.
class Car:
def __init__(self, speed, color, name, is_police):
self.speed = speed
self.color = color
self.name = name
self.is_police = is_police
def show_speed(self):
return f'текущая скорость: {self.speed}'
@staticmethod
def go():
return 'Она поехала'
@staticmethod
def stop():
return 'Она остановилась'
@staticmethod
def turn(direction):
return f'мы повернули на{direction}'
class TownCar(Car):
def __init__(self, speed, color, name, is_police):
super().__init__(speed, color, name, is_police)
def show_speed(self):
if self.speed < 60:
return f'текущая скорость: {self.speed}'
else:
return f'превышение скорости! Скорость: {self.speed}'
class SportCar(Car):
def __init__(self, speed, color, name, is_police):
super().__init__(speed, color, name, is_police)
class WorkCar(Car):
def __init__(self, speed, color, name, is_police):
super().__init__(speed, color, name, is_police)
def show_speed(self):
if self.speed < 40:
return f'текущая скорость: {self.speed}'
else:
return f'превышение скорости! Скорость: {self.speed}'
class PoliceCar(Car):
def __init__(self, speed, color, name, is_police):
super().__init__(speed, color, name, is_police)
car_1 = WorkCar(70, 'Blue', 'Toyota', False)
car_2 = SportCar(100, 'Black', 'Bugatti', False)
car_3 = PoliceCar(80, 'Brown', 'Kopeyka', True)
car_4 = TownCar(50, 'White', 'Ford', False)
print(car_1.show_speed())
print(car_2.show_speed())
print(car_3.show_speed())
print(car_4.show_speed())
print(car_3.name)
# 5. Реализовать класс Stationery (канцелярская принадлежность). Определить в нем атрибут title (название) и метод draw
# (отрисовка). Метод выводит сообщение “Запуск отрисовки.” Создать три дочерних класса Pen (ручка), Pencil (карандаш),
# Handle (маркер). В каждом из классов реализовать переопределение метода draw.
class Stationery:
def __init__(self, title):
self.title = title
@staticmethod
def draw():
print('Запуск отрисовки')
class Pen(Stationery):
@staticmethod
def draw():
print('Рисуем ручкой')
class Pencil(Stationery):
@staticmethod
def draw():
return print('Рисуем карандашом')
class Handle(Stationery):
@staticmethod
def draw():
return print('Рисуем маркером')
ex_1 = Pen('Ручка')
print(ex_1.title)
ex_1.draw()
ex_2 = Pencil('Карандаш')
print(ex_2.title)
ex_2.draw()
|
f8327a56682bd0b9e4057defb9b016fd0b56afdd | karagdon/pypy | /48.py | 671 | 4.1875 | 4 | # lexicon = allwoed owrds list
stuff = raw_input('> ')
words = stuff.split()
print "A TUPLE IS SIMPLY A LIST YOU CANT MODIFY"
# lexicon tuples
first_word = ('verb', 'go')
second_word = ('direction', 'north')
third_word = ('direction', 'west')
sentence = [first_word, second_word, third_word]
def convert_numbers(s):
try:
return int(s):
except ValueError:
return None
print """
Create one small part of the test I give you \n
Make sure it runs and fails so you know a test is actually confirming a feature works. \n
Go to your source file lexicon.py and write the code that makes this test pass \n
Repeat until you have implemented everything in the test
"""
|
80a5137b9ab2d2ec77805ef71c2513d8fcdf81a0 | karagdon/pypy | /Python_codeAcademy/binary_rep.py | 1,384 | 4.625 | 5 | #bitwise represention
#Base 2:
print bin(1)
#base8
print hex(7)
#base 16
print oct(11)
#BITWISE OPERATORS#
# AND FUNCTION, A&B
# 0b1110
# 0b0101
# 0b0100
print "AND FUNCTION, A&B"
print "======================\n"
print "bin(0b1110 & 0b101)"
print "= ",bin(0b1110&0b101)
# THIS OR THAT, A|B
#The bitwise OR (|) operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if either of the corresponding bits of either number are 1.
# 0b1110
# 0b0101
# ======
# 0b1111
print "OR FUNCTION, A|B"
print "======================\n"
print "bin(0b1110|0b0101)"
print "= ",bin(0b1110|0b0101)
# XOR FUNCTION, A^B
#XOR (^) or exclusive or operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if either of the corresponding bits of the two numbers are 1, but not both.
# 1 1 1 0
# 0 1 0 1
# = = = =
# 1 0 1 1 thus 0b1011 should appear
print "XOR FUNCTION"
print "======================\n"
print "bin(0b1110 ^ 0b101)"
print "=", bin(0b1110 ^ 0b101)
# XOR FUNCTION, ~A
#The bitwise NOT operator (~) just flips all of the bits in a single number.This is equivalent to adding one to the number and then making it negative.
print "NOT FUNCTION, ~A"
print "======================\n"
print "~1 =", ~1
print "~2 =", ~2
print "~3 =", ~3
print "~42 =", ~42
print "~123 =", ~123
|
729099b198e045ce3cfe0904f325b62ce3e3dc5e | karagdon/pypy | /diveintopython/707.py | 579 | 4.28125 | 4 | ### Regex Summary
# ^ matches
# $ matches the end of a string
# \b matches a word boundary
# \d matches any numeric digit
# \D matches any non-numeric character
# x? matches an optional x character (in other words, it matches an x zero or one times)
# x* matches x zero or more times
# x+ matches x one or more times
# x{n,m} matches an x character atleast n times, but not more than m times
# (a|b|c) matches either a or b or c
# (x) in general is a remembered group. You can get the value of what matched by using the groups() method of the object returned by re.search
|
25aec7ea0f73f0bf5fee4c5d8905f7d0561bb043 | karagdon/pypy | /learnpythonthw/34.py | 491 | 3.921875 | 4 | animals = ['bear', 'tiger', 'penguin', 'zebra','cat','dog']
bear = animals[0]
print animals
print "............"
print "The animal at 1 is %s" % animals[1]
print "The third (3rd) animal. is %s" % animals[2]
print "The first (1st) animal. is %s" % animals[0]
print "The animal at 3. is %s" % animals[3]
print "The fifth (5th) animal. is %s" % animals[4]
print "The animal at 2. is %s" % animals[2]
print "The sixth (6th) animal. is %s" % animals[5]
print "The animal at 4. is %s" % animals[4] |
d865c2adf4c6c528500b3faa8a879c9fbf501303 | mfarukoz/HackerRank | /starcase-.py | 400 | 4.03125 | 4 | def staircase():
n = int(input())
# n icin veri girisi
if 0 < n <= 100:
# n ,0 ile 100 arasında ise
for i in range(1, n):
# 1 den n'e kadar dongu
print(('#' * i).rjust(n))
# n uzunlugunda satıra saga hizalı yıldız yazdırma
print(('#' * n).rjust(n), end='')
# alt satıra gecisi engellemek icin son satır end='' ile ayrı yazdırılıdı
staircase()
|
a8e3061f27de656ee077ebb6f3c43a86ef16dde2 | TIEmerald/UNDaniel_Python_Library | /csv_reader/read_value_from_csv.py | 1,738 | 3.609375 | 4 | # -*- coding:utf-8 -*-
import csv
import os
import sys
import inspect
import getopt
def read_key_value_pair_from_csv(file, key, value):
values = None
if value is not None:
values = [value]
results = []
with open(file, mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
if values is None:
values = list(row.keys())
values.remove(key)
results.append(row)
if values is not None:
for value in values:
print(f'\n Generating Key-Value pair: \"{key}\" = \"{value}\" ------- Start *************')
for result in results:
print(f'\"{result[key]}\" = \"{result[value]}\"')
print(f'Generating Key-Value pair: \"{key}\" = \"{value}\" ------- End ************* \n')
def main(argv):
searchingFile = None
key = None
value = None
formattedDes = 'read_value_from_csv.py -f <file-name> -k <key> -v <values>'
try:
opts, args = getopt.getopt(argv,"f:k:v:",["file-name=","key=","values=","value="])
except getopt.GetoptError:
print(formattedDes)
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print(formattedDes)
sys.exit()
elif opt in ("-f", "--file-name"):
searchingFile = arg
elif opt in ("-k", "--key"):
key = arg
elif opt in ("-v", "--values", "--value"):
value = arg
if key is None:
print(formattedDes + ', Please provide the key in csv')
sys.exit(2)
read_key_value_pair_from_csv(searchingFile, key, value)
if __name__ == '__main__':
main(sys.argv[1:])
|
ba16b62a2d46ec2373bc85d8d1e33852ed2861ca | davsvijayakumar/python-programming | /player/first game creation.py | 521 | 3.984375 | 4 | while (1):
import random
arr=['p','s','sc']
c=random.choice(arr)
v=str(input("enter the your choice form -- s, sc, p:"))
b=str(v)
n=str(c)
print(b)
print(n)
if(c==v):
print("match draw")
elif(b=="s" and n=="sc"):
print("vijay is win")
elif(b=="s" and n=="p"):
print("computer is win")
elif(b=="p" and n=="s"):
print("vijay is win")
elif(b=="p" and n=="sc"):
print("computer is win")
elif(b=="sc" and n=="p"):
print("vijay is win")
elif(b=="sc" and n=="s"):
print("computer is win")
|
963d100dfd5d65c50a092b0d6a6784402f760515 | reggieag/Spotify-Puzzles | /reversedbinary/reversedbinary.py | 121 | 3.6875 | 4 | def reverseBinary(x):
x = bin(x)
return int(x[:2]+x[2:][::-1], 2)
a = raw_input()
a = int(a)
print reverseBinary(a)
|
bd00c3566cf764ca82bba1a4af1090581a84d50f | f1uk3r/Daily-Programmer | /Problem-3/dp3-caeser-cipher.py | 715 | 4.1875 | 4 | def translateMessage(do, message, key):
if do == "d":
key = -key
transMessage = ""
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord("Z"):
num -= 26
elif num < ord("A"):
num += 26
if symbol.islower():
if num > ord("z"):
num -= 26
elif num < ord("a"):
num += 26
transMessage += chr(num)
else:
transMessage += symbol
return transMessage
do = input("Do you want to (e)ncrypt or (d)ecrypt? ")
message = input("Type your message : ")
key = int(input("Enter a key number between -26 and 26: "))
translated = translateMessage(do, message, key)
print("Your translated message is : " + translated)
|
e2b0a7d7bc76ef3739eace98f62081e78df24b67 | f1uk3r/Daily-Programmer | /Problem-11/Easy/tell-day-from-date.py | 540 | 4.5 | 4 | # python 3
# tell-day-from-date.py #give arguments for date returns day of week
# The program should take three arguments. The first will be a day,
# the second will be month, and the third will be year. Then,
# your program should compute the day of the week that date will fall on.
import datetime
import calendar
import sys
def get_day(day, month, year):
date = datetime.datetime(int(year), int(month), int(day))
print(calendar.day_name[date.weekday()])
if __name__ == '__main__':
get_day(sys.argv[1], sys.argv[2], sys.argv[3]) |
e849ae5643cfd27401834592cb4e5e2db8dd0339 | aryanxxvii/myAssistant | /my_calendar.py | 3,047 | 3.6875 | 4 | import reminder
import user_notes
import calendar
import datetime
import os
Help = """
Make your planning more efficient with the use of calendar.
You won't miss your favourite events like watching movies,
plan tours, mark birthdays, manage datewise to-do lists and
other benefits by using it in the best possible way.
"""
Msg = """
======================== Welcome to Calendar ============================
Were you ever confused what all things you need to do and you
are not able to focus? Did you ever forget some important events?
Have you experienced the power of proper planning? Have you ever
felt the need to plan things out?....
Reminder:
" A goal without a plan is just a wish. "
-- Antoine de Saint-Exupery
-------------------------------------------------------------------------
"""
def my_calendar_help(): # -----------------------------------------------
# tells the user about how to use the feature.
global Help
print(Help)
def display_calendar(year): # -------------------------------------------
# displays the calendar of a particular year using the calendar module.
x = calendar.calendar(year)
print(x)
def display_month(year, month): # ---------------------------------------
# display the calendar of a particular month of the year.
x = calendar.month(year, month)
print(x)
def start(uid): # --------------------------------------------------------
# the actual command implemented in the program
# the uid parameter is used to know which user is wanting to use the feature.
# the special thing is that the user is able to create to-do lists for a particular date.
global Msg
try:
os.system('cls'); print(Msg)
# input for the year
yys = input("Enter Year(YYYY):")
assert len(yys) == 4
yy = int(yys)
os.system('cls'); print(Msg)
display_calendar(yy)
# input for the month
mms = input("Enter Month number(MM):")
assert len(mms) == 2
mm = int(mms)
os.system('cls'); print(Msg)
display_month(yy, mm)
print("If you want to add notes for a particular date,")
print("or read the notes you have added for that day then")
print("you may enter the respective date and review the notes.")
print("Otherwise you may just press ENTER to ignore.")
print()
dd = input("Enter Date(DD):")
assert len(dd) == 2 and uid != 'Guest'
Date = dd + '-' + mms + '-' + yys # formatting the date structure for input parameter.
# sets the reminder to notify user that he/she has made plans for that day.
reminder.set_reminder(uid, "Calendar notification. Check calendar.", time = '06:00', date = Date)
# storing the to-do list plans in a text file.
user_notes.start_notes(uid, '\\'+Date, Msg)
except:
pass
|
c6cfa2227a88fc9e9a721ccfffac4b816bbb0039 | Atharva321/Python_GUI-tkinter- | /Submit3.py | 946 | 3.5625 | 4 | from tkinter import *from tkinter import messagebox
root = Tk()
def hl():
messagebox.showinfo("Do you want to conttinue","SUCCESS")
print("Name : ", text_var.get())
print("Branch : ", branch_var.get())
print("College : ", college_var.get())
root.title("Window")
root.geometry("350x250")
mylabel=Label(root,text="Name")
mylabel.grid(row=0,column=0)
mylabel1=Label(root,text="Branch")
mylabel1.grid(row=1,column=0)
mylabel2=Label(root,text="College")
mylabel2.grid(row=2,column=0)
text_var = StringVar()
txb=Entry(root, text = text_var, width=16)
txb.bind('<Return>',hl)
txb.grid(row=0,column=1)
branch_var = StringVar()
brnch=Entry(root, text = branch_var, width=16)
brnch.bind('<Return>',hl)
brnch.grid(row=1,column=1)
college_var = StringVar()
clg=Entry(root, text = college_var, width=16)
clg.bind('<Return>',hl)
clg.grid(row=2,column=1)
bt=Button(root,text="Submit",command=hl).grid(row=3,column=1)
root.mainloop()
|
25b11fa2a4a8d5b01b6c20a5edf8c506fc869f0d | kakalinath/Hackfest | /11th.py | 550 | 4 | 4 | #Fibo Simple
Limit = input("Enter Limits >> ")
try:
Limit = int(Limit)
n1,n2 = 0,1
count = 0
if Limit < 0 :
print("Fibonacci Series is 0 !")
elif Limit==1:
print("Fibonacci Series is :", n2)
else:
print("Fibonacci Series >> ")
while count < Limit:
print(n1)
next = n1 + n2
n1 = n2
n2 = next
count = count + 1
except:
print("Stop it and Start Again !")
|
b9bd13976ab7971faac6cee441b57255d928d7d9 | namho102/ml-recipes | /regr.py | 758 | 3.59375 | 4 |
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
N = 50
X = [[2], [3], [4], [7]]
y = [2, 4, 3, 10]
X_test = [[1], [10]]
X_test2 = [[5], [9]]
# y_test = [[6]]
# Create linear regression object
regr = linear_model.LinearRegression()
# Train the model using the training sets
regr.fit(X, y)
# The coefficients
print('Coefficients: \n', regr.coef_)
# The mean square error
# print("Residual sum of squares: %.2f"
# % np.mean((regr.predict(X_test) - y_test) ** 2))
print regr.predict(X_test)
plt.scatter(X, y, color='black')
plt.plot(X_test, regr.predict(X_test), color='blue', linewidth=3)
# plt.plot(X_test2, regr.predict(X_test2), color='yellow', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show() |
f7b95be5656ba3ef2d1eadd1169c919d4ad90676 | SeanHildreth/CodingDojo | /python_stack/python_fundamentals/for_loop_basic1.py | 561 | 3.546875 | 4 | for basic in range(151):
print("Number is ", basic)
fives = 5
for count in range(1000001):
print('Number is ', fives)
count += 5
for dojo in range(1,101):
... if dojo % 5 == 0 and dojo % 10 == 0:
... print('Coding Dojo')
... elif dojo % 5 == 0:
... print('Coding')
... else:
... print('Number is ', dojo)
sum = 0
for whoa in range(1, 500001, +2):
sum += whoa
if whoa == 499999:
print(sum)
for fours in range(2018,0,-4):
print(fours)
for flex in range(2,9,3):
print(flex+1) |
aa9169094c6b112f71a47c1487d80bb762c593d6 | SeanHildreth/CodingDojo | /python_stack/python_OOP/assignments/product.py | 1,366 | 3.640625 | 4 | class Product:
def __init__(self, price, name, weight, brand):
self.price = price
self.name = name
self.weight = weight
self.brand = brand
self.status = 'For Sale'
def sell(self):
self.status = 'Sold'
return self
def add_tax(self, tax):
total = self.price * tax + self.price
return total
def return_item(self, reason_for_return):
if reason_for_return == 'defective':
self.status = 'defective'
self.price = 0
elif reason_for_return == 'like new':
self.status = 'For Sale'
elif reason_for_return == 'opened':
self.status = 'used'
self.price *= .8
return self
def display_info(self):
print('*'*80)
print('Price: ', self.price)
print('Name: ', self.name)
print('Weight: ', self.weight)
print('Brand: ', self.brand)
print('Status: ', self.status)
return self
bicycle = Product(1000, 'HyRoad', '10lbs', 'Giant')
bicycle.display_info()
chain = Product(20, 'Bike Chain', '1lb', 'Giant')
chain.display_info()
sprocket = Product(50, 'Rear Sprocket', '5lb', 'Schwinn')
sprocket.display_info()
chain.price = 19.99
sprocket.brand = 'Bell'
bicycle.name = 'Off-roader'
chain.display_info()
sprocket.display_info()
bicycle.display_info() |
3668ddc967fedbc8d02c0ff1dcdabc98d8393488 | PitiasFessahaie/GAMER | /Banking.py | 1,429 | 3.953125 | 4 |
class Banking():
def __init__(self, balance=100):
self.balance = balance
print("\nWelcome to the ATM Deopsit and Withdrawal Machine!")
def machine(self):
data=self.usage()
if data == True:
self.deposit()
self.display()
else:
self.withdraw()
self.display()
def usage(self):
print('\nDo you want to Deposit (Press d) or Withdraw (Press w)??')
return input().lower().startswith('d')
def withdraw(self):
try:
amount = float(input("the amount you like withdraw: "))
if self.balance >= amount:
self.balance -= amount
print("\n The amount you withdrawed is " + str(amount))
else:
print("\n Insufficient fund!")
except ValueError:
print("Please Enter a Valied Number")
self.withdraw()
def deposit(self):
try:
amount = float(input("the amount you like to Deposit: "))
self.balance += amount
print ("\n The amount you Deposited is: " + str (amount))
except ValueError:
print("Please Enter a Valied Number")
self.deposit()
def display(self):
print("\n The amount balance is: ", self.balance)
if __name__ == "__main__":
g=Banking()
g.machine()
|
7ced3f8d1bd43326c0828d20a300a4cc3e58a11e | lanhaixuan/Data-Structure | /剑指offer/15.合并两个排序的链表.py | 1,253 | 3.859375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/12/6 10:18
# @Author : lanhaixuan
# @Email : jpf199727@gmail.com
# @File : 15 合并两个排序的链表.py
# @Software: PyCharm
'''
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
'''
'''
要注意特殊输入,如果输入是空链表,不能崩溃。
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回合并后列表
def Merge(self, p_head1, p_head2):
if p_head1 == None:
return p_head2
elif p_head2 == None:
return p_head1
p_merge_head = None
if p_head1.val < p_head2.val:
p_merge_head = p_head1
p_merge_head.next = self.Merge(p_head1.next, p_head2)
else:
p_merge_head = p_head2
p_merge_head.next = self.Merge(p_head1, p_head2.next)
return p_merge_head
node1 = ListNode(1)
node2 = ListNode(3)
node3 = ListNode(5)
node1.next = node2
node2.next = node3
node4 = ListNode(2)
node5 = ListNode(4)
node6 = ListNode(6)
node4.next = node5
node5.next = node6
test = Solution()
test.Merge(node1, node4)
print(node4.next.val)
|
edbc74972bc4193c0bdf0196182c5863ab168d44 | lanhaixuan/Data-Structure | /剑指offer/5.用两个栈实现队列.py | 1,109 | 3.890625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/12/2 8:53
# @Author : lanhaixuan
# @Email : jpf199727@gmail.com
# @File : 5 用两个栈实现队列.py
# @Software: PyCharm
'''
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
'''
'''
需要两个栈Stack1和Stack2,push的时候直接push进Stack1。
pop需要判断Stack1和Stack2中元素的情况,Stack1空的话,直接从Stack2 pop,Stack1不空的话,把Stack1的元素push进入Stack2,然后pop Stack2的值。
'''
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
self.stack1.append(node)
def pop(self):
if len(self.stack1) == 0 and len(self.stack2) == 0:
return None
elif len(self.stack2) == 0:
while len(self.stack1) > 0:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
test = Solution()
test.push(1)
test.push(2)
test.push(3)
print(test.pop())
test.push(4)
print(test.pop())
print(test.pop())
print(test.pop())
print(test.pop())
|
e944a493701484b85f0930ed5c5c716253ed6a9b | NosevichOleksandr/firstrepository | /srezy.py | 205 | 3.75 | 4 | print('hello world')
a = input('write your ... something: ')
if len(a) % 2 == 0:
b = a[:len(a)//2]
c = a[len(a)//2:][::-1]
print(b + c)
else:
print('ты неправильно ввел')
|
763884703173c3ed766a39097bb0fe42ab72ae19 | NosevichOleksandr/firstrepository | /18_10__20_11_20.py | 178 | 3.71875 | 4 | data = [1, 2, 3, [2, 3, '12'], [123], 22, [1, 2]]
answer = []
for i in data:
if isinstance(i,list):
answer.extend(i)
else:
answer.append(i)
print(answer)
|
2c7f663cce98480b163dbea34a34f09c4027dc21 | NosevichOleksandr/firstrepository | /hus;o.f.py | 536 | 3.78125 | 4 | def countpolindroms(a):
a += ' '
word_or_number = ''
answ = ''
for i in a:
if i != ' ':
word_or_number += i
elif i == ' ':
if word_or_number == word_or_number[::-1] and len(word_or_number) > 1:
answ += word_or_number + ' '
word_or_number = ''
else:
word_or_number = ''
return(answ)
print(countpolindroms('ablolbabc '))
|
46890d2654f4c0dcc68273311338af570ec4b7f5 | NiramBtw/leetcode_python_solutions | /26. Remove Duplicates from Sorted Array.py | 732 | 3.53125 | 4 | class Solution(object):
def removeDuplicates(self, nums):
"""
nums= [1,1,2,2,3,4]
create and index of all unique chars in the list
then remove all the rest
return the new index list we make
+ the len of them
"""
# first cond
if len(nums) == 0:
return 0
if len(nums) == 1:
return 1
j = 0 # index count
for i in range(1,len(nums)): # loop any element in nums
if nums[i] != nums[j]: # if number index i is diff the j
j += 1 # add 1 to the count
nums[j] = nums[i]
return j + 1 # because we start look from 0
|
c33e56b18a347e0055347e36894261e1f0bb7c38 | NiramBtw/leetcode_python_solutions | /1. Two Sum.py | 1,135 | 3.640625 | 4 | class Solution:
def twoSum(self,nums,target):
# by try give 1 num vs the target we can cheack if the num(we look)
# + the num we hold = traget
# nums = [2,7,11,15], target = 9
# try use a dict()
comp_map = dict()
for i in range(len(nums)):
num = nums[i] # 7?
comp = target - nums[i]# comp = 2
if num in comp_map: # here we r find the pair
return [comp_map[num], i]
else:
comp_map[comp] = i # {7,0}
"""
# he i use 2 for loops which make its run long time
def naive_twoSum(self, nums, target):
for i in range(len(nums)): # run all elements in nums
for j in range(i+1, len(nums)): # loop for the sec nums no run same elemet
#2 time i+1
sum = nums[i] + nums[j] #same as traget
if sum == target:
return [i,j]
"""
if __name__ == '__main__':
s = Solution()
print (s.twoSum([2,7,11,15], 9))
|
646b8ee4ffb125dfa1971e004ebb645a5a9447eb | siumingdev/course-exercises | /Data Structures and Algorithms, UCSD/1. Algorithmic Toolbox/week3_greedy_algorithms/2_maximum_value_of_the_loot/fractional_knapsack.py | 860 | 3.75 | 4 | # Uses python3
import sys
def get_optimal_value(capacity, weights, values):
value = 0.
# write your code here
# build a tuple which is [(v, w, v/w), ...]
vw_tuple = [(values[i], weights[i], 1. * values[i] / weights[i]) for i in range(len(values))]
# print(vw_tuple)
vw_tuple.sort(key=lambda x: x[2], reverse=True)
# print(vw_tuple)
for v, w, v_over_w in vw_tuple:
if w < capacity:
value += v
capacity -= w
else: # w >= capacity
value += v_over_w * capacity
break
return value
if __name__ == "__main__":
data = list(map(int, sys.stdin.read().split()))
n, capacity = data[0:2]
values = data[2:(2 * n + 2):2]
weights = data[3:(2 * n + 2):2]
opt_value = get_optimal_value(capacity, weights, values)
print("{:.10f}".format(opt_value))
|
1c427e738788145d19708d54f62415beb637a771 | siumingdev/course-exercises | /Data Structures and Algorithms, UCSD/3. Algorithms on Graphs/week2_decomposition2/3_strongly_connected/strongly_connected.py | 1,608 | 3.59375 | 4 | #Uses python3
import sys
sys.setrecursionlimit(200000)
def toposort(adj):
# print(adj)
visited = [False] * len(adj)
post_order = []
def explore(_x):
visited[_x] = True
for _neighbor_of_x in adj[_x]:
if not visited[_neighbor_of_x]:
explore(_neighbor_of_x)
post_order.append(_x)
def dfs():
for _x in range(len(adj)):
if not visited[_x]:
explore(_x)
dfs()
post_order.reverse()
return post_order
def reverse_graph(adj):
ret_adj = [[] for _ in range(len(adj))]
for u, adj_u in enumerate(adj):
for v in adj_u:
ret_adj[v].append(u)
return ret_adj
def number_of_strongly_connected_components(adj):
#write your code here
rev_adj = reverse_graph(adj)
topo_order = toposort(rev_adj)
# print(topo_order)
visited = [False] * len(adj)
scc = []
def explore(_x):
visited[_x] = True
scc[-1].append(_x)
for _neighbor_of_x in adj[_x]:
if not visited[_neighbor_of_x]:
explore(_neighbor_of_x)
for _x in topo_order:
if not visited[_x]:
scc.append([])
explore(_x)
# print(scc)
return len(scc)
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n, m = data[0:2]
data = data[2:]
edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
adj = [[] for _ in range(n)]
for (a, b) in edges:
adj[a - 1].append(b - 1)
print(number_of_strongly_connected_components(adj))
|
817446639494fd93cf885e9a527fd040c0cdeee0 | siumingdev/course-exercises | /Data Structures and Algorithms, UCSD/1. Algorithmic Toolbox/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/fibonacci_sum_squares.py | 1,034 | 3.703125 | 4 | # Uses python3
from sys import stdin
def fibonacci_sum_squares_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current * current
return sum % 10
def get_fibonacci_huge_fast(n, m):
if n <= 1:
return n
fibs = [0, 1]
mods = [0, 1]
period = None
for i in range(2, n + 1):
# print('i', i)
fibs.append(fibs[i - 1] + fibs[i - 2])
mods.append(fibs[i] % m)
if mods[i - 1] is 0 and mods[i] is 1:
period = i + 1 - 2
break
# print(period)
if period is None:
return fibs[n] % m
else:
return fibs[n % period] % m
def fibonacci_sum_squares_fast(n):
return (get_fibonacci_huge_fast(n, 10) * get_fibonacci_huge_fast(n + 1, 10)) % 10
if __name__ == '__main__':
# n = int(stdin.read())
n = int(input())
# n = 1234567890
print(fibonacci_sum_squares_fast(n))
|
9c77351cf0ddb6158bb91a0e73914797c9d770b0 | Oleh6195/BattleShip | /field.py | 6,944 | 3.578125 | 4 | from funcs import has_ship, ship_size, field_to_str, is_valid
from ship import Ship
import random
class Field:
"""
This class representts field
"""
def __init__(self):
self.empty_field = dict()
self.score = 0
letters = "ABCDEFGHIJ"
for let in letters:
self.empty_field[let] = [" " for i in range(10)]
shipses = []
def generate():
"""
() -> (tuple)
:return: tuple of field with dictionary and list
"""
ships = []
direc = ''
field, ship = {}, {4: [1], 3: [1, 1], 2: [1, 1, 1],
1: [1, 1, 1, 1]}
direction, letters = "vh", 'ABCDEFGHIJ'
for letter in letters:
field[letter] = []
for i in range(10):
field[letter].append(' ')
field[letter].append('\n')
for key in ship:
while ship[key] != []:
cordinates = ()
while cordinates == ():
y = random.choice(letters)
x = random.randint(0, 9)
direc = random.choice(direction)
horizontal = field[y]
if y == "A":
hor_down = field[letters[letters.index(y) + 1]]
hor_up = []
elif y == "J":
hor_up = field[letters[letters.index(y) - 1]]
hor_down = []
else:
hor_up = field[letters[letters.index(y) - 1]]
hor_down = field[letters[letters.index(y) + 1]]
vertical = [field[key][x] for key in field]
vertical_up = [field[key][x - 1] for key in field]
vertical_down = [field[key][x + 1] for key in field]
if direc == "h":
if '*' not in field[y][
x: x + 2 + key] and x <= 10 - key:
try:
work1 = horizontal[:x]
work2 = horizontal[x + 1:]
if work1[-1] == "*":
continue
elif work2[0] == "*":
continue
wor1 = hor_up[x - 1:x + key + 1]
wor2 = hor_down[x - 1:x + key + 1]
if "*" in wor1:
continue
if "*" in wor2:
continue
else:
cordinates = (x, y)
except IndexError:
pass
if direc == "v":
if "*" not in vertical[letters.index(y):
letters.index(y) +
2 + key] and \
letters.index(y) <= 10\
- key:
try:
work1 = horizontal[:x]
work2 = horizontal[x + 1:]
if work1[-1] == "*":
continue
elif work2[0] == "*":
continue
wor1 = \
vertical_up[letters.index(y) -
1:letters.index(
y) + key + 1]
wor2 = vertical_down[letters.index(y) -
1:letters.index(
y) + key + 1]
if "*" in wor1:
continue
if "*" in wor2:
continue
else:
cordinates = (x, y)
except IndexError:
continue
if direc == "v":
ship[key].remove(1)
for keys in range(letters.index(y),
letters.index(y) + key):
field[letters[keys]][x] = "*"
elif direc == "h":
ship[key].remove(1)
for elements in range(x + 1, x + 1 + key):
field[y][elements] = '*'
if direc == "v":
ships.append(((y, x), (1, key), False, []))
elif direc == "h":
ships.append(((y, x), (key, 1), True, []))
return field, ships
def generate_field():
"""
Call generate while field won't be valid
"""
field = generate()
while not is_valid(field[0]):
field = generate()
return field
field = generate_field()
self.data = field[0]
for ship in field[1]:
shp = Ship(ship[0], ship[2], ship[1], ship[3])
shipses.append(shp)
self.__ships = shipses
def shoot_at(self, cordinates):
"""
:param cordinates:
Change point which user shooted in
"""
status = False
for ship in self.__ships:
if cordinates in ship.get_cordanates():
status = True
self.score += 1
ship.shoot_at(cordinates)
if status:
self.empty_field[cordinates[0]][cordinates[1]] = \
'\033[1;31mX\033[1;m'
self.data[cordinates[0]][cordinates[1]] = \
'\033[1;31mx\033[1;m'
else:
self.empty_field[cordinates[0]][cordinates[1]] = 'X'
self.data[cordinates[0]][cordinates[1]] = 'X'
return status
def field_with_ships(self):
return field_to_str(self.data)
def field_without_ships(self):
return field_to_str(self.empty_field)
def winner(self):
lst = []
for ship in self.__ships:
if ship.length == len(ship.hit):
lst.append(True)
if len(lst) == 10:
return True
return False
|
cd2653796bca22901b7f979ed126040fdebeeac8 | dev-tanvir/automate_boring | /while_adder.py | 147 | 3.734375 | 4 | #adding from 1 to 100 using while loop
i = 0
total = 0
while True:
total = total + i
if i == 100:
break
i = i + 1
print(total)
|
4db7eb9ce2a95a1a46229b08ab0da06b0f7dd1be | PritishMukherjee123/c-136 | /c-131.py | 8,421 | 3.59375 | 4 | import csv
rows=[]
with open("planetdata.csv","r") as f:
csvreader=csv.reader(f)
for row in csvreader:
rows.append(row)
headers=rows[0]
Planet_data_row=rows[1:]
print(headers)
print(Planet_data_row[0])
headers[0]="row_num"
Solar_System_Planet_Count={}
for Planet_data in Planet_data_row:
if Solar_System_Planet_Count.get(Planet_data[11]):
Solar_System_Planet_Count[Planet_data[11]]+=1
else:
Solar_System_Planet_Count[Planet_data[11]]=1
max_solar_system=max( Solar_System_Planet_Count,key=Solar_System_Planet_Count.get)
print(max_solar_system)
temp_planet_data_rows= list(Planet_data_row)
for i in temp_planet_data_rows :
planet_mass=i[3]
if planet_mass.lower()=="unknown":
Planet_data_row.remove(i)
continue
else :
planet_mass_value=planet_mass.split(" ")[0]
planet_mass_ref=planet_mass.split(" ")[1]
if planet_mass_ref =="Jupiters":
planet_mass_value= float(planet_mass_value)*317.8
i[3]=planet_mass_value
planet_radius=i[7]
if planet_radius.lower()=="unknown":
Planet_data_row.remove(i)
continue
else :
planet_radius_value=planet_radius.split(" ")[0]
planet_radius_ref=planet_radius.split(" ")[1]
if planet_radius_ref =="Jupiter":
planet_radius_value= float(planet_radius_value)*11.2
i[7]=planet_radius_value
print(len(Planet_data_row))
koi_planets=[]
for i in Planet_data_row :
if max_solar_system == i[11]:
koi_planets.append(i)
print(len(koi_planets))
import plotly.express as px
koi_planet_mass=[]
koi_planet_name=[]
for i in koi_planets :
koi_planet_mass.append(i[3])
koi_planet_name.append(i[1])
koi_planet_mass.append(1)
koi_planet_name.append("earth")
graph = px.bar(x=koi_planet_name,y=koi_planet_mass)
graph.show()
temp_planet_data_rows=list(Planet_data_row)
for i in temp_planet_data_rows:
if i[1].lower()=="hd 100546 b":
Planet_data_row.remove(i)
planet_mass =[]
planet_radius=[]
planet_name=[]
for i in Planet_data_row:
planet_mass.append(i[3])
planet_radius.append(i[7])
planet_name.append(i[1])
planet_gravity=[]
for index , name in enumerate(planet_name):
gravity=float(planet_mass[index])*5.972e+24/(float(planet_radius[index])*float(planet_radius[index])*6371000*6371000)
gravity=gravity*6.674e-11
planet_gravity.append(gravity)
graph=px.scatter(x=planet_radius,y=planet_mass,size=planet_gravity,hover_data=[planet_name])
graph.show()
low_gravity=[]
for index,gravity in enumerate(planet_gravity):
if gravity<10 :
low_gravity.append(Planet_data_row[index])
low_gravityplanets=[]
for index,gravity in enumerate(planet_gravity):
if gravity<100 :
low_gravityplanets.append(Planet_data_row[index])
print(len(low_gravity))
print(len(low_gravityplanets))
planet_type_values=[]
for i in Planet_data_row:
planet_type_values.append(i[6])
print(list(set(planet_type_values)))
planet_masses=[]
planet_radiuses=[]
for i in Planet_data_row:
planet_masses.append(i[3])
planet_radiuses.append(i[7])
graph3=px.scatter(x=planet_radiuses,y=planet_masses)
graph3.show()
"""from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import seaborn as sb
X=[]
for index,planet_mass in enumerate(planet_masses):
temp_list=[planet_radiuses[index],planet_mass]
X.append(temp_list)
Wcss=[]
for i in range(1,11):
kmeans=KMeans(n_clusters=i,init="k-means++",random_state=42)
kmeans.fit(X)
Wcss.append(kmeans.inertia_)
plt.figure(figsize=(10,5))
sb.lineplot(range(1,11),Wcss,marker="o",color="red")
plt.show()"""
planet_masses=[]
planet_radiuses=[]
planet_types=[]
for i in low_gravityplanets:
planet_masses.append(i[3])
planet_radiuses.append(i[7])
planet_types.append(i[6])
graph4=px.scatter(x=planet_radiuses,y=planet_masses,color=planet_types)
graph4.show()
suitable_planets=[]
for i in low_gravityplanets :
if i[6].lower()=="terrestrial" or i[6].lower()=="super earth":
suitable_planets.append(i)
print(len(suitable_planets))
temp_suitable_planets=list(suitable_planets)
for i in temp_suitable_planets :
if i [8].lower()=="unknown":
suitable_planets.remove(i)
for i in suitable_planets:
if i[9].split(" ")[1].lower()=="days":
i[9]=float(i[9].split(" ")[0])
else:
i[9]=float(i[9].split(" ")[0])*365
i[8]=float(i[8].split(" ")[0])
orbital_radius=[]
orbital_period=[]
for i in suitable_planets:
orbital_radius.append(i[8])
orbital_period.append(i[9])
graph5=px.scatter(x=orbital_radius,y=orbital_period)
graph5.show()
goldilock_planet= list(suitable_planets)
temp_goldilock_planet=list(suitable_planets)
for i in temp_goldilock_planet:
if float(i[8])<0.38 or float(i[8])>2 :
goldilock_planet.remove(i)
print(len(goldilock_planet))
print(len(suitable_planets))
planet_speed=[]
for i in suitable_planets:
distance = 2*3.14*i [8]*1.496e+9
time =i[9]*86400
speed=distance/time
planet_speed.append(speed)
speed_suporting_planets=list(suitable_planets)
temp_speedsupporting=list(suitable_planets)
for index,pd in enumerate(temp_speedsupporting):
if planet_speed[index]>200:
speed_suporting_planets.remove(pd)
print(len(speed_suporting_planets))
print(len(suitable_planets))
habitableplanets=[]
for i in speed_suporting_planets:
if i in temp_goldilock_planet :
habitableplanets.append(i)
print(len(habitableplanets))
finaldict ={}
for index,planet_data in enumerate(Planet_data_row):
feautureslist=[]
gravity=(float(planet_data[3])*5.972e+24)/(float(planet_data[7])*float(planet_data[7])*6371000*6371000)*6.674e-11
try:
if gravity<100:
feautureslist.append("gravity")
except:pass
try:
if planet_data[6].lower()=="terrestrial" or planet_data[6].lower()=="super earth":
feautureslist.append("planet_type")
except:pass
try:
if planet_data[8] > 0.38 or planet_data[8]<2 :
feautureslist.append("goldilock")
except:pass
try:
distance=2*3.14*(planet_data[8]*1.496e+9)
time=planet_data[9]*86400
speed=distance/time
if speed<200:
feautureslist.append("speed")
except:pass
finaldict[index]=feautureslist
print(finaldict)
# graph.plot
gravity_planet_count=0
for key , value in finaldict.items():
if "gravity" in value:
gravity_planet_count+=1
print(gravity_planet_count)
type_planet_count=0
for key , value in finaldict.items():
if "planet_type" in value:
type_planet_count+=1
print(type_planet_count)
speed_planet_count=0
for key , value in finaldict.items():
if "speed" in value :
speed_planet_count+=1
print(speed_planet_count)
goldilock_planet_count=0
for key , value in finaldict.items():
if"goldilock" in value :
goldilock_planet_count+=1
print(goldilock_planet_count)
planet_not_gravity_support=[]
for i in Planet_data_row :
if i not in low_gravityplanets :
planet_not_gravity_support.append(i)
type_no_gravity_planet_count=0
for i in planet_not_gravity_support:
if i[6].lower()=="terrestrial" or i[6].lower()=="super earth":
type_no_gravity_planet_count+=1
print(len(planet_not_gravity_support))
print(type_no_gravity_planet_count)
final_dict1={}
for i,pd in enumerate(Planet_data_row):
feautures_list =[]
gravity=(float(pd[3])*5.972e+24)/(float(pd[7])*float(pd[7])*6371000*6371000)*6.674e-11
try:
if gravity<100 :
feautures_list.append("gravity")
except:
pass
try:
if pd[6].lower()=="terrestrial" or pd[6].lower()=="super earth":
features_list.append("planet_type")
except:
pass
try:
if pd[8]>0.38 or pd[8]<2 :
features_list.append("goldilock")
except:
pass
try:
distance=2*3.14*(pd[8]*1.496e+9)
time=pd[9]*86400
speed=distance/time
if speed<200 :
features_list.append("speed")
except:
pass
final_dict1[i]=feautures_list
print(final_dict1) |
697cac8a717c9c03fac83a47e080f5112f6a4ec2 | 99003766/python_practice | /tryingnew.py | 903 | 3.53125 | 4 | import pandas as pd
from openpyxl import load_workbook
# empty data frame is created
df_total = pd.DataFrame()
res=[]
# all sheets are taken as a list
sheets = ['Sheet1', 'Sheet2', 'Sheet3', 'Sheet4']
# from user email address is taken
yin = input("Enter Official Email Address")
# for loop for reading all the data in datasheets and searching for the data we need
for i in sheets:
# loop through sheets inside an Excel file
y = pd.read_excel('Excel.xlsx', sheet_name=i)
number = i
for i in range(i.nrows):
if (i.row_values(i)[0] == PS_NUMBER and sheet.row_values(i)[1] == PsNo and sheet.row_values(i)[2] == EmailId):
print(i.row_values(i))
if number == 0:
for i in i.row_values(i):
if i not in res:
res.append(i)
else:
print(i.row_values(i)[3:])
for j in i.row_values(i)[3:]:
res.append(j)
# print(res) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.