blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
62149622c7cb41563872862f2246a49a7692ec95 | ledelma2/CS474 | /HW3/Game.py | 1,890 | 3.921875 | 4 | # The game class houses all the rules for the game in addition to
# the players and board
import Player
import Board
class Game(object):
def __init__(self):
self.board = Board.Board()
self.players = [Player.Player('X'), Player.Player('O')]
def run(self):
while True:
winner = ''
i = 0
self.board.resetBoard()
moves = []
self.board.printBoard()
while ' ' in self.board.board:
print("Turn ", i + 1, ": Player ", (i % 2) + 1, "(",self.players[i%2].getPiece(),") choose your move: ")
while True:
move = input()
move = move.split(" ")
if(len(move) != 2):
print("Invalid move, try again: ")
continue
else:
move = [int(move[0]), int(move[1])]
action = self.players[i%2].addMove(moves, move, self.board)
if action == "Player":
print("Invalid move, position already taken, try again:")
continue
elif action == "Board":
print("Invalid move, outside board, try again:")
continue
else:
break
self.board.printBoard()
if self.players[i%2].checkForWin(self.board):
winner = "Player " + str(i%2 + 1)
break
i+=1
if winner != '':
print(winner, " wins! Play again? (y/n): ")
else:
print("Tie Game! Play again? (y/n): ")
i = input()
if i == 'n':
print("Goodbye")
break
|
84246bc9ce9cedbc9ff27bb52a84876822e6e025 | lizator/Euclidean_Algorithm | /Euklids.py | 1,799 | 3.578125 | 4 | import math
import tabula
# Python solution to Euklids algorithm for Discrete Mathematics with automated LaTeX code output
# does the computing for Euklids algorithm
class Euklid:
def __init__(self):
self.s0 = 0; self.s1 = 0
self.t0 = 0; self.t1 = 0
self.r0 = 0; self.r1 = 0
pass
def update(self, s1, s2, t1, t2, r1, r2):
self.s0 = s1; self.s1 = s2
self.t0 = t1; self.t1 = t2
self.r0 = r1; self.r1 = r2
pass
def gcd(self, a, b, addLatex):
myTable = tabula.TableSetUp()
if abs(a) < abs(b):
self.update(0, 1, 1, 0, b, a)
myTable.addLine(-1, self.s0, self.s1, " ", self.r0)
myTable.addLine( 0, self.t0, self.t1, " ", self.r1)
else:
self.update(1, 0, 0, 1, a, b)
myTable.addLine(-1, self.s0, self.t0, " ", self.r0)
myTable.addLine(0, self.s1, self.t1, " ", self.r1)
if addLatex:
self.tex = tabula.Latex()
self.tex.beginTabluar(self.r0, self.r1)
self.tex.addLineAsCode(-1, self.s0, self.t0, " ", self.r0)
self.tex.addLineAsCode(0, self.s1, self.t1, " ", self.r1)
i = 1
while (self.r1 != 0):
q = math.floor(self.r0 / self.r1)
s2 = self.s0 - (self.s1 * q)
t2 = self.t0 - (self.t1 * q)
r2 = self.r0 - (self.r1 * q)
myTable.addLine(i, s2, t2, q, r2)
if addLatex:
self.tex.addLineAsCode(i, s2, t2, q, r2)
self.update(self.s1, s2, self.t1, t2, self.r1, r2)
i += 1
if addLatex:
self.tex.endTabular()
return myTable.table
# testing
#eu = Eukild()
#eu.gcd(4, 3, False)
#print (" ")
#eu.gcd(341, 217, True)
|
e4936104d77489a25ad08a34ad26684da58b5831 | Disunito/hello-world | /python_work/Chap_four/players.py | 901 | 4.46875 | 4 | #Useing slices of lists. Slices are indexed like lists
players = ['bear', 'eric', 'kayla', 'thom', 'cristina']
#Starts at the begining of the list of first number listed and ends before the
#second argument
print("These are my roommates:")
for player in players[0:3]:
print(player.title())
#Using a neg. index counts from the end of the list
print("\nThese are my partners:")
for player in players[-3:]:
print(player.title())
#This starts 3 from the front and prints to the end
print("\nThese people don't live with me:")
for player in players[3:]:
print(player.title())
#This prints only the first and the 3rd and skips the second.
print("\nThese people knew each other years ago:")
for player in players[0:3:2]:
print(player.title())
#this doesnt print the last three names in the list.
print("\nThese people are dating:")
for player in players[:-3]:
print(player.title())
|
c845e2e91c01fd28014414ab25840d5f98c25a70 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_3_1/ihpk/senate_evacuation.py | 3,593 | 4.0625 | 4 | import string
def senate_evacuation(file_name):
read_file_name = file_name
write_file_name = file_name + ' - answer.txt'
read_file = open(read_file_name)
write_file = open(write_file_name, "w")
cases = int(read_file.readline())
current_case = 1
while current_case <= cases:
parties = int(read_file.readline())
senator_distribution = read_file.readline()
output = build_evacuation_plan(parties, senator_distribution)
file_output = "Case #{0}: {1}\n".format(current_case, output)
print(file_output)
write_file.write(file_output)
current_case += 1
def build_evacuation_plan(parties, senator_distribution):
senator_split = senator_distribution.split()
party_names = list(string.ascii_uppercase)
pop_to_party = {}
total_number_of_senators = 0
highest_population_in_party = 0
i = 0
while i < parties:
party = party_names[i]
number_of_senators = int(senator_split[i])
highest_population_in_party = max(highest_population_in_party, number_of_senators - 1)
total_number_of_senators += number_of_senators
j = 0
while j < number_of_senators:
if j in pop_to_party:
pop_to_party[j].append(party)
else:
pop_to_party[j] = [party]
j += 1
i += 1
print(pop_to_party)
exit_plan = ""
while total_number_of_senators > 0:
if total_number_of_senators == 3: #grab 1 senator
highest_population_in_party, senator_1 = grab_next_senator(pop_to_party, highest_population_in_party)
total_number_of_senators -= 2
exit_plan += senator_1 + " "
else: #grab 2 senators
highest_population_in_party, senator_1 = grab_next_senator(pop_to_party, highest_population_in_party)
highest_population_in_party, senator_2 = grab_next_senator(pop_to_party, highest_population_in_party)
total_number_of_senators -= 2
exit_plan += senator_1 + senator_2 + " "
return(exit_plan)
def grab_next_senator(pop_to_party, highest_population_in_party):
senators_at_pop = pop_to_party[highest_population_in_party]
if len(senators_at_pop) > 0:
return highest_population_in_party, senators_at_pop.pop()
else:
highest_population_in_party -= 1
senators_at_pop = pop_to_party[highest_population_in_party]
return highest_population_in_party, senators_at_pop.pop()
"""
def build_evacuation_plan(parties, senator_distribution):
senator_split = senator_distribution.split()
party_names = list(string.ascii_uppercase)
party_to_pop = {}
pop_to_party = {}
total_number_of_senators = 0
highest_population_in_party = 0
i = 0
while i < parties:
party = party_names[i]
number_of_senators = int(senator_split[i])
party_to_pop[party] = number_of_senators
pop_to_party[number_of_senators] = party
total_number_of_senators += number_of_senators
i += 1
exit_plan = ""
while highest_population_in_party > 0:
if total_number_of_senators == 3: #grab 1 senator
pass
else: #grab 2 senators
"""
if __name__ == "__main__":
senate_evacuation("test.txt")
#senate_evacuation("A-small-attempt0.in")
senate_evacuation("A-large.in") |
01cd589b40119a300d48a8fddded2e21084d81b5 | ruidge/TestPython | /Test/com/ruidge/liaoxuefeng/functional/test_functional1.py | 266 | 3.625 | 4 | #coding=utf-8
'''
Created on 2015年2月5日
@author: zhangrui6
'''
def inc(x):
def incx(y):
return x+y
return incx
inc2 = inc(2)
inc5 = inc(5)
print inc2(5) # 输出 7
print inc5(5) # 输出 10
print type(inc2)
print type(inc5) |
ed08357850e2a1418ac914d297b635fc46fbee6f | jxjk/git_jxj | /python_img_demo/bresenham_line.py | 595 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
bresenham画直线
蒋小军
2018.6.26
"""
import cv2
import numpy as np
def bresenhamLine(x0=0,y0=0,x1=1,y1=1):
# 设置x/y偏移量、设置斜率
dx = x1-x0
dy = y1-y0
k = dy / dx
e = -0.5
x = x0
y = y0
points = set()
for x in range (x0,x1,1):
points.add((x,y))
e = e + k
if e > 0:
y +=1
e -=1
return points
points = bresenhamLine(50,50,380,80)
print(points)
img = np.zeros((480,600,1),np.uint8)
for w,h in points:
img[h,w] = 255
cv2.imshow("img",img)
cv2.waitKey(0)
|
2d63d7d54fb8ff954188a1adfe6567e4ba35c5e4 | miyamotok0105/ai_chatbot | /team1/neuralNetwork.py | 10,238 | 3.53125 | 4 | #coding:utf-8
#### Libraries
# Standard library
import random
# Third-party libraries
import numpy as np
import math
import sys
import MeCab
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pdb
import logging
import codecs
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.neighbors import KNeighborsClassifier
class Network(object):
def __init__(self, sizes):
"""The list ``sizes`` contains the number of neurons in the
respective layers of the network. For example, if the list
was [2, 3, 1] then it would be a three-layer network, with the
first layer containing 2 neurons, the second layer 3 neurons,
and the third layer 1 neuron. The biases and weights for the
network are initialized randomly, using a Gaussian
distribution with mean 0, and variance 1. Note that the first
layer is assumed to be an input layer, and by convention we
won't set any biases for those neurons, since biases are only
ever used in computing the outputs from later layers."""
self.num_layers = len(sizes)
self.sizes = sizes
self.biases = [np.random.randn(y, 1) for y in sizes[1:]]
self.weights = [np.random.randn(y, x)
for x, y in zip(sizes[:-1], sizes[1:])]
def feedforward(self, a):
"""Return the output of the network if ``a`` is input."""
for b, w in zip(self.biases, self.weights):
a = sigmoid(np.dot(w, a)+b)
return a
def SGD(self, training_data, epochs, mini_batch_size, eta,
test_data=None):
"""Train the neural network using mini-batch stochastic
gradient descent. The ``training_data`` is a list of tuples
``(x, y)`` representing the training inputs and the desired
outputs. The other non-optional parameters are
self-explanatory. If ``test_data`` is provided then the
network will be evaluated against the test data after each
epoch, and partial progress printed out. This is useful for
tracking progress, but slows things down substantially."""
if test_data!='': n_test = len(test_data)
n = len(training_data)
for j in range(epochs):
random.shuffle(training_data)
mini_batches = [
training_data[k:k+mini_batch_size]
for k in range(0, n, mini_batch_size)]
for mini_batch in mini_batches:
self.update_mini_batch(mini_batch, eta)
if test_data:
print("Epoch {0}: {1} / {2}".format(
j, self.evaluate(test_data), n_test))
else:
print("Epoch {0} complete".format(j))
def update_mini_batch(self, mini_batch, eta):
"""Update the network's weights and biases by applying
gradient descent using backpropagation to a single mini batch.
The ``mini_batch`` is a list of tuples ``(x, y)``, and ``eta``
is the learning rate."""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
log.warning(mini_batch.shape)
for x, y in mini_batch:
delta_nabla_b, delta_nabla_w = self.backprop(x, y)
nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
self.weights = [w-(eta/len(mini_batch))*nw
for w, nw in zip(self.weights, nabla_w)]
self.biases = [b-(eta/len(mini_batch))*nb
for b, nb in zip(self.biases, nabla_b)]
def backprop(self, x, y):
"""Return a tuple ``(nabla_b, nabla_w)`` representing the
gradient for the cost function C_x. ``nabla_b`` and
``nabla_w`` are layer-by-layer lists of numpy arrays, similar
to ``self.biases`` and ``self.weights``."""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
# feedforward
activation = x
activations = [x] # list to store all the activations, layer by layer
zs = [] # list to store all the z vectors, layer by layer
for b, w in zip(self.biases, self.weights):
z = np.dot(w, activation)+b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
# backward pass
delta = self.cost_derivative(activations[-1], y) * \
sigmoid_prime(zs[-1])
nabla_b[-1] = delta
nabla_w[-1] = np.dot(delta, activations[-2].transpose())
# Note that the variable l in the loop below is used a little
# differently to the notation in Chapter 2 of the book. Here,
# l = 1 means the last layer of neurons, l = 2 is the
# second-last layer, and so on. It's a renumbering of the
# scheme in the book, used here to take advantage of the fact
# that Python can use negative indices in lists.
for l in range(2, self.num_layers):
z = zs[-l]
sp = sigmoid_prime(z)
delta = np.dot(self.weights[-l+1].transpose(), delta) * sp
nabla_b[-l] = delta
nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())
return (nabla_b, nabla_w)
def evaluate(self, test_data):
"""Return the number of test inputs for which the neural
network outputs the correct result. Note that the neural
network's output is assumed to be the index of whichever
neuron in the final layer has the highest activation."""
test_results = [(np.argmax(self.feedforward(x)), y)
for (x, y) in test_data]
return sum(int(x == y) for (x, y) in test_results)
def cost_derivative(self, output_activations, y):
"""Return the vector of partial derivatives \partial C_x /
\partial a for the output activations."""
return (output_activations-y)
#### Miscellaneous functions
def sigmoid(z):
"""The sigmoid function."""
return 1.0/(1.0+np.exp(-z))
def sigmoid_prime(z):
"""Derivative of the sigmoid function."""
return sigmoid(z)*(1-sigmoid(z))
FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(format=FORMAT)
log = logging.getLogger('randomKNN')
# log.warning('Protocol problem: %s', 'connection reset')
# log.info('It works')
# log.warning('does it')
# log.debug('it really does')
train = pd.read_csv("IntentDataFormated.csv", header=0, quoting=3)
print(train.columns.values)
stop_words_ja = ['の', 'に', 'は', 'を', 'た', 'が', 'で', 'て', 'と', 'し', 'れ', 'さ','ある', 'いる', 'も', 'する', 'から', 'な', 'こと', 'として', 'い', 'や', 'れる','など', 'なっ', 'ない', 'この', 'ため', 'その', 'あっ', 'よう', 'また', 'もの','という', 'あり', 'まで', 'られ', 'なる', 'へ', 'か', 'だ', 'これ', 'によって','により', 'おり', 'より', 'による', 'ず', 'なり', 'られる', 'において', 'ば', 'なかっ','なく', 'しかし', 'について', 'せ', 'だっ', 'その後', 'できる', 'それ', 'う', 'ので','なお', 'のみ', 'でき', 'き', 'つ', 'における', 'および', 'いう', 'さらに', 'でも','ら', 'たり', 'その他', 'に関する', 'たち', 'ます', 'ん', 'なら', 'に対して', '特に','せる', '及び', 'これら', 'とき', 'では', 'にて', 'ほか', 'ながら', 'うち', 'そして','とともに', 'ただし', 'かつて', 'それぞれ', 'または', 'お', 'ほど', 'ものの', 'に対する','ほとんど', 'と共に', 'といった', 'です', 'とも', 'ところ', 'ここ']
def text_to_clean_words( raw_text ):
tagger = MeCab.Tagger('mecabrc') # 別のTaggerを使ってもいい
mecab_result = tagger.parse( raw_text )
info_of_words = mecab_result.split('\n')
words = []
for info in info_of_words:
# mecabで分けると、文の最後に’’が、その手前に'EOS'が来る
if info == 'EOS' or info == '':
break
# info => 'な\t助詞,終助詞,*,*,*,*,な,ナ,ナ'
info_elems = info.split(',')
# 6番目に、無活用系の単語が入る。もし6番目が'*'だったら0番目を入れる
if info_elems[6] == '*':
# info_elems[0] => 'ヴァンロッサム\t名詞'
words.append(info_elems[0][:-3])
continue
words.append(info_elems[6])
return( " ".join( words ))
stops = set(stop_words_ja)
meaningful_words = [w for w in words if not w in stops]
return( " ".join( meaningful_words ))
# and return the result.
# return( " ".join( meaningful_words ))
num_examples = train['text'].size
clean_training_data = []
for i in range( 0, num_examples ):
if( (i+1)%10 == 0 ):
print("Review %d of %d\n" % ( i+1, num_examples ) )
clean_training_data.append(text_to_clean_words( train["text"][i] ) )
print("Creating the bag of words...\n")
vectorizer = CountVectorizer(analyzer = "word", tokenizer = None, preprocessor = None, stop_words = None, max_features = 5000)
train_data_features = vectorizer.fit_transform(clean_training_data)
train_data_features = train_data_features.toarray()
print(train_data_features.shape)
# Read the test data
test = pd.read_csv("testDataFormated.csv", header=0, quoting=3 )
# Verify that there are 25,000 rows and 2 columns
print(test.shape)
# Create an empty list and append the clean reviews one by one
num_test_data = len(test["text"])
clean_test_text = []
print("Cleaning and parsing the test set...\n")
for i in range(0,num_test_data):
if( (i+1) % 1000 == 0 ):
print("test %d of %d\n" % (i+1, num_test_data))
clean_text = text_to_clean_words( test["text"][i] )
clean_test_text.append( clean_text )
# Get a bag of words for the test set, and convert to a numpy array
test_data_features = vectorizer.transform(clean_test_text)
test_data_features = test_data_features.toarray()
net = Network([230, 116, 2])
net.SGD(train_data_features, 30, 10, 3.0, test_data=test_data_features) |
aac82444ac7998ed8a737208c3ab5c7d2d53cdcb | Adikanatbek/python2 | /problem9.py | 165 | 3.578125 | 4 | a=-100
b= -100
c=0
e=0
while a <= 100:
if a %13 == 0 and a % 2 == 0:
print (a**2, a)
c += 1
a += 1
while b <= 100:
if b % 2==1:
print (b)
e += 1
b += 7
|
896a68ab417f0271506b8ceb26344544fc4008ff | Aasthaengg/IBMdataset | /Python_codes/p02265/s545227861.py | 499 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import sys
import os
from collections import deque
N = int(input())
q = deque()
for i in range(N):
lst = input().split()
command = lst[0]
if command == 'insert':
v = int(lst[1])
q.appendleft(v)
elif command == 'delete':
v = int(lst[1])
try:
q.remove(v)
except Exception:
pass
elif command == 'deleteFirst':
q.popleft()
elif command == 'deleteLast':
q.pop()
print(*q) |
840aac5d747350d938d5de3cfa9d1804161cd275 | MarinaLutak/python_homework | /laboratory2/task1.py | 477 | 3.546875 | 4 | """
Обчислення суми
"""
from validators.validators_library import validator
from validators.validators_library import re_float
from validators.validators_library import re_plus_int
x= float(validator(re_float, 'Введiть значення x'))
n= int(validator(re_plus_int, 'Введiть значення верхньої границi суми (лише натуральнi числа)'))
n = 0
for i in range(0, n + 1):
n += (x + i) / x ** 2
print(n) |
cf29c5e2869d67a3b56dd55604b9b394051b94dc | Omkar-Atugade/Python-Function-Files-and-Dictionaries | /week5.py | 1,428 | 4.28125 | 4 | #1. Sort the following string alphabetically, from z to a, and assign it to the variable sorted_letters.
#ANSWER :
letters = "alwnfiwaksuezlaeiajsdl"
sorted_letters=sorted(letters, reverse=True)
#2. Sort the list below, animals, into alphabetical order, a-z. Save the new list as animals_sorted.
#ANSWER :
animals = ['elephant', 'cat', 'moose', 'antelope', 'elk', 'rabbit', 'zebra', 'yak', 'salamander', 'deer', 'otter', 'minx', 'giraffe', 'goat', 'cow', 'tiger', 'bear']
animals_sorted=sorted(animals)
#3. The dictionary, medals, shows the medal count for six countries during the Rio Olympics.
#Sort the country names so they appear alphabetically.
#Save this list to the variable alphabetical.
#ANSWER :
medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}
alphabetical=sorted(medals)
#4. Given the same dictionary, medals, now sort by the medal count.
#Save the three countries with the highest medal count to the list, top_three.
#ANSWER :
medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}
top_there=[]
def g(k,d):
return d[k]
ks=medals.keys()
top_three=sorted(ks,key=lambda x :g(x,medals), reverse=True)[:3]
|
e36d528d95a5480e7b505f32ca39a2fc4c1995d3 | mosihere/hackerNews | /hackernews.py | 567 | 3.53125 | 4 | import requests
from bs4 import BeautifulSoup
# Send request to fetch data
response = requests.get('https://hckrnews.com/')
# Parse Needed Data with BS !
soup = BeautifulSoup(response.text, 'html.parser')
# Select a special tag that we need --> and use attributes to find that exactly
data = soup('a', attrs={'class':'link'})
# Print Data
counter = 0
for title in data:
counter += 1
print('%i:'%counter,title.text,title.get('href')) # title.get('href) will show the links
print() # title.text is just the text |
da77be16b39e67543933a371c1ec163b87e79738 | pavlosprotopapas/course-starter-harvard | /exercises/chapter2/exc_02_03/solution_02_03.py | 1,179 | 4.1875 | 4 | # Import the numpy library and name it np
import numpy as np
# Import the pandas library and name it pd
import pandas as pd
# import matplotlib.pyplot
import matplotlib.pyplot as plt
# add the following line in order to have the plots inside the notebook
%matplotlib inline
# Data set used in this exercise (Advertising.csv)
data_filename = 'https://raw.githubusercontent.com/Harvard-IACS/' \
'2018-CS109A/master/content/lectures/lecture5/data/Advertising.csv'
# Read Advertising.csv file using pandas libraries:
df = pd.read_csv(data_filename)
# Create a new dataframe called `df_new`. witch the columns ['TV' and 'sales'].
df_new = df[['TV', 'sales']]
# Set beta0 = 2.2
beta0 = 6.67
# Create lists to store the MSE and beta1
MSE = []
beta1_list = []
for beta1 in np.arange(-1, 2, 0.01):
y_predict = beta0 + beta1 * df_new.TV
# Append the new MSE in the list that you created above
MSE.append(np.mean((df_new.sales - y_predict) ** 2))
# Also append beta1 values in the list
beta1_list.append(beta1)
# Plot MSE as a function of beta1
plt.plot(beta1_list, MSE)
plt.xlabel('Beta1')
plt.ylabel('MSE')
# To display all figures
plt.show() |
afe6ff4a7dc556e6d74723234fd9b5221dad675f | alfaroqueIslam/Intro-Python-II | /src/player.py | 645 | 3.625 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, player, room):
self.player = player
self.room = room
inventory = []
def check_for_items(self):
if not self.room.items:
print('You see no items in this room')
else:
print(f'You see the following items:')
for item in self.room.items:
print(item.name, '-', item.description)
def get(self, item):
self.inventory.extend(item)
def drop(self, item):
for i in item:
self.inventory.remove(i)
|
0ccaf05ee0becbabc0541f6e57f36f5b2e315670 | fgirardi/SourcePython | /diversos/ExampleGetAttr.py | 304 | 3.703125 | 4 | class ABC():
x = "Some Value"
y = ""
def SetY(self, value):
print("Debug SetY {0}".format(value))
self.y = value
obj = ABC()
print("x {0}".format(obj.x))
print(getattr(obj,"x"))
getattr(obj,"SetY")("200")
print("obj.y={0}".format(obj.y))
setattr(obj,"a","definition of a")
print(obj.a)
|
3399c6c526602b7254e1ca07430c3a46e0aec9af | Frank1963-mpoyi/REAL-PYTHON | /MODULE_AND_PACKAGE/the_dir_function.py | 369 | 3.90625 | 4 | '''
The dir() Function
The built-in function dir() returns a list of defined names in a namespace.
Without arguments, it produces an alphabetically sorted list of names in the
current local symbol table:
'''
print(dir())
a = "yrs"
qux = [1, 2, 3, 4, 5]
print(dir())# return the list of the name of all the variable
class Bar():
pass
x = Bar()
print(dir())
|
668bc201ffa00c3de32aee5a1d5f17ffc4ba774e | AlanArvizu739/AlanArvizu | /grade book.py | 1,158 | 4.125 | 4 | #Alan Arvizu
print ("Enter your grade for average to be calculated")
print(" algebra 2")
Algebra_2 = float(input("enter your grade: "))
print(" Ap chemistry")
Ap_chemistry = float(input("enter your grade: "))
print("computational thinking")
computational_thinking = float(input(" enter your grade: "))
print("geometry")
Ap_geometry = float(input("enter your grade: "))
print("Ap english")
Ap_english = float(input("enter your grade: "))
student_grades = [Algebra_2,Ap_chemistry,computational_thinking,Ap_geometry,Ap_english,]
grade_average = (Algebra_2 + Ap_chemistry + computational_thinking + Ap_geometry + Ap_english) / 5
student_grades.append(grade_average)
print student_grades
if grade_average in range(1,60):
print ("student needs improvment")
elif grade_average in range(60,70):
print ("student needs improvment")
elif grade_average in range (70,80):
print("student is doing fairly well")
elif grade_average in range(80,90) :
print("student is doing good")
elif grade_average in range(90,100):
print("student is doing outstadning")
else:
print ("your doing ok")
|
0558d54f6cb1e86baf20db508b1b98f9ee7437d4 | JerryZhuzq/leetcode | /linked list/206. Reverse Linked List.py | 788 | 3.96875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList_iterate(self, head: ListNode) -> ListNode:
if not head:
return None
dummy = ListNode(0, head)
pre = dummy
cur = head
while (cur):
cur.next, cur, pre = pre, cur.next, cur
head.next = None
return pre
def reverseList_recursive(self, head: ListNode) -> ListNode:
if not head:
return None
def helper(node, pre):
if not node:
return pre
res = helper(node.next, node)
node.next = pre
return res
return helper(head, None)
|
3985fffaf7eef8d5a7ffe8441fd414c9c3a8f42d | heecheol1508/algorithm-problem | /_baekjoon/1654_렌선 자르기.py | 661 | 3.59375 | 4 | import sys
sys.stdin = open('input.txt', 'r')
def can_make_n(length):
cnt = 0
for i in range(K):
t = lines[i] // length
if t == 0:
return False
cnt += t
if cnt >= N:
return True
return False
def binary_search(left, right):
if right - 1 == left:
return left
mid = (left + right) // 2
if can_make_n(mid):
return binary_search(mid, right)
else:
return binary_search(left, mid)
K, N = map(int, input().split())
lines = [int(input()) for _ in range(K)]
lines.sort(reverse=True)
MAX = sum(lines) // N
answer = binary_search(1, MAX + 1)
print(answer)
|
8f70428e96025659ef97b55962da7591e01425b8 | ykuzin/amis_python71 | /km71/Kuzin_Yuriy/homework_4/task1.py | 471 | 4.09375 | 4 | """
Умова: Дано два цілих числа. Вивести найменше з них.
Вхідні дані: користувач вводить ціле число
Вихідні дані: вивести ціле число
"""
x = int(input("ВВедіть перше чило "))
y = int(input("Введіть друге число "))
answer = ""
if x<y:
answer = y
elif x>y:
answer = x
else:
answer = "Числа рівні"
print(answer)
|
e196e7084aa322d37eb20789602fe95d6d5aaa00 | apillalamarri/python_exercises | /contacts.py | 2,470 | 3.984375 | 4 | # Challenge Level: Beginner
# NOTE: Please don't use anyone's *real* contact information during these exercises, especially if you're putting it up on Github!
# Background: You have a dictionary with people's contact information. You want to display that information as an HTML table.
# Goal 1: Loop through that dictionary to print out everyone's contact information.
# Sample output:
# Shannon's contact information is:
# Phone: 202-555-1234
# Twitter: @svt827
# Github: @shannonturner
# Beyonce's contact information is:
# Phone: 303-404-9876
# Twitter: @beyonce
# Github: @bey
contacts = {
'Shannon': {'phone': '202-555-1234', 'twitter': '@svt827', 'github': '@shannonturner' },
'Beyonce': {'phone': '303-404-9876', 'twitter': '@beyonce', 'github': '@bey'},
'Tegan and Sara': {'phone': '301-777-3313', 'twitter': '@teganandsara', 'github': '@heartthrob'}
}
for name, info in contacts.iteritems():
print "{0}'s contact information is:".format(name)
for k,v in info.iteritems():
print " {0}: {1}".format(k.title(),v)
# Goal 2: Display that information as an HTML table.
# Goal 3: Write all of the HTML out to a file called contacts.html and open it in your browser.
# Sample output:
# <table border="1">
# <tr>
# <td colspan="3"> Shannon </td>
# </tr>
# <tr>
# <td> Phone: 202-555-1234 </td>
# <td> Twitter: @svt827 </td>
# <td> Github: @shannonturner </td>
# </tr>
# </table>
# ...
# Goal 4: Instead of reading in the contacts from the dictionary above, read them in from contacts.csv, which you can find in lesson_07_(files).
with open ("contact_info.html", "w") as contact_info_code:
with open ("contacts.csv", "r") as contact_file:
contacts = contact_file.read().split("\n")
headers = contacts.pop(0).split(",")
contact_dict = {}
for contact in contacts:
contact_split = contact.split(",")
single_contact_dict = {}
for header, element in zip(headers, contact_split):
single_contact_dict[header] = element
contact_dict[single_contact_dict.get("Name")] = single_contact_dict
#print contact_dict
contact_info_code.write('<table border="1">\n')
for name, info in contact_dict.iteritems():
contact_info_code.write('<tr><td colspan="3">\n')
contact_info_code.write('<b>{0}</b>\n</td>\n</tr>\n'.format(name))
for k,v in info.iteritems():
if k != "Name":
contact_info_code.write('<td>{0}: {1}</td>\n'.format(k.title(),v))
contact_info_code.write('</tr>\n</table>\n')
|
debd8f3b2188b43291f577347b23d79b9bfe6a42 | wuworkshop/LPTHW | /ex9/ex9.py | 645 | 4.125 | 4 | # Here's some new strange stuff, remember type it exactly.
# Assigns the string to the variable days
days = "Mon Tue Wed Thu Fri Sat Sun"
# Assigns the string to the variable months
# The \n is for adding a new line
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
# Prints the string and the variable days
print "Here are the days: ", days
# Prints the string and the variable months
print "Here are the months: ", months
# Prints out all the lines inside the three double quotes
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""" |
deee2d5be1d66df9f017b4573a65d0c47491025c | Zhenye-Na/leetcode | /python/127.word-ladder.py | 3,224 | 3.84375 | 4 | #
# @lc app=leetcode id=127 lang=python3
#
# [127] Word Ladder
#
# https://leetcode.com/problems/word-ladder/description/
#
# algorithms
# Hard (31.55%)
# Likes: 4766
# Dislikes: 1402
# Total Accepted: 555.3K
# Total Submissions: 1.7M
# Testcase Example: '"hit"\n"cog"\n["hot","dot","dog","lot","log","cog"]'
#
# A transformation sequence from word beginWord to word endWord using a
# dictionary wordList is a sequence of words such that:
#
#
# The first word in the sequence is beginWord.
# The last word in the sequence is endWord.
# Only one letter is different between each adjacent pair of words in the
# sequence.
# Every word in the sequence is in wordList.
#
#
# Given two words, beginWord and endWord, and a dictionary wordList, return the
# number of words in the shortest transformation sequence from beginWord to
# endWord, or 0 if no such sequence exists.
#
#
# Example 1:
#
#
# Input: beginWord = "hit", endWord = "cog", wordList =
# ["hot","dot","dog","lot","log","cog"]
# Output: 5
# Explanation: One shortest transformation is "hit" -> "hot" -> "dot" -> "dog"
# -> "cog" with 5 words.
#
#
# Example 2:
#
#
# Input: beginWord = "hit", endWord = "cog", wordList =
# ["hot","dot","dog","lot","log"]
# Output: 0
# Explanation: The endWord "cog" is not in wordList, therefore there is no
# possible transformation.
#
#
#
# Constraints:
#
#
# 1 <= beginWord.length <= 10
# endWord.length == beginWord.length
# 1 <= wordList.length <= 5000
# wordList[i].length == beginWord.length
# beginWord, endWord, and wordList[i] consist of lowercase English letters.
# beginWord != endWord
# All the strings in wordList are unique.
#
#
#
# @lc code=start
from collections import deque
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if not beginWord or len(beginWord) == 0 or \
not endWord or len(endWord) == 0 or \
not wordList or len(wordList) == 0 or \
len(beginWord) != len(endWord) or \
endWord not in wordList:
return 0
wordList = set(wordList)
word_queue = deque([beginWord])
seen = set([beginWord])
steps = 1
while word_queue:
size = len(word_queue)
for _ in range(size):
curr_word = word_queue.popleft()
if curr_word == endWord:
return steps
next_words, wordList = self._gen_new_words(curr_word, wordList)
for next_word in next_words:
if next_word not in seen:
word_queue.append(next_word)
seen.add(next_word)
steps += 1
return 0
def _gen_new_words(self, curr_word, wordList):
new_words = []
for i in range(len(curr_word)):
for code in 'abcdefghijklmnopqrstuvwxyz':
if curr_word[i] == code:
continue
tmp_word = curr_word[:i] + code + curr_word[i + 1:]
if tmp_word in wordList:
new_words.append(tmp_word)
wordList.remove(tmp_word)
return new_words, wordList
# @lc code=end
|
375249bae94bbbabb1080df93aab447ce4c0c5f9 | danish45007/Code-Algo-DS | /Random/Data_Stack.py | 1,280 | 4.09375 | 4 | """LIFO (Last in First out)
Methods:
-> Push
-> PoP
-> Peek
-> Size
-> IsEmpty
"""
class Stack(object):
def __init__(self):
self.items = []
def push(self, item):
"""Push the Element at the last
:return : None
"""
self.items.append(item)
def pop(self):
"""Pop the last element
:return: Last element for each call
"""
self.items.pop()
def peek(self):
"""return: the last element for each stack
"""
if len(self.items) > 0:
return self.items[-1]
else:
return "Stack is Empty"
def size(self):
"""Gives the size of the stack(no. of elements)
:return : int
"""
if len(self.items) > 0:
return(len(self.items))
def isEmpty(self):
"""Give the info is Stack empty or not
:return: True or Flase
"""
if len(self.isEmpty) > 0:
return True
else:
return False
def Print(self):
return self.items
if __name__ == "__main__":
s = Stack()
s.push("1")
s.push("2")
s.push("3")
print(s.size())
s.pop()
print(s.size())
print(s.Print())
|
f7ccdf311908e21eccbdf89894c847c85a0cdd69 | kyawphyoaung/JCU-Programming-Subj-Tutorial-Exercises | /prac_02/word_generator.py | 1,480 | 4.15625 | 4 | """
CP1404/CP5632 - Practical
Random word generator - based on format of words
Another way to get just consonants would be to use string.ascii_lowercase
(all letters) and remove the vowels.
"""
import random
VOWELS = "aeiou"
CONSONANTS = "bcdfghjklmnpqrstvwxyz"
ALPHABET = "abcdefghijclmnpqrstuvwxyz"
def auto():
word_format = "ccvcvvc"
word = ""
for kind in word_format:
if kind == "c":
word += random.choice(CONSONANTS)
else:
word += random.choice(VOWELS)
print(word)
def manual():
# user_format mean word format from user
user_format = input("Enter the word format :")
# validating user input
lowerword = user_format.lower()
word = ""
for kind in lowerword:
if kind == "c":
word += random.choice(CONSONANTS)
else:
word += random.choice(VOWELS)
print(word)
def wildcard():
# user_format mean word format from user
user_format = input("Enter the word format with special:")
# validating user input
lowerword = user_format.lower()
word = ""
for kind in lowerword:
if kind == "%":
word += random.choice(CONSONANTS)
elif kind == "#":
word += random.choice(VOWELS)
elif kind == "*":
word += random.choice(ALPHABET)
elif kind in ALPHABET:
word += kind
else:
print("Invalid Input")
print(word)
# auto()
# manual()
wildcard()
|
9ceacbb23c4c135079670719ff7939e3fb76c630 | frankiegu/python_for_arithmetic | /力扣算法练习/day100-二叉搜索树中第K小的元素.py | 1,902 | 3.609375 | 4 | # -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# Name: day100-二叉搜索树中第K小的元素
# Author: xin
# Date: 2019/6/12
# IDE: PyCharm
# -------------------------------------------------------------------------------
# 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
#
# 说明:
# 你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
#
# 示例 1:
#
# 输入: root = [3,1,4,null,2], k = 1
# 3
# / \
# 1 4
# \
# 2
# 输出: 1
# 示例 2:
#
# 输入: root = [5,3,6,2,4,null,null,1], k = 3
# 5
# / \
# 3 6
# / \
# 2 4
# /
# 1
# 输出: 3
# 进阶:
# 如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数?
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#解法一:
class Solution:
def kthSmallest(self, root, k):
def gen(r):
if r is not None:
yield from gen(r.left)
yield r.val
yield from gen(r.right)
it = gen(root)
for _ in range(k):
ans = next(it)
return ans
#解法二:
# class Solution(object):
# def kthSmallest(self, root, k):
# """
# :type root: TreeNode
# :type k: int
# :rtype: int
# """
# arr = []
# self.get_tree_arr(root, arr)
# # print(arr)
# return arr[k - 1]
#
# def get_tree_arr(self, root, arr):
# if root is None:
# return
# self.get_tree_arr(root.left, arr)
# arr.append(root.val)
# self.get_tree_arr(root.right, arr)
|
f970f2e9eaa71e62c1fb6ab6c0079f912a26c40a | Susmitha0211/ChatBot | /myBot.py | 5,738 | 3.71875 | 4 | import random
from datetime import datetime
def Greet_n_intro():
print("Hi ! I am Knowledge Bot.")
print( "I can help you to know the details like Capital, language, most popular places of respective States in India. ")
def get_timeofday():
current_time = datetime.now()
timeofday_greeting = "Good morning"
if current_time.hour > 12 and current_time.hour<=17:
timeofday_greeting = "Good Afternoon"
elif current_time.hour > 17 and current_time.hour<=22:
timeofday_greeting = "Good evening"
elif current_time.hour > 22:
timeofday_greeting = "Hi, That's late"
return timeofday_greeting
def welcome():
name=input("Enter your sweet name:")
messages = [
"Nice to meet you!"+" "+name,
"Good to see you!"+" "+name
]
print (get_timeofday())
print(random.choice(messages))
print()
def show_choices():
print("The tasks that can be done by me....")
print("1.Do you Want to know about details of respective states ?")
print("2.Now its time to quit this chat.")
print()
def choice_selection():
try:
return int(input("Enter your choice : "))
except:
print("Invalid, I didn't get you. ")
def show_states():
print()
print("1: Andhra Pradesh, 2: Arunachal Pradech, 3: Assam, 4: Bihar, 5: Cchattisgarh, 6: Goa, 7: Gujarat, 8: Haryana, 9: Himachal Pradesh, 10: JharKand ")
print("11: Karnataka, 12: Kerala, 13: Madhyapradesh, 14: Maharashtra, 15: Manipur, 16: Meghalaya, 17: Mizoram ,18: Nagaland ,19: Odisha ,20: Punjab ")
print("21: Rajasthan, 22: Sikkim, 23:Tamil nadu, 24: Telangana, 25: Tripura, 26: Uttar Pradesh, 27: Uttarakhand, 28: West Bengal, 29: Jammu & kashmir")
print()
def States_in_India(select):
details = {
1: "Andhra Pradesh - Capital: Visakapatnam(Executive), Amaravathi(legislative), karnool(Judiciary) - language: Telugu - Most popular place: Tirupathi.",
2: "Arunachal Pradesh - Capital: Itanagar - language: English - Most popular place: Ziro valley." ,
3: "Assam - Capital: dispur - language: Assamese - Most popular place: Kaziranga National Park.",
4: "Bihar - Capital: Patna - language: Hindi - Most popular place: Bodh Gaya.",
5: "Cchattisgarh - capital: Naya Raipur -language: Hindi- Most popular place: Chitrakote Waterfalls.",
6: "Goa - capital: Panaji - language: konkani - Most popular place: Calangute Beach.",
7: "Gujarat - Capital: Gandhinagar - language: Gujarati - Most popular place: Gir National Park.",
8: "Haryana - Capital: Chandigarh - language: Hindi - Most popular place: Firoz Shah Palace.",
9: "Himachal Pradesh - Capital: Shimla(summer), Dharmashala(winter) - language: Hindi - Most popular place: Manali.",
10: "JharKand - Capital: Ranchi - language: Hindi - Most popular place: Dassam Falls.",
11: "Karnataka - Capital: Bangalore - language: Kannada - Most popular place: Bannerghatta National Park.",
12: "Kerala - Capital: Tiruvananthapuram - language: Malayalam - Most popular place: Athirapally Vazhachal Waterfalls.",
13: "Madhyapradesh - Capital: Bhopal - language: Hindi - Most popular place: Pachmarhi.",
14: "Maharashtra - Capital: Mumbai(Summer),Nagpur(Winter) - language: Marathi - Most popular place: Ajanta Caves.",
15: "Manipur - Capital: Imphal - language: Meitei - Most popular place: Loktak Lake.",
16: "Meghalaya - Capital: Shillong - language: English - Most popular place: Seven Sisters Waterfalls.",
17: "Mizoram - Capital: Aizwal - language: Mizo - Most popular place: Blue National Park.",
18: "Nagaland - Capital: Kohima - language: English - Most popular place: Naga Hills.",
19: "Odisha - Capital: Bhubaneshwar - language: Odia - Most popular place: Chilika Lake.",
20: "Punjab - Capital: Chandigarh - language: Punjabi - Most popular place: Golden Temple.",
21: "Rajasthan - Capital: Jaipur - language: Hindi - Most popular place: Hawa Mahal.",
22: "Sikkim - Capital: Gangtok - Language: Nepali - Most popular place: Rumtek Monastery.",
23: "Tamil nadu - Capital: Chennai - language: Tamil - Most popular place: Rameshwaram.",
24: "Telangana - Capital: Hyderabad - language: Telugu - Most popular place: Golconda Fort.",
25: "Tripura - Capital: Agarthala - language: Bengali and Kokborok - Most popular place: Ujjayanta Palace.",
26: "Uttar Pradesh - Capital: Lucknow - language: Hindi - Most popular place: Taj Mahal.",
27: "Uttarakhand - Capital: Gairsain(Summer),Dehradun(Winter) - language: Hindi - Most popular place: Mussoorie.",
28: "West Bengal - Capital: Kolkata - language: Bengali,nepali - Most popular place: Victoria Memorial.",
29: "Jammu & kashmir - Capital: Srinagar -language: Dogri - Most popular place: Pahalgam."
}
print(details.get(select, "Please select from above numbers "))
def Knowledgebot():
Greet_n_intro()
get_timeofday()
welcome()
show_choices()
choice=choice_selection()
while choice !=2:
if choice == 1 :
show_states()
try:
select=int(input("Enter the number of corresponding State: "))
print(States_in_India(select))
except:
print("Enter only integers")
else:
print("Please enter numbers 1 or 2")
print("Would you like to know the details of any other states?")
print()
show_choices()
choice=choice_selection()
Knowledgebot()
|
cc5d7806a42e448b1fd1d11858719e8e68cd7c59 | Vattikondadheeraj/python | /1.py | 611 | 3.921875 | 4 | class Sample:
def setstudent(self):
self.name=input("enter the name")
self.no=int(input("enter the number"))
self.dob=self.dob()
self.dob.setdob()
def getstudent(self):
print(self.name,self.no)
self.dob.getdob()
class dob:
def setdob(self):
self.date=int(input("enter the date"))
self.month=int(input("enter the month"))
self.year=int(input("enter the year"))
def getdob(self):
print("{}-{}-{}".format(self.date,self.month,self.year))
s=Sample()
s.setstudent()
s.getstudent() |
7012b03855fd409adee39dc771c33d1ed614b0b3 | Tsugunni/pj_algorithm_python | /python_algorithms/sort/heap_sort.py | 1,310 | 3.578125 | 4 | # pattern1
from heapq import heappush
from heapq import heappop
def linked_heap_sort(nums: list) -> list:
heap = []
while nums:
heappush(heap, nums.pop())
while heap:
nums.append(heappop(heap))
return nums
# pattern2
def heap_sort(nums: list) -> list:
heapify(nums)
index = len(nums) - 1
while index:
nums[0], nums[index] = nums[index], nums[0]
_siftup(nums, 0, index)
index = index - 1
nums.reverse()
return nums
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if newitem < parent:
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos, endpos):
startpos = pos
newitem = heap[pos]
childpos = 2 * pos + 1
while childpos < endpos:
rightpos = childpos + 1
if rightpos < endpos and not heap[childpos] < heap[rightpos]:
childpos = rightpos
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
heap[pos] = newitem
_siftdown(heap, startpos, pos)
def heapify(x):
n = len(x)
for i in reversed(range(n // 2)):
_siftup(x, i, n)
|
9ea375160a788fe99be5d6950b1b723aae858db8 | guillaume-gomez/basics-python | /variables.py | 616 | 4.0625 | 4 | myint = 7
print(myint)
myfloat = 7.0
print(myfloat)
myfloat = float(7)
print(myfloat)
mystring = 'hello'
print(mystring)
mystring = "hello"
print(mystring)
mystring = "Don't worry about apostrophes"
print(mystring)
one = 1
two = 2
three = one + two
print(three)
hello = "hello"
world = "world"
helloworld = hello + " " + world
print(helloworld)
# Assignments can be done on more than one variable "simultaneously" on the same line like this
a, b = 3, 4
print(a,b)
# Mixing operators between numbers and strings is not supported:
# This will not work!
one = 1
two = 2
hello = "hello"
print(one + two + hello) |
095d7d713c0fa69ca663e4bfac17b09d9d1f97c7 | leledada/LearnPython | /test_code/20180327-6-11test.py | 401 | 4.125 | 4 | # 用符号的组合在控制台输出不同大小的矩形图案。
# 要求:写一个输出矩形的函数,该函数拥有三个默认参数,矩形的长5、宽5和组成图形的点的符号“*”,为函数添加不同的参数,输出三个不同类型的矩形;
def myRact(l=5, h=5, p='*'):
for i in range(l):
print(p * h)
myRact()
myRact(4, 3, '#')
myRact(2, 6, "!")
|
0acb259955ba1e5271e83530c1edc186e5afdbd3 | JasonMuscles/All | /Chapter_04/wjs_02_(4.3.4)_summary.py | 1,359 | 3.75 | 4 | # Page-54(4-3)
# 使用一个for循环打印数字一到20(含20)。
# for num in range(1, 21):
# print(num)
# Page-54(4-4)
# 一百万:创建一个列表,其中包含数字1到1,000,000在使用一个或循环,将这些数字打印出来。
# numbers = []
# for value in range(1, 1000001):
# numbers.append(value)
# print(numbers)
# Page-54(4-5)
# 计算1到1,000,000的总和。
# numbers = []
# for value in range(1, 1000001):
# numbers.append(value)
# print(sum(numbers))
# Page-54(4-6)
# 通过给函数range指定第3个参数来创建一个列表,其中包含1到20的奇数,在使用一个或循环中,这些数字都打印出来。
# for c in range(1, 21, 2):
# print(c)
# 3的倍数创建一个列表,其中包含3到30名能被三整除的数字,在使用一个或循环将这些列表中的数字都打印出来。
# for c in range(3, 31, 3):
# print(c)
# 立方:将同一个数字乘以3次成为立方,请创建一个列表,其中包含前10个整数,即到10的立方在使用一个或循环,将这些地方都打印出来。
# cube = []
# for values in range(1, 11):
# cube = values ** 3
# print(cube)
# 立方解析:使用列表解析生成一个列表,其中包含前10个整数的立方。
lists = [values ** 3 for values in range(1, 11)]
print(lists)
|
36b848696a214828c71f7e10fc2441a3cc23b5d2 | Imsid64/Siddharth | /siddha.py | 301 | 4.21875 | 4 | #!/usr/bin/python3
# guess what this program does????
import random
r=random.randint(23,49) # gives random num
print(r)
if r<35:
print(r)
print(":is less than 35")
elif r==30:
print("30 is multiple of 10 and 3,both")
elif r>=35:
print(r,"is greater than 35")
else:
print("your nnumber is:",r)
|
43de3ffab70f9b1f95982e49d2b62dd503e85773 | emilianoNM/Tecnicas3 | /bubbleSort&StackIsraelFP/bubbleSort.py | 468 | 4 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 10 17:24:35 2018
@author: israel
"""
#MergeSort to TECNICAS 3
def bubbleSort(A):
for i in range(1,len(A)+1):
for j in range(len(A)-1):
if A[j]>A[j+1]:
tmp=A[j]
A[j]=A[j+1]
A[j+1]=tmp
return A
list=["Juan","Carlos","Estefania","Alejandro","Cesia"]
print "Lista original: ",list
print "Lista ordenada: \n",bubbleSort(list) |
ed4cf65c105cfb246b15be6b47cd78f92dcbe180 | withchristopher/Tutorials_2015 | /tut_convolution.py | 473 | 3.546875 | 4 | #Tutorial 4, Convolution
import numpy
from numpy.fft import fft,ifft
from matplotlib import pyplot as plt
#Function
def conv(x,i=0):
vector=x*0
vector[i]=1
fourierft=fft(vector)
xft=fft(x)
return numpy.real(ifft(xft*fourierft))
if __name__=='__main__':
#Variables
x= numpy.arange(-20,20,0.1)
s=2
y= numpy.exp(-0.5*x**2/(s**2))
N=y.size
#Shift
yshift = conv(y,N/2)
plt.ion()
plt.plot(x,y)
plt.plot(x,yshift)
|
6f0b7f8f8b494d41f541ccb9c5442606e3a66e87 | CILIWFES/MyPythonStudy | /Numpy/matrix.py | 3,144 | 3.546875 | 4 | import numpy as np
myZero = np.zeros([5, 6]) # 生成一个5x6的矩阵,初始值为0
print(type(myZero))
print(myZero)
myOnes = np.ones([5, 4]) # 生成一个5x4的矩阵,初始值为1
print(type(myOnes))
print(myOnes)
myRand = np.random.rand(5, 4) # 生成一个5x4的矩阵,初始值为随机值,(0~1)
print(type(myRand))
print(myRand)
myEye = np.eye(5) # 生成5x5单位矩阵
print(type(myEye)) # <class 'numpy.ndarray'>
print(myEye)
# list转化为矩阵
testList = [[1, 2, 3, 4, 5], [1, 5, 7, 8, 9], [1, 4, 7, 8, 5], [1, 2, 2, 2, 2], [2, 1, 5, 3, 6]]
myMatrix = np.mat(testList)
print(type(myMatrix)) # <class 'numpy.matrixlib.defmatrix.matrix'>
print(myMatrix)
print()
print("""矩阵操作""", end='\n\n')
# 矩阵数加
print(6 + myEye)
# 矩阵相加
print(myOnes + myRand)
# print(myOnes+myEye)#相加失败,行列数不一致
# 矩阵数乘
print(10 * myRand)
# 矩阵求和(逐个列向量求和)
print(np.sum(myRand))
print(np.sum(myMatrix))
print(np.sum(myEye))
# 矩阵乘积
myMatrix1 = np.eye(5)
myMatrix2 = np.random.rand(5, 5)
print(myMatrix2)
print(2 * myMatrix1 * myMatrix2)
# 两个类型相同的矩阵乘积,最后类型还是对于矩阵
print(type(2 * myMatrix1 * myMatrix2)) # <class 'numpy.ndarray'>
print(myMatrix * myMatrix1)
# 两个类型不同的矩阵乘积类型是下列矩阵
print(type(myMatrix * myMatrix1)) # <class 'numpy.matrixlib.defmatrix.matrix'>
# 矩阵中各个元素乘积
print(myMatrix)
print(np.multiply(myMatrix, myMatrix))
print(np.multiply(myMatrix, myMatrix1))
# 矩阵的n次幂
print(myMatrix)
print(np.power(myMatrix, 3))
# 矩阵的转置
print(myMatrix)
print(myMatrix.T)
print(myMatrix.transpose())
print(np.random.rand(5, 3).transpose())
print(end="\n\n")
# 矩阵的操作
print(myMatrix)
print(myMatrix)
[m, n] = np.shape(myMatrix)
print("矩阵的行数与列数:", m, n)
print("按行切片:", myMatrix[2])
print("按列切片:", myMatrix.T[2])
# 矩阵元素比较
print(myMatrix1 > myMatrix)
# 复制矩阵
tempMatrix = myMatrix.copy()
print(tempMatrix == myMatrix)
print(id(tempMatrix) == id(myMatrix))
# 矩阵的合并
tempMatrix = np.append(myMatrix, np.random.rand(1, 5), 0) # 为myMatrix添加一行
print(tempMatrix)
tempMatrix = np.append(myMatrix, np.random.rand(5, 1), 1) # 为myMatrix添加一列
print(tempMatrix)
# 矩阵的删除
print(myMatrix)
tempMatrix = np.delete(myMatrix, [1, 2, 3], 0) # 删除myMatrix的第2,3,4行
print(tempMatrix) # 删除后的矩阵
print(myMatrix) # 删除前的矩阵
tempMatrix = np.delete(myMatrix, 2, 0) # 删除myMatrix的第三行
print(tempMatrix)
print(myMatrix) # 删除前的矩阵
tempMatrix = np.delete(myMatrix, 1, 1) # 删除myMatrix的第三列
print(tempMatrix)
#矩阵的行列式
print(myMatrix)
print(np.linalg.det(myMatrix))
#矩阵的逆矩阵
print(np.linalg.inv(myMatrix))
print(myMatrix*np.linalg.inv(myMatrix))
#矩阵的对称
print(myMatrix)
print(myMatrix*myMatrix.T)
#矩阵的秩
print(np.linalg.matrix_rank(myMatrix))
#可逆矩阵求解
y=[0,0,0,0,5]
print(np.linalg.solve(myMatrix,y))
print(sum(np.multiply(myMatrix,np.linalg.solve(myMatrix,y)).T)) |
31b77440bf986e8d65f81a645bcbb5a580a88001 | ivanychev/githubers | /src/download_users.py | 1,322 | 3.796875 | 4 | #!/usr/bin/env python3
"""
Downloads users data from github.com and stores it in SQLite database. The path of
DB is stored in config file.
Version: 0.2
Author: Sergey Ivanychev
"""
import sys
import config
import githubers as g
CONFIG_PATH = "../resources/config.json"
def check_args(argv):
"""
Validates `main()` input arguments
:param argv: program arguments
:return: True/False
"""
if len(argv) != 3:
print("Github login and password are expected as script parameters")
return False
return True
def main(argv):
"""
Connects to the database/creates one if there's no DB. Downloads all
users of GitHub and stores the data in the DB.
Usage:
```
python3 download_users.py <username> <password>
```
:param argv: input arguments
:return: nothing
"""
if not check_args(argv):
return -1
login, password = argv[1], argv[2]
db_path = config.read_config(CONFIG_PATH)
conn = g.connect_db(db_path)
cursor = conn.cursor()
max_id = g.max_user_id(conn)
for user_tuple in g.remote_users(login, password, since_id=max_id):
g.add_user(cursor, user_tuple)
conn.commit()
print("added {}:{}".format(user_tuple.UserID, user_tuple.Login))
if __name__ == "__main__":
sys.exit(main(sys.argv))
|
99bf0cf32d83b9905ee8e5f3c607cff1529d1723 | mitrofanov-m/6_sem_labs | /2l_AVL_map/AVLTree.py | 5,628 | 3.59375 | 4 |
class Node:
def __init__(self, item):
self.item = item
self.left = None
self.right = None
# thanks to groupmate for this feature
def __str__(self):
return self.diagram(self, "", "", "")
def diagram(self, node, top, root, bottom):
if node is None:
return root + "nil\n"
if node.left is None and node.right is None:
return root + " " + str(node.item) + "\n"
return self.diagram(node.right, top + " ", top + "┌──", top + "│ ") + \
root + str(node.item) + "\n" + \
self.diagram(node.left, bottom + "│ ", bottom + "└──", bottom + " ")
class BinaryTree:
def __init__(self, Node=Node):
self.__root = None
self.__count = 0
self.__Node = Node
def __str__(self):
return str(self.__root)
def __len__(self):
return self.__count
def __contains__(self, item):
if self._get_node_by_item(self.__root, item) is None:
return False
return True
def __iter__(self):
if self.__root is not None:
for item in self._in_order(self.__root):
yield item
# Public Methods Section #
def is_empty(self):
return self.__root is None
def insert(self, item):
self.__root = self._insert_in(self.__root, item)
def remove(self, item):
if item in self:
self.__count -= 1
self.__root = self._remove(item, self.__root)
return True
return False
def remove_all(self):
self.__root = self._post_order_removing(self.__root)
self.__count = 0
# Private Methods Section #
def _insert_in(self, node, item):
if node is None:
self.__count += 1
return self.__Node(item)
elif item < node.item:
node.left = self._insert_in(node.left, item)
else:
node.right = self._insert_in(node.right, item)
return node
def _get_node_by_item(self, node, item):
""" Used in __contains__ """
if node is None:
return None
elif item < node.item:
return self._get_node_by_item(node.left, item)
elif item > node.item:
return self._get_node_by_item(node.right, item)
else:
return node
def _remove(self, item, node):
if node is None:
return None
if item == node.item:
if node.left is None:
return node.right
elif node.right is None:
return node.left
child = node.left
while child.right:
child = child.right
node.item = child.item
node.left = self._remove(node.item, node.left)
elif item < node.item:
node.left = self._remove(item, node.left)
else:
node.right = self._remove(item, node.right)
return node
def _in_order(self, node):
if node.left:
for item in self._in_order(node.left):
yield item
yield node.item
if node.right:
for item in self._in_order(node.right):
yield item
def _post_order_removing(self, node):
if node is not None:
node.left = self._post_order_removing(node.left)
node.right = self._post_order_removing(node.right)
node.item = None
return None
class AVLNode(Node):
def __init__(self, item):
super().__init__(item)
self.height = 0
class AVLTree(BinaryTree):
def __init__(self):
super().__init__(AVLNode)
# Public Methods Section #
def get_height(self):
return self._get_height(self._BinaryTree__root)
# Private Methods Section #
def _insert_in(self, node, item):
node = super()._insert_in(node, item)
# append balancing of node that is returned
return self._balanced(node)
def _remove(self, node, item):
node = super()._remove(node, item)
# append balancing of node that is returned
if node is not None:
return self._balanced(node)
def _get_height(self, node):
if node is None:
return -1
return node.height
def _refresh_height(self, node):
return 1 + max(self._get_height(node.left),
self._get_height(node.right))
def _right_rotate(self, node):
pivot = node.left
node.left = pivot.right
pivot.right = node
node.height = self._refresh_height(node)
pivot.height = self._refresh_height(pivot)
return pivot
def _left_rotate(self, node):
pivot = node.right
node.right = pivot.left
pivot.left = node
node.height = self._refresh_height(node)
pivot.height = self._refresh_height(pivot)
return pivot
def _get_balance(self, node):
if node is None:
return 0
return self._get_height(node.right) - self._get_height(node.left)
def _balanced(self, node):
if self._get_balance(node) == 2:
if self._get_balance(node.right) == -1:
node.right = self._right_rotate(node.right)
return self._left_rotate(node)
elif self._get_balance(node) == -2:
if self._get_balance(node.left) == 1:
node.left = self._left_rotate(node.left)
return self._right_rotate(node)
else:
node.height = self._refresh_height(node)
return node
|
9196cec6298cfd16d70709fc1021e70043ae0bbd | frownytown/cs21a | /account.py | 1,168 | 4.1875 | 4 | class Account(object):
"""
Represent a bank account.
Argument:
account_holder (string): account holder's name.
Attributes:
holder (string): account holder's name.
balance (float): account balance in dollars.
"""
def __init__(self, account_holder):
self.holder = account_holder
self.balance = 0
def __str__(self):
return self.holder + ':$' + str(self.balance)
def deposit(self, amount):
"""
deposit the amount to the account.
:param:
amount (float): the amount to be deposited in dollars.
:return:
the updated account object.
"""
self.balance += amount
return self
def withdraw(self, amount):
"""
withdraw the amount from the account if possible.
:param amount:
amount (float): the amount to be withdrawn in dollars.
:return:
boolean: True if the withdrawal is successful
"""
if self.balance >= amount:
self.balance = self.balance - amount
return True
else:
return False
|
48d2a44ccda408625d6e3135e639fde3b6f29d56 | Not-Aryan/42Stuff | /ML-4/BMW-Classifier.py | 1,551 | 3.875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
#Preparing the data
dataset = pd.read_csv('/nfs/2020/a/ajain/PycharmProjects/MachineLearning/ML-4/previous_users_dataset.csv')
X = dataset['Age'].values.reshape(-1, 1)
y = dataset['EstimatedSalary'].values.reshape(-1, 1)
scaler = MinMaxScaler(feature_range=(-2,3))
X = scaler.fit_transform(X)
y = scaler.fit_transform(y)
X = X.astype('float')
y = y.astype('float')
plt.title('Logistical Regression(Test Set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
#Now performing the logistic regression
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
logisticRegr = LogisticRegression()
logisticRegr.fit(X_train.astype('int'), y_train.ravel().astype('int'))
#Feature scaling is done after training cause it only accepts int values and this makes them floats
# scaler = MinMaxScaler(feature_range=(-2,3))
# X_test = scaler.fit_transform(X_test)
# y_test = scaler.fit_transform(y_test)
#Predicting
y_pred = logisticRegr.predict(X_test.astype('int'))
df = pd.DataFrame({'Actual': y_test.flatten(), 'Predicted': y_pred.flatten()})
print(df)
score = logisticRegr.score(X_test.astype('int'), y_test.astype('int'))
print('Score', score)
parameters = logisticRegr.coef_
plt.scatter(X_test, y_test, color='red')
# plt.plot(X_test, y_pred, color='blue', linewidth=2)
plt.show()
|
702c3dd020a000d985bf3aa829b72d910f44f261 | zzwshow/python | /learn_python/正则表达式.py | 3,245 | 3.734375 | 4 | #coding=utf-8
import re
#findall()可以将匹配到的结果以列表的形式返回,如果匹配不到则返回一个空列表
def re_method():
s1='Hello this is joey'
s2='The first price is $9.90 and the second price is $100'
print(re.findall(r'\w',s1)) #[a-z-A-Z-0-9]
print(re.findall(r'\d+\.?\d*',s2))
#finditer() 可以将匹配到的结果生成一个迭代器
def re_method1():
s2='The first price is $9.90 and the second price is $100'
s = re.finditer(r'\d+\.?\d*',s2)
for i in s:
print(i.group()) #
#search() 是匹配整个字符串直到匹配到一个就返回
def re_demo():
txt='If you puchase more than 100 sets, the price of product A is $9.90.'
m = re.search(r'(\d).*\$(\d+\.?\d*)',txt)
print(m.groups())
#match从要匹配的字符串的开头开始,尝试匹配,如果字符串开始不符合正则表达式,则匹配失败,
# 函数返回None,匹配成功的话用group取出匹配的结果
def re_method2():
s='abcdc'
print(re.search(r'c',s)) #seach是从头到尾的匹配 第一个匹配
print(re.search(r'^c',s)) #匹配开头为c 没有匹配到返回None
print(re.match(r'c',s)) #相当于^c开头匹配 没有匹配到返回None
print(re.match(r'.*c',s))
def re_method_object():
s1='Joey Huang'
m = re.match(r'(.*?) (\w+)',s1)
print(m.group(1,2))
print(m.groups())
#split能够将匹配的子串分割后返回列表
def re_method_split():
s1='This is joey Huang'
print(re.split(r'\W',s1))
#re.sub()、re.subn()
#sub能将匹配到的字段用另一个字符串替换返回替换后的字符串,
# subn还返回替换的次数
def re_method3():
s2='The first price is $9.90 and the second price is $100'
print(re.sub(r'\d+\.?\d*','<number>',s2,1))# 还能指定替换的次数 这里是1次
print(re.subn(r'\d+\.?\d*','<price>',s2))
#if __name__ == "__main__":
#re_method()
#re_method1()
#re_demo()
#re_method2()
#re_method_object()
#re_method_split()
#re_method3()
#re的flags标识位
def re_pattern_syntax():
# .表示任意单一字符
# *表示前一个字符出现>=0次
# re.DOTALL就可以匹配换行符\n,默认是以行来匹配的
print(re.match(r'.*', 'abc\nedf').group())
print('*' * 80)
print(re.match(r'.*', 'abc\nedf', re.DOTALL).group())
if __name__ == '__main__':
re_pattern_syntax()
#小例
# print(re.match('www','www.baidu.com').span()) #从字符串开头开始匹配 返回匹匹配的字符串跨度
#
# print(re.match('www','www.baidu.com')) #匹配成功返回匹配对象
# print(re.match('com','www.baidu.com')) #文件开头没有匹配成功,返回None
#
# print(re.search('www','www.baidu.com').span())
# print(re.search('com','www.baidu.com').span())
# #re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,
# # 函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
#
# phone='18839399820 ¥这个号码值5元'
# print(re.sub(r'¥.*$','',phone))#将¥符号后所有字符替换为空‘’
# print(re.sub(r'\D','',phone)) #将非数字的替换为空!
# # answer:
# # 18839399820
# # 188393998205
#
#
# #
|
bf440d9605de2227ab19e0bb2d23ab276c571492 | srinaveendesu/Programs | /leetcode/day10.py | 990 | 3.609375 | 4 | # https://leetcode.com/problems/intersection-of-two-linked-lists/submissions/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
l1 = 1
l2 = 1
p1 = headA
p2 = headB
while p1.next is not None:
l1 += 1
p1 = p1.next
while p2.next is not None:
l2 += 1
p2 = p2.next
# print(l1, l2)
if p1 is not p2:
return None
p1 = headA
p2 = headB
if l1 > l2:
rem = l1 - l2
for i in range(rem):
p1 = p1.next
elif l2 > l1:
rem = l2 - l1
for i in range(rem):
p2 = p2.next
# print(p1, p2)
while p1 is not p2:
p1 = p1.next
p2 = p2.next
return p1 |
71e3d1d9f9031dc55080d9576c9c75f5ee6f2264 | andyc010/JIRA_list_string | /JIRA_list_string.py | 835 | 3.6875 | 4 | class jiraListString():
separator = ""
itemList = ""
def __init__(self, separator, itemList):
self.separator = separator
self.itemList = itemList
def __init__(self):
pass
def add_separator_text(self, separator, itemList):
long_string = ''
if len(itemList) > 1:
for item in itemList:
if item == itemList[-1]:
# add the last item to the string
long_string += str(item)
else:
# add the item and the separator string
long_string += str(item) + str(separator)
return long_string
# if only one item is in the list, just display it
elif len(itemList) == 1:
return itemList[0]
else:
return None
|
6ca37ec3083f26907c30e406451c862fbc6044e8 | mgaravindsai/Python-Projects | /search.py | 2,077 | 3.71875 | 4 | import timeit
class search:
def __init__(self,target,num):
self.nums = num
self.target = target
def squentical_search_unsorted(self):
found = False
pos = 0
while pos < len(self.nums) and not found:
if self.nums[pos] == self.target:
found = True
else:
pos+=1
return found
def squentical_search_sorted(self):
nums = self.nums
found = False
stop = False
pos = 0
while pos < len(nums) and not found and not stop:
if nums[pos] == self.target:
found = True
else:
if nums[pos] > self.target:
stop = True
else:
pos+=1
return found
def Binary_search(self,nums=[]):
if nums==[]:
nums = self.nums
if len(nums)==0:
return False
midpoint = len(nums)//2
if nums[midpoint]==self.target:
return True
elif self.target<midpoint:
return self.Binary_search(nums[:midpoint])
elif self.target>midpoint:
return self.Binary_search(nums[midpoint+1:])
########################################################################################################
t1 = timeit.Timer("Search.squentical_search_unsorted()","from __main__ import Search")
Search = search(13,[1, 2, 32, 8, 17, 19, 42, 13, 0])
for i in range(10):
x = t1.timeit(number=1000)
print(x)
print()
########################################################################################################
t2= timeit.Timer("Search_sorted.squentical_search_sorted()","from __main__ import Search_sorted")
Search_sorted = search(13,[0, 1, 2, 8, 13, 17, 19, 32, 42])
for j in range(10):
y = t2.timeit(number=1000)
print(y)
print()
########################################################################################################
Binary = search(0,[0, 1, 2, 8, 13, 17, 19, 32, 42])
print(Binary.Binary_search())
|
def6d91a7daa99a060147d43c9b9470c2d8052c7 | arizala13/CTCI_Problems | /2.2.py | 1,686 | 4.40625 | 4 | # This is question 2.2 of CTCI
# ------ Notes to myself ----------
# Write an algorithm to find the kth to the last
# element of a singly linked list
# Original solution from: https://www.geeksforgeeks.org/nth-node-from-the-end-of-a-linked-list/
# Time complexity: O(n) where n is the length of linked list.
# Space complexity:
# finds the nth node from end
# Class node creates the Nodes themselves
#
class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
# class LinkedList
class LinkedList:
def __init__(self):
self.head = None
# createNode and and make linked list
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Function to get the nth node from
# the last of a linked list
def print_nth_from_last(self, n):
temp = self.head # used temp variable
length = 0
while temp is not None:
temp = temp.next
length += 1
# print count
if n > length: # if entered location is greater
# than length of linked list
print('Location is greater than the' +
' length of LinkedList')
return
temp = self.head
for i in range(0, length - n):
temp = temp.next
print(temp.data)
# How do we get the kth element in a linked list?
# how do we count elements in linked list?
# can we count from the end in a linked list?
# Driver Code
test_list = LinkedList()
test_list.push(20)
test_list.push(4)
test_list.push(15)
test_list.push(33)
test_list.push(35)
test_list.print_nth_from_last(5)
|
ecf238ac50b04d66bf31d2efbc8682c16610fe87 | ds-5/ds | /hw_16_B_sypark.py | 2,661 | 3.5625 | 4 | def count_matches(some_list, value):
if some_list == [] : return 0
else :
if some_list[0] == value : return count_matches(some_list[1:], value) + 1
else : return count_matches(some_list[1:], value)
def double_each(some_list):
if some_list == [] : return some_list
else : return some_list[0:1]*2 + double_each(some_list[1:])
def sums_to(nums, k):
if nums == [] :
if k == 0 : return True
else : return False
else : return sums_to(nums[1:], k-nums[0])
def is_reverse(string1, string2):
if string1 == "" or string2 == "" :
if len(string1+string2) == 0 : return True
else : return False
elif string1[0] != string2[len(string2)-1] : return False
else : return is_reverse(string1[1:], string2[:len(string2)-1])
def sort_repeated(L) :
re_el = set()
new_el = set()
for el in L :
if el in new_el: re_el.add(el)
new_el.add(el)
return sorted(re_el)
def make_Dict_number(lst) :
make_dic = {}
for i in lst:
if i in make_dic.keys() : make_dic[i] += 1
else : make_dic[i] = 1
key_list = list(make_dic.keys())
for min in range(len(key_list)):
min_index = min
for i in range(min+1, len(key_list)):
if key_list[min_index] > key_list[i] : min_index = i
key_list[min_index], key_list[min] = key_list[min], key_list[min_index]
new_make_dic = {}
for key in key_list : new_make_dic[key] = make_dic[key]
return new_make_dic
#w/get
##def most_Frequent(lst) :
## #make_Dict_number
## make_dic = {}
## for i in lst:
## if i in make_dic.keys() : make_dic[i] += 1
## else : make_dic[i] = 1
##
## max_key = list(make_dic.keys())[0]
## max_freq = make_dic.get(max_key)
##
## for key in list(make_dic.keys()) :
## if max_freq < make_dic.get(key) :
## max_freq = make_dic.get(key)
## max_key = key
##
## return max_key
#wo/get
def most_Frequent(lst) :
#make_Dict_number
make_dic = {}
for i in lst:
if i in make_dic.keys() : make_dic[i] += 1
else : make_dic[i] = 1
max_key = list(make_dic.keys())[0]
max_freq = make_dic[max_key]
for key in list(make_dic.keys()) :
if max_freq < make_dic[key] :
max_freq = make_dic[key]
max_key = key
return max_key
def histogram(d) :
chg_dic = {}
value_list = list(d.values())
for v in value_list:
chg_dic[v] = value_list.count(v)
return chg_dic
|
4ea6719791838ed68a7f836235f271a22cb83c53 | julimorozova/Coursera_Python_programming_basics | /game.py | 507 | 4 | 4 | import random
number = random.randint(0, 101)
while True:
answer = input('Enter number ')
if not answer or answer == 'exit':
break
if not answer.isdigit():
print('Enter the correct number ')
continue
user_anser = int(answer)
if user_anser > number:
print('Our number is less')
elif user_anser < number:
print('Our number is bigger')
else:
print('Congratulations! You guessed the number', + number)
break
|
d6df1ba2694b85b3b583b9de9a22ff701c62b057 | NithinNitz12/ProgrammingLab-Python | /CO1/10_areaofcircle.py | 77 | 3.90625 | 4 | r = float(input("Enter the radius:"))
area = 3.14 * r * r
print("Area=",area) |
860df468f48f1e7b88927292d01c2cb54789b5ec | krrdms/ITP270Codes | /Scratch/week3/22Whilept1.py | 119 | 3.9375 | 4 | n = 5
while n > 0:
n -= 1
if n == 2: #notice that code returns before printing...
continue
print(n) |
8f7ecbf41ecad336f5d81fa722b4fbddd009aa67 | AlexiaAM/Python-Bootcamp | /Problems/pruebas.py | 238 | 3.90625 | 4 |
while True:
print("Who are you?")
name = str(input())
if name != "Alexia":
continue
print("Password: ")
password = str(input())
if password == "00":
break
print("Welcome to your computer Alexia")
|
54b3523bb359e46a956db9fad75e94ab1ae6ef68 | RanjitSolomon/python | /day8/greet.py | 305 | 3.9375 | 4 | from datetime import date, datetime
def greet(name, loc):
print(f"Hello {name} in {loc}")
print(f"Today's date is {date.today()} ")
print(f"Current date and time is {datetime.now()} ")
name = input("What is your name? \n")
location = input("What is your location? \n")
greet(name, location)
|
e7da9a776ddde9c8420522e459e55154f3204ee9 | ieesejin/algorithm_study | /programmers/위장.py | 526 | 3.734375 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/42578
def solution(clothes):
answer = 1
closet = {} # initial dictionary
for cloth, kind in clothes:
if kind not in closet: # if key is not in dict
closet[kind] = 1
else:
closet[kind] += 1
for value in closet.values(): # Multiply the number of clothes for each kind.
answer *= value + 1 # If you don't wear it, you have to add it.
answer -= 1 # Excludes the case of not wearing all.
return answer |
5a9827b316418f865d56c21043583aa49c6052e3 | brook1123/git | /4_3.py | 848 | 3.84375 | 4 | # error exception
# try:
# # with open('f.txt','r') as f:
# # for line in f:
# # x = int(line.strip())
# x = 5
# except FileNotFoundError as err:
# print('沒有檔案',err)
# except ValueError:
# print('資料錯誤')
# else:
# print('沒有錯誤')
# finally:
# print('不管有沒有錯最後定會執行')
# try:
# s = input('enter a number:')
# n = int(s)
# except ValueError:
# print('只能輸入數字')
# except NameError:
# print('名子錯誤')
err_count = 0
i = 0
while True:
try:
s = input('enter a number:')
n = int(s)
except ValueError:
err_count +=1
if err_count >= 3:
print('已經三次了')
break
print('錯了')
finally:
i=i+1
print(f'這是第{i}次玩')
|
e2a8b75443f11b63666b586ab22c4f5afb4316a4 | Teldrin89/DBPythonTut | /LtP5.py | 1,351 | 4.4375 | 4 | # Python functions allow us to re-use part of code
# This makes the overall code shorter and easier to understand
# Function example: simple function that adds two numbers
def add_numbers(num1, num2):
return num1 + num2
print("5 + 4 =", add_numbers(5, 4))
# Local variables - any variable created inside a
# function is a variable available only inside this function
# Global variable is created outside of any function
# Even if the global variable is passed inside the function
# it may not necessarily change
def change_name(name):
name = "Luke"
name = "Derek"
# Trying to change name using function and global var
change_name(name)
print(name)
# Didn't change the name
# To make it work is to assign return for a function
# so it would pass some value
def change_name2(name):
return "Luke"
# Assign a new name using function
name = change_name2(name)
print(name)
# It did change the name
# Another way to make it work is to refer
# inside a function a global variable
gbl_name = "Sally"
# The new function does not even need input variable
def change_name3():
# Reference to global variable set up before function
global gbl_name
gbl_name = "Sammy"
change_name3()
print(gbl_name)
# A function without return value would return none
def get_sum(num1, num2):
sum = num1 + num2
print(get_sum(5, 2))
|
c953b2072e5d44998f4a555f91f02792933a9944 | ijockeroficial/Python | /CursoEmVídeo/Mundo 2/Laços/While/fatorial.py | 133 | 4.125 | 4 | numero = int(input("Informe um número inteiro: "))
x = numero
fatorial = 1
while x > 0:
fatorial *= x
x -= 1
print(fatorial) |
10a92f0df7c81b24df058be6c1ec7e44aa77f14b | LucaMarino747/Conway | /Conway's Game of Life.py | 962 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 31 10:21:26 2020
@author: Luca
"""
import os
import time
def display_array(ar):
"clear the screen, display the contents of an array, wait for 1 sec"
os.system('clear')
rows = len(ar) # grab the rows
if rows == 0:
raise ValueError("Array contains no data")
cols = len(ar[0]) # grab the columns - indices start at 0!
for i in range(rows):
for j in range(cols):
print(ar[i][j],end=' ') # no carriage return, space separated
print()
time.sleep(1)
##############################################################################
ar = [[1,2,3],
[4,5,6],
[7,8,9]]
display_array(ar)
##############################################################################
board = [[' ','*',' '],
['*',' ','*'],
[' ','*',' ']]
display_array(board) |
994b50861e720486749e851adf45a3c043ca9d3d | thenerdpoint60/PythonCodes | /minmaxvalBT.py | 1,129 | 3.9375 | 4 | class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def insertNode(self,data):
if self.data:
if data<self.data:
if self.left==None:
self.left=Node(data)
else:
self.left.insertNode(data)
elif data>self.data:
if self.right==None:
self.right=Node(data)
else:
self.right.insertNode(data)
else:
self.data=data
def printTree(self):
print(self.data)
if self.left:
self.left.printTree()
if self.right:
self.right.printTree()
def minValue(node):
current = node
while(current.left is not None):
current = current.left
return current.data
def maxValue(node):
current1 = node
while(current1.right is not None):
current1 = current1.right
return current1.data
|
eb43d5a85e3ba2ad029986d1b2d957c338051f75 | bloy/adventofcode | /2017/day2.py | 570 | 3.53125 | 4 | #!env python
import itertools
import aoc
def checksum(row):
return max(row) - min(row)
def solve1(rows):
return sum(checksum(row) for row in rows)
def checksum2(row):
for a, b in itertools.combinations(row, 2):
if a % b == 0:
return a // b
if b % a == 0:
return b // a;
def solve2(rows):
return sum(checksum2(row) for row in rows)
if __name__ == '__main__':
rows = [[int(col) for col in row.split('\t')]
for row in aoc.input_lines(day=2)]
print(solve1(rows))
print(solve2(rows))
|
eb69e6927870caec28557783a280e2b9508b82b7 | rohithjallipalli/Leetcode_Toekneema | /LeetcodeSolutions/154. Find Minimum in Rotated Sorted Array II.py | 1,706 | 3.515625 | 4 | class Solution:
def findMin(self, nums: List[int]) -> int:
#binary search variation
#check either left or right side with mid,
#since there's duplicates, need to have an extra condition to account for if n[mid] == n[right]
#then just return the n[left]
'''
binarySearch(target=7) #generic binary search algo
m
r
l
[6,7,8,9,10,11]
return -1
binarySearch() #leetcode 153, part 1
m
r
l
[6,7,8,9,2,3]
return arr[left]
binarySearch() #leetcode 154, part 2
m
r
l
[8,8,8,9,2,8]
return arr[left]
binarySearch() #another example of 154, part 2
m
r
l
[8,2,7,8,8,8]
return arr[left]
'''
if len(nums) == 1:
return nums[0]
left = 0
right = len(nums) - 1
if nums[left] < nums[right]: # there was no rotation
return nums[0]
while left < right:
mid = left + (right-left) // 2
if nums[mid] > nums[right]:
left = mid + 1
elif nums[mid] < nums[right]:
right = mid
elif nums[mid] == nums[right]:
right -= 1
return nums[left] |
d2e6e34372ff073580e9052967068ec4cbb04c19 | BorodaUA/cool_scripts | /task_5_numbers_convertor/task_5.py | 1,021 | 3.78125 | 4 | import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from number_2_words import NumbersToWords # noqa
HELP_MSG = (
'***Welcome to the Numbers 2 Words converter *** \n'
'Please type in number(s), that will be converted to word(s): '
)
NUMBER_TO_LARGE = (
'Handling numbers above 999 999 999 not implemented yet.'
)
NEGATIVE_NUM_MSG = 'Please enter a number greater then zero'
ZERO = 'ноль'
NOT_INTEGER_MSG = 'Please enter a valid number'
def main():
'''
Starting point of the program
'''
try:
user_input = int(input(HELP_MSG))
if user_input == 0:
print(ZERO)
sys.exit()
if user_input < 0:
print(NEGATIVE_NUM_MSG)
sys.exit()
if user_input > 999999999:
print(NUMBER_TO_LARGE)
sys.exit()
number_inst = NumbersToWords(user_input)
print(number_inst)
except ValueError:
print(NOT_INTEGER_MSG)
if __name__ == "__main__":
main()
|
6095ebc680ef706d456707364b7eb6eabcc58823 | vt0311/python | /ex/ex244.py | 595 | 3.546875 | 4 | '''
Created on 2017. 10. 26.
@author: hsw
'''
'''
LIFE is TOO Short 만들기
* 힌트 : for 구문과 if 구문 사용
짝수번쨰 항은 대문자, 홀수번째 항은 소문자로 변경
join() 함수를 이용하여 특정 문자열에 다른 문자열을 추가
'''
list1 = ['Life', 'is', 'too', 'short']
for i in range(len(list1)):
if i % 2 == 0 :
list1[i] = list1[i].upper()
else :
list1[i] = list1[i].lower()
print('join() 함수를 이용하여 문자열 합치기')
result = ' '.join(list1)
print('결과 리스트 :', result)
|
765c8767c1f217c300c7ed27b0f15a71774b6e15 | todatech/checkio | /py_checkio_solutions/PyCon TW/express_delivery.py | 3,733 | 3.671875 | 4 | #!/usr/bin/env checkio --domain=py run express-delivery
# Our three robots found a few mysterious boxes on the island. After some examination Nicola discovered that these boxes have an an interesting feature. If you place something in one of them, you can retrieve it again from any other box. Stephan figures this makes for quick delivery of cargo across the island, moving loads twice as fast. Stephan can place the cargo in one box and pick it up later at the delivery point. On the map there are water cells which Stephan can't pass, but else these boxes will make his task a whole lot easier.
#
# The map for delivery is presented as an array of strings, where:
#
# "W" is a water (closed cell)"B" is a box"E" is a goal point."S" is a start point."." is an empty cell.Stephan moves between neighbouring cells in two minutes if he carries a load. Without any carry-on luggage, he only needs one minute. Loading and unloading of cargo in (and out of) the box takes one minute. You should find the fastest way for the cargo delivery (minimum time).
#
# The route is a string, where each letter is an action.
#
# "U" -- Up (north)"D" -- Down (south)"L" -- Left (west)"R" -- Right (east)"B" -- Load or unload in (out) a box.
#
# Input:A map for delivery as a list of strings.
#
# Output:The fastest route as a string.
#
# Precondition:0<rows<10
# 0<columns<10
# ∀ x,y ∈ coordinates : 0 ≤ x,y ≤ 10
#
#
#
# END_DESC
from typing import List
def checkio(field_map: List[str]) -> str:
return "RRRDDD"
if __name__ == '__main__':
print("Example:")
print(checkio(["S...", "....", "B.WB", "..WE"]))
#This part is using only for self-checking and not necessary for auto-testing
ACTIONS = {
"L": (0, -1),
"R": (0, 1),
"U": (-1, 0),
"D": (1, 0),
"B": (0, 0)
}
def check_solution(func, max_time, field):
max_row, max_col = len(field), len(field[0])
s_row, s_col = 0, 0
total_time = 0
hold_box = True
route = func(field[:])
for step in route:
if step not in ACTIONS:
print("Unknown action {0}".format(step))
return False
if step == "B":
if hold_box:
if field[s_row][s_col] == "B":
hold_box = False
total_time += 1
continue
else:
print("Stephan broke the cargo")
return False
else:
if field[s_row][s_col] == "B":
hold_box = True
total_time += 1
continue
n_row, n_col = s_row + ACTIONS[step][0], s_col + ACTIONS[step][1],
total_time += 2 if hold_box else 1
if 0 > n_row or n_row >= max_row or 0 > n_col or n_row >= max_col:
print("We've lost Stephan.")
return False
if field[n_row][n_col] == "W":
print("Stephan fell in water.")
return False
s_row, s_col = n_row, n_col
if field[s_row][s_col] == "E" and hold_box:
if total_time <= max_time:
return True
else:
print("You can deliver the cargo faster.")
return False
print("The cargo is not delivered")
return False
assert check_solution(checkio, 12, ["S...", "....", "B.WB", "..WE"]), "1st Example"
assert check_solution(checkio, 11, ["S...", "....", "B..B", "..WE"]), "2nd example"
print("Coding complete? Click 'Check' to earn cool rewards!") |
b816ea98b5ccbf71f26287a6d52022eb135bad2c | meaniechee/level_one | /guesszenumber.py | 790 | 3.75 | 4 | # ====================
# WIN THE LOTTERY
# ====================
'''
What you needa doz
1. Random number generated by Python lel
2. Get input from user
3. Loop If else statements
4. Print result
'''
# task 1
import random
rand = random.randint(1,100) # a random int number will be generated between 1 ~ 99
# task 3
for i in range(5): # range(5) starts from 0... So yeah.
# task 2
print("Please enter a number between 1 to 99 as your guess. You only have 5 chances. May the odds ever be in your favour. >=D")
user_try = int(input())
# cont. task 3
if(user_try < rand):
print("Nope. A little higher.")
elif(user_try > rand):
print("Overshot. Boo.")
else:
break # user is correctzo
if (user_try == rand):
print("OMG. ARE YOU A SEER?")
else:
print("HAHAHAHHA. LOSERRRRRRRR.") |
8070cc817e24a64d7cc43a211934fd1cbb0c842a | anaconda121/General-Python-Projects | /Python Data Analysis/Course Materials/Python/Numpy.py | 2,742 | 3.953125 | 4 | def printLine():
print("\n")
import numpy as np
np.array([1, 2, 3]) #generating basic numpy array
print(np.zeros(3)) #generates an array with three slots, all with value 0
printLine()
print(np.ones((4,5))) #generates 2-d array with 4 rows and 5 cols
printLine()
print(np.full((5,4), 3.14))#generates 2-d array with 5 rows and 4 cols all values as 3.14
printLine()
#basic numy array stats
size = np.full((5,5), 4)
print(size)
printLine()
print(size.ndim) #number of dimensions
printLine()
print(size.size) #num elements
printLine()
print(size.shape) #prints num of cols, rows
printLine()
print(size.dtype) #what type of data is in array - only one type allowed
printLine()
#random nums
import random
random.seed(3)
print(random.randint(1, 1000))
random.seed(3)
print(random.randint(1, 1000))
random.seed(3)
print(random.randint(1, 1000))
printLine()
#accessing and editing array vals
edit = np.full((5,5), 3)
print(edit)
print(edit[0,1]) #prints val of number in first row, second col slot
edit[0,1] = 222.2 #edited value of number in first row, second col slot
printLine()
print(edit) #array cant hold .2 part b/c only data type in there is int right now
#concatenating arrays
printLine()
x = np.array([1, 2, 3])
y = np.array([3, 2, 1])
print(np.concatenate([x, y])) #result: 1 2 3 3 2 1
#formatting arrays using vertical stacking
printLine()
x = np.array([1, 2, 3])
grid = np.array([[9, 8, 7], [6, 5, 4]])
print(np.vstack([x, grid])) #prints array in rows of 3 because first array is in set of 3
printLine()
#formatting arrays using np.arange
print("A\n", np.arange(4).reshape(2, 2), "\n") #prints array with vals 0-3
print("A\n", np.arange(4, 10, 2) ,"\n") #prints array with vals 4-9 incremented by 2
#basic math functions
x = [-2, -1, 1, 2]
print("Absolute value: ", np.abs(x))
print("Exponential: ", np.exp(x)) #takes e to the power of elements of x
print("Logarithm: ", np.log(np.abs(x))) #takes log of abs value of elements of x
#boolean operations - np.where
y = np.random.rand(3) #2-d array of random nums, 3 rows and 3 cols
printLine()
y > 0.5
#aggregation
#sum all vals
nums = np.random.random(100)
totalSum = np.sum(nums) #sums up all values of nums
print(totalSum)
#sum of a column
cols = np.random.random((3,4))
print("\n", cols)
print("\n sum of all element in columns", cols.sum(axis = 0))
print("\n sum of all element in rows", cols.sum(axis = 1))
#basic statistics functions
print("\n", np.std(cols)) #mean standard deviation
print("\n",np.argmin(cols)) #prints index of the smallest element
print("\n", np.percentile(cols, 50))#prints number in 50 percentile
a = np.array([0, 1, 2])
b = np.array([5, 5, 5])
a + b
M = np.ones((3, 3))
print("M is: \n", M)
print("M+a is: \n", M+a)
|
41f412a6cd886b0c78cebb68c8e77e446f9db454 | imod-mirror/IMOD | /pysrc/imoduntar | 1,101 | 3.5 | 4 | #!/usr/bin/env python
# imoduntar - Utility to list or extract all files from a tar file
#
# Author: David Mastronarde
#
# $Id$
import sys, os, tarfile
dolist = False
numStart = 1
if len(sys.argv) > 1 and sys.argv[1] == '-t':
numStart = 2
dolist = True
if len(sys.argv) < numStart + 1:
sys.stdout.write("""Usage: imoduntar [-t] filename
Extracts all files from a tar file created with gzip, bzip2, or no
compression, or lists all files with the -t option\n""")
sys.exit(0)
fname = sys.argv[numStart]
pyVersion = 100 * sys.version_info[0] + 10 * sys.version_info[1]
try:
mess = 'opening ' + fname + ' as a tar file'
tf = tarfile.open(fname, 'r')
if dolist:
mess = 'listing the files in ' + fname
tf.list()
else:
mess = 'extracting the files from ' + fname
if pyVersion >= 250:
tf.extractall()
else:
for tfi in tf:
tf.extract(tfi)
sys.stdout.write('All files extracted from ' + fname + '\n')
except Exception:
sys.stdout.write('An error occurred ' + mess + '\n')
sys.exit(1)
sys.exit(0)
|
40596014bf1bcf51e119aff281391a961dbf35ae | dileepnsp/Algorithms_Practice | /Assignment/pandas_practice.py | 288 | 3.59375 | 4 | import pandas as pd
#1.Create a Datatime index containing all the weekdays days of year 2019 and assign a random number to each of them in a dataframe.
#2. Given Pandas series , height = [23,42,55] and weight = [71,32,48] . Create a dataframe with height and weight as column names.
|
1b0bb552261e40feb4ef28168312a843272ea010 | CrisTowi/cracking-the-code-interview | /LinkedList/2-8.py | 1,826 | 3.828125 | 4 | """
Description: Detect if a linked list is a loop and detect the first node
that represents the beginning of the loop
Author: Christian Consuelo
"""
class Node:
def __init__(self, value):
self.value = value
self.next = None
def append_to_tail(self, value):
new_node = Node(value)
current_node = self
while current_node.next:
current_node = current_node.next
current_node.next = new_node
def append_node_to_tail(self, node):
current_node = self
while current_node.next:
current_node = current_node.next
current_node.next = node
def print_linked_list(self):
current_node = self
while current_node:
print(current_node.value)
current_node = current_node.next
def loop_detection(root):
current_node = root
current_node_runner = root
while current_node and current_node_runner.next:
current_node = current_node.next
current_node_runner = current_node_runner.next.next
if current_node == current_node_runner:
break
if not current_node or not current_node_runner:
return False
current_node = root
while current_node != current_node_runner:
current_node = current_node.next
current_node_runner = current_node_runner.next
return current_node_runner
root = Node(1)
node_2 = Node(2)
node_3 = Node(3)
node_4 = Node(4)
node_5 = Node(5)
node_6 = Node(6)
node_7 = Node(7)
node_8 = Node(8)
node_9 = Node(9)
node_10 = Node(10)
root.append_node_to_tail(node_2)
root.append_node_to_tail(node_3)
root.append_node_to_tail(node_4)
root.append_node_to_tail(node_5)
root.append_node_to_tail(node_6)
root.append_node_to_tail(node_7)
root.append_node_to_tail(node_8)
root.append_node_to_tail(node_9)
root.append_node_to_tail(node_10)
root.append_node_to_tail(node_4)
result = loop_detection(root)
print(result.value)
|
664c76461db59ab93d9fb056925fcc1174662f4e | CharlotteKuang/algorithm | /LeetCode/156.BinaryTreeUpsideDown/Solution.py | 3,035 | 3.6875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def recursiveUpsideDown(self, node):
if not node.left:
self.newNode = TreeNode(node.val)
return self.newNode
father = self.recursiveUpsideDown(node.left)
if node.right:
father.left = TreeNode(node.right.val)
father.right = TreeNode(node.val)
return father.right
# @param {TreeNode} root
# @return {TreeNode}
def upsideDownBinaryTree(self, root):
if root:
self.recursiveUpsideDown(root)
return self.newNode
else: return None
def postorderTraversalGenerator(self, node):
if node.left:
for i in self.postorderTraversalGenerator(node.left):
yield i
if node.right:
for i in self.postorderTraversalGenerator(node.right):
yield i
if node: yield node.val
# @param {TreeNode} root
# @return {integer[]}
def postorderTraversalFunc(self, root):
return list(self.postorderTraversalGenerator(root))
def inorderTraversalGenerator(self, node):
if node.left:
for i in self.inorderTraversalGenerator(node.left):
yield i
if node: yield node.val
if node.right:
for i in self.inorderTraversalGenerator(node.right):
yield i
# @param {TreeNode} root
# @return {integer[]}
def inorderTraversalFunc(self, root):
return list(self.inorderTraversalGenerator(root))
def preorderTraversalGenerator(self, node):
if node: yield node.val
if node.left:
for i in self.preorderTraversalGenerator(node.left):
yield i
if node.right:
for i in self.preorderTraversalGenerator(node.right):
yield i
# @param {TreeNode} root
# @return {integer[]}
def preorderTraversalFunc(self, root):
return list(self.preorderTraversalGenerator(root))
# @param {TreeNode} root
# @return {integer[]}
def preorderTraversal(self, root):
result = []
if root:
s = [root]
while len(s):
top = s.pop(-1)
result.append(top.val)
if top.right:
s.append(top.right)
if top.left:
s.append(top.left)
return result
# @param {TreeNode} root
# @return {integer[]}
def inorderTraversal(self, root):
result = []
s = []
if root: s.append(root)
while len(s):
top = s[-1]
while top.left:
s.append(top.left)
top = top.left
while not top.right:
result.append(top.val)
s.pop()
if len(s): top = s[-1]
else:
top = None
break
if top:
result.append(top.val)
s.pop(-1)
s.append(top.right)
return result
# @param {TreeNode} root
# @return {integer[]}
def postorderTraversal(self, root):
result = []
s = []
if root: s.append(root)
while len(s):
top = s[-1]
if not top.left and not top.right:
result.append(top.val)
s.pop()
while len(s):
tmp = s[-1]
if tmp.left == top or tmp.right == top:
result.append(tmp.val)
top = s.pop(-1)
else:
break
else:
if top.right:
s.append(top.right)
if top.left:
s.append(top.left)
return result
|
d222f2c24f0f042054d12d53353357bf366dab00 | dynizhnik/python_home_work | /ua/univer/lesson06HW/chapter10_task01_Programm.py | 371 | 3.875 | 4 | from ua.univer.lesson06HW.chapter10_task01_Pet import Pet
def main():
name = input('Enter name your pet: ')
animal_type = input('Enter type your pet: ')
age = float(input('Enter age your pet: '))
pet = Pet(name, animal_type, age)
print('Pet name is', pet.get_name(), ', pet type is', pet.get_animal_type(), 'and pet age is', pet.get_age())
main() |
636e6b6d7f94b6edaf31d219a9a1fa90fe59c440 | 0ssamaak0/CS50X | /pset7/houses/roster.py | 782 | 3.859375 | 4 | # TODO
from sys import argv, exit
import sqlite3
# Checking the right number of command line arguments
if len(argv) != 2:
print("Enter a valid number of command line arguments")
exit(1)
connect = sqlite3.connect("students.db")
curs = connect.cursor()
curs.execute(f"SELECT first, middle, last, birth FROM students WHERE house = '{argv[1]}' ORDER BY last, first")
student_tuple = curs.fetchall()
student_list = []
for student in student_tuple:
student_list.append([student_item for student_item in student])
# print(student_list)
for student in student_list:
if student[1] == None:
print(f"{student[0]} {student[2]}, born {student[3]}")
else:
print(f"{student[0]} {student[1]} {student[2]}, born {student[3]}")
connect.commit()
connect.close() |
a7792d6927943cf8482bf763f0799a18e98f6d1f | imjaya/Leetcode_solved | /twosigma_missing_words.py | 456 | 3.71875 | 4 | #make a dict of bigger string and then for every word in the second string remove the count in the dict, return the list of remaining words
def missingWords(s, t):
ls = s.split(' ')
lt = t.split(' ')
counter = collections.Counter(lt)
res = []
for s in ls:
if s in counter:
counter[s] -= 1
if counter[s] == 0:
del counter[s]
else:
res.append(s)
return " ".join(res) |
50dbd02175e2aa5c90394538769916471e883b17 | soyoung823/Udacity_Adventure_game | /adventure_game.py | 5,614 | 3.75 | 4 | import time
import random
weapons = ["Magical Sword of Ogoroth", "TNT", " Sharp Knife", "Golden Ax"]
creatures = ["Monster", "Gozilla", "Gorgon", "Pirate"]
weapon = random.choice(weapons)
creature = random.choice(creatures)
got_weapon = False
def print_pause(message_to_player):
print(message_to_player)
time.sleep(1)
def intro():
print_pause("You find yourself standing in an open field, filled with "
"grass and yellow wildflowers.")
print_pause("Rumor has it that a pirate is somewhere around here, and has "
"been terrifying the nearby village.")
print_pause("In front of you is a house.")
print_pause("To your right is a dark cave.")
print_pause("In your hand you hold your trusty (but not very effective) "
"dagger.")
def valid_input(prompt, options):
while True:
response = input(prompt)
for option in options:
if response == option:
return response
print_pause("Sorry I don't understand.")
def play_again():
response2 = valid_input("Would you like to play again? (y/n)", ["y", "n"])
if response2 == "y":
print_pause("Excellent! Restarting the game ...")
play_game()
else:
print_pause("Thanks for playing! See you next time.")
def fight():
if got_weapon:
print_pause("As the dragon moves to attack, you unsheath your new "
"sword.\n"
"The Sword of Ogoroth shines brightly in your hand as you "
"brace yourself for the attack.\n"
"But the dragon takes one look at your shiny new toy and "
"runs away!\n"
"You have rid the town of the dragon. You are victorious!")
play_again()
else:
print_pause("You do your best...")
print_pause("but your dagger is no match for the pirate.")
print_pause("You have been defeated!")
play_again()
def field():
print_pause("You run back into the field. Luckily, you don't seem to have "
"been followed.")
# go back to step1
house_or_cave()
def house():
print_pause("You approach the door of the house.")
print_pause("You are about to knock when the door opens and out steps a "
+ creature + ".")
print_pause("Eep! This is the " + creature + "'s house!\n")
print_pause("The " + creature + " attacks you!\n")
if not got_weapon:
print_pause("You feel a bit under-prepared for this, what with only "
"having a tiny dagger.")
response1 = valid_input("Would you like to (1) fight or (2) run away?",
["1", "2"])
if response1 == "1":
fight()
# choose "run away".
else:
field()
def cave():
print_pause("You peer cautiously into the cave.")
print_pause("It turns out to be only a very small cave.")
print_pause("Your eye catches a glint of metal behind a rock.")
print_pause("You have found the " + weapon + "!")
print_pause("You discard your silly old dagger and take the sword "
"with you.")
print_pause("You walk back out to the field.")
while True:
response2 = valid_input("Enter 1 to knock on the door of the house.\n"
"Enter 2 to peer into the cave.\n"
"What would you like to do?\n"
"(Please enter 1 or 2.)", ["1", "2"])
if response2 == "1":
print_pause("You approach the door of the house.")
print_pause("You are about to knock when the door opens and out "
"steps a " + creature + ".")
print_pause("Eep! This is the " + creature + "'s house!")
print_pause("The " + creature + " attacks you!")
response3 = valid_input("Would you like to (1) fight or (2) run "
"away?", ["1", "2"])
if response3 == "1":
print_pause("As the " + creature + " moves to attack, you "
"unsheath your new sword.")
print_pause("The " + weapon + " shines brightly in your "
"hand as you brace yourself for the attack.")
print_pause("But the " + creature + " takes one look "
"at your shiny new toy and runs away!")
print_pause("You have rid the town of the " + creature +
". You are victorious!")
play_again()
# choose run away
else:
print_pause("You run back into the field. Luckily, you don't "
"seem to have been followed.")
house_or_cave()
break
else:
print_pause("You peer cautiously into the cave.\n"
"You've been here before, and gottten all the "
"good stuff.\n"
"It's just an empty cave now.\n"
"You walk back out to the field")
def house_or_cave():
response = valid_input("Enter 1 to knock on the door of the house.\n"
"Enter 2 to peer into the cave.\n"
"What would you like to do?\n"
"(Please enter 1 or 2.)", ["1", "2"])
if response == "1":
house()
elif response == "2":
cave()
def play_game():
intro()
house_or_cave()
if __name__ == "__main__":
play_game()
|
d14f430996f028786c638b213cd8b707b23c98dd | nook2/LearningSF | /projects/SkillFactory/practice_C1/python_practice/1.10.4.py | 808 | 3.6875 | 4 | class Client:
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
class Guests(Client):
def __init__(self, name, address, status):
super().__init__(name)
self.address = address
self.status = status
def get_address(self):
return self.address
def get_status(self):
return self.status
List = [{'name': 'Петя', 'address': 'МCK', 'status': 'VIP'}, {'name': 'Вася', 'address': 'СПБ', 'status': 'Regular'}]
#with open('client.txt', "r") as List:
print('Список приглашенных гостей')
for i in List:
client = Guests(name=i.get('name'), address=i.get('address'), status=i.get('status'))
print(f'{client.name}, г. {client.address}, статус {client.status}')
|
4fc774be860349e6f475720f86633d10bf151fb3 | khushal2911/hackerrank-30days-of-code | /lets_review.py | 309 | 3.796875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
if __name__ == '__main__':
t = int(input())
for i in range(t):
s = input()
a = "".join([s[c] for c in range(len(s)) if c%2==0])
b = "".join([s[c] for c in range(len(s)) if c%2==1])
print(f'{a} {b}')
|
f95d8b727eb01b0520dbda447c72efdcd1a03ee2 | KritiMitraD/ga-learner-dsmp-repo | /Projectsby_Kriti/code.py | 1,600 | 3.890625 | 4 | # --------------
# Code starts here
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
#Concatenation
new_class = class_1 + class_2
print("New class is : ", new_class)
#Appending new data
new_class.append("Peter Warden")
print("Updated new class is : ", new_class)
print(len(new_class))
#Removing data
new_class.remove("Carla Gentry")
print("Updated class list is : ", new_class)
len(new_class)
# Code ends here
# --------------
# Code starts here
courses = {'Math' : 65, 'English' : 70, 'History' : 80, 'French' : 70, 'Science' : 60}
print("The marks of Geoffrey Hinton in each subject : ", courses)
#Fetching only marks
marks = courses.values()
#print(marks)
#Getting the total
total = 0
for x in marks :
total += x
print("The total marks of Geoffrey Hinton is :", total)
#Calculate Percentage
percentage = total/ 500 * 100
print("Percentage of Geoffrey Hinton: ", percentage)
# Code ends here
# --------------
# Code starts here
mathematics = {'Geoffrey Hinton' : 78, 'Andrew Ng': 95, 'Sebastian Raschka' : 65, 'Yoshua Benjio' : 50, 'Hilary Mason' : 70, 'Corinna Cortes' : 66, 'Peter Warden' : 75 }
#marks_scored = mathematics.values()
#top_number = max(marks_scored)
topper = max(mathematics, key = mathematics.get)
print("The topper in mathematics is : ", topper)
# Code ends here
# --------------
# Given string
topper = 'andrew ng'
# Code starts here
first_name = topper.split()[0]
last_name = topper.split()[1]
full_name = last_name + ' ' + first_name
print("The toppper is ", full_name)
certificate_name = full_name.upper()
print("Cetificate name :", certificate_name)
# Code ends here
|
b6badfed124ec69dafeb6d9353d38825b762de62 | Uche-Clare/python-challenge-solutions | /Ekeopara_Praise/Phase 1/Python Basic 2/Day21 Tasks/Task5.py | 860 | 4.1875 | 4 | '''5. There are two circles C1 with radius r1, central coordinate (x1, y1) and C2 with radius r2 and central coordinate (x2, y2).
Write a Python program to test the followings -
"C2 is in C1" if C2 is in C1
"C1 is in C2" if C1 is in C2
"Circumference of C1 and C2 intersect" if circumference of C1 and C2 intersect, and
"C1 and C2 do not overlap" if C1 and C2 do not overlap.
Input:
Input numbers (real numbers) are separated by a space.
Input x1, y1, r1, x2, y2, r2:
5 6 4 8 7 9
C1 is in C2'''
import math
print("Input x1, y1, r1, x2, y2, r2:")
x1,y1,r1,x2,y2,r2 = [float(i) for i in input().split()]
d = math.sqrt((x1-x2)**2 + (y1-y2)**2)
if d < r1-r2:
print("C2 is in C1")
elif d < r2-r1:
print("C1 is in C2")
elif d > r1+r2:
print("Circumference of C1 and C2 intersect")
else:
print("C1 and C2 do not overlap")
#Reference: w3resource |
dcc0c2437211e471c00fd73b2bb25ea3c5a25a32 | evbeda/games2 | /guess_number_game/test_guess_number_game.py | 1,593 | 3.609375 | 4 | import unittest
from guess_number_game.guess_number_game import GuessNumberGame
class TestGuessNumberGame(unittest.TestCase):
def setUp(self):
self.game = GuessNumberGame()
self.game._guess_number = 50
def test_initial_status(self):
self.assertTrue(self.game.is_playing)
def test_play_lower(self):
play_result = self.game.play(10)
self.assertEqual(play_result, 'too low')
self.assertTrue(self.game.is_playing)
def test_play_higher(self):
play_result = self.game.play(80)
self.assertEqual(play_result, 'too high')
self.assertTrue(self.game.is_playing)
def test_play_equal(self):
play_result = self.game.play(50)
self.assertEqual(play_result, 'you win')
self.assertFalse(self.game.is_playing)
def test_initial_next_turn(self):
self.assertEqual(
self.game.next_turn(),
'Give me a number from 0 to 100',
)
def test_next_turn_after_play(self):
self.game.play(10)
self.assertEqual(
self.game.next_turn(),
'Give me a number from 0 to 100',
)
def test_next_turn_after_win(self):
self.game.play(50)
self.assertEqual(
self.game.next_turn(),
'Game Over',
)
def test_get_board(self):
self.assertEqual(
self.game.board,
'[]'
)
self.game.play(10)
self.assertEqual(
self.game.board,
'[10]'
)
if __name__ == "__main__":
unittest.main()
|
654f9410498780a712fc8c721f3109f4ad787e64 | Ethan30749/monthy-python-and-the-holy-grail | /Ejercicio 4 Moodle.py | 336 | 4.0625 | 4 | Vocal=('a','e','i','o','u')
Consonante=('b','c','d','f','g','h','j','k','l','m','n','ñ','p','q','r','s','t','v','w','x','y','z',)
Letra=(input('ingrese una letra: '))
if Letra in Vocal:
print('Su letra es la vocal ',Letra)
elif Letra in Consonante:
print('Su letra es la consonante ',Letra)
else:
print('letra no válida') |
844a8368e9a94efea8ca122e90f18edd956486b9 | iluvmusubis/Guessing-Game | /Guessing Game.py | 13,640 | 4.09375 | 4 | import random
def main():
print("\nWelcome to the Guessing Game!\n"
"\nPlease choose your difficulty level:\n"
"\n1. Easy\n"
"\n2. Medium\n"
"\n3. Hard\n")
x = int(input())
if x == 1:
easy()
elif x == 2:
medium()
elif x == 3:
hard()
def easy():
print("\nFirst to 10 guesses loses\n"
"\nPlayer 1, try and guess the random number between 1 and 10")
random_num = random.randrange(1, 11)
x = int(input())
count = 0
while random_num != x:
if x < random_num:
print("The number you entered is too low")
x = int(input())
count = count + 1
elif x > random_num:
print("The number you entered is too high")
x = int(input())
count = count + 1
while random_num == x:
print("Congratulations you guessed the correct number!")
count = count + 1
count = str(count)
print("It took you " + count + " tries to guess the number")
break
print("\nPlayer 2, try and guess a number between 1 and 10")
random_num2 = random.randrange(1, 11)
y = int(input())
count2 = 0
while random_num2 != y:
if y < random_num2:
print("The number you entered is too low")
y = int(input())
count2 = count2 + 1
elif y > random_num2:
print("The number you entered is too high")
y = int(input())
count2 = count2 + 1
while random_num2 == y:
print("Congratulations you guessed the correct number!")
count2 = count2 + 1
count2 = str(count2)
print("It took you " + count2 + " tries to guess the number")
break
count = int(count)
count2 = int(count2)
while count < 10 and count2 < 10:
print("\nPlayer 1, try and guess the random number between 1 and 10")
random_num = random.randrange(1, 11)
user_num = int(input())
while random_num != user_num:
if user_num < random_num:
print("The number you entered is too low")
user_num = int(input())
count = count + 1
elif user_num > random_num:
print("The number you entered is too high")
user_num = int(input())
count = count + 1
while random_num == user_num:
print("Congratulations you guessed the correct number!")
count = count + 1
count = str(count)
print("It took you " + count + " tries to guess the number")
break
print("\nPlayer 2, try and guess the random number between 1 and 10")
random_num2 = random.randrange(1, 11)
user_num = int(input())
while random_num2 != user_num:
if user_num < random_num:
print("The number you entered is too low")
user_num = int(input())
count2 = count2 + 1
elif user_num > random_num2:
print("The number you entered is too high")
user_num = int(input())
count2 = count2 + 1
while random_num2 == user_num:
print("Congratulations you guessed the correct number!")
count2 = count2 + 1
count2 = str(count2)
print("It took you " + count + " tries to guess the number")
break
if count > count2:
print("\nPlayer 2 wins!\n"
"\nPlayer 1 loses\n")
elif count < count2:
print("\nPlayer 1 wins!\n"
"\nPlayer 2 loses\n")
elif count == count2:
print("There is tie. Play again.")
replay()
def medium():
print("First to 15 guesses loses. Good Luck!\n"
"\nPlayer 1, try and guess the random number between 1 and 20")
random_num = random.randrange(1, 21)
x = int(input())
count = 0
while random_num != x:
if x < random_num:
print("The number you entered is too low")
x = int(input())
count = count + 1
elif x > random_num:
print("The number you entered is too high")
x = int(input())
count = count + 1
while random_num == x:
print("Congratulations you guessed the correct number!")
count = count + 1
count = str(count)
print("It took you " + count + " tries to guess the number")
break
print("\nPlayer 2, try and guess a number between 1 and 20")
random_num2 = random.randrange(1, 21)
y = int(input())
count2 = 0
while random_num2 != y:
if y < random_num2:
print("The number you entered is too low")
y = int(input())
count2 = count2 + 1
elif y > random_num2:
print("The number you entered is too high")
y = int(input())
count2 = count2 + 1
while random_num2 == y:
print("Congratulations you guessed the correct number!")
count2 = count2 + 1
count2 = str(count2)
print("It took you " + count2 + " tries to guess the number")
break
while count < 15 and count2 < 15:
print("\nPlayer 1, try and guess the random number between 1 and 20")
random_num = random.randrange(1, 21)
user_num = int(input())
while random_num != user_num:
if user_num < random_num:
print("The number you entered is too low")
user_num = int(input())
count = count + 1
elif user_num > random_num:
print("The number you entered is too high")
user_num = int(input())
count = count + 1
while random_num == user_num:
print("Congratulations you guessed the correct number!")
count = count + 1
count = str(count)
print("It took you " + count + " tries to guess the number")
break
print("\nPlayer 2, try and guess the random number between 1 and 20")
random_num2 = random.randrange(1, 21)
user_num = int(input())
while random_num2 != user_num:
if user_num < random_num:
print("The number you entered is too low")
user_num = int(input())
count2 = count2 + 1
elif user_num > random_num2:
print("The number you entered is too high")
user_num = int(input())
count2 = count2 + 1
while random_num2 == user_num:
print("Congratulations you guessed the correct number!")
count2 = count2 + 1
count2 = str(count2)
print("It took you " + count + " tries to guess the number")
break
if count > count2:
print("\nPlayer 2 wins!\n"
"\nPlayer 1 loses\n")
elif count < count2:
print("\nPlayer 1 wins!\n"
"\nPlayer 2 loses\n")
elif count == count2:
print("There is tie. Play again.")
replay()
def hard():
print("First to 30 guesses loses. Good Luck!\n"
"\nPlayer 1, try and guess the random number between 1 and 100")
random_num = random.randrange(1, 101)
user_num = int(input())
count = 0
while random_num != user_num:
if user_num < random_num:
print("The number you entered is too low")
user_num = int(input())
count = count + 1
elif user_num > random_num:
print("The number you entered is too high")
user_num = int(input())
count = count + 1
while random_num == user_num:
print("Congratulations you guessed the correct number!")
count = count + 1
count = str(count)
print("It took you " + count + " tries to guess the number")
break
print("\nPlayer 2, try and guess a number between 1 and 100")
random_num2 = random.randrange(1, 101)
y = int(input())
count2 = 0
while random_num2 != y:
if y < random_num2:
print("The number you entered is too low")
y = int(input())
count2 = count2 + 1
elif y > random_num2:
print("The number you entered is too high")
y = int(input())
count2 = count2 + 1
while random_num2 == y:
print("Congratulations you guessed the correct number!")
count2 = count2 + 1
count2 = str(count2)
print("It took you " + count2 + " tries to guess the number")
break
if count > count2:
print("\nPlayer 2 wins!\n"
"\nPlayer 1 loses\n")
elif count < count2:
print("\nPlayer 1 wins!\n"
"\nPlayer 2 loses\n")
elif count == count2:
print("There is tie. Play again.")
replay()
replay()
def replay():
print("\nWould you like to play again?\n"
"\n1. Yes\n"
"\n2. No\n "
"\nPlease choose a number\n")
choice = int(input())
if choice == 1:
main()
else:
print("Game Over")
def easy1():
print("\nPlayer 1, try and guess the random number between 1 and 10")
random_num = random.randrange(1, 11)
user_num = int(input())
while random_num != user_num:
if user_num < random_num:
print("The number you entered is too low")
user_num = int(input())
count = count + 1
elif user_num > random_num:
print("The number you entered is too high")
user_num = int(input())
count = count + 1
while random_num == user_num:
print("Congratulations you guessed the correct number!")
count = count + 1
count = str(count)
print("It took you " + count + " tries to guess the number")
break
def easy2():
print("\nPlayer 2, try and guess a number between 1 and 10 ")
random_num2 = random.randrange(1, 11)
user_num2 = int(input())
count2 = 0
while random_num2 != user_num2:
if user_num2 < random_num2:
print("The number you entered is too low")
user_num2 = int(input())
count2 = count2 + 1
elif user_num2 > random_num2:
print("The number you entered is too high")
user_num2 = int(input())
count2 = count2 + 1
while random_num2 == user_num2:
print("Congratulations you got the number!")
count2 = count2 + 1
count2 = str(count2)
print("It took you " + count2 + " tries to guess the number")
break
def medium1():
print("\nPlayer 1, try and guess the random number between 1 and 20")
random_num = random.randrange(1, 21)
user_num = int(input())
while random_num != user_num:
if user_num < random_num:
print("The number you entered is too low")
user_num = int(input())
count = count + 1
elif user_num > random_num:
print("The number you entered is too high")
user_num = int(input())
count = count + 1
while random_num == user_num:
print("Congratulations you guessed the correct number!")
count = count + 1
count = str(count)
print("It took you " + count + " tries to guess the number")
break
def medium2():
print("\nPlayer 2, try and guess a number between 1 and 20 ")
random_num2 = random.randrange(1, 21)
user_num2 = int(input())
count2 = 0
while random_num2 != user_num2:
if user_num2 < random_num2:
print("The number you entered is too low")
user_num2 = int(input())
count2 = count2 + 1
elif user_num2 > random_num2:
print("The number you entered is too high")
user_num2 = int(input())
count2 = count2 + 1
while random_num2 == user_num2:
print("Congratulations you got the number!")
count2 = count2 + 1
count2 = str(count2)
print("It took you " + count2 + " tries to guess the number")
break
def hard1():
print("\nPlayer 2, try and guess a number between 1 and 100 ")
random_num2 = random.randrange(1, 101)
user_num2 = int(input())
count2 = 0
while random_num2 != user_num2:
if user_num2 < random_num2:
print("The number you entered is too low")
user_num2 = int(input())
count2 = count2 + 1
elif user_num2 > random_num2:
print("The number you entered is too high")
user_num2 = int(input())
count2 = count2 + 1
while random_num2 == user_num2:
print("Congratulations you got the number!")
count2 = count2 + 1
count2 = str(count2)
print("It took you " + count2 + " tries to guess the number")
break
def hard2():
print("\nPlayer 2, try and guess a number between 1 and 100 ")
random_num2 = random.randrange(1, 101)
user_num2 = int(input())
count2 = 0
while random_num2 != user_num2:
if user_num2 < random_num2:
print("The number you entered is too low")
user_num2 = int(input())
count2 = count2 + 1
elif user_num2 > random_num2:
print("The number you entered is too high")
user_num2 = int(input())
count2 = count2 + 1
while random_num2 == user_num2:
print("Congratulations you got the number!")
count2 = count2 + 1
count2 = str(count2)
print("It took you " + count2 + " tries to guess the number")
break
main() |
4b59514edc2483a6f7740925ae4c4fb4824421fc | rajdharmkar/Python2.7 | /removedupes1.py | 443 | 3.5625 | 4 | set()={} # holds lines already seen
outfile = open("new2.txt", "w")#the text files have to be in same dir as py files
infile = open("new3.txt", "r")
print infile
print lines_seen
for line in infile:
lines_seen = line
print lines_seen
#if line not in lines_seen: # not a duplicate
outfile.write(line)
for line in open("new2.txt", "r"):
print line
# lines_seen.add(line)
outfile.close()
|
f148d33e95cbaa850a845eec35b675ff3134f6b1 | lizebang/think-python-2e-examples | /class/functions.py | 592 | 3.84375 | 4 | class Time:
"""Represents the time of day.
attributes: hour, minute, second
"""
# pure functions, modifiers and designed development
# think python 2e -- chapter16
# designed development
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
def add_time(t1, t2):
seconds = time_to_int(t1) + time_to_int(t2)
return int_to_time(seconds)
|
f55d67d875af84166ca0af66d531e326228669c4 | bluewater18/Euler-Probelms | /euler12.py | 393 | 3.640625 | 4 | from functions import findDiv
def euler12(x):
"""What is the value of the first triangle number to have over x divisors?"""
i =1
c=1
while True:
#print("i is :"+ str(i))
#print("*************")
#print("*************")
temp = len(findDiv(i))
#print(temp)
if temp>x:
return i
c+=1
i+=c |
ed8969bd34094ea33d2f79ee4f4b94e8cf0ad50a | EnricoChi/algo | /1/1.py | 1,956 | 4.0625 | 4 | # 1. Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
# Чтобы исключить левый ввод будем использовать регулярки
import re
# Циклим на всякий, если вдруг не с первого раза будет верный ввод
while True:
# Принимает пользовательский ввод
num = input('Введите трёхзначное число: ')
# Ищем левые значения
wrong_items = re.findall(r'[\D]', num)
# Если не нашли - продолжаем, иначе тыкаем в ошибку и начинаем сначала
if not wrong_items:
# Проверим количество символов
if len(num) != 3:
print('Не верное число, попробуйте снова!')
# Если не = 3 перезапускаем цикл
continue
else:
# Генератором загоняем всё в list и заодно преобразуем в числа
num = [int(s) for s in num]
# Делим на переменные и производим математические операции
# a, b, c = num
# sum = a + b + c
# mult = a * b * c
# Или так
sum_result = 0
mult_result = 1
for i in num:
sum_result += i
mult_result *= i
print('-> Сумма {};\n-> Произведение {};'.format(sum_result, mult_result))
else:
# Объеденим все левые значения и выведем оповещение
print('Значение "{}" - не является числом!\n'.format(', '.join(wrong_items)))
continue
|
47f45a742eb7d89eab3d74b986d10511bc138877 | LaplaceKorea/aboleth | /aboleth/prediction.py | 2,658 | 3.609375 | 4 | """Convenience functions for building prediction graphs."""
import tensorflow as tf
from tensorflow.contrib.distributions import percentile
def sample_mean(predictor, name=None):
"""
Get the mean of the samples of a predictor.
Parameter
---------
predictor : Tensor
A tensor of samples, where the first dimension indexes the samples.
name : str
name to give this operation
Returns
-------
expec : Tensor
A tensor that contains the mean of the predicted samples.
"""
expec = tf.reduce_mean(predictor, axis=0, name=name)
return expec
def sample_percentiles(predictor, per=[10, 90], interpolation='nearest',
name=None):
"""
Get the percentiles of the samples of a predictor.
Parameter
---------
predictor : Tensor
A tensor of samples, where the first dimension indexes the samples.
per : list
A list of the percentiles to calculate from the samples. These must be
in [0, 100].
interpolation : string
The type of interpolation method to use, see
tf.contrib.distributions.percentile for details.
name : str
name to give this operation
Returns
-------
percen: Tensor
A tensor whose first dimension indexes the percentiles, computed along
the first axis of the input.
"""
for p in per:
assert 0 <= p <= 100
pers = [percentile(predictor, p, interpolation=interpolation, axis=0)
for p in per]
percen = tf.stack(pers, name=name)
return percen
def sample_model(graph=None, sess=None, feed_dict=None):
"""
Sample the model parameters.
This function returns a feed_dict containing values for the sample tensors
in the model. It means that multiple calls to eval() will not change the
model parameters as long as the output of this function is used as a
feed_dict.
Parameters
----------
graph : tf.Graph
The current graph. If none provided use the default.
sess : tf.Session
The session to use for evaluating the tensors. If none provided
will use the default.
feed_dict : dict
An optional feed_dict to pass the session.
Returns
-------
collection : dict
A feed_dict to use when evaluating the model.
"""
if not graph:
graph = tf.get_default_graph()
if not sess:
sess = tf.get_default_session()
params = graph.get_collection('SampleTensors')
param_values = sess.run(params, feed_dict=feed_dict)
sample_feed_dict = dict(zip(params, param_values))
return sample_feed_dict
|
ddc7af534d8cf07887545b1a5fa27c703ba30678 | JerinPaulS/Python-Programs | /SpiralMatrixSP.py | 664 | 3.671875 | 4 | '''
59. Spiral Matrix II
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
1 <= n <= 20
'''
class Solution:
def generateMatrix(self, n):
ans = [[0]*n for i in range(n)]
i,j = 0, 0
dire = [0,1,0,-1,0]
po = 0
for a in range(1,n*n+1):
ans[i][j] = a
ni,nj = i+dire[po],j+dire[po+1]
if (not 0<=ni<n) or (not 0<=nj<n) or ans[ni][nj]!=0:
po+=1
po%=4
ni,nj = i+dire[po],j+dire[po+1]
i,j = ni,nj
return ans
obj = Solution()
print(obj.generateMatrix(10)) |
52a9c400341c3697d93944749d1229c45914896f | johnobrien/pyshortz | /solutions/20150802/spooning_animals.py | 1,174 | 3.6875 | 4 | from solver.solver import Solver
from solver.lists import get_animals
def first_vowel(word):
vowels = "aeiou"
word = word.lower()
for i in range(0, len(word)):
if word[i] in vowels:
return i
class SpooningAnimalsSolver(Solver):
def solve(self, animals):
candidates = []
for a1 in animals:
for a2 in animals:
if self.__dict__.get("verbose", False):
print("Trying {0} and {1}".format(a1, a2))
offset_1 = first_vowel(a1)
offset_2 = first_vowel(a2)
word1 = a1[0:offset_1] + a2[offset_2:]
word2 = a2[0:offset_2] + a1[offset_1:]
new_a1 = " ".join([word1, word2])
if new_a1 in animals:
candidates.append((a1, a2, new_a1))
return candidates
if __name__ == '__main__':
p = """
Name two animals. Exchange their initial consonant sounds,
and the result in two words will be the name of a third animal.
What is it?
"""
s = SpooningAnimalsSolver(puzzle_text=p,
verbose=True)
print(s.solve(animals=get_animals()))
|
eeaa5d914ba863d82b4498b9249537a78908cf3b | xniccum/chorewheel | /utils/date_utils.py | 3,407 | 3.59375 | 4 | from datetime import datetime, timedelta
import logging
import pytz
def get_utc_datetime_from_user_input(tz_str, date_time_str):
"""Returns a datetime object from a string, taking into account the time zone for that string.
Note that the date_time_str must be in the one and only acceptable format %m-%d-%Y %I:%M %p"""
try:
tz = pytz.timezone(tz_str) # Convert the time zone string into a time zone object.
except:
logging.warn("Time zone string did NOT parse. tz_str = " + tz_str)
tz = pytz.utc
# Convert the string into a datetime object (time zone naive)
send_datetime_raw = datetime.strptime(date_time_str, "%m-%d-%Y %I:%M %p")
# Set the time zone to the user's preference value (make the datetime object time zone aware instead of time zone naive).
send_datetime_in_user_tz = send_datetime_raw.replace(tzinfo=tz)
# Adjust for Daylight Savings Time if appropriate (only an issue in the US March-November).
send_datetime_adj_for_dst = send_datetime_in_user_tz - tz.normalize(send_datetime_in_user_tz).dst()
# Shift the time to UTC time (all datetime objects stored on the server should always be in UTC no exceptions)
send_datetime_in_utc = send_datetime_adj_for_dst.astimezone(pytz.utc)
# Used during development to make sure I did the time zone stuff correctly.
# print("send_datetime = " + date_time_display_format(send_datetime_in_utc, "UTC"))
# print("now = " + date_time_display_format(datetime.now(), "UTC"))
# Then remove the tzinfo to make the datatime again time zone naive, which is how AppEngine stores the time. (naive but known to be UTC)
return send_datetime_in_utc.replace(tzinfo=None)
def is_within_next_24_hours(send_time):
"""Returns true if the datetime object passed in is within the next 24 hours."""
one_day = timedelta(1) # Create a timedelta object set to 1 day long
time_delta = send_time - datetime.utcnow() # Creates a timedelta ojbect that is the difference between now and the send_time
return time_delta.total_seconds() > 0 and time_delta < one_day
def get_seconds_since_epoch(datetime):
"""Returns the seconds since epoch. Note, this function is not used in this app I just like it."""
return int(datetime.strftime("%s"))
# ## Jinja filters
def date_time_input_format(value, tz_str):
"""Take a date time object and convert it into a string that uses the required input box format.
Note, this format MUST match the format used in the get_utc_datetime_from_user_input function."""
try:
tz = pytz.timezone(tz_str)
except:
tz = pytz.utc
value = value.replace(tzinfo=pytz.utc).astimezone(tz)
return value.strftime("%m-%d-%Y %I:%M %p")
def date_time_display_format(value, tz_str):
"""Take a date time object and convert it into a string that can be displayed in the text message event tables."""
try:
tz = pytz.timezone(tz_str)
except:
tz = pytz.utc
value = value.replace(tzinfo=pytz.utc).astimezone(tz)
if value.year == value.now(tz).year:
# current year
if value.month == value.now(tz).month and value.day == value.now(tz).day:
# today, just show the time
format_str = "Today %I:%M %p %Z"
else:
# otherwise show the month and day
format_str = "%b %d %I:%M %p %Z"
else:
# previous year, show the year, too
format_str = "%m/%d/%y %I:%M %p %Z"
return value.strftime(format_str)
|
3b5677714383568aa1d0b1c65c2e89c5cb1dad08 | Siddhant08/Recommendation-System | /norm.py | 1,255 | 3.578125 | 4 | import random
#initialize empty lists to store ratings
rahul=[]
silky=[]
#randomly fill lists with ratings in the range 1 to 5 considering Rahul's standards
for i in range(10):
#randomly fill lists with ratings in the range 1 to 5 considering Rahul's standards
rahul.append(random.randint(1,5))
#randomly fill lists with ratings in the range 5 to 10 considering Silky's standards
silky.append(random.randint(5,10))
#see ratings by Rahul and Silky
print rahul
print silky
print "------------------------------------"
#initialize lists to store the normalized ratings by Silky and Rahul
silky_norm=[]
rahul_norm=[]
#Use the formula below to get normalized ratings for Rahul and Silky
'''
normalized value range is 0 to 1
for Rahul, min value = 1 and max value = 5
norm_value = min_norm_range + (norm_max_value - norm_min_value)/(current_max_range - current_min_range)*(value - current_min_range)
'''
for i in rahul:
rahul_norm.append(0+0.25*(i-1))
'''
normalized value range is 0 to 1
for Silky, min value = 5 and max value = 10
norm_value = min_norm_range + (norm_max_value - norm_min_value)/(current_max_range - current_min_range)*(value - current_min_range)
'''
for i in silky:
silky_norm.append(0+0.2*(i-5))
print rahul_norm
print silky_norm
|
d3595bf4c19461539bc16cb6083b2f7e8945e236 | belladewusa/Python-MD5-Brute-Force | /passCrack - (Readable).py | 5,667 | 4.09375 | 4 | # Required For The Exit Message That Lets The User Know Their Password Has Been Found
import sys
# Required for md5!!
import hashlib
# Global Vars:
stringPass = ""
# Functions:
def intro():
print("Welcome to Password Crack!!!\n\n In this application, you will type a password into the console and Python will return an MD5 Hash of that password. Go ahead and copy that and then when Python asks you for the MD5 Hash, go ahead and Paste that into the console. ")
print("Your md5 Hash is:", str(hashlib.md5(input("\n\nType your Password here: ").encode()).hexdigest()))
main()
# Main Function That Uses Brute-Force To Guess and Check MD5 Hashes Created by Python in order!
def main():
inputMD5Hash = input("Paste your MD5 Hash here: ")
print("Your MD5 Hash is: ", inputMD5Hash)
listOfCharacters = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-=_+,./;'[]\\<>?:\"{}|`~ ")
for i in range(95):
global stringPass
stringPass = listOfCharacters[i]
if hashlib.md5(stringPass.encode()).hexdigest() == inputMD5Hash:
success()
else:
print(stringPass, "didn't seem to be your password!!")
stringPass = listOfCharacters[i]
for j in range(95):
currentStringPass = stringPass + listOfCharacters[j]
if hashlib.md5(currentStringPass.encode()).hexdigest() == inputMD5Hash:
stringPass = currentStringPass
success()
else:
print(currentStringPass, "didn't seem to be your password!!")
for k in range(95):
currentStringPass = stringPass + listOfCharacters[j] + listOfCharacters[k]
if hashlib.md5(currentStringPass.encode()).hexdigest() == inputMD5Hash:
stringPass = currentStringPass
success()
else:
print(currentStringPass, "didn't seem to be your password!!")
for l in range(95):
currentStringPass = stringPass + listOfCharacters[j] + listOfCharacters[k] + listOfCharacters[l]
if hashlib.md5(currentStringPass.encode()).hexdigest() == inputMD5Hash:
stringPass = currentStringPass
success()
else:
print(currentStringPass, "didn't seem to be your password!!")
for m in range(95):
currentStringPass = stringPass + listOfCharacters[j] + listOfCharacters[k] + listOfCharacters[l] + listOfCharacters[m]
if hashlib.md5(currentStringPass.encode()).hexdigest() == inputMD5Hash:
stringPass = currentStringPass
success()
else:
print(currentStringPass, "didn't seem to be your password!!")
for n in range(95):
currentStringPass = stringPass + listOfCharacters[j] + listOfCharacters[k] + listOfCharacters[l] + listOfCharacters[m] + listOfCharacters[n]
if hashlib.md5(currentStringPass.encode()).hexdigest() == inputMD5Hash:
stringPass = currentStringPass
success()
else:
print(currentStringPass, "didn't seem to be your password!!")
for o in range(95):
currentStringPass = stringPass + listOfCharacters[j] + listOfCharacters[k] + listOfCharacters[l] + listOfCharacters[m] + listOfCharacters[n] + listOfCharacters[o]
if hashlib.md5(currentStringPass.encode()).hexdigest() == inputMD5Hash:
stringPass = currentStringPass
success()
else:
print(currentStringPass, "didn't seem to be your password!!")
for p in range(95):
currentStringPass = stringPass + listOfCharacters[j] + listOfCharacters[k] + listOfCharacters[l] + listOfCharacters[m] + listOfCharacters[n] + listOfCharacters[o] + listOfCharacters[p]
if hashlib.md5(currentStringPass.encode()).hexdigest() == inputMD5Hash:
stringPass = currentStringPass
success()
else:
print(currentStringPass, "didn't seem to be your password!!")
for q in range(95):
currentStringPass = stringPass + listOfCharacters[j] + listOfCharacters[k] + listOfCharacters[l] + listOfCharacters[m] + listOfCharacters[n] + listOfCharacters[o] + listOfCharacters[p] + listOfCharacters[q]
if hashlib.md5(currentStringPass.encode()).hexdigest() == inputMD5Hash:
stringPass = currentStringPass
success()
else:
print(currentStringPass, "didn't seem to be your password!!")
# Function To Be Called If A Match Is Found
def success():
# Simple Exit Program With Message That Says Password Was Found!
sys.exit("\n\n\n\n\n\n\n\n\n\n\n\n\nPython found your password to be \"" + stringPass + "\"!!!")
# Initiate Program
intro() |
c0c81086e622f6925bfb989845e7275680b29ede | pkitutu/ferry_Terminal | /vehicle.py | 513 | 3.515625 | 4 | class Vehicle(object):
"""docstring for Vehicle"""
__size = ''
__price = 0
__current_gas = 0
def __init__(self):
super(Vehicle, self).__init__()
def set_size(self, size):
self.__size = size
def get_size(self):
return self.__size
def set_price(self, price):
self.__price = price
def get_price(self):
return self.__price
def set_current_gas(self, gas):
self.__current_gas = gas
def get_current_gas(self):
return self.__current_gas
def add_gas(self, gas):
self.__current_gas += gas |
1b2251a0eb221ce3b4e17595357bb39fbc3b87d7 | AusProtoBell/Hillel_KuzmenkoAlex | /lesson_14/task_1.py | 1,932 | 3.578125 | 4 | import random
class City:
def __init__(self, street_count):
self.streets = []
self.initialize_city(street_count)
def initialize_city(self, street_count):
for street_id in range(street_count):
self.streets.append(Street(street_id))
def population(self):
population = 0
for street in self.streets:
for house in street.houses:
population += house.humans
return population
def delete_street(self, street_id):
self.streets.pop(street_id)
def add_street(self):
self.streets.append(Street(len(self.streets)))
def population_report(self):
with open('population-report.txt', mode='w', encoding='utf-8') as txt_file:
txt_file.write(f'{"Улица".ljust(8)}{"Дом".ljust(8)}Население\n')
for street in self.streets:
for house in street.houses:
txt_file.write(f'{str(street.street_id).ljust(8)}{str(house.house_id).ljust(8)}{house.humans}\n')
class Street:
min_houses_amount = 5
max_houses_amount = 20
def __init__(self, street_id):
self.houses = []
self.street_id = street_id
for house_id in range(random.randint(self.min_houses_amount,
self.max_houses_amount)):
self.houses.append(House(house_id))
def delete_house(self, street_id):
self.houses.pop(street_id)
def add_house(self):
self.houses.append(House(len(self.houses) + 1))
class House:
min_people_amount = 1
max_people_amount = 100
def __init__(self, house_id):
self.house_id = house_id
self.humans = random.randint(self.min_people_amount,
self.max_people_amount)
if __name__ == '__main__':
odessa = City(10)
print(odessa.population())
odessa.population_report()
|
a88966cedb2e155819cab7ba9e2acfeb5f86da9b | HuipengXu/leetcode | /sumNumbers.py | 1,958 | 3.78125 | 4 | # 129. 求根到叶子节点数字之和
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 递归
class Solution1:
def rec(self, node, sum):
if node == None:
return 0
if not node.left and not node.right:
return sum * 10 + node.val
return self.rec(node.left, sum * 10 + node.val) + self.rec(node.right, sum * 10 + node.val)
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.rec(root, 0)
# 栈
class Solution:
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
s = 0
single_trace = root.val
stack = []
stack.append(root)
if root.left == None and root.right == None:
return single_trace
fl = 1
fr = 1
while len(stack):
temp = stack[-1]
# if temp == None:
# break
if temp.left:
stack.append(temp.left)
single_trace = single_trace * 10 + temp.left.val
temp.left = None
fl = 0
fr = 1
elif temp.right:
stack.append(temp.right)
single_trace = single_trace * 10 + temp.right.val
temp.right = None
fl = 1
fr = 0
else:
if not fl:
s += single_trace
single_trace //= 10
fl = 1
elif not fr:
s += single_trace
single_trace //= 10
fr = 1
else:
single_trace //= 10
stack.pop()
return s |
140f1ec8e935dcb282b88d26bd9f5e9d778383e7 | cpeixin/leetcode-bbbbrent | /geekAlgorithm010/Week01/plus-one.py | 950 | 3.8125 | 4 | # coding: utf-8
# Author:Brent
# Date :2020/6/13 6:30 PM
# Tool :PyCharm
# Describe :给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
#
# 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
#
# 你可以假设除了整数 0 之外,这个整数不会以零开头。
#
# 示例 1:
#
# 输入: [1,2,3]
# 输出: [1,2,4]
# 解释: 输入数组表示数字 123。
# 示例 2:
#
# 输入: [4,3,2,1]
# 输出: [4,3,2,2]
# 解释: 输入数组表示数字 4321。
#
# 链接:https://leetcode-cn.com/problems/plus-one
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
index = len(digits)-1
while digits[index] == 9:
digits[index] = 0
index-=1
# 针对9999这种情况
if index < 0:
digits = [1]+digits
else:
digits[index]+=1
return digits
|
345ff211e099b7170ed6d61dea2cd7891f3514b1 | dukkipatisamyu5/MultiLinear | /2_linear_regression_multivariate.py | 1,065 | 3.890625 | 4 | # multiple linear regression
#Importing the libraries
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn import linear_model
#Importing the dataset
df = pd.read_csv('homeprices.csv')
#Finding the missing value
import math
med_bedrooms = math.floor(df.bedrooms.median())
df.bedrooms = df.bedrooms.fillna(med_bedrooms)
print(df)
# Fitting Multiple Linear Regression to the Training set
reg = linear_model.LinearRegression()
reg.fit(df[['area','bedrooms','age']],df.price)
#Finding the coefficients
print(reg.coef_)
print(reg.intercept_)
# Predicting the Test set results
#Find price of home with 3000 sqr ft area, 3 bedrooms, 40 year old
reg.predict([[3000, 3, 40]])
112.06244194*3000 + 23388.88007794*3 + -3231.71790863*40 + 221323.00186540384
#Find price of home with 2500 sqr ft area, 4 bedrooms, 5 year old
reg.predict([[2500, 4, 5]])
plt.xlabel('age')
plt.ylabel('prices')
y = reg.predict(df.iloc[:,:-1].values)
x= df.iloc[:,0]
plt.plot(df.iloc[:,2],df.iloc[:,-1],color ='blue')
plt.plot(df.iloc[:,2,] , y,color = 'red') |
1592ea950b476e6ae3787356fd653b37d9ebb1a9 | MadhanChiluka/Python_CheatSheet | /PatternsEx.py | 274 | 3.921875 | 4 | for i in range(4):
for j in range(4):
print("#" , end = " ")
print()
print()
for a in range(4):
for b in range(a+1):
print("#", end = " ")
print();
print()
for m in range(4):
for n in range(4-m):
print("#", end=" ")
print()
|
ee6300a46759eb0d7785d10bdb8b75ad4463fc66 | Serine-T/Hangman_game | /hangman.py | 2,449 | 3.890625 | 4 | import random
import os
from display_hangman import display_hangman
def get_word():
file_path = os.path.abspath(__file__)
cur_dir = os.path.dirname(file_path)
with open(os.path.join(cur_dir, 'fruits.txt')) as f:
word = random.choice(f.readlines()).upper()
return word.strip()
def play(word):
word_completion = '_ ' * len(word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 6
print(f'Let\'s play Hangman!' )
print(display_hangman(tries))
print(word_completion)
print('\n')
while not guessed and tries > 0:
guess = input('Please guess a letter or word: ').upper()
if len(guess) == 1 and guess.isalpha():
if guess in guessed_letters:
print(f'You have already tried {guess} letter')
elif guess not in word:
print(f'{guess} is not in the word.')
tries -= 1
guessed_letters.append(guess)
else:
print(f'Good job, {guess} is in the word!')
guessed_letters.append(guess)
word_as_list = list(word_completion.split())
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = guess
word_completion = ' '.join(word_as_list)
if '_' not in word_completion:
guessed = True
elif len(guess) == len(word) and guess.isalpha():
if guess in guessed_words:
print(f'You already guessed {guess} word.')
elif guess != word:
print(f'{guess} is not the word.')
tries -= 1
guessed_words.append(guess)
else:
guessed = True
word_completion = word
else:
print('Not a valid guess.')
print(display_hangman(tries))
print(word_completion)
print(f'{tries} tries remain.')
print('\n')
if guessed:
print('Congrats, you guessed the word. You win')
else:
print(f'Sorry, you ran out of tries. The word was {word}. Maybe next time!')
if __name__ == '__main__':
word = get_word()
print(len(word))
play(word)
while input('Play Again?(Y/N) ').upper() =='Y':
word = get_word()
play(word)
|
381a5b27cb9c47056def3c8bd106fb23dd2c2bae | brutalchrist/test_5rabbits | /3_dise~o/2/Mazo.py | 6,004 | 3.59375 | 4 | #-*- coding: utf-8 -*-
"""
Problema 2 del Test de diseño para LemonTech.\n
<Diseñe un mazo de cartas (orientado a objetos) con propiedades y métodos básicos que considere para ser utilizado en distintas aplicaciones que utilicen cartas.>
"""
class Mazo(object):
def __init__(self, nombreMazo, nCartasMazo=60, listaCartasMazo=[]):
"""Inicializador de la clase.
:parameter:
- nombreMazo: Nombre del mazo
- nCartasMazo: Número de cartas del mazo (60 por defecto).
- listaCartasMazo: Lista con las cartas del mazo (vacia por defecto)"""
# Se definen los atributos estaticos de un mazo
self.nombreMazo = nombreMazo
self.nCartasMazo = nCartasMazo
self.listaCartasMazo = listaCartasMazo
# Se definen los atributos dinámicos de un mazo
self.listaBiblioteca = self.listaCartasMazo
self.listaPozoDescarte = []
# Acciones
def robarCartaBiblioteca(self, nCartas=1):
"""Método encargado de obtener la o las cartas de la la parte superior de la Biblioteca.
:parameter:
- nCartas: Número de cartas a robar (1 por defecto)."""
return "Se ha robado la carta: " + self.listaBiblioteca.pop()
def enviarCartasPozoDescarte(self, listaCartas):
"""Método encargado de enviarr una o unas cartas al Pozo de descarte.
:parameter:
- listaCartas: Lista las cartas a enviar."""
return "Enviada la(s) carta(s): " + str(listaCartas) + " al Pozo de descarte"
def buscarCartasBiblioteca(self, listaIndexs):
"""Método encargado de obtener la o las cartas de una posición especifica de la Biblioteca.
:parameter:
- listaIndexs: Lista con las posiciones de las cartas a obtener."""
return "La(s) carta(s) con index(s): " + str(listaIndexs)
def buscarCartasPozoDescarte(self, listaIndexs):
"""Método encargado de obtener la o las cartas de una posición especifica del Pozo de descarte.
:parameter:
- listaIndexs: Lista con las posiciones de las cartas a obtener."""
return "La(s) carta(s) con index(s): " + str(listaIndexs)
def devolverCartasBiblioteca(self, listaCartas):
"""Método encargado de devolver una o unas cartas en la parte superior de la Biblioteca.
:parameter:
- listaCartas: Lista las cartas a devolver."""
# Si para robar utilizamos push para devolver utilizamos append
print "Agregada(s) la(s) carta(s): " + str(listaCartas) + " a la parte superior de la Biblioteca"
def devolverCartasBibliotecaAleatorio(self, listaCartas):
"""Método encargado de devolver una o unas cartas aleatoriamente a la Biblioteca.
:parameter:
- listaCartas: Lista las cartas a devolver."""
print "Agregada(s) la(s) carta(s): " + str(listaCartas) + " aleatoriamente a la Biblioteca"
def cartasRestantesBiblioteca(self):
"""Método encargado retornar el número de cartas restantes en la Biblioteca."""
return len(self.listaBiblioteca)
def barajarBiblioteca(self):
"""Método encargado de barajar la Biblioteca."""
print "Biblioteca barajada"
def barajarPozoDescarte(self):
"""Método encargado de barajar el Pozo de descarte."""
print "Pozo de descarte barajada"
# Comprobaciones
def isBibliotecaVacia(self):
"""Método encargado de retornar verdadero si la Biblioteca está vacia."""
if len(self.listaBiblioteca) <= 0:
return True
return False
def isPozoDescarteVacio(self):
"""Método encargado de retornar verdadero si el Pozo de descarte está vacio."""
if len(self.listaBiblioteca) <= 0:
return True
return False
# Getters & Setters
def getNombreMazo(self):
"""Método encargado de retornar el nombre del Mazo."""
return self.nombreMazo
def setNombreMazo(self, nombreMazo):
"""Método encargado de setear el nombre del Mazo.
:parameter:
- nombreMazo: Nombre del mazo."""
self.nombreMazo = nombreMazo
def getNCartasMazo(self):
"""Método encargado de retornar el número de cartas del Mazo."""
return self.nCartasMazo
def setNCartasMazo(self, nCartasMazo):
"""Método encargado de setear el número de cartas del Mazo.
:parameter:
- nCartasMazo: Número de cartas del mazo."""
self.nCartasMazo = nCartasMazo
def getListaCartasMazo(self):
"""Método encargado de retornar la lista de cartas del Mazo."""
return self.listaCartasMazo
def setListaCartasMazo(self, listaCartasMazo):
"""Método encargado de setear la lista de cartas del Mazo.
:parameter:
- listaCartasMazo: Lista de cartas del Mazo."""
self.listaCartasMazo = listaCartasMazo
def getListaBiblioteca(self):
"""Método encargado de retornar la lista de cartas de la Biblioteca."""
return self.listaBiblioteca
def setListaBiblioteca(self, listaBiblioteca):
"""Método encargado de setear la lista de cartas de la Biblioteca. Esta lista suele ser la misma del Mazo, por ejemplo:
magicMazo.setListaBiblioteca(magicMazo.getListaCartasMazo())
:parameter:
- listaBiblioteca: Lista de cartas de la Biblioteca."""
self.listaBiblioteca = listaBiblioteca
def getListaPozoDescarte(self):
"""Método encargado de retornar la lista de cartas del Pozo de descarte."""
return self.listaPozoDescarte
def setListaPozoDescarte(self, listaPozoDescarte):
"""Método encargado de setear la lista de cartas del Pozo de descarte.
:parameter:
- listaBiblioteca: Lista de cartas de la Biblioteca."""
self.listaPozoDescarte = listaPozoDescarte |
48f1d220769b768632c136f21aa9a7dbf6a05b3c | bguenthe/coursera | /week4/pong.py | 6,146 | 3.734375 | 4 | # Implementation of classic arcade game Pong
import simpleguitk as simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
ball_pos = [0, 0]
ball_vel = [1, 1]
ball_acc = 0.0
paddleleft_pos = 0
paddleright_pos = 0
paddleleft_vel = 0
paddle_acc = 6
paddleright_vel = 0
scoreleft = 0
scoreright = 0
paddleright_direction = ""
paddleleft_direction = ""
# initialize ball_pos and ball_vel for new bal in middle of table
# if direction is RIGHT, the ball's velocity is upper right, else upper left
def spawn_ball(direction):
global ball_pos, ball_vel # these are vectors stored as lists
ball_pos = [WIDTH / 2, HEIGHT / 2]
if direction == 1:
ball_vel[0] = (random.randrange(120, 240) / 60)
ball_vel[1] = (random.randrange(60, 180) / 60) * random.randrange(-1, 2, 2)
else:
ball_vel[0] = (random.randrange(120, 240) / 60) * -1
ball_vel[1] = (random.randrange(60, 180) / 60) * random.randrange(-1, 2, 2)
def reset_handler():
new_game(0)
# define event handlers
def new_game(direction):
global paddleleft_pos, paddleright_pos, paddleleft_vel, paddleright_vel # these are numbers
global scoreleft, scoreright, ball_acc
paddleleft_pos = HEIGHT / 2
paddleright_pos = HEIGHT / 2
paddleleft_vel = 0
paddleright_vel = 0
ball_acc = 1.0
if direction == 0:
scoreleft = 0
scoreright = 0
ran = random.randrange(1, 3)
print ran
if ran == 1:
spawn_ball(1)
else:
spawn_ball(-1)
elif direction == 1:
scoreleft += 1
spawn_ball(-1)
else:
scoreright += 1
spawn_ball(1)
def draw(canvas):
global soreleft, scoreright, paddleleft_pos, paddleright_pos, ball_pos, ball_vel
global paddleright_direction, paddleleft_direction, ball_acc
# draw mid line and gutters
canvas.draw_line([WIDTH / 2, 0], [WIDTH / 2, HEIGHT], 1, "White")
canvas.draw_line([PAD_WIDTH, 0], [PAD_WIDTH, HEIGHT], 1, "White")
canvas.draw_line([WIDTH - PAD_WIDTH, 0], [WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
# update ball
if ball_vel[0] > 0:
ball_pos[0] += ball_vel[0] + ball_acc
else:
ball_pos[0] += ball_vel[0] - ball_acc
if ball_vel[1] > 0:
ball_pos[1] += ball_vel[1] + ball_acc
else:
ball_pos[1] += ball_vel[1] - ball_acc
# abprallen, wenn auf paddle; and der rechten wand und im paddle bereich
if ball_pos[0] >= (WIDTH - 1 - BALL_RADIUS - PAD_WIDTH):
if (ball_pos[1] + BALL_RADIUS >= paddleright_pos - HALF_PAD_HEIGHT) and (
ball_pos[1] + BALL_RADIUS <= paddleright_pos + HALF_PAD_HEIGHT):
ball_vel[0] = ball_vel[0] * -1
ball_acc += 0.3
else:
new_game(1)
elif ball_pos[0] <= BALL_RADIUS + PAD_WIDTH:
if (ball_pos[1] + BALL_RADIUS >= paddleleft_pos - HALF_PAD_HEIGHT) and (
ball_pos[1] + BALL_RADIUS <= paddleleft_pos + HALF_PAD_HEIGHT):
ball_vel[0] = ball_vel[0] * -1
ball_acc += 0.3
else:
new_game(-1)
elif ball_pos[1] >= HEIGHT + 1 - BALL_RADIUS:
ball_vel[1] = ball_vel[1] * -1
elif ball_pos[1] <= BALL_RADIUS:
ball_vel[1] = ball_vel[1] * -1
# draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")
# update paddle's vertical position, keep paddle on the screen
if paddleleft_direction == "down" and paddleleft_pos + HALF_PAD_HEIGHT <= HEIGHT:
paddleleft_pos += paddle_acc * paddleleft_vel
if paddleleft_direction == "up" and paddleleft_pos - HALF_PAD_HEIGHT >= 0:
paddleleft_pos += paddle_acc * paddleleft_vel
if paddleright_direction == "down" and paddleright_pos + HALF_PAD_HEIGHT <= HEIGHT:
paddleright_pos += paddle_acc * paddleright_vel
if paddleright_direction == "up" and paddleright_pos - HALF_PAD_HEIGHT >= 0:
paddleright_pos += paddle_acc * paddleright_vel
# draw paddles
canvas.draw_polygon([(0, paddleleft_pos - HALF_PAD_HEIGHT),
(0 + PAD_WIDTH, paddleleft_pos - HALF_PAD_HEIGHT),
(0 + PAD_WIDTH, paddleleft_pos + HALF_PAD_HEIGHT),
(0, paddleleft_pos + HALF_PAD_HEIGHT)
],
5, 'White', 'White')
canvas.draw_polygon([(WIDTH - PAD_WIDTH, paddleright_pos - HALF_PAD_HEIGHT),
(WIDTH, paddleright_pos - HALF_PAD_HEIGHT),
(WIDTH, paddleright_pos + HALF_PAD_HEIGHT),
(WIDTH - PAD_WIDTH, paddleright_pos + HALF_PAD_HEIGHT),
], 5, 'White', 'White')
# draw scores
canvas.draw_text(str(scoreleft), [WIDTH / 2 - 100, HEIGHT / 5], 40, "White")
canvas.draw_text(str(scoreright), [WIDTH / 2 + 100, HEIGHT / 5], 40, "White")
def keydown(key):
global paddleleft_vel, paddleright_vel, paddleright_direction, paddleleft_direction
if key == simplegui.KEY_MAP["up"]:
paddleright_vel = -1
paddleright_direction = "up"
if key == simplegui.KEY_MAP["down"]:
paddleright_vel = 1
paddleright_direction = "down"
if key == simplegui.KEY_MAP["w"]:
paddleleft_vel = -1
paddleleft_direction = "up"
if key == simplegui.KEY_MAP["s"]:
paddleleft_vel = 1
paddleleft_direction = "down"
def keyup(key):
global paddleleft_vel, paddleright_vel
if key == simplegui.KEY_MAP["up"]:
paddleright_vel = 0
if key == simplegui.KEY_MAP["down"]:
paddleright_vel = 0
if key == simplegui.KEY_MAP["w"]:
paddleleft_vel = 0
if key == simplegui.KEY_MAP["s"]:
paddleleft_vel = 0
# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keyup_handler(keyup)
frame.set_keydown_handler(keydown)
frame.add_button("Reset", reset_handler, 50)
# start frame
new_game(0)
frame.start() |
03a2128b0f9766aa59e6420ab47cbe45a2f954fc | tikogr/NLP100 | /01/05.py | 276 | 3.703125 | 4 | def n_gram(target, n: int):
result = []
for i in range(0, len(target)-n+1):
result.append(target[i:i+n])
return result
target = "I am an NLPer"
# 単語bi-gram
words = target.split(' ')
print(n_gram(words, 2))
# 文字bi-gram
print(n_gram(target, 2))
|
36d1bd2b8efc91d48a4ada8e4d7b1e8ab131ed80 | amantaymagzum/magzumcs | /1.py | 348 | 4.15625 | 4 | num1=int(input("Введите превое число:"))
num2=int(input("Введите второе число:"))
num1*=5
print("Results:",num1+num2)
print("Results:",num1-num2)
print("Results:",num1/num2)
print("Results:",num1*num2)
print("Results:",num1**num2)
print("Results:",num1//num2)
word="Hi"
print(word*2)
word=True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.