blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
c60df7c6d2aa3eaecdc1c95bc7bba9a96eff1add | kasemodz/RaspberryPiClass1 | /LED_on_off.py | 831 | 4.125 | 4 | # The purpose of this code is to turn the led off and on.
# The LED is connected to GPIO pin 25 via a 220 ohm resistor.
# See Readme file for necessary components
#! /usr/bin/python
#We are importing the sleep from the time module.
from time import sleep
#We are importing GPIO subclass from the class RPi. We are referring to this subclass via GPIO.
import RPi.GPIO as GPIO
# Resets all pins to factory settings
GPIO.cleanup()
# Sets the mode to pins referred by "GPIO__" pins (i.e. GPIO24)
GPIO.setmode(GPIO.BCM)
# Configures GPIO Pin 25 as an output, because we want to
# control the state of the LED with this code.
GPIO.setup(25, GPIO.OUT)
# Turns the LED state to ON by the HIGH command. To turn off the LED, change HIGH to LOW,
# then run this file again. ie. GPIO.output(25, GPIO.LOW)
GPIO.output(25, GPIO.HIGH)
|
99f64a174783c4a4f8a4a304672a096b0fe04ccc | Poter0222/poter | /PYTHON/03.04/string.py | 697 | 4.1875 | 4 | #coding=UTF-8
# 03
# 字串運算
# 字串會對內部的字元編號(索引),從 0 開始
s="hello\"o" # \ 在雙引號前面打入,代表跳脫(跟外面雙引號作區隔) 去避免你打的字串中有跟外面符號衝突的問題
print(s)
# 字串的串接
s="hello"+"world"
print(s)
s="hello" "world" # 同 x="hello"+"world"
print(s)
# 字串換行
s="hello\nworld" # /n代表換行
print(s)
s=""" hello
world""" # 前後加入“”“可將字串具體空出你空的行數
print(s)
s="hello"*3+"world" #概念同 先乘除後加減
print(s)
# 對字串編號
s="hello"
print(s[1])
print(s[1:4]) # 不包含第 4 個字元
print(s[:4]) # 到第 4 個字串(不包含)
|
e799fbff3d6be502d48b68fb1094b6dd4bcc4079 | yihangx/Heart_Rate_Sentinel_Server | /validate_heart_rate.py | 901 | 4.25 | 4 | def validate_heart_rate(age, heart_rate):
""" Validate the average of heart rate, and return
the patient's status.
Args:
age(int): patient'age
heart_rate(int): measured heart rates
Returns:
status(string): average heart rate
"""
status = ""
if age < 1:
tachycardia_threshold = -1
if age in range(1, 3):
tachycardia_threshold = 151
if age in range(3, 5):
tachycardia_threshold = 137
if age in range(5, 8):
tachycardia_threshold = 133
if age in range(8, 12):
tachycardia_threshold = 130
if age in range(12, 16):
tachycardia_threshold = 119
if age > 15:
tachycardia_threshold = 100
if tachycardia_threshold != -1:
if heart_rate >= tachycardia_threshold:
status = "tachycardia"
else:
status = "not tachycardia"
return status
|
59af5bd8671e37f88a8d870dafb252a31d19feb8 | julminen/aoc-2020 | /day_15.py | 1,095 | 3.59375 | 4 | #!/usr/bin/python3
from collections import namedtuple
def read_file(day: str):
with open(f"input/day_{day}.txt") as file:
lines = [line.strip() for line in file]
numbers = [int(n) for n in lines[0].split(",")]
return numbers
def play(input, until):
# A bit slow
print(f"Initial: {input}")
mem = dict()
for i, v in enumerate(input[:-1]):
mem[v] = i + 1
spoken_num = input[-1]
for age in range(len(mem) + 1, until):
previously_spoken = mem.get(spoken_num, age)
mem[spoken_num] = age
spoken_num = age - previously_spoken
print(f'{len(mem)} elements in memory')
return spoken_num
def phase_1(input):
return play(input, 2020)
def phase_2(input):
return play(input, 30_000_000)
def execute(input):
p1 = phase_1(input)
print(f"Phase 1: {p1}\n")
p2 = phase_2(input)
print(f"Phase 2: {p2}")
if __name__ == "__main__":
for day_input in ["15"]:
print(f"For {day_input}:")
input = read_file(day_input)
execute(input)
print("..............")
|
214209cf95f808f20e613ff30529a04a4c0d1094 | julminen/aoc-2020 | /day_23.py | 8,448 | 3.609375 | 4 | #!/usr/bin/python3
# Tried different variations for phase 2, none which is especially fast
from typing import List
from collections import namedtuple
Cup = namedtuple('Cup', ['value', 'next'])
class ListNode:
def __init__(self, node_id: int):
self.node_id = node_id
self.next_node = None
def __repr__(self):
return f'Node {self.node_id}'
def phase_1(cups: List[int], moves: int):
# print(f'Initial: {cups}')
cup_count = len(cups)
current_cup_index = 0
max_cup_value = max(cups)
min_cup_value = min(cups)
all_indexes = list(range(cup_count))
for round in range(moves):
# print(f'Move {round+1}: cci = {current_cup_index} : {cups}')
pick_up_indexes = [(current_cup_index + x + 1) % cup_count for x in range(3)]
# print(f' picking up: {[cups[i] for i in pick_up_indexes]}')
current_cup_value = cups[current_cup_index]
new_cups = [cups[i] for i in all_indexes if i not in pick_up_indexes]
destination_cup_index = -1
search_cup_value = current_cup_value - 1
while destination_cup_index == -1:
if search_cup_value in new_cups:
destination_cup_index = new_cups.index(search_cup_value)
else:
search_cup_value -= 1
if search_cup_value < min_cup_value:
search_cup_value = max_cup_value
# print(f' destination: [{destination_cup_index}] = {search_cup_value}')
cups = new_cups[0:destination_cup_index+1] + [cups[i] for i in pick_up_indexes] + new_cups[destination_cup_index+1:]
current_cup_index = (cups.index(current_cup_value) + 1) % len(cups)
# print(f'Final: {cups}')
bp = cups.index(1)
return ''.join(map(str, cups[bp+1:] + cups[0:bp]))
def phase_2_faster(cups: List[int], moves: int):
print(cups)
# More moves
moves = 10_000_000
# More cups
cups = cups + list(range(max(cups)+1, 1_000_001))
#
min_cup_value = min(cups)
max_cup_value = max(cups)
start_node = ListNode(cups[0])
current_node = start_node
node_map: Dict[int: ListNode] = dict()
node_map[cups[0]] = start_node
print(f'Creating node list ({len(cups)})')
for cup in cups[1:]:
head_node = ListNode(node_id=cup)
node_map[cup] = head_node
current_node.next_node = head_node
current_node = head_node
current_node.next_node = start_node
print(f'Nodes done {current_node} -> {current_node.next_node}')
current_node = start_node
x = start_node.next_node
counter = 1
while x != start_node:
#print(x)
x = x.next_node
counter += 1
print(x, counter)
print(f'node_map len = {len(node_map)}')
for move in range(moves):
if move % 250000 == 0:
print(f'Move {move}')
# pick up 3 nodes after current_node
pick_up_node = current_node.next_node
current_node.next_node = current_node.next_node.next_node.next_node.next_node
#pick_up_node.next_node.next_node.next_node = None
pick_up_ids = [pick_up_node.node_id, pick_up_node.next_node.node_id, pick_up_node.next_node.next_node.node_id]
# Find destination
destination_cup_value = current_node.node_id - 1
while destination_cup_value < min_cup_value or destination_cup_value in pick_up_ids:
if destination_cup_value < min_cup_value:
destination_cup_value = max_cup_value + 1
destination_cup_value -= 1
destination_node = node_map[destination_cup_value]
# Put picked up cups after destination
pick_up_node.next_node.next_node.next_node, destination_node.next_node = destination_node.next_node, pick_up_node
# Set new current_node
current_node = current_node.next_node
node_1 = node_map[1]
print(f'Nodes after {node_1} are {node_1.next_node} and {node_1.next_node.next_node}')
return node_1.next_node.node_id * node_1.next_node.next_node.node_id
def phase_2_namedtuple(cups: List[int], moves: int):
print(cups)
# More moves (10M)
moves = 10_000_000
# More cups (1M total)
cups = cups + list(range(max(cups)+1, 1_000_001))
#
min_cup_value = min(cups)
max_cup_value = max(cups)
cup_map: Dict[int: Cup] = dict()
print(f'Creating cup map ({len(cups)})')
for i, cup in enumerate(cups[:-1]):
cup_map[cup] = Cup(cup, cups[i+1])
cup_map[cups[-1]] = Cup(cups[-1], cups[0])
current_cup: Cup = cup_map[cups[0]]
print(f'Cups done, first = {current_cup}')
for move in range(moves):
if move % 250000 == 0:
print(f'Move {move}')
# print(current_cup)
# pick up 3 nodes after current_node
pick_up_node = cup_map[current_cup.next]
new_next_node_value = cup_map[cup_map[cup_map[current_cup.next].next].next].next
current_cup = Cup(current_cup.value, new_next_node_value)
# print(f'CC: {current_cup}')
cup_map[current_cup.value] = current_cup
pick_up_values = [pick_up_node.value, pick_up_node.next, cup_map[pick_up_node.next].next]
# Find destination
destination_cup_value = current_cup.value - 1
while destination_cup_value < min_cup_value or destination_cup_value in pick_up_values:
if destination_cup_value < min_cup_value:
destination_cup_value = max_cup_value + 1
destination_cup_value -= 1
destination_cup = cup_map[destination_cup_value]
# Put picked up cups after destination
new_dest_cup = Cup(destination_cup.value, pick_up_node.value)
new_last_picked_up_cup = Cup(pick_up_values[2], destination_cup.next)
cup_map[destination_cup.value] = new_dest_cup
cup_map[new_last_picked_up_cup.value] = new_last_picked_up_cup
# Set new current_node
current_cup = cup_map[current_cup.next]
cup_1 = cup_map[1]
print(f'Nodes after {cup_1} are {cup_1.next} and {cup_map[cup_1.next].next}')
return cup_1.next * cup_map[cup_1.next].next
def phase_2(cups: List[int], moves: int):
print(cups)
# More moves (10M)
moves = 10_000_000
# More cups (1M total)
cups = cups + list(range(max(cups)+1, 1_000_001))
#
min_cup_value = min(cups)
max_cup_value = max(cups)
cup_map: Dict[int: List[int]] = dict()
print(f'Creating cup map ({len(cups)})')
for i, cup in enumerate(cups[:-1]):
cup_map[cup] = [cup, cups[i+1]]
cup_map[cups[-1]] = [cups[-1], cups[0]]
current_cup_value, current_cup_next = cup_map[cups[0]]
print(f'Cups done, first = {current_cup_value} -> {current_cup_next}')
for move in range(moves):
if move % 500000 == 0:
print(f'Move {move}')
# pick up 3 nodes after current_node
pick_up_cup = cup_map[current_cup_next]
current_cup_next = cup_map[cup_map[pick_up_cup[1]][1]][1]
cup_map[current_cup_value][1] = current_cup_next
pick_up_values = [pick_up_cup[0], pick_up_cup[1], cup_map[pick_up_cup[1]][1]]
# Find destination
destination_cup_value = current_cup_value - 1
while destination_cup_value < min_cup_value or destination_cup_value in pick_up_values:
if destination_cup_value < min_cup_value:
destination_cup_value = max_cup_value + 1
destination_cup_value -= 1
destination_cup = cup_map[destination_cup_value]
# Put picked up cups after destination
cup_map[destination_cup[0]][1], cup_map[pick_up_values[2]][1] = pick_up_cup[0], destination_cup[1]
# Set new current_node
current_cup_value, current_cup_next = cup_map[current_cup_next]
cup_1 = cup_map[1]
print(f'Nodes after {cup_1} are {cup_1[1]} and {cup_map[cup_1[1]][1]}')
return cup_1[1] * cup_map[cup_1[1]][1]
def execute(input: str, moves: int):
cups = list(map(int, list(input)))
p1 = phase_1(cups, moves)
print(f"Phase 1: {p1}")
if moves == 100:
p2 = phase_2_faster(cups, moves)
print(f"Phase 2: {p2} ")
if __name__ == "__main__":
for day_input in [
("389125467", 10),
# ("389125467", 100),
("942387615", 100)
]:
print(f"For {day_input[0]} with {day_input[1]} moves:")
execute(day_input[0], day_input[1])
print("..............")
# Answers
# 1: 36542897
# 2: 562136730660
|
83bba9ae93acb35a1789d734cdf7acc0349a08d4 | JamesKing9/NewHeart-NewLife | /Study/Python/JCP027.py | 273 | 3.734375 | 4 | #!/usr/bin/python
# -*-coding: UTF-8-*-
'''
需求:
'''
def palin(n):
next = 0
if n <= 1:
next = input()
print
print next
else:
next = input()
palin(n-1)
print next
i = 5
palin(i)
print
|
7d0799241a47e78342643a0ed708ae9e5ff4c777 | nabilahap/Labpy03 | /Latihan1.py | 187 | 3.53125 | 4 | from random import random
n = int(input("Masukan Nilai N: "))
for i in range(n):
while 1:
n = random()
if n < 0.5:
break
print("dara ke: ",i, '==>', n) |
519f6444488b6478ac2c09ded5f689c63ba21dd7 | SifatIbna/codeforces-problems | /Boboniu Plays Chess/main.py | 1,096 | 3.65625 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
def move_column():
pass
def move_row():
pass
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
val = input()
inputs = val.split(' ')
n, m, Sx, Sy = int(inputs[0]), int(inputs[1]), int(inputs[2]), int(inputs[3])
print(Sx,'',Sy)
dir = True
for i in range(0, n):
if i != Sx-1:
print(i+1, '', Sy)
for i in range(0,m):
if i == Sy-1:
continue
if dir:
for j in reversed(range(0,n)):
print(j+1, '', i+1)
dir = False
else:
for j in range(0,n):
print(j+1, '',i+1)
dir = True
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
76db64ba5a47301aeaae345e43b6e528037e369c | yanigisawa/python-morsels | /format_fixed_width.py | 3,630 | 3.90625 | 4 | # This week I'd like you to write a function, format_fixed_width, that accepts rows of columns (as a list of lists)
# and returns a fixed-width formatted string representing the given rows.
# For example:
# >>> print(format_fixed_width([['green', 'red'], ['blue', 'purple']]))
# green red
# blue purple
# The padding between the columns should be 2 spaces. Whitespace on the right-hand
# side of each line should be trimmed and columns should be left-justified.
# Bonus #1
# For the first bonus, allow the padding for columns to be specified
# with an optional padding keyword argument:
# >>> rows = [['Robyn', 'Henry', 'Lawrence'], ['John', 'Barbara', 'Gross'], ['Jennifer', '', 'Bixler']]
# >>> print(format_fixed_width(rows))
# Robyn Henry Lawrence
# John Barbara Gross
# Jennifer Bixler
# >>> print(format_fixed_width(rows, padding=1))
# Robyn Henry Lawrence
# John Barbara Gross
# Jennifer Bixler
# >>> print(format_fixed_width(rows, padding=3))
# Robyn Henry Lawrence
# John Barbara Gross
# Jennifer Bixler
# Bonus #2
# For the second bonus, allow column widths to be specified manually with an optional widths keyword argument:
# >>> rows = [["Jane", "", "Austen"], ["Samuel", "Langhorne", "Clemens"]]
# >>> print(format_fixed_width(rows, widths=[10, 10, 10]))
# Jane Austen
# Samuel Langhorne Clemens
# Bonus #3
# For the third bonus, allow column justifications (left or right) to be specified with with an optional alignments keyword argument. This argument will take lists of 'L' and 'R' strings representing left and right:
# >>> print(format_fixed_width(rows, alignments=['R', 'L', 'R']))
# Jane Austen
# Samuel Langhorne Clemens
# Hints
# Getting the longest string
# Looping over multiple things at the same time
# Left-justifying strings
# Removing spaces from the end of a line
# Joining rows back together
# A shorthand for creating new lists from old lists
# Bonus 1: making optional function arguments
# Bonus 1: making a string of N whitespace characters
# Bonus 3: Right-justifying strings
# Tests
# Automated tests for this week's exercise can be found here. You'll need to write your function in a module named format_fixed_width.py next to the test file. To run the tests you'll run "python test_format_fixed_width.py" and check the output for "OK". You'll see that there are some "expected failures" (or "unexpected successes" maybe). If you'd like to do the bonus, you'll want to comment out the noted lines of code in the tests file to test them properly.
# Once you've written a solution for this exercise, submit your solution to track your progress! ✨
# Submit your solution
# You can also view the problem statement for this exercise on the Python Morsels website.
# To make sure you keep getting these emails, please add [email protected] to your address book.
# If you want to unsubscribe from Python Morsels click here
from itertools import zip_longest
def format_fixed_width(rows, padding=2, widths=None, alignments=None):
if widths is None:
widths = [
max(len(cell) for cell in col) for col in zip_longest(*rows, fillvalue="")
]
if alignments is None:
alignments = ["L" for row in rows for _ in row]
result = []
for row in rows:
row_str = ""
for col, width, alignment in zip(row, widths, alignments):
if alignment == "L":
row_str += f"{col}".ljust(width + padding)
else:
row_str += f"{col}".rjust(width)
result.append(row_str.rstrip())
return "\n".join(result)
|
e56c47a35358601f048e68397fa45658523a1469 | TechKrowd/sesion1python_03062020 | /operadores/06.py | 465 | 4.09375 | 4 | """
Pedir dos datos numéricos reales al usuario y calcular la suma,
resta, producto y división de los mismos.
"""
n1 = float(input("Introduce un número real:"))
n2 = float(input("Introduce otro número real:"))
suma = n1 + n2
resta = n1 - n2
producto = n1 * n2
division = n1 / n2
print("La suma es {:.2f}".format(suma))
print("La resta es {:.2f}".format(resta))
print("La producto es {:.2f}".format(producto))
print("La división es {:.2f}".format(division)) |
fe0364c9796f13da242bb31a99cd74ed21ca33c8 | TechKrowd/sesion1python_03062020 | /operadores/05.py | 201 | 4.0625 | 4 | """
Pedir un número entero por teclado y calcular su cuadrado.
"""
n = int(input("Introduce un número: "))
#cuadrado = n ** 2
cuadrado = pow(n,2)
print("El cuadrado de {} es {}".format(n,cuadrado)) |
08edecc297ce651d8e7178941aa00e01de2b8ef7 | halfozone007/repoA | /PythonProjects/RegularExpressions/1Regex.py | 420 | 3.796875 | 4 | #Regular Expressions are a very powerful method of matching patterns in a text
import re
def main():
fh = open('raven.txt')
for line in fh.readlines():
if re.search('(Neverm|Len)ore', line):
print(line, end = '')
for line in fh.readlines():
match = re.search('(Neverm|Len)ore', line)
if match:
print(match.group())
if __name__ == '__main__':
main()
|
112fcd917a53cbc7da8ce27c1055bfa577b93458 | halfozone007/repoA | /PythonProjects/Loops/enumerate.py | 151 | 3.5625 | 4 |
def main():
string = "this is a string"
for i, c in enumerate(string):
print(i, c)
if __name__ == '__main__':
main()
|
5b014f4393fb6048c8f2d7546fe03a3d5625b28d | halfozone007/repoA | /PythonProjects/VariablesObjectAndValues/2UsingString.py | 232 | 3.796875 | 4 |
def main():
n = 24
s = "This is a {} string".format(n)
print(s)
s1 = '''
Hello
hello1
hello2
''' #Print strings on different lines
print(s1)
if __name__ == '__main__':main()
|
8604414ab76375a1977f0b49929df80184b2fb9c | sagarnil1989/DemoProjects | /Customer Churn for Bank Customer/Classification_Solution_Sagarnil.py | 2,586 | 4.03125 | 4 | #Evaluating, Improving, Tuning Artificial Neural Network
# Part 1 - Data Preprocessing
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Set working directory & import data
dataset = pd.read_csv("Churn_Modelling.csv")
X=dataset.iloc[:,3:13].values
Y=dataset.iloc[:,13].values
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
#To avoid dummy variable trap, we have removed the first column of X
X = X[:, 1:]
# Spliting the dataset into Training set & Test set
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)
#Feature Scaling (to make the features on same scale)
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
#------------------
# Fitting Logistic Regression to the Training set
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(random_state = 0)
classifier.fit(X_train, Y_train)
# Predicting the Test set results
Y_pred = classifier.predict(X_test)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm_LogicalRegression = confusion_matrix(Y_test, Y_pred)
#-------------------
# Fitting SVM to the Training set
from sklearn.svm import SVC
classifier= SVC(kernel='linear', random_state=0)
classifier.fit(X_train,Y_train)
# Predicting the Test set results
Y_pred = classifier.predict(X_test)
# Making the Confusion Matrix
cm_SVM = confusion_matrix(Y_test, Y_pred)
#---------------------
# Fitting classifier to the Training set
from sklearn.svm import SVC
classifier= SVC(kernel='rbf',random_state=0)
classifier.fit(X_train,Y_train)
# Predicting the Test set results
Y_pred = classifier.predict(X_test)
# Making the Confusion Matrix
cm_SVM_Kernel = confusion_matrix(Y_test, Y_pred)
#------------------
# Fitting Random Forest Classification
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0)
classifier.fit(X_train, Y_train)
# Predicting the Test set results
Y_pred = classifier.predict(X_test)
# Making the Confusion Matrix
cm_RandomForest = confusion_matrix(Y_test, Y_pred)
|
cb9c3f9e12220ab7a64692d3d4a2fa22860152c6 | zxy1013/creat_mode | /creat_mode/factory.py | 1,234 | 4 | 4 | # 简单工厂模式
from abc import ABCMeta, abstractmethod
# 抽象产品角色
class Payment(metaclass=ABCMeta):
@abstractmethod
def pay(self, money):
pass
# 具体产品角色
class Alipay(Payment):
def __init__(self, use_huabei=False):
self.use_huabei = use_huabei
def pay(self, money):
if self.use_huabei:
print("花呗支付%d元" % money)
else:
print("支付宝余额支付%d元" % money)
class WechatPay(Payment):
def pay(self, money):
print("微信支付%d元" % money)
# 工厂角色
# 工厂类生产对象---支付对象
class PaymentFactory:
def create_payment(self, method):
if method == 'alipay':
return Alipay()
elif method == 'wechat':
return WechatPay()
elif method == 'huabei':
return Alipay(use_huabei=True) # 可以传一些不需要用户自己传入的参数或隐藏一些功能 否则需要用户自己将代码读完,自己实现
else:
raise TypeError("No such payment named %s" % method)
# client代码--高层代码
pf = PaymentFactory()
p = pf.create_payment('huabei') # 免去了用户了解use_huabei参数的作用
p.pay(100) |
c45a016425d84fc6eda59d6d82c359b0eb3d49a6 | iayushbhartiya/iayushbhartiya | /Guessing the number.py | 739 | 3.96875 | 4 | #Guessing the number
nam = input('Enter your name: ')
print('Welcome to guessing game', nam)
num = 18
i = 0
while(True):
count = 9 - i
if count<0:
print('Game over')
break
i += 1
val = int(input('Enter a number: '))
if val>18:
if val>30:
print('You are guessing much bigger, guess near 25')
if val==19:
print('You are close')
print('Guess a smaller number')
elif val<18:
if val <10:
print('You are guessing much smaller')
print('Guess a bigger number')
else:
print('Congrats! you guessed it correctly')
break
print("left count=", count)
|
4b4076ce66e3a70a7c36bc4c5aa87699a9f30995 | Bayaz/flasktaskr | /project/db_create.py | 780 | 3.625 | 4 | #project/db_create.py
import sqlite3
from _config import DATABASE_PATH
with sqlite3.connect(DATABASE_PATH) as connection:
#get cursor object to execute SQL commands
c = connection.cursor()
#create table
c.execute("""CREATE TABLE tasks(\
task_id INTEGER PRIMARY KEY AUTOINCREMENT, \
name TEXT NOT NULL, \
due_date TEXT NOT NULL, \
priority INTEGER NOT NULL, \
status INTEGER NOT NULL\
)""")
#insert dummy data into table
c.execute(
'INSERT INTO tasks (name, due_date, priority, status)'
'VALUES("Finish Tutorial", "01/09/2016", 10, 1)'
)
c.execute(
'INSERT INTO tasks (name, due_date, priority, status)'
'VALUES("Finish Real Python 2", "01/25/2016", 9, 3)'
) |
4f7f761819b008ab5a09eb51272fcfaeb974c12f | Ad0rian/Python-Voice-input-test | /venv/app.py | 2,076 | 3.75 | 4 | """
Este pequeño programa tiene el objetivo de probar el servicio de voz que permite usar python, en concreto este pequeño
programa te permite realizar dos funciones, la primera es la de apagar tu equipo si le dices 'Apagar' y la otra funcion
es la de buscar en internet, para activar esta funcion le tienes que decir 'servicio' y se activara el buscador, este
buscador se divide en dos partes, la primera parte le dices el objeto que buscar y la segunda parte lo que quieres hacer
con dicho objeto (Ejemplo: Pingu - bailando).
"""
import speech_recognition as sr
import webbrowser as wb
r1 = sr.Recognizer()
r2 = sr.Recognizer()
r3 = sr.Recognizer()
with sr.Microphone() as source:
print('speak now:')
audio = r3.listen(source)
text = str(r2.recognize_google(audio, language = 'es-Es'))
if text == 'servicio':
def services(text):
with sr.Microphone() as source:
print('¿Que deseas hacer?')
audio = r2.listen(source)
text = str(r2.recognize_google(audio, language='es-Es'))
if text == 'apagar':
import os
os.system("shutdown /s /t 1")
services(text)
if text in r2.recognize_google(audio, language = 'es-Es') :
r2 = sr.Recognizer()
url = 'https://www.google.com/search?q='+text
with sr.Microphone() as source:
print ('¿Que hace'+ text+'?')
audio = r2.listen(source)
try:
get = r2.recognize_google(audio, language = 'es-Es')
print(get)
wb.get().open_new(url+get)
except sr.UnknownValueError:
print('error')
except sr.RequestError as e:
print('failed'.format(e))
"""
#Asi son los comentarios.
a1 = b1 = c1 = "multiple Variables"
fruits = ["kiwi",1,"papaya"]
a2,b2,c2 = fruits
test= 10 #int
age = 20 #int
union = age + test
texto = "Texto" #Texto
print(a1)
print(b1)
print(c1)
print(a2)
print(b2)
print(c2)
print(union)
if age == 20:
print(age + test
if cebolla == 10:
print("Esto es un " + a2)
if texto == "Texto":
print(texto)
#Global variables
x= "engerenge"
def functiontesting():
x = test
print("Python is" + x)
functiontesting()
print(x)
print(type(x))
print(type(fruits))
""" |
85dcf64aed58d3d0f44bf12a86430788e684838e | Jayem-11/machine-learning-scratch | /machine_learning/neural_network/ann/perceptron/multiclass_perceptron.py | 5,428 | 3.828125 | 4 | import itertools
import numpy as np
from sklearn.datasets import make_classification
import matplotlib.pyplot as plt
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Perceptron as sklearn_perceptron
class multiClassPerceptron:
"""
Perceptron algorithm for multiclass classification
"""
def __init__(self, num_iter=1000):
"""
:param num_iter: total number of iteration through the training set(epochs)
num_class --> Total number of output class
w --> weights for our model of shape (num_class, number_of_feature)
b --> bias of our model of shape (num_class, )
"""
self.w = None
self.b = None
self.num_class = None
self.num_iter = num_iter
def fit(self, X_train, y_train):
"""
This method trains the model
:param x_train: training data of shape (number_of_training_example, number_of_input_feature)
:param y_train: label of the training example of shape (number of training_example, )
:return:
"""
# m represent the number of training example
# n_feature represent of number of input feature
m, num_feature = X_train.shape
self.num_class = len(np.unique(y_train))
# Every class will have its own weights and intercept/bias
# Initializing the weights and bias with zero
self.w = np.zeros((self.num_class, num_feature))
self.b = np.zeros(self.num_class)
# Number of time we will iter through the training example
for _ in range(self.num_iter):
# We will check every training example
for i in range(m):
# Make prediction for this training example
y_pred = self.predict(np.expand_dims(X_train[i], axis=0))
# ground truth
y_true = y_train[i]
# checking if our prediction is correct or not
if y_pred != y_true:
# if our prediction is wrong we will update the weights only for this true label
self.w[y_true, :] += X_train[i, :]
self.b[y_true] += 1.0
# We will also penalize the wrong predicted label
self.w[y_pred, :] -= X_train[i, :]
self.b[y_pred] -= 1.0
def predict(self, X_test):
"""
Make prediction of our model
:param x_test: Data for which we will make prediction
:return:
"""
# will contain the score for each class
scores = np.zeros((X_test.shape[0], self.num_class))
for i in range(self.num_class):
scores[:, i] = np.dot(X_test, self.w[i]) + self.b[i]
return np.argmax(scores) if X_test.shape[0] == 1 else np.argmax(scores, axis=1)
def get_f1_score(self, X_test, y_test):
"""
measure f1 score for our model
:param x_test: data for which we will calculate the f1_score
:param y_test: true label of x_test
:return:
"""
return f1_score(y_test, self.predict(X_test), average='weighted')
def show_decision_boundary(self, x, y):
"""
Show the decision boundary that was predicted by our model
:param X: Data to plot on the decision boundary
:param y: label of x
:return:
"""
colors = itertools.cycle(['r','g','b','c','y','m','k'])
markers = itertools.cycle(['o', 'v', '+', '*', 'x', '^', '<', '>'])
# Determine the x1- and x2- limits of the plot
x1min = min(x[:, 0]) - 1
x1max = max(x[:, 0]) + 1
x2min = min(x[:, 1]) - 1
x2max = max(x[:, 1]) + 1
plt.xlim(x1min, x1max)
plt.ylim(x2min, x2max)
# Plot the data points
k = int(max(y)) + 1
for label in range(k):
plt.plot(x[(y == label), 0], x[(y == label), 1], marker=next(markers), color=next(colors),linestyle='', markersize=8)
# Construct a grid of points at which to evaluate the classifier
grid_spacing = 0.05
xx1, xx2 = np.meshgrid(np.arange(x1min, x1max, grid_spacing), np.arange(x2min, x2max, grid_spacing))
grid = np.c_[xx1.ravel(), xx2.ravel()]
Z = self.predict(grid)
# Show the classifier's boundary using a color plot
Z = Z.reshape(xx1.shape)
plt.pcolormesh(xx1, xx2, Z, cmap=plt.cm.Pastel1, vmin=0, vmax=k)
plt.show()
if __name__ == '__main__':
X, y = make_classification(n_features=2, n_redundant=0, n_informative=2,
n_clusters_per_class=1, n_classes=4)
X_train, X_test, y_train, y_test = train_test_split(X, y)
perceptron = multiClassPerceptron()
perceptron.fit(X_train, y_train)
pred = perceptron.predict(X_test)
print(f"Training f1 score: {perceptron.get_f1_score(X_train, y_train)}")
print(f"Testing f1 score: {perceptron.get_f1_score(X_test, y_test)}")
print("=============================================")
perceptron.show_decision_boundary(X, y)
# measure performance with sklearn model
clf = sklearn_perceptron()
clf.fit(X_train, y_train)
print(f"Train F1 score for sklearn model: {f1_score(y_train, clf.predict(X_train), average='weighted')}")
print(f"Test F1 score for sklearn model: {f1_score(y_test, clf.predict(X_test), average='weighted')}") |
43382e8fe8fac375b8bdbbda97a67d853a5a7e19 | eleanorpark/Python-Dec-2018-CrashCourse | /areaofcircle.py | 348 | 4.125 | 4 | def area_of_circle(radius):
3.14*radius*radius
radius=2
area = 3.14*radius*radius
area_of_circle(radius)
print('area of circle of radius {} is:{}'.format(radius,area))
def area_of_circle(radius):
3.14*radius*radius
radius=10
area = 3.14*radius*radius
area_of_circle(radius)
print('area of circle of radius {} is:{}'.format(radius,area))
|
6f89741abdec32b48b49bb52fa494c944e2ad541 | mugiritsu/deepl-tr-pyppeteer | /deepl_tr_pp/browse_filename.py | 972 | 3.578125 | 4 | r"""Browse for a filename.
https://pythonspot.com/tk-file-dialogs/
filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes=(("jpeg files","*.jpg"),("all files","*.*")))
"""
# import sys
from pathlib import Path
import tkinter
from tkinter import filedialog
# fmt: off
def browse_filename(
initialdir=Path.cwd(),
title="Select a file",
filetypes=(
("text files", "*.txt"),
("docx files", "*.docx"),
# ("gzip files", "*.gz"),
# ("bzip2 files", "*.bz2"),
("all files", "*.*"),
)
):
# fmt: on
"""Browse for a filename.
or None when cancelled.
"""
root = tkinter.Tk()
# root.withdraw()
root.attributes('-alpha', 0.05)
root.focus_force()
filename = filedialog.askopenfilename(
parent=root,
initialdir=initialdir,
title=title,
filetypes=filetypes,
)
root.withdraw()
return filename
|
d84ff4475eee0708a755242c6019a381a1aa7c5f | carinapetcu/University-Projects | /Fundamentals of Programming/Game of Life/Validator/Validate.py | 673 | 3.640625 | 4 | import math
from Exceptions.Exceptions import ValidatorError
class Validate:
def __init__(self):
pass
@staticmethod
def validateBoards(board, boardWithPattern, row, column):
dimension = int(len(boardWithPattern))
for index1 in range(dimension):
for index2 in range(dimension):
if board[row+index1][column+index2] == boardWithPattern[index1][index2] == 1:
raise ValidatorError("The live cells overlap!")
if index1 + row > 8 or index2 + column > 8 and boardWithPattern[index1][index2] == 1:
raise ValidatorError("The live cell is outside the board!")
|
6832c702badf29d98eed86d234df1ba0183f9f4f | Deepak995/python | /bacic_exception.py | 501 | 3.8125 | 4 |
class division:
def divi(self, a,b):
try:
# a=int(input("enter the value of a "))
#b=int(input("enter the value of b"))
c=a/b
except ArithmeticError :
print("enter the right value of b")
else:
return c
print("this is a free statement")
class exe:
a=int(input("enter the value of a "))
b=int(input("enter the value of b"))
ob=division()
d=ob.divi(a,b)
print(d)
|
4add69787b4ad852eb7511ddbcdf5664ea1b2917 | Deepak995/python | /iterator.py | 173 | 3.796875 | 4 | a=[1,2,2,3,2,'eraju','baju']
"""for i in a:
print (i)"""
b=iter(a)
print(b)
print(next(b))
print(next(b))
print(next(b))
print(next(b))
print(next(b))
print(next(b))
|
137bcdcadc480592f4a3c50240146b6fe9126313 | Deepak995/python | /ansss.py | 1,287 | 3.59375 | 4 | ###P- Replace somthing from given input
# s1 = 'how are you'
# s1 = s1.replace('how', 'who')
# print(s1)
#
# list = ['where are you']
# list = list[0].replace('where','who')
# print(list)
######################################################
###P- output should be ----->[4, 5, 6, 1, 2, 3]
# input = [1,2,3,4,5,6]
# output = []
# l = len(input)
# n = int(l/2)
#
# print(l)
#
# for j in range(n,l):
# output.append(input[j])
# for i in range(0,n):
# output.append(input[i])
# print(output)
######################################################
###P- output should be ----->{'sw1': 'vlan1', 'sw2': 'vlan2', 'sw3': 'vlan3'}
# import re
# swvlans = '''sw1 has vlan1
# sw2 has vlan2
# sw3 has vlan3'''
# dictt = {}
# match = re.findall(r'(sw\d+).*(vlan\d+)',swvlans)
# for i in match:
# print(i[0])
# print(i[1])
# print(i)
# dictt[i[0]] = i[1]
# print(dictt)
######################################################
###P- list all the files in current directory
# import os
# output = os.listdir()
# print(output)
# print(len(output))
######################################################
###P- find the square of each element
# listt = [1,2,3,4,5,6]
# liis1 = [x*x for x in listt]
# print(liis1)
|
16e7156b501609938163fcdc287b256589830413 | nilloc95/Graphing-with-python | /d_graph.py | 11,906 | 4.09375 | 4 | # Course: CS261 - Data Structures
# Author: Collin Gilmore
# Assignment: 6
# Description: This file contains a class for an directed graph using a matrix to store links between nodes
# along with the weight. It also has methods to add vertices, edges, remove edges,
# find out if a path is valid, depth and breadth first searches, if the graph contains a cycle or not,
# and dijkstra's algorithm to find the shortest path to each node
from collections import deque
class DirectedGraph:
"""
Class to implement directed weighted graph
- duplicate edges not allowed
- loops not allowed
- only positive edge weights
- vertex names are integers
"""
def __init__(self, start_edges=None):
"""
Store graph info as adjacency matrix
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
self.v_count = 0
self.adj_matrix = []
# populate graph with initial vertices and edges (if provided)
# before using, implement add_vertex() and add_edge() methods
if start_edges is not None:
v_count = 0
for u, v, _ in start_edges:
v_count = max(v_count, u, v)
for _ in range(v_count + 1):
self.add_vertex()
for u, v, weight in start_edges:
self.add_edge(u, v, weight)
def __str__(self):
"""
Return content of the graph in human-readable form
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
if self.v_count == 0:
return 'EMPTY GRAPH\n'
out = ' |'
out += ' '.join(['{:2}'.format(i) for i in range(self.v_count)]) + '\n'
out += '-' * (self.v_count * 3 + 3) + '\n'
for i in range(self.v_count):
row = self.adj_matrix[i]
out += '{:2} |'.format(i)
out += ' '.join(['{:2}'.format(w) for w in row]) + '\n'
out = f"GRAPH ({self.v_count} vertices):\n{out}"
return out
# ------------------------------------------------------------------ #
def add_vertex(self) -> int:
"""
Add new vertex to the graph
"""
self.adj_matrix.append([0 for x in self.adj_matrix])
for vertex in self.adj_matrix:
vertex.append(0)
self.v_count += 1
return self.v_count
def add_edge(self, src: int, dst: int, weight=1) -> None:
"""
Add edge to the graph
"""
if weight < 1:
return
if src == dst:
return
if src >= self.v_count or dst >= self.v_count:
return
self.adj_matrix[src][dst] = weight
def remove_edge(self, src: int, dst: int) -> None:
"""
Removes and edge between two vertices, if they are in the correct range
"""
if src < 0 or dst < 0:
return
if src < self.v_count and dst < self.v_count:
self.adj_matrix[src][dst] = 0
def get_vertices(self) -> []:
"""
returns the vertices in the graph in a list
"""
return [x for x in range(self.v_count)]
def get_edges(self) -> []:
"""
Returns a list of all the edges
"""
edges = []
for x in range(self.v_count):
for i in range(self.v_count):
if self.adj_matrix[x][i] != 0:
tup = (x, i, self.adj_matrix[x][i])
edges.append(tup)
return edges
def is_valid_path(self, path: []) -> bool:
"""
Return true if provided path is valid, False otherwise
"""
length = len(path)
if length == 0:
return True
for i in range(length - 1):
if path[i] >= self.v_count:
return False
if self.adj_matrix[path[i]][path[i + 1]] == 0:
return False
return True
def dfs(self, v_start, v_end=None) -> []:
"""
Return list of vertices visited during DFS search
Vertices are picked in ascending order
"""
path = []
stack = []
# Return empty path if the start isn't in the graph
if v_start >= self.v_count:
return path
# Else: Search the entire graph until we've searched everything or the value is found. Return the search path
path.append(v_start)
for vertex in range(self.v_count - 1, -1, -1):
if self.adj_matrix[v_start][vertex] != 0:
stack.append(vertex)
if v_end in path:
return path
while len(stack) != 0:
current = stack.pop()
if current not in path:
path.append(current)
if current == v_end:
return path
for vertex in range(self.v_count - 1, -1, -1):
if self.adj_matrix[current][vertex] != 0 and vertex not in path:
stack.append(vertex)
return path
def bfs(self, v_start, v_end=None) -> []:
"""
Return list of vertices visited during BFS search
Vertices are picked in ascending order
"""
path = []
queue = deque()
# Return empty path if the start isn't in the graph
if v_start >= self.v_count:
return path
# Else: Search the entire graph until we've searched everything or the value is found. Return the search path
path.append(v_start)
for vertex in range(self.v_count):
if self.adj_matrix[v_start][vertex] != 0:
queue.append(vertex)
if v_end in path:
return path
while len(queue) != 0:
current = queue.popleft()
if current not in path:
path.append(current)
if current == v_end:
return path
for vertex in range(self.v_count):
if self.adj_matrix[current][vertex] != 0 and vertex not in path:
queue.append(vertex)
return path
def has_cycle(self):
"""
Returns True if there is a cycle in the directed graph, returns False otherwise
"""
visited = [False for x in range(self.v_count)]
found = False
for vertex in range(self.v_count):
visited[vertex] = True
for link in range(self.v_count - 1, -1, -1):
if self.adj_matrix[vertex][link] != 0:
found = self.cycle_helper(visited, link)
if found is True:
return True
visited[vertex] = False
return False
def cycle_helper(self, visited, current):
"""
Helper method for has_cycle used recursively
"""
if visited[current] is True:
return True
visited[current] = True
found = False
for i in range(self.v_count - 1, -1, -1):
if self.adj_matrix[current][i] != 0:
found = self.cycle_helper(visited, i)
if found is True:
return True
visited[current] = False
return False
def dijkstra(self, src: int) -> []:
"""
Takes a starting vertex and returns a list with the shortest path to all other vertices in the graph. A vertex
will contain an "inf" value if it cannot be reached.
"""
length = len(self.adj_matrix)
output = [float('inf') for x in range(length)]
output[src] = 0
finished = [False for x in range(length)]
for vertex in range(length):
low = self.minDistance(output, finished)
if low is None:
return output
finished[low] = True
for index in range(length):
if self.adj_matrix[low][index] > 0 and finished[index] is False and \
output[index] > output[low] + self.adj_matrix[low][index]:
output[index] = output[low] + self.adj_matrix[low][index]
return output
def minDistance(self, lengths, processed):
"""Helper function for dijkstra's algorithm to find the next shortest node"""
minimum = float('inf')
index = None
for vertex in range(len(self.adj_matrix)):
if lengths[vertex] < minimum and processed[vertex] is False:
minimum = lengths[vertex]
index = vertex
return index
if __name__ == '__main__':
#
# print("\nPDF - method add_vertex() / add_edge example 1")
# print("----------------------------------------------")
# g = DirectedGraph()
# print(g)
# for _ in range(5):
# g.add_vertex()
# print(g)
#
# edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
# (3, 1, 5), (2, 1, 23), (3, 2, 7)]
# for src, dst, weight in edges:
# g.add_edge(src, dst, weight)
# print(g)
# print("\nPDF - method get_edges() example 1")
# print("----------------------------------")
# g = DirectedGraph()
# print(g.get_edges(), g.get_vertices(), sep='\n')
# edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
# (3, 1, 5), (2, 1, 23), (3, 2, 7)]
# g = DirectedGraph(edges)
# print(g.get_edges(), g.get_vertices(), sep='\n')
# print("\nPDF - method is_valid_path() example 1")
# print("--------------------------------------")
# edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
# (3, 1, 5), (2, 1, 23), (3, 2, 7)]
# g = DirectedGraph(edges)
# test_cases = [[0, 1, 4, 3], [1, 3, 2, 1], [0, 4], [4, 0], [], [2]]
# for path in test_cases:
# print(path, g.is_valid_path(path))
# print("\nPDF - method dfs() and bfs() example 1")
# print("--------------------------------------")
# edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
# (3, 1, 5), (2, 1, 23), (3, 2, 7)]
# g = DirectedGraph(edges)
# for start in range(5):
# print(f'{start} DFS:{g.dfs(start)} BFS:{g.bfs(start)}')
#
# print("\nPDF - method dfs() and bfs() example 2")
# print("--------------------------------------")
# edges = [(2, 11, 7), (3, 8, 13), (4, 7, 1), (4, 4, 10), (6, 3, 7), (6, 11, 7), (10, 4, 14), (11, 5, 2), (11, 12, 9),
# (12, 4, 4), (12, 6, 5)]
# g = DirectedGraph(edges)
#
# print(f'DFS:{g.dfs(12)} BFS:{g.bfs(6)}')
# print("\nPDF - method has_cycle() example 1")
# print("----------------------------------")
# edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
# (3, 1, 5), (2, 1, 23), (3, 2, 7)]
# g = DirectedGraph(edges)
#
# edges_to_remove = [(3, 1), (4, 0), (3, 2)]
# for src, dst in edges_to_remove:
# g.remove_edge(src, dst)
# print(g.get_edges(), g.has_cycle(), sep='\n')
#
# edges_to_add = [(4, 3), (2, 3), (1, 3), (4, 0)]
# for src, dst in edges_to_add:
# g.add_edge(src, dst)
# print(g.get_edges(), g.has_cycle(), sep='\n')
# print('\n', g)
#
# print("\nPDF - method has_cycle() example 2")
# print("----------------------------------")
# edges = [(0, 3, 1), (2, 6, 17), (2, 8, 14), (3, 11, 7), (4, 5, 19), (5, 3, 19), (5, 10, 2), (5, 11, 10), (6, 7, 15),
# (8, 6, 15), (8, 12, 7), (11, 7, 20), (12, 9, 10)]
# g = DirectedGraph(edges)
#
# print(g.get_edges())
# print(g.has_cycle())
# print('\n', g)
print("\nPDF - dijkstra() example 1")
print("--------------------------")
edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
(3, 1, 5), (2, 1, 23), (3, 2, 7)]
g = DirectedGraph(edges)
for i in range(5):
print(f'DIJKSTRA {i} {g.dijkstra(i)}')
g.remove_edge(4, 3)
print('\n', g)
for i in range(5):
print(f'DIJKSTRA {i} {g.dijkstra(i)}')
|
0f7cfefeb124d76ef25dc904500246c9e843658d | xg04tx/number_game2 | /guessing_game.py | 2,282 | 4.125 | 4 |
def main():
while True:
try:
num = int(
input("Please, think of a number between 1 and 1000. I am about to try to guess it in 10 tries: "))
if num < 1 or num > 1000:
print("Must be in range [1, 100]")
else:
computer_guess(num)
except ValueError:
print("Please put in only whole numbers for example 4")
def computer_guess(num):
NumOfTry = 10
LimitLow = 1
LimitHigh = 1000
NumToGuess = 500
while NumOfTry != 0:
try:
print("I try: ", NumToGuess)
print("Please type: 1 for my try is too high")
print(" 2 for my try is too low")
print(" 3 I guessed your number")
Answer = int(input("So did I guess right?"))
if 1 < Answer > 3:
print("Please enter a valid answer. 1, 2 and 3 are the valid choice")
NumOfTry = NumOfTry + 1
if Answer == 1:
LimitHigh = NumToGuess
print("Hmm, so your number is between ", LimitLow, "and ", LimitHigh)
NumOfTry = NumOfTry - 1
print(NumOfTry, "attempts left")
NumToGuess = int(((LimitHigh - LimitLow) / 2) + LimitLow)
if NumToGuess <= LimitLow:
NumToGuess = NumToGuess + 1
if LimitHigh - LimitLow == 2:
NumToGuess = LimitLow + 1
elif Answer == 2:
LimitLow = NumToGuess
print("Hmm, so your number is between ", LimitLow, "and ", LimitHigh)
NumOfTry = NumOfTry - 1
print(NumOfTry, "attempts left")
NumToGuess = int(((LimitHigh - LimitLow) / 2) + LimitLow)
if NumToGuess <= LimitLow:
NumToGuess = NumToGuess + 1
if LimitHigh - LimitLow == 2:
NumToGuess = LimitLow + 1
elif num == NumToGuess:
print("Don't cheat")
NumOfTry = NumOfTry + 1
elif Answer == 3:
print("I won!!!!")
NumOfTry = 0
except:
return main()
if __name__ == '__main__':
main()
|
76b9e0167bf76c50015b4359665b33f495e85c81 | echo-1234/code-complete-MIT60001 | /assignments/ps0/ps0.py | 191 | 3.953125 | 4 | ## input
## data type
## numerical operation
import numpy
x = int(input("Enter a number x: "))
y = int(input("Enter a number y: "))
print("x**y = ", x**y)
print("log(x) = ", numpy.log2(x))
|
3beab522b6c62c0302f7a436bd2da893889d87d4 | rickmansfield/U5.2-M3 | /U5-2-M3-Homework/Task4b.py | 799 | 3.734375 | 4 |
def csWordPattern(pattern, a):
# print(a.split())
words = a.split()
# print("words split", words)
if len(words) != len(pattern):
return False
char_to_word = dict()
for i in range(len(pattern)):
char = pattern[i]
word = words[i]
if char in char_to_word:
if char_to_word[char] != word:
return False
else:
if word in char_to_word.values():
return False
char_to_word[char] = word
return True
print(csWordPattern("abba", "lambda school school lambda"))
print(csWordPattern("abba", "lambda school school coding"))
print(csWordPattern("aaaa", "lambda school school lambda"))
print(csWordPattern("abba", "lambda lambda lambda lambda")) |
3d2acafdebab21cb2ff8c5b0b08e26ba47ed8b44 | vtheno/zuse_sim | /MainMenu.py | 4,269 | 3.796875 | 4 | import Tkinter as Tk
import App
class MainMenu(object):
def __init__(self, master):
self.master = master
self.width = master.winfo_width()
self.height = master.winfo_height()
f_text = Tk.Frame(master, bg = 'white', width = self.width, height = self.height / 6,bd=1)
f_text.grid(row = 0, column = 0, columnspan = 2)
f_text.grid_propagate(False)
f_instruction = Tk.Frame(master, bg = 'white', width = self.width, height = self.height / 6,bd=1)
f_instruction.grid(row = 1, column = 0, columnspan = 2)
f_instruction.grid_propagate(False)
fleft = Tk.Frame(master, bg = 'white', width = self.width / 2, height = self.height * 2 / 3)
fleft.grid(row = 2, column = 0)
fright = Tk.Frame(master, bg = 'white', width = self.width / 2, height = self.height * 2 / 3)
fright.grid(row = 2, column = 1)
header = Tk.Label(f_text, text='Simulation of Konrad Zuses "logistische Maschine"', font = "Helvetica 16 bold",bg = 'white')
header.place(relx=0.5, rely=0.5, anchor=Tk.CENTER)
instruction = Tk.Label(f_instruction, text='Use the Buttons to select a Program',font = "Helvetica 12",bg = 'white')
instruction.place(relx=0.5, rely=0.2, anchor=Tk.CENTER)
fl1 = Tk.Frame(fleft,width = self.width / 2, height = self.height * 2 / 9)
fl1.pack_propagate(0)
fl1.pack()
fl2 = Tk.Frame(fleft,width = self.width / 2, height = self.height * 2 / 9)
fl2.pack_propagate(0)
fl2.pack()
fl3 = Tk.Frame(fleft,width = self.width / 2, height = self.height * 2 / 9)
fl3.pack_propagate(0)
fl3.pack()
button1 = Tk.Button(fl1,text = 'QUIT', command = self.close_window, bg = 'white')
button1.pack(fill=Tk.BOTH,expand = 1)
button2 = Tk.Button(fl2,text = 'Addition of 2 4-Bit Integers \n~5 minutes', command = self.add_4_bit,bg = 'white')
button2.pack(fill=Tk.BOTH,expand = 1)
button3 = Tk.Button(fl3,text = 'Addition of 2 8-Bit Integers \n~10 minutes', command = self.add_8_bit,bg = 'white')
button3.pack(fill=Tk.BOTH,expand = 1)
fr1 = Tk.Frame(fright,width = self.width / 2, height = self.height * 2 / 9)
fr1.pack_propagate(0)
fr1.pack()
fr2 = Tk.Frame(fright,width = self.width / 2, height = self.height * 2 / 9)
fr2.pack_propagate(0)
fr2.pack()
fr3 = Tk.Frame(fright,width = self.width / 2, height = self.height * 2 / 9)
fr3.pack_propagate(0)
fr3.pack()
button4 = Tk.Button(fr1,text = 'Subtraction of 2 4-Bit Integers. \n~10 minutes', command = self.sub_4_bit,bg = 'white')
button4.pack(fill=Tk.BOTH,expand = 1)
button5 = Tk.Button(fr2,text = 'Multiplication of 2 3-Bit Integers. \n~17 minutes', command = self.mul_3_bit, bg = 'white')
button5.pack(fill=Tk.BOTH,expand = 1)
button6 = Tk.Button(fr3,text = 'Division of 2 3-Bit Integers \n~50(!) minutes', command = self.div_3_bit,bg = 'white')
button6.pack(fill=Tk.BOTH,expand = 1)
def add_4_bit(self):
self.new_window('add_4_bit.txt','Adding Numbers t0-t3 and t4-t7.', 't10-t14',5)
def add_8_bit(self):
self.new_window('add_8_bit.txt','Adding Numbers t0-t7 and t10-t17','t18-t26',10)
def sub_4_bit(self):
self.new_window('sub_4_bit.txt','Subtracting Number t4-t7 from t0-t3.', 't11-t15.',10)
def mul_3_bit(self):
self.new_window('mul_3_bit.txt','Multiplying Numbers t0-t2 and t3-t5.', 't20-t25',17)
def div_3_bit(self):
self.new_window('div_3_bit.txt','Dividing Number t0-t2 by t3-t5.','t18-t20 with remainder t27-t32.',50)
def new_window(self,file_name,input_info,output_info,duration_estimate):
self.newWindow = Tk.Toplevel(self.master)
self.newWindow.attributes('-fullscreen', True)
self.newWindow.geometry("{0}x{1}+0+0".format(self.newWindow.winfo_screenwidth(), self.newWindow.winfo_screenheight()))
#self.newWindow.geometry("1024x768")
self.newWindow.configure(bg="white")
self.newWindow.update()
self.app = App.App(self.newWindow,file_name,input_info,output_info,duration_estimate)
def close_window(self):
self.master.destroy()
|
d3030ce858b421aa3b7d4f86874063ed0d862890 | akshayjoshii/LeetCode_Coding_Interview | /Pos_Neg_Array.py | 942 | 3.578125 | 4 | import numpy as np
import timeit
#O(n^2) - Simple solution
def pos_neg_simple(arr):
t = []
#2 for loops
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if(abs(arr[i]) == abs(arr[j])):
t.append(abs(arr[i]))
if(len(t)==0):
return "No Positive/Negative pairs found"
t.sort()
for k in range(len(t)):
print("\nThe pairs are {} & {}".format(t[k], -t[k]))
# O(n) - Optimised solution with Hash table
def pos_neg_hash(arr):
t = {}
v = []
#Single for loop
for i in range(len(arr)):
if not abs(arr[i]) == t:
t = arr[i]
else:
v.append(abs(arr[i]))
if len(v) == 0:
return "No match"
v.sort()
v = np.array(v)
#v[:] = map(lambda x: -x, v)))
print(v, -v)
if __name__ == "__main__":
ar = input().split(' ')
ar = [int(num) for num in ar]
print(pos_neg_simple(ar)) |
4659470dc6b39f197e43b358b5bd8f196157dec1 | Parkhomets/Python | /Stepic/2/DateAndTime.py | 208 | 3.765625 | 4 | import datetime
x = input().split(" ")
for i in range(3):
x[i] = int(x[i])
data = datetime.date(x[0], x[1], x[2])
data = data + datetime.timedelta(int(input()))
print(data.year, data.month, data.day)
|
1c1b4cd1dda92e6aef9fe38236a45a856776f082 | ConorMB93/Python1 | /AirportDistance/Airports.py | 635 | 3.734375 | 4 | '''
Airports
by Conor Byrne
'''
class Airports:
def __init__(self, airport_code, name, city, country, lat, long):
self.airport_code = airport_code
self.name = name
self.country = country
self.city = city
self.lat = float(lat)
self.long = float(long)
def __str__(self):
return " {} ( Name : {} , {} ,{} lat :{} long :{}) ". format(
self.airport_code, self.name, self.city, self.country, self.lat, self.long)
def main():
myAirport = Airports("DUB", "Dublin Airport","Dublin", "Ireland", 15, 23)
print(myAirport)
if __name__ == "__main__":
main()
|
d8d59642182dbba4388cdfd81ab97e99efa92cc5 | rchaskar/PycharmWork | /Functions.py | 742 | 4.0625 | 4 | '''def average(a,b):
return (a+b/2)
print(average(20,10))
'''
'''def calculate(a,b):
x=a+b
y=a-b
z=a*b
r=a/b
return x,y,z,r
print(calculate(10,20))
'''
#function inside another function
'''
def message(name):
def gretting():
return "How are u "
return gretting() + name
print(message("Rahul "))
'''
'''
def display():
def messsage():
return "hello"
return messsage()
print(display())
def display():
def message():
return "Hi!!"
return message
fun=display()
print(fun())
'''
#python program to find a factorial of a given number
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result
print(factorial(3))
|
98f3f92f67791def2251246bccb8770c73320dae | rchaskar/PycharmWork | /assignment1.py | 117 | 3.5625 | 4 | Name = "Rahul Chaskar"
City = "Pune"
Age = 26
height = 179
Weight = 80
print("Name is" + Name , "City:" +City, Age, Weight) |
6c111511875ad1fd6eb2c23a7206122a73f23e76 | kexinxin/Defect | /genetic-hyperopt/mahakil/Distance.py | 348 | 3.578125 | 4 | class Distance:
def __init__(self,distance,label):
self.__distance__ = distance
self.__label__= label
def get_distance(self):
return self.__distance__
def get_label(self):
return self.__label__
def __str__(self):
return str("distance:{} label:{} ".format(self.__distance__,self.__label__))
|
dc0b326cbbd52603b780b087d8f2fe9ab7e3c63a | kexinxin/Defect | /SoftwarePrediction/OverSampleAlgorithm/smote.py | 3,030 | 3.5625 | 4 | from sklearn.neighbors import NearestNeighbors
import random
import numpy as np
class Smote:
"""
Implement SMOTE, synthetic minority oversampling technique.
Parameters
-----------
sample 2D (numpy)array
class samples
N Integer
amount of SMOTE N%
k Integer
number of nearest neighbors k
k <= number of minority class samples
Attributes
----------
newIndex Integer
keep a count of number of synthetic samples
initialize as 0
synthetic 2D array
array for synthetic samples
neighbors K-Nearest Neighbors model
"""
def __init__(self,data,label,b, k):
self.data=data
self.label=label
self.sample = self.getminSample(data,label)
self.k = k
self.T = len(self.sample)
self.ms, self.ml, self.minority = self.calculate_degree()
self.b=b
self.newIndex = 0
self.synthetic = []
self.neighbors = NearestNeighbors(n_neighbors=self.k).fit(self.sample)
def getminSample(self,data,label):
sample=[]
for i in range(len(data)):
if label[i]==1:
sample.append(data[i])
sample=np.array(sample)
return sample
def calculate_degree(self):
pos, neg = 0, 0
for i in range(0, len(self.label)):
if self.label[i] == 1:
pos += 1
elif self.label[i] == 0:
neg += 1
ml = max(pos, neg)
ms = min(pos, neg)
if pos > neg:
minority = 0
else:
minority = 1
return ms, ml, minority
def over_sampling(self):
# if self.N < 100:
# self.T = int((self.N / 100) * self.T)
# self.N = 100
# self.N = int(self.N / 100)
self.N=int((self.ml - self.ms) * self.b)
for i in range(0,self.N):
#for i in range(0, self.T):
j=random.randint(0,self.T-1)
nn_array = self.compute_k_nearest(j)
self.populate(1, j, nn_array)
data_new=np.array(self.synthetic)
label_new = np.ones(len(data_new))
return np.append(self.data, data_new, axis=0), np.append(self.label, label_new, axis=0)
def compute_k_nearest(self, i):
nn_array = self.neighbors.kneighbors([self.sample[i]], self.k, return_distance=False)
if len(nn_array) is 1:
return nn_array[0]
else:
return []
def populate(self, N, i, nn_array):
while N is not 0:
nn = random.randint(0, self.k - 1)
self.synthetic.append([])
for attr in range(0, len(self.sample[i])):
dif = self.sample[nn_array[nn]][attr] - self.sample[i][attr]
gap = random.random()
self.synthetic[self.newIndex].append(self.sample[i][attr] + gap * dif)
self.newIndex += 1
N -= 1
|
760e2277fae9977374f73331293fb6efd1d7cddd | kexinxin/Defect | /SoftwarePrediction/OverSampleAlgorithm/BorderlineOverSamplling.py | 4,098 | 3.5625 | 4 | import random
from sklearn.neighbors import NearestNeighbors
import numpy as np
class BorderlineOverSampling:
"""
RandomOverSampler
Parameters
-----------
X 2D array
feature space X
Y array
label, y is either 0 or 1
b float in [0, 1]
desired balance level after generation of the synthetic data
K Integer
number of nearest neighbors
Attributes
----------
ms Integer
the number of minority class examples
ml Integer
the number of majority class examples
d float in n (0, 1]
degree of class imbalance, d = ms/ml
minority Integer label
the class label which belong to minority
neighbors K-Nearest Neighbors model
synthetic 2D array
array for synthetic samples
"""
def __init__(self, X, Y, b, K):
self.X = X
self.Y = Y
self.K = K
self.N=1
self.ms, self.ml, self.minority = self.calculate_degree()
self.b = b
self.neighbors = NearestNeighbors(n_neighbors=self.K).fit(self.X)
self.synthetic = []
self.sample = self.getminSample(X, Y)
self.minNeighbors = NearestNeighbors(n_neighbors=self.K).fit(self.sample)
self.newIndex = 0
def getminSample(self,data,label):
sample=[]
for i in range(len(data)):
if label[i]==1:
sample.append(data[i])
sample=np.array(sample)
return sample
def calculate_degree(self):
pos, neg = 0, 0
for i in range(0, len(self.Y)):
if self.Y[i] == 1:
pos += 1
elif self.Y[i] == 0:
neg += 1
ml = max(pos, neg)
ms = min(pos, neg)
if pos > neg:
minority = 0
else:
minority = 1
return ms, ml, minority
def sampling(self):
# a: calculate the number of synthetic data examples
# that need to be generated for the minority class
G = (self.ml - self.ms) * self.b
#G=142
# b: for each xi in minority class, find K nearest neighbors
# based on Euclidean distance in n-d space and calculate ratio
# ri = number of examples in K nearest neighbors of xi that
# belong to majority class, therefore ri in [0,1]
r = []
for i in range(0, len(self.Y)):
if self.Y[i] == self.minority:
delta = 0
neighbors = self.neighbors.kneighbors([self.X[i]], self.K, return_distance=False)[0]
for neighbors_index in neighbors:
if self.Y[neighbors_index] != self.minority:
delta += 1
r.append(1. * delta / self.K)
indexs=[]
for i in range(0,len(r)):
if r[i]>=0.5 and r[i]<0.9:
indexs.append(i)
for i in range(0,int(G)):
index = random.randint(0,len(indexs)-1)
nn_array = self.compute_k_nearest(indexs[index])
self.populate(self.N, indexs[index], nn_array)
data_new = np.array(self.synthetic)
label_new = np.ones(len(data_new))
return np.append(self.X, data_new, axis=0), np.append(self.Y, label_new, axis=0)
def compute_k_nearest(self, i):
nn_array = self.minNeighbors.kneighbors([self.sample[i]], self.K, return_distance=False)
if len(nn_array) is 1:
return nn_array[0]
else:
return []
def populate(self, N, i, nn_array):
while N is not 0:
nn = random.randint(0, self.K - 1)
self.synthetic.append([])
for attr in range(0, len(self.sample[i])):
dif = self.sample[nn_array[nn]][attr] - self.sample[i][attr]
gap = random.random()
self.synthetic[self.newIndex].append(self.sample[i][attr] + gap * dif)
self.newIndex += 1
N -= 1 |
4092786eb3254dc3dcddd09bbe6892d5a0ccb717 | cksrb1616/Algorithm_past_papers | /DFSBFS/DFSBFS_5-5_factorial.py | 265 | 3.921875 | 4 | #반복적으로 구현한 n!
def factorial_iterative(n):
result=1
for i in range(1,n+1)
result *= i
return result
#재귀적으로 구현한 n!
def factorial_reculsive(n):
if n<=1:
return 1
return n*factorial_reculsive(n-1) |
513540cee31c1fbd3c2dbb95ffb4ed2bf3473b2c | TanyaGerenko/T.Gerenko | /Ex4.py | 555 | 3.8125 | 4 | #ДЗ-4
#N-школьников делят k-яблок поровну, неделящийся остаток остается в корзинке.
#Сколько яблок достанется каждому, сколько останется в корзинке?
k = int(input("Сколько всего яблок? "))
n= int(input("Сколько всего школьников? "))
print("Каждому школьнику достанется ", k//n, "яблок")
print("В корзинке останется ", k%n, "яблок")
|
6eae59d3f1e4f73b5563fc1979024d0cbd612705 | TanyaGerenko/T.Gerenko | /Ex6.py | 636 | 3.859375 | 4 | #ДЗ-6
#Дано целое, положительное, ТРЁХЗНАЧНОЕ число.
#Например: 123, 867, 374. Необходимо его перевернуть.
#Например, если ввели число 123, то должно получиться на выходе ЧИСЛО 321.
#ВАЖНО! Работать только с числами.
#Строки, оператор IF и циклы использовать НЕЛЬЗЯ!
n = int(input("Ввести целое, положительное, ТРЁХЗНАЧНОЕ число."))
reversN=n%10*100+n//10%10*10+n//100;
print("reversN:", reversN)
|
66c3ffce7cface103349ba9d972521cbe57c883c | MateusValasques/AlgoritmosPython | /Ordenação/Quase ordenados.py | 11,576 | 3.8125 | 4 | from array import *
import time
import random
cont_selection = 0
cont_insertion = 0
cont_shell = 0
cont_quicksort = 0
cont_heap = 0
cont_merge = 0
def selection_sort(array):
global cont_selection
for index in range(0, len(array)):
min_index = index
for right in range(index + 1, len(array)):
cont_selection += 1
if array[right] < array[min_index]:
min_index = right
array[index], array[min_index] = array[min_index], array[index]
return array
def insertion_sort(array):
global cont_insertion
for index in range(1, len(array)):
current_element = array[index]
cont_insertion += 1
while index > 0 and array[index - 1] > current_element:
array[index] = array[index - 1]
index -= 1
array[index] = current_element
return array
def shell_sort(array):
global cont_shell
gap = len(array) // 2
while gap > 0:
for i in range(gap, len(array)):
val = array[i]
j=i
cont_shell += 1
while j >= gap and array[j - gap] > val:
array[j] = array[j - gap]
j -= gap
array[j] = val
gap //= 2
return array
def partition(arr,low,high):
global cont_quicksort
i = (low - 1)
pivot = arr[high]
for j in range(low , high):
cont_quicksort += 1
if arr[j] < pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
def quick_sort(array,low=0,high=None):
global cont_quicksort
if high == None:
cont_quicksort += 1
high = len(array)-1
if low < high:
cont_quicksort += 1
pi = partition(array,low,high)
quick_sort (array, low, pi-1)
quick_sort (array, pi+1, high)
return array
def heapify(arr, n, i):
global cont_heap
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
cont_heap+=1
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i]
heapify(arr, n, largest)
def heap_sort(array):
global cont_heap
n = len(array)
#constroi heapmax
for i in range(n, -1, -1):
cont_heap+=1
heapify(array, n, i)
#remove os elementos 1 a 1
for i in range(n-1, 0, -1):
cont_heap+=1
array[i], array[0] = array[0], array[i]
heapify(array, i, 0)
return array
def merge_sort(array):
global cont_merge
if len(array) >1:
cont_merge+=1
mid = len(array)//2
L = array[:mid]
R = array[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
cont_merge+=1
if L[i] < R[j]:
array[k] = L[i]
i+=1
else:
array[k] = R[j]
j+=1
k+=1
while i < len(L):
cont_merge+=1
array[k] = L[i]
i+=1
k+=1
while j < len(R):
cont_merge+=1
array[k] = R[j]
j+=1
k+=1
return array
vet1 = array('i', [])
vet2 = array('i', [])
vet3 = array('i', [])
vet4 = array('i', [])
vet5 = array('i', [])
vet6 = array('i', [])
for i in range (10):
for i in range(5):
vet1.append(i)
for i in range(5):
vet1.append(random.randrange(10))
inicio = time.time()
selection_sort(vet1)
print("O SELECTIONSORT REALIZOU ", cont_selection, " COMPARAÇÕES")
cont_selection = 0
fim = time.time() - inicio
print("TEMPO PARA O SELECTION SORT DO VETOR 1 É", fim)
inicio = time.time()
insertion_sort(vet1)
print("O INSERTIONSORT REALIZOU ", cont_insertion, " COMPARAÇÕES")
cont_insertion = 0
fim = time.time() - inicio
print("TEMPO PARA O INSERTION SORT DO VETOR 1 É", fim)
inicio = time.time()
shell_sort(vet1)
print("O SHELLSORT REALIZOU ", cont_shell, " COMPARAÇÕES")
cont_shell = 0
fim = time.time() - inicio
print("TEMPO PARA O SHELL SORT DO VETOR 1 É", fim)
inicio = time.time()
quick_sort(vet1, cont_quicksort)
print("O QUICKSORT REALIZOU ", cont_quicksort, " COMPARAÇÕES")
cont_quicksort = 0
fim = time.time() - inicio
print("TEMPO PARA O QUICK SORT DO VETOR 1 É", fim)
inicio = time.time()
heap_sort(vet1)
print("O HEAPSORT REALIZOU ", cont_heap, " COMPARAÇÕES")
cont_heap = 0
fim = time.time() - inicio
print("TEMPO PARA O HEAP SORT DO VETOR 1 É", fim)
inicio = time.time()
merge_sort(vet1)
print("O MERGESORT REALIZOU ", cont_merge, " COMPARAÇÕES")
cont_merge = 0
fim = time.time() - inicio
print("TEMPO PARA O MERGE SORT DO VETOR 1 É", fim)
for i in range (100):
for i in range(5):
vet2.append(i)
for i in range(5):
vet2.append(random.randrange(10))
inicio = time.time()
selection_sort(vet2)
print("O SELECTIONSORT REALIZOU ", cont_selection, " COMPARAÇÕES")
cont_selection = 0
fim = time.time() - inicio
print("TEMPO PARA O SELECTION SORT DO VETOR 2 É", fim)
inicio = time.time()
insertion_sort(vet2)
print("O INSERTIONSORT REALIZOU ", cont_insertion, " COMPARAÇÕES")
cont_insertion = 0
fim = time.time() - inicio
print("TEMPO PARA O INSERTION SORT DO VETOR 2 É", fim)
inicio = time.time()
shell_sort(vet2)
print("O SHELLSORT REALIZOU ", cont_shell, " COMPARAÇÕES")
cont_shell = 0
fim = time.time() - inicio
print("TEMPO PARA O SHELL SORT DO VETOR 2 É", fim)
inicio = time.time()
quick_sort(vet2, cont_quicksort)
print("O QUICKSORT REALIZOU ", cont_quicksort, " COMPARAÇÕES")
cont_quicksort = 0
fim = time.time() - inicio
print("TEMPO PARA O QUICK SORT DO VETOR 2 É", fim)
inicio = time.time()
heap_sort(vet2)
print("O HEAPSORT REALIZOU ", cont_heap, " COMPARAÇÕES")
cont_heap = 0
fim = time.time() - inicio
print("TEMPO PARA O HEAP SORT DO VETOR 2 É", fim)
inicio = time.time()
merge_sort(vet2)
print("O MERGESORT REALIZOU ", cont_merge, " COMPARAÇÕES")
cont_merge = 0
fim = time.time() - inicio
print("TEMPO PARA O MERGE SORT DO VETOR 2 É", fim)
for i in range (1000):
for i in range(5):
vet3.append(i)
for i in range(5):
vet3.append(random.randrange(10))
inicio = time.time()
selection_sort(vet3)
print("O SELECTIONSORT REALIZOU ", cont_selection, " COMPARAÇÕES")
cont_selection = 0
fim = time.time() - inicio
print("TEMPO PARA O SELECTION SORT DO VETOR 3 É", fim)
inicio = time.time()
insertion_sort(vet3)
print("O INSERTIONSORT REALIZOU ", cont_insertion, " COMPARAÇÕES")
cont_insertion = 0
fim = time.time() - inicio
print("TEMPO PARA O INSERTION SORT DO VETOR 3 É", fim)
inicio = time.time()
shell_sort(vet3)
print("O SHELLSORT REALIZOU ", cont_shell, " COMPARAÇÕES")
cont_shell = 0
fim = time.time() - inicio
print("TEMPO PARA O SHELL SORT DO VETOR 3 É", fim)
inicio = time.time()
quick_sort(vet3, cont_quicksort)
print("O QUICKSORT REALIZOU ", cont_quicksort, " COMPARAÇÕES")
cont_quicksort = 0
fim = time.time() - inicio
print("TEMPO PARA O QUICK SORT DO VETOR 3 É", fim)
inicio = time.time()
heap_sort(vet3)
print("O HEAPSORT REALIZOU ", cont_heap, " COMPARAÇÕES")
cont_heap = 0
fim = time.time() - inicio
print("TEMPO PARA O HEAP SORT DO VETOR 3 É", fim)
inicio = time.time()
merge_sort(vet3)
print("O MERGESORT REALIZOU ", cont_merge, " COMPARAÇÕES")
cont_merge = 0
fim = time.time() - inicio
print("TEMPO PARA O MERGE SORT DO VETOR 3 É", fim)
for i in range (10000):
for i in range(5):
vet4.append(i)
for i in range(5):
vet4.append(random.randrange(10))
inicio = time.time()
selection_sort(vet4)
print("O SELECTIONSORT REALIZOU ", cont_selection, " COMPARAÇÕES")
cont_selection = 0
fim = time.time() - inicio
print("TEMPO PARA O SELECTION SORT DO VETOR 4 É", fim)
inicio = time.time()
insertion_sort(vet4)
print("O INSERTIONSORT REALIZOU ", cont_insertion, " COMPARAÇÕES")
cont_insertion = 0
fim = time.time() - inicio
print("TEMPO PARA O INSERTION SORT DO VETOR 4 É", fim)
inicio = time.time()
shell_sort(vet4)
print("O SHELLSORT REALIZOU ", cont_shell, " COMPARAÇÕES")
cont_shell = 0
fim = time.time() - inicio
print("TEMPO PARA O SHELL SORT DO VETOR 4 É", fim)
inicio = time.time()
quick_sort(vet4, cont_quicksort)
print("O QUICKSORT REALIZOU ", cont_quicksort, " COMPARAÇÕES")
cont_quicksort = 0
fim = time.time() - inicio
print("TEMPO PARA O QUICK SORT DO VETOR 4 É", fim)
inicio = time.time()
heap_sort(vet4)
print("O HEAPSORT REALIZOU ", cont_heap, " COMPARAÇÕES")
cont_heap = 0
fim = time.time() - inicio
print("TEMPO PARA O HEAP SORT DO VETOR 4 É", fim)
inicio = time.time()
merge_sort(vet4)
print("O MERGESORT REALIZOU ", cont_merge, " COMPARAÇÕES")
cont_merge = 0
fim = time.time() - inicio
print("TEMPO PARA O MERGE SORT DO VETOR 4 É", fim)
for i in range (100000):
for i in range(5):
vet5.append(i)
for i in range(5):
vet5.append(random.randrange(10))
inicio = time.time()
selection_sort(vet5)
print("O SELECTIONSORT REALIZOU ", cont_selection, " COMPARAÇÕES")
cont_selection = 0
fim = time.time() - inicio
print("TEMPO PARA O SELECTION SORT DO VETOR 5 É", fim)
inicio = time.time()
insertion_sort(vet5)
print("O INSERTIONSORT REALIZOU ", cont_insertion, " COMPARAÇÕES")
cont_insertion = 0
fim = time.time() - inicio
print("TEMPO PARA O INSERTION SORT DO VETOR 5 É", fim)
inicio = time.time()
shell_sort(vet5)
print("O SHELLSORT REALIZOU ", cont_shell, " COMPARAÇÕES")
cont_shell = 0
fim = time.time() - inicio
print("TEMPO PARA O SHELL SORT DO VETOR 5 É", fim)
inicio = time.time()
quick_sort(vet5, cont_quicksort)
print("O QUICKSORT REALIZOU ", cont_quicksort, " COMPARAÇÕES")
cont_quicksort = 0
fim = time.time() - inicio
print("TEMPO PARA O QUICK SORT DO VETOR 5 É", fim)
inicio = time.time()
heap_sort(vet5)
print("O HEAPSORT REALIZOU ", cont_heap, " COMPARAÇÕES")
cont_heap = 0
fim = time.time() - inicio
print("TEMPO PARA O HEAP SORT DO VETOR 5 É", fim)
inicio = time.time()
merge_sort(vet5)
print("O MERGESORT REALIZOU ", cont_merge, " COMPARAÇÕES")
cont_merge = 0
fim = time.time() - inicio
print("TEMPO PARA O MERGE SORT DO VETOR 5 É", fim)
for i in range (1000000):
for i in range(5):
vet6.append(i)
for i in range(5):
vet6.append(random.randrange(10))
inicio = time.time()
selection_sort(vet6)
print("O SELECTIONSORT REALIZOU ", cont_selection, " COMPARAÇÕES")
cont_selection = 0
fim = time.time() - inicio
print("TEMPO PARA O SELECTION SORT DO VETOR 6 É", fim)
inicio = time.time()
insertion_sort(vet6)
print("O INSERTIONSORT REALIZOU ", cont_insertion, " COMPARAÇÕES")
cont_insertion = 0
fim = time.time() - inicio
print("TEMPO PARA O INSERTION SORT DO VETOR 6 É", fim)
inicio = time.time()
shell_sort(vet6)
print("O SHELLSORT REALIZOU ", cont_shell, " COMPARAÇÕES")
cont_shell = 0
fim = time.time() - inicio
print("TEMPO PARA O SHELL SORT DO VETOR 6 É", fim)
inicio = time.time()
quick_sort(vet6, cont_quicksort)
print("O QUICKSORT REALIZOU ", cont_quicksort, " COMPARAÇÕES")
cont_quicksort = 0
fim = time.time() - inicio
print("TEMPO PARA O QUICK SORT DO VETOR 6 É", fim)
inicio = time.time()
heap_sort(vet6)
print("O HEAPSORT REALIZOU ", cont_heap, " COMPARAÇÕES")
cont_heap = 0
fim = time.time() - inicio
print("TEMPO PARA O HEAP SORT DO VETOR 6 É", fim)
inicio = time.time()
merge_sort(vet6)
print("O MERGESORT REALIZOU ", cont_merge, " COMPARAÇÕES")
cont_merge = 0
fim = time.time() - inicio
print("TEMPO PARA O MERGE SORT DO VETOR 6 É", fim) |
0bd28c58aec4f2d5ebb0428cb3da2929239206b7 | zhangxingxing12138/web-pycharm | /pycharm/改版.py | 737 | 3.90625 | 4 | from collections import Iterable
class MyList(object):
def __init__(self):
self.items = []
self.index = 0
def add(self, name):
self.items.append(name)
self.index = 0
def __iter__(self):#加这个方法变成了可迭代对象(iterable)
return self #返回一个迭代器(MyIterator(self))
def __next__(self):#有next方法的成为迭代器 for 循环取值调用next方法
if self.index < len(self.items):
item = self.items[self.index]
self.index += 1
return item
else:
raise StopIteration
mylist = MyList()
mylist.add('老王')
mylist.add('老张')
mylist.add('老宋')
for num in mylist:
print(num) |
2e3b067497ab8a8005abecbcea9606bb56d43493 | licebmi/extra-projects | /number-printer.py | 1,416 | 4.0625 | 4 | #!/usr/bin/env python3
import argparse
import random
def parse_arguments():
parser = argparse.ArgumentParser(description="Generate a range of random integers")
parser.add_argument(
"-o",
"--ordered",
action="store_true",
dest="ordered",
help="Returns an ordered range",
)
parser.add_argument(
"-s",
"--start",
action="store",
dest="start",
type=int,
default=1,
help="Specify the start of the range",
)
parser.add_argument(
"ammount",
action="store",
type=int,
default=10,
nargs="?",
help="Specify the ammount of digits to return",
)
args = parser.parse_args()
if args.ammount < 0:
parser.error(f"argument ammount: must be a positive integer: '{args.ammount}'")
return args
def main():
args = parse_arguments()
start = args.start
end = args.start + args.ammount
result = []
number_list = list(range(start, end))
if not args.ordered:
random.shuffle(number_list)
## Map might be used, as it's generally more efficient, although in this case, a for loop is clearer
## and we don't take advantage of many of the more interesting properties of the map function.
# list(map(print, number_list))
for n in number_list:
print(n)
if __name__ == "__main__":
main()
|
4280e622f18a3eac097f5773902f30ba2c8cb6d3 | uva-sp2021-cs5010-g6/finalproject | /project01/question3.py | 7,685 | 3.796875 | 4 | """
This module provides the functions and code in support of answering the
question "How do popular food categories fare with corn syrup?"
The `main()` function provides the pythonic driver, however this can
be run directly using python3 -m project01.question3 after the files
have been fetched from the USDA (see `project01.fetcher`).
"""
import sys
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn import linear_model as lm
from matplotlib import pyplot as plt
from typing import List
import project01.parser as food_parser
def establish_food_object(csv_file: str) -> food_parser.FoodBrandObject:
"""Creates our food object leveraging our general purpose parser.
Args:
csv_file (str): The path to the food brand CSV file.
Returns:
food_parser.FoodBrandObject: A general purpose brand object which
contains the parsed dataframe with corn syrup already added as
a new index.
"""
bfood = food_parser.FoodBrandObject(csv_file)
bfood.cleanup()
bfood.run_on_df(food_parser.insert_index, find="corn syrup")
bfood.run_on_df(food_parser.insert_index, find="sugar")
return bfood
def clamp(bfood: food_parser.BaseFood,
floor: int = 0,
ceiling: int = None,
col: str = "corn_syrup_idx") -> pd.DataFrame:
"""Clamping function used to filter the allowed indices of a column.
Args:
bfood (food_parser.BaseFood): The dataframe to operate on.
floor (int): The lowest allowed value of the column. Defaults to 0.
ceiling (int): The highest allowed value in the column.
Defaults to the maximum value in the column.
col (str): The column name to operate on. Defaults to corn_syrup_idx.
Returns:
pd.DataFrame: A new dataframe, where only the rows within the values
of floor and ceiling are included, and all others are dropped.
"""
return bfood.clamp(floor=floor, ceiling=ceiling, col=col)
def find_top_five_food_categories(bfood: food_parser.BaseFood,
col: str = "branded_food_category") -> pd.DataFrame:
"""Establishes the dataset for top5 food categories
Args:
bfood (food_parser.BaseFood): The dataframe to seek against.
col (str): The column to find the top occurrences of.
Returns:
pd.DataFrame: A filtered dataframe containing only the foods
in the top five largest categories.
"""
return bfood.find_top(col=col, limit=5)
def metrics_on_food_categories(df: pd.DataFrame,
col: str = "branded_food_category") -> List[pd.Series]:
"""Produces simple analysis on a specific column in a dataframe
Args:
df (pd.DataFrame): The dataframe to operate on.
col (str): The column to perform analysis on. Default: branded_food_category.
Returns:
list[pd.Series]: The output of describe() and value_counts() on the dataframe's series.
"""
return [df[col].describe(), df[col].value_counts()]
def plot_foodcat(df: pd.DataFrame, col="corn_syrup_idx", out: str = "plot.png"):
"""Creates a violin plot of the distribution of data.
Args:
df (pd.DataFrame): The dataframe to use when plotting.
col (str): The column to use for the violinplot magnitude.
out (str): The path to save the plotting graphic to.
Returns:
None: The graphic is saved to `out` as a side effect.
"""
# Note, we need to establish the figure to ensure sns doesn't
# try to add to its prior plot.
fig, ax1 = plt.subplots(figsize=(12, 6))
sns.violinplot(x=col,
y="branded_food_category",
orient="h",
bw=0.2,
cut=0,
scale="width",
data=df, ax=ax1)
ax1.set(xlabel="Rank",
ylabel="Food Category")
# Calling plt.tight_layout() ensures our labels fit in our
# plotting space.
plt.tight_layout()
fig.savefig(out)
def density(bfood: food_parser.BaseFood, out: str = ""):
newdf = pd.DataFrame({"brand": bfood.df["branded_food_category"],
"sugar": bfood.df["sugar_idx"],
"corn_syrup": bfood.df["corn_syrup_idx"]})
# Insert NaNs for no matches to ensure our counts aren't skewed.
newdf.loc[newdf["sugar"] == -1, "sugar"] = np.NaN
newdf.loc[newdf["corn_syrup"] == -1, "corn_syrup"] = np.NaN
fig, ax1 = plt.subplots(figsize=(12, 6))
sns.histplot(element="step", bins=30, ax=ax1, data=newdf)
ax1.set(xlabel="Index",
ylabel="Count")
# Calling plt.tight_layout() ensures our labels fit in our
# plotting space.
plt.tight_layout()
fig.savefig(out)
def correlation(bfood: food_parser.BaseFood, out: str = "q3-correlation.png"):
newdf = pd.DataFrame({"category": bfood.df["branded_food_category"],
"sugar": bfood.df["sugar_idx"],
"corn_syrup": bfood.df["corn_syrup_idx"]})
# Insert NaNs for no matches to ensure our counts aren't skewed.
newdf.loc[newdf["sugar"] == -1, "sugar"] = np.NaN
newdf.loc[newdf["corn_syrup"] == -1, "corn_syrup"] = np.NaN
myfig = sns.pairplot(data=newdf, hue="category", markers="|", kind="reg")
myfig.savefig(out)
def lin_model(df):
newdf = pd.DataFrame({"category": df["branded_food_category"],
"sugar": df["sugar_idx"],
"corn_syrup": df["corn_syrup_idx"]})
# Insert NaNs for no matches to ensure our counts aren't skewed.
newdf.loc[newdf["sugar"] == -1, "sugar"] = np.NaN
newdf.loc[newdf["corn_syrup"] == -1, "corn_syrup"] = np.NaN
reg = lm.LinearRegression()
X = newdf["corn_syrup"].values.reshape(-1, 1)
y = newdf["sugar"].values.reshape(-1, 1)
reg.fit(X, y)
print(f"y = {reg.intercept_} + {reg.coef_}x")
yhat = reg.predict(X)
SSres = sum((y-yhat)**2)
SSt = sum((y-np.mean(y))**2)
rsq = 1 - (float(SSres))/SSt
print(f"R2 = {rsq}")
def main(csv_file: str):
"""Pythonic driver for our third question / query
This method:
1. Establishes our food object of interest
2. Outputs trivial summary statistics on a column
3. Establishes a subset to the top five food categories
4. Outputs metrics on the subset.
5. Establishes another subset from the dataframe by limiting
the data to only values that have corn syrup
6. Produces a violin plot to show our data density across the
top five groups. We see a large left tail.
7. After reviewing the data, the corn_syrup_idx ceiling appears
to be near ten, so we further clamp the data down to center
our distribution.
Args:
csv_file (str): The path to the branded_foods.csv file.
Returns:
None: Output to the terminal statistics and various
plots are written out to file.
"""
bfood = establish_food_object(csv_file)
df = find_top_five_food_categories(bfood)
print(metrics_on_food_categories(bfood.df))
# Very wide range, adjusted to 10 as this seems to match most index returns.
df_cornsyrup = clamp(bfood)
plot_foodcat(df_cornsyrup, out="q3-cornsyrup-cat.png")
df_sugar = clamp(bfood, col="sugar_idx")
plot_foodcat(df_sugar, out="q3-sugar.png")
density(bfood, out="q3-density.png")
correlation(bfood, out="q3-correlation.png")
lin_model(bfood.df)
if __name__ == "__main__":
brand_csv = sys.argv[1] if len(sys.argv) > 2 else "./dataset/FoodData_Central_csv_2020-10-30/branded_food.csv"
main(csv_file=brand_csv)
|
4deedfe0dea559088f4d2652dfe71479fce81762 | saman-rahbar/in_depth_programming_definitions | /errorhandling.py | 965 | 4.15625 | 4 | # error handling is really important in coding.
# we have syntax error and exceptions
# syntax error happens due to the typos, etc. and usually programming languages can help alot with those
# exceptions, however, is harder to figure and more fatal. So in order to have a robust code you should
# handle the errors and take care of the exceptions, and raise exceptions when necessary.
""" Circuit failure example """
class Circuit:
def __init__(self, max_amp):
self.capacity = max_amp # max capacity in amps
self.load = 0 # current load
def connect(self, amps):
"""
function to check the connectivity
:param amps: int
:return: None
"""
if self.capacity += amps > max_amp:
raise exceptions("Exceeding max amps!")
elif self.capacity += amps < 0:
raise exceptions("Capacity can't be negative")
else:
self.capacity += amps
|
1e922122a376fe94be19ce450289691680dfc55a | MuraliSarvepalli/Squeezing-reptile | /my_func_ex3.py | 176 | 3.984375 | 4 | def myfunc3(a,b):
if (a+b)==20 or a==20 or b==20:
return True
else:
return False
a=input('Enter a')
b=input('Enter b')
r=myfunc3(a,b)
print(r)
|
dce7935bd17f8f27baf4cda9a2eb2f0db19c00b7 | MuraliSarvepalli/Squeezing-reptile | /my_func_ex_7.py | 370 | 3.9375 | 4 | #Given a list of ints, return True if the array contains a 3 next to a 3 somewhere
def three_conseq(ls):
count=0
while count<len(ls):
if ls[count]==3 and ls[count+1]==3:
return True
count+=1
ls=[]
for i in range(0,5):
num=int(input('Enter the values'))
ls.append(num)
print(ls)
r=three_conseq(ls)
print(r)
|
55f4fc114333b02e47285ac8d06aac4889ae403a | MuraliSarvepalli/Squeezing-reptile | /try_except_fianlly.py | 245 | 3.84375 | 4 | #try except finally
def ask():
while True:
try:
n=int(input("Enter the number"))
except:
print("Whoops! Thats not a number")
else:
break
return n**2
print(ask())
|
d5d16ef90534d51086eb9966710e794b39265ef7 | MuraliSarvepalli/Squeezing-reptile | /my_func_ex_19.py | 171 | 4.15625 | 4 | #palindrome
def palindrome(st):
if st[::]==st[::-1]:
return True
else:
return False
st=input('Enter the string')
print(palindrome(st))
|
a21b9e2173759cf993bcc77f445b4c2fedc10348 | MuraliSarvepalli/Squeezing-reptile | /my_func_ex_17.py | 225 | 4.03125 | 4 | #Write a Python function that takes a list and returns a new list with unique elements of the first list.
def unique(mylist):
un_list=set(mylist)
return un_list
print(unique([1,1,1,1,3,3,5,4,9,5,6,7,8,7,2]))
|
f545e77bc882b7dacb6ba522f354531b8a3206ad | zdrasteenastya/utils | /patterns/strategy.py | 1,443 | 3.71875 | 4 | import types
# Option 1
class Strategy:
def __init__(self, func=None):
self.name = 'Patter Strategy 1'
if func is not None:
self.execute = types.MethodType(func, self)
def execute(self):
print(self.name)
def execute_replacement1(self):
print(self.name + 'replace with 1')
def execute_replacement2(self):
print(self.name + 'replace with 2')
# Option 2
from abc import abstractmethod
class People(object):
# Strategy
tool = None
def __init__(self, name):
self.name = name
def setTool(self, tool):
self.tool = tool
def write(self, text):
self.tool.write(self.name, text)
class Tools(object):
@abstractmethod
def write(self, *args):
pass
class Pen(Tools):
def write(self, *args):
print '{} (pen) {}'.format(*args)
class Brush(Tools):
def write(self, *args):
print '{} (brush) {}'.format(*args)
class Student(People):
tool = Pen()
class Painter(People):
tool = Brush()
if __name__ == '__main__':
strat0 = Strategy()
strat1 = Strategy(execute_replacement1)
strat1.name = 'Patter Strategy 2'
strat2 = Strategy(execute_replacement2)
strat2.name = 'Patter Strategy 3'
strat0.execute()
strat1.execute()
strat2.execute()
nik = Student('Nik')
nik.write('write about pattern')
sasha = Painter('sasha')
sasha.write('draw something')
|
483f62eacc57d12e1542ef8bf8265896ef921323 | zdrasteenastya/utils | /requests_to_db.py | 1,821 | 3.6875 | 4 | # coding: utf-8
import sqlite3
import psycopg2
conn = sqlite3.connect('Chinook_Sqlite.sqlite')
cursor = conn.cursor()
# Read
cursor.execute('SELECT Name FROM Artist ORDER BY Name LIMIT 3')
results = cursor.fetchall()
results2 = cursor.fetchall()
print results # [(u'A Cor Do Som',), (u'AC/DC',), (u'Aaron Copland & London Symphony Orchestra',)]
print results2 # []
# Write
cursor.execute('INSERT INTO Artist VALUES (Null, "A nasty!")')
conn.commit() # in case of changin DB
cursor.execute('SELECT Name FROM Artist ORDER BY Name LIMIT 3')
results = cursor.fetchall()
print results
# Placeholder
# C подставновкой по порядку на места знаков вопросов:
print cursor.execute("SELECT Name FROM Artist ORDER BY Name LIMIT ?", '2').fetchall()
# И с использованием именнованных замен:
print cursor.execute("SELECT Name from Artist ORDER BY Name LIMIT :limit", {"limit": 3}).fetchall()
print cursor.execute("SELECT Name FROM ? ORDER BY Name LIMIT 2", 'Artist').fetchall() # Error
# Many and Iterator
new_artists = [
('A aa',),
('A a2',),
('A a3',)
]
cursor.executemany('INSERT INTO Artist VALUES (Null, ?);', new_artists)
cursor.execute('SELECT Name FROM Artist ORDER BY Name LIMIT 3')
print cursor.fetchone()
print cursor.fetchone()
print cursor.fetchone()
for row in cursor.execute('SELECT Name from Artist ORDER BY Name LIMIT 3'):
print row
conn.close()
connect = psycopg2.connect(database='test_base', user='test_user', host='localhost', password='test_password')
cursor = connect.cursor()
cursor.execute("CREATE TABLE tbl(id INT, data JSON);")
cursor.execute('INSERT INTO tbl VALUES (1, \'{ "name":"Tester" }\');')
connect.commit()
cursor.execute("SELECT * FROM tbl;")
for row in cursor:
print(row)
connect.close()
|
21fb03593c46ab3dee1bbfc36bf93698a0d87286 | returnpointer/trainsim | /user_interface/menu_sim.py | 1,826 | 3.5 | 4 | """
Simulation Menu
"""
from PyInquirer import prompt
from user_interface.menu_questions import style, sim_questions1, sim_questions2
from sim_engine.simulation import sim_run
def sim_menu(railway, graph):
"""Simulation Menu"""
if not railway['stations'] or \
not railway['tracks'] or \
not railway['trains']:
print("Sorry! Cannot run simulation without building "
"railway network of stations/tracks/trains first.")
return
while 1:
trains = {}
answers = prompt(sim_questions1, style=style)
if answers['trains'] == 'Main Menu':
# Quit Simulation
break
elif answers['trains'] == 'All':
# print("Sorry! Simulation of 'All' trains currently not supported, "
# "please select a single train.")
for key in railway['trains'].keys():
base_station = railway['trains'][key]
# arbitrary choice of last
# neighbor as destination station
neighbor_stations = list(graph.get_vertex(base_station).get_connections())
neighbor_stations.sort()
# print(neighbor_stations)
dest_station = neighbor_stations[-1]
trains[key] = [base_station, dest_station]
else: # User selected train
train = answers['trains']
base_station = railway['trains'][train]
answers = prompt(sim_questions2, style=style)
while answers['destination'] == base_station:
print("Sorry! Can't start and end at the same station.")
answers = prompt(sim_questions2, style=style)
trains[train] = [base_station, answers['destination']]
sim_run(graph, trains)
return
|
6c0b90765de1de097e3da9a5434649929ee01b7a | newpheeraphat/banana | /Algorithms/String/T_ReverseStringInList.py | 147 | 3.609375 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
s3 = s.split()
res = [i[::-1] for i in s3]
return " ".join(res)
|
a9a4f9e454711353a969c827b8c3a6226ced3bf9 | newpheeraphat/banana | /Algorithms/List/T_ChangeValuesInList.py | 340 | 3.546875 | 4 | def check_score(s):
import itertools
# Transpose 2D to 1D
res = list(itertools.chain.from_iterable(s))
for key, i in enumerate(res):
if i == '#':
res[key] = 5
elif i == '!!!':
res[key] = -5
elif i == '!!':
res[key] = -3
elif i == '!':
res[key] = -1
elif i == 'O':
res[key] = 3
elif i == 'X':
res[key] = 1
|
aee829e9b7b2796c39884a76f4dc1a8fe0b6aca7 | newpheeraphat/banana | /Algorithms/Integer/Prime/10001st_prime.py | 311 | 4 | 4 | def nth_prime(nums):
counter =2
for i in range(3, nums**2, 2):
j = 1
while j*j < i:
j += 2
if i % j == 0:
break
else:
counter += 1
if counter == nums:
return i
int1 = int(input())
print(nth_prime(int1))
|
a61fb10a9c8b3dc6244a01c7296a2de90fde246a | newpheeraphat/banana | /Algorithms/Map-FIlter/T_Zip.py | 307 | 3.640625 | 4 | class Solution:
def convert_cartesian(self, x : list, y : list) -> list:
res = [[i, j] for i, j in zip(x, y)]
return res
if __name__ == '__main__':
print(Solution().convert_cartesian([1, 5, 3, 3, 4], [5, 8, 9, 1, 0]) )
print(Solution().convert_cartesian([9, 8, 3], [1, 1, 1]) )
|
41ff3ef5de93046c9836bfb2ea81435539244849 | newpheeraphat/banana | /Algorithms/Dictionary/T_FindMax.py | 308 | 3.84375 | 4 | country = ['Brazil', 'China', 'Germany', 'United States']
dict1 = {}
my_list = []
_max = 0
for i in country:
int1 = int(input())
my_list.append(int1)
dict1[i] = int1
if _max < int1:
_max = int1
print(dict1)
for key in dict1:
if dict1[key] == _max:
print(key, dict1[key])
|
339523698a51d97b56c9419d2f2a7ac90231edfb | bajca/pyladies | /Import_piskvorky/piskvorky.py | 1,392 | 3.71875 | 4 | def tah(herni_pole, cislo_policka, symbol):
return herni_pole[:cislo_policka] + symbol + herni_pole[cislo_policka + 1:]
def tah_pocitace(herni_pole):
while True:
cislo_policka = random.randrange(len(herni_pole))
if herni_pole[cislo_policka] == "-":
return tah(herni_pole, cislo_policka, "o")
def vyhodnot(herni_pole):
if "xxx" in herni_pole:
return "x"
elif "ooo" in herni_pole:
return "o"
elif "-" not in herni_pole:
return "!"
else:
return "-"
def piskvorky1d():
herni_pole = "-" * 20
na_tahu = "x"
while True:
if na_tahu == "x":
herni_pole = tah_hrace(herni_pole)
na_tahu = "o"
elif na_tahu == "o":
herni_pole = tah_pocitace(herni_pole)
na_tahu = "x"
vysledek = vyhodnot(herni_pole)
print(herni_pole)
if vysledek != "-":
if vysledek == "!":
print("Remiza! {}".format(herni_pole))
elif vysledek == "x":
print("Vyhravas nad pocitacem! {}".format(herni_pole))
elif vysledek == "o":
print("Bohuzel, pocitac vyhral. {}".format(herni_pole))
else:
raise ValueError("Nepripustny vysledek hry '{}'".format(vysledek))
break
piskvorky1d() |
fa1354ec7e81123f76e33054103be26e6d644e6d | bormanjo/Basic-Scrabble-Word-Aid | /Main.py | 3,199 | 3.71875 | 4 |
scrabbleScores = [ ["a", 1], ["b", 3], ["c", 3], ["d", 2], ["e", 1], ["f", 4], ["g", 2], ["h", 4], ["i", 1], ["j", 8], ["k", 5], ["l", 1], ["m", 3], ["n", 1], ["o", 1], ["p", 3], ["q", 10], ["r", 1], ["s", 1], ["t", 1], ["u", 1], ["v", 4], ["w", 4], ["x", 8], ["y", 4], ["z", 10] ]
def letterScore(letter, scorelist):
'''returns the associated score for the given letter'''
if letter == scorelist[0][0]:
return scorelist[0][1]
else:
return letterScore(letter, scorelist[1:])
def wordScore(word, scorelist):
'''returns the sum of each letters scores in the word'''
if word == [] or word == '':
return 0
return letterScore(word[0], scorelist) + wordScore(word[1:], scorelist)
def isWord(word, rack):
'''returns a nuerical value for the number of characters in word that exist in rack'''
if word == [] or word == '':
return False
elif word[0] in rack:
return True + isWord(word[1:], rack)
else:
return isWord(word[1:], rack)
def dictFilter(s, rack):
'''filters through the dictionary (s) and returns words whose characters (excluding doubles) exist in rack'''
if s == [] or s == '':
return []
elif isWord(s[0], rack) == len(s[0]):
return [s[0]] + dictFilter(s[1:], rack)
else:
return dictFilter(s[1:], rack)
def extraFilter(rack, words):
'''determines if a possible word can be formed by letters in rack'''
def remove(rack, letter):
'''returns rack with one character 'letter' removed if it exists in rack'''
if rack == []:
return []
elif rack[0] == letter:
return rack[1:]
else:
return [rack[0]] + remove(rack[1:], letter)
def checkWord(rack, word):
'''returns True or False if word can be made with letters in rack'''
if word == '': #if the word is empty, that means that all letters have been subtracted
return True #from the word and rack, thus word is in rack
elif word[0] in rack:
return checkWord(remove(rack, word[0]), word[1:])
else:
return False
return filter(lambda x: checkWord(rack, x), words)
def scoreList(rack):
'''returns the highest scoring word of available list of letters in Rack as recognized in the given Dictionary'''
possWords = extraFilter(rack, dictFilter(Dictionary, rack))
possScores = map(lambda x: wordScore(x, scrabbleScores), possWords)
def makeScoreList(words, scores):
'''pairs possible words and scores into a list'''
if words == [] or scores == []:
return []
return [[words[0], scores[0]]] + makeScoreList(words[1:], scores[1:])
return makeScoreList(possWords, possScores)
def bestWord(rack):
'''returns a list of the highest scoring word'''
def compareScores(x, y):
if x[1] >= y[1]: #NOTE: if x and y are equal in score, returns x by default
return x
elif x[1] < y[1]:
return y
return reduce(compareScores, scoreList(rack))
|
0b2de788f6be653826240f287578a86d2070893d | Donovan1905/Ants-colony-search-algorithm | /ants.py | 3,237 | 3.78125 | 4 | from AntsAlgo.const import ALPHA, BETA, RHO, CUL
import random
class Ant: # the ant class
def __init__(self): # initialize visited and to visit cities lists as well as the time
self.visited = list()
self.toVisit = list()
self.time = 0
"""[summary]
Function to choose the next city by using pheromones and distances (formulas)
"""
def choose(self, graph, phero, param):
remaining_total = {} # list of importance of the city regarding the distance and the pheromones
for city in self.toVisit:
if graph[self.visited[len(self.visited)-1]][city][(self.time%1440)//60 if param["has_traffic"] else 0] != 0: # check if the ant can go to this city
remaining_total[city] = 0.00001 + (pow(phero[self.visited[len(self.visited)-1]][city], ALPHA) * pow(graph[self.visited[len(self.visited)-1]][city][(self.time%1440)//60 if param["has_traffic"] else 0], BETA))
key_list = list(remaining_total.keys())
val_list = list(remaining_total.values())
chossen_city = random.choices(key_list, weights= val_list, k=1) # randomly weighted choice of the next city
self.visit(chossen_city[0], graph, param) # go to the city
return
"""[summary]
Function to check if the ants arrived on time, and then calculate the waiting time
"""
def deliver(self, tw):
waiting_time = 0
city = self.visited[len(self.visited)-1]
if tw[city]["start_time"] >= self.time % 1440 or tw[city]["end_time"] <= self.time: # if late or early
waiting_time = (tw[city]["start_time"] - self.time) % 1440
elif tw[city]["end_time"] >= self.time % 1440 and tw[city]["start_time"] <= self.time % 1440: # on time
waiting_time = 0
self.time += waiting_time
"""[summary]
Function to actualize the two list and update the current time
"""
def visit(self, choosed, graph, param):
self.time += graph[self.visited[len(self.visited)-1]][choosed][(self.time%1440)//60 if param["has_traffic"] else 0] # add the time
last = None
if self.toVisit == [0]:
last = True
self.visited.append(choosed)
self.toVisit.remove(choosed)
if self.toVisit == [] and not(last):
self.toVisit.append(0)
"""[summary]
Loop to travel all the cities of the list
"""
def travel(self, graph, phero, tw, param):
self.time = 0
while self.toVisit:
self.choose(graph, phero, param)
self.deliver(tw)
"""[summary]
Function calculate the delta pheromones
"""
def analyzeTravel(self, graph):
deltasPheromones = list()
for i in range(0, len(self.visited)-1):
deltasPheromones.append(CUL/self.time) # formula
return deltasPheromones
"""[summary]
Put the pheromones in the pheromones graph
"""
def spittingPheromone(self, phero, graph, param):
pheromone_path = self.analyzeTravel(graph) #Spit new pheromones
for i in range(0, len(self.visited)-1):
phero[self.visited[i]][self.visited[i+1]] += pheromone_path[i]
return phero |
ef9848abae877105114ff60a86f33f40a7fc5a6a | Scottycags/Scott-Cagnard---Assignment-2 | /Scott.Cagnard---Assignment.2.py | 4,508 | 4.3125 | 4 | #Scott Cagnard
#Assignment 2
#2.1 practice
str = "hello, i am a string" #Create any certain string
x = str.find("am") #Set x to find the position of "am" in str
print(x) #Print the location of "am"
print(str.replace("i", "me")) #Replace "i" with "me" in the string and print the new string
print("\n\n") # print a couple of blank lines
input("Press and key to continute")
print("\n\n") # print a couple of blank lines
#2.2 practice
s = "a string with words"
n = len(s) #This tells us the length of the string
print(s[0], s[1], s[2], s[n - 1]) #Print the characters of the string under a certain location
a = s[4:8]
b = s[:5] #Locate the chain of characters under the specific location
c = s[5:]
print("t --> |" + a + "|")
print("t --> |" + b + "|") #Print the characters that were extracted
print("v --> |" + c + "|")
print("\n\n") # print a couple of blank lines
input("Press and key to continute")
print("\n\n") # print a couple of blank lines
#2.3
expr = "12+27" #define the expression as a string
op_pos = expr.find("+") #locate the plus sign in the expression
num1 = int(expr[:op_pos]) #extract the first number of the expression
num2 = int(expr[op_pos+1:]) #extract the second number of the expression
print("12 + 37 = ", num1 + num2) #calculate and print the sum of num1 and num2
x = input("Please enter an expression in the form num1 + num2") #Acquire an expression of addition
y = x.find("+") #Locate the plus sign
if x.find("+") == -1:
pass #Do nothing if no plus sign found
n1= int(x[:y]) #Extract number before plus sign
n2 = int(x[y + 1:]) #Extract number after plus sign
print(n1, "+", n2, "=", n1 + n2) #Calculate sum of two numbers and print finished expression with solution
print("\n\n") # print a couple of blank lines
input("Press and key to continute")
print("\n\n") # print a couple of blank lines
#2.4
b = input("Please enter an expression calculating two numbers") #Acquire a numeric expression from user
while b != "end": #Create a while loop with the condition that b is not equal to "end"
#This while loop will keep asking for expressions to calculate until the user enters "end", which will end the calculator
if b.find("+") == -1: #If no plus sign found, do nothing
pass
else:
y = b.find("+") #If plus sign found, extract number before and after plus sign
n1= int(b[:y])
n2 = int(b[y + 1:])
print(n1, "+", n2, "=", n1 + n2) #Calculate and print full expression
b = input("Please enter an expression calculating two numbers") #Ask for new expression
if b.find("-") == -1:
pass #If no minus sign found, do nothing
else:
y = b.find("-") #If minus sign found, extract number before and after minus sign
n1= int(b[:y])
n2 = int(b[y + 1:])
print(n1, "-", n2, "=", n1 - n2) #Calculate and print full expression
b = input("Please enter an expression calculating two numbers") #Ask for new expression to calculate
if b.find("/") == -1: #If no division sign found, do nothing
pass
else:
y = b.find("/")
n1= int(b[:y]) #If division sign found, extract the number before and after division sign
n2 = int(b[y + 1:])
print(n1, "/", n2, "=", n1 / n2) #Calculate and print full expression
b = input("Please enter an expression calculating two numbers") #Ask for a new expression to calculate
if b.find("*") == -1:
pass #If multiplication sign not found, do nothing
else:
y = b.find("*")
n1= int(b[:y]) #If multiplication sign found, extract the number before and after the multiplication sign
n2 = int(b[y + 1:])
print(n1, "*", n2, "=", n1 * n2) #Calculate and print full expression
b = input("Please enter an expression calculating two numbers") #Ask for new expression to calculate
if b.find("+") == -1 and b.find("-") == -1 and b.find("/") == -1 and b.find("*") == -1:
print("invalid expresssion") #If no arithmetic sign found, print "invalid expression"
b = input("Please enter an expression calculating two numbers") #Ask for new expression to calculate
|
218cd58e485e9a4dee468613d738c5c84613ffc1 | gopiselvi30/Python | /to find common elements in two elements.py | 315 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 29 22:46:58 2016
@author: gopi-selvi
"""
list1= range(1,100)
list2= range(50,150)
list3=[]
for a in list1:
if a in list1:
list3.append(a)
for b in list2:
if b not in list1:
list3.append(b)
print(list3)
|
227510fcca18ea1c2a74af631cb1ba532ea3522b | oamole/Projects | /Iocane.py | 9,848 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Iocane Powder
#
# ## Overview
#
# > Man in Black: All right. Where is the poison? The battle of wits has begun. It ends when you decide and we both drink, and find out who is right... and who is dead.
#
# The line above is from the perennial favorite 1980s movie adaptation of William Goldman's *The Princess Bride*, wherein a mysterious hero sits down to a battle of wits with a villainous Sicilian kidnapper. The setup: two cups positioned between the two, one of which (purportedly) contains a colorless, odorless, lethal poison (viz., iocane powder). After a guess is made as to which cup contains the poison, both drink, and the winner is the one left standing.
#
# For this machine problem you will write a program that simulates multiple rounds of this battle of wits, allowing the player to repeatedly guess which cup is poisoned. The computer will "place" the poison before the player guesses, and
# will reveal who is right... and who is dead, afterwards.
#
# At the outset, the computer will always place the poison in cup 2 before letting the player guess, but after enough guesses have been entered the computer will start to place the poison based on the pattern of previous guesses so as to outsmart the player.
#
# Here's a sample game session (note how the silly player keeps alternating guesses, and that the computer catches on to this fact after a while):
#
# Where is the iocane powder: my cup (1) or yours (2)? 1
# Wrong! Ha! Never bet against a Sicilian!
#
# You died 1 times, and I drank the poison 0 times
#
# Where is the iocane powder: my cup (1) or yours (2)? 2
# Good guess! Ack! I drank the poison!
#
# You died 1 times, and I drank the poison 1 times
#
# Where is the iocane powder: my cup (1) or yours (2)? 1
# Wrong! Ha! Never bet against a Sicilian!
#
# You died 2 times, and I drank the poison 1 times
#
# Where is the iocane powder: my cup (1) or yours (2)? 2
# Good guess! Ack! I drank the poison!
#
# You died 2 times, and I drank the poison 2 times
#
# Where is the iocane powder: my cup (1) or yours (2)? 1
# Wrong! Ha! Never bet against a Sicilian!
#
# You died 3 times, and I drank the poison 2 times
#
# Where is the iocane powder: my cup (1) or yours (2)? 2
# Wrong! Ha! Never bet against a Sicilian!
#
# You died 4 times, and I drank the poison 2 times
#
# Where is the iocane powder: my cup (1) or yours (2)? 1
# Wrong! Ha! Never bet against a Sicilian!
#
# You died 5 times, and I drank the poison 2 times
#
# Where is the iocane powder: my cup (1) or yours (2)? 2
# Wrong! Ha! Never bet against a Sicilian!
#
# You died 6 times, and I drank the poison 2 times
#
# Where is the iocane powder: my cup (1) or yours (2)? 1
# Wrong! Ha! Never bet against a Sicilian!
#
# You died 7 times, and I drank the poison 2 times
#
#
# ## Implementation
#
# To keep track of the pattern of previous guesses, you will use a dictionary that maps a pattern (of fixed length) to a list of counts for the subsequent guess.
#
# For instance, imagine that the computer observes the player continuing to alternate guesses across ten separate attempts, like so: '1', '2', '1', '2', '1', '2', '1', '2', '1', '2'. If we are using a pattern detection length of three, then after the fourth guess we can create an entry in our dictionary that maps the key '121' to the list [0, 1], where the second value (1) in the list indicates that the player guessed '2' following the sequence '1', '2', '1'. After the fifth guess, we create the entry '212' → [1, 0], and after the sixth guess we update the value for '121' to [0, 2] (since the user guesses '2' again, after the sequence '1', '2', '1').
#
# Once the player enters a series of guesses that matches a previously seen pattern, the computer should place the poison in the cup that the player is *least likely to guess next*. When the player enters the next guess, the dictionary should be updated to reflect the actual guess.
#
# This means that if the computer has yet to see a given pattern of guesses, or when the counts are tied, it will have to place the poison "blindly" --- your implementation should simply place the poison furthest away from itself (cup 2).
#
# ### `record_guess`
#
# The first function you are to complete is `record_guess`. It will take the following arguments:
#
# - a dictionary to update (possibly containing previously recorded pattern → list mappings)
# - a pattern string
# - a guess -- which is either '1' or '2'.
#
# If necessary, the function will create a new entry for the pattern (if one doesn't already exist), then record the updated count for the guess. Since the dictionary is updated in place (i.e., mutated), the function will not return anything.
#
# Complete the function below, checking your implementation with the test cases that follow when you're ready. Note that in the future, the bulk of the description for functions we ask you to implement will simply be placed in the functions' docstrings, as below.
#
# *Hints: the [`int`](https://docs.python.org/3/library/functions.html#int) function can be used to convert strings to integers, and you might find the dictionary's [`setdefault`](https://docs.python.org/3/library/stdtypes.html?highlight=setdefault#dict.setdefault) method useful.*
# In[ ]:
def record_guess(pattern_dict, pattern, guess):
if pattern in pattern_dict:
if int(guess) ==1 :
pattern_dict[pattern][0] += 1
else:
pattern_dict[pattern][1] += 1
else:
pattern_dict[pattern] = [0,0]
if int(guess) ==1:
pattern_dict[pattern][0] += 1
else:
pattern_dict[pattern][1] += 1
# In[ ]:
# (5 points)
from unittest import TestCase
tc = TestCase()
d = {}
record_guess(d, '121', '1')
tc.assertDictEqual(d, {'121': [1, 0]})
record_guess(d, '222', '2')
record_guess(d, '121', '1')
tc.assertDictEqual(d, {'121': [2, 0], '222': [0, 1]})
record_guess(d, '122', '2')
record_guess(d, '121', '2')
record_guess(d, '222', '2')
tc.assertDictEqual(d, {'121': [2, 1], '122': [0, 1], '222': [0, 2]})
# ### `next_placement`
#
# The next function you'll write will take a dictionary of pattern → counts mappings and a string representing the pattern of most recent guesses, and return the next best location (either '1' or '2') for the poison (i.e., to try and outwit the player). If the pattern hasn't been seen previously or the counts are tied, the function should return '2'.
# In[ ]:
def next_placement(pattern_dict, pattern):
if pattern in pattern_dict:
if pattern_dict[pattern][0]<pattern_dict[pattern][1]:
return '1'
else:
return '2'
else:
return '2'
# In[ ]:
# (5 points)
from unittest import TestCase
tc = TestCase()
tc.assertEqual(next_placement({}, '121'), '2')
tc.assertEqual(next_placement({'121': [2, 0]}, '121'), '2')
tc.assertEqual(next_placement({'121': [2, 5]}, '121'), '1')
tc.assertEqual(next_placement({'121': [2, 5]}, '212'), '2')
tc.assertEqual(next_placement({'121': [5, 5]}, '121'), '2')
tc.assertEqual(next_placement({'121': [15, 5]}, '121'), '2')
tc.assertEqual(next_placement({'121': [2, 5],
'212': [1, 1]}, '212'), '2')
tc.assertEqual(next_placement({'121': [2, 5],
'212': [1, 3]}, '212'), '1')
# ### `play_interactive`
#
# Now for the fun bit. The function `play_interactive` will take just one argument --- the length of patterns to use as keys in the dictionary --- and will start an interactive game session, reading either '1' or '2' from the player as guesses, using the functions you wrote above and producing output as shown in the sample game session at the beginning of this writeup. If the player types in any other input (besides '1' or '2'), the game should terminate.
#
# *Hint: the [`input`](https://docs.python.org/3/library/functions.html#input) function can be used to read input from the user as a string.*
# In[ ]:
def play_interactive(pattern_length=4):
# YOUR CODE HERE
raise NotImplementedError()
# ### `play_batch`
#
# Finally, so that we can check your implementation against a lengthier sequence of guesses without having to play an interactive session, implement the `play_batch` function, which will take the `pattern_length` argument as your `play_interactive` function did, but will also take a sequence of guesses. The function will return the total numbers of wins and losses, as determined by the same algorithm as before.
# In[ ]:
def play_batch(guesses, pattern_length=4):
str = ''
dict = {}
c = [0,0]
for guess in guesses:
if guess != "1" and guess != "2":
break
pred = next_placement(dict,str)
if guess == pred:
c[0] += 1
elif guess != pred:
c[1] += 1
if len(str) == pattern_length:
record_guess(dict,str,guess)
str = str[1:]
str += guess
return tuple(count)
# In[ ]:
# (10 points)
from unittest import TestCase
tc = TestCase()
tc.assertEqual(play_batch(['1', '1', '1', '1', '1', '1'], 3), (0, 6))
tc.assertEqual(play_batch(['1', '2', '1', '2', '1', '2'], 3), (2, 4))
tc.assertEqual(play_batch(['1', '2', '1', '2', '1', '2'], 4), (3, 3))
tc.assertEqual(play_batch(['1', '2'] * 100, 5), (3, 197))
tc.assertEqual(play_batch(['1', '1', '2', '1', '2', '1'] * 100, 2), (398, 202))
tc.assertEqual(play_batch(['1', '1', '2', '1', '2', '1'] * 100, 3), (201, 399))
tc.assertEqual(play_batch(['1', '1', '2', '1', '2', '1'] * 100, 5), (4, 596))
import random
random.seed(0, version=2)
tc.assertEqual(play_batch((random.choice(['1', '2']) for _ in range(10000)), 4), (5047, 4953))
# In[ ]:
|
b595630701a103250cb67649b0182040c982d1cf | Prink0054/Assignment-Python | /practice/practice.py | 708 | 4.03125 | 4 | """
#Question-1
a = int(input("Enter year to check it is leap year or not"))
if((a%4) == 0):
{
print("Yes it is leap year")
}
else:
{
print("no it is not a leap year")
}
"""
"""
#Question-2
a = int(input("Enter Length of box"))
b = int(input("Enter Width of box"))
if(a == b):
print("Box is square")
else:
print("Box is Rectagle")
"""
"""
#Question-3
a = int(input("Enter age of First Person"))
b = int(input("Enter age of Seconed Person"))
c = int(input("Enter age of third Person"))
if (a>b):
if(a>c):
print("a is greater than b and c")
elif(b>a):
if(b>c):
print("B is greater than a and c")
else:
print("c is greater")
""" |
a202ac88914984267b1065b58c388b2a69e4af2e | Prink0054/Assignment-Python | /Assignment11/Assignment11.py | 1,346 | 3.96875 | 4 |
#Question1
import threading
from threading import Thread
import time
class Th(threading.Thread):
def __init__(self,i):
threading.Thread.__init__(self)
self.h = i
def run(self):
time.sleep(5)
print("hello i am running",self.h)
obj1 = Th(1)
obj1.start()
obj2 = Th(2)
obj2.start()
#Question 2
import threading
from threading import Thread
import time
class Th(threading.Thread):
def __init__(self,i):
threading.Thread.__init__(self)
self.h = i
def run(self):
print("Number is = ", self.h)
for i in range(1,11):
thread = Th(i)
time.sleep(1)
thread.start()
#Question 3
import threading
from threading import Thread
import time
List = [1, 4, 6, 8, 9]
class Data(threading.Thread):
def __init__(self, i):
threading.Thread.__init__(self)
self.h = i
def run(self):
print("Number is = ", self.h)
for i in List :
for f in range(2,11,2):
thread = Data(i)
time.sleep(f)
print(f)
thread.start()
#Question 4
import math
import threading
from threading import Thread
import time
class Th(threading.Thread):
def __init__(self,i):
threading.Thread.__init__(self)
self.h = i
def run(self):
print(math.factorial(5))
obj1 = Th(1)
obj1.start()
|
0a8a9a0a4c6ca24fde6c09886c52d1d5c7817a24 | Trietptm-on-Coding-Algorithms/Learn_Python_the_Hard_Way | /ex40b.py | 974 | 4.53125 | 5 | cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not found."
# ok pay attention!
cities ['_find'] = find_city
while True:
print "State? (ENTER to quit)",
state = raw_input("> ")
if not state: break
#this line is the msot important ever! study!
city_found = cities['_find'] (cities, state)
print city_found
"""
'CA' = key
More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins.
Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed.
Continue with these:
http://docs.python.org/2/tutorial/datastructures.html
http://docs.python.org/2/library/stdtypes.html - mapping types
"""
|
5892f0c1c6cb36853a85e541cb6b3259346546e9 | Trietptm-on-Coding-Algorithms/Learn_Python_the_Hard_Way | /ex06.py | 898 | 4.1875 | 4 | # Feed data directly into the formatting, without variable.
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
#Referenced and formatted variables, within a variable.
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
#r puts quotes around string
print "I said: %r." % x
#s does not put quotes around string, so they are added manually
print "I also said: '%s'." % y
hilarious = False
#variable anticipates formatting of yet unkown variable
joke_evaluation = "Isn't that joke so funny?! %r"
#joke_evaluation has formatting delclared in variable, when called formatting statement is completed by closing the formatting syntax
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
#since variables are strings python concatenates, rather than perform mathmetic equation with error
print w + e |
15eb6a39ec8e85689d6dc60f8bed506d68955634 | pellertson/scripts | /bin/fenparser | 1,712 | 3.5625 | 4 | #!/usr/bin/python3
# parser for printing properly formatted chess boards from a FEN record
# assumes piped input from json2tsv(2)
import fileinput
import sys
# uppercase letters are white; lowercase letters are black
def parse_square(sq):
if sq == 'k':
return '♚'
elif sq == 'K':
return '♔'
elif sq == 'q':
return '♛'
elif sq == 'Q':
return '♕'
elif sq == 'b':
return '♝'
elif sq == 'B':
return '♗'
elif sq == 'n':
return '♞'
elif sq == 'N':
return '♘' # m'lady
elif sq == 'r':
return '♜'
elif sq == 'B':
return '♖'
elif sq == 'p':
return '♟'
elif sq == 'P':
return '♙'
else:
return None
def print_fen(fen):
board, active, castle, en_passant, half_move, full_move = fen.split(' ')
parsed_board = []
# for row in board.split('/'):
# squares_parsed = 0
# for index, square in enumerate(row):
# parsed = parse_square(square)
# squares_parsed += 1
#
# if parsed:
# parsed_board.insert(0, parsed)
# else:
# i = square
# while i > 0:
# if i + parsed_squares % 2 == 0:
# parsed_board.insert(0, '')
# else:
# parsed_board.insert(
for row in board.split('/'):
result = ""
for index, sq in enumerate(row):
parsed_sq = parse_square(sq)
if parsed_sq:
result += parsed_sq
else:
for i in range(sq):
if i + index % 2 == 0:
result += ''
else:
result += '■'
parsed_board.append(result)
for row in parsed_board:
print(row)
def parse_line(line):
# for key, _, value in line.split('\t'):
# if key == '.games[].fen':
# print_fen(value)
print(type(line))
def main():
for line in sys.stdin:
parse_line(line)
if __name__ == '__main__':
main()
|
b67a4bd391591382eeadec48c55e5db6e9417f1f | samyumobiMSIT/ads-2 | /practise/m3/Bonus _ Hamilton Path/Hamilton Path/HamiltonianPath.py | 1,684 | 3.71875 | 4 | from __future__ import print_function
from data_structures.adjacency_list_graph import construct_graph
class HamiltonianPath(object):
'''Find the hamiltonian path in a graph'''
def __init__(self, graph):
self.graph = graph
self.vertices = self.graph.adjacency_dict.keys()
self.hamiltonian_path = []
def is_hamitonian(self):
'''Check if the path exists between the current sequence of vertices'''
N = len(self.vertices)
for i in range(N-1):
if self.vertices[i+1] not in self.graph.get_connected_vertices(self.vertices[i]):
return False
return True
def get_permutations(self, left, right):
'''Find all the permutation of vertices and return hamiltonian path if it exists'''
if (left == right):
if self.is_hamitonian():
self.hamiltonian_path.append(self.vertices[:]) # Copying by value
else:
for i in range(left, right+1):
self.vertices[left], self.vertices[i] = self.vertices[i], self.vertices[left]
self.get_permutations(left+1, right)
# backtrack
self.vertices[left], self.vertices[i] = self.vertices[i], self.vertices[left]
def hamiltonian(self):
self.get_permutations(0, len(self.vertices)-1)
return self.hamiltonian_path
def test_hamiltonian():
g = construct_graph()
hamiltonian = HamiltonianPath(g)
hamiltonian_path = hamiltonian.hamiltonian()
hamiltonian_path = [[str(vertex) for vertex in path] for path in hamiltonian_path]
print (hamiltonian_path)
if __name__ == "__main__":
test_hamiltonian() |
59c54a778af80dc495ed27f83006893f36e9a9e7 | saurabhslsu560/myrespository | /oop3.py | 1,028 | 4.15625 | 4 | class bank:
bank_name="union bank of india"
def __init__(self,bank_bal,acc_no,name):
self.bank_bal=bank_bal
self.acc_no=acc_no
self.name=name
return
def display(self):
print("bank name is :",bank.bank_name)
print("account holder name is:",self.name)
print("account number is :",self.acc_no)
print("account balance is :",self.bank_bal)
return
def main():
print("enter first customer detail:")
k=input("enter name:")
l=int(input("enter account number:"))
m=int(input("enter balance:"))
print("enter second customer detail:")
n=input("enter name:")
o=int(input("enter account number:"))
p=int(input("enter balance:"))
print("first customer detail is:")
obj=bank(m,l,k)
obj.display()
print("second customer detail is:")
obj=bank(p,o,n)
obj.display()
return
bank.main()
|
31ebe8918dd39a56be55d7d73315ea3a1e0e292b | ftuyama/AIproblems | /Lab5/DiffEvolution.py | 7,634 | 3.703125 | 4 | # -*- coding: utf-8 -*-
# !/usr/bin/env python
"""Algoritmo das N-Rainhas."""
from random import randint
from copy import deepcopy
from graphics import *
import timeit
def print_board(board):
u"""Desenha o grafo de rotas a partir do mapa lido."""
win = GraphWin('N-Rainhas', 850, 650)
win.setBackground(color_rgb(188, 237, 145))
title = Text(Point(400, 30), "N-Rainhas")
title.setSize(20)
title.draw(win)
# Desenha tabuleiro principal
rect = Rectangle(
Point(150 - 5, 100 - 5),
Point(650 + 5, 600 + 5)
)
rect.setFill('brown')
rect.draw(win)
# Desenha as casas no tabuleiro
square = 500 / N
for i in range(N):
for j in range(N):
if (i + j) % 2 == 0:
x = 150 + i * square
y = 100 + j * square
rect = Rectangle(
Point(x, y),
Point(x + square, y + square)
)
rect.setFill('gray')
rect.draw(win)
# Desenha as peças no tabuleiro
x = 150 + i * square
y = 100 + board[i] * square
cir = Circle(
Point(x + 0.5 * square, y + 0.5 * square), 160 / N
)
cir.setFill('blue')
cir.draw(win)
win.getMouse()
win.close()
def restricoes(board):
u"""Número de restrições violadas."""
restricoes = 0
for i in range(N):
for j in range(i):
if check(board, i, j):
restricoes += 1
return restricoes
def check(board, i, j):
u"""Número de ataques no tabuleiro."""
return (board[i] == board[j]) or \
(abs(i - j) == abs(board[i] - board[j]))
'''################# <Implementação da Evolução Diferencial> ###############'''
def check_solution(generation):
u"""Verifica se problema foi resolvido."""
# Calcula restrições para indivíduos da geração
restrs = [restricoes(ind) for ind in generation]
solution = []
for i, retr in enumerate(restrs):
if retr == 0:
solution.append(generation[i])
return solution, restrs
def initial_population(population):
u"""Gera uma população inicial para algoritmo."""
return [[randint(0, (N - 1)) for i in range(N)] for j in range(population)]
def diff_evolution(population, max_steps):
u"""Realiza evolução diferencial."""
gen_restrs, generations = [], []
last_restrs, last_generation = [], []
generation = initial_population(population)
generations.append(generation)
for steps in range(max_steps):
# Verifica a solução
solution, restrs = check_solution(generation)
gen_restrs.append(restrs)
if len(solution) > 0:
return solution[0], generations, gen_restrs, steps
# Realiza pedigree com gerações anteriores
if len(last_generation) > 0:
generation = pedigree(
last_generation, last_restrs,
generation, restrs)
# Roda novo ciclo de evolução diferencial
new_generation = []
probabilities = evaluate_fitness(generation, restrs)
for i in range(population / 2):
[ind1, ind2] = fitness(generation, probabilities)
[ind1, ind2] = crossover(ind1, ind2)
new_generation += [mutation(ind1), mutation(ind2)]
last_restrs, last_generation = restrs, generation
generations.append(new_generation)
generation = new_generation
return [], generations, gen_restrs, -1
'''####### Funções de Fitness #######'''
def pedigree(generation, restrs, next_generation, next_restrs):
u"""Mantém indíviduos da geração anterior."""
population = len(generation)
total_restrs = sorted(restrs + next_restrs)
median = total_restrs[len(total_restrs) / 2]
selection = []
for i, restr in enumerate(next_restrs):
if restr <= median and len(selection) < population:
selection.append(next_generation[i])
for i, restr in enumerate(restrs):
if restr <= median and len(selection) < population:
selection.append(mutation(generation[i]))
return selection
'''####### Funções de Fitness #######'''
def evaluate_fitness(generation, restrs):
u"""Retorna probabilidades para geração."""
total = sum([1.0 / restr for restr in restrs])
def calc_prob(restr, total, generation):
return 100.0 / (total * restr)
# Calcula probabilidade de seleção de indivíduos
probabilities = []
for restr in restrs:
probabilities.append(calc_prob(restr, total, generation))
return probabilities
def select_fitness(probabilities):
u"""Seleciona indíviduo conforme probabilidade."""
acc = 0
n = randint(0, 100)
for i, prob in enumerate(probabilities):
if n <= acc + prob:
return i
acc += prob
return select_fitness(probabilities)
def fitness(generation, probabilities):
u"""Seleciona indíviduos para crossover."""
ind1 = select_fitness(probabilities)
ind2 = select_fitness(probabilities)
while ind1 == ind2:
ind2 = select_fitness(probabilities)
return [generation[ind1], generation[ind2]]
'''####### Funções de Crossover #######'''
def crossover(board1, board2):
u"""Realiza o crossover de dois indivíduos."""
n = randint(0, N)
return [board1[0:n] + board2[n:N], board2[0:n] + board1[n:N]]
'''####### Funções de Mutação #######'''
def mutation(board):
u"""Substitui aleatoriamente um valor de uma posição aleatória do vetor."""
restr = restricoes(board)
if restr < 5 and restr > 2:
for steps in range(100):
index = randint(0, (N - 1))
new_board = deepcopy(board)
new_board[index] = randint(0, (N - 1))
if restricoes(new_board) < restr:
return new_board
else:
index = randint(0, (N - 1))
board[index] = randint(0, (N - 1))
return board
'''################ <Implementação da Evolução Diferencial/> ###############'''
def log_performance(steps, solution, gen_restrs):
u"""Imprime estatísticas do resultado."""
if steps > 0:
print "Resolvido em " + str(steps) + " passos"
print(solution)
else:
print "Não foi resolvido"
print("###########################################################")
print("Máximo: " + str([max(gen_restr) for gen_restr in gen_restrs]))
print("Média: " + str([sum(gen_restr) / len(gen_restr)
for gen_restr in gen_restrs]))
print("Mínimo: " + str([min(gen_restr) for gen_restr in gen_restrs]))
if steps > 0:
print_board(solution)
def monte_carlo(population, steps, depth):
u"""Roda algoritmo várias vezes."""
total_steps = 0
start = timeit.default_timer()
for i in range(depth):
(solution, generations, gen_restrs, max_steps) =\
diff_evolution(population, steps)
total_steps += max_steps
stop = timeit.default_timer()
print "Média de tempo: " + str(((stop - start) * 1.0) / depth)
print "Média de passos: " + str((total_steps * 1.0) / depth)
# Rotina main()
print "*************************************"
print "* *"
print "* Problema das N-Rainhas *"
print "* *"
print "*************************************"
N = 10
demo = True
if demo:
(solution, generations, gen_restrs, steps) = diff_evolution(40, 100)
log_performance(steps, solution, gen_restrs)
else:
monte_carlo(40, 100, 20)
|
5d14097892b10f631944b82dbe03262a26d84021 | dariokl/firebase-flask-ponzi | /ponzi.py | 2,355 | 3.546875 | 4 | """
PONZI. A pyramid scheme you can trust
YOU HAVE UNLIMTED TRIES
THE 4 DIGITS IN THE NUMBER DONT REPEAT
THERE IS NO LEADING ZERO
YOUR GUESS CANNOT HAVE REPEATING NUMBERS
THE FASTER YOU ARE DONE THE BEST
THE RETURNS ARE ALLOCATED ACCORDING TO YOU ABILITY TO SCAPE THE PYRAMID FROM THE TOP
KILLED MEANS THE NUMBER IS PRESENT AND IT IS LOCATED IN THE RIGHT POSITION
INJURED MEANS THE NUMBER IS PRESENT BUT NOT IN THE RIGHT POSITION
"""
import time
from random import sample, shuffle
import json
data = {}
digits = 3
guesses = 10
player="name"
#check if input repeats digits function to warn player
def has_doubles(n):
return len(set(str(n))) < len(str(n))
#counting killed-injured function
def countX(lst, x):
count = 0
for ele in lst:
if (ele == x):
count = count + 1
return count
# Create a random number with no leading 0 no repeated digit.
letters = sample('0123456789', digits)
if letters[0] == '0':
letters.reverse()
number = ''.join(letters)
counter = 1
while True:
print('Guess #', counter)
guess = input()
if counter == 2:
start_time = time.time()
if len(guess) != digits:
print('Wrong number of digits. Try again!')
continue
if has_doubles(guess) is True:
print('You cannot repeat digits. Try again!')
continue
# Create the clues.
clues = []
for index in range(digits):
if guess[index] == number[index]:
clues.append('Killed')
elif guess[index] in number:
clues.append('Wounded')
if len(clues) == 0:
print('Nothing')
else:
print('There are {} {}'.format(countX(clues, "Killed"), "Killed"))
print('There are {} {}'.format(countX(clues, "Wounded"), "Wounded"))
counter += 1
if guess == number:
print('You got it!')
end_time = time.time()
data['start_time']= start_time
data['end_time']= end_time
data['total_time']= end_time - start_time
data['status']= "solved"
json_data = json.dumps(data)
print("You took: ", end_time - start_time)
break
if counter > guesses:
print('You ran out of guesses. The answer was', number)
end_time = time.time()
print("You took: ", int(end_time - start_time), "seconds")
break |
263c7fb994dca4aeb198f87793683ef6630b267a | kdolder79/maze_game | /rooms/room10.py | 3,951 | 3.5 | 4 | import adventure_game.my_utils as utils
from colorama import Fore, Style
# # # # #
# ROOM 10
#
# Serves as a good template for blank rooms
room10_description = '''
. . . 10th room ...
This looks like another hallway.
Not much is in this room.
'''
room8_state = {
'door locked': False
}
room11_state = {
'door locked': True
}
room10_inventory = {
'sword': 1,
'iron key': 1
}
def run_room(player_inventory):
# Let the user know what the room looks like
utils.print_description(room10_description)
# valid commands for this room
commands = ["go", "take", "drop", "use", "examine", "status", "help"]
no_args = ["examine", "status", "help"]
# nonsense room number,
# In the loop below the user should eventually ask to "go" somewhere.
# If they give you a valid direction then set next_room to that value
next_room = -1
done_with_room = False
while not done_with_room:
# Examine the response and decide what to do
response = utils.ask_command("What do you want to do?", commands, no_args)
response = utils.scrub_response(response)
the_command = response[0]
# now deal with the command
if the_command == 'go':
go_where = response[1].lower()
if go_where == 'north':
is_locked = room8_state['door locked']
if not is_locked:
next_room = 8
done_with_room = True
else:
print('The door to Room 8 is locked.')
elif go_where == 'south':
is_locked = room11_state['door locked']
if not is_locked:
next_room = 11
done_with_room = True
else:
print('The door to Room 11 is locked.')
else:
print('You cannot go:', go_where)
elif the_command == 'take':
take_what = response[1]
utils.take_item(player_inventory, room10_inventory, take_what)
elif the_command == 'drop':
drop_what = response[1]
utils.drop_item(player_inventory, room10_inventory, drop_what)
elif the_command == 'status':
utils.player_status(player_inventory)
utils.room_status(room10_inventory)
elif the_command == 'use':
use_what = response[1]
if use_what in player_inventory:
object = use_what.split()
if object[1] == 'key':
direction = utils.prompt_question('Which door would you like to use the key on?', ['north', 'south'])
if direction.lower() == 'north':
print('The door was already unlocked')
elif direction.lower() == 'south':
door_locked = room11_state['door locked']
if door_locked:
if object[0] == 'iron':
room11_state['door locked'] = False
current_count = player_inventory['iron key']
player_inventory['iron key'] = current_count - 1
print('The door to the SOUTH is now unlocked.')
else:
print('A', use_what, 'is unable to unlock the', direction, 'door.')
else:
print('The door was already unlocked.')
else:
print('You have no way to use:', use_what)
else:
print("You don't have:", use_what)
else:
print('The command:', the_command, 'has not been implemented in room 10.')
# END of WHILE LOOP
return next_room
|
b42c601cfb574a4d8f6f4f5c37b117385bd350ee | KevinBorah/Python_for_Absolute_Beginners | /Python_Code/RPS_Game-v1.py | 1,614 | 4.09375 | 4 | print("----------------------------")
print(" Rock Paper Scissors v1")
print("----------------------------")
print()
player_1 = input("Enter Player 1's name: ")
player_2 = input("Enter Player 2's name: ")
rolls = ['rock', 'paper', 'scissors']
roll1 = input(f"{player_1} what is your roll? {rolls}: ")
roll1 = roll1.lower().strip()
if roll1 not in rolls:
print(f"Sorry {player_1}, {roll1} is not a valid play!")
roll1 = input(f"{player_1} what is your roll? {rolls}: ")
roll2 = input(f"{player_2} what is your roll? {rolls}: ")
roll2 = roll2.lower().strip()
if roll2 not in rolls:
print(f"Sorry {player_2}, {roll2} is not a valid play!")
roll2 = input(f"{player_2} what is your roll? {rolls}: ")
print(f"{player_1} rolls {roll1}")
print(f"{player_2} rolls {roll2}")
# Test for a winner
winner = None
if roll1 == roll2:
elif roll1 == 'rock':
if roll2 == 'paper':
winner = player_2
elif roll2 == 'scissors':
winner = player_1
elif roll1 == 'paper':
if roll2 == 'rock':
winner = player_1
elif roll2 == 'scissors':
winner = player_2
elif roll1 == 'scissors':
if roll2 == 'rock':
winner = player_2
elif roll2 == 'paper':
winner = player_1
print("The round is over!")
if winner is None:
print("The game was a tie")
else:
print(f"{winner} wins the game!")
# Rock
# Rock -> Tie
# Paper -> Lose
# Scissors -> Win
# Paper
# Rock -> Win
# Paper -> Tie
# Scissors -> Lose
# Scissors
# Rock -> Lose
# Paper -> Win
# Scissors -> Tie
# <K2>
|
638ba2a42c0aae6fa5a250d6aeaac2a81c264180 | szerem/pySolve100Exercises | /45.py | 201 | 3.546875 | 4 | import os, string
if not os.path.exists("letters"):
os.makedirs("letters")
for letter in string.ascii_lowercase:
with open("letters/{}.txt".format(letter), "w") as f:
f.write(letter) |
3fe58aa1750f43479050a19efe175cbffcf60d9a | szerem/pySolve100Exercises | /79.py | 293 | 3.796875 | 4 | import platform
import string
print(platform.python_version())
while True:
psw = input('--> ')
if any( i.isdigit() for i in psw) and any( i.isupper() for i in psw) and len(psw) >= 5:
print("Password is fine")
break
else:
print("Password is not fine")
|
02a81d00904de7e79c311d05919ad55012d903af | CHENHERNGSHYUE/pythonTest | /tkinter/tkinter_09_messagebox.py | 1,260 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 12:00:12 2019
@author: chenmth
"""
import tkinter as tk
window = tk.Tk()
window.title('messagebox test')
window.geometry('600x300')
def answer():
print(input(''))
def messageBoxShowing():
tk.messagebox.showinfo(title='info box', message='一般顯示')
tk.messagebox.showwarning(title='warning box', message='可執行但有問題')
tk.messagebox.showerror(title='warning box', message='執行異常')
answer = tk.messagebox.askquestion(title='question', message='回答問題')
if(answer=='yes'): #注意 question是return yes & no
name=input('輸入名字: ')
age=input('輸入年齡: ')
tk.messagebox.showinfo(title='個人資料', message=name+'今年'+age+'歲')
else:
tk.Label(window, text='輸入失敗', fg='red').pack()
answer = tk.messagebox.askyesno(title='小問題', message='你是人嗎?')
if answer: #注意 yesno是return True & False
tk.Label(window, text='正常人', fg='blue').pack()
else:
tk.Label(window, text='快跑喔!', fg='red', font=('Arial',50)).pack()
tk.Button(window, text='show new box', bg='pink', command=messageBoxShowing
).pack()
window.mainloop()
|
525bea426bd338a87b1c0b2a76c833fd2eedae49 | CHENHERNGSHYUE/pythonTest | /class.py | 566 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 5 15:33:44 2019
@author: chenmth
"""
class Calculator: #class名稱第一個字母要大寫
Name = 'kenny'
def add_function(a,b):
return a+b
def minus_function(a,b):
return a-b
def times_function(a,b):
return a*b
def divide_function(a,b):
return a//b
add = Calculator.add_function(10,10)
minus = Calculator.minus_function(10,10)
times = Calculator.times_function(10,10)
divide = Calculator.divide_function(10,10)
print(add)
print(minus)
print(times)
print(divide) |
9a0d3d86d0390f77a0533b36d751799489a582e3 | CHENHERNGSHYUE/pythonTest | /pandas/a.py | 450 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 15 20:18:54 2019
@author: chenmth
"""
#list = ['3','4','a','-1','b']
#
#try:
# total = 0
# for i in list:
# # if type int(i) is int:
# total = total + int(i)
# else:
# pass
# print(total)
#except:
# ValueError
list = ['3', '4', 'a', '-1', 'b']
total = 0
for i in lst:
try:
total += int(i)
except ValueError:
pass
print(total) |
982bf085f43b2e0d3c48701b3df06e8edb66cd76 | CHENHERNGSHYUE/pythonTest | /copy_id.py | 767 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 7 14:46:21 2019
@author: chenmth
"""
import copy
a = [1,2,3]
b = a
print(id(a)) #id表示秀出該物件存放記憶體的位置
print(id(b))
print(id(a)==id(b))
b[0]=111
print(a) #因為空間共用, 所以互相影響
c = copy.copy(a) #copy a 的東西, 但存放記憶體空間位置不同
print(c)
print(id(a)==id(c))
c[0] = 1
print(a) #c是copy a來的 但c的變化不影響a
a[0] = [0,1]
print(a)
d = copy.copy(a) #此copy為表面上copy, 但實際內部內容仍為相同
print(id(d[0])==id(a[0])) #so....is true
d[0][0] = [0,1] #會影響到a 因為copy不夠全面
print(a)
e = copy.deepcopy(a)
print(a)
e[0][0] = 3333333333333
print(a) #a內容不變
print(e) #e內容會變
print(id(d[0])==id(e[0]))
|
d11526d684d51e31950e0220c01d977fde90a8f6 | CHENHERNGSHYUE/pythonTest | /pandas/pandas_07_merge04_index.py | 542 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 12 12:05:55 2019
@author: chenmth
"""
import pandas as pd
import numpy as np
A = pd.DataFrame({'A':[0,1,2],
'B':[3,4,5],
'C':[0,1,2]},
index=['X','Y','Z'])
B = pd.DataFrame({'C':[0,1,2],
'M':['A','A','A'],
'D':[3,4,5]},
index=['X','Y','F'])
#right_index和left_index: 保留index項目 可看成針對行的join
C = pd.merge(A, B, left_index=True, right_index=True, how='left')
print(C) |
5a8526d077625013a78de556b1c3f86f6f628860 | CHENHERNGSHYUE/pythonTest | /numpy/numpy_01.py | 404 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 15:20:54 2019
@author: chenmth
"""
import numpy as np
array = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
print(array) #秀出矩陣形式 array不能有逗號且必須是矩形
print(array.ndim) #2 多少維度
print(array.size) #12 (4*3) 多少個元素
print(array.shape) #(4,3) (x,y)->(矩陣數、行、row, 矩陣內部元素、列、column) |
beebefcc521dfb5aafbb12b0d67d9a6516c831d5 | natahlieb/adventofcode2017 | /Day2/day2.2.py | 540 | 3.625 | 4 | import sys
def findDivisor(row):
max = 0
min = sys.maxsize
for k in range(0, len(row), 1):
for j in range(k+1, len(row), 1):
print(' comparing k {} j {}'.format(row[k], row[j]))
if(int(row[k]) > int(row[j])):
if (int(row[k]) % int(row[j]) == 0):
return int(row[k]) / int(row[j])
else:
if (int(row[j]) % int(row[k]) == 0):
return int(row[j]) / int(row[k])
sum = 0
with open(sys.argv[1], "r") as f:
for line in f:
row = line.strip().split(' ')
sum += findDivisor(row)
print(sum)
|
7b10d33efe740095c60a6d108f704c85d413eefd | natahlieb/adventofcode2017 | /Day13/day13.0.py | 1,645 | 3.53125 | 4 | import sys
def calculateScannerLocation(cycleNubmer, depth):
currentLocation = 0
count = 0
direction = "down"
depth = depth - 1
while(count != cycleNubmer):
if (direction == "down"):
if currentLocation+1 <= depth:
currentLocation += 1
else:
direction = "up"
currentLocation -= 1
elif direction == "up":
if(currentLocation -1 >= 0):
currentLocation -= 1
else:
direction = "down"
currentLocation+=1
count+=1
#print("Count:{}, Location: {}, Direction:{}".format(count, currentLocation, direction))
#print("Current location of scanner is: {}".format(currentLocation))
return currentLocation
layerHash = {}
file = open(sys.argv[1])
totalCost = 0
for line in file:
inputArray = list(map(int, line.replace(" ", "").split(":")))
layerHash[inputArray[0]] = inputArray[1]
for item in layerHash:
print("{}: {}".format(item, layerHash[item]-1))
currentLayer = 0
numberCycles = max(layerHash)
for i in range(0, numberCycles+1):
'''for j in layerHash:
#calculate scanner location
location = calculateScannerLocation(i, layerHash[j])
print("Layer: {} CurrentLocation of scanner for this layer:{}".format(j, location))
#if (location == 0):
# print("Hit the scanner; adding to total cost")
# totalCost += (i * layerHash[i])
print("\\\\\\\\\\\\\\\\\n")
input("Press Enter to continue...")
'''
if i in layerHash:
#calculate scanner location
location = calculateScannerLocation(i, layerHash[i])
if location == 0:
print("Cycle {}: Hit the scanner; adding to total cost".format(i))
totalCost += (i * layerHash[i])
print(totalCost)
#severity = depth * range |
1b344f93dd4970ffba799d08516651b0958a7ba2 | joshwinebrener/clock-math | /clockmath.py | 3,148 | 3.53125 | 4 | """
Created to compute all the meaningful mathematical arrangements of a sequence
of integers. Specifically, this script is made to find the percentage of such
meaningful arrangements in 12- and 24-hour time formats.
E.g. 6:51 : 6 - 5 = 1
"""
import sys
class Mode:
twelve_hour = 0
twentyfour_hour = 1
decimal = 2
MODE = Mode.twelve_hour
def add(a, b):
if a is None or b is None:
return None
return a + b
def sub(a, b):
if a is None or b is None:
return None
return a - b
def mul(a, b):
if a is None or b is None:
return None
return a * b
def div(a, b):
if a is None or b is None:
return None
if b == 0:
return None
return a / b
def pow_(a, b):
if a is None or b is None:
return None
if a == 0 and b <= 0:
return None
if b > 1000:
return None
return pow(a, b)
def root(a, b):
if a is None or b is None:
return None
if a == 0:
return None
return pow_(b, 1/a)
def concat(a, b):
if a is None or b is None:
return None
return a * 10 + b
ops = {
'+': add,
'-': sub,
'*': mul,
'/': div,
'^': pow_,
'√': root,
'': concat,
}
hits = 0
misses = 0
def test(k, l, m, n, s=sys.stdout):
global hits, misses, MODE
if MODE == Mode.twelve_hour:
s.write(f'{k}{l}:{m}{n} : ')
else:
s.write(f'{k}{l}{m}{n}: ')
for symbol1, op1 in ops.items():
for symbol2, op2 in ops.items():
if op1(k, l) == op2(m, n): # kl = mn
s.write(f'{k}{symbol1}{l} = {m}{symbol2}{n}\n')
hits += 1
return
if op1(k, op2(l, m)) == n: # k(lm) = n
s.write(f'{k}{symbol1}({l}{symbol2}{m}) = {n}\n')
hits += 1
return
if op2(op1(k, l), m) == n: # (kl)m = n
s.write(f'({k}{symbol1}{l}){symbol2}{m} = {n}\n')
hits += 1
return
if k == op1(l, op2(m, n)): # k = l(mn)
s.write(f'{k} = {l}{symbol1}({m}{symbol2}{n})\n')
hits += 1
return
if k == op2(op1(l, m), n): # k = (lm)n
s.write(f'{k} = ({l}{symbol1}{m}){symbol2}{n}\n')
hits += 1
return
s.write(f'-\n')
misses += 1
if __name__ == '__main__':
with open('results.txt', 'w') as f:
for k in range(10):
for l in range(10):
if MODE == Mode.twelve_hour and (concat(k, l) > 12 or concat(k, l) <= 0):
continue
elif MODE == Mode.twentyfour_hour and (concat(k, l) > 12 or concat(k, l) < 0):
continue
for m in range(10):
for n in range(10):
if (MODE == Mode.twelve_hour or MODE == Mode.twentyfour_hour) and concat(m, n) > 59:
continue
test(k, l, m, n, f)
f.write(f'\nhits: {hits}, misses: {misses}, hit percentage: {hits/(hits+misses)*100:.2f}%.\n')
|
750870bd2e4bdfc1ca690ec6a09cf37245f0ad59 | Binary-Developers/Dark-Algorithms | /Count_Inversions/countInversion.py | 249 | 3.78125 | 4 | n=int(input('Enter number of elements\n'))
a=[]
print('Enter n elements\n')
count = 0
for i in range (0,n):
a.append(int(input()))
for i in range(0,n):
for j in range(0,i):
if a[j]>a[i]:
count+=1
print(count)
|
344023505df184a5c5dca70610b0f77c116b3158 | antonioanerao/python-codecademy | /aula2.py | 459 | 3.578125 | 4 | def applicant_selector(gpa, ps_score, ec_count):
if (gpa >= 3.0) and (ps_score >= 90) and (ec_count >= 3):
return "This applicant should be accepted."
elif (gpa >= 3.0) and (ps_score >= 90) and (ec_count < 3):
return "This applicant should be given an in-person interview."
else:
return "This applicant should be rejected."
print(applicant_selector(4.0, 95, 4))
print(applicant_selector(4.0, 95, 2))
print(applicant_selector(4.0, 70, 4))
|
3a0fdd4a1bcc83eb0501f91cdc0da8abebfd8172 | Gabriel-Teles/Mercado | /Mercado.py | 799 | 3.5625 | 4 | #coding: utf-8
from Estoque import estoque
class mercado:
def mercado(self):
esto = estoque()
while True:
print("\n= = = = Bem-vindo(a) ao EconomizaTec= = = =\n")
print("Digite a opção desejada\n")
print("1. Cadastrar um Produto")
print("2. Vender um Produto")
print("3. Imprimir Balanço")
print("4. Sair")
opcao = raw_input("\nOpção: ")
if opcao == "1":
esto.cadastroP()
elif opcao=="2":
esto.vendendo()
elif opcao=="3":
esto.imprimirBalanco()
elif opcao == "4":
print "\nFim de caixa."
return "sair"
mec = mercado()
mec.mercado() |
00dc2338120ff076d7e0f1e7a16e1affbec35fb7 | Pallavirampal/python_games_programs | /exercise 6.py | 2,562 | 3.765625 | 4 | import random
comp=['Rock','Paper','Sicssor']
# print(comp_choice)
user_score=0
comp_score=0
i=1
while i<=6:
comp_choice = random.choice(comp)
print('*** ROUND',i,'***')
user_choice = input('Press (r) for rock (p) for paper and (s) for scissor:')
if user_choice == 'r':
if comp_choice == 'Rock':
print('Both choose rock, this is a tie')
print('user_score=', user_score)
print('comp_score=', comp_score)
elif comp_choice == 'Paper':
print('Comp_choice=', comp_choice, ',User_choice=', user_choice)
comp_score += 1
print('user_score=', user_score)
print('comp_score=', comp_score)
elif comp_choice == 'Sicssor':
print('Comp_choice =', comp_choice, ',User_choice=', user_choice)
user_score += 1
print('user_score=', user_score)
print('comp_score=', comp_score)
elif user_choice == 'p':
if comp_choice == 'Rock':
print('Comp_choice =', comp_choice, ',User_choice=', user_choice)
user_score += 1
print('user_score=', user_score)
print('comp_score=', comp_score)
elif comp_choice == 'Paper':
print('Both choose paper, this is a tie')
print('user_score=', user_score)
print('comp_score=', comp_score)
elif comp_choice == 'Sicssor':
print('Comp_choice =', comp_choice, ',User_choice=', user_choice)
comp_score += 1
print('user_score=', user_score)
print('comp_score=', comp_score)
elif user_choice == 's':
if comp_choice == 'Rock':
print('Comp_choice =', comp_choice, ',User_choice=', user_choice)
comp_score += 1
print('user_score=', user_score)
print('comp_score=', comp_score)
elif comp_choice == 'Paper':
print('Comp_choice =', comp_choice, ',User_choice=', user_choice)
user_score += 1
print('user_score=', user_score)
print('comp_score=', comp_score)
elif comp_choice == 'Sicssor':
print('Both choose scissor, this is a tie')
print('user_score=', user_score)
print('comp_score=', comp_score)
else:
print('Invalid Choice...please try again')
i+=1
print('\n' * 2)
# choice=input('Do you want to play again, if yes press (y) if no press (n):')
# if choice=='y':
# continue
# elif choice=='n':
# exit()
|
f0b9981c887e5a642a1479a2ae52da120b79d3dc | MarlenXique/lab-10-more-loops | /hanoi.py | 872 | 4 | 4 | def move(f,t): #from,to.A value passed to a function (or method) when calling the function.
print("move from {} to {}".format(f,t)) #.format is amethod because of the dot. ots a strong, class of data.
move("A","C")
def moveVia(f,v,t): #from,via,to.
move(f,v) #function call to move(): move from step1 to step 2 (out of 3)
#at first the destinations is v
move(v,t) # move from step 2 to step 3 (out of 3)
#now, the origin is v, and the desitination is t
def hanoi(n,f,h,t):
#n: number of discs
#f: front postion
#h: helper position
#t: target pposition
if n==0:
pass #this is the BASE CASE. termination condition
else:
hanoi(n-1,f,t,h) #functon call within the function definition (the recursion)!
move(f,t)
hanoi(n-1,h,f,t)
hanoi(4,"A","B","C")
# based on a tutorial by Professor Thorsten Altenkirch
|
79b5d599291b8b0ec5532134e2f382177e935d3b | Chih-YunW/Full_Name | /name.py | 174 | 4.15625 | 4 | def full_name(f: str, l:str):
full_name = f + ' ' + l
return full_name
f = input("What is the first name: ")
l = input("What is the second name: ")
print(full_name(f,l))
|
c4167ce0440026258141ff33fb5c0ba2404938fa | Artarin/study-python-Erick-Metis | /operation_with_files/exceptions/words_counter.py | 488 | 3.96875 | 4 | """this program search and counting quontity of simple word in text.file"""
pre_path = "books_for_analysis//"
books = ["Életbölcseség.txt",
"Chambers's.txt",
"Crash Beam by John Barrett.txt"
]
for book in books:
print (book +':')
with open (pre_path+book, 'r', encoding='utf-8') as f:
text = f.read()
print (("count 'the...':") + str(text.lower().count('the')))
print (("count 'the':") + str(text.lower().count('the '))) |
71a2fe42585b7a6a2fece70674628c1b529f3371 | pltuan/Python_examples | /list.py | 545 | 4.125 | 4 | db = [1,3,3.4,5.678,34,78.0009]
print("The List in Python")
print(db[0])
db[0] = db[0] + db[1]
print(db[0])
print("Add in the list")
db.append(111)
print(db)
print("Remove in the list")
db.remove(3)
print(db)
print("Sort in the list")
db.sort()
print(db)
db.reverse()
print(db)
print("Len in the list")
print(len(db))
print("For loop in the list")
for n_db in db:
print(n_db)
print(min(db))
print(max(db))
print(sum(db))
my_food = ['rice', 'fish', 'meat']
friend_food = my_food
friend_food.append('ice cream')
print(my_food)
print(friend_food)
|
97745f9a33b8e5653d050d3a5c875c57bc4e5780 | WangMingJue/StudyPython | /Test/Python 100 example/Python 练习实例6.py | 1,134 | 4.25 | 4 | # 题目:斐波那契数列。
#
# 程序分析:斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……。
#
# 在数学上,费波那契数列是以递归的方法来定义:
# F0 = 0 (n=0)
# F1 = 1 (n=1)
# Fn = F[n-1]+ F[n-2](n=>2)
# 普通方法
def method_1(index):
a, b = 1, 1
for i in range(index - 1):
a, b = b, a + b
return a
# 使用递归
def method_2(index):
if index == 1 or index == 2:
return 1
return method_2(index - 1) + method_2(index - 2)
# 输出前 n 个斐波那契数列
def fib(n):
if n == 1:
return [1]
if n == 2:
return [1, 1]
fibs = [1, 1]
for i in range(2, n):
fibs.append(fibs[-1] + fibs[-2])
return fibs
if __name__ == '__main__':
print("第一种方法输出了第10个斐波那契数列,结果为:{}".format(method_1(10)))
print("第二种方法输出了第10个斐波那契数列,结果为:{}".format(method_1(10)))
print("输出前10个斐波那契数列,结果为:{}".format(fib(10)))
|
e87c204af85487af4753814f850156fd414b36b8 | WangMingJue/StudyPython | /Test/Python 100 example/Python 练习实例8.py | 260 | 3.796875 | 4 | # 题目:输出 9*9 乘法口诀表。
#
# 程序分析:分行与列考虑,共9行9列,i控制行,j控制列。
for i in range(1, 10):
result = ""
for j in range(1, i + 1):
result += "{}*{}={} ".format(i, j, i * j)
print(result)
|
16ea342f088dabb6af5c4f932144b9904e417cd3 | ueoSamy/Python | /lesson4/easy.py | 1,552 | 4.09375 | 4 | # Все задачи текущего блока решите с помощью генераторов списков!
# Задание-1:
# Дан список, заполненный произвольными целыми числами.
# Получить новый список, элементы которого будут
# квадратами элементов исходного списка
# [1, 2, 4, 0] --> [1, 4, 16, 0]
list_a = [1, 2, 4, 0]
list_b = [elem ** 2 for elem in list_a]
print(list_b)
# Задание-2:
# Даны два списка фруктов.
# Получить список фруктов, присутствующих в обоих исходных списках.
fruits_one = ['яблоко', 'киви', 'лимон', 'ананас', 'арбуз', 'груша']
fruits_two = ['груша', 'виноград', 'киви', 'какос', 'мандарин', 'ананас']
fruits_three = [elem for elem in fruits_one if elem in fruits_two]
print(fruits_three)
# Задание-3:
# Дан список, заполненный произвольными числами.
# Получить список из элементов исходного, удовлетворяющих следующим условиям:
# + Элемент кратен 3
# + Элемент положительный
# + Элемент не кратен 4
import random
list_one = [9, 6, 12, 35, -50, 42, -3, 62, 33]
list_two = [number for number in list_one if number % 3 == 0 and number > 0 and number % 4 != 0]
print(list_two) |
678e8e9b2995324a8c7fd091d1a9b2cc7dde8171 | KIMZI0N/bioinfo-lecture-2021-07 | /src/016_1.py | 811 | 3.59375 | 4 | #! /usr/bin/env python
file_name = "read_sample.txt"
'''
#1
with open(file_name, 'r') as handle:
for line in handle:
print(line) #line에 이미 \n가 들어있음.
#print()도 디폴트end가 \n이므로 enter가 두번씩 쳐짐.
#print(line, end' ')하면 end를 띄어쓰기로 바꿀 수 있음.
#2
#print(line.strip()) #line의 \n를 없앨 수 있음.
#3
handle = open(file_name,'r')
for line in handle:
print(line.strip())
handle.close()
#with open 대신 그냥 open하면 반드시: close()해야하고 들여쓰기 안함.
#4
handle = open(file_name,'r')
lines = handle.readlines()
for line in lines:
print(line.strip())
handle.close()
'''
#취향껏 용도에 맞게..
#5
with open(file_name, 'r') as handle:
lines = handle.readlines()
for line in lines:
print(line.strip())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.