blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1fa6a0c73d34d55016eb66aeca0e8a7ecd3bb375 | bobby20180331/Algorithms | /LeetCode/python/_338.CountingBits.py | 325 | 3.6875 | 4 | # 原来列表也有加法![a]+[b]=[a,b].思路L:利用位移运算
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
ans = [0]
for x in range(1, num + 1):
ans += ans[x >> 1] + (x & 1),
return ans
|
9a0fdd2226aa51129d3f5e409dfdd29ece33810c | beggerss/algorithms | /Sort/merge.py | 1,425 | 3.96875 | 4 | #!/usr/bin/python2
# Author: Ben Eggers
import time
import numpy as np
import matplotlib.pyplot as plt
# Implementation of mergesort written in Python.
def main():
base = 1000
x_points = []
y_points = []
for x in range(1, 20):
arr = [np.random.randint(0, base*x) for k in range(base*x)]
start = int(round(time.time() * 1000))
arr = merge_sort(arr)
end = int(round(time.time() * 1000))
x_points.append(len(arr))
y_points.append(end - start)
print("%d ms required to sort array of length %d using mergesort."
% (end - start, len(arr)))
make_plot(x_points, y_points)
def merge_sort(arr):
length = len(arr)
if length <= 1:
return arr
# cut the array in 2
first = arr[:length/2]
last = arr[length/2:]
# sort both halves
first = merge_sort(first)
last = merge_sort(last)
# now put them together
results = []
while len(first) > 0 or len(last) > 0:
if len(first) is 0:
results.append(last[0])
del last[0]
elif len(last) is 0:
results.append(first[0])
del first[0]
elif first[0] < last[0]:
results.append(first[0])
del first[0]
else:
results.append(last[0])
del last[0]
return results
def make_plot(x_points, y_points):
plt.plot(x_points, y_points, 'ro')
plt.axis([0, max(x_points), 0, max(y_points)])
plt.xlabel('length of array')
plt.ylabel('time to sort (milliseconds)')
plt.title('Efficiency of merge sort')
plt.show()
if __name__ == "__main__":
main() |
f7f98b782810ea91307db96d7c212fd2f0106a8c | nyucusp/gx5003-fall2013 | /ke638/Assignment 1/Problem 2.py | 434 | 3.75 | 4 | import sys
def absvalue(i,j):
return abs(int(sys.argv[i]) - int(sys.argv[j]))
n = int(sys.argv[1])
diff = []
for i in range(2,len(sys.argv)-1):
value = absvalue(i,i+1)
diff.append(value)
for i in range(1,n):
found = False
for element in diff:
if(i == element):
found = True
if (found == False):
print "Not jolly"
exit()
print "jolly"
|
0f82a6b3dbce734db750187ab3fe34513ec4388d | LuisPalominoTrevilla/CompetitiveProgramming | /Competition1/primalSport.py | 540 | 3.734375 | 4 | import math
def sieve(primes):
real_primes = []
for i in range(2, x2+1):
if primes[i]:
real_primes.append(i)
for j in range(i*2, x2+1, i):
primes[j] = False
return real_primes
def getX0(x2):
hash_primes = [True]*(x2+1)
primes = sieve(hash_primes)
largest = 2
for prime in primes:
if prime > x2:
break
if not x2%prime and prime > largest:
largest = prime
lower_bound = x2-largest+1
x2 = int(input())
print(getX0(x2)) |
d8dadc4a84dff70cac6fa482f7c739e4fb92e51d | Natalshadow/Learning-Python | /Main.py | 1,835 | 3.8125 | 4 | import random
import sys
import datetime
import time
#fake authentication function
def authenticate():
for attempts in range(5):
print("Enter ID: ")
ID = input()
ID = ID.upper()
if ID == 'EXIT':
print('Exiting...\n')
sys.exit()
elif ID == 'JOE':
print('Enter password: ')
password = input()
if password == 'swordfish':
break
else:
print('Wrong ID. ')
attempts += 1
print(attempts)
if attempts == 5:
print('No more tokens, wait two hours. Password changed, contact admin')
# figure how to setup a timer
password = 'fishtank'
sys.exit()
continue
print('Access granted')
return
#my own collatz attempts, it's messy and unoptimized, not even working as intended.
def collatzOWN():
#the collatz used as reference, to check behaviours and results.
def collatz():
number = int(input())
while number != 1:
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
#function selector
print('What do you want to do ?')
liste = ['Number Guess',
'Collatz by Me',
'Collatz by Git',
'MagicBall of Trips']
print('Your options are : %s ' % (liste))
selection = input()
#I want to get rid of these and make it as short as possible relying on lists
if selection == "1":
from Games import guessGame
guessGame()
elif selection == "2":
collatzOWN()
elif selection == "3":
collatz()
elif selection == "4":
from Games import magicBall
magicBall()
else:
sys.exit()
|
e9857632937fe32da7a587d056c6fa53b3b41257 | YuudachiXMMY/Python-Challenge | /1.py | 990 | 3.671875 | 4 | '''
# 1
http://www.pythonchallenge.com/pc/def/map.html
'''
def decry(input):
return chr(((ord(input)+2) - ord('a')) % 26 + ord('a'))
def main(txt):
result = ''
for i in txt:
if ord(i)>=ord('a') and ord(i)<=ord('z'):
result += decry(i)
else:
result += i
print result
tar = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
url = 'map'
main(tar)
main(url)
'''
# Answer
i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url.
http://www.pythonchallenge.com/pc/def/ocr.html
'''
'''
# To use Maketrans
import string
temp = string.maketrans("abcdefghijklmnopqrstuvwxyz", "cdefghijklmnopqrstuvwxyzab")
print tar.translate(temp)
''' |
43ff9e7c419b90ba17eead1e2eb81d88c022e0e7 | luamnoronha/cursoemvideo | /ex.055.py | 373 | 4.125 | 4 | maior = 0
menor = 0
for c in range(1, 6):
numero = float(input('Digite um numero: '))
if numero == 1:
maior = numero
menor = numero
else:
if numero > maior:
maior = numero
if numero < menor:
menor = numero
print('O maior numero lido é {}'.format(maior))
print('o menor numero lido é {}.'.format(menor))
|
2c3e69d8ca5a14247555da07a1989ab292c561b0 | eufmike/wu_data_bootcamp_code | /homework/w04_HeroesOfPymoli/code.py | 10,033 | 3.65625 | 4 | '''
# Unit 4: Assignment - Pandas, Pandas, Pandas
## Project: Heroes of Pymoli
Heroes Of Pymoli Data Analysis
* Of the 1163 active players, the vast majority are male (84%). There also exists, a smaller, but notable proportion of female players (14%).
* Our peak age demographic falls between 20-24 (44.8%) with secondary groups falling between 15-19 (18.60%) and 25-29 (13.4%).
Note
* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.
'''
# %%
import os, sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
# %%
# path = '/Users/michaelshih/Documents/code/education/wu_data_bootcamp_code/HeroesOfPymoli'
path = '/Volumes/MacProSSD2/code/wu_data_bootcamp_code/HeroesOfPymoli'
subfolder = 'Resources'
filename = 'purchase_data.csv'
filepath = os.path.join(path, subfolder, filename)
data = pd.read_csv(filepath, header = 0)
data = pd.DataFrame(data)
data.head(10)
# %%
'''
# Player Count
* Display the total number of players
'''
# %%
playercount = len(data['SN'].unique())
# print(playercount)
playercount_df = pd.DataFrame({'Total Players': [playercount]})
playercount_df
# %%
'''
# Purchasing Analysis (Total)
* Run basic calculations to obtain number of unique items, average price, etc.
* Create a summary data frame to hold the results
* Optional: give the displayed data cleaner formatting
* Display the summary data frame
'''
# %%
unqitm = len(data['Item ID'].unique())
avgprice = data['Price'].mean()
totalprch = len(data['Purchase ID'].unique())
totalprice = data['Price'].sum()
primary_analysis_df = pd.DataFrame({
'Number of Unique Items': [unqitm],
'Average Price': [avgprice],
'Number of Purchases': [totalprch],
'Total Revenue': [totalprice],
})
primary_analysis_df['Average Price'] = primary_analysis_df['Average Price'].map('${:.2f}'.format)
primary_analysis_df['Total Revenue'] = primary_analysis_df['Total Revenue'].map('${:,.2f}'.format)
primary_analysis_df
# %%
'''
# Gender Demographics
* Percentage and Count of Male Players
* Percentage and Count of Female Players
* Percentage and Count of Other / Non-Disclosed
'''
# %%
data_sn = data.loc[:, ['SN', 'Gender']]
gender_factor = data['Gender'].unique()
gender_count = []
for i in gender_factor:
count = data_sn[data_sn['Gender'] == i]['SN'].nunique()
gender_count.append(count)
gender_percentage = np.array(gender_count) / playercount * 100
gender_analysis_df_01 = pd.DataFrame({
'Percentage of Players': gender_percentage,
'Total Count': gender_count,
}, index=gender_factor)
gender_analysis_df_01['Percentage of Players'] = \
gender_analysis_df_01['Percentage of Players'].map('{:.2f}%'.format)
gender_analysis_df_01
# %%
'''
# Purchasing Analysis (Gender)
* Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender
* Create a summary data frame to hold the results
* Optional: give the displayed data cleaner formatting
* Display the summary data frame
'''
# %%
# Purchase Count
gender_purchase_count = data.groupby(['Gender'])[['Purchase ID']].count()
# Average Purchase Price
gender_avg_purchase_price = data.groupby(['Gender'])[['Price']].mean()
gender_avg_purchase_price['Price'] = gender_avg_purchase_price['Price'].map('${:.2f}'.format)
# Total Purchase Value
gender_totalprch = data.groupby(['Gender'])[['Price']].sum()
gender_totalprch['Price'] = gender_totalprch['Price'].map('${:.2f}'.format)
# Average Purchase Total per Person by Gender
gender_data_gb = data.groupby(['Gender', 'SN'])[['Price']].mean()
gender_data_gb_2 = gender_data_gb.groupby(['Gender']).mean()
gender_data_gb_2['Price'] = gender_data_gb_2['Price'].map('${:.2f}'.format)
gender_analysis_df_02 = pd.concat([gender_purchase_count, \
gender_avg_purchase_price, \
gender_totalprch, \
gender_data_gb_2
], axis = 1)
gender_analysis_df_02.columns = ['Purchase Count', \
'Average Purchase Price', \
'Total Purchase Value', \
'Avg Purchase Total per Person']
gender_analysis_df_02
# %%
'''
# Age Demographics
* Establish bins for ages
* Categorize the existing players using the age bins. Hint: use pd.cut()
* Calculate the numbers and percentages by age group
* Create a summary data frame to hold the results
* Optional: round the percentage column to two decimal points
* Display Age Demographics Table
'''
# %%
# bin data
bin = [0, 9.90, 14.90, 19.90, 24.90, 29.90, 34.90, 39.90, 99999]
group_names = ["<10", "10-14", "15-19", "20-24", "25-29", "30-34", "35-39", "40+"]
data_age = data
data_age['age_range'] = pd.cut(data_age['Age'], list(bin), labels = group_names)
data_age
# data processing
age_prch_count = data_age.groupby(['age_range', 'SN'])[['SN']].count()
age_prch_count = age_prch_count.groupby(['age_range']).sum()
age_prch_count = age_prch_count.rename(index=str, columns={'SN': 'Total Count'})
# Average Purchase Price
age_prch_percentage = np.array(age_prch_count['Total Count']) / playercount * 100
age_prch_count['Percentage of Players'] = age_prch_percentage
age_prch_count['Percentage of Players'] = age_prch_count['Percentage of Players'].map("{:.2f}%".format)
age_prch_count
age_analysis_df_01 = age_prch_count
# %%
'''
# Purchasing Analysis (Age)
* Bin the purchase_data data frame by age
* Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. in the table below
* Create a summary data frame to hold the results
* Optional: give the displayed data cleaner formatting
* Display the summary data frame
'''
# %%
# Purchase Count
age_purchase_count = data.groupby(['age_range'])[['Purchase ID']].count()
age_purchase_count['Purchase ID'] = age_purchase_count['Purchase ID'].map("${:.2f}".format)
# Average Purchase Price
age_avg_purchase_price = data.groupby(['age_range'])[['Price']].mean()
age_avg_purchase_price['Price'] = age_avg_purchase_price['Price'].map("${:.2f}".format)
# Total Purchase Value
age_totalprch = data.groupby(['age_range'])[['Price']].sum()
age_totalprch['Price'] = age_totalprch['Price'].map("${:.2f}".format)
# Average Purchase Total per Person
age_prch_count = data_age.groupby(['age_range', 'SN'])[['Price']].mean()
age_prch_count = age_prch_count.groupby(['age_range']).mean()
age_prch_count['Price'] = age_prch_count['Price'].map("${:.2f}".format)
age_analysis_df_02 = pd.concat([age_purchase_count, \
age_avg_purchase_price, \
age_totalprch,\
age_prch_count
], axis = 1)
age_analysis_df_02.columns = ['Purchase Count', \
'Average Purchase Price', \
'Total Purchase Value', \
'Avg Purchase Total per Person']
age_analysis_df_02
# %%
'''
# Top Spenders
* Run basic calculations to obtain the results in the table below
* Create a summary data frame to hold the results
* Sort the total purchase value column in descending order
* Optional: give the displayed data cleaner formatting
* Display a preview of the summary data frame
'''
# %%
spender_top_sum = data.groupby(['SN'])[['Price']].sum()
spender_top_count = data.groupby(['SN'])[['Purchase ID']].count()
spender_top_avg = data.groupby(['SN'])[['Price']].mean()
spender_top = pd.concat([spender_top_count, spender_top_avg, spender_top_sum], axis = 1)
spender_top.columns = ['Purchase Count', 'Average Purchase Price', 'Total Purchase Value']
spender_top = spender_top.sort_values('Total Purchase Value', ascending=False)
# clean format
spender_top['Average Purchase Price'] = spender_top['Average Purchase Price'].map("${:.2f}".format)
spender_top['Total Purchase Value'] = spender_top['Total Purchase Value'].map("${:.2f}".format)
topspender_analysis_df = spender_top.head(5)
topspender_analysis_df
# %%
'''
# Most Popular Items
* Retrieve the Item ID, Item Name, and Item Price columns
* Group by Item ID and Item Name. Perform calculations to obtain purchase count, item price, and total purchase value
* Create a summary data frame to hold the results
* Sort the purchase count column in descending order
* Optional: give the displayed data cleaner formatting
* Display a preview of the summary data frame
'''
# %%
item_top_count = data.groupby(['Item ID', 'Item Name'])[['Purchase ID']].count()
item_top_avg = data.groupby(['Item ID', 'Item Name'])[['Price']].mean()
item_top_sum = data.groupby(['Item ID', 'Item Name'])[['Price']].sum()
item_top = pd.concat([item_top_count, item_top_avg, item_top_sum], axis = 1)
item_top.columns = ['Purchase Count', 'Average Purchase Price', 'Total Purchase Value']
item_top = item_top.sort_values('Purchase Count', ascending=False)
item_top['Average Purchase Price'] = item_top['Average Purchase Price'].map("${:.2f}".format)
item_top['Total Purchase Value'] = item_top['Total Purchase Value'].map("${:.2f}".format)
topitem_analysis_df = item_top.head(5)
topitem_analysis_df
# %%
'''
# Most Profitable Items
* Sort the above table by total purchase value in descending order
* Optional: give the displayed data cleaner formatting
* Display a preview of the data frame
'''
# %%
item_top_2 = pd.concat([item_top_count, item_top_avg, item_top_sum], axis = 1)
item_top_2.columns = ['Purchase Count', 'Average Purchase Price', 'Total Purchase Value']
item_top_2 = item_top_2.sort_values('Total Purchase Value', ascending=False)
item_top_2['Average Purchase Price'] = item_top_2['Average Purchase Price'].map("${:.2f}".format)
item_top_2['Total Purchase Value'] = item_top_2['Total Purchase Value'].map("${:.2f}".format)
topitem_analysis_df_2 = item_top_2.head(5)
topitem_analysis_df_2 |
5959c1c0d5751792deac3dbab234604e96439cb7 | punpraphanphoj/Project-1 | /A3dataStatistics.py | 1,680 | 3.515625 | 4 | """
Created on Thu Jan 14 16:02:20 2016
A3 Data statistics function
"""
import numpy as np
import math
def dataStatistics(data, statistics):
if statistics == "Mean Temperature":
temperature = data[:,0]
result = np.mean(temperature)
elif statistics == "Mean Growth rate":
growthRate = data[:,1]
result = np.mean(growthRate)
elif statistics == "Std Temperature":
stdTem = data[:,0]
result = np.std(stdTem)
elif statistics == "Std Growth rate":
stdGrowthRate = data[:,1]
result = np.std(stdGrowthRate)
elif statistics == "Rows":
row = np.size(data[:,0])
result = row
elif statistics == "Mean Cold Growth rate":
tem = data[:,0]
grow = data[:,1]
totalsum = 0
count = 0
for i in range(np.size(data[:,0])):
if tem[i] < 20:
totalsum = totalsum + grow[i]
count = count + 1
else:
print("Selected dataset does not contain temperature samples below 20°C")
result = totalsum/count
elif statistics == "Mean Hot Growth rate":
tem = data[:,0]
grow = data[:,1]
totalsum = 0
count = 0
for i in range(np.size(data[:,0])):
if tem[i] > 50:
totalsum = totalsum + grow[i]
count = count + 1
else:
print("Selected dataset does not contain temperature samples above 50°C")
result = totalsum/count
return result
#print(dataStatistics(dataLoad("test.txt"), "Mean Temperature"))
|
c07ab9b61466ac38b6f893b4bb6f604c9c901d5a | jinjiangliang/pythonLearner | /PythonResearch/221NumPy.py | 757 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 25 19:36:30 2018
@author: 1000877
2.2.1: Introduction to NumPy Arrays
Learn how to import NumPy
Learn how to create simple NumPy arrays, including vectors and matrices of zeros and ones
n-dimentional;
C, C++
linear algebra
numpy.org;
"""
import numpy as np
zero_vector = np.zeros(5)
zero_matrix = np.zeros((5,3))
x = np.array([1,2,3])
y = np.array([3,6,9])
[[1,3],[5,9]]
A = np.array([[1,3],[5,9]])
A.transpose()
#Transpose
'''
True or False: a numpy array's length may be modified after being created.
False
//
numpy.array([0., 0., 0., 0., 0.])
numpy.zeros(5)
//
Consider the following code:
x = numpy.array([[3,6],[5,7]])
y = x.transpose()
print(y)
What does this print?
array([[3 5],[6 7]])
'''
|
2cd06ee91417cff3f075f252431fca211f612c26 | SurajSarangi/Python | /Python/school_salary.py | 334 | 3.765625 | 4 | """Displaying salary in tabular format depending on years of experience"""
s=eval(input("Enter starting salary:\n"))
p=eval(input("Enter percentage increase:\n"))
y=eval(input("Enter number of years:\n"))
print("{0:<8} | {1:<8}".format("Years:","Salary:"))
for i in range (1,y+1):
s+=(p/100)*s
print("{0:>8} | {1:^.2f}".format(i,s)) |
fc5acf6505e90ff4f7016a432f53c01a1abcff7d | hansinla/Qualtity_Code | /Lesson code/Palindrome.py | 221 | 4 | 4 | def is_palindrome(s):
"""(str)->bool
This fundction should return True if
and only if the string s is a palindrome.
>>> is_palindrome('noon')
True
>>> is_palindrome('racecar')
True
>>> is_palindrome('ented')
False
"""
|
b9941081bfa0d9e429467c515d0f1aa23d25bcfe | cathalhughes/data-mining | /nn.py | 1,254 | 3.53125 | 4 | # Create your first MLP in Keras
from keras.models import Sequential
from keras.layers import Dense
import numpy
import pandas as pd
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from sklearn.preprocessing import LabelEncoder
# fix random seed for reproducibility
numpy.random.seed(7)
# load pima indians dataset
dataset = pd.read_csv('Datasets/relevant_data/forBayes2.csv', )
# split into input (X) and output (Y) variables
X = dataset.iloc[:,1:7]
Y = dataset.iloc[:,7]
encoder = LabelEncoder()
encoder.fit(Y)
encoded_Y = encoder.transform(Y)
# convert integers to dummy variables (i.e. one hot encoded)
dummy_y = to_categorical(encoded_Y)
X_train, X_test, y_train, y_test = train_test_split(X, dummy_y, test_size = 0.2)
print(X, Y)
# create model
model = Sequential()
model.add(Dense(12, input_dim=6, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(3, activation='sigmoid'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit the model
model.fit(X_train, y_train, epochs=150, batch_size=10)
# evaluate the model
scores = model.evaluate(X_test, y_test)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) |
d98b84de7d8e9d28715d7da26869eda4e4125c91 | samanthaWest/Python_Scripts | /AlgoDaily/TwoStackQueue.py | 952 | 3.671875 | 4 | # import functools
# import math
# import numpy
# Two Stack Queue
# Stack LIFO
# Queue FIFO
# Implementing Queue using 2 stacks
#
class TwoStackQueue:
def __init__(self):
self.s1 = []
self.s2 = []
def en(self, e):
self.s1.append(e)
def de(self):
if not self.s2:
self.s2 = list(reversed(self.s1))
self.s1 = []
return self.s2.pop()
def isEmpty(self):
# Returns True if both stacks are empty, otherwise False
return True if not self.s2 and not self.s1 else False
def size(self):
# Returns size of stacks = queue
return len(self.s1) + len(self.s2)
if __name__ == '__main__':
print("TWO STACK QUEUE")
q = TwoStackQueue()
q.en('a')
q.en('b')
print(q.isEmpty())
print(q.size())
print(q.de())
q.en('c')
print(q.de())
print(q.de()) |
5ead8e1accb928c42ef3f18674536e443ae6f072 | frclasso/1st_Step_Python_Fabio_Classo | /Cap12_Estruturas_de_dados/9.3_Dicionarios/2020/dicionarios_2020.py | 2,602 | 4.03125 | 4 | #!/usr/bin/env python3
#dicionario vazio
al = {}
aluno = {'ID': 1223,
'Nome':'Fabio',
'Sobrenome':'Classo',
'Idade': 45,
'Curso': 'Sistemas de Informação',
'Turno':'Noturno'
}
print(f"ID: {aluno['ID']}")
print(f"Nome: {aluno['Nome']}")
print(f"Idade:{aluno['Idade']}")
# Atualizando valores existentes
aluno['Idade'] = 28
print(aluno)
# Inserindo novo campo
aluno['Matrícula'] = 8990020198
print(aluno)
aluno.update({'Curso':'Cienccias da Coputacao'})
print(aluno)
aluno.update({'Unidade Educacional': 'Florianopolis Centro'})
print(aluno)
'''Deletando items'''
aluno.__delitem__('Idade')
print(aluno)
aluno.pop('Turno')
print(aluno)
#
del aluno['Matrícula']
print(aluno)
"""Apagando todos os dados"""
aluno.clear()
print(f'clear:',aluno) # {}
# Deletando o dicionario em si
# del aluno
#print(aluno) # NameError: name 'aluno' is not defined
print(f'Tamanho do dicionario: {len(aluno)} items.')
# Imprimindo um dicionario com as chaves - keys()
print(aluno.keys())
# Imprimindo um dicionario com os valores - values()
print(aluno.values())
# Imprimindo um dicionario com todos os items
print(aluno.items())
# A funcao dict()
aluno2 = dict(nome='Giovanna', idade='7', turno='matutino', unidade_educacional='Santo Antonio de Lisboa')
print(aluno2)
print()
# loops
questions = ['name', 'questions', 'favourite color']
answer = ['Lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answer):
print("What's yours {}? It's {}".format(q, a))
print()
# -- criando um dicionarios a partir de outra estrutura de dados
respostas = {}
for q, a in zip(questions, answer):
respostas[q] = a
print(respostas)
# Chaves repetidas
aluno3 = {'nome':'Erick', 'idade':11, 'turno':'vespertino', 'unidade_educacional':'centro', 'nome':'Perdro'}
print(aluno3)
# conversao (tupla para dict) -erro
#aluno4 = dict(nome='Erick', idade=11, turno='verpertino', unidade_educacional='Santo Antoio de Lisboa', nome='Pedro')
# print(aluno4)
# copy()
aluno5 = aluno3.copy()
print(aluno5)
aluno5['nome']='Vinicius'
print(aluno5)
# fromkeys()
novo_aluno = ['nome', 'idade', 'turno', 'unidade_educaional']
dict_aluno = dict.fromkeys(novo_aluno)
print('Novo aluno: {}'.format(str(dict_aluno))) # nenhum valor foi definido para 'value'
# procurando chaves inexistentes
#print(aluno5['phone'])
print(aluno5.get('phone','Key Not Found!'))
# Definindo valores padrao
aluno6 = {'nome':'Fernanda'}
aluno6.setdefault('idade', 33)
aluno6.setdefault('turno', 'noturno')
aluno6.setdefault('unidade_educacional', 'Centro')
print(aluno6)
|
ce567f6ddc62685dc7f18f760af4446a6c349a8c | Amathlog/MTH6412B | /TP1/unionFind.py | 935 | 3.96875 | 4 | # -*- coding: utf-8 -*-
class UnionFind(object):
def __init__(self):
self.__parent = dict()
self.__rang = dict()
def make_set(self, item):
self.__parent[item] = item
self.__rang[item] = 0
def find(self, item):
""" Compression des chemins. Le parent de chaque noeud de l'arbre
est la racine de l'arbre"""
if self.__parent[item] != item:
self.__parent[item] = self.find(self.__parent[item])
return self.__parent[item]
def union(self, item1, item2):
root1 = self.find(item1)
root2 = self.find(item2)
if self.__rang[root1] < self.__rang[root2]:
self.__parent[root2] = self.__parent[root1]
elif self.__rang[root1] > self.__rang[root2]:
self.__parent[root1] = self.__parent[root2]
else:
self.__parent[root2] = self.__parent[root1]
self.__rang[root1] += 1
|
7f698dd9c19fe40b1e895b20938ff096c4f9720e | dschoonwinkel/NetworkingPGCourse | /Activity1BashPrimer/python_populator.py | 293 | 3.515625 | 4 | import time
file1 = open("some_text.txt", 'w')
file1.close()
write_count = 0
while(True):
file1 = open("some_text.txt", 'a')
print("Writing to std_out %d" % write_count)
file1.write("Writing to file %d \n" % write_count)
write_count += 1
time.sleep(3)
file1.close()
|
d22f0806ec754c0aedca4cd5e09ded9b61dca7e7 | Ewa-Gruba/Building_AI | /Scripts/C1E1_Optimalization.py | 710 | 3.8125 | 4 |
import math
import random
import numpy as np
import io
from io import StringIO
portnames = ["PAN", "AMS", "CAS", "NYC", "HEL"]
def permutation(start, end=[]):
if len(start) == 0:
if end[0] == 0:
print(' '.join([portnames[i] for i in end]))
else:
for i in range(len(start)):
permutation(start[:i] + start[i+1:], end + start[i:i+1])
def permutations(route, ports):
routes = route + ports
permutation(routes)
# write the recursive function here
# remember to print out the route as the recursion ends
# this will start the recursion with 0 as the first stop
permutations([0], list(range(1, len(portnames))))
|
bfa65d91ff23f2c5c291ba4a6450c2acb279d838 | dmil/raspberrypi | /main2.py | 535 | 3.625 | 4 | #!/usr/bin/env python
"""
main.py - turns light red if I might need an umbrella today, and green if I won't
"""
from weather import rain
import rgbled
import RPi.GPIO as GPIO
import time
import rgbled
from weather import rain
GPIO.setmode(GPIO.BCM)
GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True:
input_state = GPIO.input(26)
if input_state == True:
print('Button Pressed')
rgbled.on()
if rain():
rgbled.red()
else:
rgbled.green()
time.sleep(20)
rgbled.off()
rgbled.cleanup()
|
eca2f753aacff678567625016d7e98882478ab20 | gautamsreekumar/tictactoe | /tictactoe.py | 3,032 | 4.125 | 4 | from numpy import *
from os import *
def markPosition(canvas, playername, n):
moves = int(raw_input("Enter position "))
x = int(moves/10)-1
y = int(moves%10)-1
if x > n-1 or y > n-1:
print "Invalid position"
temp = markPosition(canvas, playername, n)
elif canvas[x, y] == 2*n:
canvas[x, y] = playername
temp = canvas
else:
print "Position occupied"
temp = markPosition(canvas, playername, n)
return temp
def displayCanvas(canvas, n):
system('clear')
print " 1 2 3\n"
for i in range(0, n):
temp = ""
for j in range(0, n):
if (canvas[i, j] == 2*n):
temp += '- '
elif (canvas[i, j] == 1):
temp += 'x '
elif (canvas[i, j] == 2):
temp += 'o '
print i+1, " ", temp, "\n"
# this is a multiplayer version of tic tac toe
print "The canvas will be a square whose side length you can set"
n = raw_input("Enter the dimension of the canvas you want to play on") # you can set the size of the canvas
canvas = 2*n*ones((n, n)) # this is the canvas that will be displayed
seals = ['x', 'o']
# the valid inputs are 1 and 2. 1 for x and 2 for o
# the player has mention the position using two digits
# such as 11, 12, 32, 23, etc.
# the indices of the columns are {1, 3} starting from top, while the indices of the rows are {1, 3} starting from left
print "Player 1's moves are shown as x and Player 2's moves are shown as o\n"
print "Enter the position for each move as numbers from 1 to 3"
print "For example, 12 means the move is on row 1 and column 2\n"
name = ["", ""]
name[0] = raw_input("Enter player 1's name ")
name[1] = raw_input("Enter player 2's name ")
print "Are you ready to begin? [press ENTER]"
raw_input()
# inputting moves in a loop until someone wins
gameon = True
playername = 1
move_count = 0
while gameon and move_count < 9:
displayCanvas(canvas, n)
row_sum = sum(canvas, 1)
column_sum = sum(canvas, 0)
diagonal_sum = trace(canvas)
adiagonal_sum = trace(fliplr(canvas))
print "row_sum ", row_sum
print "column_sum ", column_sum
print "diagonal_sum ", diagonal_sum
print "adiagonal_sum ", adiagonal_sum
print name[playername-1], "'s move"
print move_count
print (2*n in column_sum)
canvas = markPosition(canvas, playername, n)
row_sum = sum(canvas, 1)
column_sum = sum(canvas, 0)
diagonal_sum = trace(canvas)
adiagonal_sum = trace(fliplr(canvas))
if (n in row_sum) or (n in column_sum) or diagonal_sum == n or adiagonal_sum == n:
gameon = False
displayCanvas(canvas, n)
print name[0], " wins"
elif (2*n in row_sum) or (2*n in column_sum) or diagonal_sum == 2*n or adiagonal_sum == 2*n:
gameon = False
displayCanvas(canvas, n)
print name[1], " wins"
else:
playername = 3 - playername
move_count += 1
if gameon:
print "Draw"
|
cdbb1dc82dac13f36383f179e2df457c3bf5a1b1 | reshmaladi/Python | /1.Class/Language_Python-master/Language_Python-master/LC25_1_IPaddressChecking.py | 751 | 3.640625 | 4 |
import re
def checkip(ip):
pattern = re.compile("(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})")
k=re.match(pattern,ip)
type=k.group(1)
print(type)
type = int(type)
if(int(k.group(2))<256 and int(k.group(3))<256 and int(k.group(4))<256):
if(type<127 and type>0):
print("Class A")
elif(type<192 and type>127):
print("Class B")
elif(type<127 and type>192):
print("Class C")
elif(type<192 and type>224):
print("Class D")
elif(type<224 and type>256):
print("Class E")
else:
print("Invalid IP")
else:
print("Invalid IP")
def main():
ip=input("Enter IP:\t")
checkip(ip)
if __name__=='__main__':
main()
'''
try:
n=10/0
except ZeroDivisionError as e:
print(e,"222")
except Exception as e:
print(e,"111")
''' |
46b6e19cee41566551164635cb3daca26a6a396d | HiCitron/PythonOftenUsed | /chars.py | 1,422 | 3.75 | 4 | # -*- coding: utf-8 -*-
def IsNumber(s):
for i in range(len(s)):
k = ord(s[i])
if not(k >= 48 and k <= 57 ):
return False
return True
def IsUpper(s):
for i in range(len(s)):
k = ord(s[i])
if not(k >= 65 and k <= 90 ):
return False
return True
def IsLower(s):
for i in range(len(s)):
k = ord(s[i])
if not(k >= 97 and k <= 122 ):
return False
return True
def IsLetter(s):
for i in range(len(s)):
k = ord(s[i])
if not(k >= 65 and k <= 90 ) and not(k >= 97 and k <= 122):
return False
return True
def IsAlphanum(s):
for i in range(len(s)):
k = ord(s[i])
if not(k >= 65 and k <= 90 ) and not(k >= 97 and k <= 122) and not(k >= 48 and k <= 57 ):
return False
return True
def IsSpecial(s):
for i in range(len(s)):
k = ord(s[i])
if not( not(k >= 65 and k <= 90 ) and not(k >= 97 and k <= 122) and not(k >= 48 and k <= 57 ) ):
return False
return True
def StringIs(s):
t = []
for i in range(len(s)):
k = ord(s[i])
if (k >= 48 and k <= 57 ):
t += [0]
elif (k >= 65 and k <= 90 ):
t += [1]
elif (k >= 97 and k <= 122 ):
t += [2]
else:
t += [3]
return t
|
dca811d735a4d086641730c3537c30a9240fb1d0 | brisa123/palindrome | /practice.py | 147 | 3.53125 | 4 |
a="i am a girl"
b=a.capitalize()
print(b)
c=a.split()
print(c)
'''wkejfnwjiefjnf
sdfkfjnsalkgm
wlggknwrlg
woekfowkenmf
ewlkfnwrg
weflkwng'''
|
efec61863383cf738f3ff00e6e8ffc0441232a54 | jeromejohnenriquez1121/SJSU_CMPE130_Project | /school_content.py | 7,488 | 3.890625 | 4 | # a module with the information and functions about the students and assignments
'''
The school_content module has a 'student' class. The student has a full name, an email
address, an ID number, and a list of grades. The students can be sorted by their names
or their ID numbers; their grades can also be sorted from lowest to highest, in order to
easily get each student's grade quartiles and average grade.
We will sort each student's grades with the quick sort algorithm; the specialized QuickSort()
class will take in any array of numbers and sort them. The sort_grades() function in our
student class will make use of this function.
'''
def get_median_index(array, lo, hi):
# returns median of 'array'
# lo: index 0 of 'array'
# hi: last index of 'array'
n = hi - lo + 1
n2 = (n + 1) // 2 - 1
return n2 + lo
class QuickSort:
# only two functions needed: partition and quicksort
# 'collection': the array to be sorted
def partition(self, collection, lo, hi):
# hi = len(collection) - 1
j = lo # collection[j] and everything behind it must be less than pivot
pivot = hi # selecting last item as pivot
# what do we know? We know that we must go from lo to hi, until we find an item less than the pivot
# we use i and j for this, i is in the for loop, j is the index for most recent element < pivot element
for i in range(lo, hi):
# when collection[i] < collection[pivot], we've found a left partition item
# we swap collections[i] and collections[j], so now j is the first element < pivot
# we increment j to move on to find the next element < pivot
if (collection[i] < collection[pivot]):
collection[i], collection[j] = collection[j], collection[i]
j += 1
# now we swap our 'marker' j with the pivot
collection[pivot], collection[j] = collection[j], collection[pivot]
return j
def quicksort(self, collection, lo, hi):
# hi = len(collection) - 1
if (lo < hi):
pivot = self.partition(collection, lo, hi)
self.quicksort(collection, lo, pivot - 1)
self.quicksort(collection, pivot + 1, hi)
class student:
def __str__(self):
ret = "name:\t" + self.name + "\n"
ret += "student ID:\t" + self.student_id + "\n"
ret += "Email:\t" + self.email + "\n"
if self.completed:
ret += "Grades:\t" + str(self.grades) + "\n"
ret += "Average:\t" + str(self.avg) + "\n"
ret += "Quartiles:\t" + str(self.quartiles) + "\n"
ret += "STATUS:\t" + self.student_status() + "\n"
else:
print("*** Grades calculations have not been made for this student yet ***")
return ret
def __init__(self, name, student_id, email, grades=[], avg=0, quartiles=[], completed = False):
self.name = name
self.student_id = student_id
self.email = email
self.grades = grades
self.avg = avg
self.quartiles = quartiles
self.completed = completed
def add_grade(self):
# adds a grade to the 'grades' list
print("--------------")
total = float(input("Total Points Possible on Assignment: "))
pts = float(input("Points Earned: "))
letter_grade = (pts / total) * 100
self.grades.append(letter_grade)
# calls quicksort function from QuickSort class
def sort_grades(self):
n = len(self.grades)
QuickSort().quicksort(self.grades, 0, n - 1)
def calculate_grade_quartiles(self):
# calculate grade quartiles with global median function
# Q1 (lower quartile): median of lower half
# Q2: median
# Q3 (upper quartile): median of upper half
q1 = 0
q2 = 0
q3 = 0
n1 = len(self.grades)
# 1. make sure array is sorted in ascending order
self.sort_grades()
# 2. find median of array to divide it in lower and upper half
index_mid = get_median_index(self.grades, 0, n1)
# for [65, 70, 80, 90], index_mid returned 2, i.e. the index of 80
# this happened when I tested an 8-element-long list in IDLE too
# for even numbers, get_median_index() returns the index of the second median #
if (n1 % 2 == 0):
num1 = self.grades[index_mid - 1]
num2 = self.grades[index_mid]
q2 = (num1 + num2) / 2
else:
q2 = self.grades[index_mid]
# now to find q1 and q3
# q1: median of lower half
# q3: median of upper half
lower_half = self.grades[0:index_mid]
n2 = len(lower_half)
upper_half = self.grades[index_mid:]
n3 = len(upper_half)
# we will use same odd array length vs. even array length process for each half of the array
# that we used for the whole array
indexmid_2 = get_median_index(lower_half, 0, n2) # median index of lower half
if (n2 % 2 == 0):
num1 = lower_half[indexmid_2 - 1]
num2 = lower_half[indexmid_2]
q1 = (num1 + num2) / 2
else:
q1 = lower_half[indexmid_2]
indexmid_3 = get_median_index(upper_half, 0, n3) # median index of upper half
if (n3 % 2 == 0):
num1 = upper_half[indexmid_3 - 1]
num2 = upper_half[indexmid_3]
q3 = (num1 + num2) / 2
else:
q3 = upper_half[indexmid_3]
newlist = [q1, q2, q3]
self.quartiles = newlist.copy()
def get_quartiles(self):
return self.quartiles
def calculate_average(self):
# get average grade
avg_grade = 0
# we must divide sum of weighted grades by sum of weights
grade_sum = 0
wt_sum = 0
# first, multiply each grade by its weight
# next, add up the numbers
for grade in self.grades:
wt = float(input(f"Grade Weight (e.g. for 20% weight, type 0.2) for {grade}: "))
grade *= wt
grade_sum += grade # remember, grade_sum: sum of WEIGHTED grades
wt_sum += wt
# finally, do the division and store result in 'avg' variable
avg_grade = grade_sum / wt_sum
self.avg = avg_grade
self.completed = True
def get_average(self):
return self.avg
def student_status(self):
# compares average grade with passing grade
# any grade below passing - 'need to improve'
# 70-79: 'ok, but could be better'
# 80-89: 'ok/good'
# 90-99: 'excellent/amazing'
passing = 70.00
temp_name = self.name
ret = ""
if (self.avg < passing):
ret = temp_name + " has a low grade in the class and needs to improve. They should do the assignments and try to get high scores on the exams to raise their grade\n"
elif (self.avg >= passing and self.avg <= 79):
ret = temp_name + " is passing the class, but could be doing much better. They should keep up with the assignments and study hard for the exams.\n"
elif (self.avg >= 80 and self.avg <= 89):
ret = temp_name + " has a good grade in the class and can bump it up to an A if they do well in the exams.\n"
else:
ret = temp_name + "'s grade is excellent! To keep it up, they should still try and do well on the exams.\n"
return ret
|
945b7bfbdf8e92a61122fb4fe18c40c55df4e98e | dbarella/ArrowLanguage | /datatypes.py | 7,220 | 3.625 | 4 | import numbers, functools, evaluator, inverter, shared
@functools.total_ordering
class Num:
"""
Because floating-point numbers lead to irreversibility, infinite-precision
rational numbers are used in Arrow.
"""
def __init__(self, top, bottom=None, sign=None):
"""
Nums store a numerator, denominator, and sign (either 1 or -1).
"""
if bottom is None:
bottom = 1
if sign is None:
# If top and bottom's signs match, self.sign is positive.
if (bottom > 0) == (top > 0):
self.sign = 1
# Otherwise it's negative.
else:
self.sign = -1
else:
self.sign = sign
# Top and bottom are positive only, since +/- is stored in self.sign.
self.top = abs(top)
self.bottom = abs(bottom)
# Because Nums are immutable, a reduction to lowest terms
# in the constructor ensures they are always in lowest form.
self.reduce()
@staticmethod
def gcd(a, b):
# Euclid's algorithm.
while True:
a, b = b, a % b
if b == 0:
return a
def reduce(self):
"""
Reduce this fraction to lowest terms.
"""
# While the top and bottom have a factor in common, divide it out.
while True:
d = Num.gcd(self.top, self.bottom)
if d == 1:
break
# Integer division here because the whole point
# is to remain within the integers!
self.top, self.bottom = self.top // d, self.bottom // d
def reciprocal(self):
return Num(self.bottom, self.top, sign=self.sign)
def __add__(self, other):
# a/b + c/d = (ad)/(bd) + (bc)/(bd) = (ad + bc)/(bd)
a, b, c, d = self.top, self.bottom, other.top, other.bottom
return Num(a*self.sign*d + b*c*other.sign, b*d)
def __sub__(self, other):
return self + (-other)
def __neg__(self):
return Num(self.top, self.bottom, sign=-self.sign)
def __mul__(self, other):
return Num(self.top*other.top, self.bottom*other.bottom,
sign=self.sign*other.sign)
def __truediv__(self, other):
return self * other.reciprocal()
def __mod__(self, other):
return Num(self.top % other.top)
__rmul__ = __mul__
__radd__ = __add__
__rsub__ = lambda self, other: -self + other
__rtruediv__ = lambda self, other: self.reciprocal() * other
def __repr__(self):
if self.bottom == 1:
return str(self.top * self.sign)
else:
return "({}/{})".format(self.top * self.sign, self.bottom)
def __eq__(self, other):
return (
self.top == other.top
and self.bottom == other.bottom
and self.sign == other.sign
)
def __lt__(self, other):
return True if (self - other).sign == -1 else False
class Function:
"""
Functions are first-class objects in Arrow.
"""
def __init__(self, name, ref_parameters, const_parameters, block):
"""
Functions store
- their name
- their code
- their parameters and those parameters' types, in L-to-R order.
- a list of their entry conditions (in bottom-up order).
"""
self.name = name
self.block = block
self.ref_parameters = ref_parameters
self.const_parameters = const_parameters
def evaluate(self, backwards, ref_arg_vars, ref_arg_vals, const_arg_vals):
"""
Given a list of reference and constant args, evaluates functions.
Returns a memory table.
"""
# Create a memory table for the function by zipping up
# the arguments into (parameter, value) pairs.
table = evaluator.Memory(
zip([var.name for var in self.ref_parameters], ref_arg_vals),
zip([var.name for var in self.const_parameters], const_arg_vals)
)
# Go up from the bottom, looking for enter statements, in order to
# find out where we should start executing.
# The backwards flag tells us whether we are calling or uncalling.
block = inverter.unblock(self.block) if backwards else self.block
# TODO: this approach only finds un-nested enter statements.
to_execute = []
for node in reversed(block.statements):
if node.kind == "ENTER":
if evaluator.expr_eval(node.condition, table):
table["result"] = evaluator.expr_eval(node.value, table)
break
to_execute.append(node)
block_to_execute = self.block.replace(statements=to_execute[::-1])
# Execute the block. If it returns, catch the return exception
# and update the table accordingly.
try:
table = evaluator.block_eval(block_to_execute, table)
except shared.ReturnException as e:
table["result"] = e.value
# Go through the variable names in the function's memory table
# and change them to the new names.
for arg, param in zip(ref_arg_vars, self.ref_parameters):
table.refs[arg.name] = table.refs[param.name]
# If a function like
#
# f (ref x){
# ...
# }
#
# was called like
#
# f(&x)
#
# then we shouldn't delete 'x' from the resulting memory table.
if arg.name != param.name:
del table.refs[param.name]
return table
class List:
"""
Arrow's list/array datatype, also serving as a stack.
"""
def __init__(self, contents):
self.contents = contents
def push(self, data):
self.contents.push(data)
def pop(self):
return self.contents.pop()
def check_index(self, index):
"""
Raises an error if the index isn't valid.
"""
if index.bottom != 1:
pass
#Only access arrays with whole indices!
elif index.top >= len(self):
pass
#Array out of bounds error!
elif index.sign == -1:
pass
#Indexes can't be negative!
def __getitem__(self, index):
self.check_index(index)
# After checking, we know the index is n/1 so we just grab index.top
return self.contents[index.top]
def __setitem__(self, index, value):
self.check_index(index)
# Again, the index is n/1 at this point.
self.contents[index.top] = value
def __len__(self):
return len(self.contents)
def __repr__(self):
return self.contents.__repr__()
class String:
"""
Arrow's string datatype.
"""
def __init__(self, python_str):
self.str = python_str
def __add__(self, other):
return self.str + other.str
def __repr__(self):
return self.str
if __name__ == "__main__":
x = Num(-1)
y = Num(1, 2)
print(x)
print(-y)
print(y - x)
print(x / y) |
7f0afe650638d180d15316bf2d203d74d3273dce | GregBlockSU/iSchool | /ist652/Week8/twitter_hashtags.py | 3,266 | 3.71875 | 4 | '''
This program processes a DB collection of tweets and returns the top frequency hashtags.
The Mongod server must be running.
The number parameter is the number of top frequency hashtags to print.
Usage: python twitter_hashtags.py <DBname> <DBcollection> <number>
Example: python twitter_hashtags.py mmquery mmv1 20
'''
import sys
from operator import itemgetter
from DB_fn import load_from_DB
# this program contains a function to return lists of some twitter entities
# for each tweet, this function returns lists of the entities: mentions, hashtags, URLs
# Parameter: a tweet (as a Twitter json object)
# Result: 3 lists of the above entities
def get_entities(tweet):
# make sure this is a tweet by checking that it has the 'entities' key
if 'entities' in tweet.keys():
# list of mentions comes from the 'screen_name' field of each user_mention
mentions = [user_mention['screen_name'] for user_mention in tweet['entities']['user_mentions']]
# list of hashtags comes from the 'text' field of each hashtag
hashtags = [hashtag['text'] for hashtag in tweet['entities']['hashtags']]
# list of urls can come either from the 'url' field or 'expanded_url' field of each url
urls = [urlitem['url'] for urlitem in tweet['entities']['urls']]
urls = urls + [urlitem['expanded_url'] for urlitem in tweet['entities']['urls']]
# we ignore the symbols and optional media entity fields
return mentions, hashtags, urls
else:
# if no entities key, return empty lists
return [], [], []
# use a main so can get command line arguments
if __name__ == '__main__':
# Make a list of command line arguments, omitting the [0] element
# which is the script itself.
args = sys.argv[1:]
if not args or len(args) < 3:
print('usage: python twitter_hashtags.py <DBname> <DBcollection> <number>')
sys.exit(1)
DBname = args[0]
DBcollection = args[1]
limit = int(args[2])
# load all the tweets
tweet_results = load_from_DB(DBname, DBcollection)
# Create a frequency dictionary of the hashtags,
# a dictionary where the keys are hashtags and the values are the frequency (count)
hashtag_fd = {}
for tweet in tweet_results:
# get the three entity lists from this tweet
(mentions, hashtags, urls) = get_entities(tweet)
# put the hashtags in the frequency dictionary
for tag in hashtags:
# if the tag is not yet in the dictionary, add it with the count of 1
if not tag in hashtag_fd:
hashtag_fd[tag] = 1
else:
# otherwise, add 1 to the count that is already there
hashtag_fd[tag] += 1
# sort the dictionary by frequency values, returns a list of pairs of words and frequencies
# in decreasing order
hashtags_sorted = sorted(hashtag_fd.items(), key=itemgetter(1), reverse=True)
# print out the top number of words with frequencies
# go through the first 20 tweets and find the entities
print("Top", limit, "Frequency Hashtags")
for (word, frequency) in hashtags_sorted[:limit]:
print (word, frequency)
|
de761230b22c343cde9f22d47e84345128d717b8 | noamoalem/intro | /ex7/ex7.py | 6,776 | 4.46875 | 4 | #################################################################
# FILE : ex7.py
# WRITER : noa moalem , noamoa , 208533554
# EXERCISE : intro2cs ex7 2019
# DESCRIPTION: we asked to write 10 recursive function
# #################################################################
def print_to_n(n):
"""This function print the number from n to 1 in ascending order """
if n < 1: # if n is smaller then 1 we won't print anything & base case
return
print_to_n(n - 1)
print(n)
def print_reversed(n):
"""This function print the number from 1 to n in descending order"""
if n < 1: # if n is smaller then 1 we won't print anything & base case
return
print(n)
print_reversed(n - 1)
def check_prime(n, d):
"""This function find if n is a prime number """
if n % d == 0:
return False
if n < d * d: # check all divisors till sqrt
return True # because all numbers till sqrt of n not divides n
return check_prime(n, d + 1)
def is_prime(n):
"""This function return true if a number is a prime number and false if
it's not """
if n <= 1: # n is not a prime number
return False
if n == 2:
return True
return check_prime(n, 2)
def factorial(n):
"""This function calculate n!"""
if n == 0:
return 1
return n * factorial(n - 1)
def exp_n_x(n, x):
"""This function calculate tne exponential function sum which is:
∑ x^i/x! """
if n == 0:
return 1
else:
return (x ** n / factorial(n)) + exp_n_x(n - 1, x)
def play_hanoi(hanoi, n, src, dest, temp):
"""This function run the game Tower of Hanoi"""
if n <= 0:
return
play_hanoi(hanoi, n - 1, src, temp,
dest) # move n-1 disks from src to temp
hanoi.move(src, dest) # move the last disk from src to dest
play_hanoi(hanoi, n - 1, temp, dest,
src) # move n-1 disks from temp to dest
def print_sequences_helper(char_list, n, combination):
"""This function receives a list of characters, and prints all possible
combinations of characters in length of n with characters from the given
list"""
if n == 0:
print("")
return
if n == 1:
for i in char_list:
print(i)
return
if len(combination) == n:
print(combination)
return
elif len(combination) < n:
for i in char_list:
combination += i
print_sequences_helper(char_list, n, combination)
combination = combination[:-1]
return
def print_sequences(char_list, n):
"""This function use the print_sequences_helper to prints all possible
combinations of characters in length of n with characters from the given
list"""
return print_sequences_helper(char_list, n, "")
def print_no_repetition_sequences_helper(char_list, n, combination):
"""This function receives a list of characters to prints all possible
combinations of characters in length of n with characters from the given
list without repetition"""
if n == 0:
print("")
return
if n == 1:
for i in char_list:
print(i)
return
if len(combination) == n:
print(combination)
return
elif len(combination) < n:
for i in char_list:
if i not in combination: # so we won't have repetition
combination += i
print_no_repetition_sequences_helper(char_list, n, combination)
combination = combination[:-1]
return
def print_no_repetition_sequences(char_list, n):
"""This function use the print_no_repetition_sequences_helper to prints all
possible combinations of characters in length of n with characters from
the given list without repetition"""
return print_no_repetition_sequences_helper(char_list, n, "")
print(print_no_repetition_sequences("012",2))
def parentheses_helper(n, open, close, str, final):
"""This function find all the balanced combinations of parentheses in len
of n"""
if n == 0:
final.append("")
return final
if close == n: # we have balanced combination
final.append(str)
return
if open < n: # we will not have more then n "("
parentheses_helper(n, open + 1, close, str + "(", final)
if open > close: # we will have the same amout of "(" and ")"
parentheses_helper(n, open, close + 1, str + ")", final)
return final
def parentheses(n):
"""This function find all the balanced combinations of parentheses in len
of n"""
return parentheses_helper(n, 0, 0, "", [])
def up_and_right_helper(char_list, n, k, way):
"""This function prints all the ways to reach the (n, k) only by steps
right or up"""
if n+k == 0:
print("")
return
if len(way) == n+k:
print(way)
return
elif len(way) < n+k:
for i in char_list:
if i == "r":
if way.count(i) < n: # so we still need to go right
way += i
up_and_right_helper(char_list, n, k, way)
way = way[:-1]
else:
if way.count(i) < k: # so we still need to go up
way += i
up_and_right_helper(char_list, n, k, way)
way = way[:-1]
return
def up_and_right(n, k):
"""This function use the up_and_right_helper to prints all the ways to
reach the (n, k) only by steps right or up"""
return up_and_right_helper(["r", "u"], n, k, "")
def flood_fill(image, start):
"""This function fill the empty places on the board with *, according to
the rules"""
image[start[0]][start[1]] = "*" # fill this place with *
for i in ["d", "u", "r", "l"]: # the direction we need to search in
if i == "d":
new_start = [start[0] + 1, start[1]] # change the start position
if image[new_start[0]][new_start[1]] == ".":
# we need to fill this place
flood_fill(image, new_start) # call the function again to
# fill this place and keep searching for places to fill
if i == "u":
new_start = [start[0] - 1, start[1]]
if image[new_start[0]][new_start[1]] == ".":
flood_fill(image, new_start)
if i == "r":
new_start = [start[0], start[1] + 1]
if image[new_start[0]][new_start[1]] == ".":
flood_fill(image, new_start)
if i == "l":
new_start = [start[0], start[1] - 1]
if image[new_start[0]][new_start[1]] == ".":
flood_fill(image, new_start)
|
01a0e26ada1e183ff9d65d4e2196177cb0ad8863 | daniel-reich/ubiquitous-fiesta | /sDvjdcBrbHoXKvDsZ_24.py | 114 | 3.625 | 4 |
def anagram(name, words):
name = name.replace(" ","").lower()
return sorted("".join(words)) == sorted(name)
|
18ae81b7575762b250afdc7035ae8483ab6f8f4a | lakshmipraba/New-two | /search.py | 457 | 4.0625 | 4 | def search(sorted_list,n):
i=0
while(i<=int(new)):
if(sorted_list[i]==n):
print "ur element in the %r position of the list"%i
exit(0)
else:
exit
i=i+1
print "-1"
sorted_list=[]
i=0
new=raw_input("enter the no.of elements in ur list:")
while(i<=int(new)):
print "the %r element in the list"%i
a=raw_input()
sorted_list.append(a)
i=int(i)+1
print sorted_list
n=raw_input("enter the element u want to search:")
search(sorted_list,n)
|
4dedf03cb9ef479426f56d4206a2192afae54ab2 | jessiditocco/interview_prep | /hackerrank/problem_solving/algorithms/diagonal_difference.py | 1,116 | 4.03125 | 4 | def diagonal_difference(matrix, num):
diagonal1 = 0
diagonal2 = 0
for i in range(num):
diagonal1 += matrix[i][i]
diagonal2 += matrix[i][(num - 1) - i]
return abs(diagonal1 - diagonal2)
print diagonal_difference([
[11, 2, 4],
[4, 5, 6],
[10, 8, -12]
], 3)
# diagonal1 = matrix[0][0] + matrix[1][1] + matrix[2][2]
# diagonal2 = matrix[0][2] + matrix[1][1] + matrix[2][0]
# #!/bin/python
# import math
# import os
# import random
# import re
# import sys
# # Complete the diagonalDifference function below.
# def diagonalDifference(a):
# len_a = len(a)
# sum_d1 = 0
# sum_d2 = 0
# for i in range(len_a):
# sum_d1 += a[i][i]
# sum_d2 += a[i][(len_a - 1) - i]
# return abs(sum_d1 - sum_d2)
# if __name__ == '__main__':
# fptr = open(os.environ['OUTPUT_PATH'], 'w')
# n = int(raw_input())
# a = []
# for _ in xrange(n):
# a.append(map(int, raw_input().rstrip().split()))
# result = diagonalDifference(a)
# fptr.write(str(result) + '\n')
# fptr.close()
|
30b6660dc1a038d117e6adb5d3a32754a78f4099 | yenwel/DAT256x | /Module03/excercises.py | 165 | 3.84375 | 4 | def magnitude(x):
return sum([i**2 for i in x])**(1/2)
print([i**2 for i in [3 ,5]])
print(sum([9, 25]))
print(34**(1/2))
print(magnitude([3 ,5]))
print(2*4+5*3) |
8e89364bc15157166dc4fa6cab299a76d4483b82 | mike111452/code-practice | /code/elenen.py | 467 | 3.71875 | 4 | while True:
n=str(input())
if n == '0':
break
sum1=0
sum2=0
for i in range(1,len(n),2):
sum1=sum1+int(n[i])
for j in range(0,len(n),2):
sum2=sum2+int(n[j])
if sum2>sum1:
sum1,sum2=sum2,sum1
if (sum1-sum2)==0:
print(n,"is a multiple of 11.")
elif (sum1-sum2)%11==0:
print(n,"is a multiple of 11.")
else:
print(n,"is not a multiple of 11.")
|
6d3c055b12c84936c9cbe99849021b3da64273ec | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4081/codes/1643_869.py | 306 | 3.625 | 4 | # Teste seu código aos poucos.
# Não teste tudo no final, pois fica mais difícil de identificar erros.
# Use as mensagens de erro para corrigir seu código.
preço=float(input("sem desconto:"))
desc=(preço*5/100)
sub=(preço- desc)
if(preço>=200):
print(round(sub, 2))
else:
print(round(preço, 2)) |
5d624f375d637476c7601d16ea9ab915a0f8b776 | malyar0v/UVa-solutions | /543/543 - Goldbach's Conjecture.py | 717 | 3.625 | 4 | UPPER_BOUND = 1000000
def generate_primes():
table = {boolean: True for boolean in range(UPPER_BOUND)}
root = int(UPPER_BOUND ** 0.5)
for i in range(2, root):
index = i * 2
while True:
if index > UPPER_BOUND:
break
table[index] = False
index += i
return table
if __name__ == '__main__':
table = generate_primes()
while True:
n = int(input())
if n == 0:
break
found = False
for index in range(3, UPPER_BOUND):
a = table[index]
if a:
b = n - index
if table[b]:
print(f"{n} = {index} + {b}")
found = True
break
if not found:
print("Goldbach's conjecture is wrong.")
|
1502853316e915aee5615901940ef65c321de075 | baothais/Practice_Python | /lambda.py | 938 | 4.21875 | 4 | # thislist = list(filter(lambda x: x%2==0, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
# for i in thislist: print(i)
# thisdict = dict(brand = "Ford", model = "Everest", price = "50,000$")
# l = list(map(lambda x: x[0], thisdict.items()))
# for i in l: print(i)
# syntax
"""lambda arguments : expression""" # The expression is executed and the result is returned
# Example
x = lambda i: i*2
print(x(2))
y = lambda x, *y: x*y
print(y(2, 3, 4)) # x=2, y=(3, 4) => x * y = 2 * (3, 4) = (3, 4, 3, 4)
thistuple = 2 * (2, 4)
print(thistuple)
z = lambda x, *y, **z: f"{x} + {y} + {z}"
print(z([1, 2], 3, 4, a=2, b=3, c=4))
# Advanced example
X = [1, 2, 3, 4]
X1 = (1, 2, 3)
X2 = {
"model": "hello",
"price": "3500"
}
def parabolic(x, a=1.0, b=0.0, c=0.0):
return a * x * x + b * x + c
# Y = list(map(parabolic, X))
# for y in Y: print(y, end=' ')
print()
Y = lambda x, *y, **z: f"{x} + {y} + {z}"
print(Y(X, X1, X2))
|
f96d62b329f857259e0ebb8c144dd01f51c993dc | prolaymukherjee/PythonBasicToAdvance | /python/py12.py | 174 | 3.875 | 4 | x=int(input("Enter The First Number:"))
y=int(input("Enter The First Number:"))
z=int(input("Enter The First Number:"))
print(max(x,y,z))
input("Please press enter to exit")
|
a7f3f2529a637643e5a8e68779b0e6ff8e28f3e0 | tom-henderson/dotfiles | /scripts/num2words | 2,705 | 4.125 | 4 | #!/usr/bin/python
import sys
def bigNumbers( n, lowerBound, theWord ):
if n % lowerBound == 0:
return numberAsWords( n / lowerBound ) + ' ' + theWord
elif n - ( n / lowerBound * lowerBound ) < max( lowerBound / 1000, 100 ):
return numberAsWords( n / lowerBound ) + ' ' + theWord + ' and ' + numberAsWords( n - ( n / lowerBound * lowerBound ) )
else:
return numberAsWords( n / lowerBound ) + ' ' + theWord + ', ' + numberAsWords( n - ( n / lowerBound * lowerBound ) )
def numberAsWords(n):
"""Takes an integer and returns that number in words. Input must be no more than 15 digits in length."""
bignums = ('hundred', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion')
tens = ('ten','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety')
teens = ('eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen')
digits = ('zero','one','two','three','four','five','six','seven','eight','nine')
# greater than 9999999999
if n > 999999999999999 or n < -999999999999999:
return 'Sorry, I can\'t count that high. Try again with fewer digits.'
# Negative numbers:
if n < 0:
return 'minus ' + numberAsWords( n * - 1 )
# For future reference, as per http://en.wikipedia.org/wiki/Orders_of_magnitude
# Septillion 1000000000000000000000000
# Sextillion 1000000000000000000000
# Quintillion 1000000000000000000
# Quadrillion 1000000000000000
# Trillions
if n >= 1000000000000 and n < 1000000000000000:
return bigNumbers( n, 1000000000000, 'trillion' )
# Billions
if n >= 1000000000 and n < 1000000000000:
return bigNumbers( n, 1000000000, 'billion' )
# Millions
if n >= 1000000 and n < 1000000000:
return bigNumbers( n, 1000000, 'million' )
# Thousands
if n >= 1000 and n < 1000000:
return bigNumbers( n, 1000, 'thousand' )
# Hundreds
if n >= 100 and n < 1000:
return bigNumbers( n, 100, 'hundred' )
# greater than 10, less than 20
if n > 10 and n < 20:
return teens[n - 11]
# less than 10
if n < 10:
return digits[n]
# multiple of 10
if n%10 == 0:
return tens[(n/10)-1]
# else (2 digit numbers from 21 to 99 not multiples of 10)
return tens[(n/10)-1] + ' ' + digits[n%10]
if len(sys.argv) > 1:
for i in sys.argv[1:]:
try:
print numberAsWords(int(i))
except:
print 'Can\'t convert', i, 'to a words. Input must be an integer.'
else:
print 'Usage:', sys.argv[0], '[number] [...]'
|
662c83ad2bdd231e9296ff70e80b026dd686c465 | mrgsfl/Python-OOP-course | /python_task_2.py | 143 | 3.578125 | 4 | objects = [1, 2, 1, 2, 3, True, False, "true", '1', True]
ans = 0
s = set()
print("set: ", s)
for obj in objects:
s.add(id(obj))
print(s)
|
3ec14b058b49c2526452378dd85d02733e398c1d | allankeiiti/Python_Studying | /SoloLearn_Scripts/Strange_Root.py | 1,133 | 4.375 | 4 | # Strange Root
# A number has a strange root if its square and square rot share any digit. For example, 2 has a strange root because
# the square root of 2 equals 1.414 (consider the first three digits after the dot) and it contains 4 (which is the square
# of 2).
#
# Examples:
# Input: 11
# Output: True
# (The square root of 11 is 3.317, the square of 11 is 121. They share the same digit, 1.)
#
# Input: 24
# Output: false (the square root of 24 (4.899) and square (576) do not share any digits)
#
# Write a program to check if the user input has a strange root or not.
from math import sqrt
def check_num(num):
square = num**2
# squareRoot receives the num variable and passes by sqrt math function, later passes by round function,
# limiting the float to three decimal points
squareRoot = round(sqrt(num), 3)
square_list = [n for n in str(square)]
squareRoot_list = [n for n in str(squareRoot) if n != '.']
for n1 in square_list:
for n2 in squareRoot_list:
if n1 in n2:
return True
else:
return False
num = input('Type a Number: ') |
19c5cc14784451d9169eefa0f825cd9d702c5e1f | rambling/algo-study | /userspace/mitkim123.kim/week01/mercy_mitkim123_01.py | 321 | 3.578125 | 4 | # -*- conding: utf-8 -*-
'''
Created on 2016. 5. 16.
@author: mitkim123
'''
def main():
print("Input number ...")
a = input()
count = int(a)
if(count>0):
print("Hello Algospot!\n" * count)
else:
print("[Warning]Input number should be > 0")
if __name__ == "__main__":
main()
|
7d98ad6bcd6d6652a37386cdda2f3033933bda69 | LarsiParsii/Smarthus.gruppe9 | /Python/print_func.py | 202 | 3.5625 | 4 | import datetime as dt
def TimePrint(msg):
'''Takes an input and combines it with a timestamp, then prints it.'''
now = dt.datetime.now().strftime('%x %X')
print(f"[{now}] {msg}") |
e82c06d2dfbf9ed4590f27513dc89e58ee3322fa | sgscomputerclub/tutorials-python | /Week 2/Tutorial Walkthrough/6-Slicing.py | 1,845 | 4.34375 | 4 | '''
More Advanced Slicing Techniques
'''
l = [0,1,2,3,4,5,6,7]
print l[4:5] # Gets 5th item from the list (indexing starts from 0)
'''
Important to Note: Slicing isn't choosing the items in the list, it's about dividing the list or slicing the list. In l[4:5], imagine a cursor is placed four items in, then it's moved to the fifth position, and what it's gone over is what's returned. In other words, you're selecting around the list not the items themselves (hence why the 5th item is obtained, but not the 6th):
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
"One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0."
'''
print l[-1:-3] # returns the last two members of the list (if you use negatives, it starts from the end, see above diagram).
print l[:4] # equals l[0:4], means to get everything up to the 4th slice position
print l[2:] # Means to get everything from the second slice on: l[2:len(l)-1]
print l[::1] # same as l. the Third position is step, meaning how much to advance by each time. See next line for eg.
print l[::2] # will get every second member in list (as it jumps by 2 each time, skipping 1 item)
#Note: slicing defined as l[start:end:step] where start is the position you start to slice at, end is where you stop and step is the amount by which you move.
# Defaults: start -> 0, end -> last item in list (ie: len(l)-1), step: 1
print l[2:6:2] # will get every second item between the 3rd and 7th items.
print l[::-1] # will print the reverse of the list as will step back through all of the items of the list
# It will go: l[-1], l[-2], l[-3] and so on.
# Note all this works for strings as well:
t = "Hello World"
print t[2:7:1]
print t[::-1]
|
9d9d58a9dd4f54e232d0ff346c0de9e234704ed1 | PARKJUHONG123/turbo-doodle | /ALGOSPOT/7_2_FENCE.py | 1,605 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 12 14:59:58 2020
@author: elin9
"""
def biggest_rectangle(left, right):
if left == right:
return fences[left]
mid = int((left + right) / 2)
ret = max(biggest_rectangle(left, mid), biggest_rectangle(mid + 1, right))
lo = mid
hi = mid + 1
height = min(fences[lo], fences[hi])
ret = max(ret, height * 2)
while (left < lo or right > hi):
if hi < right and (lo == left or fences[lo - 1] < fences[hi + 1]):
hi += 1
height = min(height, fences[hi])
else:
lo -= 1
height = min(height, fences[lo])
ret = max(ret, height * (hi - lo + 1))
return ret
def find_widest(fences, height, fence_num):
ret_num = 0; count = 0
for i in range(fence_num):
if fences[i] >= height:
if count == 0:
count = 1
else:
if fences[i - 1] >= height:
count += 1
else :
count = 1
ret_num = max(ret_num,count)
return ret_num
file = open("7_2_input.txt", "r")
C = int(file.readline())
for _ in range(C):
fence_num = int(file.readline())
fences = list(map(int, file.readline().split()))
highest = max(fences)
# O(n^2)
area = [0 for _ in range(highest + 1)]
for i in reversed(range(highest + 1)):
area[i] = find_widest(fences, i, fence_num) * i
print("O(n^2) : " + str(max(area)))
# O(n*log(n))
print("O(n * log(n)) : " + str(biggest_rectangle(0, fence_num - 1)))
|
b3e9a8000f72208d59493eb01b3cba1a55231f2c | Flor246/PythonFlor | /Modulo2/scripts/triangulo.py | 202 | 3.96875 | 4 | # %%
altura = int(input('Ingrese la altura del triangulo: '))
# %%
print(altura)
# %%
for i in range(1,altura+1):
print('#'*i)
# %%
for i in range(1,altura+1):
print(' ' * (altura-i) + '#' * i)
|
f7c64163adb1191c131b8862c5b343d303d5aa00 | nilanjanchakraborty87/py-learn | /introduction/hello.py | 367 | 3.578125 | 4 |
#! /usr/bin/python
import sys
from utils import power, repeat
"""
Hello python
"""
def main():
# print("Hello ", sys.argv[1])
print("Square of 9: ", power(9, 2))
print("Docstring of power: ", power.__doc__)
print("power type: ", type(power))
print(repeat("Python", 3))
print(repeat("-", 100))
if __name__ == "__main__":
main()
|
cd88028fbc09d312f34e66cec2f21509d0020634 | BIGWangYuDong/Algorithm | /1.sort/sort_count.py | 436 | 3.796875 | 4 | def sort_count(array):
n = len(array)
num = max(array)
count = [0] * (num+1)
for i in range(n):
count[array[i]] += 1
arr = []
for i in range(num+1):
for j in range(count[i]):
arr.append(i)
return arr
if __name__ == '__main__':
x1 = [4, 2, 1, 5, 7, 3, 9, 6, 8]
x2 = [2, 1, 3, 1, 2, 3, 4]
out1 = sort_count(x1)
out2 = sort_count(x2)
print(out1)
print(out2) |
1cdfd84bea0f3eda7a72aaf8224883c5977d9e23 | Billl000/gotit-intership | /Chap4.py | 1,740 | 3.515625 | 4 | from utils.display import display_chap_result
class chap4():
def practice1(self):
print ('Computer' + 'Science')
print ('Darwin\s')
print ('H2O' * 3)
print ('CO2' * 0)
def practice2(self):
print("They'll hibernate during the winter.")
print('"Absolutely not," he said.')
print('''"He said, 'Absolutely not'", recalled Mel''')
print("hydrogen sulfide")
print("Left" + "'" + "right")
def practice3(self):
print("'''A")
print("B")
print("C'''")
def practice4(self):
a = ""
print(len(a))
def practice5(self):
x = 3
y = 12.5
print("The rabbit is " + str(x))
print("The rabbit is " + str(x) + " years old")
print(str(y) + " is average")
print(str(y) + " * " + str(x))
print(str(y) + " * " + "3" + " is " + str((y * x)))
def practice7(self):
i = input()
return float
def practice8(self, index1, index2):
if index2 > 0:
for i in range(index2):
print(index1)
else :
return ""
def practice9(self, s1, s2):
return sum(len(s1) + len(s2))
challenge = chap4()
# display_chap_result("1", challenge.practice1())
# display_chap_result("2", challenge.practice2())
print("Practice 1: %s" % challenge.practice1())
print("Practice 2: %s" % challenge.practice2())
print("Practice 3: %s" % challenge.practice3())
print("Practice 4: %s" % challenge.practice4())
print("Practice 5: %s" % challenge.practice5())
print("Practice 7: %s" % challenge.practice7())
print("Practice 8: %s" % challenge.practice8(4, 5))
print("Practice 9: %s" % challenge.practice9('faid', 'kaow'))
|
fe9eba66c854ffd380037e9e211adc5b693be440 | biljiang/pyprojects | /Badbuy_NN/.ipynb_checkpoints/Car_predict1-checkpoint.py | 6,850 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 13 10:15:43 2018
Build Neural network from perceptron,treating biases as part of weights and use
matrix computation to optimize the stochastic gradient descent method.
@author: Feng
"""
#### Libraries
import random
import numpy as np
class NeuralNetwork(object):
def __init__(self, sizes):
self.num_layers = len(sizes)
self.sizes = sizes
self.weights = [np.random.randn(y, x+1) \
for x, y in zip((sizes[:-1]), sizes[1:])] # biases are included in weights
def feedforward(self, a):
for w in self.weights:
a = np.concatenate((a,np.array([1]).reshape(1,1))) # add bias neuron
a = sigmoid(np.dot(w, a))
return a
def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None):
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_0(test_data), n_test))
else:
print ("Epoch {0} complete".format(j))
def update_mini_batch(self, mini_batch, eta):
nabla_w = [np.zeros(w.shape) for w in self.weights]
for x, y in mini_batch:
delta_nabla_w = self.backprop(x, y)
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)]
def backprop(self, x, y):
nabla_w = [np.zeros(w.shape) for w in self.weights]
# feedforward
activation = x
activations = [activation] # list to store all the activations, layer by layer
zs = [] # list to store all the z vectors, layer by layer
for w in self.weights:
activation = np.concatenate((activation,np.array([1]).reshape(1,1)))
activations[-1]=activation
z = np.dot(w, activation)
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
# backward pass
delta = self.cost_derivative(activations[-1], y) * \
sigmoid_prime(zs[-1])
nabla_w[-1] = np.dot(delta, activations[-2].transpose())
for l in range(2, self.num_layers):
z = zs[-l]
sp = sigmoid_prime(z)
delta = np.dot(self.weights[-l+1].transpose(), delta)[:-1]
delta = delta * sp
nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())
return nabla_w
def evaluate_0(self, test_data):
test_results = [(int(self.feedforward(x)[1][0]>0.1), y)
for (x, y) in test_data]
return sum(int(x == y) for (x, y) in test_results)
def evaluate(self, test_data):
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 (output_activations-y)
#### Miscellaneous functions
def sigmoid(z):
return 1.0/(1.0+np.exp(-z))
def sigmoid_prime(z):
return sigmoid(z)*(1-sigmoid(z))
#### prepare training data ,Validation data, test data
import pandas as pd
car_data=pd.read_csv('car.csv')
car_data = car_data.reindex(columns=['IsBadBuy','Size','Make','VNST','IsOnlineSale','VehicleAge','Transmission',
'WheelType','Auction'])
shuffler= np.random.permutation(len(car_data))
car_shuffle = car_data.take(shuffler) # pandas' shuffling method in comparison of random.shuffle
# X preparation
Size = pd.get_dummies(car_data['Size'],prefix='Size') # generate dummy varibles from categorical varible
Make = pd.get_dummies(car_data['Make'],prefix='Make')
VNST = pd.get_dummies(car_data['VNST'],prefix='VNST')
VehicleAge = pd.get_dummies(car_data['VehicleAge'],prefix='VehicleAge')
WheelType = pd.get_dummies(car_data['WheelType'],prefix='WheelType')
Auction = pd.get_dummies(car_data['Auction'],prefix='Auction')
IsOnlineSale =(car_data.IsOnlineSale=='Yes').apply(float)
X= Size.join(Make).join(VNST).join(IsOnlineSale).join(VehicleAge).join(WheelType).join(Auction)
Y=pd.get_dummies(car_data['IsBadBuy'],prefix='IsBadbuy')
car_training=[(X.iloc[i].values.reshape(93,1),Y.iloc[i].values.reshape(2,1)) for i in X.index]
#test data preparing, as did with training data
car_test=pd.read_csv('car_test.csv')
car_test = car_test.reindex(columns=['IsBadBuy','Size','Make','VNST','IsOnlineSale','VehicleAge','Transmission',
'WheelType','Auction'])
Size = pd.get_dummies(car_test['Size'],prefix='Size') # generate dummy varibles from categorical varible
Make = pd.get_dummies(car_test['Make'],prefix='Make')
VNST = pd.get_dummies(car_test['VNST'],prefix='VNST')
VehicleAge = pd.get_dummies(car_test['VehicleAge'],prefix='VehicleAge')
WheelType = pd.get_dummies(car_test['WheelType'],prefix='WheelType')
Auction = pd.get_dummies(car_test['Auction'],prefix='Auction')
IsOnlineSale =(car_test.IsOnlineSale=='Yes').apply(float)
X= Size.join(Make).join(VNST).join(IsOnlineSale).join(VehicleAge).join(WheelType).join(Auction)
Y=car_test['IsBadBuy']
car_test=[(X.iloc[i].values.reshape(93,1),Y.iloc[i]) for i in X.index]
# set of net for Car training
net = NeuralNetwork([93, 10, 2])
net.SGD(car_training, 10, 50, 1.0)
net.SGD(car_training, 30, 50, 1.0,test_data=car_test)
ProbIsGoodBuy=[net.feedforward(x)[0][0] for (x,y) in car_test]
ProbIsBadBuy=[net.feedforward(x)[1][0] for (x,y) in car_test]
import matplotlib.pyplot as plt
plt.hist(ProbIsBadBuy,bins=30,color='red',alpha=0.3)
plt.hist(ProbIsGoodBuy,bins=30,color='blue',alpha=0.5)
test_result=pd.read_csv('car_test.csv')
test_result = test_result.reindex(columns=['IsBadBuy','Size','Make','VNST','IsOnlineSale','VehicleAge','Transmission',
'WheelType','Auction'])
test_result['ProbIsBadBuy']=ProbIsBadBuy
test_result["ProbCat"]=pd.qcut(ProbIsBadBuy,10,precision=1)
#test_result=test_result.sort_values('ProbIsBadBuy')
test_result.groupby("ProbCat").count()
test_result.groupby("ProbCat").sum()
|
86089a27a146fa9f673458f71e563dd9e31975e9 | spencerbertsch1/IOT-Raspberry_Pi | /web_led_communication_test.py | 960 | 3.796875 | 4 | # Spencer Bertsch
# Dartmouth College - Winter 2018
# IOT Short Course, R-Pi Programming Demo
# This program blinks an LED pseudo randomly
#
# Import needed modules
import time
import RPi.GPIO as GPIO
import random
#### o_o
import web
#### -_-
led = 4 # connect the LED to this pin on the GPIO
pir = 17 # connect the PIR motion detector to this pin on the GPIO
# Set the mode for the pin
GPIO.setmode( GPIO.BCM )
# Set our LED, pin 4, to output
GPIO.setup( led, GPIO.OUT )
# Set out PIR motion detector, pin 17 to input
GPIO.setup( pir, GPIO.IN )
def led_on():
print "> LED on"
GPIO.output( led, 1 )
def led_off():
print "> LED off"
GPIO.output( led, 0 )
try:
web.server_start()
web.register( "<button>Turn LED on</button>", led_on )
web.register( "<button>Turn LED off</button>", led_off )
# the program is finished, we put things back in their original state
print "> finishing"
web.server_stop()
led_off()
GPIO.cleanup()
|
727e95470fa7f79947831e4b2f577365f81ba387 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/443a8b38e1c74b13b3a060c20bc57613.py | 395 | 3.828125 | 4 | def square_of_sum(number):
total_holder = 0
for x in range(1,number+1):
total_holder += x
total_holder = total_holder ** 2
return total_holder
def sum_of_squares(number):
total_holder = 0
for x in range(1,number+1):
total_holder += x**2
total_holder = total_holder
return total_holder
def difference(number):
return abs(sum_of_squares(number) - square_of_sum(number))
|
ba7eb01fbe6edd7b1498ddd4d0e64b686343ff12 | wkcn/leetcode | /0001-0100/0070-climbing-stairs.py | 320 | 3.578125 | 4 | class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2: return n
one = 2
two = 1
for i in range(3, n):
old_one = one
one = two + one
two = old_one
return one + two
print(Solution().climbStairs(2))
print(Solution().climbStairs(3))
|
63c16911a2de926b882ee6f5b550a4895fceec7e | manusia1932/Praktikum-STEI-IF-ITB | /Dasar-Pemrograman/PRAKTIKUM-5/berat.py | 873 | 3.53125 | 4 | # NIM/Nama : 16520299/Malik Akbar Hashemi Rafsanjani
# Nama file : berat.py
# Topik : Pengulangan dan Pemrosesan Array
# Tanggal : 9 April 2021
# Deskripsi : Program yang digunakan untuk membaca masukan berat tubuh mahasiswa dan menampilkan beberapa statistik
# KAMUS
# total, N, i, kurang, lebih : integer
# arr : array of integer
# ALGORITMA
arr = []
total = 0
N = int(input())
if (N >= 30) and (N <= 200):
arr += [N]
total += N
while N != (-999):
N = int(input())
if (N >= 30) and (N <= 200):
arr += [N]
total += N
if (len(arr) > 0):
print(len(arr))
kurang = 0
for i in range(len(arr)):
if arr[i] <= 50:
kurang += 1
print(kurang)
lebih = 0
for i in range(len(arr)):
if arr[i] >= 100:
lebih += 1
print(lebih)
print(round(total/len(arr)))
else:
print("Data kosong") |
2a024b3a118d5fef6ec7acfaf8a610e78808d248 | Dustyposa/goSpider | /python_advance/about_pyhton/simple_interpreter/interpreter_1.py | 1,573 | 3.59375 | 4 | class Interpreter:
def __init__(self):
self.stack = []
def LOAD_VALUE(self, val) -> None:
self.stack.append(val)
def PRINT_ANSWER(self) -> None:
answer = self.stack.pop()
print(answer)
def ADD_TWO_VALUES(self) -> None:
total = self.stack.pop() + self.stack.pop()
self.stack.append(total)
def run_code(self, what_to_execute) -> None:
instructions, numbers = what_to_execute["instructions"], what_to_execute["numbers"]
for each_step in instructions:
step_name, argument = each_step
if step_name == "LOAD_VALUE":
getattr(self, step_name)(numbers[argument])
elif step_name == "ADD_TWO_VALUES":
getattr(self, step_name)()
elif step_name == "PRINT_ANSWER":
getattr(self, step_name)()
if __name__ == '__main__':
# what_to_execute = {
# "instructions": [("LOAD_VALUE", 0), # the first number
# ("LOAD_VALUE", 1), # the second number
# ("ADD_TWO_VALUES", None),
# ("PRINT_ANSWER", None)],
# "numbers": [7, 5]
# }
what_to_execute = {
"instructions": [("LOAD_VALUE", 0),
("LOAD_VALUE", 1),
("ADD_TWO_VALUES", None),
("LOAD_VALUE", 2),
("ADD_TWO_VALUES", None),
("PRINT_ANSWER", None)],
"numbers": [7, 5, 8]}
Interpreter().run_code(what_to_execute)
|
c17a27d6d704102b2929f8c0cc347c06bf549b94 | piyushkaran/old-python | /prev Python/pyt25.py | 208 | 3.9375 | 4 | year=int(input())
if(year%100==0):
if(year%400==0):
print("leap year")
else:
print("not a leap year")
elif(year%4==0):
print("leap hai")
else:print("bewakkof nahi h leap")
|
827040c9fa87434546df9f8365c41ece8cdd527d | Kuldeep28/Satrt_py | /zipinffuntion.py | 922 | 4.21875 | 4 | string="kuldeepop"
tup=[1,2,5,7,8,8,9,89,90]
print(list(zip(string,tup)))# in zip function the length of the zip list is depending on the value of the shortest listt
zipped=list(zip(string,tup))
for entity,num in zipped:# that cool we are using tupple assingnment to iterate over it as we are confirmed that there
# would be nly 2 entities in 1 entity of the given list
print(entity,num)
#we can use zip for and loop to traverse through three itewration at the sAme time that a great utility
def triple_triversal(ty1,ty2,ty3):
for wr1,wr2,wr3 in zip(ty1,ty2,ty3):
print(wr1,wr2,wr3)#here we are traversing the continous structure with same loop and i need it
st="kuldeepparasha"
st1="tanyaparashar"
st3="anitaparashar"
# enumerate is the functoin use if you wwant to traverse the structure with index and and the values at the same time
triple_triversal(st,st1,st3) |
c94816c68324c76fdd4b223980fdfb47a5fe6634 | tanlangqie/coding | /二叉树/98二叉搜索树.py | 1,088 | 3.53125 | 4 | # -*- coding: utf-8 -*-#
# Name: 98二叉搜索树.py
# Author: tangzhuang
# Date: 2021/7/20
# desc:
"""
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def helper(node, lower=float('-inf'), upper=float('inf')):
if not node:
return True
val = node.val
if val <= lower or val >= upper:
return False
return helper(node.right, val, upper) and helper(node.left, lower, val)
return helper(root) |
c828b1de74e770642ab4b6bedce0244bead4e745 | Sunsetjue/python | /多线程/多线程_3.py | 1,079 | 3.90625 | 4 | import time
import threading
def loop1():
print('Start loop1 at:',time.ctime())
time.sleep(4)
print('End loop1 at:',time.ctime())
def loop2():
print('Start loop2 at:',time.ctime())
time.sleep(1)
print("End loop2 at:",time.ctime())
def loop3():
print('Start loop3 at:',time.ctime())
time.sleep(3)
print('End loop3 at:',time.ctime())
def main():
print('Start at:',time.ctime())
t1 = threading.Thread(target=loop1,args=())
#setName是给每个子线程设置一个名字
t1.setName('thread1')
t1.start()
t2 = threading.Thread(target=loop2,args=())
t2.setName('thread2')
t2.start()
t3 = threading.Thread(target=loop3,args=())
t3.setName('thread3')
t3.start()
#预计两秒后,loop2子线程已经运行结束
time.sleep(2)
for thr in threading.enumerate():
print('正在运行着的线程的名称为:',thr.getName())
print('正在运行着的线程的数量为:',len(threading.enumerate()))
print('All down at:',time.ctime())
if __name__ == '__main__':
main() |
baec963ba0762ddff463147c2445fec2fe2b47a1 | belaidabdellah/databricks | /04-Working-With-Dataframes/1.Describe-a-dataframe.py | 4,084 | 3.640625 | 4 | # Databricks notebook source
# MAGIC %md
# MAGIC
# MAGIC # Describe a DataFrame
# MAGIC ### Tuto à suivre en détail
# MAGIC
# MAGIC Your data processing in Azure Databricks is accomplished by defining Dataframes to read and process the Data.
# MAGIC
# MAGIC This notebook will introduce how to read your data using Azure Databricks Dataframes.
# COMMAND ----------
# MAGIC %md
# MAGIC #Introduction
# MAGIC
# MAGIC ** Data Source **
# MAGIC * One hour of Pagecounts from the English Wikimedia projects captured August 5, 2016, at 12:00 PM UTC.
# MAGIC * Size on Disk: ~23 MB
# MAGIC * Type: Compressed Parquet File
# MAGIC * More Info: <a href="https://dumps.wikimedia.org/other/pagecounts-raw" target="_blank">Page view statistics for Wikimedia projects</a>
# MAGIC
# MAGIC **Technical Accomplishments:**
# MAGIC * Develop familiarity with the `DataFrame` APIs
# MAGIC * Introduce the classes...
# MAGIC * `SparkSession`
# MAGIC * `DataFrame` (aka `Dataset[Row]`)
# MAGIC * Introduce the actions...
# MAGIC * `count()`
# COMMAND ----------
# MAGIC %md
# MAGIC ## Getting Started
# MAGIC
# MAGIC Run the following cell to configure our "classroom."
# COMMAND ----------
# MAGIC %run "./Includes/Classroom-Setup"
# COMMAND ----------
# MAGIC %md
# MAGIC ## **The Data Source**
# MAGIC
# MAGIC * In this notebook, we will be using a compressed parquet "file" called **pagecounts** (~23 MB file from Wikipedia)
# MAGIC * We will explore the data and develop an understanding of it as we progress.
# MAGIC * You can read more about this dataset here: <a href="https://dumps.wikimedia.org/other/pagecounts-raw/" target="_blank">Page view statistics for Wikimedia projects</a>.
# MAGIC
# MAGIC We can use **dbutils.fs.ls()** to view our data on the DBFS.
# COMMAND ----------
(source, sasEntity, sasToken) = getAzureDataSource()
spark.conf.set(sasEntity, sasToken)
# COMMAND ----------
path = source + "/wikipedia/pagecounts/staging_parquet_en_only_clean/"
files = dbutils.fs.ls(path)
display(files)
# COMMAND ----------
# MAGIC %md
# MAGIC As we can see from the files listed above, this data is stored in <a href="https://parquet.apache.org" target="_blank">Parquet</a> files which can be read in a single command, the result of which will be a `DataFrame`.
# COMMAND ----------
# MAGIC %md
# MAGIC ## Create a DataFrame
# MAGIC * We can read the Parquet files into a `DataFrame`.
# MAGIC * We'll start with the object **spark**, an instance of `SparkSession` and the entry point to Spark 2.0 applications.
# MAGIC * From there we can access the `read` object which gives us an instance of `DataFrameReader`.
# COMMAND ----------
parquetDir = source + "/wikipedia/pagecounts/staging_parquet_en_only_clean/"
# COMMAND ----------
pagecountsEnAllDF = (spark # Our SparkSession & Entry Point
.read # Our DataFrameReader
.parquet(parquetDir) # Returns an instance of DataFrame
)
print(pagecountsEnAllDF) # Python hack to see the data type
# COMMAND ----------
# MAGIC %md
# MAGIC ## count()
# MAGIC
# MAGIC If you look at the API docs, `count()` is described like this:
# MAGIC > Returns the number of rows in the Dataset.
# MAGIC
# MAGIC `count()` will trigger a job to process the request and return a value.
# MAGIC
# MAGIC We can now count all records in our `DataFrame` like this:
# COMMAND ----------
total = pagecountsEnAllDF.count()
print("Record Count: {0:,}".format( total ))
# COMMAND ----------
# MAGIC %md
# MAGIC That tells us that there are around 2 million rows in the `DataFrame`.
# COMMAND ----------
# MAGIC %md
# MAGIC ## Next steps
# MAGIC
# MAGIC Start the next lesson, [Use common DataFrame methods]($./2.Use-common-dataframe-methods)
|
0a50346b59d640e568e92bc3ad21f5ae5b7099f5 | vinobc/UGE1176 | /scope.py | 650 | 3.546875 | 4 | def main():
type = "hot"
def mix_and_heat():
print("prepare ingredients")
print("heat milk/water in a bowl")
print("put sugar")
def make_coffee(param1):
global type
mix_and_heat()
print("put coffee powder")
coffee='{} coffee ready'.format(type)
return coffee
def make_tea():
global type
type = "cold"
mix_and_heat()
print("put tea powder")
tea='{} tea ready'.format(type)
return tea
tea = make_tea()
print(tea,"\n")
coffee = make_coffee("cold")
print(coffee)
if __name__ == "__main__":
main() |
77660f9dad44fc30b1094c63aba74842f8f45ddd | ralphbean/ms-thesis | /__old_stuff/src/1_over_f_visualization.py | 369 | 3.53125 | 4 | #!/usr/bin/python
import pylab
from math import log
def frange(start, stop, step):
return [ start + float(i)*step for i in range((stop-start+step)/step)]
T = frange(0.01,1,0.01)
X = [1.0/(ele) for ele in T]
pylab.subplot(2,1,1)
pylab.title('1/x')
pylab.plot(T,X)
pylab.subplot(2,1,2)
pylab.title('log(1/x)')
pylab.plot(T,[log(ele) for ele in X])
pylab.show()
|
1405df871cd8674ab1f6c1896dcf8f81bb242ca7 | PKNU-IT-ALGORITHM2019/pa-04-alsgur1368 | /programming4-1.py | 2,350 | 3.546875 | 4 | #-*- coding : utf-8 -*-
import random
import sys
import time
def input_random(size):
sort_list=[]
for i in range(0, size):
sort_list.append(random.randint(1, size))
return sort_list
def input_reverse(size):
sort_list=[]
for i in range(size, 0, -1):
sort_list.append(i)
return sort_list
def swap(sort_list, i, j):
tmp = sort_list[i]
sort_list[i] = sort_list[j]
sort_list[j] = tmp
return sort_list
def MAX_HEAPIFY(sort_list,i):
heap_size=len(sort_list)
# 만약 sort_list[i]의 자식노드가 없으면 종료
if (2*i+1) > heap_size-1 or (2*i+2) > heap_size-1:
return
if sort_list[2*i+1] < sort_list[(2*i)+2]:
k=2*i+2
else:
k=2*i+1
if sort_list[i] >= sort_list[k]:
return
swap(sort_list,i,k)
MAX_HEAPIFY(sort_list,k)
def Build_MAX_HEAP(sort_list):
heap_size=len(sort_list)
for i in range(int(heap_size/2),0,-1):
MAX_HEAPIFY(sort_list,i)
def Heapsort(sort_list):
Build_MAX_HEAP(sort_list)
heap_size=len(sort_list)
for i in range(heap_size-1,1,-1):
swap(sort_list,0,i)
heap_size-=1
MAX_HEAPIFY(sort_list,0)
def main():
unsort_list=[]
time_list=[[],[]]
print("\t\t\t\tRandom1000\t\t\tReverse1000\t\t\tRandom10000\t\t\tReverse10000\t\t\tRandom100000\t\t\tReverse100000")
#힙 정렬
print("Heap\t\t\t\t\t", end='')
for i in [1000,10000,100000]:
unsort_list = input_random(i)
start_time = time.time()
Heapsort(unsort_list)
end_time1 = time.time() - start_time
time_list[0].append(end_time1)
unsort_list = input_reverse(i)
start_time = time.time()
Heapsort(unsort_list)
end_time2 = time.time() - start_time
time_list[0].append(end_time2)
for t in time_list[0]:
print("%0.3f" % t, end='\t\t\t\t')
print("\n")
# 파이썬 정렬 함수
print("python\t\t\t\t\t", end='')
for i in [1000,10000,100000]:
unsort_list = input_random(i)
start_time=time.time()
unsort_list = sorted(unsort_list)
end_time1 = time.time() - start_time
time_list[1].append(end_time1)
unsort_list = input_reverse(i)
start_time=time.time()
unsort_list = sorted(unsort_list)
end_time2 = time.time() - start_time
time_list[1].append(end_time2)
for t in time_list[1]:
print("%0.3f" % t, end='\t\t\t\t')
print("\n")
main()
|
bbebeb8648ba561b5c0660b775ee9e348d0c8977 | maverick13m/correletion | /meme.py | 1,000 | 3.96875 | 4 | import plotly.express as px
import csv
"""
#ice cream vs temp
with open("./Ice-Cream vs Cold-Drink vs Temperature - Ice Cream Sale vs Temperature data.csv")as f:
df1 = csv.DictReader(f)#₹
figure1 = px.scatter(df1,x = "Temperature",y = "Ice-cream Sales( ₹ )")
figure1.show()
"""
#coffee vs sleep
with open("./cups of coffee vs hours of sleep.csv")as g:
df2 = csv.DictReader(g)
figure2 = px.scatter(df2,x = "Coffee in ml",y = "sleep in hours",color = "week")
figure2.show()
"""
A correlation of 1 means the two datasets are closely correlated. This will be a rising graph where the data points are close to a central line.
A correlation of -1 means that the two data sets are inversely correlated. This will be a falling graph where the data points are close to a central line.
A correlation of 0 means that the two data sets are not correlated at all! The data points will be scattered on the graph.
Correlation always lies between -1 and 1
"""
|
e5748150fe6b2333ee0c35fb8626c813e1e03661 | gerisd/Path_Planning | /Breadth First Search/main.py | 1,773 | 3.875 | 4 | from BFS import BreadthFirstSearch as BFS
import numpy as np
#10x10 grid
grid = [[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]
start = [0,0]
goal = [9,9]
bfs = BFS(grid, start, goal)
while True:
bfs.find_moves()
if bfs.find_goal():
break
bfs.select_move()
depth_path = bfs.depth_path
#Now to find the best path, we follow the position depths in ascending order
#Only move to positions with a position depth that is one higher than current position
def get_path(pos, path, depth_path):
#mark current pos as part of the path
path[pos[0]][pos[1]] = 1
curr_depth = depth_path[pos[0]][pos[1]]
#Find the possible moves
possible_moves = find_moves(pos)
#Iterate through all the possible moves
for move in possible_moves:
#Check if move is valid and within boundaries
if bfs.bound_check(move):
possible_depth = depth_path[move[0]][move[1]]
#check if move position depth is one higher than current position depth
if curr_depth == possible_depth - 1:
#That move is our new position and depth
pos = move
curr_depth = possible_depth
#Reiterate process
get_path(pos, path, depth_path)
return path
def find_moves(pos):
up = [pos[0] - 1, pos[1]]
down = [pos[0] + 1, pos[1]]
left = [pos[0], pos[1] - 1]
right = [pos[0], pos[1] + 1]
possible_moves = [up, down, left, right]
return possible_moves
#list of path from start to goal
path = np.zeros([len(grid), len(grid)], dtype=int)
path = get_path(bfs.start, path, depth_path)
path[start[0]][start[1]] = 99
print(f'Path Depth \n {depth_path}')
print(f'\nPath \n {path}')
|
636931f6c8b05e09e52c35ace3b1ed4c29eca811 | HaoPham1912/ML_gradient-boosting | /GradientBoostingRegressor.py | 2,231 | 3.53125 | 4 | #tham khao tai https://acadgild.com/blog/gradient-boosting-for-regression-problems
#import các thư viện cần dùng
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import datasets
from sklearn.metrics import mean_squared_error, r2_score
from sklearn import ensemble
from sklearn.model_selection import cross_val_predict
# Load data
boston = datasets.load_boston()
#print(boston.data.shape, boston.target.shape)
#print(boston.feature_names)
data = pd.DataFrame(boston.data,columns=boston.feature_names)
data = pd.concat([data,pd.Series(boston.target,name='MEDV')],axis=1)
data.head()
#Chọn biến dự đoán và biến đích
X = data.iloc[:,:-1]
y = data.iloc[:,-1]
#tách ma trận từ dataset thành các biến dùng cho việc train
x_training_set, x_test_set, y_training_set, y_test_set = train_test_split(X,y,test_size=0.10,
random_state=42,
shuffle=True)
# Fit regression model
params = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 2,
'learning_rate': 0.01, 'loss': 'ls'}
model = ensemble.GradientBoostingRegressor(**params)
model.fit(x_training_set, y_training_set)
#tính hệ số của các dự đoán
model_score = model.score(x_training_set,y_training_set)
# Have a look at R sq to give an idea of the fit ,
# Explained variance score: 1 is perfect prediction
print('R2 sq: ',model_score)
y_predicted = model.predict(x_test_set)
# The mean squared error (tính giá trị loss function)
print("Mean squared error: %.2f"% mean_squared_error(y_test_set, y_predicted))
# Explained variance score: 1 is perfect prediction
print('Test Variance score: %.2f' % r2_score(y_test_set, y_predicted))
# So let's run the model against the test data
# Visible kết quả
fig, ax = plt.subplots()
ax.scatter(y_test_set, y_predicted, edgecolors=(0, 0, 0))
ax.plot([y_test_set.min(), y_test_set.max()], [y_test_set.min(), y_test_set.max()], 'k--', lw=4)
ax.set_xlabel('Actual')
ax.set_ylabel('Predicted')
ax.set_title("Ground Truth vs Predicted")
plt.show()
|
cab5908306224830d26c969dc89f71e883819a37 | JacobAAnderson/Python | /Templates/Textfile.py | 669 | 3.984375 | 4 | # .txt template
# This script will create a text file and read and write to the text file
# The read comands return a list object containing the text from the file.s
with open("Desktop/testfile.txt",'w') as file:
file.write('Hello World\n')
file.write('This is a test\n')
file.write('This is line 3\n')
file.write('This is line 4\n')
with open("Desktop/testfile.txt",'r') as file:
print file.read()
with open("Desktop/testfile.txt",'r') as file:
print file.readline(3)
with open("Desktop/testfile.txt",'r') as file:
words =()
for line in file:
print(line)
words = line.split()
print words
file.close()
|
128de0e1c7170501e9fcd130e0f464a3c6481094 | ramlaxman/cisco-feb2020 | /mytest.py | 194 | 3.734375 | 4 | #!/usr/bin/env python3
def hello(name: str) -> str:
greeting = 3
greeting = 'Hello'
return f'{greeting}, {name}'
print(hello('world'))
print(hello(5))
print(hello([10, 20, 30]))
|
09de478578b5a67f5401f75ab7cf2e7d6ed19e43 | angel-robinson/carrion.chancafe.trabajo7 | /rango02.py | 167 | 3.5625 | 4 | # imprimir los n numeros enteros
import os
#input
n=int(os.sys.argv[1])
#inicio_rango
for n in range(n):
print(n+1)
#fin_rango
print("fin del bucle")
|
bc7cf8151bb8d8556600ce95222128a9f9a38a98 | Nikitushechka/mipt_python_1sem | /1/1.7.py | 727 | 3.734375 | 4 | import turtle
import numpy as np
import math
turtle.shape('turtle')
R = 30
x = 1
n = 3
turtle.up()
turtle.goto(R,0)
turtle.down()
def ok(x):
while x<=n:
turtle.left((180 - 360 / n) / 2)
turtle.left(360 / n)
turtle.forward(2 * R * math.sin(math.pi/n))
x += 1
turtle.right((180 - 360 / n) / 2)
while n<=10:
ok(x)
R+=10
n+=1
turtle.up()
turtle.goto(R,0)
turtle.down()
|
76fa058c4bfb8b4ef1bd3b0d41610ca0845be809 | ujjwalshiva/pythonprograms | /Replace 0 with 5.py | 465 | 3.875 | 4 | number = int(input("Enter a number: "))
def convertFive(n):
lst_num = list(str(n))
if '0' not in lst_num:
return n
else:
updated_number = 0
for items in lst_num:
if items == '0':
index = lst_num.index('0')
lst_num[index] = '5'
for items1 in lst_num:
updated_number = updated_number*10 + int(items1)
return updated_number
print(convertFive(number))
|
5be8e772ab21e22f7660c9bdd9697685764428fb | dineshpazani/algorithms | /src/com/python/ReverseStringRecursive.py | 396 | 3.8125 | 4 |
def reverse(s, k):
if k == len(s):
return;
reverse(s, k+1);
print(s[k])
def reverseNby2(s):
if len(s) == 0:
print(s)
ls = list(s)
l = len(s)-1
for i in range(len(ls)//2):
t = ls[i]
ls[i] = ls[l-i]
ls[l-i] = t
print(ls)
#reverse("dinesh", 0)
reverseNby2("dinesh") |
3fa87b39fbff52cb2c76e44f9d3b7c1eede2cd6e | tywins/TC1014 | /funWithNumbers.py | 415 | 4.15625 | 4 | x=int(input("Enter a number: "))
y=int(input("Enter another number: "))
summ=x+y
difference=x-y
product=x*y
division=x/y
remainder=x%y
print ("the sum of ", x, " + ", y, " = ", summ)
print ("the difference of ", x, " - ", y, " = ", difference)
print ("the product of ", x, " x ", y, " = ", product)
print ("the division of ", x, " / ", y, " = ", division)
print ("the remainder of ", x, " % ", y, " = ", remainder)
|
7b7f1e18492c29217ff0162770af9b0065292af9 | codebubb/python_course | /Semester 1/Week 1/maths.py | 215 | 4 | 4 | # What do the different symbols do?
print 2 + 2 # Add
print 12 - 2 # Subtract
print 3 * 3 # Multiply
print 3 ** 3 # To the power of
print 12 / 3 # Divide
print 12 % 3 # Remainder
|
5ba74cdd0f08689e4c74a784f8d56df5f5d0ba56 | luisandre69/python-programming-course | /syntax_errors.py | 299 | 3.59375 | 4 | # %% IndexError
L=[1,5,8]
L[3]
# %% KeyError
x={"a":1,"b":2,"c":3}
x["d"]
# %% TypeError
L=[1,2,3,4]
L["a"]
# %% AttributeError
L=[1,2,3,4]
L.add(5)
# %% NameError
z
# %% ZeroDivisionError
y=10/0
y
# %% IndentationError
def greet():
print("Hello")
# %% OverflowError
a=24583**2456.1245
a |
2561c8aafdd87bf22d67be444ed45e9e9f2b389d | gaTarr/PythonasaurusRex | /Module8/more_fun_with_collections/assign_average.py | 603 | 3.890625 | 4 | """CIS189 Python
Author: Greg Tarr
Created: 10/14/2019"""
def switch_average():
""" This prompts a user to select from a set of Keys
and returns the value associated with that key.
:returns the value of the selected key, or a message
if an invalid key is selected
"""
try:
search_value = input("Choose a Key from (A, B, C, D): ").upper()
except ValueError:
print("Invalid Input")
return {
'A': 100,
'B': 200,
'C': 300,
'D': 400
}.get(search_value, 'Invalid Key')
if __name__ == '__main__':
print(switch_average())
|
d0986444945a96db564f2cdda08b9e0dcffdf373 | JoJaJones/leetcode_solutions | /SameTree.py | 548 | 3.5625 | 4 | class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
return self.BFS(q) == self.BFS(p)
def BFS(self, node):
queue = [node]
res = []
while len(queue) > 0:
cur = queue.pop(0)
if cur:
queue.append(cur.left)
queue.append(cur.right)
res.append(cur.val)
else:
res.append(cur)
return res
|
d8b4cb3cc121e48a4e8d2b35c19f790892db8119 | MattB17/ComputerNetworks | /Networking/UDPPinger/udp_server.py | 2,561 | 3.953125 | 4 | """The UDPServer class implements a server using the UDP protocol.
"""
import socket
from Networking.Base.network_server import NetworkServer
from Networking.UDPPinger import utils
class UDPServer(NetworkServer):
"""Implements a UDP Server of a given `reliability`.
UDPServer is a dervived class of the generic NetworkServer.
Parameters
----------
host: str
A string representing the host on which the server is run.
port: int
An integer representing the host on which the server is run.
reliability: float
A float representing the reliability of the server. Values are
between 0 and 1 giving the long run proportion of packets that
are successfully received. That is, for a value of `x` the server
will successfully receive `100x` percent of packets when running
for a sufficiently long time.
Attributes
----------
_host: str
The host on which the server runs.
_port: int
The port on which the server runs.
_running: bool
Specifies whether the server is currently running.
_server_socket: socket.socket
The socket used to run the server.
_reliability: float
The server's reliability. A value between 0 and 1 representing
the long run proportion of packets that are successfully received.
"""
def __init__(self, host, port, reliability):
utils.validate_proportion(reliability)
super().__init__(host, port, socket.AF_INET, socket.SOCK_DGRAM)
self._reliability = reliability
def get_reliability(self):
"""Gives the reliability of the server.
The reliability is a float between 0 and 1 representing the long run
proportion of packets that are successfully received by the server.
Returns
-------
float
A float representing the server's reliability.
"""
return self._reliability
def run(self):
"""Runs the UDP server.
While running, the server receives, processes, and replies to
messages. Only a proportion of messages, equal to the server's
reliability, are successfully processed.
Returns
-------
None
"""
super().run()
while self.is_running():
message, addr = self._server_socket.recvfrom(1024)
if not utils.will_drop_message(self._reliability):
self._server_socket.sendto(
utils.process_message(message.decode()).encode(), addr)
|
41afd55e7130037e9c77fa03b832ace16cbaae5e | chanthony/Oregon-112 | /TP3 Test/characters.py | 4,391 | 3.5625 | 4 | #characters.py
import random
def generateCharacters(data):
data.characterList = []
for char in range(4):#four people per party
character = Character("",char)
data.characterList.append(character)
class Character(object):
def __init__(self,name,index):
self.name = name#keeps track of the player name
self.grade = 100#everyone starts with a 100 in the class
self.index = index
self.alive = True#The character is still alive
self.x = 650 + 50*self.index#characters are on the right third of screen
self.y = 350#characters in bottom 2/3rds of screen
self.headY = self.y - 30#center of chars head
def reduceGrade(self,amount):#reduces the characters grade
self.grade -= amount
def increaseGrade(self,amount):#increases the characters grade
self.grade += amount
if self.grade >= 100:#no one gets over 100 in 112. No one.
self.grade = 100
def stillPassing(self):#returns the person is still passing
if self.getLetterGrade() != "R":
return True
#they're not failing so they are passing
else:#they failed
self.alive = False#kiill this player
return "%s dropped out of CMU" % self.name
#ex. Anthony dropped out of cmu
def caughtDisease(self,data):
chance = random.randint(1,100)#probability simulator
if chance < 40:
disease = self.pickDisease(data)#picks a disease at random
if disease.effect == "energy":#if it affects energy
if data.player.energy == 0:#if there is no more energy to lose
self.caughtDisease(data)#call the function again
else:
return disease#return what they got hit with
return disease
else:#they survived....this time
return False
def getLetterGrade(self):#return the letter version of grade
if self.grade > 90:#letter grades based on numeric conversions
return "A"
elif self.grade > 80:
return "B"
elif self.grade > 70:
return "C"
elif self.grade > 60:
return "D"
else:
return "R"
def __repr__(self):
return "Name = %s ; Grade = %s" % (self.name,self.getLetterGrade())
def pickDisease(self,data):#chooses what disease this character gets
return random.choice(data.diseaseList)
def drawCharacter(self,canvas,data):
# canvas.create_line(640,616,660,616,fill="white")
#draw each body part in a helper method
self.drawBody(canvas)
self.drawArms(canvas)
self.drawHead(canvas)
if data.dayHour in [4,5,6,10,11,12]:#every 3 hours
self.drawLegsWalking(canvas)
else:
self.drawLegs(canvas)#draw the walking animation
def drawBody(self,canvas):#draws the center line
x0=x1=self.x#straight up and down line
y0 = self.y - 20#40 units tall
y1 = self.y + 20
canvas.create_line(x0,y0,x1,y1,fill="white")#draws the white line
def drawArms(self,canvas):
y0=y1=self.y#arms are a straight horizontal line in center of body
x0 = self.x - 10#arms are ten units long
x1 = self.x + 10
canvas.create_line(x0,y0,x1,y1,fill="white")
def drawHead(self,canvas):
x0 = self.x - 10#head is a circle of radius ten
x1 = self.x + 10#centered on the body axis
y0 = self.headY - 10
y1 = self.headY + 10
canvas.create_oval(x0,y0,x1,y1,outline="white",fill="black")
def drawLegs(self,canvas):
x0 = self.x#center point of the legs
y0 = self.y + 20#legs start at the bottom of the body
x1 = self.x - 10#end x of the left leg
x2 = self.x + 10#end x of the right leg
y1 = y2 = self.y + 40#left and right leg end at same vertical point
canvas.create_line(x0,y0,x1,y1,fill="white")#draws the legs
canvas.create_line(x0,y0,x2,y2,fill="white")
def drawLegsWalking(self,canvas):
x0=x1=self.x#the legs are straight up and down when taking a step
y0 = self.y + 20
y1 = self.y + 40
canvas.create_line(x0,y0,x1,y1,fill="white") |
d1eca227b49239da04226bc6c8f66fc434babe0c | hosankang/AI_Class | /Classification_2.py | 437 | 3.671875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import math
def ActivationFunction1(n):
return 1/(1+math.e**(-n))
def ActivationFunction2(n):
return n
w11=10
w12=10
b1=-10
b2=10
w21=1
w22=1
b3=0
p=np.arange(-2,2,0.01)
p1=ActivationFunction1(w11*p+b1)
p2=ActivationFunction1(w12*p+b2)
p3=ActivationFunction2((p1*w21)+(p2*w22)+b3)
plt.ylabel("a^2")
plt.xlabel("p")
#plt.axis([-2,2,-2,2])
print(p3)
plt.plot(p,p3,'k')
plt.show()
|
de871b56ca8cc3cb5930520a1a55efbf73186ba8 | Akashmallareddy/mini-tool | /generator.py | 764 | 3.96875 | 4 | import random
def pwd_generator(name, mail):
#name=input('Enter your name:')
#mail=input('Enter your mailid:')
symbol=['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>',
'*', '(', ')']
#print(name, mail)
n=[]
n[:]=name
m=[]
m[:]=mail
final=n+m+symbol
password=[]
z=''
t1 = len(n)
t2 = len(m)
t1 = t1 - 3
t2 = t2 - 3
for i in range(5):
z = ''
ttt1 = random.randrange(0,t1)
for tt1 in range(ttt1, ttt1+3):
z = z + str(n[tt1])
ttt2 = random.randrange(0,t2)
for tt2 in range(ttt2, ttt2+3):
z = z + str(m[tt2])
for j in range(3):
z+= str(random.choice(symbol))
password.append(z)
print(z)
return(password)
#print(z)
#for i in password:
# print(i)
#password = pwd_generator()
#print(password)
|
1afc3c225159031d26cb695863e698d82d494b32 | thetruejacob/CS166 | /pycx-0.32/misc-fileio.py | 371 | 3.984375 | 4 | # Simple file I/O in Python
#
# Copyright 2008-2012 Hiroki Sayama
# sayama@binghamton.edu
# writing to file
f = open("myfile.txt", "w")
f.write("Hello\n")
f.write("This is a second line\n")
f.write("Bye\n")
f.close()
# reading from file
f = open("myfile.txt", "r")
for row in f:
print row,
# The last comma is to prevent automatic line break
f.close()
|
3f22d80169b7776fb5d159cbab04aaa28038add2 | MalyshkinMike/Gubar | /3.py | 2,837 | 3.625 | 4 | # 3 лаба
import numpy as np
from numpy import fabs
import matplotlib.pyplot as canvas
def f(x):
return (np.pi * x - 3) / (x - 1) ** 2
def f2(x):
return 2 * (x - 1) - 5 * (np.pi * (x ** 2 + x - 2) - 9 * x + 9) # 2⋅(x−1)−5⋅(π⋅(x2+x−2)−9⋅x+9)
def f4(x):
return 24 * ((x - 1) ** -7) * (np.pi * (x * (x + 3) - 4) - 15 * x + 15)
def f4abs(x):
return fabs(f4(x))
def lagrange_P(arg, x, y):
Lagrange = 0
size = len(x)
for i in range(size):
l = 1
for j in range(size):
if i != j:
l = l * (arg - x[j]) / (x[i] - x[j])
Lagrange = Lagrange + l * y[i]
return Lagrange
def newton_P(x, X, Y, h):
Newton = Y[0]
t = (x - X[0]) / h
diff = [0] * 4
for i in range(len(Y)):
diff[i] = Y[i]
for i in range(len(X) - 1):
for j in range(len(X) - i - 1):
diff[j] = diff[j + 1] - diff[j]
temp = diff[0]
for j in range(0, i + 1):
temp *= (t - j)
temp /= (j + 1)
Newton = Newton + temp
return Newton
def func_max(func, x1, x2, eps):
while fabs(x1 - x2) >= eps:
y1 = fabs(func(((x1 + x2) / 2) - eps))
y2 = fabs(func(((x1 + x2) / 2) + eps))
if y1 > y2:
x2 = x1 + ((x2 - x1) / 2) - eps
else:
x1 = x1 + ((x2 - x1) / 2) + eps
else:
return (x1 + x2) / 2
a = 0
eps = 0.001
b = 0.9
'''def find_err(a_arg, b_arg):
xx = np.linspace(a_arg, b_arg, num=4)
def w_4(argument):
return (argument - xx[0]) * (argument - xx[1]) * (argument - xx[2]) * (argument - xx[3])
return find_max(w_4, a_arg, b_arg, eps) * find_max(f4abs, a_arg, b_arg, eps) / 24
e = find_err(a, b)
while e >= eps:
b -= 0.01
e = find_err(a, b)
print(b)
путем сужения отрезка получено b = 0.43
'''
b = 0.43
h = (b - a) / 3
canvas.figure(1)
x = np.arange(a, b, 0.001)
canvas.title("График 4 производной")
canvas.xlabel("x")
canvas.ylabel("y")
canvas.grid()
canvas.plot(x, f4(x))
X = np.array([a, a + h, a + 2 * h, a + 3 * h])
Y = f(X)
lagrange, newton, function = [], [], []
for i in range(len(x)):
lagrange.append(lagrange_P(x[i], X, Y))
newton.append(newton_P(x[i], X, Y, h))
function.append(f(x[i]))
canvas.figure(2)
canvas.title("Полиномы")
canvas.xlabel("x")
canvas.grid()
canvas.plot(x, newton, label="Ньютон")
canvas.plot(x, lagrange, label="Лагранж")
canvas.plot(x, function, label="Функция")
canvas.legend()
canvas.figure(3)
canvas.title("Абслоютные погрешности")
canvas.xlabel("x")
canvas.ylabel("Rn(x)")
canvas.plot(x, abs(f(x) - newton), label="Ньютон")
canvas.plot(x, abs(f(x) - lagrange), label="Лагранж")
canvas.legend()
canvas.grid()
canvas.show()
|
ce3207a74b696e47c3349e4817cabcae55a4649a | ogarnica/Compumaticas | /progresiones.py | 151 | 3.5 | 4 | a1 = int(input('primer numero: '))
d = int(input('desplazamiento: '))
n = int(input('ultimo termino: '))
an = a1+(n-1)*d
suma = (a1+an)/2*n
print(suma) |
68fe05c07018b0dab716f70b94febaedc60e988e | romulovieira777/Programacao_em_Python_Essencial | /Seção 05 - Estruturas Lógicas e Condicionais em Python/Exercícios da Seção/Exercício_31.py | 1,044 | 4.21875 | 4 | """
31) Faça um programa que receba a altura e o peso de uma pessoa.
De acordo com a tabela a seguir, verifique e mostre qual a classificação
dessa pessoa.
| Altura | Peso |
| |Até 60 | Entre 60 e 90 (Inclusive) | Acima de 90 |
|Menor que 1,20| A | D | G |
|De 1,20 a 1,70| B | E | H |
|Maior que 1,70| C | F | I |
"""
height = float(input("Enter your height: "))
weight = int(input("Enter yor weight: "))
if height < 1.20 and weight <= 60:
print('Classification: A')
elif (height >= 1.20) and (height <= 1.70) and (weight <= 60):
print('Claasification B')
elif (height > 1.70) and (weight <= 60):
print('Classification C')
elif (height < 1.20) and (weight >= 60) and (weight <= 90):
print('Classification D')
elif (height >= 1.20) and (height <= 170) and (weight >= 60) and (weight <= 90):
print('Classification E')
|
0c197f957465b229407a753d8e95d9154976eb04 | andres4423/Andres-Arango--UPB | /Numpy/Ejercicio14.py | 954 | 4.1875 | 4 | print("Write a NumPy program to convert the values of Centigrade degrees into Fahrenheit degrees. Centigrade values are stored into a NumPy array.")
print("Sample Array [0, 12, 45.21 ,34, 99.91] Expected Output: Values in Fahrenheit degrees: [ 0. 12. 45.21 34. 99.91] Values in Centigrade degrees: [-17.77777778 -11.11111111 7.33888889 1.11111111 37.72777778]")
print("Escriba un programa NumPy para convertir los valores de grados centígrados en grados Fahrenheit. Los valores en grados centígrados se almacenan en una matriz NumPy.")
print("Matriz de muestra [0, 12, 45.21, 34, 99.91] Salida esperada: Valores en grados Fahrenheit: [0. 12. 45.21 34. 99.91] Valores en grados centígrados: [-17.77777778 -11.11111111 7.33888889 1.11111111 37.72777778]")
import numpy as np
fvalues = [0, 12, 45.21, 34, 99.91]
F = np.array(fvalues)
print("Values in Fahrenheit degrees:")
print(F)
print("Values in Centigrade degrees:")
print(5*F/9 - 5*32/9) |
2a28b5fc1d2aacf435be44ab848b76a981d5860c | whjr2021/G11-C3-V1-SAA1-Solution | /C3_SAA1_Solution.py | 694 | 4.15625 | 4 | # Define a variable "num1" and assign a value to it
num1 = 90
# Define a variable "num2" and assign a value to it
num2 = 50
# Define a variable "choice" and assign any one value between 1 to 4
choice = 3
# Check if "choice" is equal to 1, then print the sum of "num1" and "num2"
if choice == 1:
print(num1 + num2)
# Check if "choice" is equal to 2, then print the difference between "num1" and "num2"
if choice == 2:
print(num1 - num2)
# Check if "choice" is equal to 3, then print the product of "num1" and "num2"
if choice == 3:
print(num1 * num2)
# Check if "choice" is equal to 4, then print the result of "num1" divided by "num2"
if choice == 4:
print(num1 / num2) |
5fe95ba0f69683028a95ff2a976c464c7c4ec33b | zidarsk8/aoc2019 | /test_aoc_20.py | 12,848 | 3.515625 | 4 | import string
import collections
import heapq
class Vertex:
def __init__(self, name, pos=None, dl=0):
self.pos = pos
self.name = name
self.adjacent = {}
self.distance = 100000000
self.previous = None
self.dl = dl
def __str__(self):
return (
f"{self.name} {self.previous and self.previous.name} "
f"{self.distance} adjacent: {[x.name for x in self.adjacent]}"
)
def add_neighbor(self, neighbor, weight=0):
self.adjacent[neighbor] = weight
def get_connections(self):
return self.adjacent.keys()
def get_weight(self, neighbor):
return self.adjacent[neighbor]
def get_adjacent_repr(self):
return {k.name: v for k, v in self.adjacent.items()}
def __gt__(self, other):
return self.distance > other.distance
class Graph:
def __init__(self):
self.vert_dict = {}
self.num_vertices = 0
def __iter__(self):
return iter(self.vert_dict.values())
def add_vertex(self, name, pos=None, dl=0):
self.num_vertices = self.num_vertices + 1
new_vertex = Vertex(name, pos, dl)
self.vert_dict[name] = new_vertex
return new_vertex
def get_vertex(self, vertex_id: str) -> Vertex:
return self.vert_dict[vertex_id]
def add_edge(self, frm, to, cost=0):
if frm not in self.vert_dict:
self.add_vertex(frm)
if to not in self.vert_dict:
self.add_vertex(to)
self.vert_dict[frm].add_neighbor(self.vert_dict[to], cost)
self.vert_dict[to].add_neighbor(self.vert_dict[frm], cost)
def get_vertices(self):
return self.vert_dict.keys()
class Maze:
moves = [(-1, 0), (1, 0), (0, 1), (0, -1)]
def __init__(self, input_number):
self.current = set()
self.visited = set()
self.input_file: str = f"aoc_20_input_{input_number}.txt"
self.data: Dict[Point, str] = {}
self.width = 0
self.height = 0
self.read_data()
self.close_dead_ends()
self.thickness = self.get_maze_thickness()
self.portals: Dict[str, Tuple[int, int]] = self.all_portals()
self.portal_map: Dict[Tuple[int, int], str] = {
v: k for k, v in self.portals.items()
}
def get_maze_thickness(self):
if not self.data:
return 0
for i in range(2, self.height // 2):
if self.data[(i, i)] != "#":
break
return i - 2
def read_data(self):
with open(self.input_file) as f:
for y, line in enumerate(f.read().splitlines()):
for x, char in enumerate(line):
self.data[(x, y)] = char
self.width = x
self.height = y
def _count_walls(self, x, y):
return self._count_chars(x, y, "#")
def _count_chars(self, x, y, char):
return sum(1 for dx, dy in self.moves if self.data[(x + dx, y + dy)] == char)
def close_dead_ends(self):
grid = ""
new_grid = self.get_grid()
while grid != new_grid:
grid = new_grid
for _ in range(10):
self._close_wall_step()
new_grid = self.get_grid()
def _close_wall_step(self):
for y in range(1, self.height):
for x in range(1, self.width):
if self._count_walls(x, y) == 3:
self.data[(x, y)] = "#"
def get_grid(self):
def ch(x, y):
if (x, y) in self.current:
return "*"
if (x, y) in self.visited:
return " "
return self.data[(x, y)]
return "\n".join(
"".join(ch(x, y) for x in range(self.width + 1))
for y in range(self.height + 1)
)
def print(self):
print(self.get_grid().replace("#", "░"))
print()
def _add_graph_vertices(self, g):
for portal, pos in self.portals.items():
g.add_vertex(portal, pos)
return g
def _get_possible_steps(self, position):
x, y = position
return [
(x + dx, y + dy)
for dx, dy in self.moves
if self.data[(x + dx, y + dy)] == "."
]
def _walk_from_portal(self, start_position):
visited_portals = {}
self.current = {start_position}
self.visited = {start_position}
steps = 0
while self.current:
possible_positions = set(
sum([self._get_possible_steps(cur) for cur in self.current], [])
)
self.visited = self.visited.union(self.current)
self.current = possible_positions.difference(self.visited)
steps += 1
for pos in self.current:
if pos in self.portal_map:
visited_portals[self.portal_map[pos]] = (steps, pos)
# print(steps)
# self.print()
self.visited = set()
self.current = set()
return visited_portals
def _add_graph_edges(self, g):
for portal, position in self.portals.items():
visited_portals = self._walk_from_portal(position)
for visited_portal, dist_pos in visited_portals.items():
distance, _ = dist_pos
g.add_edge(portal, visited_portal, cost=distance)
for portal in self.portals:
base = portal[:2]
p1, p2 = f"{base}o", f"{base}i"
if p1 in self.portals and p2 in self.portals:
g.add_edge(f"{base}o", f"{base}i", 1)
return g
def to_graph(self):
g = Graph()
g = self._add_graph_vertices(g)
g = self._add_graph_edges(g)
return g
def _find_dot_around(self, x, y):
for dx, dy in self.moves:
if self.data.get((x + dx, y + dy), "") == ".":
return (x + dx, y + dy)
def _get_portal_position(self, x1, y1, x2, y2):
return self._find_dot_around(x1, y1) or self._find_dot_around(x2, y2)
def _get_portal_name(self, x1, y1, x2, y2):
chars = self.data[(x1, y1)] + self.data[(x2, y2)]
rim = "i" if 3 < x1 < self.width - 3 and 3 < y1 < self.height - 3 else "o"
return chars + rim
def all_portals(self):
portals = {}
for x in range(self.width):
for y in range(self.height):
if (
self.data[(x, y)] in string.ascii_uppercase
and self.data[(x + 1, y)] in string.ascii_uppercase
):
portal_name = self._get_portal_name(x, y, x + 1, y)
portal_position = self._get_portal_position(x, y, x + 1, y)
portals[portal_name] = portal_position
if (
self.data[(x, y)] in string.ascii_uppercase
and self.data[(x, y + 1)] in string.ascii_uppercase
):
portal_name = self._get_portal_name(x, y, x, y + 1)
portal_position = self._get_portal_position(x, y, x, y + 1)
portals[portal_name] = portal_position
return portals
def _dl(self, pos):
return -1 if min(pos) < 3 or max(pos) > self.width - 3 else 1
def _is_wall(vert, current_level):
if vert.name[:2] in ("AA", "ZZ"):
return current_level != 0
elif vert.name[2] == "o":
return current_level == 0
return False
def _add_level_neighbors(data, g, current):
for vert, cost in data.vert_dict[current.name[:3]].adjacent.items():
neighbor_level = int(current.name[3:])
if vert.name[:2] == current.name[:2]:
if vert.name[2] == "o":
neighbor_level += 1
else:
neighbor_level -= 1
if _is_wall(vert, neighbor_level):
continue
neighbor_name = f"{vert.name}{neighbor_level}"
neighbor: Vertext = g.vert_dict.get(neighbor_name)
if neighbor:
if neighbor.distance > current.distance + cost:
neighbor.distance = current.distance + cost
neighbor.previous = current
else:
g.add_edge(current.name, neighbor_name, cost)
new_vertex = g.vert_dict[neighbor_name]
new_vertex.distance = current.distance + cost
new_vertex.previous = current
yield new_vertex
def dikstra_walk(data, to):
g = Graph()
start_vertex = g.add_vertex("AAo0")
start_vertex.distance = 0
unvisited: List[Vertex] = [start_vertex]
heapq.heapify(unvisited)
i = 0
while to not in g.vert_dict:
current: Vertex = heapq.heappop(unvisited)
new_neighbors = _add_level_neighbors(data, g, current)
for n in new_neighbors:
heapq.heappush(unvisited, n)
i += 1
if i > 600000:
break
return g
def test_maze3_levels():
maze = Maze(3)
to = "ZZo0"
data = maze.to_graph()
g = dikstra_walk(data, to)
assert g.vert_dict.get(to).distance == 396
def test_part2():
maze = Maze(0)
to = "ZZo0"
data = maze.to_graph()
g = dikstra_walk(data, to)
assert g.vert_dict.get(to).distance == 6592
def dikstra(g: Graph, frm, to):
print("Dikstra")
distances = 1000000000000
frm = g.get_vertex(frm)
to = g.get_vertex(to)
frm.distance = 0
unvisited: List[Vertex] = list(g.vert_dict.values())
heapq.heapify(unvisited)
while unvisited:
closest: Vertex = heapq.heappop(unvisited)
for neighbor, distance in closest.adjacent.items():
alt = closest.distance + distance
if neighbor.distance > alt:
neighbor.distance = alt
neighbor.previous = closest
heapq.heapify(unvisited)
def test_dikstra_1():
maze = Maze(1)
g = maze.to_graph()
dikstra(g, "AAo", "ZZo")
assert g.get_vertex("ZZo").distance == 23
def test_dikstra_2():
maze = Maze(2)
g = maze.to_graph()
dikstra(g, "AAo", "ZZo")
assert g.get_vertex("ZZo").distance == 58
# def test_dikstra():
# maze = Maze(0)
# g = maze.to_graph()
# dikstra(g, "AAo", "ZZo")
# assert g.get_vertex("ZZo").distance == 578
def test_graph():
g = Graph()
g.add_vertex("a")
g.add_vertex("b")
g.add_vertex("c")
g.add_vertex("d")
g.add_vertex("e")
g.add_vertex("f")
g.add_edge("a", "b", 7)
g.add_edge("a", "c", 9)
g.add_edge("a", "f", 14)
g.add_edge("b", "c", 10)
g.add_edge("b", "d", 15)
g.add_edge("c", "d", 11)
g.add_edge("c", "f", 2)
g.add_edge("d", "e", 6)
g.add_edge("e", "f", 9)
for v in g:
for w in v.get_connections():
vid = v.name
wid = w.name
print("( %s , %s, %3d)" % (vid, wid, v.get_weight(w)))
for v in g:
print("g.vert_dict[%s]=%s" % (v.name, g.vert_dict[v.name]))
assert g.vert_dict["a"].get_adjacent_repr() == {"b": 7, "c": 9, "f": 14}
def test_maze_thickness():
maze = Maze(2)
assert maze.thickness == 7
maze = Maze(1)
assert maze.thickness == 5
maze = Maze(3)
assert maze.thickness == 5
# maze = Maze(0)
# assert maze.thickness == 31
def test_maze_to_graph_2():
maze = Maze(2)
maze.print()
g = maze.to_graph()
assert set(g.vert_dict.keys()) == {
"AAo",
"ASo",
"ASi",
"BUo",
"BUi",
"CPo",
"CPi",
"DIo",
"DIi",
"JOo",
"JOi",
"JPo",
"JPi",
"LFo",
"LFi",
"QGo",
"QGi",
"VTo",
"VTi",
"YNo",
"YNi",
"ZZo",
}
print(maze.portals)
assert set(maze.portals) == set(g.vert_dict.keys())
def test_graph_edges():
maze = Maze(1)
maze.print()
g = maze.to_graph()
assert "ZZo" in {v.name for v in g.vert_dict["AAo"].adjacent}
assert g.vert_dict["AAo"].adjacent[g.get_vertex("ZZo")] == 26
assert g.vert_dict["ZZo"].adjacent[g.get_vertex("AAo")] == 26
assert g.vert_dict["AAo"].adjacent[g.get_vertex("BCi")] == 4
assert g.vert_dict["BCi"].adjacent[g.get_vertex("AAo")] == 4
assert g.vert_dict["BCo"].adjacent[g.get_vertex("DEi")] == 6
assert g.vert_dict["DEi"].adjacent[g.get_vertex("BCo")] == 6
assert g.vert_dict["FGo"].adjacent[g.get_vertex("DEo")] == 4
assert g.vert_dict["FGi"].adjacent[g.get_vertex("ZZo")] == 6
def test_maze_to_graph():
# maze = Maze(0)
# g = maze.to_graph()
# assert set(maze.portals) == set(g.vert_dict.keys())
maze = Maze(1)
g = maze.to_graph()
assert set(maze.portals) == set(g.vert_dict.keys())
maze = Maze(2)
g = maze.to_graph()
assert set(maze.portals) == set(g.vert_dict.keys())
|
d6da3d1dc564c45307cc28a419e904c3bab9bcba | AndresERojasI/ClaseJS | /Python/First Class/3_Operators.py | 1,696 | 4 | 4 | #------------------ Arithmetic: ------------------#
x = 15
y = 4
# Output: x + y = 19
print('x + y =', x+y)
# Output: x - y = 11
print('x - y =', x-y)
# Output: x * y = 60
print('x * y =', x*y)
# Output: x / y = 3.75
print('x / y =', x/y)
# Output: x // y = 3
print('x // y =', x//y)
# Output: x ** y = 50625
print('x ** y =', x**y)
#------------------ Comparisons: ------------------#
x = 10
y = 12
# Output: x > y is False
print('x > y is',x>y)
# Output: x < y is True
print('x < y is',x<y)
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
# Output: x >= y is False
print('x >= y is',x>=y)
# Output: x <= y is True
print('x <= y is',x<=y)
#------------------ Logical: ------------------#
x = True
y = False
# Output: x and y is False
print('x and y is', x and y)
# Output: x or y is True
print('x or y is', x or y)
# Output: not x is False
print('not x is', not x)
camilo = False
print(not camilo)# True
#------------------ Identity: ------------------#
# Is mira la posiciòn de memoria del dato
True is True
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
x3[2] = True
# Output: False
print(x1 is not y1)
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
if x1 is y1:
print('They are the same')
type(x1)
isinstance(x1, type(y1))
#------------------ Membership: ------------------#
x = 'Hello world'
y = {1:'a',2:'b'}
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)
#------------------ Assignment and Bitwise: ------------------#
# https://www.programiz.com/python-programming/operators |
a535b84f63b71526ec980926a847574d4a0dc5a9 | mrsingh3131/Foobar | /Some other foobar gits/xslittlegrass/solutions/Q41.py | 1,984 | 3.796875 | 4 | import itertools
def calculate_graph_distance_matrix(weight_mtx):
"""calculate shortest graph distance matrix"""
num_vertex = len(weight_mtx)
dist = [[0 for i in range(num_vertex)] for j in range(num_vertex)]
for i in range(num_vertex):
for j in range(num_vertex):
dist[i][j] = weight_mtx[i][j]
for k in range(num_vertex):
for i in range(num_vertex):
for j in range(num_vertex):
if dist[i][j] > dist[i][k] + dist[k][j]:
dist[i][j] = dist[i][k] + dist[k][j]
if dist[j][j] < 0:
return -1
return dist
def calculate_path_length(weight_mtx,path):
"""calculate path length"""
path_length = 0
for i in range(len(path)-1):
path_length += weight_mtx[path[i]][path[i+1]]
return path_length
def answer(times,time_limit):
dim = len(times)
all_paths = [] # all paths from initial point to door
path_distances = [] # all path with path length
for i in range(dim-1):
all_paths.extend(itertools.permutations(range(1,dim-1),i))
all_paths = [[0] + list(path) + [dim-1] for path in all_paths]
distance_matrix = calculate_graph_distance_matrix(times)
if distance_matrix == -1: # if there is a negative cycle
return range(0,dim-2) # all bunnies can be rescued
# all possible path that can exit
for path in all_paths:
path_len = calculate_path_length(distance_matrix,path)
if path_len <= time_limit:
path_distances.append([path,path_len])
num_rescu = max([len(p[0]) for p in path_distances]) # max number of bunnies can be rescued
path_distances = [p for p in path_distances if len(p[0]) == num_rescu]
optimal_paths = [p[0] for p in path_distances]
for p in optimal_paths:
p.sort()
optimal_paths.sort()
bunny_list = optimal_paths[0][1:-1]
bunny_list = [i-1 for i in bunny_list]
return bunny_list
|
9f36d102f754864e405354fa1dd86c970eec5f76 | ahd3r/some_code_python | /Cat.py | 2,414 | 3.5625 | 4 | from random import randint
class Cat:
def __init__(self, name):
self.name = name
self.mood = 100
self.fulness = 50
self.home = None
self.sleep = 100
def __str__(self):
if self.home is None:
if self.sleep >= 75:
return f'I am a {self.name}, I am {self.mood}% good, I am full on {self.fulness}%, I don`t want to sleep ({self.sleep}%) and i am a stranger'
if self.sleep >= 50:
return f'I am a {self.name}, I am {self.mood}% good, I am full on {self.fulness}%, I want to sleep a little bit ({self.sleep}%) and i am a stranger'
if self.sleep >= -200:
return f'I am a {self.name}, I am {self.mood}% good, I am full on {self.fulness}%, I want to sleep ({self.sleep}%) and i am a stranger'
else:
if self.sleep >= 75:
return f'I am a {self.name}, I am {self.mood}% good, I am full on {self.fulness}%, I don`t want to sleep ({self.sleep}%)'
if self.sleep >= 50:
return f'I am a {self.name}, I am {self.mood}% good, I am full on {self.fulness}%, I want to sleep a little bit ({self.sleep}%)'
if self.sleep >= -200:
return f'I am a {self.name}, I am {self.mood}% good, I am full on {self.fulness}%, I want to sleep ({self.sleep}%)'
def eat(self):
print(f'Food was teasty')
self.fulness += 20
self.sleep -= 10
self.mood += 20
def zzzz(self):
print(f'I was dreaming')
self.fulness -= 10
self.sleep += 20
self.mood -= 20
def walk(self):
print(f'Finaly, I am at home')
self.sleep -= 10
self.fulness -= 10
self.mood += 20
def in_home(self):
if self.home is None:
house = Home(full_of_bawl = 100)
self.home = house
print(f'I, {self.name}, settle in the house')
else:
print(f'Go back at your house')
def act(self):
dice = randint(1, 3)
if dice == 1:
self.eat()
if dice == 2:
self.zzzz()
if dice == 3:
self.walk()
class Home:
def __init__(self, full_of_bawl):
self.bawl = full_of_bawl
bob = Cat(name = 'Bob')
print(bob)
bob.eat()
print(bob)
bob.zzzz()
print(bob)
bob.in_home()
print(bob)
for day in range(1, 31):
print(f'********************{day}')
if bob.sleep <= 40:
bob.zzzz()
print(f'{bob.name} forced to sleep')
if bob.fulness <= 20:
bob.eat()
print(f'{bob.name} forced to eat')
if bob.mood <= 40:
bob.walk()
print(f'{bob.name} forced to walk')
else:
bob.act()
print(bob) |
4a081e1427d0562c4ca9a6d57fc003355e93278d | wljave/subentry | /test/module.py | 767 | 3.796875 | 4 | a = '我是模块中的变量a'
def hi():
a = '我是函数里的变量a'
print('函数“hi”已经运行!')
class Go1: # 如果没有继承的类,class语句中可以省略括号,但定义函数的def语句括号不能省
a = '我是类1中的变量a'
@classmethod
def do1(cls):
print('函数“do1”已经运行!')
class Go2:
a = '我是类2中的变量a'
def do2(self):
print('函数“do2”已经运行!')
print(a) # 打印变量“a”
hi() # 调用函数“hi”
print(Go1.a) # 打印类属性“a”
Go1.do1() # 调用类方法“Go1”
A = Go2() # 实例化“Go2”类
print(A.a) # 打印实例属性“a”
A.do2() # 调用实例方法“do2”
|
66976de4fdaa47fb3986cc9ca06751dbb4868ba9 | AndrewDuncan/Doublecoset | /python/genfold/hd.py | 499 | 3.53125 | 4 | from graph import *
G=Graph()
a=G.addVertex()
b=G.addVertex()
c=G.addVertex()
d=G.addVertex()
e=G.addVertex()
f=G.addVertex()
G.addEdge(a,b,'x')
G.addEdge(a,b,'y')
G.addEdge(b,c,'x')
G.addEdge(b,c,'y')
G.addEdge(c,d,'x')
G.addEdge(c,d,'y')
G.addEdge(d,a,'x')
G.addEdge(d,a,'y')
G.addEdge(a,e,'w')
G.addEdge(e,a,'w')
G.addEdge(e,f,'x')
G.addEdge(f,e,'y')
print "digraph hd {"
print(str(G))
print "}"
D= G.double()
print ("digraph SxS {")
print (str(D))
print ("}")
|
828879ec7bbfeb56f44b558e961fdc4017d59c7f | akimi-yano/algorithm-practice | /lc/1814.CountNicePairsInAnArray.py | 3,029 | 3.609375 | 4 | # 1814. Count Nice Pairs in an Array
# Medium
# 103
# 11
# Add to List
# Share
# You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions:
# 0 <= i < j < nums.length
# nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])
# Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.
# Example 1:
# Input: nums = [42,11,1,97]
# Output: 2
# Explanation: The two pairs are:
# - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.
# - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.
# Example 2:
# Input: nums = [13,10,35,24,76]
# Output: 4
# Constraints:
# 1 <= nums.length <= 105
# 0 <= nums[i] <= 109
# This solution works:
from sortedcontainers import SortedList
class Solution:
MOD = 10 ** 9 + 7
def countNicePairs(self, nums: List[int]) -> int:
memo = {}
for num in nums:
digit = 0
temp = num
while temp:
temp //=10
digit +=1
val = 0
temp = num
digit -= 1
while temp:
temp, mod = divmod(temp, 10)
val += mod * 10 ** digit
digit -=1
memo[num] = val
ans = 0
slist = SortedList()
'''
look = 2
[1, 3]
bisect_left = 1
bisect_right = 1
look = 2
[1, 2, 2, 3]
bisect_left = 1
bisect_right = 3
'''
for num in nums:
opposite = memo[num]
look = num - opposite
left = slist.bisect_left(look)
right = slist.bisect_right(look)
ans += right - left
slist.add(look)
return ans % Solution.MOD
# This approach does not work:
# class Solution:
# MOD = 10 ** 9 + 7
# def countNicePairs(self, nums: List[int]) -> int:
# memo = {}
# for num in nums:
# digit = 0
# temp = num
# while temp:
# temp //=10
# digit +=1
# val = 0
# temp = num
# digit -= 1
# while temp:
# temp, mod = divmod(temp, 10)
# val += mod * 10 ** digit
# digit -=1
# memo[num] = val
# ans = 0
# counts = Counter(nums)
# for num in nums:
# if counts[num] < 1:
# continue
# opposite = memo[num]
# look = num - opposite
# for nextnum in nums:
# if nextnum - memo[nextnum] == look:
# ans += 1
# counts[num] -= 1
# counts[nextnum] -= 1
# break
# return ans % Solution.MOD
|
7b4f974b6893ef01ea389b5665d6158c5b2d168b | SuryaGowrisetti/War_game | /game_logic.py | 1,996 | 3.578125 | 4 | import deck
import player
a_deck = deck.Deck()
a_deck.shuffle() # shuffling the deck
player1 = player.Player('Surya')
player2 = player.Player('Chandu')
for i in range(int(len(a_deck.cards)/2)):
player1.cards.append(a_deck.deal_one())
player2.cards.append(a_deck.deal_one())
game_on = True
round_num = 0
while game_on == True:
round_num += 1
print(f"Round {round_num}")
if len(player1.cards) == 0:
print(f"{player1.name} has lost")
game_on = False
break
elif len(player2.cards) == 0:
print(f"{player2.name} has lost")
game_on = False
break
player_one_cards = []
player_one_cards.append(player1.remove_one())
player_two_cards = []
player_two_cards.append(player2.remove_one())
at_war = True
while at_war == True:
if player_one_cards[-1].value > player_two_cards[-1].value:
player1.add_cards(player_two_cards)
player1.add_cards(player_two_cards)
at_war = False
elif player_one_cards[-1].value < player_two_cards[-1].value:
player2.add_cards(player_two_cards)
player2.add_cards(player_one_cards)
at_war = False
elif player_two_cards[-1].value == player_two_cards[-1].value:
print('WARR')
if len(player1.cards) < 10:
print(f'{player1.name} has no cards left and loses')
print(f'{player2.name} has won the game')
game_on = False
break
elif len(player2.cards) < 10:
print(f'{player2.name} has no cards left and loses')
print(f'{player1.name} has won the game')
game_on = False
break
else:
for num in range(10):
player_one_cards.append(player1.remove_one())
player_two_cards.append(player2.remove_one())
|
455c50d52518d02c67c1095fd2ed087f8909e8f4 | alexhla/programming-problems-in-python | /remove_duplicates.py | 667 | 3.71875 | 4 | class Solution:
def removeDuplicates(self, nums): # remove duplicate numbers from a sorted list
if not nums: # an empty list has zero duplicates
return 0
i = 0 # 1st pointer
for j in range(1, len(nums)): # loop with 2nd pointer to avoid index overflow
if nums[i] != nums[j]: # IF nums at 1st and 2nd pointers are NOT the same
i += 1 # increment first pointer
nums[i] = nums[j] # swap nums
return i+1
obj = Solution()
arr = [0, 0, 0, 1, 2, 3, 3, 4, 5, 5, 5, 6, 6, 7, 8, 9, 10]
print("Remove Duplicates From Integers: {}\n" .format(arr))
print("Answer: {}" .format(obj.removeDuplicates(arr)))
print("Resulting Integers: {}" .format(arr)) |
5ee59d3cf66f8cea47d1d32cb3ba1ddc667dff41 | amandeep1991/data_science | /ai/nlp/udemy/1/Section 4 - Regular Expression/regex6_groups.py | 405 | 3.796875 | 4 |
import re
# Regex Groups using or '|'
###### OR is represented by |
###### You can a group using ()
###### explicit character range using []
# Few patters
r"[A-Za-z]+" # upper or lowercase English alphabet
r"[0-9]" # numbers from 0 to 9
r"[A-Za-z\-\.]+" # upper or lower case English alphabets with - or .
r"(a-z)" # a,- & z
s_c = r"(\s+|,)" # spaces or commas
sentence = ","
re.search(s_c, sentence) |
a9f066966368df9c51ebea91a1cbfff8b06bb8c5 | Neha-kumari31/Intro-Python-II | /src/player.py | 413 | 3.578125 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
from room import Room
class Player:
def __init__(self, current_room=None):
self.current_room = current_room
self.player_items= []
def add_inventory(self,item):
self.player_items.append(item)
#player_1 = Player('outside')
#print(player_1.current_room)
#print(player_1.description) |
721aee08db14cd87e44347ab075b48c4706b942e | kunalt4/AlgorithmsandDataStructuresCoursera | /Algorithmic Toolbox/week4_divide_and_conquer/5_organizing_a_lottery/points_and_segments.py | 1,456 | 3.625 | 4 | # Uses python3
import sys
import collections
def fast_count_segments(starts, ends, points):
l_label = 1
point_label = 2
r_label = 3
cnt = [0] * len(points)
points_dict = collections.defaultdict(set)
tuples = []
for start in starts:
tuples.append((start, l_label))
for end in ends:
tuples.append((end, r_label))
for idx, point in enumerate(points):
tuples.append((point, point_label))
points_dict[point].add(idx)
sort_vals = sorted(tuples, key=lambda p: (p[0], p[1]))
overlap = 0
for tup in sort_vals:
if tup[1] == l_label:
overlap += 1
elif tup[1] == r_label:
overlap -= 1
else:
indexes = points_dict[tup[0]]
for i in indexes:
cnt[i] = overlap
# write your code here
return cnt
def naive_count_segments(starts, ends, points):
cnt = [0] * len(points)
for i in range(len(points)):
for j in range(len(starts)):
if starts[j] <= points[i] <= ends[j]:
cnt[i] += 1
return cnt
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n = data[0]
m = data[1]
starts = data[2:2 * n + 2:2]
ends = data[3:2 * n + 2:2]
points = data[2 * n + 2:]
# use fast_count_segments
cnt = fast_count_segments(starts, ends, points)
for x in cnt:
print(x, end=' ')
|
5eed55109def2c21809d4178fdfd5567bbd32797 | CesaireTchoudjuen/programming | /week03-Variables/Lab3.2.2-absolute.py | 246 | 4.28125 | 4 | # Author: Cesaire Tchoudjuen
# Program takes in number and give its absolute value (ie -4 or 4 would both output 4)
number = float(input("Enter a number: "))
absoluteValue = abs(number)
print("The absolute value of {} is {}.".format(number, absoluteValue)) |
161ef8932c1a6c2be3e188b8e3ba01a014255d69 | anirudh1808/Python | /python_tut/concept_in.py | 102 | 3.640625 | 4 | word="anirudh is a good boy"
for letter in word :
print (letter)
if ("good" in word) :
print ("hello")
|
1b4ce7373f79c139354d9c65b7fc6654c47c44bc | shijia-listen/python-basic-exercises | /python基础知识练习/user-password.py | 324 | 3.59375 | 4 | import getpass
n=0
while n <3:
name = raw_input('û: ')
pwd = getpass.getpass(': ')
if name=='listen' and pwd=='admin123':
print('ӭɹ,listen')
break
else:
print('û!')
n+=1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.