blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
d8934ad267ed1e02c9cc609bcf333d30f90d72ef | JonasAraujoP/Python | /desafios/desafio003.py | 238 | 3.9375 | 4 | """Crie um programa que leia dois números e mostrre a soma entre eles"""
x1 = int(input('Digite um número inteiro: '))
x2 = int(input('Digite outro número inteiro: '))
soma = x1 + x2
print(f'A soma de {x1} + {x2} é igual a {soma}') |
7a07017dfad85df43dace040c37d7131bb46469d | goodmami/pydmrs | /pydmrs/matching/common.py | 1,091 | 3.546875 | 4 | def are_equal_nodes(n1, n2):
"""Returns True if nodes n1 and n2 have the same predicate and sortinfo."""
return n1.pred == n2.pred and n1.sortinfo == n2.sortinfo and n1.carg == n2.carg
def are_equal_links(l1, l2, dmrs1, dmrs2):
"""Returns True if links l1 and l2 have the same link label and their
starting and ending nodes respectively satisfy are_equal_nodes."""
if l1.label == l2.label:
if l1.rargname is None:
if (are_equal_nodes(dmrs1[l1.start], dmrs2[l2.start]) and
are_equal_nodes(dmrs1[l1.end], dmrs2[l2.end])) or (are_equal_nodes(dmrs1[l1.start], dmrs2[l2.end])
and are_equal_nodes(dmrs1[l1.end],
dmrs2[l2.start])):
return True
else:
if (are_equal_nodes(dmrs1[l1.start], dmrs2[l2.start]) and
are_equal_nodes(dmrs1[l1.end], dmrs2[l2.end])):
return True
else:
return False
|
d0fb9c93e3f84385763132287c685f56e4c26068 | calvinfroedge/Factorials | /forLoop/for.py | 272 | 4.125 | 4 | import sys
def factorial(number):
product = 1
for i in range(number):
product = product * (i + 1)
#This will also work:
#for i in range(number + 1)
# if i > 0: product = product * (i)
return product
number = int(sys.argv[1])
print(factorial(number)) |
2ac2e14b947a8e0734340f5bd08862954645c813 | SOURADEEP-DONNY/WORKING-WITH-PYTHON | /PRA practice/PRA1.py | 1,220 | 3.765625 | 4 | class Employee:
def __init__(self,employeeId,employeeName,gelnRole):
self.employeeId=employeeId
self.employeeName=employeeName
self.gelnRole=gelnRole
self.status="In Service"
class Organization:
def __init__(self,employeeList):
self.employeeList=employeeList
def updateEmployeeStatus(self,yv):
for i in self.employeeList:
if i.gelnRole > yv :
i.status="Retirement Due"
return self.employeeList
def countEmployees(self):
c=0
for i in self.employeeList:
if i.status=="Retirement Due":
c=c+1
return c
if __name__=="__main__":
c=int(input())
employeeList=[]
for i in range(c):
employeeId=int(input())
employeeName=input()
gelnRole=int(input())
o=Employee(employeeId,employeeName,gelnRole)
employeeList.append(o)
obj=Organization(employeeList)
yv=int(input())
res1=obj.updateEmployeeStatus(yv)
res=obj.countEmployees()
if res>0:
print(res)
else:
print("NO UPDATE")
for i in res1:
print(i.employeeId,i.employeeName,i.status)
|
c4167ce0440026258141ff33fb5c0ba2404938fa | Artarin/study-python-Erick-Metis | /operation_with_files/exceptions/words_counter.py | 488 | 3.96875 | 4 | """this program search and counting quontity of simple word in text.file"""
pre_path = "books_for_analysis//"
books = ["Életbölcseség.txt",
"Chambers's.txt",
"Crash Beam by John Barrett.txt"
]
for book in books:
print (book +':')
with open (pre_path+book, 'r', encoding='utf-8') as f:
text = f.read()
print (("count 'the...':") + str(text.lower().count('the')))
print (("count 'the':") + str(text.lower().count('the '))) |
ef79d66df178986222288328d66bb6daa3a4b3f1 | tanyuejiao/python_2.7_stuty | /lxf/class2.py | 1,908 | 4.125 | 4 | #!/usr/bin/python
# coding:utf-8
import types
'''获取对象信息
当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢?
使用type()
首先,我们来判断对象类型,使用type()函数:
基本类型都可以用type()判断:'''
print type(123)
# <class 'int'>
print type('str')
# <class 'str'>
print type(None)
# <type(None) 'NoneType'>
# 如果一个变量指向函数或者类,也可以用type()判断:
def abs():
pass
class Animal(object):
def __init__(self):
print "animal"
a = Animal()
print type(abs)
# <class 'builtin_function_or_method'>
print type(a)
# <class '__main__.Animal'>
# 比较两个变量的type类型是否相同:
print type(123) == type(456)
# True
print type(123) == int
# True
print type('abc') == type('123')
# True
print type('abc') == str
# True
print type('abc') == type(123)
# False
# 判断基本数据类型可以直接写int,str等,但如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量:
def fn():
pass
print type(fn) == types.FunctionType
# True
print type(abs) == types.BuiltinFunctionType
# True
print type(lambda x: x) == types.LambdaType
# True
print type((x for x in range(10))) == types.GeneratorType
# True
# 能用type()判断的基本类型也可以用isinstance()判断:
print isinstance('a', str)
# True
print isinstance(123, int)
# True
print isinstance(b'a', bytes)
# True
# 可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是list或者tuple:
print isinstance([1, 2, 3], (list, tuple))
# True
print isinstance((1, 2, 3), (list, tuple))
# True
# 使用dir()
# 如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:
print dir('ABC') |
aa321b38167013ce2065bd7ab5904d4b03531bd3 | MYMSSENDOG/leetcodes | /5342.py | 759 | 3.59375 | 4 | class ProductOfNumbers:
def __init__(self):
self.q = [0]
self.zero = 0
def add(self, num: int) -> None:
if num == 0:
self.zero = 0
else:
self.zero +=1
prev = self.q[-1]
if prev == 0:
self.q.append(num)
else:
self.q.append(prev * num)
def getProduct(self, k: int) -> int:
if self.zero < k:
return 0
if self.q[-k - 1] == 0:
return self.q[-1]
return self.q[-1] // self.q[-k - 1]
p = ProductOfNumbers()
p.add(2)
p.add(0)
p.add(2)
p.add(0)
p.add(2)
print(p.getProduct(1))
print(p.getProduct(2))
print(p.getProduct(3))
print(p.getProduct(5))
p.add(7)
p.add(6)
p.add(7)
"""
3 0 2 5 4
3 0 0 0 0
""" |
45ac29731a0cc535df4b340cb5cc8ac33d7faaef | MariaTrindade/CursoPython | /exercises/04_While/exe_07.py | 861 | 3.984375 | 4 | """
Crie um programa tabuada que permita ao usuário solicitar quantas vezes ele quiser, encerrando quando
o mesmo responder não querer mais utilizar o programa, então finalize o programa com uma mensagem de
agradecimento.
"""
from time import sleep
resposta = ''
while True:
num = int(input('Digite um número para iniciar: '))
print()
for cont in range(1, 11):
print(f'{num} x {cont:<2} = {num * cont}')
sleep(0.5)
while True:
resposta = str(input('\nTecle N para criar uma nova ou S para sair: ')).upper().strip()
if resposta not in 'NS':
print('...resposta inválida!')
if resposta == 'S':
status = True
break
if resposta == 'N':
break
if resposta == 'S':
break
print()
print('\033[32mSistema Finalizado\033[m'.center(50)) |
801ff85c4d046ed033f90f2a07f76de0f362bd7b | ColtanF/QuizGenerator | /randomQuizGenerator.py | 7,358 | 3.765625 | 4 | #! python3
# atbsRandomQuizGenerator.py - Creates quizzes with questions and answers in
# random order, along with the answer key
import random
import pyinputplus as pyip
import sys
import time
# parseCSV(filename):
# This function parses the first two items in each line of a csv into a dictionary,
# which is then returned, along with the CSV's header values.
#
# filename: the name of the csv file to be parsed
def parseCSV(filename):
# This code could be modified to support more than state/capitals
# Ideally, this code could be used for any kind of flashcard style questions
quizVals = {}
csvFile = open(filename, 'r')
keyVal = 'US State' # This is the default for the capsFile.txt
ansVal = 'US State Capital' # This is the default for the capsFile.txt
hasHeaders = pyip.inputYesNo('Does your CSV file have headers?\n')
if (hasHeaders == 'yes'):
headers = csvFile.readline()
headList = headers.split(',')
keyVal = headList[0]
ansVal = headList[1].strip()
for line in csvFile.readlines():
quizVals[line.split(',')[0]] = line.split(',')[1].strip()
return (quizVals, keyVal, ansVal)
# getAnswers(it, states):
# This code will return a tuple of answerOptions and the correct answer for
# each quiz question.
#
# it: iterated question in the current quiz
# states: list of states to choose from. This could also be cleaned up,
# this is probably not completely necessary with capitals being
# a global and states just being list(capitals.keys())
def getAnswers(it, states):
correctAnswer = capitals[states[it]]
wrongAnswers = list(capitals.values())
del wrongAnswers[wrongAnswers.index(correctAnswer)]
wrongAnswers = random.sample(wrongAnswers, 3)
answerOptions = wrongAnswers + [correctAnswer]
random.shuffle(answerOptions)
return (answerOptions, correctAnswer)
# takeQuiz(numQs):
# This function is called when the user just wants to take a quiz.
#
# numQs: the number of questions for the user's quiz
# keyVal: the key value from the CSV's header
# ansVal: the answer value from the CSV's header
def takeQuiz(numQs, keyVal, ansVal):
states = list(capitals.keys())
rightAns = 0
random.shuffle(states)
print('\nFor each of the following %ss, select the corresponding %s.\n' % (keyVal, ansVal))
for questionNum in range(numQs):
# Get the right and wrong answers.
answerOptions, correctAnswer = getAnswers(questionNum, states)
print('%s. %s:\n' % (questionNum+1, states[questionNum]))
for i in range(4):
print(' %s. %s\n' % ('ABCD'[i], answerOptions[i]))
userAns = pyip.inputMenu(['A', 'B', 'C', 'D'],prompt='')
if (userAns == 'ABCD'[answerOptions.index(correctAnswer)]):
print('Correct!')
rightAns +=1
else:
print('Incorrect.')
gradeQuiz(rightAns, numQs)
# gradeQuiz(right,total):
# This function is called after the user finishes the quiz.
# The user's grade on the quiz (P/F) is determined and
# displayed to the user.
#
# right: The number of answers the user got correct
# total: The total number of questions in the quiz
def gradeQuiz(right,total):
print('\n\nGrading quiz...')
time.sleep(2)
if (right == total):
print('PERFECT!')
elif (right/total > .6):
print('PASS.')
else:
print('FAIL.')
print('Total answers right: %s/%s (%0.2f%%)' % (right, total, right / total * 100))
# makeQuizzes(numQuizzes, numQuestions):
# This function handles generating the quiz text files for the user.
#
# numQuizzes: the number of quizzes the user wants generated
# numQuestions: the number of questions that will be on each quiz
# keyVal: the key value from the CSV's header
# ansVal: the answer value from the CSV's header
def makeQuizzes(numQuizzes, numQuestions, keyVal, ansVal):
# Generate 35 different quiz files.
for quizNum in range(numQuizzes):
# Create the quiz and answer key files
quizFile = open('generatedQuiz%s.txt' % (quizNum + 1), 'w')
answerKeyFile = open('generatedQuiz_answers%s.txt' % (quizNum + 1), 'w')
# Write out the header for the quizNum
quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizFile.write((' ' * 30) + 'Quiz (Form %s)' % (quizNum + 1))
quizFile.write('\n\n')
# Shuffle the order of the states
states = list(capitals.keys())
random.shuffle(states)
quizFile.write('\nFor each of the following %ss, select the corresponding %s.\n\n' % (keyVal, ansVal))
# Generate each question.
for questionNum in range(numQuestions):
# Get right and wrong answers.
answerOptions, correctAnswer = getAnswers(questionNum, states)
# Write the question and answer options to the quiz file
quizFile.write('%s. %s:\n' % (questionNum+1, states[questionNum]))
for i in range(4):
quizFile.write(' %s. %s\n' % ('ABCD'[i], answerOptions[i]))
quizFile.write('\n')
# Write the answer key to a file
answerKeyFile.write('%s. %s\n' % (questionNum + 1, 'ABCD'[answerOptions.index(correctAnswer)]))
quizFile.close()
answerKeyFile.close()
print("%s quizzes successfully generated." % resp)
# getDataFromFile():
# This function tries to parse data from a file that the user specifies. If the
# function is unsuccessful at parsing the user's specified file, the function
# instead parses in the default csv file.
def getDataFromFile():
# I had trouble getting the optional pyip function parameters to work, so I
# implemented my own crude version of the mustExist and limit parameters by
# using a while loop.
data = ()
fileFound = False
i = 0
while (not fileFound and i < 3):
try:
userInp = pyip.inputFilepath("Enter the name of the CSV file to parse for the quiz data:\n", blank=True)
data = parseCSV(userInp)
fileFound = True
except FileNotFoundError:
print("File to parse not found. Please enter a different file. ")
i+=1
if (not fileFound):
print("\nCould not find file. Importing US state capitals file instead...\n")
data = parseCSV('capsFile.txt')
return data
# Main program execution begins here
capitals, keyVal, ansVal = getDataFromFile()
# First, check the CLI arguments. If the user specified 'practice', let them
# take a practice quiz.
if (len(sys.argv) >= 2 and sys.argv[1].lower() == 'practice'):
print("How many questions for your quiz?")
numOfQuestions = pyip.inputNum('',max=len(capitals))
takeQuiz(numOfQuestions, keyVal, ansVal)
else:
# The user just wants to generate the quizzes. Ask them how many quizzes, and
# how many questions per quiz.
print("How many different quizzes do you need? (Please enter a number)")
resp = pyip.inputNum()
print("How many questions in each quiz?")
numOfQuestions = pyip.inputNum('',max=len(capitals))
makeQuizzes(resp, numOfQuestions, keyVal, ansVal)
|
98a3333b35be10432866b70d8c8f17041f15bdb8 | santidev10/scripts_week4 | /untitled1.py | 6,927 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 7 22:46:44 2018
learnpython2org.py
@author: santi
"""
# NUMPY ARRAYS
# Numpy arrays are great alternatives to Python Lists. Some of the key advantages
# of Numpy arrays are that they are fast, easy to work with, and give users the
# opportunity to perform calculations across entire arrays.
# In the following example, you will first create two Python lists. Then, you
# will import the numpy package and create numpy arrays out of the newly
# created lists.
#%%
# Create 2 new lists height and weight
height = [1.87, 1.87, 1.82, 1.91, 1.90, 1.85]
weight = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
# Import the numpy package as np
import numpy as np
# Create 2 numpy arrays from height and weight
np_height = np.array(height)
np_weight = np.array(weight)
# Print out the type of np_height
print(type(np_height))
# Element-wise calculations
# Now we can perform element-wise calculations on height and weight. For example,
# you could take all 6 of the height and weight observations above, and calculate
# the BMI for each observation with a single equation. These operations are very
# fast and computationally efficient. They are particularly helpful when you
# have 1000s of observations in your data.
# Calculate bmi
bmi = np_weight / np_height ** 2
print(type(bmi))
# Print the result
print(bmi)
# Subsetting
# Another great feature of Numpy arrays is the ability to subset. For instance,
# if you wanted to know which observations in our BMI array are above 23, we
# could quickly subset it to find out.
# For a boolean response
bmi > 23
# Print only those observations above 23
bmi[bmi > 23]
#%%
# Exercise
# First, convert the list of weights from a list to a Numpy array. Then,
# convert all of the weights from kilograms to pounds. Use the scalar conversion
# of 2.2 lbs per kilogram to make your conversion. Lastly, print the
# resulting array of weights in pounds.
weight_kg = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
import numpy as np
# Create a numpy array np_weight_kg from weight_kg
np_weight_kg = np.array(weight_kg)
print(np_weight_kg)
# Create np_weight_lbs from np_weight_kg
np_weight_lbs = np_weight_kg * 2.2
# Print out np_weight_lbs
print(np_weight_lbs)
#%%
# PANDAS BASICS
# Pandas DataFrames
# Pandas is a high-level data manipulation tool developed by Wes McKinney.
# It is built on the Numpy package and its key data structure is called the
# DataFrame. DataFrames allow you to store and manipulate tabular data in
# rows of observations and columns of variables.
# There are several ways to create a DataFrame. One way way is to use a
# dictionary. For example:
dict = {"country": ["Brazil", "Russia", "India", "China", "South Africa"],
"capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"],
"area": [8.516, 17.10, 3.286, 9.597, 1.221],
"population": [200.4, 143.5, 1252, 1357, 52.98] }
import pandas as pd
brics = pd.DataFrame(dict)
print(brics)
# As you can see with the new brics DataFrame, Pandas has assigned a key
# for each country as the numerical values 0 through 4. If you would like to
# have different index values, say, the two letter country code, you can do
# that easily as well.
# Set the index for brics
brics.index = ["BR", "RU", "IN", "CH", "SA"]
# Print out brics with new index values
print(brics)
#%%
# Another way to create a DataFrame is by importing a csv file using Pandas.
# Now, the csv cars.csv is stored and can be imported using pd.read_csv:
# Import pandas as pd
import pandas as pd
# Import the cars.csv data: cars
cars = pd.read_csv('cars.csv')
# Print out cars
print(cars)
#%%
# Indexing DataFrames
# There are several ways to index a Pandas DataFrame. One of the easiest ways
# to do this is by using square bracket notation.
# In the example below, you can use square brackets to select one column of
# the cars DataFrame. You can either use a single bracket or a double bracket.
# The single bracket with output a Pandas Series, while a double bracket will
# output a Pandas DataFrame.
# Import pandas and cars.csv
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
# Print out country column as Pandas Series
print(cars['cars_per_cap'])
# Print out country column as Pandas DataFrame
print(cars[['cars_per_cap']])
# Print out DataFrame with country and drives_right columns
print(cars[['cars_per_cap', 'country']])
#%%
##################################
print("\n# 7 - Dictionary to DataFrame (1):")
# https://repl.it/@andris1990/DataCamp-Intermediate-2-Dictionaries-and-Pandas
##################################
# Pre-defined lists
names = ['United States', 'Australia', 'Japan', 'India', 'Russia', 'Morocco', 'Egypt']
dr = [True, False, False, False, True, True, True]
cpc = [809, 731, 588, 18, 200, 70, 45]
# Import pandas as pd
import pandas as pd
# Create dictionary my_dict with three key:value pairs: my_dict
my_dict = {
"country":names,
"drives_right":dr,
"cars_per_cap":cpc
}
# Build a DataFrame cars from my_dict: cars
cars = pd.DataFrame(my_dict)
# Print cars
print(cars)
# Print out first 3 observations
#print(cars[0:3])
# Print out fourth, fifth and sixth observation
#print(cars[3:6])
# Print out country column as Pandas Series
print(cars['country'])
# Print out country column as Pandas DataFrame
print(cars[['country']])
# Print out DataFrame with country and drives_right columns
print(cars[['country','drives_right']])
#Square brackets can also be used to access observations (rows) from a
#DataFrame. For example:
# Print out first 3 observations
print(cars[0:3])
# Print out fourth, fifth and sixth observation
print(cars[3:6])
# You can also use loc and iloc to perform just about any data selection
# operation. loc is label-based, which means that you have to specify rows
# and columns based on their row and column labels. iloc is integer index
# based, so you have to specify rows and columns by their integer index like
# you did in the previous exercise.
# Definition of row_labels
row_labels = ['US', 'AUS', 'JAP', 'IN', 'RU', 'MOR', 'EG']
# Specify row labels of cars
cars.index = row_labels
# Print cars again
print(cars)
# Print out observation for Japan
print(cars.loc['JAP'])
print(cars.iloc[2])
# Print out observations for Australia and Egypt
print(cars.loc[['AUS','EG']])
print(cars.iloc([[1,-1]]))
# Print out drives_right value of Morocco
print(cars.loc['MOR', 'drives_right'])
# Print sub-DataFrame
print(cars.loc[['RU','MOR'],['country','drives_right']])
#%%
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
print(cars)
# Print out drives_right column as Series
print(cars.loc[:,'drives_right'])
# Print out drives_right column as DataFrame
print(cars.loc[:,['drives_right']])
# Print out cars_per_cap and drives_right as DataFrame
print(cars.loc[:,['cars_per_cap','drives_right']])
#%%
|
dfbce9470c844c17a10c601eca96b1de327e37b3 | erjan/coding_exercises | /minimum_number_of_days_to_eat_n_oranges.py | 1,738 | 3.953125 | 4 | '''
There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:
Eat one orange.
If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.
If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges.
You can only choose one of the actions per day.
Given the integer n, return the minimum number of days to eat n oranges.
'''
class Solution:
def minDays(self, n):
@lru_cache(None)
def dfs(n):
if n<=1:
return n
opt1, opt2, opt3 = float("inf"), float("inf"), float("inf")
if n%3 == 0:
opt3 = dfs(n//3)
if n%2 == 0:
opt2 = dfs(n//2)
if n%2 or n%3:
opt1 = dfs(n-1)
return min(opt1,opt2,opt3) + 1
return dfs(n)
---------------------------------------------------------------------------------------------------------
class Solution:
def minDays(self, n: int) -> int:
ans = 0
q = [n]
visit = set()
visit.add(n)
while q:
for i in range(len(q)):
num = q.pop(0)
if num == 0:
return ans
if num and (num-1) not in visit:
visit.add(num-1)
q.append(num-1)
if num % 2 == 0 and num-(num//2) not in visit:
visit.add(num-(num//2))
q.append(num-(num//2))
if num % 3 == 0 and num-2*(num//3) not in visit:
visit.add(num-2*(num//3))
q.append(num-2*(num//3))
ans += 1
|
f576082d45209e7973d17cca05ec0e82c35f1f86 | Kokonaut/fundamentals-lab-2 | /lab.py | 1,329 | 4.28125 | 4 | """
Our functions will be imported into the game engine
and used to make decisions for our sprite.
Input 'coord_name' will be in format: {letter}{number}
For example:
a3
b5
e9
etc.
Think of it like chess positions.
ie b2 will be here:
3 |
2 | x
1 |
0 |
_ _ _ _
a b c d
Given a position of our sprite, we want you to tell the sprite
what direction to go. If you don't tell it a new direction,
it will keep moving in the same direction.
For example:
If I tell the sprite to move 'up' at c0, then its movement will
look like this.
3 | ^
2 | |
1 | |
0 | -------
_ _ _ _
a b c d
Play around with it and see what you get!
"""
up = 'up'
down = 'down'
left = 'left'
right = 'right'
def lab_run_small(coord_name):
"""
This function is given to the game in run_small.py
"""
pass
# This variable is used to keep track in lab_run_med function
got_treasure = False
def lab_run_med(coord_name):
"""
This function is given to the game in run_med.py
"""
global got_treasure
pass
# These variables are used to keep track in lab_run_big function
got_treasure_1 = False
got_treasure_2 = False
def lab_run_big(coord_name):
"""
This function is given to the game in run_large.py
"""
global got_treasure_1, got_treasure_2
pass
|
aee95209d8cde11997fd95fe57ba8c2d88f4d6f1 | utsav-crypto/Coding | /array/array_3.py | 202 | 3.84375 | 4 | '''Kth MAX AND MIN ELEMENT OF AN ARRAY'''
def kth_max_min(arr, k):
pass
arr = [12, 45, 23, 24, 46, 44, 35]
result = kth_max_min(arr, 3)
print("MAX = ", result[0], "MIN = ", result[1])
|
bb7b1acaf887a82998b6dfb724606bf62c385bb3 | arovit/Coding-practise | /misc/smallest_difference.py | 480 | 3.5 | 4 | #!/usr/bin/python
def find_small_diff(a,b):
a = sorted(a)
b = sorted(b)
i = j = 0
min = 999999999999999999
min_a = 0
min_b = 0
while (i < len(a)) and (j < len(b)):
if abs(a[i]-b[j]) < min:
min = abs(a[i]-b[j])
min_a = a[i]
min_b = b[j]
if (a[i] < b[j]):
i += 1
elif (a[i] > b[j]):
j += 1
print min_a, min_b
l1 = [1,3,15,11,2]
l2 = [23,127,235,19,8]
find_small_diff(l1, l2)
|
ed0be8c5cc5d9b05f072ca45bb25e2f8d199437d | Dhanaskv/Python | /simpleInterestNormal.py | 168 | 3.859375 | 4 | #!/usr/bin/python
P=int(input("The principal amount is :"))
T=float(input("The time of periods :"))
R=float(input("The rate of interest :"))
print((P*T*R)/100)
|
c21f03eda22f80d3ea66ca52739df541edeb9634 | Seariell/basics-of-python | /hw5/task_6.py | 1,646 | 3.96875 | 4 | # homework lesson: 5, task: 6
"""
Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный предмет и наличие лекционных,
практических и лабораторных занятий по этому предмету и их количество.
Важно, чтобы для каждого предмета не обязательно были все типы занятий.
Сформировать словарь, содержащий название предмета и общее количество занятий по нему. Вывести словарь на экран.
Примеры строк файла:
Информатика: 100(л) 50(пр) 20(лаб).
Физика: 30(л) — 10(лаб)
Физкультура: — 30(пр) —
Пример словаря: {“Информатика”: 170, “Физика”: 40, “Физкультура”: 30}
"""
def my_int(string: str) -> int:
"""
Приведение строки типа 123qwerty к числу 123.
:param string: str
:return: int
"""
result = ['0']
for letter in string:
if letter.isdigit():
result.append(letter)
else:
break
result = ''.join(result)
return int(result)
with open('task_6.txt') as file:
subjects = {}
for line in file:
line = line.split()
key = line[0][0:-1]
value = 0
for word in line[1:-1]:
value += my_int(word)
subjects.update({key: value})
print(subjects)
|
a643f532c53ac1223953596bb1cd442f443020b2 | theond/leetcode_solution | /python/baseStruct/BaseArray.py | 152 | 3.578125 | 4 | # 创建字符串
s1 = str()
s2 = "improvegogogo"
#字符串长度
s2Len = len(s2)
# print(s2Len)
# 切割字符串
subS2 = s2[-3:] # 等同于s2[10:13] |
99cbe2195b5cb23a81d612beb4b265d6b3fb242e | Luid101/CSC108-assignments | /game_data.py | 19,900 | 3.75 | 4 | class Location:
def __init__(self, position, visit_points, brief_description, long_description, available_moves, items,
is_locked=False, key="", open_text="", closed_text=""):
'''
Creates a new location.
Data that could be associated with each Location object:
a position in the world map,
a brief description,
a long description,
a list of available commands/directions to move,
items that are available in the location,
and whether or not the location has been visited before.
Store these as you see fit.
This is just a suggested starter class for Location.
You may change/add parameters and the data available for each Location class as you see fit.
The only thing you must NOT change is the name of this class: Location.
All locations in your game MUST be represented as an instance of this class.
:param position: an integer value indicating the position of that location on the map
:param visit_points: number of points awarded to a player on first visiting a place
:param brief_description: a brief description of the location
:param long_description: a long description of the location
:param available_moves: a list of available moves eg: ['west','north','east']
:param items: a list of 'items' eg: [pen, cheat_sheet..]
'''
# Default variables
self.position = position
self.visit_points = visit_points
self.brief_description = brief_description
self.long_description = long_description
self.available_moves = available_moves
self.items = items
self.visited = False
self.points_given = False
# The locked attribute variables
self.is_locked = is_locked
self.key = key
self.open_text = open_text
self.closed_text = closed_text
def get_brief_description(self):
'''
Return str brief description of location.
eg:
get_brief_description(self)
"lovely"
'''
return self.brief_description
def get_full_description(self):
'''
Return str long description of location.
eg:
get_full_description(self)
"lovely"
'''
return self.long_description
def get_description(self):
"""
Return a description of the location depending on if the lactation has been visited or not
eg:
get_description(self)
"lovely"
"""
if self.visited: # if the location has been visited
return self.brief_description + "\n" + self.show_items() # print the short description
else:
self.visited = True
return self.long_description + "\n" + self.show_items() # else print long description
def show_items(self):
"""
Return a description of all the items in a location
eg:
show_items(self)
"You can see shoe"
"""
if len(self.items) > 1:
string = "You can see "
item_list = []
for item in self.items:
item_list.append(item.get_name())
string += ", ".join(item_list)
elif len(self.items) == 1:
string = "You can see "
for item in self.items:
string += item.get_name()
else:
string = "You don't see anything useful"
return string + "."
def get_items_list(self):
"""Return a description of all the items in a location in a list"""
if len(self.items) > 0:
item_list = []
for item in self.items:
item_list.append(item.get_name())
else:
return False
return item_list
def get_item(self, item_name):
"""
takes an item name and gets back the item if it exists else return false
:param item_name: the name of an item
:return: return the item if it is present and False if not
"""
if len(self.items) > 0: # if there is at least one item in that location
for element in self.items:
if element.get_name() == item_name:
return element
return False
else:
return False
def available_actions(self):
'''
-- Suggested Method (You may remove/modify/rename this as you like) --
Return list of the available actions in this location.
The list of actions should depend on the items available in the location
and the x,y position of this location on the world map.
'''
action_text = ""
action_list = []
for action in self.available_moves:
action_text += "move " + action
action_list.append(action_text)
action_text = ""
return action_list
class Item:
def __init__(self, start, target, target_points, name, exchange_item=False, exchange_with="", exchange_accepted="",
exchange_rejected=""):
'''Create item referred to by string name, with integer "start"
being the integer identifying the item's starting location,
the integer "target" being the item's target location, and
integer target_points being the number of points player gets
if item is deposited in target location.
This is just a suggested starter class for Item.
You may change these parameters and the data available for each Item class as you see fit.
Consider every method in this Item class as a "suggested method":
-- Suggested Method (You may remove/modify/rename these as you like) --
The only thing you must NOT change is the name of this class: Item.
All item objects in your game MUST be represented as an instance of this class.
'''
self.name = name
self.start = start
self.target = target
self.target_points = target_points
self.placed = False # if the item has been placed in its target location already
self.exchange_item = exchange_item # if the item is exchangeable
self.exchange_with = exchange_with # what the item is exchangeable with
self.exchange_accepted = exchange_accepted # text that will be displayed when stuff is exchanged
self.exchange_rejected = exchange_rejected # text that will be displayed when stuff cannot be exchanged
def get_starting_location (self):
'''Return int location where item is first found.'''
return self.start
def get_name(self):
'''Return the str name of the item.'''
return self.name
def get_target_location (self):
'''Return item's int target location where it should be deposited.'''
return self.target
def get_target_points (self):
'''Return int points awarded for depositing the item in its target location.'''
return self.target_points
def is_exchangable(self):
"""Return if it is exchangeable"""
return self.exchange_item
def get_exchange_item(self):
""" :return: if this item is exchangeable and what they can be exchanged with in a list."""
return [self.exchange_item, self.exchange_with]
def show_trade_text(self, PLAYER, location):
"""
Takes a player object and see's if the player has the object in its inventory,
If it does, then drop the object from the player's inventory and add this new object to it.
else don't do anything and return the rejected item text.
:param PLAYER: a player object from the Player class
:return: a string showing if the trade was successful or not
"""
if PLAYER.get_item(self.get_exchange_item()[1]): # if the player has the item we need
return [True, self.exchange_accepted] # return that the exchange has been accepted
else:
return [False, self.exchange_rejected] # return that the exchange has been rejected
def __str__(self):
"""
:return:the string representation of the item
"""
string = "name {0}, start_area {1}, target_area {2}, target_points {3}".format(self.get_name(),
self.get_starting_location(),
self.get_target_location(),
self.get_target_points())
return string
class World:
def __init__(self, mapdata="map.txt", locdata="locations.txt", itemdata="items.txt"):
'''
Creates a new World object, with a map, and data about every location and item in this game world.
You may ADD parameters/attributes/methods to this class as you see fit.
BUT DO NOT RENAME OR REMOVE ANY EXISTING METHODS/ATTRIBUTES.
:param mapdata: name of text file containing map data in grid format (integers represent each location, separated by space)
map text file MUST be in this format.
E.g.
1 -1 3
4 5 6
Where each number represents a different location, and -1 represents an invalid, inaccessible space.
:param locdata: name of text file containing location data (format left up to you)
:param itemdata: name of text file containing item data (format left up to you)
:return:
'''
self.map = self.load_map(mapdata) # The map MUST be stored in a nested list as described in the docstring for load_map() below
self.items = self.load_items(itemdata) # This data must be stored somewhere. Up to you how you choose to do it...
self.locations = self.load_locations(locdata) # This data must be stored somewhere. Up to you how you choose to do it...
def load_map(self, filename):
'''
THIS FUNCTION MUST NOT BE RENAMED OR REMOVED.
Store map from filename (map.txt) in the variable "self.map" as a nested list of integers like so:
1 2 5
3 -1 4
becomes [[1,2,5], [3,-1,4]]
RETURN THIS NEW NESTED LIST.
:param filename: string that gives name of text file in which map data is located
:return: return nested list of integers representing map of game world as specified above
>>> my_world = World()
>>> my_world.map
[[-1, -1, -1], [-1, 0, -1], [-1, 1, -1], [-1, 2, -1], [-1, -1, -1]]
'''
game_map = []
list1 = []
file = open(filename)
for line in file:
list1.append(line.strip("\n").split(" "))
for row in list1:
element_list = []
for element in row:
element_list.append(int(element))
game_map.append(element_list)
return game_map
def load_items(self, filename):
'''
Store all items from filename (items.txt) into ... whatever you think is best.
Make sure the Item class is used to represent each item.
Change this docstring accordingly.
:param filename: a file with all items and their places
:return: a dictionary with a list of items and the location number as an index
'''
items = {}
file = open(filename)
for line in file: # create a dictionary of items grouping them by...
# start_location number
if '#' not in line: # allows us to have comments in the file with '#'
item_list_original = line.strip("\n").split(".")
item_list = item_list_original[0].split(" ", 3) # create a list with each line
exchange_info = item_list_original[1]
if exchange_info != '': # if there is data for exchange
exchange_list = item_list_original[1].strip(" ").split(",") # get data from the original list
else:
exchange_list = ["False", "", "", ""]
item = Item(int(item_list[0]), # create an item object from each element in the list
int(item_list[1]),
int(item_list[2]),
item_list[3],
exchange_list[0] == "True", # returns true if the the string there is "True"
exchange_list[1].strip(" "), # send exchange_item_name
exchange_list[2].strip(" "), # send exchange_accepted text
exchange_list[3].strip(" ")) # send exchange_rejected text
if item.get_starting_location() in items: # put that item into the dict under its target location name
items[item.get_starting_location()].append(item)
else:
items[item.get_starting_location()] = []
items[item.get_starting_location()].append(item)
file.close()
return items
def get_available_directions(self, location):
"""
look at the map and figure out available move options.
:param location: a number indicating the name of a location in the map matrix
:return: a dictionary with possible locations ['west','east','north']
"""
game_map = self.map # makes things easier to read
possible_directions = []
for row in game_map:
for location2 in row:
if location == location2:
x_axis = row.index(location)
y_axis = game_map.index(row)
# The try and catch exceptions help reduce the amount of writing needed to make the map
try:
if game_map[y_axis - 1][x_axis] != -1: # check north
possible_directions.append('north')
except IndexError:
pass
try:
if game_map[y_axis + 1][x_axis] != -1: # check south
possible_directions.append('south')
except IndexError:
pass
try:
if game_map[y_axis][x_axis + 1] != -1: # check east
possible_directions.append('east')
except IndexError:
pass
try:
if game_map[y_axis][x_axis - 1] != -1: # check west
possible_directions.append('west')
except IndexError:
pass
return possible_directions
def load_locations(self, filename):
'''
Store all locations from filename (locations.txt) as a list of location
classes into the variable self.locations.
Remember to keep track of the integer number representing each location.
Make sure the Location class is used to represent each location.
Change this docstring as needed.
:param filename: file containing all locations and their details
:return: a dictionary containing all location objects grouped by location name
'''
locations_final = {} # a dictionary holding the location name and location object
locations = [] # a list containing locations stored as lists
file = open(filename) # open a file with location data stored in correct format
s = [] # populate the 'locations' list
for line in file:
if '#' not in line: # allow us to put comments in the file
if "END" in line:
locations.append(s)
s = []
else:
if line == "\n":
pass
else:
s.append(line.strip("\n"))
for element in locations: # populate the 'locations_final' list with Location...
position = int(element[0].split(" ")[1]) # objects using data from the 'locations' list
available_directions = self.get_available_directions(position)
if position in self.items: # check if a location has items, if it does, load those items...
items = self.items[position] # else load an empty list
else:
items = []
# factor in the locked variables
key = ""
open_text = ""
closed_text = ""
if len(element) > 4: # check if the list is long enough
is_locked = element[4]
if is_locked != "True": # if !is_locked change the locked variable to False
is_locked = False
else:
is_locked = True
key = element[5]
open_text = element[6]
closed_text = element[7]
else:
is_locked = False
my_location = Location( position, # create a location object with the following data
element[1],
element[2],
element[3],
available_directions,
items,
is_locked, key, open_text, closed_text) # locked variables
if position in locations_final: # put that location into the dict under its position
locations_final[position] = my_location
else:
locations_final[position] = []
locations_final[position] = my_location
file.close()
# print(locations_final)
return locations_final
def get_location(self, x, y):
'''Check if location exists at location (x,y) in world map.
Return Location object associated with this location if it does. Else, return None.
Remember, locations represented by the number -1 on the map should return None.
:param x: integer x representing x-coordinate of world map
:param y: integer y representing y-coordinate of world map
:return: Return Location object associated with this location if it does. Else, return None.
'''
if y < 0 or x < 0:
return False
else:
if y > len(self.map):
return False
else:
if x > len(self.map[y]):
return False
elif self.map[y][x] == -1:
return False
else:
return self.locations[self.map[y][x]]
# testing
"""
my_world = World()
location = my_world.get_location(2, 2)
print(location.closed_text)
"""
"""
testing items
my_world = World()
location = my_world.get_location(1, 3)
print(location.show_items())
"""
"""
# testing get_item
my_world = World()
location = my_world.get_location(1, 2)
print(location.get_item("food"))
"""
|
aca317a1acf23f9f849d00fa931bedb40e3bc805 | learnerofmuses/slotMachine | /jan29.py | 617 | 3.8125 | 4 | #In this program you will perfrom password validation. A website is
#publication the following password rules:
#1. length: at least 6 characters and no more than 10
#2. the password must include at least ONE special character
#(the character which is not a letter and not a digit)
import random
def random_string(size):
my_str = ""
for i in range(size):
num = random.randint(33, 126)
#print(num)
my_str = my_str+chr(num)
return my_str
def validPsswd(my_str):
status = False
length = len(my_str)
if(length >= 6 and length <= 10 and my_str.isalnum()==False):
status = True
return status
main
|
658af03cda8901181f8ab898d3e2553ecd3277a8 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4375/codes/1753_3089.py | 247 | 4.125 | 4 | num=int(input("digite um numero:"))
cont=0
soma=0
while(num!=0):
soma=soma+num
num=int(input("digite um numero:"))
if(soma<0):
print(soma)
print("Esquerda")
if(soma>0):
print(soma)
print("Direita")
if(soma==0):
print(soma)
print("Inicial") |
3544e13e0b4bef8b7847b2f9e03ad68026c82379 | njsqr/PythonSource | /nwzy/T1087_NO.py | 707 | 3.796875 | 4 | #!/user/bin/env python
# _*_ coding:utf-8 _*_
"""
题目描述: 统计每个元音字母在字符串中出现的次数。
输入: 输入数据首先包括一个整数n,表示测试实例的个数,然后是n行长度不超过100的字符串。
输出: 对于每个测试实例输出5行,格式如下:
a:num1
e:num2
i:num3
o:num4
u:num5
样例输入
1
aeiou
样例输出
a:1
e:1
i:1
o:1
u:1
"""
n=int(input())
num1=num2=num3=num4=num5=0
str=[]
for i in range(0,n):
str=input()
num1+=str.count('a')
num2+=str.count('e')
num3+=str.count('i')
num4+=str.count('o')
num5+=str.count('u')
print('a:%d'%num1)
print('e:%d'%num2)
print('i:%d'%num3)
print('o:%d'%num4)
print('u:%d'%num5) |
abad91436184d80839f80855cc18361b4a5bcf20 | songhuijuantianxiezuo/all | /20180819/1.py | 5,455 | 3.515625 | 4 | #c:\users\lenovo\appdata\local\programs\python
# import math
# from selenium import webdriver
# browser=webdriver.Chrome()
# browser.get('http://www.kugou.com/')
# button1=browser.find_element_by_css_selector('.searh_btn').click()
# checkbox1=browser.find_element_by_css_selector('.search_icon.checkall').click()
# button2=browser.find_element_by_css_selector('.play_all').click()
# if True:
# print ("Answer")
# print ("True")
# else:
# print ("Answer")
# print ("False") # 缩进不一致,会导致运行错误
# a=input()
# print(a)
#
# b=".....sssssssssssssssss.........."
# print(b.strip('.'))
#
# print(a+b)
# e="shdjjncjkxcmckdd"
# f=e.find(".")
# print(f)
#
# # g=e.index('.')
# # print(f)
#
# print("a"not in e)
# print(help(e.strip))
# from selenium import webdriver
# print(help(webdriver))
# import math
# print(help(math))
# import pandas as pd
# print(help(pd))
# num=35687
# if num>=0 and num<=100:
# if num>=80 and num<=100:
# print('good')
# if num>=60 and num<80:
# print('just so so')
# if num >=0 and num<60:
# print('bad')
# else:
# print('error')
# list=[1,2,3,'ee',5]
# list.pop()
# print(list)
# a='dsadsadasdadas'
# print(a[0])
# list.append(a)
# print(list)
# list1=[1,2,3,]
# # list1.extend(list)
# list=list+list1
# print(list)
# a=('a','s')
# b=('s','f')
# c=a+b
# print(type(b))
# a=(1,2,3,[1,2,3])
# # b=(1,2,3,[2,2,3])
# for i in a:
# if type(i)==class 'list':
# i[0]=2
# print(a)
# b[3][0]=3
# print(b)
# a='dfdsfdsfds'
# for i in a:
# i='1'
# print(i)
# list7=['a','s','d','g','f','h']
# i=input()
# # for a in list7:
# # if i==a:
# # print('该元素属于列表中')
# #
# # print('该元素不属于列表中')
# if i not in list7:
# print('T')
# else:
# print('F')
# a='dsadeadsa'
# i=input()
# if i in a:
# print(i)
# if
# elif
# for i in range(1,10):
# for j in range(1,10):
# if j<=i:
# print(i,' ',j,' ',i*j,end='\t') #\t空格,杠t是反斜杠
# print(' ')
# import math
# i=int(input())
# for i in range(1,11):
# if i==5:
# print(i)
# break
# a=int(input())
# i=0
# while i<11:
# if a==5:
# print('此时输入的数字是5')
# break # break跳出第一个循环
# i+=1
# for i in range(0,9):
# print('i=',i)
# for j in range(0,5):
# print('j=',j)
# if j==5:
# break
#
# for i in range(0,9):
# print('第一次',i)
# if i==5:
# continue
# print('第二次', i)
# continue 继续最内层循环;break跳出最内层循环;pass就是什么也不做,主要是为了防止语法错误
# import math
# math.sqrt()
# x=1
# while x>0:
# if math.sqrt(x+168)-math.sqrt(x+100)==int()
# print(x)
# x+=1
# break
# print(math.sqrt(10))
# append是指加列表中一个元素,extend是将两个列表连起来
# clear 清除列表中的元素;del 清除列表;copy复制列表;index取下标,传一个值,看这个值在列表中第一次出现的位置
# a=[1,2,3,4,5,6,2,3,4]
# b=[]
# for i in a:
# if i in b:
# continue
# else:
# b.append(i)
# print()
# set去除列表中的重复值
# a='safdsfsa'
# print(set(a))
# b=list(reversed(a))
# print(b)
# a.remove(2)
# b=list(a)
# b.reverse()
# a=str(b)
# print(b)
# remove只能删除列表中的元素,不能删除字符串中的单个字符
# reverse只能颠倒列表中的元素,不能颠倒字符串中的字符
# sorted排序
# a=[1,2,3,4,5,6,2,3,4]
# # print(sorted(a)) #临时性排序
# # a.sort() #永久性排序
# a.insert(20,2)
# a.append(9)
# a=a*3 #列表的乘法是列表重复出现了3次
# print(a,len(a)) #len是测列表中元素的个数
# xiaoming={1:'ddd',2:'sdsad',3:'sssssssssss'}
# print(xiaoming['a'])
# print(xiaoming.keys())
# print(xiaoming.values())
# print(xiaoming.items()) #单个组放在元组里,全部组放在列表里
# # xiaoming.clear()
# # print(xiaoming)
# # a=list(xiaoming.fromkeys([1,2,3],[4,5,6])
# # print(a)
# # xiaoming.popitem() #随即删除,不一定是删最后一个
# print(xiaoming)
# del xiaoming
# xiaoming={1:'ddd',2:'sdsad',3:'sssssssssss'}
# xiaoming[2]='ssss'
# xiaoming[4]='dddddddddd'
# print(xiaoming)
# print(len(xiaoming))
# xiaoming.popitem()
# a=str(xiaoming)
# print(a)
# 如果键重复,则后出现的值会替代前面的值,不会报错。键必须是不可变的
# i=1
# j=1
# while i<2000:
# while j<2000:
# i,j=j,j+i #将j赋值给i,将j+i赋值给j i,j=j,i #交换i和j的值
# print(i)
# import json drumps转化成JSON格式 loads由JSON格式转出
# list1=[1,2,3,4,5,6,7,8,9]
# print(list1[1:-1:2]) #-1则取不到最后一个
# list2=['w','e']
# list1.append(list2)
# list1.extend(list2)
# print(list1.count())
# list1.sort()
# list1.remove(2)
# list1.pop(1)
# list1.reverse()
# list.clear()
# print(list1)
# tuple1=('w',)
# type(tuple1)
# tuple1.index()
# list(tuple1)
# tuple(list1)
# dict1={1:2,3:4,5:6}
# dict1.popitem()
# del dict1[1]
# dict1.pop(2)
# dict1.keys()
# dict1.values()
# dict1.items()
# dict[3]
# dict1.get(3)
# dict1[3]=999
# dict[4]=223
# dict1.fromkeys([1,2,3],'hi')
# dict1.clear()
# dict1.copy()
# #dict是无序的,list是有序的 其它方面,dict的用法类似list
#set是去重
# a=[1,1,1,2,3,4]
# b=list(set(a))
# print(b)
#
|
d35f817aa4fa70bc002f45d5125fe5817c45e226 | jellywoon/lalala | /circle.py | 735 | 3.5625 | 4 | import pygame
import random
class Circle:
def __init__(self, x, y, color, radius, thickness, direction):
self.x = x
self.y = y
self.radius = radius
self.thickness = thickness
self.color = color
self.direction = direction
def make_circle(self, screen):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius, self.thickness)
def move(self):
if self.direction == 'right':
self.x += 1
if (self.x + self.radius) == 800:
self.direction = 'left'
if self.direction == 'left':
self.x -= 1
if (self.x - self.radius) == 0:
self.direction = 'right' |
ccfe736ed86399007828c7a807a2b78ab42b96f0 | amandamorris/hackerrank | /thirty_days_code/day14.py | 578 | 3.8125 | 4 | class Difference:
def __init__(self, a):
self.__elements = a
def computeDifference(self):
"""Finds the maximum difference between any two elements in
self.__elements"""
length = len(self.__elements)
max_diff = abs(self.__elements[0] - self.__elements[1])
for i in range(length):
for j in range(i+1, length):
difference = abs(self.__elements[i] - self.__elements[j])
if difference > max_diff:
max_diff = difference
self.maximumDifference = max_diff
|
655e50b2cd79d8a2aec0cc4d82c1e987266d41fa | j-hermansen/in4110 | /assignment4/4-3/instapy/__init__.py | 3,580 | 3.796875 | 4 | import cv2
import numpy as np
from numba import jit
def greyscale_image(input_filename, output_filename=None):
"""Function to read image and make it greyscale.
:param filename: image name in filepath
:return: new greyscaled 3d array that represents image
"""
image = cv2.imread(input_filename)
imageAsRGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
for i in range(len(imageAsRGB)):
for j in range(len(imageAsRGB[i])):
sum = (imageAsRGB[i, j, 0] * .29 + imageAsRGB[i, j, 1] * .72 + imageAsRGB[i, j, 2] * 0.07)
imageAsRGB[i, j, 0] = sum
imageAsRGB[i, j, 1] = sum
imageAsRGB[i, j, 2] = sum
if not (output_filename is None):
cv2.imwrite("{}.jpeg".format(output_filename), imageAsRGB)
return imageAsRGB
def greyscale_image_numpy(input_filename, output_filename=None):
"""Function to read image and make it greyscale using numpy.
:param filename: image name in filepath
:return: new greyscaled 3d array that represents image
"""
image = cv2.imread(input_filename)
imageAsRGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# imageAsRGB[:, :, 0] = (imageAsRGB[:, :, 0] * .29 + imageAsRGB[:, :, 1] * .72 + imageAsRGB[:, :, 2] * .07)
# imageAsRGB[:, :, 1] = (imageAsRGB[:, :, 0] * .29 + imageAsRGB[:, :, 1] * .72 + imageAsRGB[:, :, 2] * .07)
# imageAsRGB[:, :, 2] = (imageAsRGB[:, :, 0] * .29 + imageAsRGB[:, :, 1] * .72 + imageAsRGB[:, :, 2] * .07)
np.add(imageAsRGB[:, :, 0], (imageAsRGB[:, :, 0] * .29 + imageAsRGB[:, :, 1] * .72 + imageAsRGB[:, :, 2] * .07))
np.add(imageAsRGB[:, :, 1], (imageAsRGB[:, :, 0] * .29 + imageAsRGB[:, :, 1] * .72 + imageAsRGB[:, :, 2] * .07))
np.add(imageAsRGB[:, :, 2], (imageAsRGB[:, :, 0] * .29 + imageAsRGB[:, :, 1] * .72 + imageAsRGB[:, :, 2] * .07))
if not (output_filename is None):
cv2.imwrite("{}.jpeg".format(output_filename), imageAsRGB)
return imageAsRGB
# @jit
# def greyscale_image_numba(input_filename, output_filename=None):
# """Function to read image and make it greyscale using numba.
#
# :param filename: image name in filepath
# :return: new greyscaled 3d array that represents image
# """
# image = cv2.imread(input_filename)
# imageAsRGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# for i in range(len(imageAsRGB)):
# for j in range(len(imageAsRGB[i])):
# sum = (imageAsRGB[i, j, 0] * .29 + imageAsRGB[i, j, 1] * .72 + imageAsRGB[i, j, 2] * 0.07)
# imageAsRGB[i, j, 0] = sum
# imageAsRGB[i, j, 1] = sum
# imageAsRGB[i, j, 2] = sum
#
# if not (output_filename is None):
# cv2.imwrite("{}.jpeg".format(output_filename), imageAsRGB)
#
# return imageAsRGB
# def sepia_image(input_filename, output_filename=None):
# sepiamatrix = [[0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131]]
# image = cv2.imread(input_filename)
# # imageAsRGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
#
# (b, g, r) = cv2.split(image)
# # (r, g, b) = cv2.split(imageAsRGB)
#
# r_new = r * sepiamatrix[0][0] + g * sepiamatrix[0][1] + b * sepiamatrix[0][2]
# g_new = r * sepiamatrix[1][0] + g * sepiamatrix[1][1] + b * sepiamatrix[1][2]
# b_new = r * sepiamatrix[2][0] + g * sepiamatrix[2][1] + b * sepiamatrix[2][2]
#
# img_new = cv2.merge((b_new, g_new, r_new))
# # img_new = cv2.merge((r_new,g_new,b_new))
#
# if not (output_filename is None):
# cv2.imwrite("{}.jpeg".format(output_filename), img_new)
#
# return img_new
|
a965483570109c674e7fd291c7e4b599df2339e9 | pbarton666/learninglab | /kirby-course/py_waldo.py | 1,015 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 17 17:23:45 2017
@author: Kirby Urner
Example of the "Where's Waldo" genre:
https://i.ytimg.com/vi/SiYrSYd7mlc/maxresdefault.jpg
Extract "Waldo" from each data structure
"""
data = {"id:":["Joe", "Smith"],
"mother": ["Judy", "Smith"],
"father": ["Waldo", "Smith"]}
print(data['father'][0]) # output "Waldo"
data = {"Waldo": {"scores":[34,56,23,98,89]}}
print(list(data.keys())[0]) # output "Waldo" hint: dict.keys()
data = {(1,2):{"Name":["Waldeen", "Smith"]},
(4,5):{"Name":["Waldorf", "Smith"]},
(9,0):{"Name":["Waldo", "Smith"]}}
print(data[(9,0)]["Name"][0]) # output "Waldo" hint: tuples may be keys
first, last = data[ (9,0) ] ["Name"]
print(first)
data = ["Joe", 3, 7, ["dog", ("cat", "Waldo")], 27, {}]
print(data[3][1][1]) # output "Waldo'
# Exercises
##data = {[], [], ()}
data = [[], [], ()]
data[1].append("Wendy")
data[1].append("Waldo")
data[1].append("Willow")
# where's Waldo?
waldo = None # <your answer> |
c0a7fe91425c4319203b8bbd0e3698e75889bc90 | mihaelacr/ProjectEuler | /Problem84.py | 3,515 | 3.640625 | 4 | import random
from itertools import count
boardtxt = """go a1 cc1 a2 t1 r1 b1 ch1 b2 b3 jail c1 u1 c2 c3 r2 d1 cc2 d2 d3
fp e1 ch2 e2 e3 r3 f1 f2 u2 f3 g2j g1 g2 cc3 g3 r4 ch3 h1 t2 h2"""
board = boardtxt.split()
JAIL = board.index("jail")
GO = board.index("go")
NPLACES = len(board)
NSIDES = 4
position = 0
chances = list(range(1, 17))
chests = list(range(1, 17))
def next_starting_with(cur_position, start_match):
"""Return the next position on the board starting with a given string"""
next_idx = next(
filter(
lambda x: board[x % NPLACES].startswith(start_match),
count(cur_position + 1),
)
)
return next_idx % NPLACES
def community_chest(cur_position):
# This will take from the top and put
# to the bottom of the pile. I guess
# that affects things a bit since there
# will be a fixed gap until a card comes
# back around, but just picking randomly
# each times also gives the same results
r = chests[0]
chests.append(r)
del chests[0]
match r:
case 1:
return GO
case 2:
return JAIL
case other:
return cur_position
def chance(cur_position):
r = chances[0]
chances.append(r)
del chances[0]
match r:
case 1:
return GO
case 2:
return JAIL
case 3:
return board.index("c1")
case 4:
return board.index("e3")
case 5:
return board.index("h2")
case 6:
return board.index("r1")
case 7 | 8:
return next_starting_with(cur_position, "r")
case 9:
return next_starting_with(cur_position, "u")
case 10:
print(f"Back 3 before {board[cur_position]}")
return (cur_position - 3) % NPLACES
case _:
return cur_position
def position_effect(cur_position):
match board[cur_position]:
case "g2j":
return JAIL
case "cc1" | "cc2" | "cc3":
return community_chest(cur_position)
case "ch1" | "ch2" | "ch3":
return chance(cur_position)
case _:
return cur_position
def roll():
d1 = random.randint(1, NSIDES)
d2 = random.randint(1, NSIDES)
return d1 + d2, d1 == d2
position_counts = {p: 0 for p in board}
for game in range(10):
# Not sure shuffling really matters
random.shuffle(chances)
random.shuffle(chests)
last_three_doubles_condition = [False, False, False]
for i in range(500000):
r, dubs = roll()
last_three_doubles_condition.append(dubs)
del last_three_doubles_condition[0]
position = (position + r) % len(board)
if all(last_three_doubles_condition):
print("THREE DOUBLES :(")
position = JAIL
last_three_doubles_condition[-1] = False
position_name = board[position]
while True:
changed_position = position_effect(position)
if changed_position == position:
break
else:
position = changed_position
print(f"{i} Position changed to {board[position]}")
position_counts[board[position]] += 1
freqs = [(v / sum(position_counts.values()), k) for k, v in position_counts.items()]
sorted_freqs = sorted(freqs, reverse=True)
print("Frequencies:")
for f in sorted_freqs[:5]:
print(f[0], f[1], board.index(f[1]))
|
ca101ee61e787b02f03db74bfbce1829dcd34ede | JAreina/python | /4_py_libro_1_pydroid/venv/4_py_libro_1_pydroid/clases_objetos/py_6_herencia_sobrecarga_operadores.py | 838 | 3.90625 | 4 | class X():
def __init__(self,first,last,pay):
self.f_name = first
self.l_name = last
self.pay_amt = pay
self.full_name = first+" "+last
def make_email(self):
return self.f_name+ "."+self.l_name+"@xyz.com"
# sobrecsrga operador +
def __add__(self,other):
result = self.pay_amt+ other.pay_amt
return result
# sobrecsrga operador >
def __gt__(self,other):
return self.pay_amt>=other.pay_amt
def __str__(self):
str1 = "instance belongs to "+self.full_name
return str1
#sobrecarga #
def __len__(self):
return len(self.f_name+self.l_name)
a = X('JAreina', 'CCC', 60000)
b = X('Juan', 'DDD',70000)
print( a+b)
print( "a > b ? ",a > b)
print(a)
print(len(a)) |
359ac8fa648d7500615b8900f1481c0f6484f208 | helgirfer/EjercicioCalificaciones | /test/calificaciones_test.py | 777 | 3.5 | 4 | '''
Created on 5 oct. 2021
@author: Usuario
'''
import unittest
from main.calificaciones import calcula_nota_cuestionario
from main.calificaciones import lee_datos_cuestionario
class calificaciones_test(unittest.TestCase):
def test_calcula_nota_cuestionario(self):
aciertos, errores, respuestas = lee_datos_cuestionario()
print("el numero de aciertos introducidos es " + str(aciertos))
print("el numero de errores introducidos es " + str(errores))
print("el numero de respuestas introducidos es " + str(respuestas))
print("la nota final es " + str(calcula_nota_cuestionario( aciertos, errores, respuestas)))
if __name__ == "__main__":
unittest.main()
|
916f46b401004840eaf73094ee23f1f3ab1291e3 | JakobSonstebo/IN1900 | /Oblig/Uke 38/quadratic_roots_error.py | 1,629 | 4.25 | 4 | from math import sqrt
import sys
def find_roots(a, b, c):
"""Function that takes a, b, c and returns the roots of a the polynomial ax^2 + bx + c"""
x = (-b + sqrt(b*b - 4*a*c))/(2*a)
y = (-b - sqrt(b*b - 4*a*c))/(2*a)
return x, y
coeff = ['a', 'b', 'c'] # Prepares a list coeff consisting of 3 elements
try: # Tries to assign the cmd-line arguments
for i in range(len(coeff) + 1): # to the corresponding a, b, c in coeff.
coeff[i] = float(sys.argv[i + 1]) # If not enough arguments are provided, the
except IndexError: # list index will go out of range, provoking an
for i in range(len(coeff)): # IndexError. The program will now check whether
if isinstance(coeff[i], str): # a given element is still a string and prompt the user for
coeff[i] = float(input(f"You forgot to input a value for {coeff[i]}, try again: ")) # the missing coefficient if yes.
a, b, c = coeff
r1, r2 = find_roots(a, b, c)
print(f"r1 = {r1}, r2 = {r2}")
"""
Terminal>>python quadratic_roots_error.py 1
You forgot to input a value for b, try again: -5
You forgot to input a value for c, try again: 6
r1 = 3.0, r2 = 2.0
"""
|
46a475d3e5d82ff1f867d4a32477837691f14733 | siunixdev/python_pro_bootcamp_2021 | /day6/defining-and-calling-python-function.py | 224 | 3.5625 | 4 | # how to write function
'''
def function_name():
do this
then do this
finally do this
'''
def my_function():
print("Hello!")
def my_function2(name):
print(f"Hello {name}!")
my_function()
my_function2("Abdillah") |
de94e5c2a1da1d4a5086e7457b8770d1296e5e32 | yuan-88/Data-Structures-and-Algorithms-using-Python | /sort/selection_sort.py | 364 | 3.953125 | 4 | # Selection sort
# Author: Y.
def selection_sort(arr):
for i in range(len(arr)):
min_ind = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_ind]:
min_ind = j
arr[i], arr[min_ind] = arr[min_ind], arr[i]
if __name__=="__main__":
arr = [6, 1, 0, -2, -4, 3, 10]
selection_sort(arr)
print(arr) |
e49dda7d45bcdcfa7d03848390f72eec155fe70e | serinamarie/CS-Hash-Tables-Sprint | /applications/lookup_table/lookup_table.py | 2,083 | 3.59375 | 4 | # Your code here
import random
import math
def slowfun_too_slow(x, y):
# let v be x ^ y
v = math.pow(x, y)
# let v be v*(v-1)*(v-2)...(v-n) where (v-n) = 1
v = math.factorial(v)
# set v equal to the floor division result of the sum of x and y
v //= (x + y)
# let v be the remainder of v / 982451653
v %= 982451653
return v
# create empty dict
lookup_table = {}
def slowfun(x, y):
"""
Rewrite slowfun_too_slow() in here so that the program produces the same
output, but completes quickly instead of taking ages to run.
"""
# if key in dict:
if (x,y) in lookup_table:
# return value
return lookup_table.get(x,y)
# if key not in dict, create key/value pair
else:
# let v be x ^ y
v = math.pow(x, y)
# let v be v*(v-1)*(v-2)...(v-n) where (v-n) = 1
v = math.factorial(v)
# set v equal to the floor division result of the sum of x and y
v //= (x + y)
# let v be the remainder of v / 982451653
v %= 982451653
# add key/value pair to dict
lookup_table[(x,y)] = v
# return value
return v
# ELI5
# store values in a lookup table as there are far less combinations
# than the range, so we're bound to have the same x,y combo
# again and again(1k~ times each)
# pseudocode
# if x,y combo in dict:
# return value v for that x,y key
# if not in dict:
# do the slow stuff
# append x,y combo and v to dict
# return v
# Review: runs in 5 seconds
# Do not modify below this line!
for i in range(50000):
x = random.randrange(2, 14)
y = random.randrange(3, 6)
print(f'{i}: {x},{y}: {slowfun(x, y)}')
# if __name__ == "__main__":
# for i in range(5):
# x = random.randrange(2, 14)
# y = random.randrange(3, 6)
# print(f'{i}: {x},{y}: {slowfun(x, y)}')
# x = 5
# y = 4
# v = x + y
# z = 1
# lookup_table = {(x,y): v}
# if (x,z) in lookup_table:
# print(lookup_table.get((x,y)))
|
d8e6bbdea7e4b337dd00e78227c186fc2dd8a728 | arjun-krishna/Multi-Layered-Perceptron | /src/MLP.py | 5,874 | 3.640625 | 4 | """
@author : arjun-krishna
@desc :
The MLP class, with the methods to train and test
"""
from __future__ import print_function
import numpy as np
from mnist_reader import display_img
def sigmoid(x, derivative=False) :
if derivative :
y = sigmoid(x)
return y*(1 - y)
else :
return 1 / (1 + np.exp(-x))
def relu(x, derivative=False) :
if derivative :
return np.maximum(0, np.sign(x))
else :
return np.maximum(0, x)
def softmax(x) :
ex = np.exp((x - np.max(x)))
return ex / ex.sum(axis=0)
class MLP :
"""
config = Is the Network structure | dimensions of x,h1,h2,h3..,y in a list
activation = List of activation functions for h1, h2,..,y
Example Launch Config :
NN = MLP([4,6,2],[sigmoid, softmax])
"""
def __init__(self, config, activation) :
self.nl = len(config)
self.z = {}
self.a = {}
self.nh = self.nl - 2 # No. of Hidden Layers
for i in range(1,self.nl+1) :
self.z[i] = np.zeros((config[i-1],1))
self.a[i] = np.zeros((config[i-1],1))
self.W = {}
self.b = {}
self.init_mu = 0
self.init_sigma = 0.08
for i in range(1,self.nl) :
self.W[i] = self.init_sigma*np.random.randn(config[i],config[i-1]) + self.init_mu # Random initial weights
self.b[i] = np.zeros((config[i],1))
self.config = config
self.activation = activation
def forward_pass(self, x) :
self.a[1] = x
for i in range(1,self.nl) :
self.z[i+1] = np.dot(self.W[i],self.a[i]) + self.b[i]
self.a[i+1] = self.activation[i-1](self.z[i+1])
return self.a[self.nl]
"""
max_iteration - Maximum training iterations
freq_test_loss - The frequency with which we log the test performance.
name - The folder (in log dir) in which progress logs will be stored
alpha - Learning rate
lamda - Regularization parameter
gamma - Momentum parameter
lrf - The decay factor
lr_itr - The iteration after which decay occurs
"""
def train_mini_batch(self, data_handler,name='model_1',act='sigmoid', max_iteration=10000, freq_test_loss = 200, alpha=0.01, lamda=0.005, gamma=0.8, lrf=1.0, lr_itr=250) :
SCALER = data_handler.scaler
TEST_DATA, TEST_LABELS = data_handler.get_test_data()
TEST_DATA = SCALER.transform(TEST_DATA)
TEST_DATA = np.array(TEST_DATA).T
TEST_SIZE = len(TEST_LABELS)
BATCH_SIZE = data_handler.BATCH_SIZE
vW = {}
vb = {}
delta = {}
config_log = open('log/'+name+'/config','w')
train_loss_log = open('log/'+name+'/train_loss.csv','w')
test_loss_log = open('log/'+name+'/test_loss.csv','w')
test_acc_log = open('log/'+name+'/test_acc.csv','w')
train_loss_log.write('iteration, train_loss\n')
test_loss_log.write('iteration, test_loss\n')
test_acc_log.write('iteration, test_accuracy\n')
config_log.write('Activation = '+act+'\n')
config_log.write('Alpha = '+str(alpha)+'\n')
config_log.write('Lambda = '+str(lamda)+'\n')
print ('Training the Network')
print ('-------------------------------------------------')
for l in range(1,self.nl) :
vW[l] = np.zeros(self.W[l].shape)
vb[l] = np.zeros(self.b[l].shape)
for iteration in range(1, max_iteration+1) :
mssg = "Training Progress [{}%]".format(float(iteration*100)/max_iteration)
clear = "\b"*(len(mssg))
print(mssg, end="")
if (iteration % lr_itr == 0) :
alpha = alpha*lrf
if (iteration % freq_test_loss == 0) :
test_acc = 0.0
test_loss = 0.0
_y = self.forward_pass(TEST_DATA)
for i in range(TEST_SIZE) :
if( np.argmax(_y[:,i]) == TEST_LABELS[i] ) :
test_acc += 1
test_loss += -np.log(_y[TEST_LABELS[i],i])
test_loss /= TEST_SIZE
test_acc_log.write(str(iteration)+','+str((test_acc*100)/TEST_SIZE)+'\n')
test_loss_log.write(str(iteration)+','+str(test_loss)+'\n')
X, Y = data_handler.get_train_batch()
X = SCALER.transform(X)
_y = self.forward_pass(np.array(X).T)
train_loss = 0.0
y = np.zeros(_y.shape)
for i in range(BATCH_SIZE) :
y[Y[i]][i] = 1.0
train_loss += -np.log(_y[Y[i],i])
train_loss /= BATCH_SIZE
train_loss_log.write(str(iteration)+','+str(train_loss)+'\n')
delta[self.nl] = _y - y
for l in range(self.nl-1,1,-1) :
delta[l] = np.dot(self.W[l].T, delta[l+1])*self.activation[l-2](self.z[l], derivative=True)
for l in range(1,self.nl) :
vW[l] = (gamma*vW[l]) + (alpha * (((1.0/BATCH_SIZE)*np.dot(delta[l+1], self.a[l].T)) + lamda*self.W[l]) )
self.W[l] = self.W[l] - vW[l]
vb[l] = (gamma*vb[l]) + (alpha * (np.sum(delta[l+1], axis=1))).reshape(self.b[l].shape)
self.b[l] = self.b[l] - vb[l]
print(clear, end="")
config_log.close()
train_loss_log.close()
test_loss_log.close()
test_acc_log.close()
print ("\nTraining Completed!")
print ('-------------------------------------------------')
# self.fixed_test(data_handler, name=name)
def fixed_test(self, data_handler, name='NN_1') :
SCALER = data_handler.scaler;
X, Y = data_handler.get_fixed_test()
X_ = SCALER.transform(X)
TEST_BATCH_SIZE = data_handler.TEST_BATCH_SIZE
_y = self.forward_pass(np.array(X_).T)
for i in range(TEST_BATCH_SIZE) :
display_img(X[i], 28, 28, "log/"+name+"/random_test/"+str(i+1)+".png")
with open("log/"+name+"/random_test/"+str(i+1)+".csv", "w") as f :
f.write('class, probability\n')
for c in range(len(_y[:,i])) :
f.write(str(c)+', '+str(_y[c,i])+'\n')
def random_test(self, data_handler, name='NN_1') :
SCALER = data_handler.scaler;
X, Y = data_handler.get_test_batch()
X_ = SCALER.transform(X)
TEST_BATCH_SIZE = data_handler.TEST_BATCH_SIZE
_y = self.forward_pass(np.array(X_).T)
for i in range(TEST_BATCH_SIZE) :
display_img(X[i], 28, 28, "log/"+name+"/random_test/"+str(i+1)+".png")
with open("log/"+name+"/random_test/"+str(i+1)+".csv", "w") as f :
f.write('class, probability\n')
for c in range(len(_y[:,i])) :
f.write(str(c)+', '+str(_y[c,i])+'\n')
|
56b3d416719e531525e3809c3698dd6a56c2c447 | andrewbates09/maxit | /playmaxit.py | 5,849 | 3.734375 | 4 | #!/usr/bin/python3
#
# Author : Andrew M Bates (abates09)
#
''' IMPORTS '''
#import curses # for coloured triangulation
import os
import random
# simple cross platform clear screen
def clearScreen():
if os.name == 'posix':
os.system('clear')
else:
os.system('cls')
# print the basic intro message
def prIntro ():
clearScreen()
print('Time to play MAXIT!\n'
'Basic gameplay is as follows:\n'
' - you are player 1\n'
' - each player alternates turns\n'
' - select element in same row or colum as current position\n'
' - value of selected element gets added to player total\n'
' - selected element becomes next player position\n'
' - game ends once all sections on the grid have been selected\n'
' - highest total score wins\n')
return
# pretty print the game board
def printBoard( mboard, msize ):
print('MAXIT Board Game\n')
if (mboard==[]):
print('-- empty board --\n')
return
print(' 0 ||', end='')
for col in range(msize):
print('%4d |' %(col+1), end='')
print('\n ------', end='')
for col in range(msize):
print('------', end='')
for row in range(msize):
if (row >= 0):
print('\n%4d ||' %(row+1), end='')
for col in range(msize):
#form = '%' + str(max(msize)) + 's'
print('%4s |' %str(mboard[row][col]), end='')
print('\n')
return
# print the current player stats
def printStats( mplayers, mcurPlayer, mcurPos):
print('%s' %mplayers[0][0] + '\'s Score: %s' %mplayers[1][0])
print('%s' %mplayers[0][1] + '\'s Score: %s' %mplayers[1][1])
print('\nCurrent Player: ' + mplayers[0][mcurPlayer])
print('Current Position: [%d, ' %(mcurPos[0]) + '%d]' %(mcurPos[1]))
return
# get board size
def getSize():
is_legit = 0
while not is_legit:
try:
msize = int (input('Enter board size: ' ))
if msize > 30:
print('Don\'t be a twat. Pick a smaller size.')
elif msize > 0:
is_legit = 1
except ValueError:
print('Please enter board size as a number.')
return msize
# setup board
def setBoard( size ):
mboard = [[random.randint(-9,15) for col in range(size)] for row in range(size)]
return mboard
# check for available moves
def checkMoves( mcurPos, mboard, msize ):
for row in range(msize):
for col in range(msize):
print('- checking [%d, %d]', row, col)
if row == (mcurPos[0]-1):
print(' - - testing [%d, %d]', row, col)
if mboard[row][col] != '-':
return 1
elif col == (mcurPos[1]-1):
print(' - - testing [%d, %d]', row, col)
if mboard[row][col] != '-':
return 1
return 0
# computer AI and play
# to later be updated for different levels of difficulty
# level 0: random next move
# level 1: highest possible
# level 2: highest possible mapped out combos
def computerAI( mcurPos, mboard, msize ):
maxNum = -10
newPos = [0,0]
aiMoves = [[],[],[]]
for row in range(msize):
for col in range(msize):
if row == (mcurPos[0]-1):
if mboard[row][col] != '-':
if int(mboard[row][col]) > maxNum:
maxNum = mboard[row][col]
newPos[0] = row+1
newPos[1] = col+1
elif col == (mcurPos[1]-1):
if mboard[row][col] != '-':
if int(mboard[row][col]) > maxNum:
maxNum = mboard[row][col]
newPos[0] = row+1
newPos[1] = col+1
print('\nComputer chooses: [%s, ' %newPos[0] + '%d]' %newPos[1])
beepBoop = input('\n(press enter to continue)\n')
return newPos
# return player's selected choice
def getMove( mcurPlayer, mcurPos, mboard, msize ):
is_legit = 0
newPos = [0,0]
while not is_legit:
try:
if mcurPlayer == 1:
return computerAI(mcurPos, mboard, msize)
else:
newPos[0] = int(input('\nSelect row: '))
newPos[1] = int(input('Select column: '))
if newPos[0] == mcurPos[0]:
if mboard[newPos[0]-1][newPos[1]-1] != '-':
is_legit = 1
elif newPos[1] == mcurPos[1]:
if mboard[newPos[0]-1][newPos[1]-1] != '-':
is_legit = 1
except ValueError:
print('Hint: new [row, column] must be in same row or column from current.')
return newPos
# simply update players
def updatePlayer( mcurPlayer ):
return ( mcurPlayer + 1 ) % 2
# init players
# get board size
# build the board
# start the game
def mainMaxit():
prIntro()
# init players, scores, boardsize, board, current player, & position
players = [['Human', 'Computer'], [0, 0]]
size = getSize()
board = setBoard( size )
curPlayer = random.randint(0,1)
curPos = [random.randint(1, size), random.randint(1, size)]
gametime = 1
while gametime:
clearScreen()
printBoard(board, size)
printStats(players, curPlayer, curPos)
curPos = getMove(curPlayer, curPos, board, size)
players[1][curPlayer] += board[curPos[0]-1][curPos[1]-1]
board[curPos[0]-1][curPos[1]-1] = '-'
curPlayer = updatePlayer(curPlayer)
# check for possible moves to do.
gametime = checkMoves(curPos, board, size)
# end game stats
clearScreen()
printBoard(board, size)
printStats(players, curPlayer, curPos)
finalize = input('\nGAME OVER!\n\n(press enter to continue)')
return
|
3317a02a650c2e988e337e2c4690e6e2e54e40ac | christopher-burke/python-scripts | /cb_scripts/demo/asyncio_demo_2.py | 1,535 | 4.09375 | 4 | #!/usr/bin/env python3
"""Asyncio demo finding next prime numbers for a list."""
import asyncio
from math import sqrt
from functools import reduce
def factors(n):
"""Find all factors of a number n.
https://stackoverflow.com/questions/6800193/what-is-the-most-efficient-way-of-finding-all-the-factors-of-a-number-in-python
"""
n_factors = ([i, n//i] for i in range(1, int(sqrt(n) + 1)) if n % i == 0)
return set(reduce(list.__add__, n_factors))
def prime(n):
"""Return True if x is prime, False otherwise."""
if n == 2:
return True
if n % 2 == 0:
return False
if len(factors(n)) == 2:
return True
else:
return False
async def find_next_prime(n):
while True:
n = n + 1
if prime(n):
return n
else:
await asyncio.sleep(0.000000000001)
async def main():
next_prime_1 = loop.create_task(find_next_prime(2123123123112))
next_prime_2 = loop.create_task(find_next_prime(222))
next_prime_3 = loop.create_task(find_next_prime(45022222222))
next_prime_4 = loop.create_task(find_next_prime(1000))
await asyncio.wait([next_prime_1, next_prime_2, next_prime_3, next_prime_4, ])
return next_prime_1, next_prime_2, next_prime_3, next_prime_4
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.set_debug(1)
p1, p2, p3, p4 = loop.run_until_complete(main())
print(p1.result())
print(p2.result())
print(p3.result())
print(p4.result())
loop.close()
|
adac82f3ced96c7b3bc2f7f6b6bd41a783e04504 | josivandodosanjos/ALGO_REDES_2016_2_LISTA4 | /Lista2.2_Quest1.py | 567 | 4 | 4 | senhas = [ input("1° - Usuario Cadastre sua primeira senha: "),
input("2° - Usuario Cadastre sua segunda senha: "),
input("3° - Usuario Cadastre sua terceira senha: "),
input("4° - Usuario Cadastre sua quarta senha: ")]
input("=============LOGIN==============")
login1 = input("Nome do usuario: ")
login = input("Digite sua senha: ")
for senha in senhas:
if login == senha:
senha == login
print(login1,"==> Seja Bem Vindo!")
else:
print("Usuario Não Cadastrado!")
|
495ef8d344ab329e125ad642c6140b689c7c273d | derekfulmer/netutils | /netutils/interface.py | 4,428 | 4.15625 | 4 | """Functions for working with interface."""
from .variables import BASE_INTERFACES, REVERSE_MAPPING
def split_interface(interface):
"""Split an interface name based on first digit, slash, or space match.
Args:
interface (str): The interface you are attempting to split.
Returns:
tuple: The split between the name of the interface the value.
Example:
>>> from netutils.interface import split_interface
>>> split_interface("GigabitEthernet1/0/1")
('GigabitEthernet', '1/0/1')
>>> split_interface("Eth1")
('Eth', '1')
>>>
"""
head = interface.rstrip(r"/\0123456789. ")
tail = interface[len(head) :].lstrip() # noqa: E203
return (head, tail)
def canonical_interface_name(interface, addl_name_map=None, verify=False):
"""Function to return an interface's canonical name (fully expanded name).
Use of explicit matches used to indicate a clear understanding on any potential
match. Regex and other looser matching methods were not implemented to avoid false
positive matches. As an example, it would make sense to do "[P|p][O|o]" which would
incorrectly match PO = POS and Po = Port-channel, leading to a false positive, not
easily troubleshot, found, or known.
Args:
interface (str): The interface you are attempting to expand.
addl_name_map (dict, optional): A dict containing key/value pairs that updates the base mapping. Used if an OS has specific differences. e.g. {"Po": "PortChannel"} vs {"Po": "Port-Channel"}. Defaults to None.
verify (bool, optional): Whether or not to verify the interface matches a known interface standard. Defaults to False.
Returns:
str: The name of the interface in the long form.
Example:
>>> from netutils.interface import canonical_interface_name
>>> canonical_interface_name("Gi1/0/1")
'GigabitEthernet1/0/1'
>>> canonical_interface_name("Eth1")
'Ethernet1'
>>>
"""
name_map = {}
name_map.update(BASE_INTERFACES)
interface_type, interface_number = split_interface(interface)
if isinstance(addl_name_map, dict):
name_map.update(addl_name_map)
# check in dict for mapping
if name_map.get(interface_type):
long_int = name_map.get(interface_type)
return long_int + str(interface_number)
if verify:
raise ValueError(f"Verify interface on and no match found for {interface}")
# if nothing matched, return the original name
return interface
def abbreviated_interface_name(interface, addl_name_map=None, addl_reverse_map=None, verify=False):
"""Function to return an abbreviated representation of the interface name.
Args:
interface (str): The interface you are attempting to shorten.
addl_name_map (dict, optional): A dict containing key/value pairs that updates the base mapping. Used if an OS has specific differences. e.g. {"Po": "PortChannel"} vs {"Po": "Port-Channel"}. Defaults to None.
addl_reverse_map (dict, optional): A dict containing key/value pairs that updates the abbreviated mapping. Defaults to None.
verify (bool, optional): Whether or not to verify the interface matches a known interface standard. Defaults to False.
Returns:
str: The name of the interface in the abbreviated form.
Example:
>>> abbreviated_interface_name("GigabitEthernet1/0/1")
'Gi1/0/1'
>>> abbreviated_interface_name("Eth1")
'Et1'
>>>
"""
name_map = {}
name_map.update(BASE_INTERFACES)
interface_type, interface_number = split_interface(interface)
if isinstance(addl_name_map, dict):
name_map.update(addl_name_map)
rev_name_map = {}
rev_name_map.update(REVERSE_MAPPING)
if isinstance(addl_reverse_map, dict):
rev_name_map.update(addl_reverse_map)
# Try to ensure canonical type.
if name_map.get(interface_type):
canonical_type = name_map.get(interface_type)
else:
canonical_type = interface_type
try:
abbreviated_name = rev_name_map[canonical_type] + str(interface_number)
return abbreviated_name
except KeyError:
pass
if verify:
raise ValueError(f"Verify interface on and no match found for {interface}")
# If abbreviated name lookup fails, return original name
return interface
|
cba4a454fce841f7bb2099d818e95308e1ad80c6 | aswath1711/code-kata-player | /set5_10.py | 236 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 19 23:50:04 2019
@author: New
"""
num = int(input())
a =0
for i in range(2,num):
if num%i ==0:
a = 1
print("yes")
break
if a==0:
print("no") |
a333c94336ae9bb7131c837127266399edfb67b7 | francescaberkoh/UnitSix | /03.py | 545 | 3.90625 | 4 | '''
Created on Apr 17, 2019
@author: s271486
'''
class Information():
def __init__(self, person, address, postal_code):
self.person = person
self.address = address
self.postal_code = postal_code
user = input("Enter your name:")
useraddress = input("Enter your address:")
userpostal_code = input("Enter municipality, province and postal code:")
user_address = Information(user, useraddress, userpostal_code)
print (user_address.person + ' ' + user_address.address + " " + user_address.postal_code) |
f198c9aa582996d7a0ea6d58b44f99cd3bf7702d | 631068264/learn_science | /learn_sklearn/预处理.py | 1,675 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author = 'wyx'
@time = 2017/6/18 14:27
@annotation = ''
"""
"""
文字信息 转化为数字
"""
"""
Dealing with categorical features in Python
● scikit-learn: OneHotEncoder()
● pandas: get_dummies()
"""
"""
In [3]: df_origin = pd.get_dummies(df)
In [4]: print(df_origin.head())
mpg displ hp weight accel size origin_Asia origin_Europe \
0 18.0 250.0 88 3139 14.5 15.0 0 0
1 9.0 304.0 193 4732 18.5 20.0 0 0
2 36.1 91.0 60 1800 16.4 10.0 1 0
3 18.5 250.0 98 3525 19.0 15.0 0 0
4 34.3 97.0 78 2188 15.8 10.0 0 1
"""
"""
Using the mean of the non-missing entries
In [1]: from sklearn.preprocessing import Imputer
In [2]: imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
In [3]: imp.fit(X)
In [4]: X = imp.transform(X)
"""
"""
Why scale your data?
● Many models use some form of distance to inform them
● Features on larger scales can unduly influence the model
● Example: k-NN uses distance explicitly when making predictions
● We want features to be on a similar scale
● Normalizing (or scaling and centering)
Ways to normalize your data
● Standardization: Subtract the mean and divide by variance
● All features are centered around zero and have variance one
● Can also subtract the minimum and divide by the range
● Minimum zero and maximum one
● Can also normalize so the data ranges from -1 to +1
● See scikit-learn docs for further details
"""
"""
In [2]: from sklearn.preprocessing import scale
In [3]: X_scaled = scale(X)
In [4]: np.mean(X), np.std(X)
Out[4]: (8.13421922452, 16.7265339794)
In [5]: np.mean(X_scaled), np.std(X_scaled)
Out[5]: (2.54662653149e-15, 1.0)
"""
|
a0fd344d0c45ce50367ce78b85565d04f02987ae | kwonbora1004/python | /20200523/test.py | 355 | 3.921875 | 4 | # print("Hello World Python")
# if True:
# print("True")
# else:
# print("False")
# a = 1
# b = 2
# c = 3
# total = a + \
# b + \
# c
# print(total)
# total1 = a+ b +c
# print(total1)
# msg='안녕하세요'
# msg1="안녕하세요"
# print(msg)
# print(msg1)
''' 여러라인 주석
print(msg)
print(msg)
print(msg)
print(msg)
'''
|
2677bf06bd507748a12bb10ff3884f046c0b785f | hrushigade/learnpython | /divisiblebygivennumber.py | 194 | 3.875 | 4 | lower=int(input("enter lower range limit"))
upper=int(input("enter upper range limit"))
n=int(input("enter the no to be divided"))
for i in range(lower,upper+1):
if(i%n==0):
print(i) |
592a76ad05ac4db53930f4c886c5c4a7074f1544 | amard07/LeetCode | /ExtraCandies.py | 321 | 3.53125 | 4 | class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
max_candy_amount = max(candies)
for index in range(len(candies)):
if candies[index] + extraCandies >= max_candy_amount:
yield True
else:
yield False
|
9db6b0d09b10a43f753aab755f3ae003a92263c2 | 1158990163/PYnotebook1 | /Day02_26/test.py | 180 | 3.53125 | 4 | t=(0,0)
tps=[]
tps.append(t)
tps.append(t)
tps.append(t)
tps.append(t)
tp=[(1,2),(2,3),(3,3),(1,4)]
tp.sort()
print(tp)
print(tp[1][1])
print(tps)
for i in range(3):
print(i)
|
75d3bc79c9fb838972bb64712b36e7cd07dc411f | proRamLOGO/Competitive_Programming | /Leetcode_30DaysChallenge/1_6_Anagrams.py | 695 | 3.546875 | 4 | primes = []
def __init__primes() :
global primes
primes = [2]
isprime = [True for i in range(102) ]
for i in range(3,102,2) :
if isprime[i] :
primes.append(i)
for j in range(i*i, 102, i) :
isprime[j] = False
def groupAnagrams( strs ) :
global primes
table = {}
for i in strs :
pro = 1
for j in i :
pro *= primes[ord(j)-97]
if pro not in table.keys() :
table[pro] = []
table[pro].append(i)
ans = []
for i in table.values() :
ans.append(i)
return ans
def main() :
l = input().split()
l = groupAnagrams(l) |
9c31e7146fdf668def279997ed31a05fe2d5a8a5 | yanjieren16/coding-problem | /Flatten_Binary_Tree2LL.py | 943 | 4.0625 | 4 | """
Given a binary tree, flatten it to a linked list in-place.
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# use stack to pre-order traversal
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if root is None:
return
stack = []
if root.right:
stack.append(root.right)
if root.left:
stack.append(root.left)
pre = root
while stack:
curr = stack.pop()
pre.left = None
pre.right = curr
if curr.right:
stack.append(curr.right)
if curr.left:
stack.append(curr.left)
pre = curr
|
d7ea51cc390ba0e11e1e6c671342d210303e3632 | KerwinTy/PythonTutorial01162018 | /ARGEPARSE.py | 269 | 3.65625 | 4 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("arianne")
args = parser.parse_args()
print(args.arianne)
if args.arianne == "Maganda":
print ("Panget ako")
elif args.arianne == "Mataray":
print ("Tru")
else:
print ("Manlilibre ako") |
619d317ee55a9b7d33b6b4c01614acfd02e88e68 | mauricio208/pythonScripts | /binary-tree.py | 1,160 | 3.875 | 4 | class Tree:
def __init__(self, data=None):
self.__l = None
self.__r = None
self.data = data
def add_l(self, data):
self.__l = Tree(data)
return self.__l
def add_r(self, data):
self.__r = Tree(data)
return self.__r
def l(self):
return self.__l
def r(self):
return self.__r
def draw(self, nodes=None):
if not nodes:
nodes = [self]
str_nodes = []
new_nodes = []
for n in nodes:
str_nodes.append(n.data if n else ' ')
if n:
new_nodes.append(n.l())
new_nodes.append(n.r())
print(' '.join([str(s) for s in str_nodes]))
if new_nodes:
return self.draw(new_nodes)
def __str__(self):
l = self.__l.data if self.__l else ''
r = self.__r.data if self.__r else ''
return "-> {} \n {} {} ".format(self.data, l, r)
def __repr__(self):
return self.__str__()
if __name__ == "__main__":
t = Tree(0)
h1l=t.add_l(1)
h1r=t.add_r(2)
h2l=h1r.add_l(11)
h2l.add_l(111)
h2l.add_r(112)
|
bf9d66394a2a7b3eb4f884989e59965beb627bc3 | little-alexandra/nlp_study_group | /1_zn/zn_问答系统&文本纠错_0404/algorithm-complexity.py | 1,944 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### 时间复杂度和空间复杂度
#
# 这是任何AI工程师必须要深入理解的概念。对于每一个设计出来的算法都需要从这两个方面来分析
# O(N), O(N^2) : o notation
# In[ ]:
int a = 0, b = 0;
'''
复杂度是相对于问题的大小的,
排序算法: 问题大小是:要被排序的数组的长度
复杂度:相对于长度(正比,N^2, logN)
'''
for (i = 0; i < N; i++) {
a = a + rand();
b = b + rand();
}
##2*N = 2N O(N) 线性复杂度
for (j = 0; j < N/2; j++) {
b = b + rand(); 1
}
##1*N/2 = 1/2*N = O(N)
##100*N, 10000000000000*N = O(N)
##常数的意思就是它跟N没有依赖关系
##空间:O(1)
# 时间复杂度? 空间复杂度?
#
#
# In[ ]:
int a = 0; i,j
for (i = 0; i < N; i++) {
for (j = N; j > i; j--) {
a = a + i + j; 1
}
}
##1*N^2 = O(N^2) 时间
##常数空间复杂度O(1)
# In[ ]:
int i, j, k = 0;
for (i = n / 2; i <= n; i++) { # O(N)
for (j = 2; j <= n; j = j * 2) { # o(logN)
k = k + n / 2;
}
}
##时间: (NlogN)
##空间: 常数
##n =40
##j = 2 4 8 16 32
# In[ ]:
# In[ ]:
int a = 0, i = N;
while (i > 0) { # log N
a += i; # 1个操作
i /= 2; #1个操作
}
# In[ ]:
# 我们每当说算法X的效率要高于Y时指的是? 时间复杂度
#
# X: o(log n) > Y: o(n)
# o(n log n) > Y: o(n^2)
#
# X实际的效率(秒来) > Y实际的效率(秒) 不一定!!!
# n足够大
# In[ ]:
##定理: if x的时间复杂度要优于y的时间复杂度,那么,假设存在一个足够大的数M,当
##n>M时,我们可以保证X的实际效率要优于Y的实际效率
# In[ ]:
##X > Y 比如N=100, 实际的运行效率有可能Y是更快的。。 但是, M=10^6, N > 10^6, 我们其实可以保证X的实际效率会更高
##x asymtoitically faster than y
|
db00d30521887c638fd47b68ae6371d27f962156 | BenDosch/holbertonschool-higher_level_programming | /0x03-python-data_structures/10-divisible_by_2.py | 599 | 4.21875 | 4 | #!/usr/bin/python3
def divisible_by_2(my_list=[]):
bool_list = []
for i in range(len(my_list)):
if my_list[i] % 2:
bool_list.append(False)
else:
bool_list.append(True)
return bool_list
def main():
my_list = [0, 1, 2, 3, 4, 5, 6]
list_r = divisible_by_2(my_list)
i = 0
while i < len(list_r):
if list_r[i]:
print("{:d} {:s} divisible by 2".format(my_list[i], "is"))
else:
print("{:d} {:s} divisible by 2".format(my_list[i], "is not"))
i += 1
if __name__ == "__main__":
main()
|
380f577eef62b388224573cdbd32ca3afae27f65 | khaledshishani32/data-structures-and-algorithms-python | /linked-list-insertions/linked_list_insertions/linked_list_insertion.py | 920 | 4.1875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while temp :
print(temp.data, end="->")
temp = temp.next
def append(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
if __name__ == '__main__':
list1 = LinkedList()
list1.append(1)
list1.append(3)
list1.append(2)
list2 = LinkedList()
list2.append(5)
list2.append(9)
list2.append(4)
list3 = LinkedList()
list3.head = zipLists(list1.head, list2.head)
list3.printList() |
181b17327110aea0b12797552de8eb52f43a7038 | vasavi-test/python | /repo_commands.py | 309 | 3.5 | 4 | import re
x="hi this is vasavi. i am working in accenture 9598878675"
y=re.search('i',x)
print y.group()
if re.findall('vasavi',x)!=-1:
print "found"
else:
print "not found"
z=re.findall("\d{10}",x)
for i in z:
print i
print re.findall("^hi.*9598878675$",x)
email = "[email protected]"
ph_no = "9121244241" |
129661c6836af176101f2b3c41f835073cce406f | uniroma2-algorithms/ingegneria-algoritmi-2018 | /python/generator/fibonacci.py | 883 | 3.625 | 4 | """
File name: fibonacci.py
Author: Ovidiu Daniel Barba
Date created: 10/12/2018
Python Version: 3.7
Generator dei numeri di Fibonacci
"""
from itertools import islice
def fibGen():
"""
Generator dei numeri di Fibonacci. Rispetto all'iterator,
è una funzione
:return:
"""
prev, curr = 0, 1
while True:
yield curr # una funzione con yield è un generator
prev, curr = curr, prev + curr
if __name__ == "__main__":
fib = fibGen()
for _ in range(10): # primi 10 numeri di fibonacci
print(next(fib))
#for f in fib: # sequenza infinita
# print(f)
limited = list(islice(fib, 0, 10)) # numeri di Fibonacci da 11 a 20 (l'iterator 'ricorda' l'ultimo numero ritornato
print(limited)
def f(a, b):
return a + b
args = {'c': 1 ,'b': 2}
print(f(**args))
print(f(1,2)) |
2f5191c402c894a161091309a9b8ea7bf9cdd8cb | StephenLingham/MachineLearning | /raymondTitanicForest.py | 2,887 | 3.59375 | 4 | from sklearn.ensemble import RandomForestClassifier
import pandas
from sklearn import tree
import pydotplus
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import matplotlib.image as pltimg
import numpy as np
import types
from sklearn import metrics
from sklearn.model_selection import train_test_split
#import csv
df = pandas.read_csv("./train.csv")
# drop non useful columns
df = df.drop(columns=["PassengerId", "Name", "Ticket",
"Fare", "Cabin"])
# drop rows with any empty cells
# https://hackersandslackers.com/pandas-dataframe-drop
df.dropna(
axis=0,
how='any',
thresh=None,
subset=None,
inplace=True
)
# One-hot encode the data using pandas get_dummies
# https://towardsdatascience.com/random-forest-in-python-24d0893d51c0
df = pandas.get_dummies(df)
print(df.head())
print(df.dtypes)
# split data into "features" and "targets" aka "features" and "labels" where Labels are the values we want to predict, and features the variables we use to predict them
# Use numpy to convert label column to array of values
labels = np.array(df['Survived'])
# Remove the label column from the df
df = df.drop('Survived', axis=1)
# Saving list of feature names as numpy array
features = np.array(df)
# use train_test_split to divide the data into train and test data
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, test_size=0.01, random_state=42)
# check eveything looks right
print('Training Features Shape:', train_features.shape)
print('Training Labels Shape:', train_labels.shape)
print('Testing Features Shape:', test_features.shape)
print('Testing Labels Shape:', test_labels.shape)
# Instantiate model with 1000 decision trees
rf = RandomForestClassifier(n_estimators=1000, random_state=42)
# Train the model on training data
rf.fit(train_features, train_labels)
# generate predictions for the test data based on test features
predictions = rf.predict(test_features)
# just compare length of the test_labels with the length of the predictions to make sure they are they same
print(len(test_labels))
print(len(predictions))
# compare each actual result on the test_label list and the predicted list and populate true or false depending on if the prediction was right
results = []
for i in test_labels:
if test_labels[i] == predictions[i]:
results.append("TRUE")
else:
results.append("FALSE")
print(results)
# create dataframe of our results
dictionaryForDataFrame = {"Predicted Outcome": predictions,
"Actual Outcome": test_labels, "Prediction Successful": results}
resultsDataFrame = pandas.DataFrame(dictionaryForDataFrame)
print(resultsDataFrame)
# looks like it is pretty accurate but is there any wrong results? check if any 'falses'
print("number of falses:", results.count("FALSE"))
|
dca453c1551fd732e110706bec1465dafc93e813 | rendoir/feup-iart | /src/network.py | 8,609 | 3.515625 | 4 | import random
import numpy as np
class CrossEntropyCost(object):
@staticmethod
def fn(a, y):
"""Return the cost associated with an output ``a`` and desired output ``y``."""
return np.sum(np.nan_to_num(-y*np.log(a)-(1-y)*np.log(1-a)))
@staticmethod
def delta(z, a, y):
"""Return the error delta from the output layer."""
return (a-y)
class Network(object):
def __init__(self, sizes):
"""
The list ``sizes`` contains the number of neurons in the respective
layers of the network. The cost is a specific implementation of a generic cost function.
"""
self.num_layers = len(sizes)
self.sizes = sizes
self.init_weights()
self.cost=CrossEntropyCost
def init_weights(self):
"""
Initialize each weight using a Gaussian distribution with mean 0
and standard deviation 1 over the square root of the number of
weights connecting to the same neuron. Initialize the biases
using a Gaussian distribution with mean 0 and standard
deviation 1.
"""
self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]]
self.weights = [np.random.randn(y, x)/np.sqrt(x)
for x, y in zip(self.sizes[:-1], self.sizes[1:])]
def feedforward(self, a):
"""Return the output of the network if ``a`` is input."""
for b, w in zip(self.biases, self.weights):
a = sigmoid(np.dot(w, a)+b)
return a
def stochastic_gradient_descent(self, training_data, epochs, batch_size, learning_rate,
lmbda = 0.0,
evaluation_data=None,
monitor_evaluation_cost=False,
monitor_evaluation_accuracy=False,
monitor_training_cost=False,
monitor_training_accuracy=False):
"""
Train the neural network using batch stochastic gradient
descent. The ``training_data`` is a list of tuples ``(x, y)``
representing the training inputs and the desired outputs.
The network's hyper-parameters are:
``epochs`` -> Number of training passes
``batch_size`` -> Size of each batch
``learning_rate`` -> Size of the step in the gradient direction
``lmbda`` -> L2 regularization parameter
The method also accepts ``evaluation_data`` and flags
that allow us to monitor the cost and accuracy as the network learns.
"""
if evaluation_data: n_data = len(evaluation_data)
n = len(training_data)
evaluation_cost, evaluation_accuracy = [], []
training_cost, training_accuracy = [], []
for j in xrange(epochs):
random.shuffle(training_data)
batches = [
training_data[k:k+batch_size]
for k in xrange(0, n, batch_size)]
for batch in batches:
self.update_batch(batch, learning_rate, lmbda, len(training_data))
print "Epoch %s training complete" % j
if monitor_training_cost:
cost = self.total_cost(training_data, lmbda)
training_cost.append(cost)
print "Cost on training data: {}".format(cost)
if monitor_training_accuracy:
accuracy, msg = self.accuracy(training_data, convert=True)
training_accuracy.append(accuracy)
print "Accuracy on training data: {} / {} = {:.2f} %\n{}".format(accuracy, n, 100.0*accuracy/n, msg)
if monitor_evaluation_cost:
cost = self.total_cost(evaluation_data, lmbda, convert=True)
evaluation_cost.append(cost)
print "Cost on evaluation data: {}".format(cost)
if monitor_evaluation_accuracy:
accuracy, msg = self.accuracy(evaluation_data)
evaluation_accuracy.append(accuracy)
print "Accuracy on evaluation data: {} / {} = {:.2f} %\n{}".format(accuracy, n_data, 100.0*accuracy/n_data, msg)
print
return evaluation_cost, evaluation_accuracy, training_cost, training_accuracy
def update_batch(self, batch, learning_rate, lmbda, n):
"""
Update the network's weights and biases by applying gradient
descent using backpropagation to a single batch. The ``n``
parameter is the total size of the training data set.
"""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
for x, y in batch:
delta_nabla_b, delta_nabla_w = self.backpropagation(x, y)
nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
self.weights = [(1-learning_rate*(lmbda/n))*w-(learning_rate/len(batch))*nw
for w, nw in zip(self.weights, nabla_w)]
self.biases = [b-(learning_rate/len(batch))*nb
for b, nb in zip(self.biases, nabla_b)]
def backpropagation(self, x, y):
"""
Return a tuple ``(nabla_b, nabla_w)`` representing the
gradient for the cost function C_x.
"""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
# feedforward
activation = x
activations = [x] # list to store all the activations, layer by layer
zs = [] # list to store all the z vectors, layer by layer
for b, w in zip(self.biases, self.weights):
z = np.dot(w, activation)+b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
# backward pass
delta = (self.cost).delta(zs[-1], activations[-1], y)
nabla_b[-1] = delta
nabla_w[-1] = np.dot(delta, activations[-2].transpose())
for l in xrange(2, self.num_layers):
z = zs[-l]
sp = sigmoid_prime(z)
delta = np.dot(self.weights[-l+1].transpose(), delta) * sp
nabla_b[-l] = delta
nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())
return (nabla_b, nabla_w)
def accuracy(self, data, convert=False):
"""
Return the number of inputs in ``data`` for which the neural
network outputs the correct result.
The output of binary neural networks is the activation of the output neuron.
The output of other neural networks is assumed to be the index of whichever
neuron in the final layer has the highest activation.
"""
if self.sizes[-1] == 1:
if convert:
results = [(np.amax(self.feedforward(x)), np.amax(y))
for (x, y) in data]
else:
results = [(np.amax(self.feedforward(x)), y)
for (x, y) in data]
correct = [0,0]
total = [0,0]
for (x, y) in results:
total[y] += 1
correct[y] += int(int(round(x)) == y)
msg = " Correct positives: {} / {} = {:.2f} %\n Correct negatives = {} / {} = {:.2f} %".format(
correct[1],total[1],100.0*correct[1]/total[1],correct[0],total[0],100.0*correct[0]/total[0])
return correct[0] + correct[1], msg
else:
if convert:
results = [(np.argmax(self.feedforward(x)), np.argmax(y))
for (x, y) in data]
else:
results = [(np.argmax(self.feedforward(x)), y)
for (x, y) in data]
return sum(int(x == y) for (x, y) in results), ""
def total_cost(self, data, lmbda, convert=False):
"""Return the total cost for the data set ``data``."""
cost = 0.0
for x, y in data:
a = self.feedforward(x)
if convert: y = vectorize_result(y, self.sizes[-1])
cost += self.cost.fn(a, y)/len(data)
cost += 0.5*(lmbda/len(data))*sum(
np.linalg.norm(w)**2 for w in self.weights)
return cost
#### Miscellaneous functions
def vectorize_result(j, n_out):
"""Creates a vector from the expected result in order to compare to the output."""
res = np.zeros((n_out, 1))
if n_out == 1:
res[0] = j
else:
res[j] = 1.0
return res
def sigmoid(z):
"""The sigmoid function."""
return 1.0/(1.0+np.exp(-z))
def sigmoid_prime(z):
"""Derivative of the sigmoid function."""
return sigmoid(z)*(1-sigmoid(z))
|
c68bdf4de0eb6e6dda0a2fdc071f23edec3d6185 | falakjain98/10-Days-of-Statistics | /Day 1/Standard-Deviation.py | 300 | 3.78125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
n = int(input())
a = input()
nums=[]
for i in a.split(' '):
nums.append(int(i))
mean = sum(nums)/n
sqd = []
for i in range(n):
sqd.append((nums[i] - mean)**2)
sigma = round(math.sqrt(sum(sqd)/n),1)
print(sigma) |
2347d5071cf613004a8216fa9fb0be9b65196f09 | Vaibhav3007/Python_List | /LongestInList.py | 303 | 4.03125 | 4 | a = []
n = int(input("Enter the number of elements in list: "))
for x in range(0,n):
elements = input("Enter element" + str(x+1) + ":")
a.append(elements)
maxx = 0
for i in range(n):
if len(a[i]) > maxx:
maxx = len(a[i])
j = i
print("Longest word in the list",a,"is",a[j])
|
2b16a928176dd829c28fe2ee5c95ed94658c6008 | yashkumarsingh99/tathastu_week_of_code | /day1/Prog2.py | 132 | 4.15625 | 4 | number = float(input("Enter the number to get the square root: "))
sqrt = number ** 0.5
print("Square root of", number ,"is", sqrt)
|
3d562305318506e69eed83fe88f4676d09d57f90 | isisisisisitch/geekPython | /homework/listpractice02.py | 292 | 3.9375 | 4 | # 2. 2.1给定2个list 2.2从这2个list当中取出公共部分
#
# list1=[1,2,3,4]
#
# list2=[1,2,5]
#
# Com = [1,2]
list1=[1,2,3,4]
list2=[1,2,5]
com=[]
for i in range(len(list1)):
for j in range(len(list2)):
if list2[j]==list1[i]:
com.append(list2[j])
print(com) |
cfeb2b9d36ddfb3b7d545256ef6947293b5cea0f | aditidesai27/wacpythonwebinar | /DAY02/2.1declaring_attribute.py | 230 | 3.53125 | 4 | class Student:
def __init__(self, first, last, enroll):
self.fname = first
self.lname = last
self.roll = enroll
st1 = Student("Neeraj", "Sharma", 31)
print(st1.fname)
print(st1.lname) |
ece8b4216d88d61ec1faa60a79d6ab2b5699b7f0 | ManuelsPonce/ACC_ProgrammingClasses | /COSC1336-IntroToProgramming/Test/Test 2/2-1.py | 1,634 | 4.0625 | 4 | def main():
try:
numGrade1=float(input('Enter first grade: ')) #ASKS USER FOR 5 GRADES
numGrade2=float(input('Enter second grade: '))
numGrade3=float(input('Enter third grade: '))
numGrade4=float(input('Enter fourth grade: '))
numGrade5=float(input('Enter fifth grade: '))
print('The average test score is: ', calc_average(numGrade1, numGrade2, numGrade3, numGrade4, numGrade5)) #SENDS GRADES TO calc_average()
determine_grade(numGrade1)
print('Student one got a: ',determine_grade(numGrade1)) # PRINTS THE LETTER SCORE BY SENDING GRADES TO determine_grade()
print('Student two got a: ',determine_grade(numGrade2))
print('Student three got a: ',determine_grade(numGrade3))
print('Student four got a: ',determine_grade(numGrade4))
print('Student five got a: ',determine_grade(numGrade5))
except ValueError: #IF THERE IS A ERROR WITH USER PUTTING WRONG VALUE THIS WILL DISPLAY
print("Non-numerical value error. Use digits and '.'.")
except: #IF THERE IS ANY OTHER ERROR THIS WILL DISPLAY
print('An error occured.')
def calc_average(a,b,c,d,e):
return(a+b+c+d+e)/5 #RETURNS AN AVERAGE OF THE GRADE
def determine_grade(g):
if g>90: #USES LOGIC TO FIT THE NUMBER INTO A RANGE AND DETERMINE LETTER SCORE
return 'A'
elif g>80:
return 'B'
elif g>70:
return 'C'
elif g>60:
return 'D'
elif g<60:
return 'F'
main()
|
0a38bae9b3bc7b08f98d8f59f692170b3e393700 | JeffLutzenberger/project-euler | /20.py | 180 | 3.515625 | 4 |
def fact(n):
ans = 1
for i in range(1, n):
ans *= i
return ans
ans = fact(100)
sum_digits = 0
for i in str(ans):
sum_digits += int(i)
print(sum_digits)
|
97adf67e15070c180fe64d956d430197ae4d038e | panasabena/PythonExercises | /Ejercicio 11 Udemy de 0 a Master.py | 278 | 4.15625 | 4 | #(3) Escribir un programa que pregunte al usuario su edad y muestre
#por pantalla todos los años que ha cumplido (desde 1 hasta su edad).
edad=int(input("Ingrese su edad: "))
numero=0
while numero< edad:
numero+=1
print("Usted ha cumplido", numero, "años alguna vez")
|
6102ef9f156e84f8fdea6bf7016802a5e415e103 | KubaWasik/object-oriented-programming-python | /student.py | 4,962 | 3.953125 | 4 | class Pupil:
"""Klasa Pupil zawierająca dane o uczniu oraz jego ocenach i wagach"""
grades = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0]
def __init__(self, name="Nieznane", surname="Nieznane"):
self.name = name
self.surname = surname
self.marks = {}
@property
def name(self):
return self._name
@name.setter
def name(self, new_name):
if len(new_name) >= 3 and new_name.isalpha():
self._name = new_name
else:
print('Imię musi składać się z co najmniej 3 liter i ' +
'zawierać tylko litery\nUstawiono "Nieznane"')
self._name = "Nieznane"
@property
def surname(self):
return self._surname
@surname.setter
def surname(self, new_surname):
if len(new_surname) >= 3 and new_surname.isalpha():
self._surname = new_surname
else:
print('Nazwisko musi składać się z co najmniej 3 liter i ' +
'zawierać tylko litery\nUstawiono "Nieznane"')
self._surname = "Nieznane"
@property
def marks(self):
return self._marks
@marks.setter
def marks(self, new_marks):
tmp = {}
for mark in new_marks:
if new_marks[mark] in Pupil.grades:
tmp[mark] = new_marks[mark]
else:
print("Dla przedmiotu", mark,
"ocena była niepoprawna, nie dodano do dziennika!")
self._marks = tmp
@marks.deleter
def marks(self):
self._marks = {}
def complete_marks(self, new_marks):
tmp = {}
for mark in new_marks:
if new_marks[mark] in Pupil.grades:
tmp[mark] = new_marks[mark]
else:
print("Dla przedmiotu", mark,
"ocena była niepoprawna, nie dodano do dziennika!")
self._marks = tmp
def print_marks(self):
print("Oceny:\n")
for mark in self.marks:
print(str(mark) + ": " + str(self.marks[mark]))
def mean(self):
if self.marks:
return sum(self.marks.values()) / len(self.marks.values())
else:
return "Dziennik jest pusty!"
def __repr__(self):
values = ', '.join(('{} = {!r}'.format(k.lstrip('_'), v)
for k, v in self.__dict__.items()))
return '{}({})'.format(self.__class__.__name__, values)
def __str__(self):
description = "Imię:\t\t{0.name}\nNazwisko:\t{0.surname}\n".format(self)
description += "Średnia ocen:\t{}".format(self.mean())
return description
class Student(Pupil):
def __init__(self, name="Nieznane", surname="Nieznane", weights=None):
super().__init__(name, surname)
if weights is None:
weights = {}
self.weights = weights
@property
def weights(self):
return self._weights
@weights.setter
def weights(self, new_weights):
tmp = {}
for mark in new_weights:
if isinstance(new_weights[mark], float) and (0 < float(new_weights[mark]) <= 1):
tmp[mark] = new_weights[mark]
else:
print("Dla przedmiotu ", mark, " waga była niepoprawna, nie dodano do dziennika!")
self._weights = tmp
@weights.deleter
def weights(self):
self._weights = {}
def complete_weights(self, new_weights):
for mark in new_weights:
if 0 < new_weights[mark] <= 1:
self._weights[mark] = new_weights[mark]
else:
print("Dla przedmiotu ", mark, " waga była niepoprawna, nie dodano do dziennika!")
def mean(self):
if self.marks:
avg_sum = 0.0
avg_wei = 0.0
for mark in self.marks:
if mark in self.weights and self.weights[mark]:
avg_sum += self.marks[mark] * self.weights[mark]
avg_wei += self.weights[mark]
else:
print("Brak wagi dla przedmiotu ", mark, "\nDodaję z wagą 0.5")
avg_sum += self.marks[mark] * 0.5
avg_wei += 0.5
return avg_sum / avg_wei
else:
return "Dziennik jest pusty!"
def main():
jozef = Pupil("Jozef", "Kowalski")
jozef.marks = {
"Chemia": 4.0,
"Biologia": 3.5,
"Matematyka": 5.5,
"Informatyka": 6.0,
"WF": 5.0
}
print(jozef)
print()
frank = Student("Franciszek", "Nowak")
frank.marks = {
"Chemia": 4.0,
"Biologia": 3.5,
"Matematyka": 5.5,
"Informatyka": 6.0,
"WF": 5.0
}
frank.weights = {
"Chemia": 0.3,
"Biologia": 0.673684,
"Matematyka": 1.0,
"Informatyka": 0.987654321,
"WF": 0.4
}
print(frank)
if __name__ == "__main__":
main()
|
88b49484b94ec00a2700245de6aab09c02e5ad13 | homawccc/PythonPracticeFiles | /simple_addition.py | 155 | 3.515625 | 4 | def simple_addition(num1, num2):
answer = num1 + num2
print(answer)
simple_addition(123,456)
x = [
[2,6],[6,2],[8,2],[5,12]
]
print(x[2][0])
|
6ae8fd546159d8e5653db74c3d6469a892eb4ea3 | Colaplusice/algorithm_and_data_structure | /LeetCode/week_38/107_二叉树的层次遍历2.py | 1,645 | 3.984375 | 4 | # 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
# 例如:
# Definition for a binary tree node.
from collections import deque, defaultdict
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return root
node_list = deque()
node_list.append((root, 0))
node_dict = defaultdict(list)
node_dict[0] = [root.val]
while node_list:
current_node, node_level = node_list.popleft()
if current_node.left:
node_dict[node_level + 1].append(current_node.left.val)
node_list.append((current_node.left, node_level + 1))
if current_node.right:
node_dict[node_level + 1].append(current_node.right.val)
node_list.append((current_node.right, node_level + 1))
result = sorted(node_dict.items(), reverse=True, key=lambda x: x[0])
return list(map(lambda x: x[1], result))
# return [value for value in node_dict.values()]
if __name__ == "__main__":
atree = TreeNode(1)
btree = TreeNode(2)
ctree = TreeNode(3)
dtree = TreeNode(4)
etree = TreeNode(5)
atree.left = btree
atree.right = ctree
btree.left = dtree
ctree.right = etree
sol = Solution()
result = sol.levelOrderBottom(atree)
print(result)
|
3130937d3e55207ee020c8c35ad40b892c1d23f7 | stanislavkozlovski/python_exercises | /hackerrank/algorithms/strings/camel_case.py | 186 | 4.15625 | 4 | # https://www.hackerrank.com/challenges/camelcase
string = input()
upper_case_words = 1
for char in string:
if char.isupper():
upper_case_words += 1
print(upper_case_words)
|
9c14a4f7a72c6f7c0d7861c469d7ff5981b335e2 | nlscng/ubiquitous-octo-robot | /p000/problem-74/CountInMulitiplicatinoTable.py | 1,288 | 3.890625 | 4 | # Good morning! Here's your coding interview problem for today.
#
# This problem was asked by Apple.
#
# Suppose you have a multiplication table that is N by N. That is, a 2D array where the value at the i-th row and
# j-th column is (i + 1) * (j + 1) (if 0-indexed) or i * j (if 1-indexed).
#
# Given integers N and X, write a function that returns the number of times X appears as a value in an N by N
# multiplication table.
#
# For example, given N = 6 and X = 12, you should return 4, since the multiplication table looks like this:
#
# | 1 | 2 | 3 | 4 | 5 | 6 |
#
# | 2 | 4 | 6 | 8 | 10 | 12 |
#
# | 3 | 6 | 9 | 12 | 15 | 18 |
#
# | 4 | 8 | 12 | 16 | 20 | 24 |
#
# | 5 | 10 | 15 | 20 | 25 | 30 |
#
# | 6 | 12 | 18 | 24 | 30 | 36 |
#
# And there are 4 12's in the table.
'''
n = 2
x = 3
1 2
2 4
'''
def count_appearance(n: int, x: int) -> int:
# this is O(n) in time, O(1) in space
# assume 1-indexed
if x > n * n:
return 0
count = 0
for i in range(1, n+1):
rem = x % i
if rem == 0 and x // i <= n:
count += 1
return count
assert count_appearance(1, 1) == 1
assert count_appearance(2, 2) == 2
assert count_appearance(2, 3) == 0, "actual: {}".format(count_appearance(2, 3))
assert count_appearance(6, 12) == 4
|
05f33d7507e4025c012f35241413ccf03d5b0139 | scMarth/Learning | /python/rounding.py | 1,261 | 4.03125 | 4 | import decimal
# python by default will round down on a half decimal:
# php by default rounds up half decimals
print(0.5555)
print(round(0.5555, 3))
# https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python
num = 0.5555
dec = decimal.Decimal(num)
# rounded = dec.quantize(decimal.Decimal(0.001), rounding=decimal.ROUND_HALF_UP) # error
# rounded = dec.quantize(decimal.Decimal('0.001'), rounding=decimal.ROUND_HALF_UP) # no error 0.555
# rounded = dec.quantize(decimal.Decimal('0.001'), rounding=decimal.ROUND_UP) # no error 0.556
rounded = dec.quantize(decimal.Decimal('1.111'), rounding=decimal.ROUND_UP) # no error 0.556
print(rounded)
# NOTE: to see why there are errors, see the comment block below
test = decimal.Decimal('1.111')
test2 = decimal.Decimal(1.111)
test3 = decimal.Decimal(str(1.111))
print(test)
print(test2)
print(test3)
print(test == test3) # True
print(float(test3)) # 1.111
'''
https://stackoverflow.com/questions/588004/is-floating-point-math-broken
This is the case because of how floating point is stored with finite precision, and there are cases
where the a number cannot be exactly represented.
'''
print(0.1 + 0.2 == 0.3) # False
print(0.1 + 0.2) # prints 0.30000000000000004 |
da2e01fc589fc1c569a5fe0e4e0a7275a11d49a4 | rhkd1129/Algorithm | /inflearn/sec02/8/AA.py | 450 | 3.640625 | 4 | # 뒤집은 소수
import sys
#sys.stdin = open('input.txt', 'rt')
n = int(input())
arr = list(map(int, input().split()))
def reverse(x):
str_x = str(x)
tmp = ''
for i in range(len(str_x)):
tmp += str_x[len(str_x)-i-1]
return int(tmp)
def isPrime(x):
for i in range(2, x):
if x%i==0:
return False
return True
for i in arr:
tmp = reverse(i)
if isPrime(tmp):
print(tmp, end=' ')
|
319a09ad13f7ca9a46a22db583928752b8f109be | VilenShvedov/Myprojects | /hometask002.py | 611 | 3.8125 | 4 | '''user_number = input('Enter some number please from 1 to 100')
if int(user_number) % (3 or 5) == 0:
print(str(user_number) + ' FizzBuzz')
elif int(user_number) % (3 or 5) == 1:
print(str(user_number))
elif pint(user_number) % 3 == 0:
print(str(user_number + ' Is a fizz'))
if int(user_number) % 5 == 0:
print(str(user_number) + ' Is a buzz')'''
for num in range(0, 100):
string = ""
if num % 3 == 0:
string = string + "Fizz"
if num % 5 == 0:
string = string + "Buzz"
if num % 5 != 0 and num % 3 != 0:
string = string + str(num)
print(string) |
15827661617839596229859a1a6d99c5c20d89b3 | hershsingh/manim-dirichlet | /play.py | 10,400 | 3.921875 | 4 | #!/bin/python
###
# from manim import *
import manim
class Example(manim.Scene):
def construct(self):
circle = manim.Circle() # create a circle
circle.set_fill(manim.PINK, opacity=0.5) # set the color and transparency
anim = manim.Create(circle)
self.play( anim ) # show the circle on screen
# class Complex:
# def __init__(self, real, imag):
# # print("Inside constructor")
# self.real = real
# self.imag = imag
# def __repr__(self):
# return "{:f} + i{:f}".format(self.real, self.imag)
# def __add__(self, z):
# real = self.real + z.real
# imag = self.imag + z.imag
# return Complex(real, imag)
# class ComplexUnit(Complex):
# def __init__(self, real, imag):
# super().__init__(real, imag)
# self.norm = (self.real**2 + self.imag**2)**(0.5)
# self.real /= self.norm
# self.imag /= self.norm
# self.norm = 1.0
# def __add__(self, z):
# real = self.real + z.real
# imag = self.imag + z.imag
# return ComplexUnit(real, imag)
# x = ComplexUnit(2.0, 3.0)
# y = ComplexUnit(2.0, 3.0)
# ###
# # Complex() =>
# # 1. Allocate memory for object "x" of type "Complex"
# # 2. Call the function: Complex.__init__(x)
# # x = Complex(1.0, 2.0)
# # y = Complex(1.0, 2.0)
# # x + y => x.__add__(y)
# # x + y => add(x,y) => add_int(x, y)
# # x + y => x.add(y)
# # add(x,y)
# # add(int, int) => add_int()
# # add(float, float) => add_float()
# # add(float, int) => add_float_int()
# # add(int, float) ..
# # add(str, str) ..
# # import random
# # import numpy as np
# # import scipy as sp
# # from matplotlib import pyplot as plt
# # # vertices =[
# # # np.array([0,0, 0]),
# # # np.array([0 ,0 ,0]),
# # # np.array([4,1,0]),
# # # np.array([2 ,0 ,0])
# # # ]
# # # vertices =[
# # # np.array([-1]),
# # # np.array([0]),
# # # np.array([-4]),
# # # np.array([2])
# # # ]
# # # circle = Circle() # create a circle
# # # circle.set_fill(PINK, opacity=0.5) # set the color and transparency
# # # self.play(Create(circle)) # show the circle on screen
# # # cubicBezier = CubicBezier(*vertices)
# # # # self.play(Create(cubicBezier))
# # # p1 = np.array([-3, 1, 0])
# # # p1b = p1 + [1, 0, 0]
# # # d1 = Dot(point=p1).set_color(BLUE)
# # # l1 = Line(p1, p1b)
# # # p2 = np.array([3, -1, 0])
# # # p2b = p2 - [1, 0, 0]
# # # d2 = Dot(point=p2).set_color(RED)
# # # l2 = Line(p2, p2b)
# # # bezier = CubicBezier(p1b, p1b + 2*RIGHT + 2*UP, p2b - 3 * RIGHT, p2b)
# # # self.add(l1, d1, l2, d2, bezier)
# # # self.add(bezier)
# # # self.add(bezier)
# # # points = [p1]
# # # points += [points[-1] + 2*RIGHT+2*UP]
# # # points += [points[-1] + 1*RIGHT]
# # axes = Axes(
# # x_range=[-2, 10, 1],
# # y_range=[-2, 10, 1],
# # # x_length=10,
# # axis_config={"color": GREEN},
# # # x_axis_config={
# # # "numbers_to_include": np.arange(-10, 10.01, 2),
# # # "numbers_with_elongated_ticks": np.arange(-10, 10.01, 2),
# # # },
# # tips=False,
# # )
# # # axes_labels = axes.get_axis_labels()
# # # sin_graph = axes.get_graph(lambda x: np.sin(x), color=BLUE)
# # # cos_graph = axes.get_graph(lambda x: np.cos(x), color=RED)
# # # sin_label = axes.get_graph_label(
# # # sin_graph, "\\sin(x)", x_val=-10, direction=UP / 2
# # # )
# # # cos_label = axes.get_graph_label(cos_graph, label="\\cos(x)")
# # # vert_line = axes.get_vertical_line(
# # # axes.i2gp(TAU, cos_graph), color=YELLOW, line_func=Line
# # # )
# # # line_label = axes.get_graph_label(
# # # cos_graph, "x=2\pi", x_val=TAU, direction=UR, color=WHITE
# # # )
# # plot = VGroup(axes)
# # # labels = VGroup(axes_labels, sin_label, cos_label, line_label)
# # grid = NumberPlane((-2, 10), (-2, 10))
# # # self.add(grid)
# # # self.wait()
# # # p1 = ORIGIN
# # # points = [p1, p1 + 2*RIGHT+2*UP]
# # # handles = [[2*UP + RIGHT, -RIGHT - UP]]
# # # points += [points[-1] + 1*RIGHT]
# # # handles += [[-handles[-1][1], -RIGHT - UP]]
# # # points += [points[-1] + 1*RIGHT]
# # # handles += [[-handles[-1][1], -RIGHT - UP]]
# # # # handles += [[2*UP + RIGHT, 0*LEFT]]
# # self.x = 1
# # num_points = 2
# # def get_new_point():
# # sign = random.choice([-1,1])
# # if random.randint(0,1) == 0:
# # return [sign, random.random(), 0.0]
# # else:
# # return [random.random(), sign, 0.0]
# # # k = 0
# # # N = 10
# # origin = [1.,1.,0.]
# # def point_generator(N=10):
# # k = 0
# # r = 3
# # first = []
# # while k <= N:
# # if k==N:
# # yield first
# # x = origin[0] + r*(np.cos(k*2*np.pi/N))
# # y = origin[1] + r/2*np.sin(k*2*np.pi/N)
# # noise = np.array([random.random(), random.random(), 0.0])
# # noise = 0.2*(2*noise - 1)
# # dd = random.random()*0.5 + 0.5
# # dx = -dd*np.sin(k*2*np.pi/N)
# # dy = dd/2*np.cos(k*2*np.pi/N)
# # p = np.array([x,y,0.0])+ noise
# # dp = np.array([dx, dy, 0.0])
# # if k==0:
# # first = [p, dp]
# # k += 1
# # yield np.array([x,y,0.0])+ noise, np.array([dx, dy, 0.0])
# # N = 10
# # pts = point_generator(N=N)
# # def get_new_point():
# # return next(pts)
# # # print("points")
# # # print(next(pts))
# # # print(next(pts))
# # # print(next(pts))
# # # print(next(pts))
# # # print(next(pts))
# # # return
# # def get_dx():
# # xx= np.array([1.0, 0.3*random.random(), 0.0])
# # # return 0.4 * xx/sum(xx**2)
# # return 0.4 * xx/sum(xx**2)
# # # dx1 = RIGHT + UP
# # # last_dx = dx1 + get_dx()
# # # last_dx =
# # # bez = BezierCurve(ORIGIN, dx1, p1 + get_new_point(), last_dx )
# # x, dx = get_new_point()
# # x2, dx2 = get_new_point()
# # bez = BezierCurve(x, dx, x2, dx2)
# # # print(dx1, last_dx)
# # # bez.add_point_delta(RIGHT+UP, 0.5*(RIGHT+UP))
# # for i in range(N-1):
# # # last_dx += get_dx()
# # x,dx = get_new_point()
# # # print(i, pt)
# # bez.add_point(x, dx)
# # # last_dx += get_dx()
# # # bez.add_point_delta(get_new_point(), get_dx())
# # self.bez = bez
# # # grp = VGroup([bez.get_bezier(i) for i in range(N)])
# # # self.play(Create(grp))
# # # self.play(Create(*[bez.get_bezier(i) for i in range(N)]))
# # self.bl = [bez.get_bezier(i) for i in range(N)]
# # # self.play(Create(self.bl[0]), Create(self.bl[1]))
# # b = self.bl[0]
# # b.add(*self.bl[1:])
# # grp = VGroup(*self.bl)
# # # self.play(FadeIn(grid))
# # self.play(Create(plot), run_time=2)
# # # self.play(Create(grid))
# # self.play(Create(grp), run_time=3, rate_func=rate_functions.linear)
# # grid_config = {
# # # "axis_config": {
# # # "stroke_color": WHITE,
# # # "stroke_width": 2,
# # # "include_ticks": False,
# # # "include_tip": False,
# # # "line_to_number_buff": SMALL_BUFF,
# # # "label_direction": DR,
# # # "number_scale_val": 0.5,
# # # },
# # # "y_axis_config": {
# # # "label_direction": DR,
# # # },
# # "background_line_style": {
# # "stroke_color": BLUE_D,
# # "stroke_width": 2,
# # "stroke_opacity": 1,
# # },
# # # Defaults to a faded version of line_config
# # # "faded_line_style": None,
# # # "x_line_frequency": 1,
# # # "y_line_frequency": 1,
# # # "faded_line_ratio": 1,
# # # "make_smooth_after_applying_functions": True,}
# # }
# # grid = NumberPlane((-2, 10), (-2, 10), **grid_config)
# # self.play(FadeIn(grid))
# # # self.add(grid)
# # # Line
# # self.wait(1)
# # # for i in range(bez.get_length()-1):
# # # # for i in range(1):
# # # # self.add(bez.get_bezier(i))
# # # # self.add(*bez.get_handles(i))
# # # self.play(Create((bez.get_bezier(i))))
# # # # self.add(*bez.get_handles(i))
# # # # self.play(bez) # show the circle on screen
# # # s = Example()
# # # s.construct()
# # # print("adsd")
# # ##
# # p = np.array([3.0,2.1])
# # def check_int(p):
# # """Return 0,1,2,3 depending on whether either of (x,y) is an integer"""
# # return sum(np.isclose(p%1, 0)*[2,1])
# # def check_entry_exit(p, theta):
# # """Whether a line is entering or exiting depends on the slope"""
# # c = check_int(p)
# # if c==1: # (x,y) y is integer. Intersects horizontal grid
# # if theta>0 and theta<np.pi:
# # return 0 # entry
# # else:
# # return 1 # exit
# # elif c==2: # Intersects vertical grid
# # if theta>PI/2 and theta < (3/2)*PI:
# # return 0 # entry
# # else:
# # return 1 # exit
# # else:
# # return -1 # At a strange place
# # def get_next_bdy(p):
# # # check whether we intersect vertical or horizontal grid
# # c = check_int(p)
# # # choices = [[]]
# # print(check_int(p))
# # ###
# # n = 10
# # [1]*n + [-1]*n
|
136fd7da997780307137197a91f108864e4e3b83 | Yasin-Shah/dataquest-projects | /Project 9 - Working with Data Downloads/enrollment.py | 812 | 3.578125 | 4 | import pandas as pd
data = pd.read_csv("data/CRDC2013_14.csv", encoding = "Latin-1")
data["total_enrollment"] = data["TOT_ENR_M"] + data["TOT_ENR_F"]
all_enrollment = data["total_enrollment"].sum()
school_enrollment = [
'SCH_ENR_HI_M',
'SCH_ENR_HI_F',
'SCH_ENR_AM_M',
'SCH_ENR_AM_F',
'SCH_ENR_AS_M',
'SCH_ENR_AS_F',
'SCH_ENR_HP_M',
'SCH_ENR_HP_F',
'SCH_ENR_BL_M',
'SCH_ENR_BL_F',
'SCH_ENR_WH_M',
'SCH_ENR_WH_F',
'SCH_ENR_TR_M',
'SCH_ENR_TR_F'
]
percentages = {}
for col in school_enrollment:
percentages[col] =100 * data[col].sum() / all_enrollment
genders = ["TOT_ENR_M", "TOT_ENR_F"]
genderpercentages = {}
for col in genders:
genderpercentages[col] =100 * data[col].sum() / all_enrollment
print(percentages)
print(genderpercentages) |
83feaeb5c4761021cfff63227c09d1d64ba4f907 | JCOUO/0820 | /THE USELESS THING.py | 1,961 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 20 11:11:38 2020
@author: user
"""
d = {}
print ("THE USELESS THING EVER !!!!")
while True :
print('1.SET ')
print('2.LIST ALL THE WORD ')
print('3.ENG TO CH ')
print('4.CH TO ENG ')
print('5.TEST ')
print('6.QUIT ')
option = input(" YOUR NUM : ")
if option == '6' :
break
elif option == '1' :
while True :
voc = input('YOUR ENG (PRESS 0 TO QUIT):')
if voc == '0' :
break
if voc not in d :
voc_ch = input("ENTER CH :")
d[voc] = voc_ch
else:
print ("NOPE")
elif option == '2':
s = sorted(d)
print(s)
for i in s:
print(i,':',d[i])
elif option == '3':
while True:
voc = input ('YOUR CH (PRESS 0 TO QUIT) :')
if voc == '0':
break
if voc in d:
print(voc,'CH IS : ',d[voc])
else:
print("CAN'T FOUND THIS WORD")
elif option == '4':
while True:
got = False
ch = input("YOUR CH (PRESS 0 TO QUIT) :")
if ch == '0':
break
for k,v in d.items():
if ch == v:
print (ch,"ENG IS",k)
got = True
if got == False:
print("CAN'T FOUND THIS WORD")
elif option == '5':
s = 0
for k,v in d.items() :
print (v,':')
ans = input()
if ans == k:
s += 1
print ("YEEEA")
else:
print('NOPE')
print("YOU GOT",s)
|
4e8a1820a6a2471ad67290e96d0f6c29ea47f42e | Chalmiller/competitive_programming | /python/leetcode_top_interview_questions/dynamic_programming/jump_game.py | 536 | 3.90625 | 4 | from typing import *
import unittest
class Solution:
def canJump(self, nums: List[int]) -> bool:
max_reach, n = 0, len(nums)
for i, num in enumerate(nums):
if max_reach < i:
return False
if max_reach >= n-1:
return True
max_reach = max(max_reach, i+num)
class TestJumpGame(unittest.TestCase):
def test_can_jump(self):
nums = [3,2,1,0,4]
self.assertTrue(Solution().canJump(nums), "Should be True")
unittest.main(verbosity=2) |
031ca253207b074370573b421b1356c89274d245 | wufanwillan/leet_code | /Maximum Depth of Binary Tree.py | 1,117 | 4.03125 | 4 | # Given a binary tree, find its maximum depth.
# The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
count=1
deque1=collections.deque([root])
deque2=collections.deque([])
while True:
while True:
root=deque1.pop()
if root.left or root.right:
if root.left:
deque2.append(root.left)
if root.right:
deque2.append(root.right)
if not deque1:
break
if deque2:
count+=1
deque1,deque2=deque2,deque1
else:
break
return count
|
e0b348468128281de8f6be605b7bbaa5b0d9f521 | sarahhabershon/birdoftheyear_preferential_voting | /preferential_voting.py | 2,056 | 3.578125 | 4 | import csv
import copy
import codecs
data = open('votes_all.csv', encoding="utf8")
vote_list = csv.reader(data)
finalScores = []
def cleanData(x):
clean_birds = []
for row in x:
length = len(row)
makeListsEqualLength(row, length)
clean_birds.append(row)
return clean_birds
def makeListsEqualLength(row, length):
x = 0
req = 6 - length
while x < req:
row.append("novote")
x+=1
def createScoreboard(x):
scoreDict = {}
for vote in x:
isitthere = scoreDict.get(vote[1], False)
if isitthere == False:
scoreDict[vote[1]] = 1
else:
scoreDict[vote[1]] +=1
return scoreDict
def youAreTheWeakestLink(x, y):
global finalScores
localcopy = copy.deepcopy(x) # create a local copy of the scoreboard dict
for burd, score in localcopy.items(): #for each bird in the copy
minvalue = min(x.values()) #find the bird with the lowest score
if score == minvalue: #check the score to see if it's the lowest scoring bird
loser = burd #if it is, it's the loser
finalScores.append([burd, score])# add its final score to the finalscore object
del x[burd] #deletes the loser from the scoreboard
contender = nextPlease(y, burd) #identifies the next contender
levelUp(x, contender) #adds a vote to the second preference
return(finalScores)
def nextPlease(votes, loser):
for vote in votes:
if vote[1] == loser:
del vote[0]
vote.append("novote")
return vote[1]
def levelUp(x, contender):
if contender in x:
x[contender] += 1
def burdIsTheWord(x, y):
minvalue = min(x.values())
while len(x) > 0:
youAreTheWeakestLink(x, y)
cleanVoteList = cleanData(vote_list)
scoreboard = createScoreboard(cleanVoteList)
burdIsTheWord(scoreboard,cleanVoteList)
# with open('birdoftheyear.csv', "w", "utf-8-sig", newline="") as csv_file:
# writer = csv.writer(csv_file)
# for bird in finalScores:
# writer.writerow([bird[0], bird[1]])
with codecs.open("birdoftheyear.csv", "w", "utf-8-sig") as csv_file:
writer = csv.writer(csv_file)
for bird in finalScores:
writer.writerow([bird[0], bird[1]]) |
b56ef0e786627a2a5edcb4329c52795a9713bcfd | WeDias/RespCEV | /Exercicios-Mundo2/ex049.py | 172 | 3.953125 | 4 | num1 = int(input('Digite Um Numero Para Ver Sua Tabuada:'))
num2 = 0
for num2 in range(1, 11):
mult = num1 * num2
print('{}X{} = {}'.format(num1, num2, mult))
|
1ed76c415eb2d7d1081a6bd1793c24257d91494f | liweiwei1419/Machine-Learning-is-Fun | /Mathematics-learning/fibonacci_demo.py | 625 | 4 | 4 | class Fibonacci(object):
''' 返回一个 fibonacci 数列'''
def __init__(self):
self.fList = [0, 1] # 设置初始的列表
self.main()
def main(self):
listLen = input("请输入的 fibonacci 数列的长度:")
while len((self.fList)) < int(listLen):
self.fList.append(self.fList[-1] + self.fList[-2])
print("得到的 Fibonacci 数列为:\n %s" % self.fList)
def checkLen(self,lenth):
lenList = map(str,range(3,51))
for item in lenList:
print(item)
if __name__ == '__main__':
f = Fibonacci()
f.checkLen(10)
|
11d30722b9e1bcefe29127ad51752c47d12b6d81 | FelixZFB/Python_advanced_learning | /02_Python_advanced_grammar_supplement/001_9_高级语法(魔法属性-init-module-class-call)/002_魔法属性__call__str__方法.py | 760 | 4.09375 | 4 | # __call__方法:实例化对象后面加括号,触发执行。
# 注:__init__方法的执行是由创建对象自动触发的,即:对象 = 类名() ;
# 而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
class Foo(object):
def __init__(self):
pass
def __call__(self, *args, **kwargs):
print("__call__")
def __str__(self):
return "获取对象描述时候自动调用"
obj = Foo() # 自动执行__init__方法
obj() # 执行__call__方法
# __str__获取对象描述时候自动调用,有以下两种方式调用对象描述
# 方式1:直接打印对象,返回__str__的返回值
print(obj)
# 方式2: 使用格式化输出
print("方式2:%s" % obj) |
44a84208fbff9098bfa62e57c0e815a42bfa2bf1 | kthdd1234/basic-python-syntax | /class instance.py | 839 | 3.9375 | 4 | # 클래스(class): 함수나 변수들을 모아 놓은 집합체
# 인스턴스(instance): 클래스에 의해 생성된 객체, 인스턴스 각자 자신의 값을 가지고 있다.
numbers1 = []
numbers2 = list(range(10))
characters = list('Harry')
print(characters)
numbers1 == list # 같지 않음
# 클래스 만들기
# 클래스와 인스턴스를 이용하면 데이터와 코드를 사람이 이해하기 쉽게 포장할 수 있다.
class Human():
"""person"""
def speak(person):
print('{}이 {}로 말을 합니다.'.format(person.name, person.language))
person1 = Human()
person2 = Human()
person1.language = '한국어'
person2.language = 'English'
print(person1.language)
print(person2.language)
person1.name = '손흥민'
person2.name = 'Harry Kane'
Human.speak = speak
person1.speak()
person2.speak()
|
0883ee1e5d6b72ca1c2c31980b1b5aefb40744dd | green-fox-academy/Atis0505 | /week-05/day-03/min_max_diff.py | 561 | 3.953125 | 4 | # Create a function called `min_max_diff` that takes a list of numbers as parameter
# and returns the difference between maximum and minimum values in the list
# Create basic unit tests for it with at least 3 different test cases
def min_max_diff(number_list):
if len(number_list) == 1:
return number_list[0]
elif type(number_list) == None:
return False
elif len(number_list) >= 2:
max_number = max(number_list)
min_number = min(number_list)
diff_min_max = max_number - min_number
return diff_min_max |
1a4d4960ad651a4cf7bb48859a4252b6d4a00e1c | Tesla99977/Homework-Tasks- | /Python ДЗ/14.py | 157 | 3.671875 | 4 | s = float(input())
r = float(input())
k = float(input())
if (s**0.5)/2 > r and ((s**0.5-k)/2 >= r) :
print("Можно")
else:
print("Нельзя")
|
109026b92a9c40e56c91c9e2ccba768b70331047 | Muhammad-CS/Missing-Operator-Calculator | /Missing Operator Calculator.py | 2,339 | 3.765625 | 4 | import itertools
string='1?2?3'
def operation_counter(string):
count = 0
for i in string:
if (i == '?'):
count += 1
else:
pass
return count
def q_positions(string):
positions = []
for i in range(len(string)):
if (string[i] == '?'):
positions.append(i)
return positions
def string_char_replacer(string,newstring,index):
string = string[:index] + newstring + string[index + 1:]
return string
def parenthesize(string):
operators = ['?']
depth = len([s for s in string if s in operators])
if depth == 0:
return [string]
if depth== 1:
return ['('+ string + ')']
answer = []
for index, symbol in enumerate(string):
if symbol in operators:
left = string[:index]
right = string[(index+1):]
strings = ['(' + lt + ')' + symbol +'(' + rt + ')'
for lt in parenthesize(left)
for rt in parenthesize(right) ]
answer.extend(strings)
return answer
def operation_replacer(string):
opr = ['+', '-', '*', '/']
operation_numbers = operation_counter(string)
products = list(itertools.product(opr, repeat=operation_numbers))
#print(products)
return products
def single_operation_list(string):
single_operators = []
for i in range(len(string)):
char = string[i]
if (char == "'" and string[i+1] != "," and string[i+1] != ")"):
single_operator = string[i+1:i+2]
single_operators.append(single_operator)
return single_operators
exp= parenthesize(string)
opr_tuple = operation_replacer(string)
opr = []
for i in opr_tuple:
tuple = str(i).replace(' ', '')
opr.append(tuple)
for i in exp:
for j in opr:
h = single_operation_list(j)
spare = i
for l in h:
i = i.replace('?',l,1)
find_q = i.find('?')
if (find_q == -1):
try:
evaluation = str(eval(i))
except ZeroDivisionError:
evaluation = 'Division By Zero!'
print(i + ' = ' + evaluation)
else:
pass
i = spare
|
49c74b6bd6ee672a40cc576d8c97150f42e9eb99 | igorverse/CC8210-programacao-avancada-I | /aulas_de_lab/aula6/ex3.py | 1,216 | 4.15625 | 4 | '''
Faça uma função chamada contaPalavras que receba uma String e que conte a quantidade de incidências de todas as palavras em uma String, assim listando todas as palavras e suas quantidades, considere como palavras as que tenha uma quantidade igual ou maior que duas letras.
A função deverá retornar duas listas, uma referente as palavras encontradas (sem duplicidade), e outra lista referente a quantidade de incidência de cada uma das palavras respectivamente a lista de palavras.
Sua função deverá considerar todas as palavras como letras minusculas, remova também as virgulas e os caracteres "!" e "?".
'''
def contaPalavras(words):
for a in '!?,':
words = words.replace(a, "")
word_array = words.lower().split(" ")
filtered_word_array = []
no_repeat_words = []
counter = []
for word in word_array:
if len(word) >= 2:
filtered_word_array.append(word)
for word in filtered_word_array:
if word not in no_repeat_words:
counter.append(word_array.count(word))
no_repeat_words.append(word)
return no_repeat_words, counter
p = " e fei a Fei feijão FeI Feijão felino Feio i Fé"
print(contaPalavras(p)) |
d603810654801fe020a313b7aee9802b175413e2 | Victor-Light/illumio-coding-challenge | /firewall.py | 3,451 | 3.609375 | 4 | import csv
class FireWall:
def __init__(self,filePath):
with open(filePath) as csvFile:
#form a rule map
self.inTcp = {"port":[], "ip_address":{}}
self.inUdp = {"port":[], "ip_address":{}}
self.outTcp = {"port":[], "ip_address":{}}
self.outUdp = {"port":[], "ip_address":{}}
self.ruleMap = {"inbound": {"tcp": self.inTcp, "udp": self.inUdp},"outbound": {"tcp": self.outTcp, "udp": self.outUdp}}
readCSV = csv.reader(csvFile)
for index, line in enumerate(readCSV):
direction = line[0]
protocol = line[1]
port = line[2]
ip_address = line[3]
self.add_entry(direction, protocol, port, ip_address, index)
sorted(self.inTcp["port"], key = lambda k:k[0][1])
sorted(self.inUdp["port"], key = lambda k:k[0][1])
sorted(self.outTcp["port"], key = lambda k:k[0][1])
sorted(self.outUdp["port"], key = lambda k:k[0][1])
return
def add_entry(self, direction, protocol, port, ip_address, index):
portRange = port.split("-")
if len(portRange) == 1:
portRange = portRange*2
#change list item type from string into integer
portRange = [int(item) for item in portRange]
self.ruleMap[direction][protocol]["port"].append((portRange, index))
ipRange = ip_address.split("-")
if len(ipRange) == 1:
ipRange = ipRange*2
ipRange = [tuple(int(n) for n in ipRange[0].split('.')), tuple(int(n) for n in ipRange[1].split('.'))]
self.ruleMap[direction][protocol]["ip_address"][index] = ipRange
return
def accept_packet(self, direction, protocol, port, ip_address):
#search all ports that includes port passed in
keys = self.search(direction, protocol, port)
ipAddresses = [self.ruleMap[direction][protocol]["ip_address"][key] for key in keys]
ip_address = tuple(int(n) for n in ip_address.split('.'))
#data structure for ipAddresses is [[(0,0,0,0),(0,0,0,0)],[(194,0,0,5),(194,0,1,6)]]
for addresses in ipAddresses:
if addresses[0] <= ip_address and ip_address <= addresses[1]:
return True
return False
def search(self, direction, protocol, port):
#brought some idea from exponential search
#data form of port is [([5,8],1), ([10,10],0)]
portsPool = self.ruleMap[direction][protocol]["port"]
keyOfPorts = []
index = 1
while index < len(portsPool)+1:
item = portsPool[index-1] # data structure for item is([5,8], 1) represent the port range 5-8 key is 1
if port > item[0][1]:
if index*2 < len(portsPool)+1:
index *= 2
else:
index +=1
else:
if port in range(item[0][0], item[0][1]+1):
keyOfPorts.append(item[1])
index +=1
return keyOfPorts
fw = FireWall("fw.csv")
print(fw.accept_packet("inbound", "tcp", 80, "192.168.1.2")) # True
print(fw.accept_packet("inbound", "udp", 53, "192.168.2.1")) # True
print(fw.accept_packet("outbound", "tcp", 10234, "192.168.10.11")) # True
print(fw.accept_packet("inbound", "tcp", 81, "192.168.1.2")) # False
print(fw.accept_packet("inbound", "udp", 24, "52.12.48.92")) # False
|
fe559f4d82572758b44b4896ee105bef4a41e93c | micheofire/studenttestscore | /app.py | 692 | 3.625 | 4 | import pandas as pd
import numpy as np
import streamlit as st
import pickle
from sklearn.linear_model import LinearRegression
loaded_model = pickle.load(open("finalized_model.sav", 'rb'))
st.title("STUDENT TEST SCORE PREDICTION APP")
st.write("Please input the student details in the sidebar")
gender = st.sidebar.selectbox("Gender", ["Male", "Female"])
age = st.sidebar.slider("Age", 1,100)
attendance = st.sidebar.slider("Attendance", 0.1,1.0)
if gender == "Male":
gender = 0
else:
gender = 1
user_input = np.array([gender, age, attendance]).reshape(1,-1)
pred = loaded_model.predict(user_input)
st.title(" ")
st.header(f"PREDICTED TEST SCORE IS ---> {round(pred[0], 2)}")
|
cc43718830c72934dca478386debdd4a863a69cf | C-CCM-TC1028-111-2113/homework-2-AdrielOlvera | /assignments/02Licencia/src/exercise.py | 515 | 3.90625 | 4 |
def main():
#Escribe tu código debajo de esta línea
age=int(input("Ingresa tu edad: "))
io=str(input("¿Tienes identificación oficial? (s/n)"))
if age>=18:
x=True
elif 18>age>=0:
x=False
elif age<0:
print("Respuesta incorrecta")
x=False
if io=="s":
y=True
elif io=="n":
y=False
else:
print("Respuesta incorrecta")
y=False
if x and y:
print("Trámite de licencia concedido")
else:
print("No cumples requisitos")
pass
if __name__ == '__main__':
main()
|
fae8ad9595533a95d46058b28d49f304782d221a | francocurses/curses-chess | /source/player.py | 1,625 | 3.6875 | 4 | from pieces.pawn import Pawn
from pieces.knight import Knight
from pieces.bishop import Bishop
from pieces.rook import Rook
from pieces.queen import Queen
from pieces.king import King
class Player():
"""
A player in chess.
"""
def __init__(self,name,pstring):
self.name = name
self.getpchars(pstring)
# create chess pieces
# pawns
self.pawns = []
for _ in range(8):
self.pawns.append(Pawn(self.pchar))
# knights
self.knight1 = Knight(self.nchar)
self.knight2 = Knight(self.nchar)
self.knights = [self.knight1,self.knight2]
# bishops
self.bishop1 = Bishop(self.bchar)
self.bishop2 = Bishop(self.bchar)
self.bishops = [self.bishop1,self.bishop2]
# rooks
self.rook1 = Rook(self.rchar)
self.rook2 = Rook(self.rchar)
self.rooks = [self.rook1,self.rook2]
# king queen
self.queen = Queen(self.qchar)
self.king = King(self.kchar)
# add pieces in "read" order
self.pieces = self.pawns + [self.rook1] + \
[self.knight1] + [self.bishop1] + \
[self.queen] + [self.king] + \
[self.bishop2] + [self.knight2] + \
[self.rook2]
def getpchars(self,pstring):
"""
Separates every character of the pieces
string and creates an attribute with each.
"""
self.pchar = pstring[0]
self.nchar = pstring[1]
self.bchar = pstring[2]
self.rchar = pstring[3]
self.qchar = pstring[4]
self.kchar = pstring[5]
|
b89b86cc89a94e32efb10d4ca2f738bc78a61a38 | francosbenitez/unsam | /06-organizacion-y-complejidad/05-busqueda/busqueda-en-listas.py | 854 | 3.96875 | 4 | """
Ejercicio 6.13: Búsqueda lineal sobre listas ordenadas.
Modificá la función busqueda_lineal(lista, e) de la Sección 4.2 para el caso de listas ordenadas, de forma que la función pare cuando encuentre un elemento mayor a e. Llamá a tu nueva función busqueda_lineal_lordenada(lista,e) y guardala en el archivo busqueda_en_listas.py.
En el peor caso, ¿cuál es nuestra nueva hipótesis sobre comportamiento del algoritmo? ¿Es realmente más eficiente?
"""
def busqueda_lineal(lista, e):
'''
Si hay un elemento mayor a e, la funcion para.
'''
pos = -1
for i, z in enumerate(lista):
if z > e:
pos = i
break
return pos
print(busqueda_lineal([1, 4, 54, 3, 0, -1], 44),
busqueda_lineal([1, 4, 54, 3, 0, -1], 3),
busqueda_lineal([1, 4, 54, 3, 0, -1], 0),
busqueda_lineal([], 42)) |
1fc4a78f1d56fd6990274b51c029a5ae11c1a989 | Suykim21/python_references | /algos/basics.py | 2,615 | 4.125 | 4 | # Print 1-255
# for x in range(1,256):
# print(x)
# Print odd numbers from 1 to 10
# for x in range(1,11):
# if(x%2==1):
# print(x)
# Print the sumof al the odd numbers from 1 to 10
# sum = 0
# for x in range(1, 11):
# if(x%2==1):
# sum = sum + x
# print(sum)
# def addOddNumbers(numbers):
# total = 0
# for num in numbers:
# if (num%2==1):
# total += num
# print(total)
# addOddNumbers([1,2,3,4,5,6,7,8,9])
# Iterating through the list
# x = [1,3,5,7,9,13]
# for i in x:
# print(i)
# Find Max, given an list with multiple values
# x = [-3,3,5,4]
# print (max(x))
# Find average, given a list with multiple values
# x=[2,3,5,6,17]
# average = sum(x)/len(x)
# print(average)
# Array with odd numbers
# def appendOdd(numbers):
# odd = []
# for number in numbers:
# if(number%2==1):
# odd.append(number)
# print(odd)
# appendOdd([1,2,3,4,5,6,7,8,9])
# Greater than Y
# x=[1,3,5,7]
# y=3
#utilize list comprehensions!!
# print (sum(i > y for i in x))
#Square the values
# def square(list):
# print([i ** 2 for i in list])
# square([1,5,10,-2])
# Eliminate Negative Numbers
# def remove_odd(x):
# print([i for i in x if i>0])
# remove_odd([-1,-3,-4,4,5,6])
# Max, min, and average in a list
# x = [-3,3,5,4]
# print (max(x))
# print (min(x))
# average = sum(x)/len(x)
# print(average)
# Shifting the values in the list
# def rotate(l, n):
# rotates to the left
# print(l[n:] + l[:n])
# list = [1,2,3,4,5]
# prints values at index of 2 - [3,4,5]
# print(list[2:])
# prints first two indices [1,2]
# print(list[:2])
# rotate(list, 4)
# Number to string, replace negative numbers with string
# x = [-1,4,-1,2]
# for i in x:
# if(x[i]<0):
# x[i] = "Dojo"
# print(x)
# Create random list(10 values)
# import random
# my_randoms = random.sample(range(1,101),10)
# print(my_randoms)
# Swapping two values
# list = [-3,5,1,3,2,10]
# temp = list[2]
# list[2] = list[0]
# list[0] = temp
# Reverse the list by swapping two values
def reverse(seq):
# Reverses elements of a list
for i in range(len(seq)/2):
x = seq[i]
y = seq[-i-1]
seq[i] = y
seq[-i-1] = x
l = ['a', 'b', 'c', 'd', 'e']
reverse(l)
print(l)
# Removing Negatives
list = [0,-1,2,-3,4,-5,6]
def removeNegatives(list):
# I want 'i' for each 'i' in list if 'i' is more than 0
num_list = [i for i in list if i>=0]
print(num_list)
removeNegatives(list)
# Long version:
my_list = []
for i in list:
if i>=0:
my_list.append(i)
print (my_list) |
77096beb877dbf605f71ee1314e146f88d2dfcc8 | maxymkuz/cs_3 | /Alko/exam/exam_second.py | 1,383 | 4.15625 | 4 | def recursive_solution(x, speed, position):
if x == position:
return ""
if x == position + speed:
return "A"
sequence = ""
while x > position + speed:
sequence += "A"
position += speed
speed *= 2
left_before = x - position
left_after = position + speed - x
if left_after < left_before:
if x == position + speed:
sequence += "A"
return sequence
sequence += "AR"
position += speed
x = position + position - x
speed = 1
sequence += recursive_solution(x, speed, position)
else:
sequence += "RR"
speed = 1
sequence += recursive_solution(x, speed, position)
return sequence
def smallest_instruction(x): # напевно краще було б зробити динамічним
# програмуванням, але я зробив жадіком алгоритмом(може бути не завжди
# правильним). Складність буде лінійна
if x == 0:
return ""
if x < 0:
result = "R"
x *= -1
else:
result = ""
speed = 1
result += recursive_solution(x, speed, 0)
return recursive_solution(x, speed, 0)
if __name__ == '__main__':
print(smallest_instruction(3)) # поки працює правильно
|
84c62dc434432290f05e21a2cb21827ad3574772 | bashenov98/BFDjango2020 | /Week 1/hackerrank/medium/minions.py | 284 | 3.5 | 4 | vowels = ['A', 'E', 'I', 'O', 'U']
s = raw_input()
a = 0
b = 0
for i, c in enumerate(s):
if c in vowels:
b += len(s) - i
else:
a += len(s) - i
if a == b:
print "Draw"
elif a > b:
print 'Stuart {}'.format(a)
else:
print 'Kevin {}'.format(b) |
3ec0e5c9a46da229ab167205ef3455629b91387b | stefaluc/algorithms | /mirror_tree.py | 2,115 | 3.890625 | 4 | #!/usr/bin/python
class TreeNode():
def __init__(self, value):
self.left = None;
self.right = None;
self.data = value;
def bfs(node):
if node == None:
return
print(node.data)
queue = []
queue.append(node.left)
queue.append(node.right)
for i in queue:
if i == None:
continue
print(i.data)
queue.append(i.left)
queue.append(i.right)
def main():
root = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
d = TreeNode(4)
e = TreeNode(5)
f = TreeNode(6)
g = TreeNode(7)
root.left = b
root.right = c
b.left = d
b.right = e
c.left = f
c.right = g
g.right = TreeNode(8)
g.right.right = TreeNode(9)
f.right = TreeNode(10)
d.left = TreeNode(11)
d.left.left = TreeNode(12)
d.left.left.left = TreeNode(12)
bfs(root)
print '======'
bfs(mirror(root))
print '======'
print getDepth(root)
print '======'
print largestValue(root)
print '======'
print isBalanced(root)
def mirror(root):
if root.left == None and root.right == None:
return root
if root.left != None and root.right != None:
tmp = root.left
root.left = mirror(root.right)
root.right = mirror(tmp)
return root
def getDepth(root, depth = 0):
if root == None:
return depth
depth += 1
depthLeft = getDepth(root.left, depth)
depthRight = getDepth(root.right, depth)
return max(depthLeft, depthRight)
def largestValue(root):
if root.left is None and root.right is None:
return root.data
elif root.left is None:
return max(root.data, largestValue(root.right))
elif root.right is None:
return max(root.data, largestValue(root.left))
return max(largestValue(root.left), largestValue(root.right))
def isBalanced(node):
if node is None:
return True
depthLeft = getDepth(node.left)
depthRight = getDepth(node.right)
return abs(depthLeft - depthRight) < 2 and isBalanced(node.left) and isBalanced(node.right)
main()
|
6ce5c40e98faad0128315b8d4caed965dab2a827 | Unique-Red/HardwaySeries | /ex39sd.py | 336 | 3.65625 | 4 | states = {
'Lagos': 'LA',
'Ondo': 'ON',
'Calabar': 'CA',
'Ogun': 'OG',
'Benin': 'BE'
}
cities = {
'LA': 'Island',
'ON': 'Ondo town',
'OG': 'Ota'
}
cities['CA'] = 'Awka'
cities['BE'] = 'Edo'
print('-' * 5)
print("OG State has: ", cities['OG'])
print("LA State has: ", cities['LA'])
|
1b37916a1f394ea8eecc9f9499ac8f8a85f3399f | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/056_Merge_Intervals.py | 1,029 | 3.84375 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
c_ Solution o..
___ merge intervals
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
__ intervals is N..:
r_
ls = l.. intervals)
__ ls <= 1:
r_ intervals
# sort by start
intervals.s.. k.._l... x: x.start)
pos = 0
w.. pos < l.. intervals) - 1:
# check overlap
__ intervals[pos].end >= intervals[pos + 1].start:
next = intervals.pop(pos + 1)
# check next is overlap or totally covered by pos
__ next.end > intervals[pos].end:
intervals[pos].end = next.end
# print [(t.start, t.end) for t in intervals], pos
____
pos += 1
r_ intervals
__ ____ __ ____
# begin
s ?
print s.merge([[1,3],[2,6],[8,10],[15,18]]) |
26f85908f72a11b89f731bc00f11da2f1e7f8224 | EduardoMachadoCostaOliveira/Python | /CEV/ex070.py | 1,222 | 3.921875 | 4 | # Crie um programa que leia o nome e o preço de vários produto.
# O Programa deverá perguntar se o usário vai continuar. No final mostre:
# A) Qual é o total gasto na compra.
# B) Quantos produtos custam mais de R$ 1000.
# C) Qual é o nome do produto mais barato.
print('-' * 30)
print('{:-^30}'.format(' LOJA SUPER BARATÃO '))
print('-' * 30)
total = totmil = menor = cont = 0
produtomenor = ''
while True:
produto = str(input('Nome do Produto: '))
preco = float(input('Preço: R$ '))
total += preco # A
cont += 1
if preco > 1000: # B
totmil += 1
if cont == 1 or preco < menor: # C
menor = preco
produtomenor = produto
'''else:
if preco < menor:
menor = preco
produtomenor = produto'''
continua = ' '
while continua not in 'SN':
continua = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
if continua == 'N':
break
print('----Fim do Programa----')
print('{:-^30}'.format(' FIM DO PROGRAMA '))
print(f'O total da compra foi de R$ {total:^10.3f}!')
print(f'Temos {totmil} produtos custando mais de R$1000,00')
print(f'O produto mais barato foi {produtomenor} que custa R$ {menor:<10.2f}!')
|
d22bbde0e626f90c742d28b3af711a2a35552888 | salihdeg/wp-message-sender | /WhatsAppMessageSender/Business/fileReader.py | 363 | 3.53125 | 4 | # -*- coding: UTF-8 -*-
import pandas as pd
contacts = ""
numbers = ""
names = ""
def save_contacts_from_file(file_path):
global contacts
global numbers
global names
contacts = pd.read_excel(file_path)
numbers = pd.DataFrame(contacts, columns=['Number']).values.tolist()
names = pd.DataFrame(contacts, columns=['Name']).values.tolist()
|
f739a159ddfde1ad4c37f71e190b0f0d491499cc | yongzhuo/leetcode-in-out | /hot/a15_three_sum_closest.py | 2,166 | 3.515625 | 4 | # !/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2020/1/3 19:20
# @author : Mo
# @function: 16.最接近三数之和
# 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
# 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
# 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/3sum-closest
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
# 双指针法, error 不能删除重复的数据
def threeSumClosestmy(self, nums, target):
num_target = [target-num if target-num>0 else num-target for num in nums]
num_target_copy = num_target.copy() # copy.deepcopy(num_target)
num_target_copy.sort()
num_target_top3 = num_target_copy[0:3]
idxs = []
for ntt in num_target_top3:
idx = num_target.index(ntt)
idxs.append(idx)
res = 0
for idxs_one in idxs:
res += nums[idxs_one]
return res
# 双指针法
def threeSumClosest(self, nums, target):
n = len(nums)
if (not nums or n < 3):
return None
nums.sort()
res = float("inf")
for i in range(n):
if (i > 0 and nums[i] == nums[i - 1]):
continue
L = i + 1
R = n - 1
while (L < R):
cur_sum = nums[i] + nums[L] + nums[R]
if (cur_sum == target):
return target
if (abs(cur_sum - target) < abs(res - target)):
res = cur_sum
if (cur_sum - target < 0):
L += 1
else:
R -= 1
return res
if __name__ == '__main__':
sol = Solution()
strs = [1,1,-1] # ["dog","racecar","car"]
target = -100
res = sol.threeSumClosest(strs, target)
print(res)
gg = 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.