blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
eb3d83b0bbece1e169567a4dcd64aaf6475713d6
|
VincentiSean/Python-Practice
|
/multiplicationTable.py
| 1,067 | 4.3125 | 4 |
#! python3
# multiplicationTable.py - This program takes a number, N, from command line
# and creates an N x N multiplication table in an Excel sheet.
import openpyxl, sys
from openpyxl.styles import Font
wb = openpyxl.Workbook() # Create a new blank spreadsheet
sheet = wb['Sheet']
numIn = int(sys.argv[1])
boldFont = Font(bold=True)
# Set default values for the first row up to numIn (skipping the first cell)
# Also, make the font bold
for col in range(1, numIn+1):
currCell = sheet.cell(row=1, column=col+1)
currCell.value = col
currCell.font = boldFont
# Set default values for the first column up to numIn (skipping the first cell)
# Also, make the font bold
for row in range(1, numIn+1):
currCell = sheet.cell(row=row+1, column=1)
currCell.value = row
currCell.font = boldFont
# Do the maths
for i in range(1, sheet.max_row):
for j in range(1, sheet.max_row):
sheet.cell(row=i+1, column=j+1).value = i * j
wb.save('excel/' + str(numIn) + 'by' + str(numIn) + '.xlsx')
wb.close()
|
f2828f15c694ca5ae8bfe5cba9a5bd43ab256dc7
|
aadimangla/Churn-Modelling-for-a-Bank
|
/Model/neural_network.py
| 2,141 | 4.03125 | 4 |
# Artificial Neural Networks
# Part 1 - Data Preprocessing
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing Dataset
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
X = X[:,1:]
# Splitting the dataset into training set and test set
from sklearn.model_selection import train_test_split
X_train , X_test , y_train , y_test = train_test_split(X,y, test_size = 0.2 , random_state=0)
#Feature Scaling
from sklearn.preprocessing import StandardScaler
sc_X=StandardScaler()
X_train=sc_X.fit_transform(X_train)
X_test=sc_X.transform(X_test)
#Importing the keras librabries nd packages
import keras
from keras.models import Sequential
from keras.layers import Dense
# Part 2 - Now let's make the ANN!
#Initialising the ANN
classifier = Sequential()
#Adding the input layer and the first hidden layer
classifier.add(Dense( units = 6 , kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))
#Adding the second hidden layer
classifier.add(Dense( units = 6 , kernel_initializer = 'uniform', activation = 'relu'))
#Adding the output layer
classifier.add(Dense( units = 1, kernel_initializer = 'uniform' , activation = 'sigmoid'))
#Compiling the ANN
classifier.compile( loss = 'binary_crossentropy',optimizer = 'adam',metrics = ['accuracy'])
#Fitting the ANN to the training set
classifier.fit(X_train,y_train, batch_size = 10 , nb_epoch = 100)
# Part 3 - Making the predictions and evaluating the model
#Predicting the Test set results
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)
#Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test , y_pred)
|
9ad4caea101d27a61c93de4c90ffca2a69fd2774
|
Anish-RV/pied-piper
|
/tests/unit/algorithms/test_pied_piper.py
| 388 | 3.578125 | 4 |
"""Tests for pied-piper/pied-piper.py."""
import unittest
class TestPiedPiper(unittest.TestCase):
def test_upper(self): # example of a unit test that tests for if the second argument is capitalized
self.assertEqual('foo'.upper(), 'FOO')
if __name__ == '__main__':
unittest.main()
"""//binary file //text file //both should have repeating non-repeating"""
|
683ecd564cb7da8235ede27662d69870611e483f
|
dstamp1/stock-query-mongodb-v2021
|
/stocks.py
| 1,864 | 3.890625 | 4 |
import pymongo
mongo_db_username = 'student'
mongo_db_password = 'PqyqrY2aEC22B5SB'
mongo_db_database = 'stock-prices'
## instantiate an instance of MongoClient
client = pymongo.MongoClient(f"mongodb+srv://{mongo_db_username}:{mongo_db_password}@cluster0-ya1yr.mongodb.net/{mongo_db_database}?retryWrites=true")
## connect to a db and store in variable []_db
stocks_db = client[mongo_db_database]
## connect to a collection in the database called 'prices'
prices_collection = stocks_db.prices ## collection = db['prices']
# write your queries here
## Warmup
# 1. List all entries in the prices collection in the stock-prices database.
# 2. List all historical Microsoft stock prices
# 3. List all historical stock prices from 2004
# 4. List all historical stock prices from September
# 5. List all historical stock prices from September 2004
# 6. List all historical stock prices in order from lowest value to highest value
# 7. List all historical stock prices in order from highest value to lowest value
# 8. List the first 5 historical stocks in the database.
# 9. Find an historical stock that was valued at $100.52.
# 10. How many entries are there in the database for Apple stock prices?
## Showtime
# 11. List the first 10 Apple entries in the database.
# 12. List the January IBM stock prices from lowest to highest.
# 13. List all historical stock prices over $200.00
# 14. List all historical stock prices less than $10.00.
# 15. What company's (or companies') stock was valued at $9.78 in October, 2000? Return only the name of the company.
# 16. What was the price of Amazon's Stock in August, 2006? Return only the price.
# 17. What was the highest historical price of Microsoft's stock? Return only the price.
# 18. For how many months (in the historical database) has Apple's stock price been greater than $100.00? Return only the number of months.
|
4e783c391c9455c813790339864fc12e82c68d41
|
ruchirbhai/Trees
|
/N-aryTreeLevelOrderTraversal_429.py
| 2,719 | 3.90625 | 4 |
# https://leetcode.com/problems/n-ary-tree-level-order-traversal/
# Given an n-ary tree, return the level order traversal of its nodes' values.
# Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
# Example 1:
# Input: root = [1,null,3,2,4,null,5,6]
# Output: [[1],[3,2,4],[5,6]]
# Example 2:
# Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
# Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
# Constraints:
# The height of the n-ary tree is less than or equal to 1000
# The total number of nodes is between [0, 10^4]
from collections import deque
global height
height = 0
class TreeNode:
def __init__(self, key):
"""
:data: key
:children: empty []
:rtype: None
"""
self.data = key
self.children = []
def add_child(self, child):
self.children.append(TreeNode(child))
class Solution:
def n_ary_tree(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
# edge case where the input is empty
if root is None:
return
# create the results list
result = []
# copy the given queue
q = deque([root])
# while len of q is not zero keep the while loop going
while len(q) != 0:
# get the count of all the nodes in this level
numnodes = len(q)
# create a tmp list for storing the values of nodes at each level
tmp = []
# go through each of the nodes
for _ in range(numnodes):
# pop the entire tree from the current root to the node variable
node = q.popleft()
# copy the key value only to tmp
tmp.append(node.data)
# for each child in the list we append the data
for child in node.children:
q.append(child)
result.append(tmp)
return result
def nary_height(self, root):
if root is None:
return 0
height = 0
for child in root.children:
height = max(height, self.nary_height(child))
return height + 1
#driver program for the above function
root = TreeNode(1)
root.add_child(3)
root.add_child(2)
root.add_child(4)
root.children[0].add_child(5)
root.children[0].add_child(6)
# Create a object for the class
obj = Solution()
#now call the class methos with the needed arguments
print(obj.n_ary_tree(root))
print(obj.nary_height(root))
|
1729d46c2c2c7bf4ba429d046e1c25a2fe4eb7ca
|
Ford-z/LeetCode
|
/1217 玩筹码.py
| 1,001 | 3.875 | 4 |
#数轴上放置了一些筹码,每个筹码的位置存在数组 chips 当中。
#你可以对 任何筹码 执行下面两种操作之一(不限操作次数,0 次也可以):
#将第 i 个筹码向左或者右移动 2 个单位,代价为 0。
#将第 i 个筹码向左或者右移动 1 个单位,代价为 1。
#最开始的时候,同一位置上也可能放着两个或者更多的筹码。
#返回将所有筹码移动到同一位置(任意位置)上所需要的最小代价。
#来源:力扣(LeetCode)
#链接:https://leetcode-cn.com/problems/minimum-cost-to-move-chips-to-the-same-position
#著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
count0 = 0
count1 = 0
for i in position:
if i%2 == 0:
count0+=1
else:
count1+=1
return min(count0,count1)
|
77c0867c00771a80927f174eae3775e7ed5e889d
|
Theveenan/Kahoot-Python-Game-Project
|
/Early Versions/V4 (two player implemented).py
| 12,831 | 3.921875 | 4 |
#Modules are imported
import time
import random
#Functions are defined
def create_question():
try:
questionsCount=int(input("how many questions would you like to create?"))
for x in range(questionsCount):
print("")
print("now editing question",x,". all changes later on will be for question",x)
inputQuestion=input("enter a question")
questions.append(inputQuestion)
print("")
inputAnswer1=input("enter an answer")
answer1.append(inputAnswer1)
print("")
inputAnswer2=input("enter an answer")
answer2.append(inputAnswer2)
print("")
inputAnswer3=input("enter an answer")
answer3.append(inputAnswer3)
print("")
inputAnswer4=input("enter an answer")
answer4.append(inputAnswer4)
print("")
correctAns=int(input("enter which answer number was the correct answer to the question"))
while correctAns>4 or correctAns<1:
print("Please enter a value between 1 and 4, this value represents which of the 4 possible answers provided, is correct.")
correctAns=int(input("enter which answer number was the correct answer to the question"))
correctAnswer.append(correctAns)
print("")
except:
print("Your entry is invalid, returning to main menu...")
def edit_question():
print("")
listToEdit=int(input("which question number do you want to change"))
print("")
newQuestion=input("re enter question for question")
print("")
newAnswer1=input("re enter answer for answer 1 of question")
print("")
newAnswer2=input("re enter answer for answer 2 of question")
print("")
newAnswer3=input("re enter answer for answer 3 of question")
print("")
newAnswer4=input("re enter answer for answer 4 of question")
print("")
newCorrectAns=int(input("which answer number was the correct answer to the question"))
print("...")
confirmation=int(input("Are you sure you would like to make these changes? Press 1 to confirm"))
if confirmation==1:
questions[listToEdit]=newQuestion
answer1[listToEdit]=newAnswer1
answer2[listToEdit]=newAnswer2
answer3[listToEdit]=newAnswer3
answer4[listToEdit]=newAnswer4
correctAnswer[listToEdit]=newCorrectAns
else:
print("cancelling question edit mode")
def preview_questions():
previewQuestion=int(input("which question would you like to preview answers for?"))
print("Question is '",questions[previewQuestion],"'",
"\n Answers are: 1)",answer1[previewQuestion]+", 2)",answer2[previewQuestion]+", 3)",answer3[previewQuestion]+", 4)",answer4[previewQuestion],
"\n Correct answer is answer",(correctAnswer[previewQuestion])+")")
def play_game1(highscore):
try:
playerCount=input("Press 1 for 1 player, or any other key for 2 players :")
if playerCount==("1"):
correct=0
incorrect=0
totalPoints=0
questionsAsked=[]
print(highscore)
for x in range(0,(len(questions))):
questionToAsk=random.randint(0,len(questions)-1)
while questionToAsk in questionsAsked:
questionToAsk=random.randint(0,len(questions)-1)
questionsAsked.append(questionToAsk)
print(questions[questionToAsk])
print(correctAnswer[questionToAsk])
time.sleep(1)
print("answer 1: ",answer1[questionToAsk])
print("answer 2: ",answer2[questionToAsk])
print("answer 3: ",answer3[questionToAsk])
print("answer 4: ",answer4[questionToAsk])
usersAnswer=input("which answer is correct (1,2,3 or 4)?")
if usersAnswer==(correctAnswer[questionToAsk]) or usersAnswer in (correctAnswer[questionToAsk]):
totalPoints+=1
correct+=1
else:
print("wrong. the correct answer was",correctAnswer[questionToAsk])
incorrect+=1
print("you have",totalPoints,"points")
print(""
"CONGRATULATIONS")
print("You finished with",totalPoints,"points!!!")
print("you got",correct,"correct and",incorrect,"incorrect")
try:
highscore=int(highscore)
if totalPoints>highscore:
highscore=totalPoints
print("THIS IS YOUR NEW HIGH SCORE")
else:
print("You didn't beat your highscore"
"but maybe next time!")
except:
print("No previous record has been recognized, which means THIS IS YOUR NEW HIGH SCORE")
highscore=totalPoints
return highscore
else:
player1points=0
player2points=0
questionsAsked=[]
for x in range(0,len(questions)):
questionToAsk=random.randint(0,len(questions)-1)
while questionToAsk in questionsAsked:
questionToAsk=random.randint(0,len(questions)-1)
questionsAsked.append(questionToAsk)
if x%2==1:
print("PLAYER 1 TURN")
print("Get ready!")
time.sleep(1)
player1Answer=play_game2(questionToAsk)
if player1Answer:
player1points+=1
print("you have",player1points,"points")
print("")
else:
print("PLAYER 2 CAN STEAL!")
time.sleep(1)
player2Answer=play_game2(questionToAsk)
if player2Answer:
player2points+=1
print("Hooray, you got the steal")
else:
print("OOF, you lost the steal..")
else:
print("PLAYER 2 TURN")
print("Get ready!")
time.sleep(1)
player2Answer=play_game2(questionToAsk)
if player2Answer:
player2points+=1
print("you have",player2points,"points")
print("")
else:
print("PLAYER 1 CAN STEAL!")
time.sleep(1)
player1Answer=play_game2(questionToAsk)
if player1Answer:
player1points+=1
print("Hooray, you got the steal")
else:
print("OOF, you lost the steal..")
print("\n"
"\n")
print("G A M E")
if player1points>player2points:
print("PLAYER 1 WINS!")
elif player2points>player1points:
print("PLAYER 2 WINS!")
else:
print("Tie game...")
print("Player 1 finished with",player1points,"points")
print("Player 2 finished with",player2points,"points")
except:
print("There was a problem while attempting to run Kahoot, Play game mode. Try restarting program.")
def play_game2(questionIndex):
print(questions[questionIndex])
print(correctAnswer[questionIndex])
time.sleep(1)
print("answer 1: ",answer1[questionIndex])
print("answer 2: ",answer2[questionIndex])
print("answer 3: ",answer3[questionIndex])
print("answer 4: ",answer4[questionIndex])
usersAnswer=input("which answer is correct (1,2,3 or 4)?")
if usersAnswer==(correctAnswer[questionIndex]) or usersAnswer in (correctAnswer[questionIndex]):
print("")
print("YAY CORRECT")
return True
else:
print("")
print("Wrong. the correct answer was",correctAnswer[questionIndex])
return False
def save_game():
try:
saveQuestions=str(questions)
saveAnswer1=str(answer1)
saveAnswer2=str(answer2)
saveAnswer3=str(answer3)
saveAnswer4=str(answer4)
saveCorrectAnswer=str(correctAnswer)
savedFile=open("gameSaveFile.txt","w")
savedFile.write(saveQuestions)
savedFile.write("\n")
savedFile.write(saveAnswer1)
savedFile.write("\n")
savedFile.write(saveAnswer2)
savedFile.write("\n")
savedFile.write(saveAnswer3)
savedFile.write("\n")
savedFile.write(saveAnswer4)
savedFile.write("\n")
savedFile.write(saveCorrectAnswer)
savedFile.write("\n")
try:
saveHighscore=str(highscore)
savedFile.write(saveHighscore)
savedFile.write("\n")
print("File saved, recover this same game data next time through 'load game' option")
except:
print("(no highscore has been found so no highscore will be saved)")
savedFile.close
except:
print("There was a problem trying to save your file, returning to main menu..")
#this function isnt allowing lists to be carried outside the function so i just copied the entire function below in the select mode section
def load_game():
try:
savedFile=open("gameSaveFile.txt","r")
fileLines=savedFile.readlines()
fileQuestions=fileLines[0].replace("[","").replace("]","").replace("'","").replace(", ",",").replace("\n","")
answers1=fileLines[1].replace("[","").replace("]","").replace("'","").replace(", ",",").replace("\n","")
answers2=fileLines[2].replace("[","").replace("]","").replace("'","").replace(", ",",").replace("\n","")
answers3=fileLines[3].replace("[","").replace("]","").replace("'","").replace(", ",",").replace("\n","")
answers4=fileLines[4].replace("[","").replace("]","").replace("'","").replace(", ",",").replace("\n","")
correctAnswers=fileLines[5].replace("[","").replace("]","").replace("'","").replace(" ","").replace(", ",",").replace("\n","")
highscore=fileLines[6]
print(fileQuestions)
print(answers1)
print(answers2)
print(answers3)
print(answers4)
print(correctAnswers)
nquestions=fileQuestions.split(",")
nanswer1=answers1.split(",")
nanswer2=answers2.split(",")
nanswer3=answers3.split(",")
nanswer4=answers4.split(",")
ncorrectAnswer=correctAnswers.split(",")
print("File loaded, save game data next time through 'save game' option")
savedFile.close
return nquestions,nanswer1,nanswer2,nanswer3,nanswer4,ncorrectAnswer,highscore
except:
print("No save files could be found, please try again another time when data has been saved from different sessions")
#list is defined
questions=["what is name","what is age","what is the time"]
answer1=["bob","15","12:00"]
answer2=["bobby","99","time to sleep"]
answer3=["Goofy","1","time to get a watch"]
answer4=["Theveenan","16","daytime"]
correctAnswer=["4","4","2"]
highscore=0
#main program
continuation="1"
print("KAHOOT \n \n \n")
while continuation=="1":
try:
print("Welcome to Kahoot! Main Menu")
selectMode=int(input("What would you like to do?\n Press 1 to create questions, \n Press 2 to edit questions, \n Press 3 to preview questions, \n Press 4 to play game, \n Press 5 for save file, \n Press 6 for load game, \n Or press any other key to power off"))
if selectMode==1:
create_question()
elif selectMode==2:
edit_question()
elif selectMode==3:
preview_questions()
elif selectMode==4:
highscore=play_game1(highscore)
elif selectMode==5:
save_game()
elif selectMode==6:
questions,answer1,answer2,answer3,answer4,correctAnswer,highscore=load_game()
else:
print("unvailable function")
except:
continuation=input("Are you sure you want to exit kahoot? press 1 for no, or any other key for yes")
print("Powering off...")
|
3871c0c930bb34de8731f55c632043e759fd11bc
|
Burlesco70/ManagerObjects
|
/ScaleZip.py
| 2,473 | 3.515625 | 4 |
'''
#####################################################################
TOPIC PYTHON OBJECT ORIENTED - ALL ACTION OBJECTS - MANAGERS - PART 3
#####################################################################
See how simple it is now to create a photo scaling class that takes advantage of the ZipProcessor functionality.
(Note: this class requires the third-party pillow library to get the PIL module.
You can install it with pip install pillow
Look how simple this class is!
All that work we did earlier paid off.
All we do is open each file (assuming that it is an image;
it will unceremoniously crash if a file cannot be opened), scale it, and save it back.
The ZipProcessor class takes care of the zipping and unzipping without any extra work on our part
'''
import sys
import shutil
import zipfile
from pathlib import Path
from PIL import Image
class ZipProcessor:
def __init__(self, filename):
self.filename = filename
# Define temp dir name
self.temp_directory = Path("unzipped-{}".format(filename))
# Delegator method
def process_zip(self):
self.unzip_files()
self.process_files()
self.zip_files()
def unzip_files(self):
# Create temp dir
try:
self.temp_directory.mkdir()
except FileExistsError:
print("WARNING: temp dir already present!")
with zipfile.ZipFile(self.filename) as zip:
zip.extractall(str(self.temp_directory))
def process_files(self):
pass
def zip_files(self):
with zipfile.ZipFile(self.filename, 'w') as file:
for filename in self.temp_directory.iterdir():
file.write(str(filename), filename.name)
# Delete temp dir
shutil.rmtree(str(self.temp_directory))
class ScaleZip(ZipProcessor):
def process_files(self):
'''Scale each image to 640x480'''
for filename in self.temp_directory.iterdir():
im = Image.open(str(filename))
scaled = im.resize((640, 480))
scaled.save(str(filename))
if __name__ == "__main__":
if len(sys.argv[1:]) == 1:
ScaleZip(*sys.argv[1:2]).process_zip()
print("ScaleZip.process_zip() executed with parameters: ",sys.argv[1:2])
else:
print("Please check the number of arguments")
print("Usage example:\npython ScaleZip.py immagini.zip")
|
2fca0ce5cb3ab56e298c866b0d1fe161a823703f
|
dhanendraverma/PythonL1Assignment
|
/Ques9.py
| 286 | 3.671875 | 4 |
#!/usr/bin/python
import os
directory = str(input("Enter the directory path: "))
for (path,dir,files) in os.walk(directory):
for file in files:
filename = os.path.join(directory, file)
size = os.path.getsize(filename)
if(size==0):
print(file)
|
8355791fc0ec1e7eebfa4fdfecc9e90d5ca2f84c
|
ornichola/learning-new
|
/pythontutor-ru/08_functions/03_capitalize.py
| 1,394 | 4.5625 | 5 |
"""
http://pythontutor.ru/lessons/functions/problems/capitalize/
Напишите функцию capitalize(), которая принимает слово из маленьких латинских букв и возвращает его же,
меняя первую букву на большую.
Например, print(capitalize('word')) должно печатать слово Word.
На вход подаётся строка, состоящая из слов, разделённых одним пробелом. Слова состоят из маленьких латинских букв.
Напечатайте исходную строку, сделав так, чтобы каждое слово начиналось с большой буквы.
При этом используйте вашу функцию capitalize().
Напомним, что в Питоне есть функция ord(), которая по символу возвращает его код в таблице ASCII, и функция chr(),
которая по коду символа возвращает сам символ. Например, ord('a') == 97, chr(97) == 'a'.
"""
def capitalize(word):
ascii_code = ord(word[0]) - 32
word_capitalized = chr(ascii_code) + word[1:]
return word_capitalized
words = input().split()
for word in words:
print(capitalize(word), end=' ')
|
fe3dbef91c1842b210ca033b532448374bb9171a
|
smile921/Ciss921
|
/code_py/old_snippets/brute_force_d20.py
| 616 | 3.59375 | 4 |
# Brute Force D20 Roll Simulator
# Import random module
import random
# Create a variable with a TRUE value
rolling = True
# while rolling is true
while rolling:
# create x, a random number between 0 and 99
x = random.randint(0, 99)
# create y, a random number between 0 and 99
y = random.randint(0, 99)
# if x is less than 2 and y is between 0 and 10
if x < 2 and 0 < y < 10:
# Print the outcome
print('You rolled a {0}{1}.'.format(x, y))
# And set roll of False
rolling = False
# Otherwise
else:
# Try again
print('Trying again.')
|
41550c2acf0c202925fbf8fb9b3523b5bce7fb2c
|
rue-glitch/PythonIntermediateWorkshopEmpty
|
/Person.py
| 1,167 | 4.4375 | 4 |
from datetime import date, datetime # for date
class Person:
"""
A person class
==== Attributes ====
firstname: str
lastname: str
birthdate: date YEAR, MONTH, DAY
address: str
"""
def __init__(self, firstname, lastname, birthdate, address):
"""
Initialize our class instance
@return:
"""
# self.firstname = ...
# self.lastname = ...
# self.birthdate = ...
# self.address = ...
pass
def __str__(self):
"""
Return the string in a human-readable manner, only print the
first and last name
@return: string
"""
pass
def age(self):
"""
Given the current date, return the age of this person
HINT: date.today() returns the date from today
:return: int age
"""
pass
def getInfo(self):
"""
Return the string "I am a person"
:return:
"""
return "I am a person"
if __name__ == '__main__':
# Example Build
# person = Person("Joane", "Do", date(1997, 4, 20), "50 st george str")
# print(person)
pass
|
1c05fd98d8d447c4d43401bc991bb941c9e34623
|
coolavy/nsf_2021
|
/Homework_Week3/problem2.py
| 567 | 4.3125 | 4 |
month = int(input("Enter the month as a number: "))
day = int(input("Enter the date: "))
if (month == 3 and day >= 20) or month in (4, 5) or (month == 6 and day < 20):
print("It is spring.")
elif (month == 6 and day >= 20) or month in (7, 8) or (month == 9 and day < 22):
print("It is summer")
elif (month == 9 and day >= 22) or month in (10, 11) or (month == 12 and day < 21):
print("It is fall.")
elif (month == 12 and day >= 21) or month in (1, 2) or (month == 3 and day < 20):
print("It is winter.")
else:
print("Invaild month and/or date. ")
|
67080fdc5e82649ea9f48dd94fe5aa5b331ee504
|
ahchin1996/Leecode
|
/21. Merge Two Sorted Lists.py
| 1,065 | 4 | 4 |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dum = ListNode(None)
prev = dum
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
if l1 == None:
prev.next = l2
elif l2 == None:
prev.next = l1
return dum.next
def main():
A = Solution()
l1 = None
l2 = ListNode(0)
# l1 = ListNode(1)
# l1.next = l1_2 = ListNode(2)
# l1_2.next = ListNode(4)
# l2 = ListNode(1)
# l2.next = l2_2 = ListNode(3)
# l2_2.next = ListNode(4)
ans = A.mergeTwoLists(l1,l2)
while ans:
print(ans.val)
ans = ans.next
main()
|
dea906bb68de3a5a9b2e2ea9c553b3b2f60d2b7f
|
Leejeongbeom/basic
|
/4-8.py
| 146 | 3.828125 | 4 |
phrase = input("문자열을 입력하시오:")
acronym = ""
for word in phrase.upper().split():
acronym += word[0]
print(acronym)
|
25fd0a90e1928817c6ef25c033fdfd3be79e7432
|
krishnajaV/luminarPythonpgm-
|
/oops/inheritance/Constructor.py
| 414 | 3.765625 | 4 |
class Person:
def __init__(self ,name,age):
self.name = name
self.age = age
print("name=", self.name)
print("age=", self.age)
class Student(Person):
def __init__(self,mark,rollno,name,age):
super().__init__(name,age)
self.mark = mark
self.rollno =rollno
print("mark=",self.mark)
print("rollno",self.rollno)
cr=Student(32,12,"anu",22)
|
540ca26c47e3fbe92ebf8bf2a395b6de1709fb90
|
felipechatalov/7-Segment-Display
|
/7SegmentDisplay.py
| 3,287 | 3.625 | 4 |
import pygame
window_w, window_h = 800, 600
white = (255, 255, 255)
red = (255, 0, 0)
screen = pygame.display.set_mode((window_w, window_h))
pygame.display.set_caption("Led Display")
clock = pygame.time.Clock()
# Segments which need to be activated to display the number, in order oif segments(a, b, c, d, e, f, g)
ledList = {
"0" : (1, 1, 1, 1, 1, 1, 0),
"1" : (0, 1, 1, 0, 0, 0, 0),
"2" : (1, 1, 0, 1, 1, 0, 1),
"3" : (1, 1, 1, 1, 0, 0, 1),
"4" : (0, 1, 1, 0, 0, 1, 1),
"5" : (1, 0, 1, 1, 0, 1, 1),
"6" : (1, 0, 1, 1, 1, 1, 1),
"7" : (1, 1, 1, 0, 0, 0, 0),
"8" : (1, 1, 1, 1, 1, 1, 1),
"9" : (1, 1, 1, 0, 0, 1, 1)
}
# reference point to draw each number (i think its the most top left pixel of the number)
referencePoint_0 = (100, 240)
referencePoint_1 = (330, 240)
referencePoint_2 = (560, 240)
def drawNumber(number, color, pos):
target = ledList[number]
if pos == 0:
cPoint = referencePoint_0
elif pos == 1:
cPoint = referencePoint_1
else:
cPoint = referencePoint_2
# draw each segment(7 in total)
if target[0] == 1:
drawRecth(cPoint[0]+30, cPoint[1], color) # a
if target[1] == 1:
drawRectv(cPoint[0]+90, cPoint[1]+30, color) # b
if target[2] == 1:
drawRectv(cPoint[0]+90, cPoint[1]+120, color) # e
if target[3] == 1:
drawRecth(cPoint[0]+30, cPoint[1]+180, color) # d
if target[4] == 1:
drawRectv(cPoint[0], cPoint[1]+120, color) # c
if target[5] == 1:
drawRectv(cPoint[0], cPoint[1]+30, color) # f
if target[6] == 1:
drawRecth(cPoint[0]+30, cPoint[1]+90, color) # g
# draw a vertical segment
def drawRectv(posx, posy, color):
pygame.draw.rect(screen, color, (posx, posy, 20, 50))
pygame.draw.line(screen, color, (posx+5, posy), (posx+10, posy-10), width=9)
pygame.draw.line(screen, color, (posx+15, posy), (posx+10, posy-10), width=9)
pygame.draw.rect(screen, color, (posx+8, posy-5, 5, 5))
pygame.draw.line(screen, color, (posx+5, posy+50), (posx+10, posy+60), width=9)
pygame.draw.line(screen, color, (posx+15, posy+50), (posx+10, posy+60), width=9)
pygame.draw.rect(screen, color, (posx+8, posy+50, 5, 5))
pygame.display.update()
#draw a horizontal segment
def drawRecth(posx, posy, color):
pygame.draw.rect(screen, color, (posx, posy, 50, 20))
pygame.draw.line(screen, color, (posx, posy+5), (posx-10, posy+10), width=9)
pygame.draw.line(screen, color, (posx, posy+15), (posx-10, posy+10), width=9)
pygame.draw.rect(screen, color, (posx-5, posy+8, 5, 5))
pygame.draw.line(screen, color, (posx+50, posy+5), (posx+60, posy+10), width=9)
pygame.draw.line(screen, color, (posx+50, posy+15), (posx+60, posy+10), width=9)
pygame.draw.rect(screen, color, (posx+50, posy+8, 5, 5))
pygame.display.update()
userInput = 369 # 3 digit number to show in screen
formated_user_input = ("{:03d}".format(userInput))
finished = False
while not finished:
for event in pygame.event.get():
if event.type == pygame.QUIT:
finished = True
for i in range(3):
info = str(formated_user_input[i])
drawNumber(info, white, i)
pygame.display.update()
clock.tick_busy_loop(20)
|
c5eb6a778353510cb34297e97dd33996904abb68
|
cbucholtz19/Project-Euler-Solutions
|
/Project_Euler/problem_12.py
| 550 | 3.6875 | 4 |
import math
def triangle(n):
return int(((n*n)/2) + (n/2))
def numFactors(n):
factors = 0
for i in range(1,math.floor(math.sqrt(n))):
if ( (n/i).is_integer() ):
factors += 2
if ((n/n).is_integer()):
factors += 1
return factors
def firstTriangleWithNFactors(n):
test = 3500
while(True):
print("Testing " + str(test))
r = numFactors(triangle(test))
print(r)
if (r >= n):
return triangle(test)
test += 1
print(firstTriangleWithNFactors(500))
|
f2fc5e5cb5e6476f777ae2a68179cb9c984fc84c
|
Mmerenz/mi_primer_proyecto
|
/test_imput.py
| 329 | 3.921875 | 4 |
mi_numero = 10
numero_del_usuario = int(input("Adivina un numero: "))
if mi_numero == numero_del_usuario:
print("Ganaste")
else:
print("Perdiste")
mi_numero = 10
numero_del_usuario = int(input("Adivina un numero: "))
if mi_numero == numero_del_usuario:
print("Ganaste")
else:
print("Perdiste")
|
f0d5cac9ad5eebeec6c230157ffbc17bb11be03c
|
zarana-nakrani/Softvan_Internship_Task
|
/Task2_Day7.py
| 3,033 | 3.828125 | 4 |
class Error(Exception):
pass
class LengthException(Error):
pass
class OneLowerCaseExceptiom(Error):
pass
class OneUpperCaseException(Error):
pass
class OneDigitException(Error):
pass
class OneSpecialCharError(Error):
pass
class LoginError(Error):
pass
class SignUp:
def __init__(self, fn, ln, un, pwd):
self.fn = fn
self.un = un
self.ln = ln
self.pwd = pwd
class SignIn:
def __init__(self, un, pwd):
self.un = un
self.pwd = pwd
def loginCheck(self, signup):
if self.un == signup.un and self.pwd == signup.pwd:
return True
else:
return False
class Main:
def __init__(self):
fn = input("Enter first name")
ln = input("Enter last name")
un = input("Enter Username for account")
lower = False
upper = False
digit = False
special = False
while True:
try:
pwd = input("Enter Password")
if len(pwd) <= 8 and len(pwd) >= 16:
raise LengthException
for i in pwd:
if i.islower():
lower = True
if lower == False:
raise OneLowerCaseExceptiom
for i in pwd:
if i.isupper():
upper = True
if upper == False:
raise OneUpperCaseException
for i in pwd:
if i.isdigit():
digit = True
if digit == False:
raise OneDigitException
for i in pwd:
if 33 <= ord(i) <= 64 or 91 <= ord(i) <=96 or 123 <= ord(i) <= 126:
special = True
if not special:
raise OneSpecialCharError
break
except LengthException:
print("Length of password must be greater than 8 & less than 16" + "\n")
except OneLowerCaseExceptiom:
print("There must be one lowercase character" + "\n")
except OneUpperCaseException:
print("There must be one upper case character, Try Again" + "\n")
except OneDigitException:
print("There must be one numeric character, try again" + "\n")
except OneSpecialCharError:
print("There must be one special character, try again" + "\n")
try:
signup = SignUp(fn, ln, un, pwd)
signinun = input("Enter username for sign in")
signinpwd = input("Enter password for signin")
signin = SignIn(signinun, signinpwd)
check = signin.loginCheck(signup)
if check:
print("Successfully signed in")
else:
raise LoginError
except LoginError:
print("Invalid Username or Password")
exit()
obj = Main()
|
31fc32b285b135240490bebaa41083799fc95156
|
zsbati/PycharmProjects
|
/Currency Converter2/Currency Converter/task/cconverter/cconverter.py
| 990 | 3.703125 | 4 |
# write your code here!
import json
import requests
user_currency = input().lower()
cache = dict() # to store the exchange rates
url = f'http://www.floatrates.com/daily/{user_currency}.json'
r = requests.get(url).json()
cache['usd'] = r.get('usd') # save the USD and EUR in the cache
cache['eur'] = r.get('eur')
while True:
target_currency = input().lower()
if target_currency == '':
break
amount_to_convert = float(input())
amount_to_return = 0
print('Checking the cache...')
if target_currency in cache:
print('Oh! It is in the cache!')
rate = cache[target_currency]['rate']
amount_to_return = round(rate * amount_to_convert, 2)
else:
print('Sorry, but it is not in the cache!')
cache[target_currency] = r.get(target_currency)
rate = r.get(target_currency)['rate']
amount_to_return = round(rate * amount_to_convert, 2)
print(f'You received {amount_to_return} {target_currency.upper()}.')
|
c6e636c09fbbd0d202465a930a9c7b63066e1f73
|
samarthsaxena/Python3-Practices
|
/Practices/advanced python/ItertoolsDemo.py
| 3,301 | 4.34375 | 4 |
# Advanced iteration functions in the itertools module
import itertools as iter
# https://docs.python.org/3/library/itertools.html
def testFunction(x):
return x < 40
def customeLogicForAccumulate(x, y):
"""
Custm logic function for accumulate
:param x: Number
:param y: Number
:return: x + y
"""
print(f'{x, "is not 0: ", x is not 0} and {y, "is not 0: ", y is not 0}')
if x and y != 0:
r = x + y
print(r)
return r
def main():
# TODO: Cycle iterator can be used to cycle over a collection
seq1 = ["Joe", "John", "Mike"]
cycle1 = iter.cycle(seq1)
print(f'It will keep looping endlessly whenever next() is called over a cycle1 which is a \'{type(cycle1)}\'')
print(next(cycle1)) # Joe
print(next(cycle1)) # John
print(next(cycle1)) # Mike
print(next(cycle1)) # Joe
print(next(cycle1)) # John
# TODO : use count to create a simple counter
count1 = iter.count(100.05, 11.65)
print(f'{type(count1)} is another way of loopin')
print(next(count1)) # 100.05
print(next(count1)) # 111.7
print(next(count1)) # 123.35000000000001 due to memory leaks
print(next(count1))
print(next(count1))
print(next(count1))
# TODO : accumulate creates an iterator that accumulates values
# vals = [i for i in range(10, 51, 10)]
vals = [10, 20, 31, 40, 50, 40, 30, 42]
acc = iter.accumulate(vals)
acc_max = iter.accumulate(vals, max)
print(f' By default accumulate generate the sum but we can change that.')
print(list(acc)) # [10, 30, 60, 100, 150, 190, 220]
print(f'Now if we follow func: (_T, _T) -> _T which is the 2nd args of accumulate() we can find min, max etc.. '
f'from the given sequence')
print(list(acc_max))
print(f'If you want to provide a custom implementation you\'d need to add a custom function that accepts 2 args.')
print(f'For example with customeLogicForAccumulate() ')
acc_customeLogicForAccumulate = iter.accumulate(vals, customeLogicForAccumulate)
print(list(acc_customeLogicForAccumulate))
# TODO : use chains to connect sequences together
chain_of_words_from_lists = iter.chain(seq1, vals)
chain_of_letters = iter.chain("AbcDFea", "123244345")
print(list(chain_of_words_from_lists)) # ['Joe', 'John', 'Mike', 10, 20, 30, 40, 50, 40, 30]
print(list(chain_of_letters)) # ['A', 'b', 'c', 'D', 'F', 'e', 'a', '1', '2', '3', '2', '4', '4', '3', '4', '5']
"""
List Flattening
----------------
You can quickly and easily flatten a list using itertools.chain.from_iterable from the itertools package. Here is a simple example:
a_list = [[1, 2], [3, 4], [5, 6]]
print(list(itertools.chain.from_iterable(a_list)))
# Output: [1, 2, 3, 4, 5, 6]
# or
print(list(itertools.chain(*a_list)))
# Output: [1, 2, 3, 4, 5, 6]
"""
# TODO : itertools provides 2 filtering functions which are dropwhile and takewhile
# these 2 keep on executing until a condition is met
print(f'Example for dropwhile and takewhile')
print("dropwhile: ", list(iter.dropwhile(testFunction, vals))) # dropwhile: [40, 50, 40, 30, 42]
print("takewhile: ", list(iter.takewhile(testFunction, vals))) # takewhile: [10, 20, 31]
if __name__ == '__main__':
main()
|
824edea190c392247a3e243007039c4dddc25959
|
mbaeumer/python-challenge
|
/block2-datatypes/date/test_age-calculator.py
| 879 | 3.859375 | 4 |
import unittest
import datetime
from age_calculator import calculate_age
class SumTestCase(unittest.TestCase):
def test_calculate_age_one_day_before(self):
birth_date = datetime.datetime.strptime("1981-07-23", "%Y-%m-%d")
today = datetime.datetime.strptime("2023-07-22", "%Y-%m-%d")
self.assertEqual(calculate_age(today, birth_date),41)
def test_calculate_age_equals(self):
birth_date = datetime.datetime.strptime("1981-07-22", "%Y-%m-%d")
today = datetime.datetime.strptime("2023-07-22", "%Y-%m-%d")
self.assertEqual(calculate_age(today, birth_date),42)
def test_calculate_age_already_had_birthday(self):
birth_date = datetime.datetime.strptime("1981-07-15", "%Y-%m-%d")
today = datetime.datetime.strptime("2023-07-22", "%Y-%m-%d")
self.assertEqual(calculate_age(today, birth_date),42)
if __name__ == '__main__':
unittest.main()
|
9d36f61604a99cdbf40d16476060f634d965058d
|
JuanPabllo/studynotes
|
/cursos/python/Estrutura-de-dados-em-python/numbers.py
| 1,855 | 4.125 | 4 |
import random
# Int
num1 = 300
num2 = -8
print(type(num1))
print(type(num2))
# Float
num3 = 300.5 # número positivo com uma casa decimal
num4 = -433.6750 # número negativo com quatro casas decimais
print(type(num3))
print(type(num4))
# Complex
num5 = 2 + 4j
num6 = 4j
num7 = -10j
print(type(num5))
print(type(num6))
print(type(num7))
# Número aleatório
# Gera um número inteiro aleatório entre 0 e 10
print(random.randint(0, 10))
# Conversões
num8 = 80 # Número do tipo int
num9 = -9.6 # Número do tipo float
print(type(float(num8))) # Convertendo de int para float
print(type(int(num9))) # Convertendo de float para int
print(type(complex(num8))) # Convertendo de int para complex
print(float(num8))
print(int(num9))
print(complex(num8))
# Operações aritméticas
# Operações com int.
print(10 + 9) # Soma de inteiros
print(9 - 8) # Subtração de inteiros
print(-9 * -9) # Multiplicação de inteiros
print(10 / 3) # Divisão de inteiros
print(10 // 3) # Parte inteira da divisão entre inteiros
print(10**2) # Exponenciação entre inteiros
print(10 % 2) # Resto da divisão entre inteiros
# Operações com float.
print("-----------------------------------")
print(10.5 + 8.2) # Soma com floats
print(-98.66 - 8.99) # Subtração com floats
print(27.5 * 3.7) # Multiplicação com floats
print(99.2 / 3.2) # Divisão com floats
print(99.2 // 3.2) # Parte inteira da divisão com floats
print(0.25**2) # Exponenciação com floats
print(5.0 % 2.5) # Resto da divisão com floats
# Operações com complex.
print("-----------------------------------")
print(3 + 4j + 3 + 4j) # Soma com complex
print(2 + 4j - 2 + 8j) # Subtração com complex
print(-2 + 9j * 16 + 90j) # Multiplicação com complex
print(2 + 10j / 2j) # Divisão com complex
print(25 + 2j ** 3 + 2j) # Exponenciação com complex
|
1b768af3c627cce6f03b03932327e86abc371906
|
Jakab90/challenges
|
/programming_101/unit_2/unit_2a_lesson.py
| 559 | 3.78125 | 4 |
# this is a basic solution using multiple inputs and variables
from typing import Sized
slithy_adj = input("Give an adjective")
gyre_noun = input("Give a noun")
gimble_noun = input("Give another noun")
mimzy_adj = input("Give another adjective")
borogoves_propernoun = input("Give a proper noun")
word_arr = [slithy_adj, gyre_noun, gimble_noun, mimzy_adj, borogoves_propernoun]
print(f"Twas brillig in the {slithy_adj} toves did {gyre_noun} and {gimble_noun} in the wabe; all {mimzy_adj} were the {borogoves_propernoun}, and the mome wraths out grabe." )
|
929dab46999f32402183f8b3f3b6847a216c6f62
|
Divisekara/Python-Codes-First-sem
|
/PA2/PA2 ANSWERS 2015/1/A1-1/2015 - PA2 - 19 - Weight of an object on a Planet.py
| 2,082 | 3.828125 | 4 |
#PA2 - 19 - Weight of an object on a Planet
def getText():
#To get text from input and check for any errors.
try:
fileOpen=open("FileIn.txt","r")
data=fileOpen.read().split()
fileOpen.close()
M=int(data.pop(0))
N=int(data.pop(0))
except ValueError:
print "Invalid Input!"
except IOError:
print "File Error!"
else:
names=[]
radii=[]
avg_dens=[]
if len(data)%3==0:
for i in range(len(data)/3):
names.append(data.pop(0))
try:
radii.append(int(data.pop(0)))
avg_dens.append(int(data.pop(0)))
except ValueError:
print "Invalid Input!"
new_data = []
if N==len(names) and N==len(radii) and N==len(avg_dens):
new_data.append(names)
new_data.append(radii)
new_data.append(avg_dens)
new_data.append(M)
new_data.append(N)
return new_data
def Calculate_Weight(x):
#To calculate the weight of an object on the given planets
N = x.pop(-1)
M = x.pop(-1)
names = x.pop(0)
radii = x.pop(0)
avg_dens = x.pop(0)
weight=[]
for i in range(N):
W=(6.67*(10**(-11)))*((4/3*3.14*(radii[i])**3)*avg_dens[i])*M/(radii[i])**2
weight.append(round(W,4))
return names[weight.index((max(weight)))]
def show(output):
#To print the output on screen as well as write to a file.
print output
try:
fileWrite=open("Result.txt","w")
fileWrite.write(output)
fileWrite.close()
except IOError:
print "File Error!"
run = getText() #To call functions in a global level
if run!=None:
show(Calculate_Weight(run))
|
6722d77c6958167e516686b036602a6f213bdcd6
|
avaiyang/Hadoop-HDFS-MapReduce
|
/mapper.py
| 1,228 | 4.03125 | 4 |
import sys
import re
def read_input(file):
for line in file:
# here we need to remove all the special characters from the file
#for the purpose of which I am using a regular expression
line = re.sub('[^A-Za-z0-9]+', ' ', line)
# split the line into words
yield line.split()
def main(separator='\t'):
# input comes from STDIN (standard input)
data = read_input(sys.stdin)
for words in data:
# write the results to STDOUT (standard output);
# what we output here will be the input for the
# Reduce step, i.e. the input for reducer.py
#
# tab-delimited; the trivial word count is 1
# we need to check whether the line contains only 1 word or more
#if the line contains only single word, treat it as pair
if len(words)==1:
a = words
for word in a:
print '%s%s%d' % (word,separator, 1)
else:
#if the line contains more than 1 words
a = zip(words, words[1:])
for word in a:
print '%s %s%s%d' % (word[0],word[1],separator, 1)
if __name__ == "__main__":
main()
|
40cb691913b6f646e004e3d88566959279dccb91
|
bamshad-shrm/codingPractice
|
/py/class/a.py
| 350 | 3.71875 | 4 |
# Note: if we use import bamshadMath we will face with the error of: TypeError: 'module' object is not callable
from bamshadMath import bamshadMath
x = int(input("Enter an integer: "))
y = int(input("Enter another integer: "))
bamshadMathObj = bamshadMath()
print('The sum of ', x, ' and ', y, ' is ', bamshadMathObj.sumFnc(x,y), '.', sep='')
|
eec0dc7ce99ba1495f5304316a3e8e0624f3756a
|
Giocatory/PythonOOP
|
/decorator/first decorator.py
| 730 | 3.6875 | 4 |
def show_func(func):
def inner():
print('Start decorator')
func()
print('Stop decorator')
return inner
@show_func # say = show_func(say)
def say():
print('Hello World')
say()
# Start decorator
# Hello World
# Stop decorator
def show_func2(func):
def inner(*args, **kwargs):
print('Start decorator')
func(*args, **kwargs)
print('Stop decorator')
return inner
@show_func2 # say = show_func2(say)
def say(first_name, last_name):
print(f'Hello {first_name} {last_name}')
print()
name = input('Enter name: ')
last = input('Last name: ')
say(name, last)
# Enter name: Mikhail
# Last name: Derkunov
# Start decorator
# Hello Mikhail Derkunov
# Stop decorator
|
09259aad7d1224c2ac7cb83e4c3ddb47cbd72cf9
|
aulb/ToAsk
|
/Technical Questions/092 - Reverse Between LL.py
| 487 | 3.6875 | 4 |
def reverseBetween(head, m, n):
x, y = min(m, n), max(m, n)
d = y - x
i = 0
current = head
# Find starting point
for i in range(1, x):
prev = current
current = current.next
last = prev
i = 0
# From the starting point just reverse the .next to like the previous one
for i in range(d + 1):
prev, current.next = current.next, prev
prev, current = current, prev
# Once I'm at the end starting is equal to the
last.next = current
return head
|
eb8818ff53904609d14825be9c5aa833bc789328
|
madease/Ciao-World
|
/Week 4/AGENTORANGE.py
| 1,237 | 3.703125 | 4 |
from turtle import Turtle
import random
t = Turtle()
t.screen.bgcolor('black')
#t.color('orange')
t.fd(100)
def generateText(txt, font, color):
t.color(randomColor)
xpos = random.randint(-500,500)
ypos = random.randint(-500,400)
t.setpos(xpos, ypos)
t.write(txt,move=True,align="center",font=(font,30,"normal"))
#In order for fonts to vary randomly, they must be installed in your font folder. See attached font files to download.
#
thingsToSay = ["AGENT ORANGE", "FUCK TRUMP", "WHAT HAVE WE DONE?", "FUCK DONALD TRUMP", "YOUR TIME WILL COME", "BLACK LIVES MATTER", "RESIST", "DEPLORABLE", "FUCK THE PRESIDENT", "SHAME!", "LITERALLY THE WORST", "BLOTUS", "YOURE FIRED", "IMPEACH THE PRESIDENT", "AMERICANHORRORSTORY", "TAKE A KNEE"]
colors = ["red", "orange", "green", "purple", "blue", "white", "yellow", "black", "magenta", "violet"]
fonts = ["Helvetica Bold", "Patriot", "Dancing on the Beach", "galderglynn", "Heavitas", "DELUSION", "AbandoN", "Cooper Black", "Gobold", "Friends", "Summer of Love", "Amateur Slash", "Wilmina", "Costa Rica", ]
while True:
randomString = random.choice(thingsToSay)
randomColor = random.choice(colors)
randomFont = random.choice(fonts)
generateText(randomString, randomFont, randomColor)
|
a3262289a989b0622b427e05cd27cd0aa5028f48
|
minahabibm/Data-Structures-Algorithms
|
/Data Structures/Hash Tables/main.py
| 4,913 | 3.90625 | 4 |
'''Collision resolution techniques:
Separate chaining (open hashing)
Linear probing (open addressing or closed hashing)
*Quadratic Probing
Double hashing
'''
class HashTable:
def __init__(self, size):
self.size = size# int(input("Enter the Size of the hash table : "))
self.table = list(0 for i in range(self.size))
self.elementCount = 0
self.comparisons = 0
def isFull(self):
if self.elementCount == self.size:
return True
else:
return False
# method that returns position for a given element
# replace with your own hash function
def hashFunction(self, element):
return element % self.size
# method to resolve collision by quadratic probing method
def quadraticProbing(self, element, position):
posFound = False
# limit variable is used to restrict the function from going into infinite loop
# limit is useful when the table is 80% full
limit = 50
i = 1
# start a loop to find the position
while i <= limit:
# calculate new position by quadratic probing
newPosition = position + (i**2)
newPosition = newPosition % self.size
# if newPosition is empty then break out of loop and return new Position
if self.table[newPosition] == 0:
posFound = True
break
else:
# as the position is not empty increase i
i += 1
return posFound, newPosition
# method that inserts element inside the hash table
def insert(self, element):
# checking if the table is full
if self.isFull():
print("Hash Table Full")
return False
isStored = False
position = self.hashFunction(element)
# checking if the position is empty
if self.table[position] == 0:
# empty position found , store the element and print the message
self.table[position] = element
print("Element " + str(element) + " at position " + str(position))
isStored = True
self.elementCount += 1
# collision occured hence we do linear probing
else:
print("Collision has occured for element " + str(element) + " at position " + str(position) + " finding new Position.")
isStored, position = self.quadraticProbing(element, position)
if isStored:
self.table[position] = element
self.elementCount += 1
return isStored
# method that searches for an element in the table
# returns position of element if found
# else returns False
def search(self, element):
found = False
position = self.hashFunction(element)
self.comparisons += 1
if(self.table[position] == element):
return position
# if element is not found at position returned hash function
# then we search element using quadratic probing
else:
limit = 50
i = 1
newPosition = position
# start a loop to find the position
while i <= limit:
# calculate new position by quadratic probing
newPosition = position + (i**2)
newPosition = newPosition % self.size
self.comparisons += 1
# if element at newPosition is equal to the required element
if self.table[newPosition] == element:
found = True
break
elif self.table[newPosition] == 0:
found = False
break
else:
# as the position is not empty increase i
i += 1
if found:
return newPosition
else:
print("Element not Found")
return found
# method to remove an element from the table
def remove(self, element):
position = self.search(element)
if position is not False and position is not None:
self.table[position] = 0
print("Element " + str(element) + " is Deleted")
self.elementCount -= 1
else:
print("Element is not present in the Hash Table")
return
# method to display the hash table
def display(self):
print("\n")
for i in range(self.size):
print(str(i) + " = " + str(self.table[i]))
print("The number of element is the Table are : " + str(self.elementCount))
if __name__=='__main__':
print("Quadratic Probing Hash Table")
hashTable = HashTable(15)
dicPair = [12, 26, 31, 17, 90, 28, 88, 40, 77, 99];
for i in dicPair:
hashTable.insert(i)
hashTable.display()
print("The position of element 31 is : " + str(hashTable.search(31)))
print("The position of element 28 is : " + str(hashTable.search(28)))
print("The position of element 90 is : " + str(hashTable.search(90)))
print("The position of element 77 is : " + str(hashTable.search(77)))
print("The position of element 1 is : " + str(hashTable.search(1)))
print("\nTotal number of comaprisons done for searching = " + str(hashTable.comparisons))
print()
hashTable.remove(90)
hashTable.remove(12)
hashTable.display()
|
6b1968cd00bec5b2a944c0f2e1a05bad3df6085c
|
suvrajitkarmaker/python
|
/data structure/stack.py
| 949 | 3.875 | 4 |
class Stack:
def __init__(self):
self.stack = []
self.top = 0
self.stackSize = 1000000
def push(self, value):
if(self.stackSize == self.top):
print("Stack is full")
else:
self.stack.append(value)
self.top = self.top + 1
def pop(self):
value = None
if(self.top == 0):
print("Stack is empty")
else:
self.top = self.top - 1
value = self.stack.pop()
return value
def display(self):
if(self.top == 0):
print("Stack is empty")
else:
i=self.top -1
while(i>=0):
print(self.stack[i], end=' ')
i-=1
print()
st = Stack()
st.push(50)
st.push(78)
st.push(15)
st.push(89)
st.display()
print(st.pop())
st.display()
st.push(59)
st.push(73)
st.display()
print(st.pop())
st.display()
|
ac67dc14fa60ec3fc7b82c3c58dc66a8630493fb
|
vegeta008/FundamentosP
|
/Ejercicio1.py
| 552 | 4.03125 | 4 |
#1.Calcular el valor a pagar de una compra realizada, cuyo monto neto es ingresado por el usuario. Considere que el valor del IVA
#(Impuesto al Valor Agregado- puede variar en cada país), y un descuento del 5% para todas las compras.
# -*- coding: utf-8 -*-
"""
@author: [email protected]
"""
Valor_Compra = int(input("Ingrese Valor:"))
descuento = Valor_Compra * 0.05
IVA = Valor_Compra * 0.19
print ("Valor Total Con IVA: ", Valor_Compra + IVA)
print ("Descuento: ", descuento )
print ("Valor a Pagar :", Valor_Compra - descuento + IVA)
|
4aebef57aff30af6fae636882f5102c81d704a5f
|
fbokovikov/leetcode
|
/solutions/longset_palyndrom.py
| 1,072 | 3.765625 | 4 |
class Solution:
def longestPalindrome(self, s: str) -> str:
max_length, length = 0, len(s)
start_pos, end_pos = 0, 0
for cur_pos in range(length):
len1 = self.expandAroundCenter(s, cur_pos, cur_pos)
len2 = self.expandAroundCenter(s, cur_pos, cur_pos + 1)
cur_length = max(len1, len2)
if cur_length > max_length:
max_length = cur_length
start_pos = cur_pos - (cur_length - 1) // 2
end_pos = cur_pos + cur_length // 2
return s[start_pos:end_pos + 1]
def expandAroundCenter(self, s: str, left: int, right: int) -> int:
length, res = len(s), 0
res = 0
while left >= 0 and right < length and s[left] == s[right]:
left -= 1
right += 1
res += 1
return right - left - 1
def main():
s = input("Input string: ")
solution = Solution()
palindrome = solution.longestPalindrome(s)
print("longest palindrome:", palindrome)
if __name__ == '__main__':
main()
|
d25a4324863b8da5d210b3e655fe9bae072a77a4
|
guilhermeleobas/maratona
|
/leetcode/14.py
| 425 | 3.546875 | 4 |
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
sol = ""
j = 0
word = strs[0]
for i in range(0, len(word)):
for j in range(1, len(strs)):
other = strs[j]
if i >= len(other):
return sol
if word[i] != other[i]:
return sol
sol += word[i]
return sol
|
a3ceed91cd041af6743133cd050e11229d7fbc26
|
deasymaharani/Grok-Learning
|
/C7-ITERATION/while loop.py
| 456 | 4.09375 | 4 |
def mul_table(num,N):
n=0
while n<N:
result = (n+1)*num
print_result = str(n+1) + " * " + str(num)+ " = "+ str(result)
n = n+1
print(print_result)
num=input("Enter the number for 'num': ")
N=input("Enter the number for 'N': ")
if not num.isdigit() or not N.isdigit() or int(num) < 0 or int(N) < 0 or int(num)==0:
print("Invalid input")
else:
num = int(num)
N = int(N)
mul_table(num,N)
|
f0fa038818368170069ddc6f7d88753a4d422efb
|
Neeraj-kaushik/Geeksforgeeks
|
/Array/Find_Triplet_With_Zer_Sum.py
| 322 | 3.65625 | 4 |
def find_triplet(li, n):
count = 0
for i in range(len(li)-2):
for j in range(i+1, len(li)-1):
for k in range(j+1, len(li)):
if li[i]+li[j]+li[k] == 0:
count += 1
print(count)
n = int(input())
li = [int(x) for x in input().split()]
find_triplet(li, n)
|
1ad46942d6c22cd688dc53237ecb559b814e3309
|
edu-athensoft/stem1401python_student
|
/py200325_python1/py200529/stem1401_python_homework_quiz10_Kevin.py
| 1,394 | 4.21875 | 4 |
"""
Quiz 10 and homework
"""
# Question 3. A class of student just look a midterm exam on French course.
# Please figure out the average of this class. And how many students got A.
# s is score, and s is student
s_s = [
("Marie", 85),
("Phoebe", 78),
("Sabrina", 96),
("Emma", 85),
("Amy", 73),
("Isabelle", 59),
("Clark", 45),
]
# name = ["Marie", "Phoebe", "Sabrina", "Emma", "Amy", "Isabelle", "Clark"]
# score = [85, 78, 96, 85, 73, 59, 45]
score_total = s_s[0][1] + s_s[1][1] + s_s[2][1] + s_s[3][1] + s_s[4][1] + s_s[5][1] + s_s[6][1]
average_score = score_total / len(s_s)
# print(score_total)
print("The average score is {:.2f}".format(average_score))
# how many people get A
number = 0
for score in s_s:
if score[1] >= 90:
number = number + 1
print("{} students got an A.".format(number))
"""
3.Python Program to Display the 9X9 multiplication Table
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
"""
for i1 in range(1, 10):
for i2 in range(1, i1 + 1):
print("{} x {} = {}".format(i1, i2, i1 * i2), end="\t")
print()
|
8e31bd87be6a78e4a13eb30b53563e0f28d2b38d
|
jmfrank63/text-catalog
|
/model.py
| 2,561 | 3.796875 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
The database model
'''
from app import db
class Language(db.Model):
'''
This table stores the language name
'''
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, unique=True, nullable=False)
def __init__(self, name):
'''
Init the language class with a name
'''
self.name = name
def __unicode__(self):
'''
Print a nice representation of the language object
'''
return "Language(Id={}, name={})".format(self.id, self.name)
class User(db.Model):
'''
This table stores the user information
username and email
'''
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, nullable=False)
email = db.Column(db.String, unique=True, nullable=False)
def __init__(self, username, email):
'''
Init the User with a username and an email address
'''
self.username = username
self.email = email
def __unicode__(self):
'''
Print a nice representaio of the the user object
'''
return "User(Id={}, username={}, email={})".format(self.id,
self.username,
self.email)
class Sentence(db.Model):
'''
This table stores the sentence information
'''
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.String, nullable=False)
translation = db.Column(db.String, nullable=False)
language_id = db.Column(db.Integer, db.ForeignKey('language.id'))
language = db.relationship('Language',
backref=db.backref('sentences', lazy='dynamic'))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
user = db.relationship('User',
backref=db.backref('sentences', lazy='dynamic'))
def __init__(self, text, translation, language, user):
'''
Init the sentence with text, translation, language and user
'''
self.text = text
self.translation = translation
self.language = language
self.user = user
def __unicode__(self):
'''
Print a nice representation of the Sentence object
'''
return "Sentence(Id={}, text={}, translation={}, language={},user={})"\
.format(self.id,
self.text,
self.translation,
self.language,
self.user)
|
703e7ae67d44db0314ce45c4d7c4ad605870351c
|
clumsy-k/memorandom_python
|
/function_zip.py
| 296 | 3.6875 | 4 |
#! /usr/bin/env python
# encoding:utf-8
# 要素10のlistを2つ作成
List1 = []
List2 = []
for i in xrange(10):
List1.append(i)
List2.append(i)
List2.reverse()
Last_list = []
for (a, b) in zip(List1, List2):
print a, b
elm = a + b
Last_list.append(elm)
print Last_list
|
4a94782b19e24504297ea7aef2749f52cedcf721
|
dxmahata/codinginterviews
|
/leetcode/3Sum.py
| 1,533 | 3.671875 | 4 |
"""Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
URL: https://leetcode.com/problems/3sum/
"""
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 0 or len(nums) == 2 or len(nums) == 1:
return []
else:
sum_zero_list = []
sorted_nums = sorted(nums)
for i in range(0, len(nums) - 2):
start = i + 1
end = len(nums) - 1
while start < end:
curr_sum = sorted_nums[i] + sorted_nums[start] + sorted_nums[end]
if curr_sum == 0:
zero_triplet = (sorted_nums[i], sorted_nums[start], sorted_nums[end])
sum_zero_list.append(zero_triplet)
start += 1
end -= 1
elif curr_sum < 0:
start += 1
elif curr_sum > 0:
end -= 1
return [list(entries) for entries in set(sum_zero_list)]
if __name__ == "__main__":
soln = Solution()
print(soln.threeSum([-1, 0, 1, 2, -1, -4]))
|
7ad26bd897c8627fc8fb22e4f82144f947b97fa7
|
anasssaghir/mundiapolis-math
|
/math/0x01-plotting/6-bars.py
| 546 | 3.65625 | 4 |
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5)
fruit = np.random.randint(0, 20, (4, 3))
names = ['Farrah', 'Fred', 'Felicia']
fs = ['apples', 'bananas', 'oranges', 'peaches']
colors = ['red', 'yellow', '#ff8000', '#ffe5b4']
for i in range(len(fruit)):
plt.bar(names, fruit[i], bottom=np.sum(fruit[:i], axis=0),
color=colors[i], label=fs[i], width=0.5)
plt.title("Number of Fruit per Person")
plt.ylabel("Quantity of Fruit")
plt.yticks(np.arange(0, 90, 10))
plt.legend()
plt.show()
|
f9d66fd14799109c00a92a392aa5c42ea8d341b5
|
daniel-reich/turbo-robot
|
/tfbKAYwHq2ot2FK3i_21.py
| 734 | 4.1875 | 4 |
"""
Let's define a non-repeating integer as one whose digits are all distinct.
97653 is non-repeating while 97252 is not (it has two 2's). Among the binary
numbers, there are only two positive non-repeating integers: 1 and 10. Ternary
(base 3) has ten: 1, 2, 10, 20, 12, 21, 102, 201, 120, 210.
Write a function that has as it's argument the base or radix and returns the
number of non-repeating positive integers in that base.
### Examples
non_repeats(2) ➞ 2
non_repeats(4) ➞ 48
non_repeats(5) ➞ 260
non_repeats(6) ➞ 1630
### Notes
Assume a radix of 1 is not legitimate.
"""
from math import factorial as f
def non_repeats(r):
return sum(f(r -1)//f(i) for i in range(r))*(r -1)
|
22e896c8f47fd3edd568ac59d276b52493bad8e8
|
payamgerami/algorithm-and-data-structure
|
/src/lists/Numeric Palindromes.py
| 687 | 4.15625 | 4 |
# A palindrome is a word or a phrase or a number, that when reversed, stays the same.
# For example, the following sequences are palindromes : "azobi4amma4iboza" or "anna".
# But this time, we are not interested in words but numbers. A "number palindrome" is a number, that taken backwards, remains the same.
# For example, the numbers 1, 4224, 9999, 1221 are number palindromes.
# Implement a function, which given an integer computes if it's a palindrome.
def is_numeric_palindrome(n):
digits = []
i=0
while n>0:
digits.append(n%10)
i+=1
n=n//10
i-=1
j=0
while j<i:
if digits[i]!=digits[j]:
return False
j+=1
i-=1
return True
print is_numeric_palindrome(100001)
|
eaffa32155cd678cc74e4a2ce02d7b667908a50c
|
aseeth/first_repo
|
/palindrom.py
| 274 | 3.78125 | 4 |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
n = int(input("enter any num:"))
m = n
rev = 0
while n>0:
dig = n%10
rev = rev *10+dig
n = n//10
if m == rev:
print("this is the palindrom")
else:
print("not a palindrom")
|
b7ccb2dc2eeebdd4219d89ab3a6832780add3dd0
|
asharilabs/PelatihanKemenpora
|
/harikedua.py
| 239 | 3.640625 | 4 |
# bilangan = input('input bilangan: ')
# for i in range(int(bilangan) + 1):
# if i != 0:
# print('Hitung %d' %i)
# x = 3
# y = 3
# a = [1,2,3]
# b = [1,2,3]
# print( x is y)
# print(x is x)
# print([1,2,3] == [1,2,3])
# print ('123 ->' + (a is b))
lst = [1,2,3,4,5,['a','b','c','d']]
for x in lst:
if isinstance(x, list):
for y in x:
print(y)
else:
print (x)
|
3a343b95f80f846efe74573fda6784b7400ccbcd
|
Environmental-Informatics/building-more-complex-programs-with-python-SteveTsui1361
|
/xu1361_program_4.2.py
| 1,006 | 4.375 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 31 14:11:38 2020
This code is used to draw flowers as mentioned in the Exercise(Think Python)
@author: xu1361
"""
# import necessary modules
import turtle
import math
bob = turtle.Turtle()
# draw the circles
def arc(t, r, angle):
arc_length = 2 * math.pi * r * angle / 360
n = int(arc_length / 3) + 1
step_length = arc_length / n
step_angle = angle / n
for i in range(n):
t.fd(step_length)
t.lt(step_angle)
# draw flowers
def petal(t, r, angle):
for i in range(2):
arc(t, r, angle)
t.lt(180 - angle)
# draw flower
def flower(t, r, n, angle):
for i in range(n):
petal(t, r, angle)
t.lt(360.0 / n)
# move flower
def move(t, length):
t.pu()
t.fd(length)
t.pd()
# draw three flowers
move(bob, -100)
flower(bob, 60, 7, 60)
move(bob, 100)
flower(bob, 40, 10, 80)
move(bob, 100)
flower(bob, 150, 20, 20)
turtle.mainloop()
|
b5a991801e8e8828449e83be5c6b1af44aca457b
|
rodyns2001/crimtech-comp-f21
|
/python/random_ints.py
| 458 | 3.53125 | 4 |
import random
def random_ints():
# Write your code here!
l = []
return l
def test():
N = 10000
total_length = 0
for i in range(N):
l = random_ints()
assert not 0 in l
assert not 11 in l
assert l[-1] == 7
total_length += len(l)
assert abs(total_length / N - 10) < 1 # checks that the length of the random strings are reasonable.
print("Success!")
if __name__ == "__main__":
test()
|
1b9a85d530d1ea3abb650e8877a44870608256b7
|
RenanRibeiroDaSilva/Meu-Aprendizado-Python
|
/Exercicios/Ex011.py
| 699 | 4 | 4 |
"""Ex 011 - Faça um programa que leia a largura e a altura de uma parede em metros, calcule sua área
e a quantidade de tinta necessaria para pinta-la, sabendo que cada litro de tinta pinta uma área de
2m²."""
print('-' * 10, '>Ex 011,', '-' * 10)
#Criando variaveis e recebendo dados.
par_alt = float(input('Qual a altura da parede: '))
par_lar = float(input('Qual a largura da parede: '))
#Processando dados.
area = par_alt * par_lar
tin = area / 2
#Imprimindo dados na tela para o usuário.
print('Sua parede tem a dimensão de {:.2f}X{:.2f} e sua área é de {:.2f}m².'.format(par_alt, par_lar, area))
print('Para pintar essa parede, voçê precisará de {:.2f}l de tinta.'.format(tin))
|
daf3a11b90138b689481a2ed9a9b7dc9219fe7d5
|
rafaelperazzo/programacao-web
|
/moodledata/vpl_data/197/usersdata/274/78744/submittedfiles/atividade.py
| 242 | 3.75 | 4 |
# -*- coding: utf-8 -*-
import math
n = int(input("Digete n: "))
i = 1
while i<n:
x = float(input("Digite x: "))
y = float(input("digite y: "))
if x>0 and y>0 and (x*x+x*y) <=1 :
print("SIM")
else:
print("NAO")
|
538693ff27cf980a4efa15e766ffae9ca1a89d4d
|
nikesh610/Guvi_Codes
|
/Beginner_Set2_3.py
| 101 | 3.78125 | 4 |
vow=['a','e','i','o','u']
x=input()
if(vow.count(x)==1):
print("Vowel")
else:
print("Consonant")
|
85a64f86e39d2b3608dec78588a7b8ea06d39b53
|
vishruth-v/Social-Network-
|
/Graph.py
| 6,867 | 3.765625 | 4 |
class Graph:
def __init__(self, nodes, names):
self.adjlist = [[] for i in range(nodes)]
self.indexes = {i:j for i,j in zip(names, range(nodes))}
self.V = nodes #V is th number of nodes present in the graph
self.cycle = []
def disp_adjlist(self):
print(self.adjlist)
def disp_indexes(self):
print(self.indexes)
def display(self):
print(self.adjlist)
print(self.indexes)
print(self.V)
def isValid(self, node):
if node in self.indexes:
return 1
else:
return 0
def connect(self, node1, node2):
if self.isValid(node1) and self.isValid(node2):
if node2 not in self.adjlist[self.indexes[node1]]:
self.adjlist[self.indexes[node1]].append(node2)
self.adjlist[self.indexes[node2]].append(node1)
else:
print("Invalid connection")
'''def addmult(self, n):
for _ in range(n):
self.indexes.update({chr(len(self.adjlist)+65): len(self.adjlist)})
self.adjlist.append([])'''
def add(self, name):
self.indexes.update({name: len(self.adjlist)})
self.adjlist.append([])
self.V += 1
def delete(self,node):
index = self.indexes[node]
self.indexes.pop(node)
for i in self.adjlist[index]:
self.adjlist[self.indexes[i]].remove(node)
self.adjlist.pop(index)
for x in self.indexes:
if self.indexes[x] > index:
self.indexes[x] -= 1
self.V -= 1
'''
# A recursive function that uses visited[] and parent to detect
# cycle in subgraph reachable from vertex v
def isCyclicUtil(self,start_node,visited,parent):
startcycle = None
l = []
#Mark the current node as visited
visited[start_node]= True
#Recur for all the vertices adjacent to this vertex (adjacency list of that vertex)
for node in self.adjlist[self.indexes[start_node]]:
# If the node is not visited then recurse on it
if visited[node]==False :
if(self.isCyclicUtil(node,visited,start_node)[0]) and start_node != startcycle:
return True,l.append(start_node)
elif(self.isCyclicUtil(node,visited,start_node)[0]) and start_node == startcycle:
return True,l
# If an adjacent vertex is visited and not parent of current vertex,
# then there is a cycle
elif (visited[node]==True and parent != node):
startcycle = node
l = [start_node]
return True, l
return False,l
#Returns true if the graph contains a cycle, else false.
def isCyclic(self):
# Mark all the vertices as not visited
#visited =[False]*(self.V)
visited = {name : False for name in self.indexes}
# Call the recursive helper function to detect cycle in different
#DFS trees
for node in self.indexes:
if visited[node] == False: #Don't recur for u if it is already visited
#b, l = self.isCyclicUtil(node,visited,-1)
#if b == True:
if(self.isCyclicUtil(node,visited,-1))[0] == True: #initial parent node = -1
print(l)
return True,l
return False,l
'''
# A recursive function that uses visited[] and parent to detect
# cycle in subgraph reachable from vertex v.
def isCyclicUtil(self,start_node,visited,parent):
#Mark the current node as visited
visited[start_node]= True
#Recur for all the vertices adjacent to this vertex
for node in self.adjlist[self.indexes[start_node]]:
# If the node is not visited then recurse on it
#self.cycle.append(start_node)
if visited[node]==False:
if(self.isCyclicUtil(node,visited,start_node)[0]):
self.cycle.append(start_node)
return True, self.cycle
# If an adjacent vertex is visited and not parent of current vertex,
# then there is a cycle
elif parent!=node:
self.cycle.append(start_node)
return True, self.cycle
if self.cycle:
self.cycle.pop()
return False, self.cycle
#Returns true if the graph contains a cycle, else false.
def isCyclic(self):
# Mark all the vertices as not visited
visited = {name : False for name in self.indexes}
# Call the recursive helper function to detect cycle in different
#DFS trees
for node in self.indexes:
if visited[node] ==False: #Don't recur for u if it is already visited
b, self.cycle = self.isCyclicUtil(node,visited,-1)
if b == True:
return True
return False, self.cycle
def popularity(self):
name_index = {v: k for k, v in self.indexes.items()}
popu_dict = {name_index[i]: len(self.adjlist[i]) for i in range(len(self.adjlist))}
return sorted(list(popu_dict.items()), key=lambda x: x[1], reverse=True)
# Suggests top friends
def suggested(self, name):
node = self.indexes[name]
children = [self.indexes[n] for n in self.adjlist[node]]
con = {}
for child in children:
grandchildren = self.adjlist[child]
# List of names
for gc in grandchildren:
if self.indexes[gc] in children or gc == name:
continue
# If connection exists
if gc in con.keys():
con[gc] += 1
# Initialise to 1
else:
con[gc] = 1
con = sorted(list(con.items()), key=lambda x:x[1], reverse=True)
return con
'''if __name__ == '__main__':
#Testing of the class for add delete
g1 = Graph(2, ['Vish', 'Vibhz'])
g1.display()
g1.connect('Vish', 'Vibhz')
g1.display()
g1.add('Cool')
g1.display()
g1.delete('Vibhz')
g1.display()
g1.add('Bruh')
g1.display()'''
if __name__ == '__main__':
g1 = Graph(5, ['A', 'B', 'C', 'D', 'E'])
#g1.display()
g1.connect('E', 'D')
g1.connect('D', 'A')
g1.connect('A', 'B')
g1.connect('B', 'C')
g1.connect('C', 'D')
g1.display()
print(g1.cycle)
print(g1.isCyclic())
|
9ff630b1b3e042fc3cf17c7d24793bc0e4b35310
|
alberto-re/aoc2020
|
/day04.py
| 1,612 | 3.59375 | 4 |
#!/usr/bin/env python3
# --- Day 4: Passport Processing ---
import re
def extract_passports(lines):
passports = [{}]
for line in lines:
if line:
for field in line.split():
key, value = field.split(":")
passports[-1][key] = value
else:
passports.append({})
return passports
def required_fields(passport, fields={"byr", "pid", "hcl", "hgt", "ecl", "eyr", "iyr"}):
return fields.issubset(set(passport.keys()))
def valid_fields(passport):
if not 1920 <= int(passport["byr"]) <= 2002:
return False
if not 2010 <= int(passport["iyr"]) <= 2020:
return False
if not 2020 <= int(passport["eyr"]) <= 2030:
return False
matches = re.match("(\d+)(cm|in)", passport["hgt"])
if not matches:
return False
qty = int(matches.group(1))
unit = matches.group(2)
if unit == "cm" and not 150 <= qty <= 193:
return False
if unit == "in" and not 59 <= qty <= 76:
return False
if not re.match("#[0-9a-f]{6}", passport["hcl"]):
return False
if not passport["ecl"] in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]:
return False
if len(passport["pid"]) != 9 or not passport["pid"].isdigit():
return False
return True
lines = []
with open("input/day4.txt") as f:
lines = [line.rstrip() for line in f]
passports = extract_passports(lines)
print("part1 solution:", sum(map(required_fields, passports)))
print(
"part2 solution:",
sum(map(lambda x: required_fields(x) and valid_fields(x), passports)),
)
|
66fdd352325fc33d2b03f6521d05c54e7a8da197
|
Georgieboy68/ICTPRG-Python
|
/addingnonx.py
| 305 | 4.21875 | 4 |
#Write a program that keeps asking the user for a number, and adds it to a total.
# Ensure that pressing x stops entering numbers.
# Example:
firstnum=input("Enter Number: ")
sum=0
while firstnum != "x":
sum=sum+int(firstnum)
firstnum=input("Enter Number: ")
print("Total: ",sum)
|
99a8b7c9e169c55220549c3b0ff8be49ef8b0108
|
b0sst0p/DinhTienHoang-Dataforeveryone-D12
|
/Session3/menu.py
| 1,401 | 3.609375 | 4 |
name ='trung ran'
name1 = 'bap'
name2 = "bo"
name3 = 'mo'
name4 = 'mam tom'
name10= 'ca ran'
#list, array: dữ liệu kiểu danh sách, mảng. dữ liệu bthg kiểu int, string chỉ tạ ra lệnh print số hoặc chữ. nhg dữ liệu list có thể in được cả 2.
mon_an = ['trung ran','bap','mo','bo','mam tom'] #buoc khoi tao(i: initialize)
print(mon_an)
#mon_an[1,2,3]: 1,2,3 goi la phan tu(value), ngam se theo thu tu la 0,1,2 goi la index, -1,-2,-3 la index chay nguoc lai
# buoc:READ
mon_an = ['trung ran','bap','mo','bo','mam tom']
print(mon_an[0]) #Read: trung ran
print(mon_an[-1]) #Read: mam tom
#print(mon_an[value1],mon_an[value2]): in ra 2 mon
mon_an = ['trung ran','bap','mo','bo','mam tom','thit cho']
for i in range(5): #co 5 phan tu
print(mon_an[i])
print(len(mon_an)) #in ra theo do dai
for i in range(len(mon_an)):
print(mon_an[i])
for value in mon_an: #giong dong tren, giam chu
print(value)
for value in ['trung ran','bap','mo','bo','mam tom']:
print(value)
mon_an = ['trung ran','bap','mo','bo','mam tom']
mon_an.append('sushi') #them vao cuoi de dam bao thu tu k bi xao tron
print(mon_an)
#lenh Creat
name10=input()
mon_an.append(name10) #them mon an theo input
#lenh update
mon_an[0] = 'bach tuoc' #update
print(mon_an)
#lenh delete
deleted_item = mon_an.pop() #khong dien so no se xoa mon cuoi cung
print(mon_an)
print(deleted_item)
|
9c85bedfa0dbd1d1e38cf4eaa2fbcac915040209
|
zs930831/Practice
|
/招聘的在线编程/华为机试/质数分解.py
| 327 | 3.53125 | 4 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
a = int(input())
def qiuzhishu(x):
iszhi = 1
for i in range(2, int(x ** 0.5 + 2)):
if x % i == 0:
iszhi = 0
print(str(i), end=" ")
qiuzhishu(x // i)
break
if iszhi == 1:
print(str(x), end=" ")
qiuzhishu(a)
|
a3ec713d6e5d037ef39d92174566551d725cf48b
|
l-damyanov/Python-Advanced---January-2021
|
/02-Tuples-and-Sets-Exercise/unique_usernames.py
| 147 | 3.625 | 4 |
n = int(input())
usernames = set()
for el in range(n):
user = input()
usernames.add(user)
for username in usernames:
print(username)
|
d5cb598d8ac769febd2232db224a9461787d5aac
|
wisdom2018/PythonLearning
|
/SodaDrinkBottleExchange/python/sodaDrinkBottleExchange.py
| 1,214 | 3.625 | 4 |
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/11/30 5:07 PM
# @Author: zhangzhihui.wisdom
# @File:sodaDrinkBottleExchange.py
import sys
from selenium import webdriver
def sodaDrinkBottleExchange(bottlesNumber):
result = 0
if bottlesNumber == 0:
result = 0
while bottlesNumber != 0:
temp = bottlesNumber // 3
result += temp
bottlesNumber = bottlesNumber % 3 + temp
if bottlesNumber < 3:
break
if bottlesNumber == 2:
result += 1
print(result)
if __name__ == '__main__':
# print('Soda drink bottle exchange')
# # method three
#
# # bottleOne = list(map(int, input().split(',')))
# # print(bottleOne)
# sodaDrinkNumber = int(input())
# sodaDrinkBottleExchange(sodaDrinkNumber)
# strings = list(input().split(' '))
# if strings[-1] != ' ':
# print(len(strings[-1]))
# print(len(strings))
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
# strings = input()
# chars = input()
# lists = list(strings)
# print(lists)
# number = 0
# for i in lists:
# if i == chars:
# number += 1
# print(number)
|
a4edfa7c702d84ddb796edd46b3c1340a4a4fa79
|
christinenyries/madlibs
|
/template/night_circus.py
| 1,078 | 3.59375 | 4 |
def madlib():
noun1 = input("Noun1: ")
verb1 = input("Verb1: ")
place1 = input("Place1: ")
place2 = input("Place2: ")
noun2 = input("Noun2: ")
adj = input("Adjective: ")
noun3 = input("Noun3: ")
noun4 = input("Noun4: ")
noun5 = input("Noun5: ")
color = input("Color: ")
madlib = f"The {noun1} arrives without warning.\n\
No announcements {verb1} it, no paper notices, on downtown {place1} and {place2},\
no mentions or advertisements in local {noun2}. It is simply there, when yesterday\
it was not.\n\
The {adj} {noun3} are striped in white and black, no golds and crimson to be\
seen. No color at all save for neighboring {noun4} and {noun5} of the surrounding\
fields. Black-and-white stripes on {color} sky; countless {noun3} of varying shapes\
and sizes, with elaborate wrought-iron fence encasing them in a colorless world.\
Even what little ground is visible from outside is black or white, painted, or\
powdered, or treated with some other {noun1} trick.\n\
- An excerpt from Erin Morgenstern's 'The Night {noun1}'"
print(madlib)
|
2559c10a8826a61b734796471b15eb0ee5984723
|
vinodhkrishnaraju/python_coding
|
/algorithms/reverse_words.py
| 487 | 3.921875 | 4 |
def reverse_words_in_list(words_list):
reverse_words = []
words = []
for letters in words_list:
if letters == '':
reverse_words += [''.join(words)]
words = []
continue
words += letters
reverse_words += [''.join(words)]
reverse_words1 = []
for i in range(len(reverse_words)-1, -1, -1):
reverse_words1 += [reverse_words[-i]]
return reverse_words1
print(reverse_words_in_list(['a','b','','z']))
|
c41587d25fb56b28e3db967a43c151467eb35302
|
monjurul003/algorithm-problems
|
/rat_in_a_maze.py
| 1,342 | 4.09375 | 4 |
# Rat in a maze problem. Given a Grid of size n*n, rat starts from (0,0) and has to reach (N-1, N-1). Find out if
# such a path exists and print that path. Note that there might be blockades in the maze (designated by 0).
def is_safe(maze, x, y, N):
if x >= 0 and x <= N-1 and y >= 0 and y <= N-1 and maze[x][y] == 1:
return True
else:
return False
def traverse_maze(maze, x, y, sol, N):
print "Path now: ", sol
if x == N-1 and y == N-1:
sol[x][y] = 1
return True
if is_safe(maze, x, y, N):
sol[x][y] = 1
if traverse_maze(maze, x+1, y, sol, N):
return True
if traverse_maze(maze, x, y+1, sol, N):
return True
sol[x][y] = 0 # backtrack since going either right or down didn't help rat reach.
return False
return False
def find_path(maze, N):
sol = []
for i in range(N):
row = []
for j in range(N):
row.append(0)
sol.append(row)
if traverse_maze(maze, 0, 0, sol, N):
print "Path exists...."
print sol
else:
print "Path doesn't exist"
if __name__ == "__main__":
N = int(raw_input())
matrix = []
for i in range(N):
row = map(lambda x: int(x), raw_input().split())
matrix.append(row)
find_path(matrix, N)
|
7f8a9128e6a927b0ca893ca1a5eb152e61a40fd1
|
dashanhust/leetcode
|
/algorithm/108_convert_sorted_array_to_binary_search_tree.py
| 2,862 | 3.96875 | 4 |
"""
题目:将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定有序数组: [-10,-3,0,5,9],
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
二叉搜索树(Binary Search Tree(BST))又称为二叉查找树或二叉排序树,它或者是一棵空树,或者是具有如下性质的二叉树:
1. 若它的左子树不空,则左子树上所有节点的值均小于它的根节点的值;
2. 若它的右子树不空,则右子树上所有节点的值均大于他的根节点的值;
3. 它的左右子树也分别为二叉搜索树
"""
import time
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
@classmethod
def printAllNodes(cls, nodes):
result = []
result.append(nodes.val)
if nodes.left:
result.extend(cls.printAllNodes(nodes.left))
if nodes.right:
result.extend(cls.printAllNodes(nodes.right))
return result
class Solution1:
"""
将有序数组,通过中序遍历的划分方法,划分数组,数组左边的作为节点的左边节点,数组右边的作为节点的右边节点
"""
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if not nums: return None
midIndex = len(nums) // 2
root = TreeNode(nums[midIndex])
if nums[:midIndex]:
root.left = self.sortedArrayToBST(nums[:midIndex])
if nums[midIndex + 1:]:
root.right = self.sortedArrayToBST(nums[midIndex + 1:])
return root
class Solution2:
"""
方法1需要不断的创建新的数字,这样增加了空间复杂度,这里我们不使用中间数组,而是通过下标的方式来约束数组
"""
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
def helper(left, right):
if left > right:
return None
midIndex = (left + right) // 2
root = TreeNode(nums[midIndex])
if left < midIndex:
root.left = helper(left, midIndex - 1)
if midIndex < right:
root.right = helper(midIndex + 1, right)
return root
return helper(0, len(nums) - 1)
if __name__ == "__main__":
test = [
[-10,-3,0,5,9]
]
start = time.perf_counter()
for nums in test:
result = Solution1().sortedArrayToBST(nums)
print(f'{nums} => {TreeNode.printAllNodes(result)}')
end = time.perf_counter()
print(f'TimeCost: {end} - {start} = {end - start}')
|
676edbfe3cf6081ab18cd0a47fc269a350156950
|
hackpsu-tech/hackPSUS2018-rfid
|
/test_programs/readConfig.py
| 385 | 3.890625 | 4 |
#!/usr/bin/python
"""
This application simply reads a config file created by the HackPSUconfig module and prints the output to the console
"""
import HackPSUconfig as config
configFile = input('Please enter the name of a configuration file: ')
dict = config.getProperties(configFile)
print('Dictionary:')
for key in dict:
print(key + ':' + dict[key])
print('Dictionary complete')
|
4405ad549385390f53647c809d36cdfe5e066538
|
kriskowal/planes
|
/python/text/indent/column.py
| 1,883 | 3.515625 | 4 |
# 2004-08-07 by Kris Kowal
from tab_length import tab_length
from next_tab import next_tab
def column(line, column = 0, tab_length = tab_length):
"""
returns the |column| offset that the cursor would end on if this
|line| were printed out on a perfect terminal, starting at |column|,
assuming tab stops at equal intervals of |tab_length|, where
|tab_length| is a power of two.
A perfect terminal is one which has no horizontal nor vertical size
constraints.
"""
# todo: consider: assumes that '\n' returns to column 0. It could
# possibly be more useful for it to return to the initial column
# offset. See comments in requirement assertions.
# note: not all white space of unicode are represented here, if it
# is ever generalized.
for character in line:
if character == '\t':
column = next_tab(column, tab_length)
elif character == '\r':
pass
elif character == '\n':
column = 0
else:
column += 1
return column
# unit tests
if __name__ == '__main__':
# for varying starting columns
for start in range(0, 4):
# core axiom
assert column("\t", start) == next_tab(start)
for count in range(0, 4):
# a count of spaces
assert column(" " * count, start) == start + count
# axiom applied to a count of spaces followed by a tab
example = " " * count + "\t"
assert column(example, start) == next_tab(start + count)
# up to three spaces before an indent
for n in range(0, 3):
assert column(" " * count + "\t") == 4
# a tab on the first tab stop
assert column(" \t") == 8
# newline and linefeed remain untested as unused.
|
0261e7039beaa4f2c339a6f8175e87c11732bafe
|
sureshallaboyina1001/python
|
/Functions/primeFunction.py
| 288 | 4.09375 | 4 |
def prime(num):
if num>1:
for i in range(2,num):
if num%2==0:
print(num,"is not prime no")
break
else:
print(num,"is a prime no")
num= int(input("enter the number:"))
prime(num)
|
31a694a567a7145f37974b5c8b4b75b317b9d7f1
|
SeanyDcode/codechallenges
|
/dailychallenge734.py
| 1,128 | 3.921875 | 4 |
# from dailycodingproblem.com
#
# Daily Challenge #734
# Write a map implementation with a get function that lets you retrieve the value of a key at a particular time.
#
# It should contain the following methods:
#
# set(key, value, time): sets key to value for t = time.
# get(key, time): gets the key at t = time.
# The map should work like this. If we set a key at a particular time, it will maintain that value forever or until
# it gets set at a later time. In other words, when we get a key at a time, it should return the value that was set
# for that key set at the most recent time.
#
# Consider the following examples:
#
# d.set(1, 1, 0) # set key 1 to value 1 at time 0
# d.set(1, 2, 2) # set key 1 to value 2 at time 2
# d.get(1, 1) # get key 1 at time 1 should be 1
# d.get(1, 3) # get key 1 at time 3 should be 2
# d.set(1, 1, 5) # set key 1 to value 1 at time 5
# d.get(1, 0) # get key 1 at time 0 should be null
# d.get(1, 10) # get key 1 at time 10 should be 1
# d.set(1, 1, 0) # set key 1 to value 1 at time 0
# d.set(1, 2, 0) # set key 1 to value 2 at time 0
# d.get(1, 0) # get key 1 at time 0 should be 2
|
8530157b0a414907aef3ea8c555c33a9de6e2000
|
aambrioso1/NLP
|
/NLTK/word_vec_view.py
| 1,995 | 3.53125 | 4 |
# Found here: https://www.kaggle.com/alvations/word2vec-embedding-using-gensim-and-nltk
# Some basic operation with word2vec and gensim.
import gensim
from nltk.data import find
word2vec_sample = str(find('models/word2vec_sample/pruned.word2vec.txt'))
model = gensim.models.KeyedVectors.load_word2vec_format(word2vec_sample, binary=False)
import numpy as np
labels = []
count = 0
max_count = 50
X = np.zeros(shape=(max_count,len(model['university'])))
for term in model.vocab:
X[count] = model[term]
labels.append(term)
count+= 1
if count >= max_count: break
# It is recommended to use PCA first to reduce to ~50 dimensions
from sklearn.decomposition import PCA
pca = PCA(n_components=50)
X_50 = pca.fit_transform(X)
# Using TSNE to further reduce to 2 dimensions
from sklearn.manifold import TSNE
model_tsne = TSNE(n_components=2, random_state=0)
Y = model_tsne.fit_transform(X_50)
# Show the scatter plot
import matplotlib.pyplot as plt
plt.scatter(Y[:,0], Y[:,1], 20)
# Add labels
for label, x, y in zip(labels, Y[:, 0], Y[:, 1]):
plt.annotate(label, xy = (x,y), xytext = (0, 0), textcoords = 'offset points', size = 10)
plt.show()
"""
See line 48. Need to work out who to get this file:
FileNotFoundError: [Errno 2] No such file or directory: 'GoogleNews-vectors-negative300.bin.gz'
import gensim
from gensim.models.word2vec import Word2Vec
# Load the binary model
model = gensim.models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin.gz', binary = True);
# Only output word that appear in the Brown corpus
from nltk.corpus import brown
words = set(brown.words())
print (len(words))
# Output presented word to a temporary file
out_file = 'pruned.word2vec.txt'
f = open(out_file,'wb')
word_presented = words.intersection(model.vocab.keys())
f.write('{} {}\n'.format(len(word_presented),len(model['word'])))
for word in word_presented:
f.write('{} {}\n'.format(word, ' '.join(str(value) for value in model[word])))
f.close()
"""
|
71654413eafa0d90df557b1099ecc097a694e306
|
robertrebnor/DataScience_Visualization
|
/InitializeData.py
| 2,589 | 4.1875 | 4 |
#########################################################
### ###
### Initialize Data ###
### ###
#########################################################
"""Overview of the program:
Goal:
-----
*Initialize data into a dataframe
*Format the dataframe and set appropriate types to columns
Functions:
----------
__init__: Creates a dataframe, prints basic info
returnDf: Return the dataframe
basicInfo:
"""
import numpy as np
import pandas as pd
import DescriptiveStatistics as DescStats
class ReadData():
# init method or constructor
def __init__(self, DataPath, FileType, sheetName):
"""
Creates a dataframe from a datafile. Prints basic info,
such as rows, cols, head, col names and variable types.
Parameters
----------
DataPath: string
the path to the file.
FileType: string
Says which filetype to read in.
Options are: "excel" and "csv"
sheetName: string
If filetype is Excel and there are multiple sheets within the Excel file,
sheetName specifies which sheet to read in.
By default sheetName is sat to empty.
Output
------
A dataframe from Pandas
"""
if FileType == "excel" and sheetName == None:
self.df = pd.read_excel(DataPath)
elif FileType == "excel" and sheetName != None:
self.df = pd.read_excel(DataPath, sheet_name = sheetName)
elif FileType == "csv":
self.df = pd.read_csv(DataPath)
print("")
print("Dataframe created.")
# Everytime a new dataframe is loaded, print some basic info:
DescStats.DescriptiveStatistics.basicInfo(self)
# Use __call__ instead of "returnDf"
#def __call__(self):
# return self.df
def returnDf(self):
"""Returns the dataframe
"""
return self.df
def UpdateDf(self, dataframe):
self.df = dataframe
def Df_toFile(self, DataPath, FileType, sheetName):
if FileType == "excel" and sheetName == None:
self.df = pd.to_excel(DataPath)
elif FileType == "excel" and sheetName != None:
self.df = pd.to_excel(DataPath, sheet_name = sheetName)
elif FileType == "csv":
self.df = pd.to_csv(DataPath)
print("Dataframe save at: ", DataPath)
|
4ac3d560b3beda9744f7ddcb9e7c4a36fc0ae8d3
|
vanrein/perpetuum
|
/compiler/pntools/petrinet.py
| 13,422 | 3.578125 | 4 |
#!/usr/bin/python3
# -*- coding_ utf-8 -*-
""" This program implements a parser and data structure for Petri net files.
This program implements an XML parser and a python data structure for
Petri nets/PNML created with VipTool or MoPeBs.
"""
import sys # argv for test file path
import xml.etree.ElementTree as ET # XML parser
import time # timestamp for id generation
from random import randint # random number for id generation
class PetriNet:
""" This class represents a Petri net.
This class represents a Petri net. A Petri net consists of
a set of labelled labelled transitions, labelled places and
arcs from places to transitions or transitions to places.
net.edges: List of all edges of this Petri net
net.transitions: Map of (id, transition) of all transisions of this Petri net
net.places: Map of (id, place) of all places of this Petri net
"""
def __init__(self):
#generate a unique id
self.id = ("PetriNet" + str(time.time())) + str(randint(0, 1000))
self.edges = [] # List or arcs
self.transitions = {} # Map of transitions. Key: transition id, Value: event
self.places = {} # Map of places. Key: place id, Value: place
def __str__(self):
text = '--- Net: ' + self.name + '\nTransitions: '
for transition in self.transitions.values():
text += str(transition) + ' '
text += '\nPlaces: '
for place in self.places.values():
text += str(place) + ' '
text += '\n'
for edge in self.edges:
text += str(edge) + '\n'
text += '---'
return text
class Transition:
""" This class represents a labelled transition of a Petri net.
A transition represents an activity.
transition.id: Unique ID of this transition.
transition.label: Label of this transition.
Layout information:
transition.position: Position to display the transition in graphical representations.
Usually a transition is drawn as a square. The position is the center of this square.
transition.offset: Offest of the transition label.
Usually the label of a transition is printed centered below the square which
represents the transition in graphical representations. This offset represents
a vector which defines a translation of the label inscription from its
usual position.
"""
def __init__(self):
self.label = "Transition" # default label of event
#generate a unique id
self.id = ("Transition" + str(time.time())) + str(randint(0, 1000))
self.offset = [0, 0]
self.position = [0, 0]
def __str__(self):
return self.label
class Place:
""" This class represents a labelled Place of a Petri net.
A place represents a resource.
place.id: Unique ID of this place.
place.label: Label of this place.
place.marking: Current marking of this place.
Usually a marking is the count of tokens contained into this place.
Layout information:
place.position: Position to display the place in graphical representations.
Usually a place is drawn as a circle. The position is the center of this circel.
place.offset: Offest of the place label.
Usually the label of a place is printed centered below the circle which
represents the place in graphical representations. This offset represents
a vector which defines a translation of the label inscription from its
usual position.
"""
def __init__(self):
self.label = "Place" # default label of event
#generate a unique id
self.id = ("Place" + str(time.time())) + str(randint(0, 1000))
self.offset = [0, 0]
self.position = [0, 0]
self.marking = 0
def __str__(self):
return self.label
class Edge:
""" This class represents an arc of a Petri net.
An edge represents an relation between a place and a transition or a transition
and a place.
edge.id: Unique ID of this edge.
edge.source: ID of the source (start) node of this edge.
edge.target: ID of the target (end) node of this edge.
edge.type: ID of the type of this edge.
edge.inscription: Inscription of this edge.
The inscription is usually an integer which is interpreted as weight of this edge.
edge.net: The Petri net which contains this edge.
This reference is used for the label resolution of the source and target events.
See __str__ method.
"""
def __init__(self):
#generate a unique id
self.id = ("Arc" + str(time.time())) + str(randint(0, 1000))
self.source = None # id of the source event of this arc
self.target = None # id of the target event of this arc
self.type = 'normal' # id of the type of this arc
self.inscription = "1" # inscription of this arc
self.net = None # Reference to net object for label resolution of source an target
def find_source(self):
if self.source in self.net.transitions:
return self.net.transitions[self.source]
else:
return self.net.places[self.source]
def find_target(self):
if self.target in self.net.transitions:
return self.net.transitions[self.target]
else:
return self.net.places[self.target]
def __str__(self):
return str(self.find_source()) + "-->" + str(self.find_target())
def parse_pnml_file(file):
""" This method parse all Petri nets of the given file.
This method expects a path to a VipTool pnml file which
represent a Petri net (.pnml), parse all Petri nets
from the file and returns the Petri nets as list of PetriNet
objects.
XML format:
<pnml>
<net id="...">
(<page>)
<name>
<text>name of Petri net</text>
</name>
<transition id="...">
<name>
<text>label of transition</text>
<graphics>
<offset x="0" y="0"/>
</graphics>
</name>
<graphics>
<position x="73" y="149"/>
</graphics>
</transition>
...
<place id="...">
<name>
<text>label of transition</text>
<graphics>
<offset x="0" y="0"/>
</graphics>
</name>
<graphics>
<position x="73" y="149"/>
</graphics>
<initialMarking>
<text>1</text>
</initialMarking>
</place>
...
<arc id="..." source="id of source event" target="id of target event">
<inscription>
<text>1</text>
</inscription>
</arc>
...
(</page>)
</net>
...
</pnml>
"""
tree = ET.parse(file) # parse XML with ElementTree
root = tree.getroot()
nets = [] # list for parsed PetriNet objects
xmlns = '{http://www.pnml.org/version-2009/grammar/pnml}'
for net_node in root.iter(xmlns+'net'):
# create PetriNet object
net = PetriNet()
nets.append(net)
net.id = net_node.get('id')
netnmnode = net_node.find('./'+xmlns+'name/'+xmlns+'text')
if netnmnode is not None:
net.name = netnmnode.text
else:
net.name = net.id
# and parse transitions
for transition_node in net_node.iter(xmlns+'transition'):
transition = Transition()
transition.id = transition_node.get('id')
trname = transition_node.find('./name/text')
if trname is not None:
transition.label = trname.text
off_node = transition_node.find('./'+xmlns+'name/'+xmlns+'graphics/'+xmlns+'offset')
transition.offset = [int(off_node.get('x')), int(off_node.get('y'))]
else:
transition.label = transition.id
position_node = transition_node.find('./'+xmlns+'graphics/'+xmlns+'position')
if position_node is not None:
transition.position = [int(position_node.get('x')), int(position_node.get('y'))]
else:
transition.position = None
net.transitions[transition.id] = transition
# and parse places
for place_node in net_node.iter(xmlns+'place'):
place = Place()
place.id = place_node.get('id')
placelabnode = place_node.find('./'+xmlns+'name/'+xmlns+'text')
if placelabnode is not None:
place.label = placelabnode.text
off_node = place_node.find('./'+xmlns+'name/'+xmlns+'graphics/'+xmlns+'offset')
place.offset = [int(off_node.get('x')), int(off_node.get('y'))]
else:
place.label = place.id
position_node = place_node.find('./'+xmlns+'graphics/'+xmlns+'position')
if position_node is not None:
place.position = [int(position_node.get('x')), int(position_node.get('y'))]
else:
place.position = None
plcmarknode = place_node.find('./'+xmlns+'initialMarking/'+xmlns+'text')
if plcmarknode is not None:
place.marking = int(plcmarknode.text)
else:
place.marking = 0
net.places[place.id] = place
# and arcs
for arc_node in net_node.iter(xmlns+'arc'):
edge = Edge()
net.edges.append(edge)
edge.id = arc_node.get('id')
edge.source = arc_node.get('source')
edge.target = arc_node.get('target')
edge.type = arc_node.get('type')
if edge.type is None:
etp = arc_node.find('./'+xmlns+'type')
if etp is not None:
edge.type = etp.get('value')
if edge.type is None:
edge.type = 'normal'
inscr_txt = arc_node.find('./'+xmlns+'inscription/'+xmlns+'text')
if inscr_txt is not None:
edge.inscription = inscr_txt.text
else:
edge.inscription = "1"
edge.net = net
return nets
def write_pnml_file(n, filename, relative_offset=True):
pnml = ET.Element('pnml')
net = ET.SubElement(pnml, 'net', id=n.id)
net_name = ET.SubElement(net, 'name')
net_name_text = ET.SubElement(net_name, 'text')
net_name_text.text = n.name
page = ET.SubElement(net, 'page', id='1')
for id, t in n.transitions.items():
transition = ET.SubElement(page, 'transition', id=t.id)
transition_name = ET.SubElement(transition, 'name')
transition_name_text = ET.SubElement(transition_name, 'text')
transition_name_text.text = t.label
transition_name_graphics = ET.SubElement(transition_name, 'graphics')
transition_name_graphics_offset = ET.SubElement(transition_name_graphics, 'offset')
transition_name_graphics_offset.attrib['x'] = str(t.offset[0])
transition_name_graphics_offset.attrib['y'] = str(t.offset[1])
transition_graphics = ET.SubElement(transition, 'graphics')
transition_graphics_position = ET.SubElement(transition_graphics, 'position')
transition_graphics_position.attrib['x'] = str(t.position[0] if t.position is not None else 0)
transition_graphics_position.attrib['y'] = str(t.position[1] if t.position is not None else 0)
for id, p in n.places.items():
place = ET.SubElement(page, 'place', id=p.id)
place_name = ET.SubElement(place, 'name')
place_name_text = ET.SubElement(place_name, 'text')
place_name_text.text = p.label
place_name_graphics = ET.SubElement(place_name, 'graphics')
place_name_graphics_offset = ET.SubElement(place_name_graphics, 'offset')
place_name_graphics_offset.attrib['x'] = str(p.offset[0] if p.offset is not None else 0)
place_name_graphics_offset.attrib['y'] = str(p.offset[1] if p.offset is not None else 0)
place_name_graphics_offset.attrib['x'] = str(p.offset[0] if p.offset is not None else 0)
place_name_graphics_offset.attrib['y'] = str(p.offset[1] if p.offset is not None else 0)
place_graphics = ET.SubElement(place, 'graphics')
place_graphics_position = ET.SubElement(place_graphics, 'position')
place_graphics_position.attrib['x'] = str(p.position[0] if p.position is not None else 0)
place_graphics_position.attrib['y'] = str(p.position[1] if p.position is not None else 0)
place_initialMarking = ET.SubElement(place, 'initialMarking')
place_initialMarking_text = ET.SubElement(place_initialMarking, 'text')
place_initialMarking_text.text = str(p.marking)
for e in n.edges:
edge = ET.SubElement(page, 'arc', id=e.id, source=e.source, target=e.target, type=e.type)
edge_inscription = ET.SubElement(edge, 'inscription')
edge_inscription_text = ET.SubElement(edge_inscription, 'text')
edge_inscription_text.text = str(e.inscription)
tree = ET.ElementTree(element=pnml)
tree.write(filename, encoding="utf-8", xml_declaration=True, method="xml")
if __name__ == "__main__":
if len(sys.argv) > 1:
nets = parse_pnml_file(sys.argv[1])
for net in nets:
print(net)
|
103942d6f4f22fbfe60b9f1ae03c38b4d41fcf55
|
salma27/pygame
|
/salma 12.py
| 1,799 | 3.78125 | 4 |
game =['a','f','g','a','b','w','c','m','b','d','l','g','w','l','e','f','e','c','g','m']
no=['1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6','7','8','9','0']
s=no
j=0
i=0
k=0
print("welcome to the memory game\n")
print(no)
while(True):
if j%2==0:
print("player 1 : it's your turn\n")
else:
print("player 2 : it's your turn\n")
print("choose 2 numbers from (1:20)\n")
no1=int(input())
no2=int(input())
while(no1==no2 or no1>20 or no2>20 or no1<1 or no2<1 or game[no1-1]=='*' or game[no2-1]=='*' or s[no1-1]=='*' or s[no2-1]=='*'):
print("choose another 2 numbers\n")
no1=int(input())
no2=int(input())
if game[no1-1]==game[no2-1]:
s[no1-1]=game[no1-1]
s[no2-1]=game[no2-1]
print(s)
print("\n")
s[no1-1]='*'
s[no2-1]='*'
no=s
print(s)
print("\n")
if j%2==0 :
i=i+1
else :
k=k+1
if s=="********************" :
if i>k :
print ("the winner is player 1\n")
print ("the highest score is : ",i)
print("\n")
break
elif(k>i) :
print("the winner is player 2 \n")
print("the highest score is : ",k)
print("\n")
break
else:
print("it's a draw")
break
else :
x=s[no1-1]
y=s[no2-1]
s[no1-1]=game[no1-1]
s[no2-1]=game[no2-1]
print (s)
print("\n")
s[no1-1]=x
s[no2-1]=y
print(no)
print("\n")
s=no
j=j+1
|
5d102cc424620eea7d9d06f28945421eb55ae479
|
haraldfw/pyprog
|
/scripts/oving02/functions.py
| 252 | 3.859375 | 4 |
def celsius_far(celsius):
return celsius * (9.0 / 5.0) + 32 # must have decimals to prevent int-calc flooring
valIn = input('Enter celsius value to be converted: ')
print str(valIn) + ' degrees celsius in fahrenheit: ' + str(celsius_far(valIn))
|
c3fbe0e9cc18c44f79296a74d07e2789ee57bd11
|
Lavenda/myPythonCastle
|
/src/myLibs/myThread/threadqueue/myCommand.py
| 1,976 | 3.734375 | 4 |
#!/usr/bin/env python2.6
#-*- coding: utf-8 -*-
"""
Created on 2013-5-1
@author: lavenda
"""
class MyCommand(object):
"""
This class is uesd to package all kinds of method objects, likes a data transfer object.
"""
def __init__(self):
self.methodObject = None
self.lock = object
self.priority = 0
self.args = []
self.kwargs = {}
self.result = None
def setCommand(self, methodObject, lock, priority, args, kwargs):
"""
this method is used to give values to this object's attributes.
@param methodObject: it is a object of the method you want to run.
@type methodObject: method object
@param args: it is the args of the method you want to run.
@type args: list type
@param kwargs: it is the key-value args of the method you want to run.
@type kwargs: dictionary type
"""
self.methodObject = methodObject
self.lock = lock
self.priority = priority
self.args = args
self.kwargs = kwargs
def setResult(self, result):
"""
This mehtod is used to set the result to this object's result after this methodObject ran
@param result: Any type, the result of the method object
"""
self.result = result
def getResult(self):
"""
This method is used to get the result from this object's attribute.
- It has many problems in this method, so it will make better in future.
@return: Any type or an exception(None temporarily). If the method has run accurately,
it will return a normal result, otherwise it will raise an exception.
"""
if self.result == None:
return None #return None temporarily,
#it should be retruning an exception
else:
return self.result
|
edfb9cba3770b70e3cd8d998d0f49c9a61cd0cbb
|
Helper2020/LRU-Cache
|
/problem_1.py
| 4,996 | 4.46875 | 4 |
class Node:
'''
Node class is used to encapsulate a key and a value.
'''
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
self.prev = None
class Doubly_linked_list:
'''
This double linked list tracks the usage order of the cache.
Attributes:
head: Start of the list. The head is the most recent key accessed.
tail: End of the list. THe tail is the least recently key accessed.
'''
def __init__(self):
self.head = None
self.tail = None
def get_tail_key(self):
return self.tail.key
def get_head_key(self):
return self.head.key
def insert_new_node(self, new_node):
'''
This function take a new_node and places the node in front of the list.
'''
# linked list is empty
if self.head is None:
self.head = new_node
self.tail = new_node
return
# insert at head
self.head.prev = new_node
new_node.next = self.head
self.head = new_node
def move_node_to_front(self, node):
'''
Takes a recently accessed node and places it at the front of the list.
'''
# Node is already at front
if node.key == self.head.key:
return
# node is at tail
if node.next is None:
# set node prev to None to make then make it the new tail
node.prev.next = None
self.tail = node.prev
else:
node.prev.next = node.next
node.next.prev = node.prev
# set node next to head
node.next = self.head
# set head to prev to node
self.head.prev = node
node.prev = None
self.head = node
def remove_least_recent_node(self):
node_to_delete = self.tail
self.tail = node_to_delete.prev
self.tail.next = None
node_to_delete.next = None
node_to_delete.prev = None
class LRU_Cache(object):
'''
Attributes:
capacity: max size of the cache
usage_order: doubly_linked_list to keep track of access order.
storage: dictionary to retrieve the values associated to a key
'''
def __init__(self, capacity):
# Initialize class variables
if capacity <= 0:
raise ValueError("Cache size should be greater than 0")
self.capacity = capacity
self.usage_order = Doubly_linked_list()
self.storage = dict()
def get(self, key):
# Retrieve item from provided key. Return -1 if nonexistent.
node = self.storage.get(key)
if node is None:
return -1
self.usage_order.move_node_to_front(node)
return node.value
def set(self, key, value):
# Set the value if the key is not present in the cache. If the cache is at capacity remove the oldest item.
node = self.storage.get(key)
if node:
node.value = value
# update recently_used list
self.usage_order.move_node_to_front(node)
return
# Node not in list
# Remove least recently used if full
if len(self.storage) == self.capacity:
tail_key = self.usage_order.get_tail_key()
self.usage_order.remove_least_recent_node()
del self.storage[tail_key]
# add new node
new_node = Node(key, value)
self.storage[key] = new_node
self.usage_order.insert_new_node(new_node)
# Test case 1
our_cache = LRU_Cache(5)
our_cache.set(1, 1)
our_cache.set(2, 2)
our_cache.set(3, 3)
our_cache.set(4, 4)
print(our_cache.get(1))
# return 1
print(our_cache.get(2))
# returns 2
print(our_cache.get(9))
# returns -1 because 9 is not present in the cache
our_cache.set(5, 5)
our_cache.set(6, 6)
print(our_cache.get(3))
# returns -1 because the cache reached it's capacity and 3 was the least recently used entry
print(our_cache.storage.keys())
print("----------------Test Case 2-----------")
# Test case 2
# Case where same key is being set in the cache.
# Occurs after the cache is full. Key of 3 is set again.
# Four should removed
our_cache = LRU_Cache(5)
our_cache.set(1, 1)
our_cache.set(2, 2)
our_cache.set(3, 3)
our_cache.set(4, 4)
our_cache.get(1)
our_cache.get(2) #
our_cache.get(9)
our_cache.set(5, 5) # Cache is full
our_cache.set(3, 3) # Three is set again
our_cache.set(6, 6)
# Here four should be removed
print(our_cache.get(4))
# -1 should be printed
print(our_cache.storage.keys())
print("----------------Test Case 3-----------")
# Test case 3
# Case where cache size is 0
our_cache = LRU_Cache(0)
# Should raise a ValueError
|
f6c402fc8a7f5c3e8cc066d170986fb7e3e62ec3
|
vbsilva/Algoritimos_2016.1
|
/Exemplo_Python/ex.py
| 250 | 3.53125 | 4 |
class MyClass():
def __init__(self):
self._nome = ""
def setNome(self, nome):
self._nome = nome;
def getNome(self):
return self._nome
def main():
x = MyClass()
x.setNome("olar mundo!")
print(x.getNome())
if __name__ == "__main__":
main()
|
172cf9b041c49df1d0230bd8b794b0179ece6386
|
enriqueee99/learning_python
|
/ejercicio_15.2.py
| 814 | 4.0625 | 4 |
empleados = []
faltas = []
for x in range(3):
nombres = input('Nombre del empleado: ')
empleados.append(nombres)
dias = int(input('Cuantos dias faltó?: '))
faltas.append([])
for y in range(dias):
dia = int(input('Qué dias faltó?: '))
faltas[x].append(dia)
print('Empleados y los dias que faltaron')
for x in range(3):
print(empleados[x])
for y in range(len(faltas[x])):
print(faltas[x][y])
print('Empleados y la cantidad de inasistencias')
for x in range(3):
print(f'El empleado {empleados[x]} faltó {len(faltas[x])} dias')
print('Empleado que faltó menos')
menos = len(faltas[0])
for x in range(1,3):
if len(faltas[x]) < menos:
menos = len(faltas[x])
for x in range(3):
if len(faltas[x]) == menos:
print(empleados[x])
|
370c04ddc8b29fcad7ff7eaf41c4bd916b9b61c3
|
zbrtech/matplotlib_study
|
/random_walk.py
| 1,778 | 4.46875 | 4 |
from random import choice #this is file 11
class RandomWalk(): #one class to randomly and autoly create walk steps
#this class contain 2 funtions and 3 properties
def __init__(self,num_points=5000): #1 of 2 functions of this class. to send steps arguments to this class itself. and declare 3 properties
self.num_points = num_points #self.number_points is 1 of 3 properties of this class. this shuxing use the sent argument
self.x_values = [0] #self.x_values is 1 of 3 properties of this class. it is a list to store up x direction steps
self.y_values = [0] #just like x
def fill_walk(self): #1 of 2 functions of this class.to randomly and autoly create walk steps
while len(self.x_values) < self.num_points: #just use 2 properties
x_direction = choice([1,-1]) #decide x go to left or right
x_distance = choice([0,1,2,3,4]) #decide distance of one step
x_step = x_direction * x_distance #combine direction and distance to create the x_step property
y_direction = choice([1,-1])
y_distance = choice([0,1,2,3,4])
y_step = y_direction * y_distance
if x_step == 0 and y_step == 0:
continue #refuse x,y all is 0, because it means do not move
next_x = self.x_values[-1] + x_step #joint the self.x_values property(-1 means the last one of the list) and the x_step to create next_x who will append to be the last self.x_values
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
|
e40d0ae8d7dd1c8799f4d36e81e27ee7497ebea1
|
ssmore88/effective-meme
|
/GuessMyNumber.py
| 550 | 3.984375 | 4 |
import random
number = random.randint(1,40)
tries = input()
tries = int(tries)
print ("You have 5 guesses to find my number otherwise you lose")
while tries < 5:
answer = int(input("Please enter a number between 1 and 40:"))
if answer == number:
break
if answer > number:
print ("Choose a number lower")
if answer < number:
print ("Choose a number higher")
if tries > 5:
print ("Sorry but you are out of tries!")
print ("Better luck next time")
print ("Nice work you found my number")
|
870282e27827d3a4662b293db1d40345fca520de
|
danagle/boggled
|
/src/boggled/boggle_words.py
| 6,118 | 3.90625 | 4 |
# boggle_words.py
"""
Library for building a word dictionary including prefixes for Boggle.
"""
from collections import UserDict
from re import sub
class NoneFieldDict(UserDict):
"""
This dict subclass returns a None type instead of raising a KeyError.
"""
def __missing__(self, key):
"Returns the null object None."
return None
class TrieNode:
"""
Represents a Trie data structure used to build an efficient word search.
The children container is implemented using the `NoneFieldDict`. It's use
of the __missing__ method reduces the memory footprint of the Trie.
Public attributes:
- parent : TrieNode - Link to parent node in the Trie.
- children : NoneFieldDict of TrieNode - The key is the next letter.
- isWord : Boolean - Indicates this node is the last letter in a word.
"""
def __init__(self, parent, value):
"""
Initialise the TrieNode and link it with the parent node.
"""
self._parent = parent
self._children = NoneFieldDict()
self._isWord = False
if parent is not None:
parent._children[value[0]] = self
@property
def parent(self):
"""
Parent node in the Trie.
TrieNode / None
"""
return self._parent
@property
def children(self):
"""
Children of the node.
NoneFieldDict: key: character string, value: TrieNode
"""
return self._children
@property
def isWord(self):
"""
Indicates whether or not this node is the last letter in a word.
"""
return self._isWord
class Trie:
"""
Represents the root node of the Trie structure.
Public attributes:
root : TrieNode - The root element of the Trie.
"""
def __init__(self):
"""
Initialise the Trie with an empty node.
"""
self._root = TrieNode(None, '')
@property
def root(self):
"""
The root element of the Trie.
"""
return self._root
def node(self, prefix, start=None):
"""
Returns the node which corresponds to the final character of the
prefix.
Returns None if the prefix is not present in the Trie.
"""
node = start if start else self._root
for ch in prefix:
if node.children[ch] is not None:
node = node.children[ch]
else:
node = None
break
return node
class BoggleWords():
"""
Represents the words used in the game dictionary.
Public attributes:
minLength : int - The prefix string length.
prefixes : dict - key: prefix string, value: TrieNode.
words: Trie - The dictionary data structure.
wordsRoot: TrieNode - The root node of the dictionary.
"""
def __init__(self, minLength=3):
"""
Initialise with a minimum word length of 3 if not specified.
"""
self._minLength = minLength
self._prefixes = dict()
self._words = Trie()
@property
def minLength(self):
"""
Word prefix length and minimum length word for the game.
"""
return self._minLength
@property
def prefixes(self):
"""
dict for dictionary word prefixes - key: prefix string, value: TrieNode.
"""
return self._prefixes
@property
def words(self):
"""
The dictionary Trie.
"""
return self._words
@property
def wordsRoot(self):
"""
TrieNode at the root of the dictionary.
"""
return self._words.root
def _cleanWord(self, word):
"""
Returns word in uppercase with all non-alphabethic characters removed.
Args:
word: String of the word being added to the Trie.
Returns:
Uppercase string or False
"""
cleaned = sub(r'[\W]', '', word)
is_valid = cleaned.isalpha() and (len(cleaned) >= self.minLength)
return cleaned.upper() if is_valid else False
def _getWordStartNode(self, word):
"""
Returns the node where the word insertion should begin.
Looks ahead to see if word prefix is already present, this will allow
the initial levels of the Trie to be skipped if the prefix is there.
Args:
word: String of the word being added to the Trie.
Returns:
tuple(start_node, word, prefix)
start_node: TrieNode where to begin process.
word: String to be added.
prefix: String prefix if it's a new prefix, otherwise None.
"""
prefix = word[:self._minLength]
if (prefix not in self._prefixes):
start_node = self.wordsRoot
else:
start_node = self.prefixes[prefix]
prefix = None
word = word[self._minLength:]
return (start_node, word, prefix)
def iteratorPopulateTrie(self, word_iter):
"""
Populates the Trie structure from an iterator of words.
"""
for word in word_iter:
cleaned_word = self._cleanWord(word)
if isinstance(cleaned_word, str):
node, word_part, prefix = self._getWordStartNode(cleaned_word)
for index, letter in enumerate(word_part, 1):
next_node = node.children[letter]
if next_node is None:
next_node = TrieNode(node, letter)
node = next_node
if prefix is not None and index == len(prefix):
self.prefixes[prefix] = node
node._isWord = True
def loadFromFile(self, file_path):
"""
Reads the list of words from a file and passes the list to the
iteratorPopulateTrie() method.
Args:
file_path: Path to the text file.
"""
with open(file_path, 'r') as words_file:
self.iteratorPopulateTrie(words_file.readlines())
|
63ae78075db5316ba31b75d1405af70b043f28fb
|
Tom-Petty98/PythonExercises
|
/Challenges/Code/DC3.py
| 483 | 4.28125 | 4 |
# Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated
# sequence after sorting them alphabetically.
# (without,hello,bag,world) -> bag,hello,without,world
def sort_words(s1):
a = s1.split(',')
a.sort()
s2 = ""
for i in range(len(a)):
if i == len(a) -1:
s2 += a[i]
else:
s2 += a[i] + ","
return s2
print(sort_words("without,hello,bag,world"))
|
56ef8d34f3b107ce9f52867d96dac289520b0621
|
aguscoppe/ejercicios-python
|
/TP_9_Matrices/TP3_EJ4.py
| 1,972 | 3.859375 | 4 |
import random
def crearMatriz():
n = int(input("Ingrese la cantidad de fábricas: "))
filas = n
columnas = 6
matriz = [[0] * columnas for i in range(filas)]
return matriz
def rellenarMatriz(matriz):
filas = len(matriz)
columnas = len(matriz[0])
for f in range(filas):
for c in range(columnas):
matriz[f][c] = random.randint(0, 150)
def imprimirMatriz(matriz):
filas = len(matriz)
columnas = len(matriz[0])
for f in range(filas):
for c in range(columnas):
print("%3d" %matriz[f][c], end=" ")
print()
def mayorFabricacion(matriz):
fila = 0
for f in range(len(matriz)):
fila = sum(matriz[f])
print("Fábrica", f + 1, "- Total de bicicletas:", fila)
def diaProductivo(matriz):
mayor = -1
fabrica = -1
for f in range(len(matriz)):
for c in range(len(matriz[0])):
if matriz[f][c] > mayor:
mayor = matriz[f][c]
fabrica = f
dia = c
print("El día de mayor producción fue el día", dia, "de la fábrica", fabrica + 1)
def columnaProductiva(matriz):
totales = [0, 0, 0, 0, 0, 0]
for f in range(len(matriz)):
for c in range(len(matriz[0])):
totales[c] += matriz[f][c]
maximo = max(totales)
dia = totales.index(maximo)
print("El día semanal más productivo para todas las fábricas fue el n°", dia)
def menosFabricadas(matriz):
menos = []
for f in range(len(matriz)):
menos.append(min(matriz[f]))
return menos
# PROGRAMA PRINCIPAL
matriz = crearMatriz()
rellenarMatriz(matriz)
print()
imprimirMatriz(matriz)
print()
mayorFabricacion(matriz)
print()
diaProductivo(matriz)
print()
columnaProductiva(matriz)
print()
menos = menosFabricadas(matriz)
for i in range(len(menos)):
print("Fábrica", i + 1, "- Menor cantidad producida:", menos[i])
|
eb31f2d88a7420acec20ecb80a8be7e7e245441a
|
sandeep-singh-79/DSAlgo
|
/src/GFG/07-peakElement.py
| 2,065 | 4.21875 | 4 |
""" A peak element in an array is the one that is not smaller than its neighbours.
Given an array arr[] of size N, find the index of any one of its peak elements.
Note: The generated output will always be 1 if the index that you return is correct. Otherwise output will be 0.
Example 1:
Input:
N = 3
arr[] = {1,2,3}
Output: 2
Explanation: index 2 is 3.
It is the peak element as it is
greater than its neighbour 2.
Example 2:
Input:
N = 2
arr[] = {3,4}
Output: 1
Explanation: 4 (at index 1) is the
peak element as it is greater than
its only neighbour element 3.
Your Task:
You don't have to read input or print anything. Complete the function peakElement() which takes the array arr[] and
its size N as input parameters and return the index of any one of its peak elements.
"""
class Solution:
def peakElement(self,arr, n):
if n == 0 or arr is None: return -1
if n == 1: return 0
arrLen = len(arr)
for i in range(arrLen):
if arrLen:
if i == arrLen - 1 and arr[i] > arr[i-1]: return i
if arr[i] > arr[i-1] and arr[i] > arr[i+1]:
return i
else:
if arr[i] > arr[i+1]: return i
return -1
#{
# Driver Code Starts
if __name__=='__main__':
t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int, input().strip().split()))
index = Solution().peakElement(arr.copy(), n)
flag = False
if index<0 or index>=n:
flag = False
else:
if index == 0 and n==1:
flag = True
elif index==0 and arr[index]>=arr[index+1]:
flag = True
elif index==n-1 and arr[index]>=arr[index-1]:
flag = True
elif arr[index-1] <= arr[index] and arr[index] >= arr[index+1]:
flag = True
else:
flag = False
if flag:
print(1)
else:
print(0)
# Contributed by: Harshit Sidhwa
# } Driver Code Ends
|
0fa31538db9bb28e6a4e7b518059509db9250dbe
|
iamwillcode/PumpBot
|
/trading/BasicInvestmentStrategy.py
| 915 | 3.625 | 4 |
"""
An investment strategy in which the funds that are invested are based on
a predefined fraction.
"""
from trading.InvestmentStrategy import InvestmentStrategy
from wallet.Wallet import Wallet
class BasicInvestmentStrategy(InvestmentStrategy):
investmentFraction: float
def __init__(self, investmentFraction=0.0):
self.investmentFraction = investmentFraction
def getAmountToInvest(self, wallet: Wallet, price: float,
confidence: float) -> float:
"""
Determines how many funds from the wallet should be used towards an
investment.
:param wallet: the trader's wallet
:param price: the price of the stock/currency
:param confidence: the confidence of the model that suggested to invest.
:return: how many funds should be invested.
"""
return wallet.getPortionOfBalance(self.investmentFraction)
|
b3fb958a829b855b9905f4317784cc44c1aab5f4
|
s-hiiragi/atcoder-study
|
/arc001_3/main.py
| 1,335 | 3.53125 | 4 |
# https://atcoder.jp/contests/arc001/tasks/arc001_3
# 斜めもダメということを忘れていた
import io
s1 = '''\
........
........
.......Q
........
..Q.....
........
.Q......
........
'''
s2 = '''\
.....Q..
.Q......
........
........
........
Q.......
........
........
'''
s = s2
c = []
with io.StringIO(s) as f:
for line in f:
c.append(list(line.strip()))
def print_map(c):
for i in range(len(c)):
print(' '.join(c[i]))
print('INPUT')
print_map(c)
i_s = list(range(8))
j_s = list(range(8))
for i in range(8):
for j in range(8):
if c[i][j] == 'Q':
i_s.remove(i)
j_s.remove(j)
def solve(i_s, j_s, points):
for i in i_s:
for j in j_s:
if c[i][j] == '.':
i_s2 = i_s.copy()
j_s2 = j_s.copy()
i_s2.remove(i)
j_s2.remove(j)
if len(i_s2) == 0 and len(j_s2) == 0:
return points + [(i, j)]
ans = solve(i_s2, j_s2, points)
if ans:
return ans + [(i, j)]
return None
ans = solve(i_s, j_s, [])
if ans:
for i,j in ans:
c[i][j] = 'Q'
print('Answer')
print_map(c)
else:
print('No Answer')
|
c413df07b9d92cc0abcfe9aef1aad0d68e21e418
|
artsR/Automate-the-Boring-Stuff-with-Python
|
/Chapter 10/Chapter 10 - Debugger.py
| 5,327 | 4.125 | 4 |
############ CHAPTER 10 #############
def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception('Symbol must be a single character string.')
if width <= 2:
raise Exception('Width must be greater than 2.')
if height <= 2:
raise Exception('Height must be greater than 2.')
print(symbol * width)
for i in range(height-2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)
for sym, w, h in (('*', 4, 4), ('0', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):
try:
boxPrint(sym,w,h)
except Exception as err: # if an Exception object is returned from boxPrint()
# this except statement will store it in a variable named err.
print('An exception happened: ' + str(err))
# raise Exception causes 'Traceback' information in console.
# The traceback is displayed by Python whenever a raised exception goes unhandled.
# traceback.format_exc() - the function is located in traceback Module
# instead of crashing my program right when an exception occurs,
# I can write the traceback information to a log file and
# keep my program running.
import traceback
try:
raise Exception('This is the error message.')
except:
errorFile = open('errorInfo.txt', 'w')
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback info was written to errorInfo.txt.')
# assertion
podBayDoorStatus = 'open'
# assert statement says: "I assert that this condition holds true,
# and if not, there is a bug somewhere in the program.
# Unlike "exceptions", my code should not handle assert statement with
# "try" and "except".
# If an assert fails, program should crash fast to shorten the time between
# the original cause of the bug and my first notice the bug.
# Assertions are for programmer errors, not user errors.
# For errors like 'file not was found..' or user enter invalid data
# I have raising an exception.
# Assertions are for development, not the final product. By the time I
# hand off my program to someone else to run, it should be free of bugs
# and not require the sanity checks.
assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'
podBayDoorStatus = 'I\'m sorry, Dave. I\'m afraid I can\'t do that.'
assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'
market_2nd = {'ns': 'green', 'ew': 'red'}
mission_16th = {'ns': 'red', 'ew': 'green'}
def switchLights(stoplight):
for key in stoplight.keys():
if stoplight[key] == 'green':
stoplight[key] = 'yellow'
elif stoplight[key] == 'yellow':
stoplight[key] = 'red'
elif stoplight[key] == 'red':
stoplight[key] = 'green'
assert 'red' in stoplight.values(), 'Neither light is red! ' + str(stoplight)
switchLights(market_2nd)
# Assertions can be disabled by passing the -0 option when running Python.
# Logging - describes when the program execution has reached the logging
# function call and list any variables I have specified at that point in time
# (sometimes I use print() to see what's going on in program. Logging
# fills this role).
# all "logging" in the code may be disabled by "logging.disable(loggin.CRITICAL)
#--- the program results are followed thanks to "logging"----------------------
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
## basicConfig() specifies what details about the LogRecord object I want to
# see and how I want those details displayed.
logging.debug('Start of program')
## logging.debug() - prints log information
## debug() - call basicConfig()
## basicConfig() - specifies the format of information
def factorial(n):
logging.debug('Start of factorial(%s%%)' % (n))
total = 1
for i in range(1, n+1):
total *= i
logging.debug('i is ' + str(i) + ', total is ' + str(total))
logging.debug('End of factorial(%s%%)' % (n))
print(factorial(5))
logging.debug('End of program')
# write loggings to the file:
# logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG,
# format='%(asctime)s - %(levelname)s - %(message)s')
#------------------------------------------------------------------------------
# logging level of importance
'''
DEBUG logging.debug()
The lowest level. Used for small details.
Usually you care about these messages only when diagnosing problems.
INFO logging.info()
Used to record information on general events
in your program or confirm that things are working at their point in the
program.
WARNING logging.warning()
Used to indicate a potential problem that
doesn’t prevent the program from working but might do so in the future.
ERROR logging.error() Used to record an error that caused the
program to fail to do something.
CRITICAL logging.critical() The highest level. Used to indicate a fatal
error that has caused or is about to cause the program to stop running
entirely.
'''
|
4a566fc5c894468882d255267ccefd94b8e15295
|
dungtutb/algorithm_pttkgt
|
/insertion_sort.py
| 265 | 3.953125 | 4 |
def insertion_sort(ds):
for i in range(len(ds)):
cur_value = ds[i];
j = i-1;
while j>=0 and ds[j]>cur_value:
ds[j+1]=ds[j]
j=j-1
ds[j+1]=cur_value
ds = [9,4,8,1,5,7,3,6,2]
insertion_sort(ds)
print ds
|
126f0859ae16160a7e2316876fb02fc21938b0d1
|
beOk91/code_up
|
/code_up1718.py
| 202 | 3.671875 | 4 |
text=input()
whereH=text.index("H")
if text[whereH-1]=="C":
c_val=1
else:
c_val=int(text[1:whereH])
if len(text)-1==whereH:
h_val=1
else:
h_val=int(text[whereH+1:])
print(c_val*12+h_val)
|
1f48bfbad0a7b2bfe17eb07780a43177a492f798
|
DanielPramatarov/Penetration-Testing-Tools
|
/Python/PythonNmap/PyMap.py
| 3,223 | 3.8125 | 4 |
import nmap
while True:
print("""\nWhat do you want to do?\n
1 - Get detailed info about a device
2 - Scan IP for open ports with stealth scan
e - Exit the application""")
user_input = input("\nEnter your option: ")
print()
ip = input("\nPlease enter the IP address to scan: ")
if user_input == "1":
mynmap = nmap.PortScanner()
print("\nThis may take a couple of minutes...\n")
scan = mynmap.scan(ip, '1-1024', '-v -sS -sV ')
print("\n= = = = = = = HOST {} = = = = = = =".format(ip))
print("\n\nGENERAL INFO")
try:
mac = scan['scan'][ip]['addresses']['mac']
print("\n-> MAC address: {}".format(mac))
except KeyError:
pass
nm = nmap.PortScanner()
scanner = nm.scan(ip, arguments='-O')
if len(scanner['scan']) == 0:
print("Host seems down. If it is really up, but blocking our ping probes")
else:
try:
os = scan['scan'][ip]['osmatch'][0]['name']
print("-> Operating system: {}".format(os))
except:
print("No OS detected")
print("\n\nPORTS\n")
for port in list(scan['scan'][ip]['tcp'].items()):
print("-> {} | {} | {}".format(port[0], port[1]['name'], port[1]['state']))
print("\n\nOTHER INFO\n")
print("-> NMAP command: {}".format(scan['nmap']['command_line']))
continue
elif user_input == "2":
mynmap = nmap.PortScanner()
print('='*100)
print('='*100)
print("\nThis may take a couple of minutes...\n")
scan = mynmap.scan(ip,ports = '1-1024', arguments = '-sS')
if len(scan['scan']) == 0:
print("Host seems down. If it is really up, but blocking our ping probes")
for device in scan['scan']:
mac_addr = scan['scan'][device]['addresses']['mac']
print("Scanning IP: {} with MAC address: {}".format(scan['scan'][device]['addresses']['ipv4'],mac_addr))
if 'tcp' in scan['scan'][device]:
print("\nPorts open on {}:".format(device))
for port in scan['scan'][device]['tcp'].items():
if port[1]['state'] == 'open':
print("-->" + str(port[0]) + "|" + port[1]['name'])
else:
print("\nNo open ports on {}:".format(device))
if 'vendor' in scan['scan'][device]:
print("The vendor is {}".format(scan['scan'][device]['vendor'][mac_addr]))
else:
pass
if 'status' in scan['scan'][device]:
status = scan['scan'][device]['status']['state']
reason = scan['scan'][device]['status']['reason']
print("Status: {} Reason: {}".format(status,reason))
else:
pass
print('='*100)
print('='*100)
continue
elif user_input == "e":
print('\nExiting program...\n')
break
else:
print("\nInvalid input. Try again!\n")
continue
|
cf1e65f9972ed22345dcdb7362ea0af992b089d5
|
text007/learngit
|
/5.字符串/字符串内建函数/35.title()方法.py
| 258 | 3.75 | 4 |
# title()方法:返回"标题化"的字符串,就是说所有单词的首个字母转化为大写,其余字母均为小写
# 注意,非字母后的第一个字母将转换为大写字母
str45 = "this is hello b2b2b2 and 3g3g3g!!!"
print(str45.title())
|
46ece28d1f110e4aee7e64ec39a494e397f30cdd
|
AtilioA/Python-20191
|
/lista7jordana/Ex055.py
| 2,285 | 3.765625 | 4 |
# Faça um programa que percorre uma lista com o seguinte formato:
# [['Brasil', 'Italia', [10, 9]], ['Brasil', 'Espanha', [5, 7]], ['Italia', 'Espanha', [7,8]]]
# e imprima na tela algumas# informações.
# Essa lista indica o número de faltas que cada time fez em cada jogo.
# Na lista acima, no jogo entre Brasil e Itália, o Brasil fez 10 faltas e a Itália fez 9.
# O programa deve imprimir na tela:
# a) o total de faltas do campeonato
# b) o time que fez mais faltas
# c) o time que fez menos faltas
from Ex048 import soma_elementos
listaFaltas = [
['Brasil', 'Italia', [10, 9]],
['Brasil', 'Espanha', [5, 7]],
['Italia', 'Espanha', [7, 8]]
]
# pega lista de times
# pra cada partida, ve se cada time está nela
# pra cada time que estiver, pegar indice dele
# acessar lista de faltas com o indice do time
# somar e repetir
# a)
def total_faltas(listaFaltas):
def terceiro(lista3):
return lista3[2]
faltas = list(map(terceiro, listaFaltas))
totalFaltas = soma_elementos(map(soma_elementos, faltas))
return totalFaltas
# b)
def remove_duplicata(lista):
if len(lista) < 2:
return lista
elif lista[0] not in lista[1:]: # O elemento é único, podemos adicioná-lo na lista final
return [lista[0]] + remove_duplicata(lista[1:])
else: # O elemento não é único, não o adicionamos ainda
return remove_duplicata(lista[1:])
def times_campeonato(listaFaltas):
def primeiro(lista):
if not lista:
return lista
else:
return lista[0]
def segundo(lista):
if len(lista) < 2:
return None
else:
return lista[1]
timesRepetidos = list(map(primeiro, listaFaltas)) + list(map(segundo, listaFaltas))
times = remove_duplicata(timesRepetidos)
return times
print(f"Total de faltas do campeonato: {total_faltas(listaFaltas)}")
print(f"Time que fez mais faltas: {total_faltas(listaFaltas)}")
print(f"Time que fez menos faltas: {total_faltas(listaFaltas)}")
print(times_campeonato(listaFaltas))
def faltas_times(listaFaltas, times):
print("\n", times)
print(listaFaltas[0])
return list(filter(lambda x: x in listaFaltas[0], times))
print(faltas_times(listaFaltas, times_campeonato(listaFaltas)))
|
664b7ff2c325bb21b55b99e44dfbc441c0407586
|
Daniyar-Yerbolat/university-projects
|
/year 2/semester 1/programming languages/labs/question H - Daniyar Nazarbayev [H00204990].py
| 4,287 | 3.78125 | 4 |
# Daniyar Nazarbayev, H00204990.
# exercise H #1
def mult1 (list_num):
x = 0
total = 1
while (x<len(list_num)):
total = total * list_num[x]
x = x + 1
return total
# exercise H #2
def mult2 (list_num):
if len(list_num)==0:
return 1
else:
return list_num.pop() * mult2(list_num)
# exercise H #3
# just make a big list and give it as an argument
x = list(range(1,1000001))
# mult2 is not tail recursive.
# each value from each recursive call is necessary to give a proper result,
# so new memory space will be created for every recursive call.
# which can result in a stack overflow error.
# exercise H #4
from functools import reduce
def mult3 (list_num):
if len(list_num)==0:
return 1
else:
return reduce((lambda x, y: x * y), list_num)
# exercise H #5
# 60.0 in every case.
# it means that python is not strictly typed.
# in SML's case that would not be possible.
# first of all, lists can only contain the same type
# and even if i were to try to use functions floor and real
# to convert everything to the same type
# i won't be able to, since i cannot check for types, cause SML is static typed.
# exercise H #6
# mult3 will be fastest, mult1 second fastest, and mult2 the slowest.
# mult3 is using the reduce function, and reduce carries over
# the value it calculates.
#
# for element in it:
# value = function(value, element)
#
# this is not recursion, this is just a loop that calls a function
# for each element, but it carries the total calculated and the next element
# so it is sort of like tail recursion.
# mult1 is second fastest, i think. It's a loop, and it uses the same variable
# for all its calculations, meaning only a single memory slot
# (don't quote me on that)
#
# total = total * list[x]
#
# maybe both mult3 and mult1 take the same time, since they don't do a lot
# of assignments, but reuse the same memory space instead.
# mult2 should take the most time, since it does a lot of assignments.
# for each recursive call, it has to allocate memory for the returned values.
# and after the base case is met, all the values are then multiplied.
# when a function is called, it's put in the stack part of the memory
# each recursive call is going to take up a slot in the stack memory
# there is going to be a lot of assignments, and at the end, the program
# will have to extract the value from each of those stack slots.
# exercise H #7
def multpoly(list_poly):
if len(list_poly)>0:
if type(list_poly[0]) is str:
x = 0
total = ""
while (x<len(list_poly)):
total = total + list_poly[x]
x = x + 1
return total
if type(list_poly[0]) is list:
x = 0
total = []
while (x<len(list_poly)):
total.extend(list_poly[x])
x = x + 1
return total
if type(list_poly[0]) is int or type(list_poly[0]) is float:
x = 0
total = 1
while (x<len(list_poly)):
total = total * list_poly[x]
x = x + 1
return total
else:
return 1
# exercise H #8
def flatten(list1, list2=None):
if list2 == None:
list2 = []
if type(list1) is list and len(list1)>0:
if type(list1[0]) is list:
temp = list1.pop(0) + list1
return flatten(temp, list2)
else:
list2.append(list1.pop(0))
return flatten(list1, list2)
else:
return list2
# this was a tricky question.
# I wasn't able to make it work with just one variable.
# I created a global variable with an empty
# where all the non list elements would get appended to.
# unfortunately the function itself would not output a list
# i would have to print that global variable to access the new list.
# then i remembered about the reduce function
# which has a local variable already set to None
# i initially set my list2 to None, and there is an if statement that checks
# whether it's None and sets it to a list ([])
# then i append to that list whenever an element in list1 is not of type list.
# and then i send the newly updated list2 as a parameter
# for the next recursive call.
|
e6868adf0854fae59f07515b2ac384fef30d945f
|
alenaks/OSTIA
|
/code/helper.py
| 789 | 3.953125 | 4 |
def prefix(w):
''' Returns a list os prefixes of a word. '''
return [w[:i] for i in range(len(w)+1)]
def lcp(*args):
''' Finds longest common prefix of unbounded number of strings strings. '''
w = list(set(i for i in args if i != "*"))
if not w: raise IndexError("At least one non-unknown string needs to be provided.")
result = ""
n = min([len(x) for x in w])
for i in range(n):
if len(set(x[i] for x in w)) == 1: result += w[0][i]
else: break
return result
def remove_from_prefix(w, pref):
''' Removes a substring from the prefix position of another string. '''
if w.startswith(pref): return w[len(pref):]
elif w == "*": return w
else: raise ValueError(pref + " is not a prefix of " + w)
|
e7cb56a91eb062c0fd7d55e1cf5cf195434b9410
|
SA253/python-assignment
|
/Python/functions/assigment.py
| 1,964 | 3.96875 | 4 |
"""#using global
x=0
def demo():
global x
x+=1
print(x)
demo()
demo()
demo()
demo()
#lexical reference here is hello . This pattern name is "closures"
#using nonlocal scope
def outer():
i=0
def inner():
nonlocal i
i+=1
print(i)
return inner
hello=outer()
hello()
hello()
hi=outer()
hello()
hello()
hello()
hi()
hi()
hi()"""
#assignment2
def wallet():
balance=int(input("enter the balance in the wallet"))
print("balance",balance)
def deposit():
cash=int(input("enter the cash "))
print("deposit cash is",cash)
nonlocal balance
balance=balance+cash
print(balance)
d={"balance":balance,"cash":cash}
return d
#deposit()
def spent():
amount=int(input("enter the amount "))
print("amount spent is:",amount)
nonlocal balance
if balance<amount:
print("negative balance")
else:
balance=balance-amount
print("remaining amount is",balance)
d1={"balance":balance,"amount":amount}
return d2
#spent()
def savings():
nonlocal balance
print("balance available is:",balance)
#savings()
d2={"deposit":deposit,"spent":spent,"savings":savings}
return d2
def transfer():
transfer=int(input("enter the transfer amount "))
print("amount transfered is:",transfer)
nonlocal balance
if balance<transfer:
print("insufficent balance")
else:
balance=balance-transfer
print("remaining amount is",balance)
d1={"balance":balance,"amount":transfer}
return d2
money=wallet()
wallet2=wallet()
money["deposit"]()
money["spent"]()
money["savings"]()
wallet2["transfer"]()
|
898701415bb5ff3873e653a5bc871ac53a634fa7
|
DoriRunyon/Dictionary-skills-assessment
|
/advanced.py
| 3,858 | 4.3125 | 4 |
"""Advanced skills-dictionaries.
IMPORTANT: these problems are meant to be solved using dictionaries and sets.
"""
def top_characters(input_string):
"""Find most common character(s) in string.
Given an input string, return a list of character(s) which
appear(s) the most the input string.
If there is a tie, the order of the characters in the returned
list should be alphabetical.
For example:
>>> top_characters("The rain in spain stays mainly in the plain.")
['i', 'n']
If there is not a tie, simply return a list with one item.
For example:
>>> top_characters("Shake it off, shake it off. Shake it off, Shake it off.")
['f']
Do not count spaces, but count all other characters.
"""
words = input_string.split(" ")
letter_counter = {}
#count the frequency of letters, and add the key/value pairs to a dict
for word in words:
for letter in word:
if letter in letter_counter:
letter_counter[letter] += 1
else:
letter_counter[letter] = 1
list_of_words = []
#make a list out of every key/value pair in the dict, and put each 'mini list' in
#the 'list of words'
for letter, number in letter_counter.iteritems():
mini_list = [number, letter]
list_of_words.append(mini_list)
#sort the 'list of words' so that the list goes from lowest frequency, to highest
sorted_list = sorted(list_of_words)
#create a variable which is the "last letter" in the dict (the most frequent or
#one of the most frequent.)
last_letter = sorted_list[len(sorted_list)-1]
most_frequent_letters = []
#check the list to see if any other letters had the same frequency as the
#"last letter", if there are any, put them in the list. "Last letter" will be
#appended to the list last.
for mini_list in sorted_list:
if mini_list[0] == last_letter[0]:
most_frequent_letters.append(mini_list[1])
return most_frequent_letters
def adv_alpha_sort_by_word_length(words):
"""Return list of word-lengths and words.
Given a list of words, return a list of tuples, ordered by word-length.
Each tuple should have two items--a number that is a word-length,
and the list of words of that word length. In addition to ordering
the list by word length, order each sub-list of words alphabetically.
For example:
>>> adv_alpha_sort_by_word_length(["ok", "an", "apple", "a", "day"])
[(1, ['a']), (2, ['an', 'ok']), (3, ['day']), (5, ['apple'])]
"""
word_length_dict = {}
#for every word in the list, get the word length. If that "length" is already
#in the dictionary, add that word to the existing list of words for that "length".
#If the "length" is not in the dictionary, create a new key/value pair.
for word in words:
length = len(word)
if length in word_length_dict:
word_length_dict[length].append(word)
else:
word_length_dict[length] = [word]
list_of_tuples = []
#for every key/value pair in the dictionary, create a new list with two
#items, length and word list. Then make that list into a tuple and append
#the tuple to the list of tuples.
for length, word_list in word_length_dict.iteritems():
sorted_word_list = sorted(word_list)
length_and_word_list = [length, sorted_word_list]
new_tuple = tuple(length_and_word_list)
list_of_tuples.append(new_tuple)
return list_of_tuples
##############################################################################
# You can ignore everything below this.
if __name__ == "__main__":
print
import doctest
if doctest.testmod().failed == 0:
print "*** ALL TESTS PASSED ***"
print
|
12e05e1d8eef3c7b6c6fb5d220301b05767a69ba
|
remd/aoc-2018
|
/07/steps-1.py
| 1,211 | 3.5 | 4 |
from re import findall
class Step():
def __init__(self, label, ancestors=[]):
self.completed = False
self.label = label
self.ancestors = ancestors
def __str__(self):
return "{'%s':%s}" % (self.label, self.ancestors)
def available(steps):
available = []
for step in steps.values():
if not step.completed and len(step.ancestors) == 0:
available.append(step.label)
return sorted(available)
steps = {}
order = ""
f = open('input.txt', 'r')
allLabels = set()
for line in f:
ancestor, label = [s.strip() for s in findall(" [A-Z] ", line)]
allLabels.update(ancestor, label)
try:
steps[label].ancestors.append(ancestor)
except KeyError:
steps[label] = Step(label, [ancestor])
# add labels with no ancestors
for label in allLabels:
if label not in steps:
steps[label] = Step(label)
remaining = available(steps)
while len(remaining):
currentStep = remaining[0]
steps[currentStep].completed = True
for step in steps.values():
if currentStep in step.ancestors:
step.ancestors.remove(currentStep)
order += currentStep
remaining = available(steps)
print order
|
d28fab07bf7bee3251333650809ecb5d361ddfbf
|
owis1998/intersection-between-two-lines
|
/intersection_algorithm.py
| 1,749 | 4 | 4 |
class Line:
def __init__(self, p1, p2):
self.x1 = p1[0]
self.y1 = p1[1]
self.x2 = p2[0]
self.y2 = p2[1]
# linear equation: y = m.x + b, m = slope, b is level of y when x is 0, then b = y - m.x
self.m = (self.y2 - self.y1) / (self.x2 - self.x1)
self.b = self.y1 - (self.m * self.x1)
def equation(self, x):
return (self.m * x) + self.b
def is_increasing(self):
return self.m > 0
def find_intersection(line1, line2):
if line1.m > 0 and line2.m > 0:
increasing_faster, increasing_slower = (line1, line2) if line1.m > line2.m else (line2, line1)
if increasing_faster.y1 < increasing_slower.y2 and increasing_faster.x1 >= increasing_slower.x1:
if increasing_faster.equation(increasing_slower.x2) > increasing_slower.y2:
print('There is intersection')
else:
print('There is no intersection')
else:
print('There is no intersection')
elif line1.m > 0 or line2.m > 0:
increasing_faster, increasing_slower = (line1, line2) if line1.m > line2.m else (line2, line1)
if increasing_faster.y1 < increasing_slower.y1 and increasing_faster.x1 < increasing_slower.x2:
if increasing_faster.equation(increasing_slower.x2) > increasing_slower.y2:
print('There is intersection')
else:
print('There is no intersection')
else:
print('There is no intersection')
elif line1.m < 0 and line2.m < 0:
decreasing_faster, decreasing_slower = (line1, line2) if line1.m < line2.m else (line2, line1)
if decreasing_faster.y1 > decreasing_slower.y2 and decreasing_faster.x1 < decreasing_slower.x2:
if decreasing_faster.equation(decreasing_slower.x2) < decreasing_slower.y2:
print('There is intersection')
else:
print('There is no intersection')
else:
print('There is no intersection')
|
d79e0f3f38d6b3bb7bacf8d2d54338652f59d8fb
|
odira1/Comparative-Study-of-Programming-Languages
|
/guess_game/string_database.py
| 644 | 3.625 | 4 |
'''
created on may 21, 2019
@author Emmanuel Uhegbu
'''
class string_database:
"""
Encapsulates a method required to create list from text File.
"""
def _init_(self):
"""
constructs a new string_database object.
"""
def get_word(self, index):
"""
returns an item using a supplied index (random index)
from a list curated from a provided textfile
"""
words = open("four_letters.txt", "r")
contents = words.read().split()
return contents[index]
def get_db():
"""
returns an instance of string_database
"""
return string_database()
|
cca8298cf8f7ee52492d35c00d2fd2934487e65a
|
mojinming/low
|
/123.py
| 208 | 3.765625 | 4 |
c=1
while c==1:
a=int(input("请输入次数"))
for b in range(a):
if b % 7 ==0 or b%10==7:
continue
print(b)
c==input("继续请按“1”,结速请按“2”")
|
3cb7735aac37595fe9988cc1ee865fc35a000b85
|
seoul-ssafy-class-2-studyclub/GaYoung_SSAFY
|
/알고리즘/알고리즘문제/4866_괄호검사.py
| 1,610 | 3.5625 | 4 |
for t in range(int(input())):
data = input()
stack = []
result = 1
for i in range(len(data)):
if data[i] == '(':
stack.append(')')
elif data[i] == '{':
stack.append('}')
elif stack and data[i] == stack[-1]:
stack.pop()
elif data[i] == ')' or data[i] == '}':
result = 0
break
if stack:
result = 0
print('#{} {}'.format(t+1, result))
# flag 다르게 작성
# for t in range(int(input())):
# data = input()
# stack = []
# flag = 1
# for i in range(len(data)):
# if data[i] == '(':
# stack.append(')')
# elif data[i] == '{':
# stack.append('}')
# elif stack and data[i] == stack[-1]:
# stack.pop()
# elif data[i] == ')' or data[i] == '}':
# flag = 0
# break
# if stack == [] and flag:
# result = 1
# else:
# result = 0
# print('#{} {}'.format(t+1, result))
# 실패
# for t in range(int(input())):
# stack = [0] * 100
# top = -1
# data = input()
# correct = True
# for i in range(len(data)):
# if data[i] == '(' or data[i] == '{': # push
# top += 1
# stack[top] = data[i]
# elif data[i] == ')' or data[i] == '}': # pop
# if top == -1:
# correct = False
# break
# top -= 1
# if top == -1 and correct:
# result = 1
# else:
# result = 0
# print('#{} {}'.format(t + 1, result))
|
a42d74c207bf67680b7bae6dcb0d7058a8701efe
|
nuriengincatak/Python_practice
|
/practice_python/8th game rock scissors and papers.py
| 1,347 | 3.9375 | 4 |
#Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them,
# print out a message of congratulations to the winner, and ask if the players want to start a new game)
#r, s ,p
repeat='yes'
while repeat=='yes':
p1=input('Player1 please input your choice:')
p2=input('Player2 please input your choice:')
if p1==p2:
print('Draw!')
elif p1=='r' and p2=='s':
print('Player1 wins')
elif p1=='r' and p2=='p':
print('Player2 wins')
elif p1=='s' and p2=='r':
print('Player2 wins')
elif p1=='s' and p2=='p':
print('Player1 wins')
elif p1=='p' and p2=='r':
print('Player1 wins')
elif p1=='p' and p2=='s':
print('Player2 wins')
repeat=input("Do you want to play again?('yes' or 'no')")
print('Thank you for playing.')
''' first try, could not get it to run again
p1=input('Player1 please input your choice:')
p2=input('Player2 please input your choice:')
if p1==p2:
print('Draw!')
elif p1=='r' and p2=='s':
print('Player1 wins')
elif p1=='r' and p2=='p':
print('Player2 wins')
elif p1=='s' and p2=='r':
print('Player2 wins')
elif p1=='s' and p2=='p':
print('Player1 wins')
elif p1=='p' and p2=='r':
print('Player1 wins')
elif p1=='p' and p2=='s':
print('Player2 wins')
'''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.