blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
f9e5997cd081b33a4a540d12e9460f13d873c4ca | dhnanj2/TS-Codes | /pangram2.py | 371 | 4.03125 | 4 | import string
all_alphabets = set(string.ascii_lowercase)
def isPangram(input_string):
return set(input_string.lower()) >= all_alphabets
input1 = "Pack my box with five dozen liquor jugs"
input2 = "Old brother fox jumps over the lazy dog"
if(isPangram(input1) == True):
print("Yes")
else:
print("No")
if(isPangram(input2) == True):
print("Yes")
else:
print("No")
|
0ddc33f9f61658e171d76996c16bd613555b9a3a | AlaaBejaoui/AberdeenProject | /AberdeenProject/utilities/loadPickledData.py | 377 | 3.65625 | 4 | import pickle
def loadPickledData(filepath):
"""
This function reads the pickled representation of an object from a file
:param filepath: Path to the pickled file
:type filepath: String
:return: The reconstituted dataframe
:rtype: Pandas dataframe
"""
with open(filepath, 'rb') as f:
dataframe = pickle.load(f)
return dataframe
|
dfb5e4b89f823133862a7004858ce8ce8f395801 | Airomantic/alogrithm_ACM | /完整整理/动态规划/鸡蛋掉落_困难_动态规划+二分查找(递归).py | 1,633 | 3.71875 | 4 |
"""
https://leetcode-cn.com/problems/super-egg-drop/solution/ji-dan-diao-luo-by-leetcode-solution-2/
视频:https://leetcode-cn.com/problems/super-egg-drop/solution/ke-shi-hua-dpguo-cheng-by-alchemist-5r/
状态描述:
动态规划表练习:
https://alchemist-al.com/algorithms/egg-dropping-problem
"""
class Solution:
def superEggDrop(self, eggs, floors):
memo={} #记录
def dp(eggs,floors):
if (eggs,floors) not in memo:
if floors==0:
ans=0
elif eggs==1:
ans=floors
else:
low,high=1,floors
#保持2个x值的差距,以便以后手动检查
while low+1<high:
x=(low+high)//2
t1=dp(eggs-1,x-1)
t2=dp(eggs,floors-x) #碎了
if t1<t2: #碎了往上走二分
low=x
elif t1>t2: #没碎往下二分
high=x
else:
low=high=x
ans=1+min( max(dp(eggs-1,x-1) ,dp(eggs,floors-x) )
for x in (low,high))
memo[eggs,floors]=ans #每次循环记录新的,用于查看当前eggs,floors是否在里面
return memo[eggs,floors]
return dp(eggs,floors)
if __name__ == '__main__':
all=list(map(int,input().strip().split()))
# while True:
start=all[0]
target=all[1]
res=Solution().superEggDrop(start,target)
print(res)
|
9d3aa39c4695a218200f8aa47f214224b324c8dc | alexsunseg/CYPAlejandroDG | /libro/problemas_resueltos/capitulo3/Problema3_19.py | 237 | 3.609375 | 4 | N=int(input("Ingrese un número: "))
I=1
for v in range (0,N,I):
SUM=0
J=1
for i in range (1,(I//2),J):
if (I%J)==0:
SUM+=J
J+=1
if SUM==J:
print(I, "Es un número perfecto")
I+=1
|
1ee4bee98f3b06da88ae8b407a28c8e74bf92181 | jwbaker/projecteuler | /PE30.py | 575 | 3.9375 | 4 | '''
Created on: 2013-06-28
Problem 30:
Surprisingly there are only three numbers that can be written as the sum of the fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of all these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
SOLUTION: ????
'''
def toDigits(N):
digits = []
for c in str(N):
digits.append(int(c))
return digits
|
d5ae4327d29f6c19927c0ff598d2e7abc1391389 | hacktoolkit/code_challenges | /project_euler/python/015.py | 1,056 | 3.625 | 4 | """http://projecteuler.net/problem=015
Lattice paths
Starting in the top left corner of a 2x2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20x20 grid?
Solution by jontsai <[email protected]>
"""
from utils import *
EXPECTED_ANSWER = 137846528820
ROWS = 20
COLS = 20
LATTICE_MEMO = {}
def lattice_paths(rows, cols):
"""Finds the number of paths through a lattice with rows and cols
"""
if rows == 0 and cols == 0:
num_paths = 0
elif rows == 0 or cols == 0:
num_paths = 1
else:
if not LATTICE_MEMO.get(rows):
LATTICE_MEMO[rows] = {}
if not LATTICE_MEMO[rows].get(cols):
num_paths = lattice_paths(rows - 1, cols) + lattice_paths(rows, cols - 1)
LATTICE_MEMO[rows][cols] = num_paths
else:
num_paths = LATTICE_MEMO[rows][cols]
return num_paths
answer = lattice_paths(ROWS, COLS)
print 'Expected: %s, Answer: %s' % (EXPECTED_ANSWER, answer)
|
03a7388706d34c92c866548024c3cecb24af9d1f | pecata83/soft-uni-python-solutions | /Programing Basics Python/For Loop/11.py | 585 | 3.625 | 4 | lily_age = int(input())
washingmachine_price = float(input())
single_toy_price = int(input())
money_sum = 0
last_bday_money = 0
brother_money = 0
toys_sum = 0
for bday in range(1, lily_age + 1):
if bday % 2 == 0:
last_bday_money += 10
money_sum += last_bday_money
brother_money += 1
else:
toys_sum += single_toy_price
total_money = (money_sum - brother_money) + toys_sum
if total_money >= washingmachine_price:
print(f"Yes! {total_money - washingmachine_price:.2f}")
else:
print(f"No! {abs(total_money - washingmachine_price):.2f}")
|
46a1e92098d9e280ad5b0723d6840e676e55d0cc | RaduMatees/Python | /Exam/24. Limita sir medie aritmetica.py | 257 | 3.671875 | 4 | """Limita unui sir recurent dat de media aritmetica"""
a = float(input("a= "))
b = float(input("b= "))
eps = float(input("eps= "))
x = float(a)
y = float(b)
while abs(x - y) >= eps:
z = (x+y)/2
x = y
y = z
print("Limita este" ,format(x,'.5f')) |
b11999fef45b46e6865c502afa69a2962a618c4c | bardayilmaz/270201019 | /lab9/example1.py | 95 | 3.5 | 4 | def harmonic(n):
if n == 0:
return 0
else:
return 1/n + harmonic(n-1)
print(harmonic(5)) |
60e49ddc186acb571954e51b06c00a2b9952aaa2 | david6666666/cwq | /1-11python基础/51__call__方法和可调用对象.py | 510 | 3.828125 | 4 | '''
定义了__call__方法的对象,称为“可调用对象”,即该对象可以像函数一样被调用。
'''
class SalaryAccount:
'''工资计算类'''
def __call__(self, salary):
yearSalary = salary*12
daySalary = salary//30
hourSalary = daySalary//8
return dict(monthSalary=salary,yearSalary=yearSalary,daySalary=daySalary
,hourSalary=hourSalary)
s = SalaryAccount()
print(s(5000)) #可以像调用函数一样调用对象的__call__方法 |
4db8bc8d8cd9d33def71f864373acab6b9669f16 | Henrysyh2000/Assignment10 | /exist_pair.py | 988 | 3.96875 | 4 | def exist_pair(L, X):
""" Detect whether we can find two elements in L whose sum is exactly X.
:param L: List[Int] -- a python list of integers
:param X: Int -- integer X
Required runtime: Expected O(len(L))
:return: True if we can find two elements in L whose sum is exactly X. False otherwise.
"""
# To do
dic = {}
for i in L:
dic[i] = None
for i in dic:
if (X - i) in dic:
return True
return False
def main():
l1 = [20, 36, 35, 46, 25, 27, 8, 0, 34, 31]
print("20 + 36 = 56, Should return True........")
print("Your result:", exist_pair(l1, 56))
print("36 + 34 = 70, Should return True........")
print("Your result:", exist_pair(l1, 70))
print("36 + 0 = 36, Should return True........")
print("Your result:", exist_pair(l1, 36))
print("No pair with sum equal to 74.... Should return False")
print("Your result:", exist_pair(l1, 74))
if __name__ == '__main__':
main()
|
20630a65d9f6715309554d4686aa841077971dbf | CKanja/pythonTasks | /Arithmetic_Game.py | 983 | 4.125 | 4 | print("Welcome to the number game!")
num1 = int(input("Enter the first number "))
num2 = int(input("Enter the second number "))
operation = input("Choose an operation: addition, subtraction, division, multiplication, modulus: ")
guess = int(input("Before we calculate the answer for you, what do you think the answer is? #QuickMaths: "))
def checkAnswer(answer,guess):
if answer == guess:
print ("well done!")
else:
print ("try again!")
if operation.lower() == "addition":
answer = num1 + num2
checkAnswer(answer,guess)
elif operation.lower() == "subtraction":
answer = num1 - num2
checkAnswer(answer,guess)
elif operation.lower() == "division":
answer = num1 / num2
checkAnswer(answer,guess)
elif operation.lower() == "multiplication":
answer = num1 * num2
checkAnswer(answer,guess)
elif operation.lower() == "modulus":
answer = num1 % num2
checkAnswer(answer,guess)
else:
print("kindly read instructions") |
e6db806d8d4c9226ec880f1cd4fd0fce5fd4699f | Winni-Lina/CodingTest | /문제08-보조.py | 192 | 3.703125 | 4 | # 8.01 문자열 arr이 "abcdefg" 일 때 다음의 값을 나타내시오(에러가)
arr = "abcdefg"
# print(arr[len(arr)]) : 에러
print(arr[3])
print(arr[6])
print(arr[0])
print(arr[-1]) |
b4eb5b7509029915d0d5ee55be9d1ca1cbe43eba | neochen2701/TQCPans | /程式語言 V2答案檔/Python/608.py | 197 | 3.59375 | 4 | score = 0
input_list = []
for i in range(10):
n = int(input())
input_list = [x + n for x in input_list]
input_list.append(n)
print('score = ' + str(sum(i > 3 for i in input_list)))
|
e09621cb976110fe291794e71c58797378d3796b | MaxKmet/Tic_Tac_Toe | /board.py | 1,997 | 3.6875 | 4 | class Board:
CELL_EMPTY = ' '
CELL_X = 'x'
CELL_0 = 'o'
CELLS = [CELL_EMPTY, CELL_X, CELL_0]
PLAYER_0 = 'x'
PLAYER_1 = 'o'
PLAYERS = [PLAYER_0, PLAYER_1]
def __init__(self, values=None):
if values is None:
values = self.CELL_EMPTY * 9
if not all(map(lambda x: x in self.CELLS, values)):
raise ValueError('One of the values is invalid')
self._cells = [c for c in values]
def __getitem__(self, i):
if not isinstance(i, int):
raise ValueError('Index should be integer')
if not 0 <= i < 10:
raise IndexError('Index should be between 0 and 10')
return self._cells[i]
def __setitem__(self, i, val):
if not isinstance(i, int):
raise ValueError('Index should be integer')
if not 0 <= i < 10:
raise IndexError('Index should be between 0 and 10')
self._cells[i] = val
def get_copy(self):
"""
Copy a board to avoid changing original
"""
new_board = Board()
for i in range(9):
new_board[i] = self[i]
return new_board
def winner(self):
"""
Returns the winner or empty cell
"""
combinations = [(0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 1, 2),
(3, 4, 5), (6, 7, 8), (0, 4, 8), (2, 4, 6)]
for combination in combinations:
if self[combination[0]] == self[combination[1]] == self[combination[2]]:
if self[combination[0]] != self.CELL_EMPTY:
return self[combination[0]]
return self.CELL_EMPTY
def is_full(self):
for cell in self._cells:
if cell == self.CELL_EMPTY:
return False
return True
def __str__(self):
result = '-----\n'
for i in range(3):
result += '|' + self[i*3] + self[i*3+1] + self[i*3+2] + '|\n'
result += '-----'
return result
|
34bc854299321af0f92852bc1fbcf44e12582efd | LoveDT/leetcode | /28 Implement strStr()/solution.py | 832 | 3.5 | 4 | class Solution:
# @param {string} haystack
# @param {string} needle
# @return {integer}
def strStr(self, haystack, needle):
length, inlen = len(haystack), len(needle)
if inlen == 0:
return 0
if length == 0:
return -1
h,n,result = 0,0,0
while h<length:
if haystack[h] == needle[n]:
result = h
while n<inlen and h<length and haystack[h] == needle[n]:
h+=1
n+=1
if n == inlen:
return result
elif h == length:
return -1
else:
h -= (n-1)
n = 0
else:
h += 1
return -1
|
dbc1e8bca05e99bb7027c81305484f2c2958bb90 | rocky/pycolumnize | /test/test_columnize.py | 5,825 | 3.5 | 4 | #!/usr/bin/env python
# -*- Python -*-
"Unit test for Columnize"
import pytest
import sys
from unittest import mock
from columnize import columnize
def test_basic():
"""Basic sanity and status testing."""
assert "1, 2, 3\n" == columnize(["1", "2", "3"], 10, ", ")
assert "1 3\n2 4\n" == columnize(["1", "2", "3", "4"], 4)
assert "1 3\n2 4\n" == columnize(["1", "2", "3", "4"], 7)
assert "0 1 2\n3\n" == columnize(["0", "1", "2", "3"], 7, arrange_vertical=False)
assert "<empty>\n" == columnize([])
assert "oneitem\n" == columnize(["oneitem"])
data = [str(i) for i in range(55)]
assert (
"0, 6, 12, 18, 24, 30, 36, 42, 48, 54\n"
+ "1, 7, 13, 19, 25, 31, 37, 43, 49\n"
+ "2, 8, 14, 20, 26, 32, 38, 44, 50\n"
+ "3, 9, 15, 21, 27, 33, 39, 45, 51\n"
+ "4, 10, 16, 22, 28, 34, 40, 46, 52\n"
+ "5, 11, 17, 23, 29, 35, 41, 47, 53\n"
== columnize(
data, displaywidth=39, ljust=False, arrange_vertical=True, colsep=", "
)
)
assert (
" 0, 7, 14, 21, 28, 35, 42, 49\n"
+ " 1, 8, 15, 22, 29, 36, 43, 50\n"
+ " 2, 9, 16, 23, 30, 37, 44, 51\n"
+ " 3, 10, 17, 24, 31, 38, 45, 52\n"
+ " 4, 11, 18, 25, 32, 39, 46, 53\n"
+ " 5, 12, 19, 26, 33, 40, 47, 54\n"
+ " 6, 13, 20, 27, 34, 41, 48\n"
== columnize(
data,
displaywidth=39,
ljust=False,
arrange_vertical=True,
colsep=", ",
lineprefix=" ",
)
)
assert (
" 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n"
+ "10, 11, 12, 13, 14, 15, 16, 17, 18, 19\n"
+ "20, 21, 22, 23, 24, 25, 26, 27, 28, 29\n"
+ "30, 31, 32, 33, 34, 35, 36, 37, 38, 39\n"
+ "40, 41, 42, 43, 44, 45, 46, 47, 48, 49\n"
+ "50, 51, 52, 53, 54\n"
== columnize(
data, displaywidth=39, ljust=False, arrange_vertical=False, colsep=", "
)
)
assert (
" 0, 1, 2, 3, 4, 5, 6, 7\n"
+ " 8, 9, 10, 11, 12, 13, 14, 15\n"
+ " 16, 17, 18, 19, 20, 21, 22, 23\n"
+ " 24, 25, 26, 27, 28, 29, 30, 31\n"
+ " 32, 33, 34, 35, 36, 37, 38, 39\n"
+ " 40, 41, 42, 43, 44, 45, 46, 47\n"
+ " 48, 49, 50, 51, 52, 53, 54\n"
== columnize(
data,
displaywidth=34,
ljust=False,
arrange_vertical=False,
colsep=", ",
lineprefix=" ",
)
)
data = (
"one",
"two",
"three",
"for",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eightteen",
"nineteen",
"twenty",
"twentyone",
"twentytwo",
"twentythree",
"twentyfour",
"twentyfive",
"twentysix",
"twentyseven",
)
assert (
"one two three for five six \n"
+ "seven eight nine ten eleven twelve \n"
+ "thirteen fourteen fifteen sixteen seventeen eightteen \n"
+ "nineteen twenty twentyone twentytwo twentythree twentyfour\n"
+ "twentyfive twentysix twentyseven\n"
== columnize(data, arrange_vertical=False)
)
assert (
"one five nine thirteen seventeen twentyone twentyfive \n"
+ "two six ten fourteen eightteen twentytwo twentysix \n"
+ "three seven eleven fifteen nineteen twentythree twentyseven\n"
+ "for eight twelve sixteen twenty twentyfour \n"
== columnize(data)
)
assert "0 1 2 3\n" == columnize(list(range(4)))
assert (
"[ 0, 1, 2, 3, 4, 5, 6, 7, 8,\n"
+ " 9, 10, 11, 12, 13, 14, 15, 16, 17,\n"
+ " 18, 19, 20, 21, 22, 23, 24, 25, 26,\n"
+ " 27, 28, 29, 30, 31, 32, 33, 34, 35,\n"
+ " 36, 37, 38, 39, 40, 41, 42, 43, 44,\n"
+ " 45, 46, 47, 48, 49, 50, 51, 52, 53,\n"
+ " 54]\n\n"
== columnize(list(range(55)), opts={"displaywidth": 38, "arrange_array": True})
)
assert (
"[ 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11]\n\n"
== columnize(list(range(12)), opts={"displaywidth": 6, "arrange_array": True})
)
assert (
"[ 0, 1,\n 2, 3,\n 4, 5,\n 6, 7,\n 8, 9,\n 10, 11]\n\n"
== columnize(list(range(12)), opts={"displaywidth": 9, "arrange_array": True})
)
return
def test_colfmt():
assert " 0 1 2 3\n" == columnize(
[0, 1, 2, 3], 7, arrange_vertical=False, opts={"colfmt": "%5d"}
)
def test_lineprefix():
assert ">>> 0\n>>> 1\n>>> 2\n>>> 3\n" == columnize(
[0, 1, 2, 3],
7,
arrange_vertical=False,
opts={"colfmt": "%5d", "displaywidth": 16, "lineprefix": ">>> "},
)
def test_lineprefix_just_wide_enough():
assert ">>>10 12\n>>>11 13\n" == columnize(
[10, 11, 12, 13], opts={"lineprefix": ">>>", "displaywidth": 9}
)
if sys.version_info[:2] >= (3, 6):
@mock.patch.dict('os.environ', {'COLUMNS': '87'}, clear=True)
def test_computed_displaywidth_environ_COLUMNS_set():
from columnize import computed_displaywidth
width = computed_displaywidth()
assert width == 87
def test_errors():
"""Test various error conditions."""
with pytest.raises(TypeError):
columnize(5)
return
if __name__ == "__main__":
test_basic()
|
14149875d7892406cbc90cb0e566fc71c835e720 | soumya9988/Python_Machine_Learning_Basics | /MachineLearning_udemy/sample_program2.py | 559 | 3.53125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [3,4]].values
from sklearn.cluster import KMeans
wcss = []
for i in range(1, 11):
kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42)
kmeans.fit(X)
wcss.append(kmeans.inertia_)
plt.plot(range(1, 11), wcss)
plt.xlabel('No of clusters')
plt.ylabel('WCSS')
plt.title('Elbow Method')
plt.show()
kmeans = KMeans(n_clusters = 5, init = 'k-means++', random_state = 42)
y_means = kmeans.fit_predict(X)
print(y_means) |
53587309ca24195df44a5a69e4d3d35ee4e0f2d0 | kksante/iTrack_myLearning | /Twitter_Analytics/src/words_tweeted.py | 1,297 | 3.515625 | 4 | # Processing Data Files
# kksante
# 05JULY2015
# This program opens tweet.txt, reads it contents, determines the
# frequency of the words used and writes the results to ft1.txt
import sys # Used to handle inputs from command prompt
import os # Used to manipulate files and directories
# Variables to hold input and output filename passed from the prompt
in_file_name = sys.argv[1]
out_file_name = sys.argv[2]
# Input and Output File Paths
inPath = os.path.join(os.pardir, "tweet_input")
outPath = os.path.join(os.pardir, "tweet_output")
# full path of each file
fpath = os.path.join(inPath, in_file_name)
# open each file for reading, read content
inFile = open(fpath, "r")
# create output file for writing
outFilePath = os.path.join(outPath, out_file_name)
outFile = open(outFilePath, "w")
# Procedure to count words in tweet.txt
countdict = {}
for aline in inFile:
values = aline.split()
for item in values:
if item in countdict:
countdict[item] = countdict[item] + 1
else:
countdict[item] = 1
wordList = list(countdict.keys())
wordList.sort()
print >> outFile, "%-30s %10s" % ("WORDS TWEETED", "FREQUENCY")
for item in wordList:
print >> outFile, "%-30s %5s" % (item, countdict[item])
# close files
inFile.close()
outFile.close()
|
d244352292bd521d5085ec7f64aac2d1411cbb07 | guptaShantanu/Python-Programs | /capitalize.py | 312 | 3.578125 | 4 | line=input().split(" ")
word=""
for i in line:
if i[0].isalpha()==False:
word=word+i+" "
else:
word=word+i.title()+" "
if word[:len(word)-1]=="Q W E R T Y U I O P A S D F G H J K L Z X C V B N M Q W E R T Y U I O P A S D F G H J K L Z X C V B N M":
print(True)
else:
print(False)
|
eda57ce1a33249da2d45ee2a959d70fcafcce691 | jogusuvarna/jala_technologies | /constructor_call.py | 164 | 3.65625 | 4 | #Try to call the constructor multiple times with the same object(*)
class A:
def __int__(self):
self.x = 10
obj = A()
obj = A()
print(obj)
print(obj)
|
55c80830dd9f346f5dd2d65d56984ea66213b2d4 | mariaelisa492/Fundamentos_python | /semana_3/programas/errado.py | 865 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 08:28:06 2021
@author: Digital
"""
# Vamos a crear una función que reduzca el número de intentos y muestre
# el mensaje al usuario para volver a ingresar el dato
def errado(cont_intentos, intentos,numero_sugerido,numero_ingresado):
# vemos si tiene chances todavia
# inicia con el false la bandera
terminar = False
if cont_intentos == intentos:
terminar = True
elif(numero_sugerido < numero_ingresado):
print("El número ingresado es mayor que el número a buscar")
else:
print("El número ingresado es menor que el número a buscar")
# aumentamos el contador
cont_intentos += 1
# mensaje para volver a preguntar
numero_ingresado = int(input("Intente de nuevo: "))
return cont_intentos, numero_ingresado, terminar
|
70406d44a50e1ea54d451094146e87de44104ae1 | nstickney/exercism | /python/kindergarten-garden/kindergarten_garden.py | 668 | 3.65625 | 4 | class Garden(object):
species = {
'C': 'Clover',
'G': 'Grass',
'R': 'Radishes',
'V': 'Violets'
}
def __init__(self, diagram, students=None):
self.rows = diagram.split('\n')
if students is None:
self.students = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred",
"Ginny", "Harriet", "Ileana", "Joseph", "Kincaid",
"Larry"]
else:
self.students = sorted(students)
def plants(self, student):
pot = self.students.index(student) * 2
return [self.species[p] for r in self.rows for p in r[pot:pot + 2]]
|
21018763231d9fbf0dd5bece1d6e7ce7750e43b9 | Yolanda599/Maze | /AStar.py | 12,226 | 3.515625 | 4 | from tkinter import Button
from tkinter import Tk
from tkinter import Canvas
import numpy as np
class Maze(object):
def __init__(self):
self.blockcolorIndex = 0
self.blockcolor = ['black', 'green', 'red', 'yellow'] # 障碍颜色为黑色、起点绿色 终点红色、路径黄色
self.mapStatus = np.ones((15, 15), dtype=int) # 地图状态数组15×15 1表示无障碍 0表示有障碍
self.startPoint = 'start' # 起点
self.endPoint = 'end' # 终点
self.selectedStart = False # 是否选了起点,默认未选择起点
self.selectedEnd = False # 是否选了终点,默认未选择终点
self.openList = [] # open表
self.closeList = [] # close表
self.isOK = False # 是否已经结束
self.route = [] # 路径列表
# 界面设计
self.root = Tk()
self.root.title('基于A*算法的迷宫游戏')
self.root.geometry("800x800+300+0")
self.btn_maze = Button(self.root, text="生成迷宫", command=self.selectmaze)
self.btn_maze.pack()
self.btn_start = Button(self.root, text="选择起点", command=self.selectstart)
self.btn_start.pack()
self.btn_end = Button(self.root, text="选择终点", command=self.selectend)
self.btn_end.pack()
self.btn_find = Button(self.root, text="开始寻路", command=self.selectfind)
self.btn_find.pack()
self.btn_restart = Button(self.root, text="重新开始", command=self.selectrestart)
self.btn_restart.pack()
self.canvas = Canvas(self.root, width=500, height=500, bg="white")#页面布局:500*500,白底
self.canvas.pack()
for i in range(1, 17):
self.canvas.create_line(30, 30 * i, 480, 30 * i,dash=(4, 4)) # 横线
self.canvas.create_line(30 * i, 30, 30 * i, 480,dash=(4, 4)) # 竖线
self.canvas.bind("<Button-1>", self.drawMapBlock)
self.root.mainloop()
# 按钮对应具体操作
def selectrestart(self):
self.mapStatus = np.ones((15, 15), dtype=int) # 地图状态数组15×15,1表示无障碍,0表示障碍
self.startPoint = 'start'
self.endPoint = 'end'
self.selectedStart = False # 是否选了起点 默认否
self.selectedEnd = False # 是否选了终点 默认否
self.openList = [] # open表
self.closeList = [] # close表
self.isOK = False # 是否已经结束
self.route = []
self.canvas.destroy()
self.canvas = Canvas(self.root, width=500, height=500, bg="white")
self.canvas.pack()
#重新开始界面重新生成
for i in range(1, 17):
self.canvas.create_line(30, 30 * i, 480, 30 * i,dash=(4, 4)) # 横线
self.canvas.create_line(30 * i, 30, 30 * i, 480,dash=(4, 4)) # 竖线
self.canvas.bind("<Button-1>", self.drawMapBlock)
def selectmaze(self):
self.blockcolorIndex = 0 # 迷宫障碍物颜色:黑
def selectstart(self):
if not self.selectedStart:
self.blockcolorIndex = 1 # 起点颜色:绿
else:
self.blockcolorIndex = 0 # 未选择菜单情况下默认为设计迷宫操作,填充黑色
def selectend(self):
if not self.selectedEnd:
self.blockcolorIndex = 2 # 终点颜色:红
else:
self.blockcolorIndex = 0
def selectfind(self):
self.blockcolorIndex = 3 # 寻找出的最短路径的颜色:黄
self.Astar()
self.route.pop(-1)
self.route.pop(0)
for i in self.route:
self.canvas.create_rectangle((i.x + 1) * 30, (i.y + 1) * 30, (i.x + 2) * 30, (i.y + 2) * 30, fill='yellow')
def Astar(self):
# 将起点放到open表中
self.openList.append(self.startPoint)
while (not self.isOK):
# 先检查终点是否在open表中,若有则结束
if self.inOpenList(self.endPoint) != -1: # 在open表中,程序结束
self.isOK = True #
self.end = self.openList[self.inOpenList(self.endPoint)]
self.route.append(self.end)
self.te = self.end
while (self.te.parentPoint != 0):
self.te = self.te.parentPoint
self.route.append(self.te)
else:
self.sortOpenList() # 将估值最小的节点放在index = 0
current_min = self.openList[0] # 估值最小节点
self.openList.pop(0)
self.closeList.append(current_min)
# 设current_min节点,并放到open 表
if current_min.x - 1 >= 0: # 没有越界
if (self.mapStatus[current_min.y][current_min.x - 1]) != 0: # 无障碍点,可前行路径
self.temp1 = mapPoint(current_min.x - 1, current_min.y, current_min.distanceStart + 1,
self.endPoint.x, self.endPoint.y, current_min)
if self.inOpenList(self.temp1) != -1: # open表存在相同的节点
if self.temp1.evaluate() < self.openList[self.inOpenList(self.temp1)].evaluate():
self.openList[self.inOpenList(self.temp1)] = self.temp1
elif self.inCloseList(self.temp1) != -1: # 否则查看close表是否存在相同的节点,若存在进行if判断
if self.temp1.evaluate() < self.closeList[self.inCloseList(self.temp1)].evaluate():
self.closeList[self.inCloseList(self.temp1)] = self.temp1
else: # open、close表都不存在 temp1
self.openList.append(self.temp1)
if current_min.x + 1 < 15:
if (self.mapStatus[current_min.y][current_min.x + 1]) != 0: # 无障碍点,可前行路径
self.temp2 = mapPoint(current_min.x + 1, current_min.y, current_min.distanceStart + 1,
self.endPoint.x, self.endPoint.y, current_min)
if self.inOpenList(self.temp2) != -1: # open表存在相同的节点
if self.temp2.evaluate() < self.openList[self.inOpenList(self.temp2)].evaluate():
self.openList[self.inOpenList(self.temp2)] = self.temp2
elif self.inCloseList(self.temp2) != -1: # 否则,查看close表是否存在相同的节点(存在)
if self.temp2.evaluate() < self.closeList[self.inCloseList(self.temp2)].evaluate():
self.closeList[self.inCloseList(self.temp2)] = self.temp2
else:
self.openList.append(self.temp2)
if current_min.y - 1 >= 0:
if (self.mapStatus[current_min.y - 1][current_min.x]) != 0: # 无障碍点,可前行路径
self.temp3 = mapPoint(current_min.x, current_min.y - 1, current_min.distanceStart + 1,
self.endPoint.x, self.endPoint.y, current_min)
if self.inOpenList(self.temp3) != -1: # open表中存在相同的节点
if self.temp3.evaluate() < self.openList[self.inOpenList(self.temp3)].evaluate():
self.openList[self.inOpenList(self.temp3)] = self.temp3
elif self.inCloseList(self.temp3) != -1: # 否则,查看close表是否存在相同的节点(存在)
if self.temp3.evaluate() < self.closeList[self.inCloseList(self.temp3)].evaluate():
self.closeList[self.inCloseList(self.temp3)] = self.temp3
else:
self.openList.append(self.temp3)
if current_min.y + 1 < 15:
if (self.mapStatus[current_min.y + 1][current_min.x]) != 0: # 无障碍点,可前行路径
self.temp4 = mapPoint(current_min.x, current_min.y + 1, current_min.distanceStart + 1,
self.endPoint.x, self.endPoint.y, current_min)
if self.inOpenList(self.temp4) != -1: # open表存在相同的节点
if self.temp4.evaluate() < self.openList[self.inOpenList(self.temp4)].evaluate():
self.openList[self.inOpenList(self.temp4)] = self.temp4
elif self.inCloseList(self.temp4) != -1: # 否则查看close表是否存在相同的节点(存在)
if self.temp4.evaluate() < self.closeList[self.inCloseList(self.temp4)].evaluate():
self.closeList[self.inCloseList(self.temp4)] = self.temp4
else:
self.openList.append(self.temp4)
#作障碍物
def drawMapBlock(self, event):
x, y = event.x, event.y
if (30 <= x <= 480) and (30 <= y <= 480):
i = int((x // 30) - 1)
j = int((y // 30) - 1)
# 记录下起止点,保证不能选择多个起点或者多个终点
if self.blockcolorIndex == 1 and not self.selectedStart:
self.startPoint = mapPoint(i, j, 0, 0, 0, 0)
self.selectedStart = True
self.canvas.create_rectangle((i + 1) * 30, (j + 1) * 30, (i + 2) * 30, (j + 2) * 30,
fill=self.blockcolor[self.blockcolorIndex])
self.blockcolorIndex = 0
elif self.blockcolorIndex == 2 and not self.selectedEnd:
self.endPoint = mapPoint(i, j, 0, 0, 0, 0)
self.selectedEnd = True
self.canvas.create_rectangle((i + 1) * 30, (j + 1) * 30, (i + 2) * 30, (j + 2) * 30,
fill=self.blockcolor[self.blockcolorIndex])
self.blockcolorIndex = 0
else:
self.canvas.create_rectangle((i + 1) * 30, (j + 1) * 30, (i + 2) * 30, (j + 2) * 30,
fill=self.blockcolor[self.blockcolorIndex])
self.mapStatus[j][i] = self.blockcolorIndex
# 检查终点是否在open表中
def endInOpenList(self):
for i in self.openList:
if self.endPoint[0] == i.x and self.endPoint[1] == i.y:
return True
return False
# 将节点加入open表前,检查该节点是否在open表中
def inOpenList(self, p1):
for i in range(0, len(self.openList)):
if p1.isEq(self.openList[i]):
return i
return -1
# 将节点加入open表前,检查该节点是否在close表中
def inCloseList(self, p1):
for i in range(0, len(self.closeList)):
if p1.isEq(self.closeList[i]):
return i # 若在返回索引
return -1 # 不在返回-1
# 将估值最小的排在 index = 0
def sortOpenList(self):
if len(self.openList) > 0:
if len(self.openList) > 1:
for i in range(1, len(self.openList)):
if self.openList[i].evaluate() < self.openList[0].evaluate():
self.t = self.openList[0]
self.openList[0] = self.openList[i]
self.openList[i] = self.t
class mapPoint(object):
def __init__(self, x, y, distanceStart, endX, endY, parentPoint):
self.x = x
self.y = y
self.distanceStart = distanceStart
self.endX = endX
self.endY = endY
self.parentPoint = parentPoint # 前一个节点
def evaluate(self): #估值函数
return self.distanceStart + abs(self.x - self.endX) + abs(self.y - self.endY)
def isEq(self, point):
if point.x == self.x and point.y == self.y:
return True
else:
return False
def main():
Maze()
if __name__ == '__main__':
main() |
8e670ce1ff3c71f6756590121cb01a5d6df70326 | goodsosbva/algorithm | /328.py | 717 | 4.125 | 4 | # 328. odd even linked list
from LinkedList import Node
def oddEvenList(head: Node) -> Node:
if head is None:
return None
odd = head
even = head.next
even_head = head.next
# 반복하면서 홀짝 노드 처리
while even and even.next:
odd.next, even.next = odd.next.next, even.next.next
odd, even = odd.next, even.next
# 홀수 노드의 마지막을 짝수 헤드로 연결
odd.next = even_head
return head
linkedlist = Node(1)
linkedlist.add(Node(2))
linkedlist.add(Node(3))
linkedlist.add(Node(4))
linkedlist.add(Node(5))
linkedlist.add(Node(None))
linkedlist.prt()
sol = oddEvenList(linkedlist)
sol.prt()
|
e7c4952babc496aba214d33670130aa26528b237 | ManoMambane/Python-PostgresSQL | /A Full Python Refresher/33_first_class_functions/divider.py | 258 | 3.8125 | 4 | def divide(dividend, divisor):
if divisor == 0:
raise ZeroDivisionError("Cannot divide by 0")
return dividend / divisor
def Calculate(*values, operator):
return operator(*values)
result = Calculate(25, 5, operator=divide)
print(result) |
0dcb701abfef4500d352bff0d030a8887f016461 | ThoStart/amstelhaegenezen | /library/start.py | 2,479 | 3.921875 | 4 | # Request user input the first time
def start():
print("1: Random")
print("2: Random + Hill climbing")
print("3: Random + Simulated annealing")
print("4: Greedy")
print("5: Greedy + Hill climbing")
print("6: Greedy + Simulated annealing")
# let user choose the algorithm
chosen_algorithm = input("Algorithm: ")
while (len(str(chosen_algorithm)) > 1 or
chosen_algorithm.isdigit() == False or
int(chosen_algorithm) > 6 or
int(chosen_algorithm) <= 0):
print("Invalid input, try again.")
chosen_algorithm = input("Algorithm: ")
# let user choose the water layout
print("1: 2:\n◼︎ ◼︎ ◼︎ ◼︎ ◻︎ ◻︎ ◼︎ ◼︎ ◻︎ ◻︎ ◼︎ ◼︎\n◼︎ ◼︎ ◻︎ ◻︎ ◻︎ ◻︎ ◼︎ ◼︎ ◻︎ ◻︎ ◼︎ ◼︎\n◼︎ ◼︎ ◻︎ ◻︎ ◻︎ ◻︎ ◻︎ ◻︎ ◻︎ ◻︎ ◻︎ ◻︎\n◻︎ ◻︎ ◻︎ ◻︎ ◼︎ ◼︎ ◻︎ ◻︎ ◻︎ ◻︎ ◻︎ ◻︎\n◻︎ ◻︎ ◻︎ ◻︎ ◼︎ ◼︎ ◼︎ ◼︎ ◻︎ ◻︎ ◼︎ ◼︎\n◻︎ ◻︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◼︎ ◻︎ ◻︎ ◼︎ ◼︎")
water_layout = input("Water layout: ")
while (len(str(water_layout)) > 1 or
water_layout.isdigit() == False or
int(water_layout) > 2 or
int(water_layout) <= 0):
print("Invalid input, try again.")
water_layout = input("Water layout: ")
# let user choose the number of runs
number_of_runs = input("Number of runs: ")
while (number_of_runs.isdigit() == False or int(number_of_runs) <= 0):
print("Invalid input, try again.")
number_of_runs = input("Number of runs: ")
# let user choose to visualize data with tkinter
visualize_data = input("Visualize data (y/n): ")
while (visualize_data.upper().startswith('Y') == False and
visualize_data.upper().startswith('N') == False):
print("Invalid input, try again.")
visualize_data = input("Visualize data (y/n): ")
# let user choose to plot data with matplotlib
plot_data = input("Plot data (y/n): ")
while (plot_data.upper().startswith('Y') == False and
plot_data.upper().startswith('N') == False):
print("Invalid input, try again.")
plot_data = input("Plot data (y/n): ")
# return chosen variables
return int(chosen_algorithm), int(water_layout), int(number_of_runs), visualize_data.upper()[0], plot_data.upper()[0]
|
e882792dab53595efd61b95cceb7080f0992cf30 | maigimenez/cracking | /chapter_02/tests/test_08.py | 784 | 3.65625 | 4 | import unittest
from chapter_02.src.answer_08 import circular_node
from chapter_02.src.LinkedList import LinkedList, Node
class TestIntersection(unittest.TestCase):
def test_empty_list(self):
self.assertIs(circular_node(None), None)
self.assertEqual(circular_node(LinkedList()), None)
def test_intersection(self):
fst_list = LinkedList(['A', 'B'])
self.assertEqual(circular_node(fst_list), None)
fst_list.append_to_tail('C')
fst_list.append_to_tail('D')
fst_list.append_to_tail('E')
fst_list.append_to_tail('F')
loop_node = fst_list._head._next._next
fst_list._tail._next = loop_node
self.assertEqual(circular_node(fst_list), loop_node)
if __name__ == '__main__':
unittest.main() |
791846071c882eab3924e3cddb1b4bbe5e2e942a | FaroukAjimi/holbertonschool-interview | /0x16-rotate_2d_matrix/0-rotate_2d_matrix.py | 493 | 4.03125 | 4 | #!/usr/bin/python3
"""
Rotation function
"""
def rotate_2d_matrix(matrix):
"""matrix - that roatates
2d matrix
@matrix: the matrixe to rotate"""
l = len(matrix)
for i in range(l // 2):
for y in range(i, l - i - 1):
temp = matrix[i][y]
matrix[i][y] = matrix[l - 1 - y][i]
matrix[l - 1 - y][i] = matrix[l - 1 - i][l - 1 - y]
matrix[l - 1 - i][l - 1 - y] = matrix[y][l - 1 - i]
matrix[y][l - 1 - i] = temp
|
777dc6f2a80be80ab97281515cdd7234cf26dfa3 | DanPsousa/Python | /QPythonparaZumbi1.py | 173 | 4.15625 | 4 | num = int(input("Digite um numero de 0 a 10:"))
while (num < 0 or num > 10):
num = float(input("Invalido,Digite uma numero de 0 a 10: "))
print("Numero valido:",num)
|
bdff9232242963e92658b186dda002f41f5ce385 | vikramzsingh/Python | /1_2_3___n.py | 109 | 4.0625 | 4 | #Display 1,2,3,...n
n=int(input("Enter the value of n: "))
i=1
while(i<=n):
print(i)
i=i+1
|
ea32d41cb5aa1096becd4f1f8fdcea8b52f633c9 | onursengul01/Ping_Scanner_Automation- | /Ping_Scanner.py | 673 | 3.625 | 4 | import os
import pyfiglet
class Ping:
def __init__(self):
pass
def ping(self):
result = pyfiglet.figlet_format("Ping Scanner")
print(result)
ping = input("Enter an ip address to scan or a website domain\n")
os.system(f"ping {ping}")
print()
if ping == "":
os.system("cls")
return s.ping()
def Again():
while True:
root = input("Would you like to ping more ip's or website domains? [y] or [n]\n")
if root == "y":
os.system("cls")
return s.ping()
if root == "n":
exit()
Again()
s = Ping()
s.ping()
|
e5c75011af367bea4f8b636d9993cd40767f1c48 | jordanforbes/queuealgos | /sllalgos.py | 1,873 | 3.921875 | 4 | class Node:
def __init__(self, valueInput):
self.value = valueInput
self.next = None
class SLL:
def __init__(self):
self.head = None
def removefront(self):
if self.head == None:
return self
else:
self.head = self.head.next
return self
def addtoFront(self, value):
newnode = Node(value)
newnode.next = self.head
self.head = newnode
return self
def contains(self, valueToFind):
if self.head == None:
return False
else:
runner = self.head
while runner != None:
if runner.value == valueToFind:
print("true")
return True
else:
runner = runner.next
print("false")
return False
def length(self):
runner = self.head
counter = 1
# print(runner.next.next.next.next)
while runner.next is not None:
runner = runner.next
counter +=1
# print(counter)
print(f'The Length is {counter}')
return counter
def display(self):
ans = ''
runner = self.head
while runner.next is not None:
ans = ans+ str(runner.value)+' '
runner = runner.next
ans = ans+ str(runner.value)+' '
print(ans)
return ans
def length(pointer):
runner = pointer.head
counter = 1
# print(runner.next.next.next.next)
while runner.next is not None:
runner = runner.next
counter +=1
print(counter)
return counter
def display(pointer):
pass
a = Node(7)
b = Node(3)
c = Node(10)
d = Node(9)
a.next = b
b.next = c
c.next = d
newList = SLL()
newList.head = a
newList.length()
newList.display()
|
f7efcd2aa686c1127e362de558969e394a730e74 | umeshror/data-structures-algorithms | /palindrome/palindrome_number.py | 1,201 | 4.34375 | 4 | """
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.
Example 1:
Input: x = 121
Output: true
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Example 4:
Input: x = -101
Output: false
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
"""
def main(num):
is_neg = False
input_num = num
if num < 0:
is_neg = True
num *= -1
reverse = 0
while num > 0:
reminder = num % 10
reverse = reverse * 10 + reminder
num //= 10
if is_neg:
num *= -1
return input_num == reverse
print(main(121))
print(main(123))
print(main(-123))
print(main(-121))
def sol2(num):
if num < 0:
return False
return str(num) == str(num)[::-1]
print(sol2(121))
print(sol2(123))
print(sol2(-123))
print(sol2(-121))
|
e0067f4dabb6427ecc7d5a68f5faa252d02aec8b | nicolasmonteiro/Python | /Exercício(tuplas,listas e dicionário)/Q3Lista.py | 339 | 3.5 | 4 | import random
lista_Num = list()
lista_Num_Sorteados = list()
qnt_Jogos = 0
for l in range(0, 60):
lista_Num.append(l+1)
qnt_Jogos = int(input('Quantos jogos você quer sortear?'))
for h in range(0, qnt_Jogos):
lista_Num_Sorteados.append(random.sample(lista_Num, 6))
print('Jogo ', h+1, ': ', sorted(lista_Num_Sorteados[h]))
|
6c1e5a087bcc526b237596e3d84f7504ac29334f | rcgalbo/advent-of-code-20 | /Advent2020/day1.py | 384 | 3.5 | 4 | # rcgalbo day 1
with open('data/day1.txt') as f:
EXX = f.read()
def parse_input(inString):
numbers = [int(i) for i in inString.split('\n')]
for number1 in numbers:
for number2 in numbers:
for number3 in numbers:
if number1+number2+number3 == 2020:
return number1 * number2 * number3
print(parse_input(EXX)) |
acbac4308ac023b4eb2246e84c1cd8f7615e2215 | Jubayer-Hossain-Abir-404/Problem-Solving-Using-Python-and-Numerical-Methods | /ultimate newton divided interpolation.py | 936 | 3.75 | 4 | def newton(x,y,n,x1):
b=[0.0]*(n+1)
for i in range(0,n+1):
if(i==0):
b[i]=y[i]
elif(i==1):
b[i]=((y[i]-b[i-1])/(x[i]-x[0]))
elif(i==2):
b[i]=(((y[i]-y[i-1])/(x[i]-x[i-1]))-b[i-1])/(x[i]-x[0])
else:
bm=(((y[i]-y[i-1])/(x[i]-x[i-1]))-((y[i-1]-y[i-2])/(x[i-1]-x[i-2])))/(x[i]-x[i-2])
b[i]=(bm-b[i-1])/(x[i]-x[0])
sum=b[0]
Mu=1.0
for i in range(0,n):
for j in range(0,i+1):
Mu=Mu*(x1-x[j])
sum=sum+b[i+1]*Mu
Mu=1.0
print "The result is:",sum
def main():
n=input("Input the value of n:")
x=[0.0]*(n+1)
y=[0.0]*(n+1)
for i in range(0,n+1):
x[i]=float(input("Input the value of x:"))
for i in range(0,n+1):
y[i]=float(input("Input the value of y:"))
x1=float(input("Determine the value:"))
newton(x,y,n,x1)
if __name__=="__main__":
main()
|
a890ad334ef766a5210e095a767d59d26602905b | MalteMagnussen/PythonProjects | /week2/Exercises/one.py | 3,678 | 4.5625 | 5 | # ## Exercise 1
# 1. Create a python file with 3 functions:
# 1. `def print_file_content(file)` that can print content of a csv file to the console
# 2. `def write_list_to_file(output_file, lst)` that can take a list of tuple and write each element to a new line in file
# 1. rewrite the function so that it gets an arbitrary number of strings instead of a list
# 3. `def read_csv(input_file)` that take a csv file and read each row into a list
# 2. Add a functionality so that the file can be called from cli with 2 arguments
# 1. path to csv file
# 2. an argument `--file file_name` that if given will write the content to file_name or otherwise will print it to the console.
# 3. Add a --help cli argument to describe how the module is used
from PythonProjects.utils import webget
import argparse
import csv
def print_file_content(file):
"""1. `def print_file_content(file)` that can print content of a csv file to the console"""
# It should be able to print content of a csv file to console.
with open(file) as f:
reader = csv.reader(f)
for row in reader:
print(str(row))
# testing 1.
# filename = './iris_csv.csv'
# print_file_content(filename)
# ^Works
def write_list_to_file(output_file, *args):
"""`def write_list_to_file(output_file, lst)`
that can take a list of tuple
and write each element to a new line in file"""
# rewrite the function so that it gets an arbitrary number of strings instead of a list
toFile = ""
for x in args:
toFile += x + "\n"
with open(output_file, 'w') as file_object:
print("Writing {} to {}".format(toFile, output_file))
file_object.write(toFile)
# Testing write_list_to_file
# testStringOne = "First Line"
# testStringTwo = "Second Line"
# testStringThree = "Third Line"
# filename = "testFile.txt"
# print("\n___________________________________________\nSecond Test::\n")
# write_list_to_file(filename, testStringOne, testStringTwo, testStringThree)
# ^Works
# `def read_csv(input_file)` that take a csv file and read each row into a list
def read_csv(input_file):
list = []
with open(input_file) as f:
reader = csv.reader(f)
for row in reader:
list.append(row)
return list
# print("\n___________________________________________\nThird Test::\n")
# filename = "iris_csv.csv"
# print(read_csv(filename))
# 2. Add a functionality so that the file can be called from cli with 2 arguments
# 1. path to csv file
# 2. an argument `--file file_name` that if given will write the content to file_name or otherwise will print it to the console.
# Add a --help cli argument to describe how the module is used
parser = argparse.ArgumentParser(
description='A program that can handle CSV')
# Positional arg
parser.add_argument('path', help='path to csv file')
# Optional Arg [- , --]
parser.add_argument('-f', '--file_name',
help='if given will write the content to file_name or otherwise will print it to the console.')
args = parser.parse_args()
def listToString(s):
str1 = ","
return (str1.join(s))
if __name__ == '__main__':
args = parser.parse_args()
path = args.path
myContent = read_csv(path)
content = ""
for x in myContent:
content += listToString(x) + "\n"
if (args.file_name != None):
file_name = args.file_name
# write the content to file_name
with open(file_name, 'w') as file_object:
print("Writing {} to {}".format(content, file_name))
file_object.write(content)
else:
# Print it to console
print_file_content(path)
|
ff42afe3cab4fe3a37752cbf0fb6c46c98bf11c3 | valentinegarikayi/Getting-Started- | /MIT/PS_0.py | 406 | 4.25 | 4 | #!/usr/bin/env python
#Find a positive integer that is divisible by both 11 and 12
counter =0
while True:
if counter>=10:
break
counter = counter+1
Ten_integers=int(input('Please enter an integer:'))
if Ten_integers%2==0:
print ('You have just entered an even number')
else:
print ('This is an odd number')
print('Even numbers are', Even, 'Odd numbers are',Odd)
|
93397bc295c5c6fe46ed9c69decc6f12f92d3a66 | leoflotor/numerical_computation | /condition_number_estimation/condition_number.py | 3,888 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# Author: Leonardo Flores Torres
# Student ID: S32015703W
import numpy as np
# Initial matrix and vector of the system of equations ofthe
# form Ax = b to be used for the computation of the conditional
# number k*.
matrixA = np.array([[1, 1/2, 1/3],
[1/2, 1/3, 1/4],
[1/3, 1/4, 1/5]],
dtype=np.float)
y0 = np.array([0.2190,
0.0470,
0.6789],
dtype=np.float)
# Infinity-norm function
def infty_norm(matrix):
row_sum = np.array([])
for i in range(0, matrix.shape[0]):
row = np.sum(np.abs(matrix[i]))
row_sum = np.append(row_sum, row)
return row_sum.max()
# The condition number k* = alph * v .
# The function for the factor v is defined as follows:
def v(matrix, vector, iterations):
for i in range(0, iterations+1):
vector = vector / infty_norm(vector)
vector = lu_solution(matrix, vector)
return infty_norm(vector), vector
# The function to calculate the condition number k*:
def k(matrix, vector, iterations):
return v(matrix, vector, iterations) * infty_norm(matrix)
# LU decomposition method with partial pivoting.
def lu_solution(matrix, vector):
# This will make a copy of the original matrix and column-vector
# which will be used to find the solution x for the system Ax = b.
matrix_A = matrix.copy()
matrix_b = vector.copy()
# Making sure that float numbers will be used.
matrix_A = np.array(matrix_A, dtype=np.float)
matrix_b = np.array(matrix_b, dtype=np.float)
indx = np.arange(0, matrix_A.shape[0])
for i in range(0, matrix_A.shape[0]-1):
am = np.abs(matrix_A[i, i])
p = i
for j in range(i+1, matrix_A.shape[0]):
if np.abs(matrix_A[j, i]) > am:
am = np.abs(matrix_A[j, i])
p = j
if p > i:
for k in range(0, matrix_A.shape[0]):
hold = matrix_A[i, k]
matrix_A[i, k] = matrix_A[p, k]
matrix_A[p, k] = hold
ihold = indx[i]
indx[i] = indx[p]
indx[p] = ihold
for j in range(i+1, matrix_A.shape[0]):
matrix_A[j, i] = matrix_A[j, i] / matrix_A[i, i]
for k in range(i+1, matrix_A.shape[0]):
matrix_A[j, k] = matrix_A[j, k] - \
matrix_A[j, i] * matrix_A[i, k]
# matrix_A
# matrix_b
# indx
x = np.zeros(matrix_A.shape[0])
for k in range(0, matrix_A.shape[0]):
x[k] = matrix_b[indx[k]]
for k in range(0, matrix_A.shape[0]):
matrix_b[k] = x[k]
# x
# matrix_b
y = np.zeros(matrix_A.shape[0])
y[0] = matrix_b[0]
for i in range(1, matrix_A.shape[0]):
sum = 0.0
for j in range(0, i):
sum = sum + matrix_A[i, j] * y[j]
y[i] = (matrix_b[i] - sum)
# y
x[-1] = y[-1] / matrix_A[-1, -1]
for i in range(matrix_A.shape[0]-1, -1, -1):
sum = 0.0
for j in range(i+1, matrix_A.shape[0]):
sum = sum + matrix_A[i, j] * x[j]
x[i] = (y[i] - sum) / matrix_A[i, i]
return x
v_factor, vector = v(matrixA, y0, 4)
# Note that k* is defined as alpha * v. Where alpha is the
# infinity-norm of the matrix A.
k = infty_norm(matrixA) * v_factor
# Python equivalent to MATLAB cond function.
cond_norm_2 = np.linalg.cond(matrixA, 2)
cond_norm_1 = np.linalg.cond(matrixA, 1)
# The rcond function from MATLAB is the reciprocal of the k-1
# norm cond function.
print('The calculated condition number is: %s' % k)
print('The solution column-vector is: %s' % vector)
print('Conditional number k2 in the k-2 norm: %s' % cond_norm_2)
print('Conditional number k1 in the k-1 norm: %s' % cond_norm_1)
print('Estimate of the reciprocal of k1: %s' % (1 / cond_norm_1))
|
4df90ed337cc21a0cae4b8cf118b5f937ce70b75 | zudcow/prog2_assignment | /b50-39_soviet_housing.py | 3,085 | 3.9375 | 4 | import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
time = input("Time (HH.MM.): ")
def time_conversion(time):
# converts input string time to int minutes
try:
hour, minutes = time.strip('.').split('.')
hour, minutes = int(hour), int(minutes)
except ValueError:
return None
if hour < 0 or hour > 24:
return None
if hour == 0:
hour = 24
if minutes < 0 or minutes > 59:
return None
minutes += hour*60
return minutes
def lights(time):
# checkin if day/night time
# and light conditions with respective hours converted to mins:
if time_conversion(time):
mins = time_conversion(time)
# time between 2AM and 5.30AM
if mins >= (120) and mins < (330):
return 'Night_off'
# time between 5.30AM till 8PM
elif mins >= 330 and mins < 1200:
return 'Day'
else:
# remaining time from 8PM till 5.30AM when lights are on
return 'Night_on'
else:
# in case invalid time input
print('Invalid input. Accepted time format: (HH.MM.)')
return None
def chance(time):
# defines chance for individual lights to be switched on
# from 95% chance at 8PM gradually decreasing to 0% at 2AM
if time_conversion(time) is not None:
hrs = time_conversion(time)/60
if hrs < 20:
hrs += 24
hrs -= 20
return 95 - (hrs*15.8)
def windows():
# creating the array representing the windows
# applying chance of switched on if applicable
mode = lights(time)
a = np.zeros(20)
if mode == 'Night_on':
for i in range(20):
if np.random.randint(1, 101) <= chance(time):
a[i] = 1
a = a.reshape(5, 4)
return a
def clrs():
# setting 'glass' and 'wall' colors in relation to day/night
# plus title
mode = lights(time)
if mode:
if mode == 'Day':
glass_clr = ['#add8e6', 'y']
wall_clr = '#e7ccab'
title = 'Daytime (5.30-19.59)'
else:
glass_clr = ['#161616', '#fff59c']
wall_clr = '#453a2c'
title = 'Night time (20.00-5.29)'
return glass_clr, wall_clr, title
try:
# color parameters for windows and wall
# setting the boundaries for on/off lights
glass, wall, title = clrs()
cmap = mpl.colors.ListedColormap(glass)
bounds = [0., 0.5, 1.]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
wd = windows()
im = plt.imshow(wd, interpolation='none', cmap=cmap, norm=norm)
# creating 'walls' with minor ticks and step correction, removing ticklables
ax = plt.gca()
ax.set_xticks(np.arange(-.5, 4, 1), minor=True)
ax.set_yticks(np.arange(-.5, 5, 1), minor=True)
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.grid(which='minor', color=wall, linestyle='-', linewidth=20)
ax.set(title=title)
plt.show()
except UnboundLocalError:
# in case invalid input exception handling
pass |
960f46aed0e4d4dd88d0d093ad381fcf975181d3 | ICimpoes/python-train | /scripts/functions/function_arguments.py | 727 | 3.5 | 4 | def f(*args):
print(type(args), args)
f()
f(1)
f(1, 2)
def f(**args):
print(type(args), args)
f()
f(a=1)
f(a=1, b=2)
f(a=1, b=2, c='3')
# *args -> tuple, **kwargs -> dict
def f(a, *args, **kwargs):
print(a, args, kwargs)
f(1)
f(1, 2)
f(1, 2, 3, 4, 5)
f(1, 2, 3, 4, 5, b=1, c=2, key=3)
f((1, 2, 3, 4, 5), b=1, c=2, key=3)
f(*(1, 2, 3, 4, 5), **{'b': 1, 'c': 2, 'key': 3})
print(list(zip(*zip((1, 2), (3, 4)))))
# key word only arguments
def konly(a, *b, c):
print(a, b, c)
# konly(1, 2, 3, 4)
konly(1, c=2)
def konly(a, *, b, c):
print(a, b, c)
konly(1, b=2, c='asdasd')
# konly(a, **, c) - invalid
# ordering rules
def f(a, *b, c, **d):
print(a, b, c, d)
f(1, 2, 3, aa=1, b=3, c='c') |
1c0c6acdeddf5cbf9a5ddaade2bb97cf8815984b | bhkangw/Python | /python_checkerboard_assignment.py | 912 | 4.5 | 4 | # Assignment: Checkerboard
# Write a program that prints a 'checkerboard' pattern to the console.
# Your program should require no input and produce console output that looks like so:
# * * * *
# * * * *
# * * * *
# * * * *
# * * * *
# * * * *
# * * * *
# * * * *
# Each star or space represents a square.
# On a traditional checkerboard you'll see alternating squares of red or black.
# In our case we will alternate stars and spaces. The goal is to repeat a process several times.
# This should make you think of looping.
def create_checkerboard():
line_one = "* " * 4
line_two = " *" * 4
for count in range(0,5): # uses a range so it repeats 5 times
print line_one
print line_two
create_checkerboard()
def checkerboard(): # CD different solution
for i in range(0,10):
if i%2 == 0:
print "* " * 5
else:
print " *" * 5
checkerboard() |
c7f2b96083e7487ab3a497b477764d728600595d | Dhaval2110/Python | /python_ closure.py | 538 | 4.1875 | 4 | def first(x):
def second():
#x=x+2
print(x)
second()
first(100)
'''
Advantages :
With Python closure, we don’t need to use global values. This is because they let us refer to nonlocal variables. A closure then provides some form of data hiding.
When we have only a few Python methods (usually, only one), we may use a Python3 closure instead of implementing a class for that. This makes it easier on the programmer.
A closure, lets us implement a Python decorator.
A closure lets us invoke Python function outside its scope.
'''
|
5db93455ee82e140dfda24a7e0c6248c2649a352 | starkblaze01/Algorithms-Cheatsheet-Resources | /Python/EncryptionAlgo_Py/CaesarCipher.py | 1,082 | 4.09375 | 4 | def encrypt(text,key):
result=""
ascno_e=0
for i in text:
if i.isupper():
ascno_e=ord('A')+((ord(i)-ord('A')+key)%26)
result=result+chr(ascno_e)
elif i.islower():
ascno_e= ord('a')+((ord(i)-ord('a')+key)%26)
result=result+chr(ascno_e)
elif i==" ":
result=result+" "
else:
result="INVALID INPUT you can only encrypt alphabets with this algo"
return result
return result
def decrypt(text,key):
result=""
ascno_d=0
for i in text:
if i.isupper():
ascno_d=ord('A')+((ord(i)-ord('A')-key)%26)
result=result+chr(ascno_d)
elif i.islower():
ascno_d= ord('a')+((ord(i)-ord('a')-key)%26)
result=result+chr(ascno_d)
elif i==" ":
result=result+" "
else:
result="INVALID INPUT you can only encrypt alphabets with this algo"
return result
if __name__ == "__main__":
x=encrypt('Hey Fellas',4)
print(x)
print("##")
print(decrypt(x,4)) |
8df5e467c6577edc62e23339e2362fa067a23c64 | nayanex/Googleinterview | /Coursera/fibonacci.py | 262 | 3.65625 | 4 | # Uses python3
def calc_fib(n):
fib = []
fib.append(0)
fib.append(1)
if n < 2:
return fib[n]
for index in range(2,n+1):
fib.append(fib[index-1] + fib[index-2])
return fib[n]
n = int(input())
print(calc_fib(n))
|
7c6d4188dc3f52c072a1623f874d8e9f3939a2c6 | miono/aoc2017 | /7/7b.py | 2,233 | 3.5625 | 4 | #!/usr/bin/env python
f = open('input').readlines()
towerlist = []
resolved_tower = []
for i in f:
towerdef = i.split()
if len(towerdef) > 2:
tmplist = [towerdef[0], int(towerdef[1].strip('()')), map(lambda it: it.strip(','), towerdef[3:])]
else:
tmplist = [towerdef[0], int(towerdef[1].strip('()'))]
towerlist.append(tmplist)
# Resolve tower
# resolved_tower.append(['dgoocsw', 99, ['ifajhb', 'gqmls', 'sgmbw', 'ddkhuyg', 'rhqocy']])
def resolve(tower):
towerdef = []
#Find towerdef
for towerdef in towerlist:
if towerdef[0] == tower:
tmpweight = towerdef[1]
resolved_tower.append([tower, tmpweight])
print [tower, tmpweight]
break
if len(towerdef) == 2:
return 1
for subtower in towerdef[2]:
resolve(subtower)
weight = 0
def get_full_weight(tower):
global weight
towerdef = []
#Find towerdef
for towerdef in towerlist:
if towerdef[0] == tower:
weight += towerdef[1]
# print weight
break
if len(towerdef) == 2:
return 1
for subtower in towerdef[2]:
get_full_weight(subtower)
# resolve('dgoocsw')
get_full_weight('ifajhb')
print weight
weight = 0
print '%%%%%%%%%'
get_full_weight('gqmls')
print weight
weight = 0
print '%%%%%%%%%'
get_full_weight('sgmbw')
print weight
weight = 0
print '%%%%%%%%%'
get_full_weight('ddkhuyg')
print weight
weight = 0
print '%%%%%%%%%'
get_full_weight('rhqocy')
print weight
weight = 0
print '#########'
get_full_weight('fqvvrgx')
print weight
weight = 0
print '%%%%%%%%%'
get_full_weight('szmnwnx')
print weight
weight = 0
print '%%%%%%%%%'
get_full_weight('jfdck')
print weight
weight = 0
print '%%%%%%%%%'
print '##########'
get_full_weight('marnqj')
print weight
weight = 0
print '%%%%%%%%%'
get_full_weight('moxiw')
print weight
weight = 0
print '%%%%%%%%%'
get_full_weight('sxijke')
print weight
weight = 0
print '%%%%%%%%%'
get_full_weight('ojgdow')
print weight
weight = 0
print '%%%%%%%%%'
get_full_weight('fnlapoh')
print weight
weight = 0
print '%%%%%%%%%'
print '#############'
get_full_weight('upair')
print weight
weight = 0
get_full_weight('mkrrlbv')
print weight
weight = 0
get_full_weight('vqkwlq')
print weight
weight = 0
get_full_weight('wsrmfr')
print weight
weight = 0
|
274e54d709d02a9c782ab0c2ebffeab8cacc55d7 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/nksvuy001/question2.py | 764 | 4.0625 | 4 | """program that uses a recursive function to count the number of pairs of repeated characters in a string
vuyolwethu nkosi
4 may 2014"""
msg=input("Enter a message:\n") #get message from user
def count_the_pairs(msg):
#message=input("Enter a message:\n")
if len(msg)<=1: #if the string is empty or if it only has one letter ie.Base case
return 0
elif msg[0]==msg[1]: #if the letter is the same as the letter next to it
return 1 + count_the_pairs(msg[2:]) #return 1 and add the call of the next function ie.Recursive step
else:
return count_the_pairs(msg[1:]) #if there's no pairs it should return none
print("Number of pairs:",count_the_pairs(msg)) #print the output
#calling the function
|
50a9c3054108548dae3351d7cce4defcc41fa1a9 | mlui8518/GWC-Projects | /GWCProjects/social_network.py | 1,400 | 3.5 | 4 | class User:
def __init__(self, name):
self.name = name
self.id = id
self.connections = []
answer = input("Press 'a' to add connections; Press 'p' to make a post; Press 'm' to write a message; Press 'e' to exit")
selfConnections = {}
posts = {}
while answer != 'e':
def add_connections ():
#selfConnections = {}
counter = 1
while True:
Username = input("First Username (Type 'done' to quit):")
if Username == 'done':
break
selfConnections[counter] = Username
counter += 1
print(selfConnections)
def add_post ():
#posts = {}
counter = 1
while True:
timeMarker = input("Time Marker (Type 'done' to quit):")
post = input("Post Content:")
if post == 'done':
break
posts[counter] = timeMarker, post
counter += 1
print(posts)
#specific
def add_message ():
messages = {}
counter = 1
while
messageWho = input("Who are you sending this message to?")
return messageWho
messageText = input("Type your message.")
return messageText
print(messageWho, messageText)
if answer == "a":
add_connections()
answer = input("Press 'a' to add connections; Press 'p' to make a post; Press 'e' to exit")
if answer == "p":
add_post()
answer = input("Press 'a' to add connections; Press 'p' to make a post; Press 'e' to exit")
if answer == "e":
exit()
|
afac8e432cf378093d0d7541cb3e83d16bb56fa1 | nveenverma1/Dataquest | /Practice/15_Statistics_Intermediate/Measures of Variability-308.py | 5,973 | 3.84375 | 4 | ## 1. The Range ##
import pandas as pd
houses = pd.read_table('AmesHousing_1.txt')
def calc_range(arr):
min_arr = min(arr)
max_arr = max(arr)
return max_arr - min_arr
range_by_year = {}
years = houses['Yr Sold']
for year in years:
if year not in range_by_year:
range_by_year[year] = calc_range(houses[houses['Yr Sold'] == year]['SalePrice'])
else:
pass
print(range_by_year)
one = False
two = True
## 2. The Average Distance ##
C = [1,1,1,1,1,1,1,1,1,21]
def calc_avg_distance(arr):
arr_mean = np.array(C).mean()
distances = []
for i in arr:
distances.append(arr_mean - i)
dist_mean = np.array(distances).mean()
return dist_mean
avg_distance = calc_avg_distance(C)
print(avg_distance)
## 3. Mean Absolute Deviation ##
C = [1,1,1,1,1,1,1,1,1,21]
def calc_mad(arr):
arr_mean = np.array(C).mean()
distances = []
for i in arr:
distances.append(abs(arr_mean - i))
dist_mean = np.array(distances).mean()
return dist_mean
mad = calc_mad(C)
print(mad)
## 4. Variance ##
C = [1,1,1,1,1,1,1,1,1,21]
def calc_variance(arr):
arr_mean = np.array(C).mean()
distances = []
for i in arr:
distances.append((arr_mean - i)**2)
dist_mean = np.array(distances).mean()
return dist_mean
variance_C = calc_variance(C)
print(variance_C)
## 5. Standard Deviation ##
from math import sqrt
C = [1,1,1,1,1,1,1,1,1,21]
C = [1,1,1,1,1,1,1,1,1,21]
def calc_sd(arr):
arr_mean = np.array(C).mean()
distances = []
for i in arr:
distances.append((arr_mean - i)**2)
dist_mean = np.array(distances).mean()
return sqrt(dist_mean)
standard_deviation_C = calc_sd(C)
print(standard_deviation_C)
## 6. Average Variability Around the Mean ##
def standard_deviation(array):
reference_point = sum(array) / len(array)
distances = []
for value in array:
squared_distance = (value - reference_point)**2
distances.append(squared_distance)
variance = sum(distances) / len(distances)
return sqrt(variance)
std_dev = standard_deviation(houses['SalePrice'])
std_dev_by_year = {}
years = houses['Yr Sold']
for year in years:
if year not in std_dev_by_year:
std_dev_by_year[year] = standard_deviation(houses[houses['Yr Sold'] == year]['SalePrice'])
else:
pass
print(std_dev_by_year, '\n')
greatest_variability = max(std_dev_by_year, key=std_dev_by_year.get)
print(greatest_variability)
lowest_variability = min(std_dev_by_year, key=std_dev_by_year.get)
print(lowest_variability)
## 7. A Measure of Spread ##
sample1 = houses['Year Built'].sample(50, random_state = 1)
sample2 = houses['Year Built'].sample(50, random_state = 2)
def standard_deviation(array):
reference_point = sum(array) / len(array)
distances = []
for value in array:
squared_distance = (value - reference_point)**2
distances.append(squared_distance)
variance = sum(distances) / len(distances)
return sqrt(variance)
bigger_spread = 'sample 2'
st_dev1 = standard_deviation(sample1)
print('Sample 1 Std. Dev.', st_dev1)
st_dev2 = standard_deviation(sample2)
print('Sample 2 Std. Dev.', st_dev2)
## 8. The Sample Standard Deviation ##
def standard_deviation(array):
reference_point = sum(array) / len(array)
distances = []
for value in array:
squared_distance = (value - reference_point)**2
distances.append(squared_distance)
variance = sum(distances) / len(distances)
return sqrt(variance)
prices = houses['SalePrice']
st_devs = []
for i in range(5000):
Sample = prices.sample(10, random_state = i)
st_dev = standard_deviation(Sample)
st_devs.append(st_dev)
import matplotlib.pyplot as plt
plt.hist(st_devs)
plt.axvline(standard_deviation(houses['SalePrice']))
plt.show()
## 9. Bessel's Correction ##
def standard_deviation(array):
reference_point = sum(array) / len(array)
distances = []
for value in array:
squared_distance = (value - reference_point)**2
distances.append(squared_distance)
variance = sum(distances) / (len(distances)-1)
return sqrt(variance)
import matplotlib.pyplot as plt
st_devs = []
for i in range(5000):
sample = houses['SalePrice'].sample(10, random_state = i)
st_dev = standard_deviation(sample)
st_devs.append(st_dev)
plt.hist(st_devs)
plt.axvline(standard_deviation(houses['SalePrice']))
plt.show()
## 10. Standard Notation ##
sample = houses.sample(100, random_state = 1)
from numpy import std, var
pandas_stdev = sample['SalePrice'].std()
numpy_stdev = std(sample['SalePrice'], ddof=1)
print(pandas_stdev)
equal_stdevs = (pandas_stdev == numpy_stdev)
print(equal_stdevs)
pandas_var = sample['SalePrice'].var()
numpy_var = var(sample['SalePrice'], ddof=1)
print(pandas_var)
equal_vars = (pandas_var == numpy_var)
print(equal_vars)
## 11. Sample Variance — Unbiased Estimator ##
population = [0, 3, 6]
samples = [[0,3], [0,6],
[3,0], [3,6],
[6,0], [6,3]
]
# Calculating Population Std dev and Variance
from numpy import std, var
pop_var = var(population)
pop_std = std(population)
# Calculating Sample Std dev and Variance
def standard_deviation(array):
reference_point = sum(array) / len(array)
distances = []
for value in array:
squared_distance = (value - reference_point)**2
distances.append(squared_distance)
variance = sum(distances) / (len(distances)-1)
return (variance, sqrt(variance))
variances = []
st_devs = []
for i in samples:
st_dev_n_var = standard_deviation(i)
variances.append(st_dev_n_var[0])
st_devs.append(st_dev_n_var[1])
from statistics import mean
equal_var = (pop_var == mean(variances))
equal_stdev = (pop_std == mean(st_devs))
print(equal_var)
print(equal_stdev) |
2156319e2fd1668d3c8ec88a0504cae8274e07d0 | Saurabh910/turtle-race | /main.py | 1,476 | 4.28125 | 4 | from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet!", prompt="Which turtle you bet would win?: ")
# Finish Line
def finish_line():
dec = Turtle()
dec.hideturtle()
dec.penup()
dec.goto(x=210, y=130)
dec.pendown()
dec.goto(x=240, y=130)
dec.goto(x=225, y=130)
dec.goto(x=225, y=-130)
dec.goto(x=210, y=-130)
dec.goto(x=240, y=-130)
dec.penup()
colors = ["red", "yellow", "orange", "green", "blue", "aquamarine", "purple"]
turtles = []
y_pos = -90
i = 0
for name in range(0, 7):
name = Turtle(shape="turtle")
name.penup()
name.color(colors[i])
i += 1
name.goto(x=-230, y=-y_pos)
y_pos += 30
turtles.append(name)
finish_line()
winning_distance = 225
if user_bet:
is_race_on = True
while is_race_on:
random_distance = random.randint(0, 10)
move_turtle = random.choice(turtles)
move_turtle.forward(random_distance)
moved_distance = move_turtle.xcor()
turtle_racing = turtles.index(move_turtle)
if moved_distance >= 225:
is_race_on = False
user_bet = colors.index(user_bet)
if user_bet == turtle_racing:
print("You have won the race!")
else:
print(f"You have lost the race. {colors[turtle_racing]} turtle has won the race!")
screen.exitonclick()
|
702751ddda4aa0c9df8ee52c96e78b9aeaa2e866 | hangnew/python_studies | /210901 JtoP 07/07-1.py | 927 | 3.578125 | 4 | # 정규 표현식 Regular Expressions
# 복잡한 문자열을 처리할 때 사용하는 기법, 줄여서 정규식이라고도 한다
# 정규식 없이 코딩
# 주민등록번호를 포함하고 있는 텍스트의 모든 주민등록번호의 쥣자리를 * 문자로 변경해 보자.
data = """
park 800905-1049118
kim 700905-1059119
"""
result = []
for line in data.split("\n"):
word_result = []
for word in line.split(" "):
if len(word) == 14 and word[:6].isdigit() and word[7:].isdigit():
word = word[:6] + "-" + "*******"
word_result.append(word)
result.append(" ".join(word_result))
print("\n".join(result))
# 정규식 코딩
import re
pat = re.compile("(\d{6})[-]\d{7}")
print(pat.sub("\g<1>-*******", data))
# \d : 숫자와 매치, [0-9]와 동일
# \d{6} : 숫자와 매치 + 6번 반복
# (\d{6}) : 그루핑 = \g<1>
# [-] : - 문자
# \g<1> : 첫번째 그룹
|
9f05c6935c956f6bf5455ef9b9652bf4eb657eb7 | In4y/1stpython | /python_test/dic_test.py | 1,047 | 3.71875 | 4 | # -*- coding:utf-8 -*-
# **FILENAME:
# **AUTHOR:
# **CREATED TIME:
# **FUN DESC :
# **MODIFIED BY :
# **MODIFIED TIME:
# **MODIFIED CONTENT:
# **REVIEWED BY:
# **REVIEWED TIME:
# **INPUT TABLE:
# **MID TABLE :
# **DIM TABLE :
# **OUTPUT TABLE:
score_dict = {
'yinandyi':88,
'killer':78,
'missa':90
}
print score_dict
print len(score_dict)
print score_dict['yinandyi'] #打印的顺序不一定是我们创建时的顺序,而且,不同的机器打印的顺序都可能不同,这说明dict内部是无序的,不能用dict存储有序的集合。
print "missa's score is:",score_dict.get('missa')
for x in score_dict:
if score_dict.get(x)>80:
print "they are good stu," ,x ,score_dict.get(x)
score_dict['yinandyi'] = 99
print score_dict
name = raw_input("enter a name:")
if name in score_dict:
print "i'm here"
elif name =="q":
quit()
else:
print "no %s" %name
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 74 }
sum =sum(d.itervalues())
print sum/len(d)
|
a52be5bf95297d1287123473e7a02bb171664047 | nirajacharya/Python | /SmallProjects/PRJ3ROCKpappersiaaors.py | 2,100 | 4.21875 | 4 | import random
computer_score=0
user_score=0
while True:
option=['rock', 'paper', 'scissor']
computer_choosed_option=random.choice(option)
user_input=input('''enter Your option
1)Rock
2)Paper
3)Scissor
press Q to Exit
Enter your value:'''
)
print('computer choose',computer_choosed_option)
if user_input.isdigit() == True:
user_input=int(user_input)
user_choosed_option=option[user_input-1]
print(user_choosed_option)
if computer_choosed_option == user_choosed_option:
user_score=user_score
computer_score=computer_score
elif computer_choosed_option=="rock":
if user_choosed_option=="paper":
user_score = user_score+1
computer_score=computer_score
if user_choosed_option=="scissor":
user_score=user_score
computer_score = computer_score+1
elif computer_choosed_option=="paper":
if user_choosed_option=="scissor":
user_score = user_score+1
computer_score=computer_score
if user_choosed_option=="rock":
computer_score = computer_score+1
user_score=user_score
elif computer_choosed_option=="scissor":
if user_choosed_option=="rock":
user_score = user_score+1
if user_choosed_option=="paper":
computer_score = computer_score+1
print("computerscore", computer_score)
print("UserScore", user_score)
else:
if user_input=="q" or "Q":
print("computerscore",computer_score)
print("UserScore",user_score)
if computer_score> user_score:
print("computer wins")
elif computer_score<user_score:
print("User Wins")
else:
print("This game is Draw")
exit()
else:
print("Enter only digits") |
e49cdd74796c267183216648b98dd3eaa44250d5 | kpu3uc/1824_GB_Python_1 | /Shishkin_Anatoliy_lesson_10/actions/my_iterators.py | 1,325 | 3.859375 | 4 | class IterObj: # просто класс-заглушка
pass
class IteratorEnergy:
"""Объект-итератор, имитация иссякающей энергии"""
def __init__(self, start=10):
self.i = start + 1
# У итератора есть метод __next__
def __next__(self):
self.i -= 1
if self.i >= 1:
return self.i
else:
raise StopIteration
class Accumulator(IterObj):
"""Объект Аккумулятор, поддерживающий интерфейс
итерации (итерируемый объект)"""
def __init__(self, energy=6):
self.energy = energy
def __iter__(self):
# Метод __iter__ должен возвращать объект-итератор
return IteratorEnergy(self.energy)
class Battery(IterObj):
"""Объект Батарейка, независимый итерируемый объект"""
def __init__(self, energy=3):
self.i = energy + 1
# Метод __iter__ должен возвращать объект-итератор
def __iter__(self):
return self
def __next__(self):
self.i -= 1
if self.i >= 1:
return self.i
else:
raise StopIteration
|
86a7cebfdf665e9239370bcff32c3435490ba4f8 | rickruan/my_git | /python/test_exception.py | 871 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# 定义函数
def t_func(var):
try:
return int(var)
except ValueError as e:
print("参数没有包含数字\n", e)
try:
fh = open("ruan_test", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print("Error: 没有找到文件或读取文件失败")
else:
print("内容写入文件成功")
fh.close()
try:
fh = open("ruan_test", "w")
try:
fh.write("这是一个测试文件,用于测试异常!!")
finally:
print("关闭文件")
fh.close()
except IOError:
print("Error: 没有找到文件或读取文件失败")
# 调用函数
t_func('xyz')
def mye(level):
if level < 1:
raise Exception('Invalid level:%s',level)
try:
mye(0)
except Exception as e:
print(e)
else:
print("End!")
|
4edf6765d220048afbe9000f39bc35f3e017cb66 | Ashish9426/Computer-Vision | /Computer Vision Tutorial/1. Reading and Writing Files/page2. reading pictures1.py | 399 | 3.53125 | 4 | # importing package
import cv2
import numpy as np
# step 1: open the file
img = cv2.imread('./messi5.jpg')
# step 2: perform operation(s)
# step 2.1: take an action
# step 2.2: generate output
# step 2.3: save the changes to a new file
# step 2.4: show the file on screen
cv2.imshow('messi', img)
# wait for user to press any key
cv2.waitKey(0)
cv2.destroyAllWindows()
# step 3: close the file
|
b89c1b0895cdaf8253e4ed6685d2977228dad4d5 | magnushedin/AOC | /2015/dec_01/dec_01b.py | 469 | 3.6875 | 4 | def read_file(filename):
f = open(filename)
input = f.read()
f.close()
return input
if __name__ == "__main__":
filename = 'input'
input = read_file(filename)
pt = 0
for (iter, i) in enumerate(input):
#print("this char: {}".format(i))
if i == ')':
pt -= 1
elif i == '(':
pt += 1
if (pt < 0):
print("Entering basement at: {}".format(iter+1))
break
|
d45ede908c2f5977eed1a01d87cb78b2bc2a63b8 | Sandy4321/vw-spam-filter | /util/text.py | 1,706 | 3.609375 | 4 | import re
def process_text(text):
"""
General-purpose text pre-processing.
:param text:
:return:
"""
if text is None:
return ""
text = text.casefold()
# Remove 1 and 2 character alphabetic words
# (Uncomment if necessary)
# text = re.sub(r"\b[a-z]{1,2}\b", "", text)
# Split non alphabetic chars out into separate tokens
text = re.sub(r"([^a-z ]+)", r" \1 ", text)
# Convert all extraneous whitespace to single spaces
text = re.sub(r"\s+", " ", text)
return text
def to_vw_format(feature_spaces, label=None):
"""
Provide a mapping of feature namespaces -> feature strings with an optional
label for a single example, and this function will return the data in the format
expected by Vowpal Wabbit.
Feature strings are space-separated lists of features, where each feature is in
the format <feature name>[:<feature value>]. If `feature_value` is omitted,
it is taken to be 1. A basic list of tokens therefore corresponds to a set of
features named after the tokens, each with value 1.
This function ensures that the VW special characters "|" and ":" are not present
in any feature string, but does no further pre-processing.
:param feature_spaces:
:param label:
:return:
"""
# Build the components of the VW-formatted line as a string, then join them at
# the end
vw = []
if label is not None:
vw.append(f"{label}")
for name, features in feature_spaces.items():
features = features.replace("|", "").replace(":", "")
features = re.sub(r"\s+", " ", features)
vw.append(f"|{name} {features}")
return " ".join(vw)
|
0484515467b9ff1caf1770b03159e94e79895acd | AdlerChan/Euler-Problem | /problem16.py | 336 | 3.6875 | 4 | def multiples(n):
a = n / 15
b = n % 15
return a, b
def sum1(n):
a, b = multiples(n)
result = (32768 ** a) * (2 ** b)
return result
if __name__ == "__main__":
print sum([int(i) for i in str(sum1(1000))])
print sum(map(lambda x: int(x), str(2 ** 1000)))
print sum([int(i) for i in str(2 ** 1000)])
|
bdce06a28c70a117aa470af18fce590a325ebd06 | tsuchan19991218/atcoder_achievement | /atcoder.jp/abc056/arc070_a/Main.py | 84 | 3.828125 | 4 | X = int(input())
x = 0
time = 0
while x < X:
time += 1
x += time
print(time) |
56b56fccff72bbc1b72515a965e1337838c1bd86 | sdramsey89/Election_Analysis | /Python_practice.py | 1,127 | 3.71875 | 4 | counties = ["Arapahoe","Denver","Jefferson"]
counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438}
#for county in counties_dict.keys():
# print(county)
#for county in counties_dict.values():
# print(county)
#for county, voters in counties_dict.items():
# print(county, voters)
voting_data = [{"county":"Arapahoe", "registered_voters": 422829},
{"county":"Denver", "registered_voters": 463353},
{"county":"Jefferson", "registered_voters": 432438}]
#retrieve list of dictionaries
print("List of Dictionaries")
for county_dict in voting_data:
print(county_dict
)
#retrieve list of dictionaries
for i in range(len(voting_data)):
print(voting_data[i]
)
#retrieve registered voters
for county_dict in voting_data:
print(county_dict['registered_voters'])
print()
print()
for county, voters in counties_dict.items():
print(f"{county} county has {voters:,} registered voters.")
print()
print()
for county_dict in voting_data:
print(f"{voting_data['county']} county has {voting_data['registered_voters']:,} registered voters.") |
5a259922e77f17a45435ac4a24bfa736e08b90b5 | WaterJames/resource | /mybaostock/my_queue.py | 529 | 3.515625 | 4 | class MyQueue:
def __init__(self):
self.items = []
def push(self, value):
self.items.append(value)
# 弹出首个数据
def pop(self):
if(self.items == []):
return 0
else:
return self.items.pop(0)
def sum(self):
total = 0.0
if(len(self.items) == 0):
return total
else:
for each_item in range (0, len(self.items)):
total = total+ float(self.items[each_item][0])
return total
|
4e5cde47dda2ed6a615a4561d49136b6539c27fb | selahattintuncer/Python | /python-master/python-master/coding-challenges/cc-009-find-the-power-set/find-the-power-set.py | 291 | 3.609375 | 4 | def func (arr):
power_set = []
smalllist =[]
for i in arr:
smalllist = []
smalllist.append(i)
power_set.append(smalllist)
for a in power_set:
tmp = a.copy()
if i not in a:
tmp.append(i)
power_set.append(tmp)
print(power_set)
|
a0c083de32282fe9c540934de8b0135b9708c198 | pombredanne/classic | /test/test_shortest_path.py | 917 | 3.578125 | 4 | #!/usr/bin/env python
#
# This script is used for testing shortest path algorithm.
#
# Liang Wang @ University of Helsinki, Finland
# 2014.09.12
#
import os
import sys
import random
import networkx as nx
sys.path.append('../code')
def get_random_graph():
G = nx.erdos_renyi_graph(100, 0.1)
H = nx.Graph()
for u,v in G.edges():
d = random.uniform(1,10)
H.add_edge(u, v, weight=d)
return H
def main():
G = get_random_graph()
from dijkstra import shortest
print "Test Dijkstra", shortest, '-'*20
print 'NetworkX =>', nx.shortest_path(G, 0, 50, 'weight')
print 'Dijkstra =>', shortest(G, 0, 50)
from floyd_warshall import shortest
print "Test Floyd-Warshall", shortest, '-'*20
print 'NetworkX =>', nx.shortest_path(G, 0, 50, 'weight')
print 'Floyd-Warshall =>', shortest(G, 0, 50)
pass
if __name__ == "__main__":
main()
sys.exit(0)
|
99dc40d56e9e2a05fcfb9a726cd838f299454643 | YalingZheng/CIS475Spr20 | /FaultInjection.py | 2,344 | 3.578125 | 4 | #!/usr/bin/env python
## FaultInjectionDemo.py
## Avi Kak (March 30, 2015)
## This script demonstrates the fault injection exploit on the CRT step of the
## of the RSA algorithm.
## GCD calculator (From Lecture 5)
def gcd(a,b): #(1)
while b: #(2)
a,b = b, a%b #(3)
return a #(4)
## The code shown below uses ordinary integer arithmetic implementation of
## the Extended Euclids Algorithm to find the MI of the first-arg integer
## vis-a-vis the second-arg integer. (This code segment is from Lecture 5)
def MI(num, mod): #(5)
'''
The function returns the multiplicative inverse (MI) of num modulo mod
'''
NUM = num; MOD = mod #(6)
x, x_old = 0L, 1L #(7)
y, y_old = 1L, 0L #(8)
while mod: #(9)
q = num // mod #(10)
num, mod = mod, num % mod #(11)
x, x_old = x_old - q * x, x #(12)
y, y_old = y_old - q * y, y #(13)
if num != 1: #(14)
raise ValueError("NO MI. However, the GCD of %d and %d is %u" % (NUM, MOD, num)) #(15)
else: #(16)
MI = (x_old + MOD) % MOD #(17)
return MI #(18)
# Set RSA params:
p = 211 #(19)
q = 223 #(20)
n = p * q #(21)
print "RSA parameters:"
print "p = %d q = %d modulus = %d" % (p, q, n) #(22)
totient_n = (p-1) * (q-1) #(23)
# Find a candidate for public exponent:
for e in range(3,n): #(24)
if (gcd(e,p-1) == 1) and (gcd(e,q-1) == 1): #(25)
break #(26)
print "public exponent e = ", e #(27)
# Now set the private exponent:
d = MI(e, totient_n) #(28)
print "private exponent d = ", d #(29)
message = 6789 #(30)
print "\nmessage = ", message #(31)
# Implement the Chinese Remainder Theorem to calculate
# message to the power of d mod n:
dp = d % (p - 1) #(32)
dq = d % (q - 1) #(33)
V_p = ((message % p) ** dp) % p #(34)
V_q = ((message % q) ** dq) % q #(35)
signature = (q * MI(q, p) * V_p + p * MI(p, q) * V_q) % n #(36)
print "\nsignature = ", signature #(37)
import random #(38)
print "\nESTIMATION OF q THROUGH INJECTED FAULTS:"
for i in range(10):
error = random.randrange(1,10) #(40)
V_hat_p = V_p + error #(42)
print "\nV_p = %d V_hat_p = %d error = %d" % (V_p, V_hat_p, error) #(41)
signature_hat = (q * MI(q, p) * V_hat_p + p * MI(p, q) * V_q) % n #(43)
q_estimate = gcd( (signature_hat ** e - message) % n, n) #(44)
print "possible value for q = ", q_estimate #(45)
if q_estimate == q: #(46)
print "Attack successful!!!" #(47)
|
4ed41be205d5352eae452091ef145e3b7ab20653 | pzp1997/Snippets | /Hangman.py | 1,785 | 3.71875 | 4 | #!/usr/bin/env python2.7
"""Hangman for Terminal"""
from urllib2 import urlopen, URLError
__author__ = 'Palmer (pzp1997)'
__version__ = '1.0.4'
__email__ = '[email protected]'
def main():
print 'Hangman.py (c) 2014, pzp1997'
print 'Input "exit" or "quit" to quit.'
print
while True:
err_cnt = 0
while True:
try:
word = urlopen('http://randomword.setgetgo.com/get.php').read()[:-2].upper()
break
except URLError:
err_cnt += 1
if err_cnt == 5:
print 'Error: Could not fetch word. Please make sure you are connected to the internet, and try again later.'
raise SystemExit
visible = '-'*len(word)
misses = []
while True:
print visible
print 'Misses ({0}/6): {1}'.format(len(misses), ', '.join(misses))
guess = ''
while not guess.isalpha() or len(guess) != 1:
guess = raw_input('Guess a letter: ').upper()
if guess == 'EXIT' or guess == 'QUIT':
raise SystemExit
if guess in word:
for letter in range(len(word)):
if guess == word[letter]:
visible = '{0}{1}{2}'.format(visible[:letter], guess, visible[letter+1:])
if visible == word:
print 'YOU WIN!'
break
elif not guess in misses:
misses.append(guess)
if len(misses) > 5:
print 'The word was {0}'.format(word)
break
print
print
if __name__ == '__main__':
main()
|
84a0f11d530b1513475239f39eaf8796b1a49ecf | GeorgeSpiller/2015-2017 | /Python/Algorithms/Bubble sort.py | 1,086 | 3.90625 | 4 | #Bubble sort
#create unordered list from input
valueList = []
valueString = ""
pointerPos = 0
valueString = input("enter list of numbers only, max 10: ")
if len(valueString) > 10:
quit
i = 0
for i in range(0, len(valueString)):
valueList.insert(i, valueString[i])
print(valueList)
#for each in list
#if the vlaue to the right is less that current value swap & set swap flag to true
def loopfunc(listvalue):
swapMade = False
for x in range(0, len(listvalue) - 1):
if listvalue[x + 1] < listvalue[x]:
swapMade = True
tmp1 = listvalue[x]
tmp2 = listvalue[x + 1]
listvalue[x] = tmp2
listvalue[x + 1] = tmp1
print(listvalue)
if swapMade == True:
loopfunc(listvalue)
loopfunc(valueList)
#'print("del value" + valueList[i + 2])
#del valueList[i + 2]
#pointer += 1
#if end then if flag = true set to false and repeat
#if flag = false at end then fin
|
abd495fbb7988d790ec10d9e005f23e6715579d0 | nicopaik/Python-Projects | /session09/strings.py | 1,087 | 3.59375 | 4 | L = [
['Apple', 'Google', 'Microsoft'], # 0
['Java', 'Python', ['Ruby','On Rail'], 'PHP'], # 1
['Adam', 'Bart', 'Lisa'] # 2
]
len(L)
AFC_east = ['New England Patriots', 'Buffalo Bills', 'Miami Dolphins', 'New York Jets']
print('Buffalo Bills' in AFC_east)
# for team in AFC_east:
# for letter in team:
# print(letter)
numbers = [2019, 10, 8, 3, 43]
# for i in range(len(numbers)):
# numbers[i]=numbers[i] * 2
# print(numbers) # everything is doubled
for number in numbers: #Stays the same, # the previous one
number = number * 2
print(numbers)
my_list = ['spam', 1, ['New England Patriots', \
'Buffalo Bills', 'Miami Dolphins', \
'New York Giants'], \
[1, 2, 3]]
print(len(my_list))
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print (c) #same line
t = ['a', 'b', 'c', 'd', 'e', 'f']
print(t[1:3])
print(t[0:4])
print(t[3:6])
print(t[::2]) # A , C , E :: is whole list, from the whole list go by 2 intervals
print(t[::-2]) #FDB
t = ['a', 'Victoria', 'd', 'e', 'f']
t[1] ='nico'
print(t) |
977d272d8fc1a3c99a89d935dc8aa08de94dcad6 | NathanialNewman/ProjectEuler | /problems/1-9/7.py | 960 | 3.671875 | 4 | # Author: Nate Newman
# Source: Project Euler Problem
# Title: 10001st prime
# Description: By listing the first six prime numbers:
# 2, 3, 5, 7, 11, and 13
# we can see that the 6th prime is 13.
# What is the 10001st prime number
import time
from math import log
from math import floor
def sieve (limit, index):
fullList = [True]*limit
fullList[0] = fullList[1] = False
for i in range(limit):
if fullList[i]:
for j in range(i*i, limit, i):
fullList[j] = False
primeIndex = 0
for i in range(len(fullList)):
if fullList[i]:
primeIndex += 1
if (primeIndex == index):
return i
if __name__ == "__main__":
start = time.time()
limit = 10001*log(10001) + 10001*(log(log(10001)))
fLimit = floor(limit)
print(sieve(int(fLimit), 10001))
# Execute code here
end = time.time()
print "Time to complete: " + str(end-start)
|
fac2dad0abf44b033265c6dd2d973402ec256feb | Priyanshuparihar/Competitive_Programming | /Coding Question/Prime number.py | 166 | 4.03125 | 4 | n=int(input("Enter a no. "))
count=0
for i in range(2,n):
if n%i==0:
count+=1
if count>1:
print(n,"is not a prime no.")
else:
print(n, "is a prime no.") |
ac61bf3b9485e1eb778ef7a83acb7c1e9daa6727 | reesep/reesep.github.io | /classes/summer2021/127/lectures/examples/student_class.py | 1,963 | 4.09375 | 4 |
class Student():
#all students have a name, major, GPA, ID, Year
def __init__(self,name,major,student_id,gpa="Undefined",year="Freshman"):
self.name = name
self.major = major
self.student_id = student_id
self.gpa = gpa
self.year = year
self.champ_change = 0
self.minor = "N/A"
#reader methods (getters)
def getName(self):
return self.name
def getMajor(self):
return self.major
def getGpa(self):
return self.gpa
def getYear(self):
return self.year
#writer methods (setters)
def setMajor(self,newMajor):
self.major = newMajor
def setYear(self,newYear):
self.year = newYear
def setMinor(self,newMinor):
self.minor = newMinor
def calculateYearsLeft(self):
if self.year == "Freshman":
print(self.name,"has 3 years left")
elif self.year == "Sophomore":
print(self.name,"has 2 years left")
elif self.year == "Junior":
print(self.name,"has 1 years left")
elif self.year == "Senior":
print(self.name,"has less than a year left")
else:
print(self.name,"has ????? years left")
## def __str__(self):
##
## answer = "Name: " + self.name + "\n"
## answer += "Major: " + self.major + "\n"
## answer += "GPA: " + str(self.gpa) + "\n"
## answer += "Student ID: " + self.student_id + "\n"
## answer += "Year: " + self.year + "\n"
## answer += "Minor: " + self.minor + "\n"
## answer += "Champ Change: " + str(self.champ_change)
##
##
## return answer
def main():
#create a student
newstudent = Student("Sam","Biology","42141241")
student1 = Student("James","Computer Science","04293401",4.0,"Junior")
student2 = Student("Sally","Math","41982641901",3.6,"Sophomore")
print(newstudent)
main()
|
314747bd5eae3e1f3adb2968bc0c7460ba1cb9d5 | sservett/python | /PDEV/SECTION6/hw601.py | 297 | 3.546875 | 4 | def is_perfect(a):
list1 = []
i = 1
while i < a:
if (a % i == 0):
list1.append(i)
i += 1
b = 0
for i in list1:
b = b + i
if a == b :
print("{} is Perfect NUMBER".format(a))
for i in range(1,1000):
is_perfect(i)
|
49798f3942eb35c66e22f5c0157fd6d84d872ea5 | Karthik-bhogi/Infytq | /Part 1/Assignment Set 3/Question4.py | 813 | 4.15625 | 4 | '''
Created on Apr 23, 2021
@author: Karthik
'''
def check_palindrome(word):
#Remove pass and write your logic here
length = len(word)
letter_list = ""
n = 0
while(length>n):
letter_list = letter_list +" "+ word[n]
n = n +1
letter_list = letter_list[1:]
letter_list=letter_list.split(" ")
first = 0
last = length-1
while(length>0):
if (letter_list[first] == letter_list[last]):
first += 1
last -= 1
length = length - 1
status = True
continue
else:
status = False
break
return status
status=check_palindrome("malayalam")
if(status == True):
print("word is palindrome")
else:
print("word is not palindrome") |
b573017ca336216332be4612d48206ba1eaa6b8c | SyureNyanko/asymmetric_tsp | /asymmetric_tsp/core.py | 1,957 | 3.765625 | 4 | # -*- coding: utf-8 -*-
import math
import time
import sys
class Timeout(object):
def __init__(self, limittime, starttime):
self.starttime = starttime
self.limittime = limittime
def get_timeout(self, time):
timeout = (time - self.starttime> self.limittime)
return timeout
def testlength(v1, v2):
'''Measure length or cost'''
#t = (x1 - x2) * 100
#return t
#print(str(v1) + " , " + str(v2))
dv = (v1[0] - v2[0], v1[1] - v2[1])
d2 = dv[0] * dv[0] + dv[1] * dv[1]
d = math.sqrt(d2)
return d
def route_swap(s, a, b):
'''Generate new route s is old route, a and b are indexes'''
new_route = s[0:a+1]
mid = s[a+1:b+1]
new_route = new_route + mid[::-1]
new_route = new_route + s[b+1:]
return new_route
def calc_route_length(route, f):
ret = 0
for i in range(len(route)):
ret += f(route[i], route[(i+1)%len(route)])
return ret
def two_opt(route, length_function, limittime=60):
'''Peforms 2-opt search to improve route'''
timeout = Timeout(limittime, time.time())
bestroute = route
l = len(bestroute)
bestroute_cost = calc_route_length(bestroute, length_function)
while(True):
flag = True
if timeout.get_timeout(time.time()):
raise TimeoutError
for i in range(l-2):
i_next = (i + 1)%l
for j in range(i + 2, l):
j_next = (j + 1)%l
if i == 0 and j_next == 0:
continue
swapped_route = route_swap(bestroute, i, j)
swapped_route_cost = calc_route_length(swapped_route, length_function)
if swapped_route_cost < bestroute_cost:
print(str(i) + "," + str(j) + "," + str(bestroute))
bestroute_cost = swapped_route_cost
bestroute = swapped_route
flag = False
if flag:
break
return bestroute
if __name__ == '__main__':
'''point_tables is example case'''
point_table = [[0,0],[1,2],[10,0],[4,5],[2,0]]
point_size = len(point_table)
print("initial :" + str(point_table))
bestroute = two_opt(point_table, testlength)
print("result :" + str(bestroute))
|
4d020519004e3dd09dc27647a7e508bac68eaa83 | Iansdfg/9chap | /7HashHeap/401. Kth Smallest Number in Sorted Matrix.py | 663 | 3.578125 | 4 | import heapq
class Solution:
"""
@param matrix: a matrix of integers
@param k: An integer
@return: the kth smallest number in the matrix
"""
def kth_smallest(self, matrix, k):
# write your code here
heap = []
res = None
for row in matrix:
if not row:
continue
heapq.heappush(heap, (row[0], row))
for _ in range(k):
curr_val, curr_row = heapq.heappop(heap)
res = curr_val
curr_row.pop(0)
if not curr_row:
continue
heapq.heappush(heap, (curr_row[0], curr_row))
return res
|
63739846b4f1202aa0db4007706c706ba5f055eb | alexsfo/uri-online-judge-python | /URI_1010.py | 277 | 3.5 | 4 | produto1 = (input().split(' '))
CP1 = int(produto1[0])
UP1 = int(produto1[1])
VP1 = float(produto1[2])
produto2= (input().split(' '))
CP2 = int(produto2[0])
UP2 = int(produto2[1])
VP2 = float(produto2[2])
valor = VP1 * UP1 + VP2 * UP2
print("VALOR A PAGAR: R$ %.2f" %valor)
|
1f5f5f2864a6714190b3812d7df43395e5cbc753 | implse/Code_Challenges | /CodeFights/InterviewPractice/Searching&Sorting/traverseTree.py | 900 | 4.03125 | 4 | # Given a binary tree of integers t, return its node values in the following format:
# The first element should be the value of the tree root;
# The next elements should be the values of the nodes at height 1 (i.e. the root children), ordered from the leftmost to the rightmost one;
# The elements after that should be the values of the nodes at height 2 (i.e. the children of the nodes at height 1) ordered in the same way;
# Etc.
class Tree(object):
def __init__(self, x):
self.value = x
self.left = None
self.right = None
def traverseTree(t):
q = list()
node_values = list()
if t is None:
return node_values
q.append(t)
while q:
node = q.pop(0)
node_values.append(node.value)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return node_values
|
d1f55923f71abb5a0092fcb46c351be467834bd8 | leninhasda/competitive-programming | /random-py/4.3-max.py | 473 | 3.6875 | 4 | def max(arr):
if len(arr) == 1:
return arr[0]
else:
m = max(arr[1:])
if m > arr[0]:
return m
return arr[0]
def test_max():
test_cases = [
{
"in": [1,2,3,4,5,6,7],
"out": 7
},
{
"in": [12, 2,3,4,5],
"out": 12
},
{
"in": [1,5,9,3,4,6],
"out": 9
}
]
for tc in test_cases:
m = max(tc["in"])
if tc["out"] != m:
print("{} != {}".format(tc["out"], m))
test_max() |
80817c535fa8a936e8276c5997e25194c561676a | sandeepmaity09/python_practice | /hackerrank/day8_rec.py | 141 | 4.1875 | 4 | #!/usr/bin/python3
def factorial(n):
if n==1:
return n
else:
return n*factorial(n-1)
num=int(input())
fact=factorial(num)
print(fact)
|
2af2b3366096b7799e0c0ffa118c0f60a26511fe | hamioo66/Test | /2018-1-19.py | 516 | 3.953125 | 4 | # -*- coding=UTF-8 -*-
"""
author:hamioo
date:2018/1/19
describle:格式化方法
"""
age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book' .format(name,age))
print('why is {0} playing with that python?'.format(name))
# 联立字符串
print name + ' is ' + str(age) + ' years old '
print('{} years old' .format(18))
print('{0:.3f}'.format(1.0/3))
print('{0:_^11}'.format('hello'))
print('{name} wrote {book}'.format(name='hamioo',book='English'))
print("hhaajkdkfkdkfkff\nwererdrldrkk") |
51c3af3c34b5d2296cb23247f6e30bfaa608f12b | sleduap/PhoneContact | /action.py | 4,502 | 3.671875 | 4 | from os import path
from csv import DictWriter, DictReader
filename = "phonebook.csv"
class PhoneBook:
phone = []
counter = 0
def __init__(self):
if PhoneBook.counter == 0:
self.read(filename)
PhoneBook.counter = PhoneBook.counter + 1
self.book = {"Name": "", "PhoneNumber": "", "Email Address": ""}
self.personal_information()
print(self.phonenumber)
self.stat = self.duplicatecheck1(self.phonenumber)
print(self.phone)
self.phoneadd = PhoneBook.phone.append(self.book)
def personal_information(self):
print("Please provide the information to add in a phone diary")
name = input("Enter a name:\n")
self.book["Name"] = name
self.phonenumber = input("Enter the phone number:\n")
self.book["PhoneNumber"] = self.phonenumber
self.book["Email Address"] = input("Enter an email_address:\n")
def duplicatecheck1(self, name):
# status = False
print("123", name)
print("list", self.phone)
for check in self.phone:
print(check)
print("name", name)
if check["PhoneNumber"] == name:
# status = True
return True
return False
def read(self, filename):
with open(filename, "r") as handlerRead:
reader = DictReader(handlerRead)
self.phone.extend(reader)
def witeintofile(self, filename):
print(filename)
a = [self.book]
if path.exists(filename):
with open(filename, "a", newline="") as handler:
print("b")
writer = DictWriter(handler, fieldnames=["Name", "PhoneNumber", "Email Address"])
writer.writerows(a)
else:
print(filename)
with open(filename, "w", newline="") as handler:
writer = DictWriter(handler, fieldnames=["Name", "PhoneNumber", "Email Address"])
writer.writeheader()
writer.writerows(a)
class List:
phone = []
counter = 0
def __init__(self):
if List.counter == 0:
self.read(filename)
List.counter = List.counter + 1
def read(self, filename):
with open(filename, "r") as handlerRead:
reader = DictReader(handlerRead)
self.phone.extend(reader)
def search(self, key, index):
counters = 0
for ser in self.phone:
if ser[key].lower() == index.lower():
for serkey, serindex in ser.items():
print(serkey, ":", serindex)
print("-" * 60)
counters += 1
if counters == 0:
print("Entered {} does not exists.".format(key))
def delete(self, phone_number):
counterl = 0
print(phone_number)
for index, value in enumerate(self.phone):
print(index, value)
if value["PhoneNumber"] == phone_number:
print(index)
self.phone.pop(index)
counterl += 1
if counterl == 0:
print("Entered phone number does not exists.")
else:
with open(filename, "w", newline="") as handler:
writer = DictWriter(handler, fieldnames=["Name", "PhoneNumber", "Email Address"])
writer.writeheader()
writer.writerows(self.phone)
print("Phone Number deleted successfully")
def edit(self, phone12, name12, phone_num12, email12):
countere = 0
for f in self.phone:
for phone_key, phone_value in f.items():
if f["PhoneNumber"] == phone12:
if name12.isspace() is False and name12 != "":
f["Name"] = name12
if phone_num12.isspace() is False and phone_num12 != "":
f["PhoneNumber"] = phone_num12
if email12.isspace() is False and email12 != "":
f["Email Address"] = email12
countere += 1
if countere == 0:
print("Entered phone number does not exists.")
else:
with open(filename, "w", newline="") as handler:
writer = DictWriter(handler, fieldnames=["Name", "PhoneNumber", "Email Address"])
writer.writeheader()
writer.writerows(self.phone)
print("Data edited successfully")
|
51dd5e4f0dab829f37a3e96d9f5276239ff54f7f | JUNGEEYOU/Algorithm-Problems | /binary_search/baekjoon/10815.py | 538 | 3.53125 | 4 | import sys
def binary(target):
left = 0
right = n - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return 1
elif arr[mid] > target:
right = mid - 1
else:
left = mid + 1
return 0
n = int(sys.stdin.readline().rstrip())
arr = list(map(int, sys.stdin.readline().split()))
m = int(sys.stdin.readline().rstrip())
arr2 = list(map(int, sys.stdin.readline().split()))
arr.sort()
for i in range(m):
print(binary(arr2[i]), end=" ")
|
b495c57f134665710ca45fdb14f08a6ebf50059c | ajaycs18/ADA-4TH-SEM | /insort.py | 272 | 3.5625 | 4 | def inSort(arr):
for i in range(1, len(arr) - 1):
ele = arr[i]
j = i - 1
while j > -1 and arr[j] > ele:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = ele
arr = list(map(int, input().split()))
inSort(arr)
print(arr)
|
30ed4db764dd06481127040bb6548cebf102a5ba | adyadyat/pyprojects | /shultais_courses/data_types/comparsion_of_num_and_lines/max_num.py | 629 | 3.625 | 4 | import sys
d1 = int(sys.argv[1])
d2 = int(sys.argv[2])
d3 = int(sys.argv[3])
print(max([d1, d2, d3])) # метод max([])
"""
МАКСИМАЛЬНОЕ ЧИСЛО
Начинающий разработчик написал программу, которая выводит максимальное из трех чисел, однако код работает не так как было задумано. Исправьте ошибку, чтобы программа работала правильно.
Пример использования в командной строке Windows:
> python program.py 9 11 7
> 11
""" |
e6e56d1aa683d83c362382d150973c7b3c46a089 | geekfiktion/python | /sals_shipping.py | 1,057 | 3.6875 | 4 | prem_ground_ship = 125.00
def ground_shipping(weight):
flat_charge = 20.00
if weight <= 2:
cost = (weight * 1.50)
elif weight <= 6:
cost = (weight * 3.00)
elif weight <= 10:
cost = (weight * 4.00)
else:
cost = (weight * 4.75)
return cost + flat_charge
def drone_shipping(weight):
flat_charge = 0.00
if weight <= 2:
cost = (weight * 4.50)
elif weight <= 6:
cost = (weight * 9.00)
elif weight <= 10:
cost = (weight * 12.00)
else:
cost = (weight * 14.25)
return cost
def print_ship_and_cost(method, cost):
print("The cheapest option available is $%.2f with the %s shipping method." % (cost, method))
def best_ship_method(weight):
ground = ground_shipping(weight)
drone = drone_shipping(weight)
if ground > drone and prem_ground_ship > drone:
print_ship_and_cost("Drone", drone)
elif drone > ground and prem_ground_ship > ground:
print_ship_and_cost("Ground", ground)
else:
print_ship_and_cost("Premium Ground", prem_ground_ship)
best_ship_method(4.8)
best_ship_method(41.5)
|
2bbb1ce80686c5a03e811d5d75ac11c4837761b1 | mrxder/simple-elevation-calculator | /main.py | 454 | 3.921875 | 4 | import math
print("Start")
print("start length:")
km_a = float(input())
print("start height:")
hm_a = float(input())
print("")
print("Target")
print("target length:")
km_b = float(input())
print("target height:")
hm_b = float(input())
distance = abs(km_a - km_b)
height = abs(hm_a - hm_b)
run = math.sqrt((math.pow(distance,2)) - (math.pow(height,2)))
percentage = (height / run) * 100
print("")
print("Elevation")
print(str(percentage) + "%")
|
72274945b849c25defc47eedb60bf24252f89e8c | xatlasm/python-crash-course | /chap10/10-12.py | 521 | 3.90625 | 4 | #Favorite Number Remembered
import json
filename = 'pythoncc exercises/chap10/fav_num.json'
def get_fav_num():
fav_num = input('What is your favorite number? ')
with open(filename, 'w') as f_obj:
json.dump(fav_num,f_obj)
def read_fav_num():
"""Reads user's favorite number from JSON"""
with open(filename, 'r') as f_obj:
fav_num = json.load(f_obj)
print('I know your favorite number! It\'s ' + str(fav_num))
try:
read_fav_num()
except FileNotFoundError:
get_fav_num() |
4a521c1d7774010774cb32938bd5a996a31d6578 | mario595/test-payments-app | /accounts/commands/transfer_command.py | 1,807 | 3.703125 | 4 | '''
Created on 6 Feb 2016
@author: mariopersonal
'''
from accounts.commands.commands import Command, CommandError
'''
This is a transfer command. It validates if the transfer is correct (Different account and enough funds) and
makes the transfer, updating both accounts involved and saving the transaction. In case of validation error,
it raised appropriate errors.
'''
class TransferCommand(Command):
def execute(self):
if not self._are_accounts_different():
raise SameAccountError('You have selected to make a transfer to the same account, please,\
select different accounts and try again')
if not self._is_balance_sufficient():
transfer = self._obj
raise FromAccountInsufficientBalanceError('The transfer of %0.2f was unsucessful as account %s \
has insufficient funds (%0.2f)' %
(transfer.amount, transfer.from_account.name, transfer.from_account.balance))
self._make_transfer()
def _are_accounts_different(self):
return self._obj.from_account.id != self._obj.to_account.id
def _is_balance_sufficient(self):
return self._obj.from_account.balance >= self._obj.amount
def _make_transfer(self):
transfer = self._obj
from_account = transfer.from_account
to_account = transfer.to_account
amount = transfer.amount
from_account.balance = from_account.balance - amount
to_account.balance = to_account.balance + amount
from_account.save()
to_account.save()
transfer.save()
class SameAccountError(CommandError):
pass
class FromAccountInsufficientBalanceError(CommandError):
pass |
2fc74c047131a5ef5bcb2f341254fc159950cb3a | pdjani91/Python-Programming-Examples | /counter.py | 143 | 3.640625 | 4 | def word_counter(s):
count = {}
for char in s:
count[char] = s.count(s)
return count
print (word_counter('harshit')) |
9fb42528c2704a2e175ee9d5b5e5bf4e5eb6fe21 | asdrubalramirezb/higher_level_programming-master | /0x0A-python-inheritance/3-is_kind_of_class.py | 365 | 3.578125 | 4 | #!/usr/bin/python3
"""Module that verify if the object is an instances of a class given
"""
def is_kind_of_class(obj, a_class):
""" Function that receive an object and a class,
Returns true if object is an instances of a class,
otherwise return false
"""
if isinstance(obj, a_class):
return True
else:
return False
|
3c69f1fac636bd87bbd014798d072677e778e7cc | mlpetuaud/first_package | /my_shoes_pkg/my_shoes.py | 2,465 | 3.578125 | 4 | import random
import itertools
class Stock():
# donne un attribut de classe (on aurait aussi pu
# initialiser un compteur à 0 et l'augmenter de 1 à
# chaque instanciation d'objet via un +=1 dans le __init__)
#instances_counter = itertools.count().next
instances_counter = 0
def __init__(self):
self.id = Stock.instances_counter
self.inventory = []
self.inventory_value = 0
Stock.instances_counter += 1
def add_shoes(self):
for element in Shoe.list_shoes_created:
if element.inventoried == False:
self.inventory.append(element)
element.inventory = True
element.stock = self.id
else:
continue
self.set_value()
def delete_shoes(self, shoe_id):
for item in self.inventory:
if item.id == shoe_id:
item.sold = True
self.inventory.remove(item)
self.set_value()
def set_value(self):
self.inventory_value = sum([item.price for item in self.inventory])
class Shoe():
instances_counter = 0
list_shoes_created = []
def __init__(self, pointure=42, color=None, brand=None, price=random.randrange(10,300)):
# si pointure n'est pas précisée à l'instanciation mettra 42 par défaut.
self.id = Shoe.instances_counter
self.pointure = pointure
self.color = color
self.brand = brand
self.price = price
self.inventoried = False
self.sold = False
self.stock = None
Shoe.list_shoes_created.append(self)
Shoe.instances_counter += 1
#self.color=color
if type(self.pointure) is not int or self.pointure < 14 or self.pointure > 46:
self.pointure = input("merci de rentrer un nombre entier compris entre 14 et 46")
#if type(self.pointure) is not int or self.pointure < 14 or self.pointure > 46:
#raise ValueError('Shoe pointure attribute only accepts integers between 14 and 46')
# if type(self.color) is not string:
#raise ValueError("Shoe color must be a string")
my_stock = Stock()
shoe1 = Shoe()
shoe2 = Shoe(color="red")
shoe3 = Shoe(pointure=24)
Shoe.list_shoes_created
shoe3.id
my_stock.add_shoes()
my_stock.inventory
my_stock.delete_shoes(shoe_id=1)
print(my_stock.inventory_value)
print(shoe1.price, shoe2.price) |
6b4d29d8b96e1b8e384dc98dec24e675f7ef81ed | mikhail-kukuyev/Masters-Degree-Courses | /Python/lab4/mid_skip_queue.py | 1,948 | 3.5 | 4 | import pprint
import copy
class MidSkipQueue(object):
def __init__(self, k, iterable=None):
assert k > 0, "k should be positive"
self.k = k
self.elements = iterable[:] if iterable else []
def append(self, *args):
if len(self.elements) <= self.k:
append_amount = 2 * self.k - len(self.elements)
self.elements += list(args)[-append_amount:]
else:
first_part = self.elements[:self.k]
second_part = self.elements[self.k:]
appended_elements = list(args)[-self.k:]
remain_amount = self.k - len(appended_elements)
remain_elements = second_part[len(second_part) - remain_amount:len(second_part)]
self.elements = first_part + remain_elements + appended_elements
return None
def index(self, value):
for i in xrange(len(self.elements)):
if self.elements[i] == value:
return i
return -1
def __getitem__(self, item):
if not isinstance(item, slice):
assert -len(self.elements) < item < len(self.elements), "IndexError: queue index out of range"
return self.elements[item]
def __contains__(self, item):
return item in self.elements
def __len__(self):
return len(self.elements)
def __eq__(self, other):
return self.elements == other.elements
def __hash__(self):
return hash(self.elements)
def __add__(self, iterable):
queue = copy.deepcopy(self)
queue.append(*iterable)
return queue
def __str__(self):
return pprint.pformat(self.elements)
class MidSkipPriorityQueue(MidSkipQueue):
def append(self, *args):
union = self.elements + list(args)
union.sort()
largest = union[-self.k:]
others = union[:len(union) - len(largest)]
self.elements = others[:self.k] + largest
return None
|
998a4cb5909b6839e1b822e02a4d1e633df6c81d | michellejzh/power-and-prices | /ISO-NE/scripty/averageWind.py | 1,450 | 3.515625 | 4 | import csv
import sys
import os
import Queue
import numpy as np
import math
def averageWindByDay(windFile):
with open(windFile, 'rU') as csvfile:
reader = csv.reader(csvfile, dialect=csv.excel_tab, delimiter=',', quotechar='|')
row = "placeholder"
dates = [] # eventually need to write in date order
days = {} # average saved per date
reader.next()
prevDay = "1/1/11"
mw = []
# fill with all the hours in the day
for row in reader:
currDay = row[1]
if currDay != prevDay:
if mw == []:
print "BREAKING!"
break
# add the previous day to the list of dates
dates.append(prevDay)
# now average the mw of prevDay and save in days
avg = np.average((np.array(mw)).astype(float))
days[prevDay] = avg
print "Average on " + str(row[1]) + " is " + str(avg)
mw = []
mw.append(row[3])
prevDay = currDay
print "-----------------------------------------"
print dates
# print days
savePairs("avgd-"+windFile, dates, days)
def savePairs(writePath, dates, days):
with open(writePath, 'a') as fp:
writer = csv.writer(fp, delimiter=',')
for day in dates:
line = [day, days[day]]
writer.writerow(line)
print "Saving " + str(line)
if __name__ == '__main__':
if len(sys.argv) > 1:
try:
windFile = str(sys.argv[1])
averageWindByDay(windFile)
except ValueError:
print("Error: input must be a string")
exit()
else:
print("Usage: averageWind.py <wind-file>") |
dbf9704dd0f98528994ea6dbfdf4f4faf25445ee | SonBui24/Python | /Lesson03/Bai01.py | 1,063 | 3.90625 | 4 | from math import sqrt
print("Giải phương trình bậc 2")
a = float(input("Nhập số a: "))
b = float(input("Nhập số b: "))
c = float(input("Nhập số c: "))
delta = b ** 2 - 4 * a * c
if a == 0:
if b == 0:
if c == 0:
print("Phương trình có vô số nghiệm!")
else:
print("Phương trình vô nghiệm!")
else:
if c == 0:
print("Phương trình có 1 nghiệm duy nhất: x = 0")
else:
print(f"Phương trình có 1 nghiệm duy nhất: x = {-c/b}")
else:
if delta < 0:
print("Phương trình vô nghiệm!")
elif delta == 0:
print(f"Phương trình có 1 nghiệm duy nhất: x = {-b / (2 * a)}")
else:
print("Phương trình có 2 nghiệm phân biệt!")
print(f"x1 = {float((-b - sqrt(delta)) / (2 * a))}")
print(f"x2 = {float((-b + sqrt(delta)) / (2 * a))}")
"""Làm bài này e phải ổn lại kiến thức :|
E import math vào k đc a ạ. Nó hiện import math như 1 dòng comment
""" |
fa6ffcea55953db6a8d91e3b07ca1782f9692705 | Denis-Oyaro/Data-structures-and-algorithms-with-Python | /quick_sort.py | 737 | 4 | 4 | """Implement quick sort in Python.
Input a list.
Output a sorted list."""
def quicksort(array):
QUICKSORT(array, 0, len(array) - 1)
return array
def QUICKSORT(array, p, r):
if p < r:
q = PARTITION(array, p, r)
QUICKSORT(array, p, q-1)
QUICKSORT(array, q+1, r)
def PARTITION(array, p, r):
x = array[r]
i = p - 1
for j in range(p,r):
if array[j] <= x:
i = i + 1
temp = array[j]
array[j] = array[i]
array[i] = temp
array[r] = array[i+1]
array[i+1] = x
return i+1
def main():
test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print(quicksort(test))
if __name__ == "__main__":
main() |
8f3cd375b168fd32c25d318ae716d90c68e23c9d | leezichanga/Project-euler-toyproblems | /projecteuler6.py | 985 | 3.703125 | 4 | #Solution 1
def squares(num):
total = []
for i in range(1,num+1):
prod = (i*i)
total.append(prod)
you=sum(total)
return you
squares(10)
def sum_squares(num):
total = []
for i in range(1,num+1):
total.append(i)
you=sum(total)
return you**2
sum_squares(10)
def diff(a,b):
difference = a-b
print(difference)
diff(sum_squares(10),squares(10))
#Solution 2
def sum_of_square(limit):
my_list = []
start = 1
while start<=limit:
square = start*start
my_list.append(square)
start+=1
p = sum(my_list)
if len(my_list)==limit:
m = sum(my_list)
return (m)
def square_of_sum(limit):
list = []
for a in range(1,limit +1):
list.append(a)
p = sum(list)
if len(list)==limit:
print()
return p*p
def difference(limit):
num_sum = (square_of_sum(limit))-(sum_of_square(limit))
print(num_sum)
difference(10)
|
6a2bdd423ec1a58632b64b1f9725abfe0c4575fe | jonchang03/PythonSpecialization | /GettingStartedWithPython/assignment4_6.py | 389 | 4.0625 | 4 | def computepay(h,r):
if h < 40 :
pay = h * r
else :
# Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate
# for all hours worked above 40 hours.
pay = 40 * r + (h - 40) * 1.5 * r
return pay
hrs = raw_input("Enter Hours:")
hrs = float(hrs)
rate = raw_input("Enter Rate:")
rate = float(rate)
p = computepay(hrs,rate)
print p |
18f0143f563abcae7ea347bb7fb183b0a61d60c7 | fsMateus/exerciciosPython | /fase8/exercicio4.py | 565 | 3.59375 | 4 | class Pessoa:
def __init__(self, nome, idade, peso, altura):
self.nome = nome
self.idade = idade
self.peso = peso
self.altura = altura
def envelhecer(self):
self.idade += 1
self.crescer(0.5)
def engordar(self, peso):
self.peso += peso
def emagrecer(self, peso):
self.peso -= peso
def crescer(self, altura):
self.altura += altura
def __str__(self):
return self.nome
p = Pessoa('Mateus', 24, 58, 1.64)
print(p)
p.envelhecer()
p.engordar(0.7)
p.crescer(0.1) |
36494ca08e8b13a992ecec4febc52db44b98532d | chaichai1997/python-algorithm | /array_allocate.py | 999 | 3.5 | 4 | # -*- coding: utf-8 -*-
# author = "chaichai"
"""
实现任务调度
方法:贪心
"""
def calculate_process_time(time, number):
if time is None or number <= 0:
return None
n_t = len(time)
p_time = [0] * n_t
for i in range(number):
min_time = p_time[0] + time[0]
min_index = 0 # 指机器数目
j = 1
while j < n_t:
if min_time > p_time[j] + time[j]:
min_time = p_time[j] + time[j]
min_index = j
j += 1
p_time[min_index] = min_time
i += 1
return p_time
if __name__ == '__main__':
t = [7, 10]
n = 6
p_tine = calculate_process_time(t, n)
if p_tine is None:
print("无法分配")
else:
totap = p_tine[0]
i = 0
while i < len(p_tine):
print(str(i+1), str(p_tine[i]/t[i]), str(p_tine[i]))
if p_tine[i] > totap:
totap = p_tine[i]
i += 1
print(totap)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.