blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
3714290166d95b048beff2b2ba2950f70678485c
|
hajdaini/tomo
|
/src/database.py
| 2,259 | 3.75 | 4 |
#!/usr/bin/python3.6
#coding:utf-8
import sqlite3
import sys
"""
Classe Database
- Sauvegarde les données du jeu
"""
class Database:
__instance = None
def __init__(self, filename : str):
self.filename = filename
self.connection = None
self.cursor = None
if Database.__instance is None:
Database.__instance = self
else:
raise Exception("Classe déjà instanciée")
self.connect()
self.create()
@staticmethod
def GetInstance(filename : str = 'tomo.db'):
if not Database.__instance:
Database(filename)
return Database.__instance
"""
Connexion à la base de données SQLite
"""
def connect(self):
try:
self.connection = sqlite3.connect(self.filename, isolation_level = None)
self.cursor = self.connection.cursor()
except:
print("Problème de connexion à la BASE !")
"""
Création des tables dans la base de données
"""
def create(self):
self.cursor.execute("CREATE TABLE IF NOT EXISTS tomo(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20) NOT NULL UNIQUE, age INTEGER NOT NULL, health INTEGER NOT NULL, items TEXT)")
self.cursor.execute("CREATE TABLE IF NOT EXISTS foods(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20) NOT NULL UNIQUE, expiration INTEGER NOT NULL, heal INTEGER NOT NULL)")
"""
Récupérer des données depuis la base
"""
def select(self, table_name : str, selector : dict):
names = ""
values = ""
for name, value in selector.items():
names = str(name)
values = "'" + str(value) + "'"
sql = f"SELECT * FROM {table_name} WHERE {names} = {values}"
return self.cursor.execute(sql).fetchone()
def save(self, table_name : str, columns : dict):
names = ""
values = ""
for name, value in columns.items():
names += "'" + str(name) + "', "
if isinstance(value, list):
values += "'" + " ".join(value) + "', "
else:
values += "'" + str(value) + "', "
values = values.strip()
names = names[:-2]
values = values[:-1]
sql = f"INSERT INTO {table_name}({names}) VALUES({values})"
try:
self.cursor.execute(sql)
except Exception as e:
print(e)
"""
Clôture la connexion à la base de données SQLite
"""
def disconnect(self):
self.cursor.close()
self.connection.close()
if __name__ == '__main__':
pass
|
b10bcbbac711fd39ce1cb97a7b34f67618e8c36b
|
dnbadibanga/Python-Scripts
|
/calc_area.py
| 181 | 4.3125 | 4 |
#Calculate the area of a circle
from math import *
radius = input('Enter the radius of a circle: ')
radius = int(radius)
area = pi * (radius ** 2)
print('The area is ', area)
|
a9aff10aa9a634abf0fafa793872b7c206cbaa39
|
praneesh12/python_review
|
/Collections_module/hackerank_OrderedDict.py
| 370 | 3.53125 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 6 14:28:06 2019
@author: praneeshkhanna
"""
from collections import OrderedDict
n = int(input())
d = OrderedDict()
for i in range(n):
item, price = (input().rsplit(None, 1))
if item not in d.keys():
d[item] = int(price)
else:
d[item] += int(price)
for k,v in d.items():
print(k,v)
|
3a19f15d99ea37d76839c5e8e3c15ff28dbff029
|
kevmct90/PythonProjects
|
/Python-Programming for Everybody/Week 10 Tuples/Code/Lab 10.2 Tuples are NOT immutable.py
| 444 | 3.640625 | 4 |
__author__ = 'Kevin'
# 08/04/2015
# Tuples are NOT immutable
# Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string
x = [9, 4, 7]
print x # [9, 4, 7]
x[2] = 6
print x # [9, 4, 6]
# cannot convert string variable
# y = 'ABC'
# y[2] = 'D' # Traceback:'str' object does not support item Assignment
# z = (5, 4, 3)
# z[2] = 0 # Traceback:'tuple' object does not support item Assignment
|
2d4f8b57199e02c2e5e61b398bad6915612689e5
|
kodeskolen/tekna_h19
|
/trondheim/dag2/funksjoner2.py
| 356 | 3.546875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 28 16:55:49 2019
@author: Marie
"""
def legg_sammen(ledd1, ledd2):
return ledd1 + ledd2
def maks(a, b):
# Ta inn to tall, returner det største av dem
if a > b:
størst = a
else:
størst = b
return størst
print(legg_sammen(1, 2))
print(maks(3, 3))
|
60eedb5211db6dad67bf52deec72877d86170771
|
MonsieurPengu/ENGR-102
|
/Apps and Progs/Lab3Act2.py
| 818 | 3.9375 | 4 |
name1 = str(input("First name "))
day1 = int(input("First day "))
month1 = int(input("First month "))
year1 = int(input("First year "))
name2 = str(input("Second name "))
day2 = int(input("Second day "))
month2 = int(input("Second month "))
year2 = int(input("Second year "))
name3 = str(input("Third name "))
day3 = int(input("Third day "))
month3 = int(input("Third month "))
year3 = int(input("Third year "))
name4 = str(input("Fourth name "))
day4 = int(input("Fourth day "))
month4 = int(input("Fourth month "))
year4 = int(input("Fourth year "))
print("Names".ljust(20),"Birthdays".ljust(10))
print(name1.ljust(20),month1,"/",day1,"/",year1)
print(name2.ljust(20),month2,"/",day2,"/",year2)
print(name3.ljust(20),month3,"/",day3,"/",year3)
print(name4.ljust(20),month4,"/",day4,"/",year4)
|
b8cf0ac6ff9726649088f5f4dcdbb436aa5993ec
|
breathfisheva/Algorithm
|
/Greedy Algorithm/GiveChange.py
| 1,883 | 3.75 | 4 |
'''
钱币找零问题
这个问题在我们的日常生活中就更加普遍了。假设1元、2元、5元、10元、20元、50元、100元的纸币分别有c0, c1, c2, c3, c4, c5, c6张。现在要用这些钱来支付K元,至少要用多少张纸币?
用贪心算法的思想,很显然,每一步尽可能用面值大的纸币即可。在日常生活中我们自然而然也是这么做的。在程序中已经事先将Value按照从小到大的顺序排好。
分解问题:
当还需要找N'钱的时候,选择一个纸币用来找零,这个纸币要小于还需要找的钱的值,而且这个纸币还有>0张
选择最优策略:
策略1:选择面值最大的纸币
'''
class Money(object):
def __init__(self, value, amount):
self.value = value
self.amount = amount
def strategy(Moneys):
max_value = 0
index = -1
for i in range(len(Moneys)):
if Moneys[i].value > max_value and Moneys[i].amount > 0: #最优解是钱币最大,同时数量不为0
max_value = Moneys[i].value
index = i
return index
def greedy(Moneys , Totalchange):
totalchange = Totalchange
index = -1
while totalchange > 0:
index = strategy(Moneys)
if index!=-1: #如果有最优解
if Moneys[index].value <= totalchange: #看下最优解是否小于现在还需要找的零钱总数, 有的话,还剩下更新还需要找零的总数,以及这个钱币的个数
print(Moneys[index].value)
totalchange -= Moneys[index].value
Moneys[index].amount -= 1
else: #如果最优解大于还需要找的零钱总数,把最优解从零钱列表里删除
del Moneys[index]
if __name__ == '__main__':
moneys = [Money(1,1), Money(2,1), Money(5,1), Money(10,2), Money(20,1)]
greedy(moneys, 16)
|
9ab9f49feb09e8ff5930514b3f664fcd583a74d9
|
shadowlaw/data_struct
|
/BinaryHeap.py
| 2,715 | 4.09375 | 4 |
class Node:
def __init__(self, value):
self.value = value
self.is_min = True
self.left = None
self.right = None
self.parent = None
class Heap:
class Queue:
def __init__(self):
self.__queue = []
def empty(self):
return self.__queue == []
def put(self, value):
self.__queue.append(value)
def get(self):
if not self.empty():
return self.__queue.pop(0)
return False
def __contains__(self, item):
return item in self.__queue
def __init__(self, value=None):
self.root = Node(value)
self.__add_to = 'left'
self.__node_add_to = self.root
self.__level_queue = Heap.Queue()
def is_empty_heap(self):
return self.root.value is None
def is_leaf(self):
return self.root.value is not None and self.root.left is None and self.root.right is None
def is_root(self):
return self.root.is_min is True
def insert(self, value):
def bubble_up(insert_node):
if insert_node.is_min or insert_node.parent.value < insert_node.value:
return
else:
temp_node_value = insert_node.value
insert_node.value = insert_node.parent.value
insert_node.parent.value = temp_node_value
bubble_up(insert_node.parent)
def add_to_queue(node):
if node.left is not None and node.left not in self.__level_queue:
self.__level_queue.put(node.left)
if node.right is not None and node.right not in self.__level_queue:
self.__level_queue.put(node.right)
if self.is_empty_heap():
self.root.value = value
return True
if self.__add_to == 'left':
self.__node_add_to.left = Node(value)
self.__node_add_to.left.parent = self.__node_add_to
self.__node_add_to.left.is_min = False
bubble_up(self.__node_add_to.left)
self.__add_to = "right"
add_to_queue(self.__node_add_to)
return True
elif self.__add_to == 'right':
self.__node_add_to.right = Node(value)
self.__node_add_to.right.parent = self.__node_add_to
self.__node_add_to.right.is_min = False
bubble_up(self.__node_add_to.right)
self.__add_to = "left"
add_to_queue(self.__node_add_to)
if not self.__level_queue.empty():
self.__node_add_to = self.__level_queue.get()
return True
def show_min(self):
return self.root.value
|
7ff552b80486bc00059ee089ab4b2cd847fa9df5
|
noamrubin22/dataprocessing
|
/homework/week_1/scraper/tvscraper.py
| 4,282 | 3.609375 | 4 |
#!/usr/bin/env python
# Name: Noam Rubin
# Student number: 10800565
"""
This script scrapes IMDB and outputs a CSV file with highest rated tv series.
"""
import csv
import re
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
TARGET_URL = "http://www.imdb.com/search/title?num_votes=5000,&sort=user_rating,desc&start=1&title_type=tv_series"
BACKUP_HTML = 'tvseries.html'
OUTPUT_CSV = 'tvseries.csv'
def extract_tvseries(dom):
"""
Extract a list of highest rated TV series from DOM (of IMDB page).
Each TV series entry should contain the following fields:
- TV Title
- Rating
- Genres (comma separated if more than one)
- Actors/actresses (comma separated if more than one)
- Runtime (only a number!)
"""
# ADD YOUR CODE HERE TO EXTRACT THE ABOVE INFORMATION ABOUT THE
# HIGHEST RATED TV-SERIES
# NOTE: FOR THIS EXERCISE YOU ARE ALLOWED (BUT NOT REQUIRED) TO IGNORE
# UNICODE CHARACTERS AND SIMPLY LEAVE THEM OUT OF THE OUTPUT.
# create lists
title_serie = []
ratings_serie = []
genre_serie = []
actors_serie= []
runtime_serie = []
complete_info_series = []
# iterate over series on page and add to lists
for serie in dom.find_all('div', class_="lister-item-content"):
# extract titles
title = serie.find('h3', class_="lister-item-header").a.text
title_serie.append(title)
# extract ratings
ratings = serie.find('div', class_="inline-block ratings-imdb-rating").strong.text
ratings_serie.append(ratings)
# extract genres
genre = serie.find('span', class_="genre").text.strip("\n")
genre_serie.append(genre.strip())
# create string
actors = ""
# extract actors
for actor in serie.find_all(class_="", href=re.compile("name")):
# add actor to actor-string
actors += actor.text + ", "
# add actors to list and remove unneccesarities
actors_serie.append(actors.replace("\n", "").strip())
# extract runtime (only number)
runtime = serie.find('span', class_="runtime").contents[0].strip("min")
runtime_serie.append(runtime)
# add lists to the complete_info list
complete_info_series = list(zip(title_serie, ratings_serie, genre_serie, actors_serie, runtime_serie))
return complete_info_series
def save_csv(outfile, tvseries):
"""
Output a CSV file containing highest rated TV-series.
"""
writer = csv.writer(outfile)
writer.writerow(['Title', 'Rating', 'Genre', 'Actors', 'Runtime'])
# write info tv serie in every row file
for serie in tvseries:
writer.writerow(serie)
def simple_get(url):
"""
Attempts to get the content at `url` by making an HTTP GET request.
If the content-type of response is some kind of HTML/XML, return the
text content, otherwise return None
"""
try:
with closing(get(url, stream=True)) as resp:
if is_good_response(resp):
return resp.content
else:
return None
except RequestException as e:
print('The following error occurred during HTTP GET request to {0} : {1}'.format(url, str(e)))
return None
def is_good_response(resp):
"""
Returns true if the response seems to be HTML, false otherwise
"""
content_type = resp.headers['Content-Type'].lower()
return (resp.status_code == 200
and content_type is not None
and content_type.find('html') > -1)
if __name__ == "__main__":
# get HTML content at target URL
html = simple_get(TARGET_URL)
# save a copy to disk in the current directory, this serves as an backup
# of the original HTML, will be used in grading.
with open(BACKUP_HTML, 'wb') as f:
f.write(html)
# parse the HTML file into a DOM representation
dom = BeautifulSoup(html, 'html.parser')
# extract the tv series (using the function you implemented)
tvseries = extract_tvseries(dom)
# write the CSV file to disk (including a header)
with open(OUTPUT_CSV, 'w', newline='') as output_file:
save_csv(output_file, tvseries)
|
6d744cb1c88d063a3265cce976134928a2a03a99
|
kojino/nlp100
|
/ch1/p5.py
| 551 | 3.6875 | 4 |
# 5
def ngram(n,s,unit):
if unit == "char":
chars = s
return ngram_char(n,s)
elif unit == "word":
words = s.replace(',','').split( )
return ngram_word(n,words)
else:
raise ValueError('unit must be char or word')
def ngram_char(n,s):
result = []
for i in range(len(s)-n+1):
result.append(s[i:i+n])
return result
def ngram_word(n,words):
result = []
for i in range(len(words)-n+1):
result.append(words[i:i+n])
return result
# print ngram(2,"I am an NLPer","char")
# print ngram(2,"I am an NLPer","word")
|
9eba57c0586d9a6e8fe03db61e977ec3c60cbd9c
|
red23495/random_util
|
/Python/Algebra/binary_exponentiation.py
| 671 | 3.90625 | 4 |
def mod_pow(base, power, mod=None):
"""
Implements divide and conquere binary exponetiation algorithm
Complexity: O(log power)
source: https://cp-algorithms.com/algebra/binary-exp.html
Params:
@base: base number which needs to be multiplied
@power: power to which base should be raised
@mod: modulas with which number should be mod'ed
returns: (base^power)%mod
"""
if mod:
base %= mod
result = 1
while power > 0:
if power & 1:
result *= base
if mod:
result %= mod
base *= base
if mod:
base %= mod
power //= 2
return result
|
7502b23ccae00d7afa3e787308781251b8632930
|
JanaRasras/CNN
|
/P01.py
| 1,109 | 3.765625 | 4 |
'''
@ Jana Rasras
Train CNN to classify images with Pytorch
'''
# Import libraries
import numpy as np
from matplotlib import pyplot as plt
from torch import nn # torch for nn and torchvision for datasets
from torchvision import datasets, transoforms #datasets for mnist # transforms for preprocessing
# define classes
# Define functions
def load_data():
''' load datasets from torchvision and preprocess it '''
pass
def build_nn_model():
''' build NN'''
pass
def train_nn(model, data):
''' train model on data. return trained model and accuracy . '''
pass
def test_nn():
''' test trained model on new data'''
pass
# main programm
def main():
'''main function '''
# load the data
train_data, test_Pdata = load_data(root ='/data')
# build NN
''' build CNN'''
model = build_nn_model()
## Train NN
trainedModel, accuracy = train_nn(model, train_data)
# test NN model on the new data
test_accuracy = test_nn(trainedModel, test_data)
if __name__ == "__main__":
main()
|
a6651bca2e1d83bb7c1bba1ea7f7211300f0eeef
|
tiagopalomares/covid-19-program
|
/covid-19-program.py
| 1,052 | 4.125 | 4 |
# new-program
print('COVID-19 ')
import time
# introdução
time.sleep(2)
print('Esse Programa foi desenvolvido por Tiago Palomares')
time.sleep(2)
print('Iniciando Programa . . . ')
time.sleep(2)
nome = (input('Qual o seu nome? '))
time.sleep(1)
print('Bem vindo {}'.format(nome))
time.sleep(1)
idade = int(input('Qual a sua idade? '))
time.sleep(2)
print('Responda se SIM ou NÃO para as perguntas a seguir \n sendo 1 para sim e 0 para não...')
time.sleep(1)
sim = int(1)
não = int(0)
f = int(input('Você está febril ? '))
time.sleep(1)
r = int(input('Você tem dificuldade para respirar ? '))
time.sleep(1)
t = int(input('Você está com tosse ? '))
time.sleep(1)
c = int(input('Você se sente cansado ? '))
time.sleep(1)
saude: int = f + r + t + c
vu = saude + idade
if vu >= 70:
print('Por favor {}, procure urgente um hospital e faça um exame de sangue'.format(nome))
elif vu :
print('Você esta bem, fique em casa {} '.format(nome))
#elif vu <= 30:
# print('Fique tranquilo deve ser apenas uma gripe, fique em casa {} '.format(nome))
|
ecebb551e0dc0f5e8123e4d6f04678cd47086b81
|
Iamsdt/Problem-Solving
|
/problems/hacker_earth/basic_input_output/ali_helping_innocent_people.py
| 378 | 3.5625 | 4 |
code = input() #"12X345-67"
# take first two
first = int(code[0]) + int(code[1]) % 2
# now check later
vowels = ["A","E","I","O","U","Y"]
# now check
second = int(code[3]) + int(code[4]) % 2
third = int(code[4]) + int(code[5]) % 2
fourth = int(code[7]) + int(code[8]) % 2
if first+second+ third+ fourth == 0 and code[2] in vowels:
print("valid")
else:
print("invalid")
|
09f5c8bf9c92f7990757dbdf04ddcef967851205
|
daniel-reich/ubiquitous-fiesta
|
/xA8FJW2cwjAnJ2ptt_3.py
| 122 | 3.640625 | 4 |
import re
def bomb(txt):
return "There is no bomb, relax." if re.search("bomb", txt.lower()) == None else "Duck!!!"
|
0fa132a77a3d3fe74a7c4f268aa3bd12f02d53fb
|
kobyyoshida/Project-Euler-Problems
|
/prob14.py
| 1,022 | 4.03125 | 4 |
import operator
highest = 0
memory = {}
def even(num):
return num/2
def odd(num):
return (3*num)+1
def process_num(num,chain):
#print("CHAIN CHECK: ",chain)
if num == 1:
#print("DONE")
return int(chain)
elif num % 2 == 0:
if num in memory:
return chain+memory[num]
else:
chain+=1
return process_num(even(num),chain)
elif num % 2 != 0:
if num in memory:
return chain+memory[num]
else:
chain+=1
return process_num(odd(num),chain)
for i in range(2,1000001):
chain = 0
chain = process_num(i,chain)
memory[i] = chain
#if chain > highest:
# print("NEW HIGHEST: ", highest)
# highest = i
#print("TYPE: ",type(chain))
#if i % 1000 == 0:
# print("NUMBER: ",i)
# print("CHAIN LENGTH: ",chain)
memory = sorted(memory.items(),key=operator.itemgetter(1),reverse=True)
print("MEMORY[0]: ", memory[0])
#print("FINAL HIGHEST : ",highest)
|
71b26523d2cfa7f747799778bce39e612710cc3a
|
fis-jogos/2016-2
|
/python-101/03 while.py
| 866 | 4.25 | 4 |
# O while executa um comando enquanto o argumento possuir um valor de verdade
# igual à True.
#
# No loop abaixo, enquanto x for menor que 5, o valor de verdade da expressão
# "x > 5" será verdadeiro. Neste caso, imprimimos os números de 1 a 5
x = 0
while x < 5:
x += 1
print('x = %s' % x)
# Note que essas formas são válidas:
#
# >>> while True:
# ... <comando a ser executado indefinidamente>
#
# Versão alternativa do anterior
#
# >>> while 1:
# ... <comando a ser executado indefinidamente>
#
# Não faz muito sentido, mas sintaticamente válido
#
# >>> while False:
# ... <comando que nunca será executado>
#
#
# Exercícios
# ----------
#
# 1) Faça um programa que calcule o produto dos números de 1 à 10 utilizando
# o laço while.
#
# 2) Faça um programa que calcule o fatorial de 20 utilizando
# o laço while.
|
edb63793a549bf6bf0e4de33f86a7cefb1718b57
|
onionmccabbage/python_april2021
|
/using_logic.py
| 355 | 4.28125 | 4 |
# determine if a number is larger or smaller than another number
a = int(float(input('first number? ')))
b = int(float(input('secomd number? ')))
# using 'if' logic
if a<b: # the colon begins a code block
print('first is less than second')
elif a>b:
print('second is less than first')
else:
print('probably the same number')
|
c45ebbaa7cca26fe8972c43b51ae727dd8ee35b2
|
marcdloz/cosc4377-Computer-Networks
|
/practice2_3.py
| 793 | 3.96875 | 4 |
# range starts inclusive, exclusive, then step
def main():
for i in range(2):
print("Go, Cats, Go!")
print("Go, Dogs, Go!")
print("BEAR DOWN!")
for i in range(3):
print("Who's house?! COUGS HOUSE")
for i in range(5):
print(i)
for num in range(2, 11, 2):
print(num)
a, b, c = 5, 0, -1
for num in range(a, b, c):
print(num)
for line in range(1, 6):
print("#" * line, end="")
print("+" * (2 * line), end="")
print("#" * line)
for line in range(1, 6):
print("#" * line, "+" * (2 * line), "#" * line, sep="") # not the favorable way, above method better.
for x in range(1, 6):
for y in range(1, 10):
print(y * x, end="\t")
print()
main()
|
92cc15e32cb659ed74d9fab6f79a11d05591bd72
|
gabriellaec/desoft-analise-exercicios
|
/backup/user_087/ch19_2019_03_12_03_14_04_642132.py
| 228 | 3.515625 | 4 |
import math
θ = float(input())
θ= math.radians(θ)
def calcula_distancia_do_projetil(v, θ, y0):
d = ((v**2)/(2 * 9.8))*(1 + math.sqrt(1 + (2 * 9.8 * y0)/(v*math.sin(θ))**2))*math.sin(2*θ)
return d
|
89aa3909cf0b4328ddc516261238123fee97c1ff
|
TylerJGabb/MoshPython
|
/foundational/classes/data_classes.py
| 576 | 4.1875 | 4 |
from collections import namedtuple
"""
sometimes we don't really need a class if all we are doing is storing data, so in this case
we can use the data class "named tuple" that allows us to create objects in a way that is
expliciy and everything is name
In this case, checking equality will only validate that data fields are equal, and does not care
about the memory address of each object
"""
Point = namedtuple("Point", ["x", "y"])
p1 = Point(x=1, y=2)
p2 = Point(x=1, y=2)
print(f'addr of p1 = {id(p1)}')
print(f'addr of p2 = {id(p2)}')
print(f'p1 == p2 -> {p1 == p2}')
|
35ac102cfebb2f1948aef10f5ffd981f9ef64b6a
|
BITMystery/leetcode-journey
|
/21. Merge Two Sorted Lists.py
| 591 | 3.546875 | 4 |
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = cur = ListNode(0)
while cur:
if not l1:
cur.next = l2
break
if not l2:
cur.next = l1
break
if l1.val < l2.val:
cur.next = l1
cur, l1 = cur.next, l1.next
else:
cur.next = l2
cur, l2 = cur.next, l2.next
return dummy.next
|
422b37bcac901a23e2af37809c89b17d83c7b1ff
|
adamrosenberg/LearnPython
|
/ex35.py
| 1,521 | 3.953125 | 4 |
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
next=raw_input("> ")
how_much = int(next)
if how_much < 50:
print "Nice, you aren't that greedy. You win!"
exit(0)
else:
dead("GREEDY! YOU LOSE!")
def bear_room():
print "There is a bear here"
print "The bear has a bunch of honey"
print "The fat bear is in front of another door"
print "How are you going to move the bear?"
bear_moved = False
while True:
next = raw_input("> ")
if next == "take honey":
dead("The bear looks at you and then eats your face")
elif next == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through now"
bear_moved = True
elif next == "taunt bear" and bear_moved:
dead("The bear gets mad and eats your leg")
elif next == "open door" and bear_moved:
gold_room()
else:
print "Invalid input"
def cthulhu_room():
print "You see the great, evil Cthulhu"
print "It stares at you and you go insane"
print "Do you flee or eat your own head?"
next = raw_input("> ")
if "flee" in next:
start()
elif "head" in next:
dead("Wll that was tasty!")
else:
cthulhu_room()
def dead(why):
print why, "Good Job!"
exit(0)
def start():
print "You are in a dark room"
print "There is a door to you right and left"
print "Which one do you take?"
next = raw_input("> ")
if next == "left":
bear_room()
elif next== "right":
cthulhu_room()
else:
dead("You stumble around until you starve")
start()
|
83ae840c22634cbfbc4b6d19721356779dad68b9
|
HellHuang/group_training
|
/base_exercise.py
| 655 | 3.796875 | 4 |
__author__ = 'fen'
#coding=utf-8
import random
list=[]
for i in range(5):
list.append(int(random.random()*100))
print "fist list",list
print "top 3",list[:3]
for i in range(10):
list.append((random.random()*50))
print "append list",list
list.sort()
print "soar list",list
list.sort(reverse=True)
print "decent list",list
print "max",max(list)
def sortedDictValues(dict):
keys=dict.keys()
keys.sort()
return [dict[key] for key in keys]
dict={9:"9",4:"4",0:'0',5:"5"}
#print sortedDictValues(dict)
keys=dict.keys()
keys.sort(reverse=True)
l=[]
for i in keys:
l.append(dict[i])
sort=[dict[key] for key in keys]
print sort
print l
|
683186491e97e944cbe0d665d937265fda1a316b
|
aloklenka666/python101
|
/ex3.py
| 334 | 3.5 | 4 |
# + -> addition operation
# - -> substraction operation
# / -> division operation
# * -> multiplication operation
# % -> modules operation ( reminder)
# < -> less than
# > -> greater than
# <= -> less than equal
# >= -> greater than equal
print(5+6*4/2-5)
print(10%2)
print(5>6)
print(3<5)
print(5<=3)
print(7>=4)
print('saikrishna')
|
d1f0010c2db6a36517ba6c5ec70b537fffa159d9
|
TheSlientnight/Algorithms-and-Data-Structures
|
/Graph/KnightTour.py
| 2,141 | 3.53125 | 4 |
from KnightGraph import knight_graph
def knight_tour(depth, path, vertex, limit):
vertex.set_color('gray')
path.append(vertex)
if depth < limit:
neighbors = order_by_available_moves(vertex)
i = 0
done = False
while i < len(neighbors) and not done:
if neighbors[i].get_color() == 'white':
done = knight_tour(depth + 1, path, neighbors[i], limit)
i += 1
if not done:
path.pop()
vertex.set_color('white')
else:
done = True
return done
def order_by_available_moves(vertex):
neighbor_moves_list = []
for neighbor in vertex.get_connections():
if neighbor.get_color() == 'white':
available_moves_num = 0
for great_neighbor in neighbor.get_connections():
if great_neighbor.get_color() == 'white':
available_moves_num += 1
neighbor_moves_list.append((available_moves_num, neighbor))
neighbor_moves_list.sort(key=lambda x: x[0])
sorted_neighbors = [neighbor_moves[1] for neighbor_moves in neighbor_moves_list]
return sorted_neighbors
def show_move_board(path):
board_size = int(len(path) ** 0.5)
path_keys = [vertex.get_id() for vertex in path]
for row in range(board_size):
for column in range(board_size):
step_num = str(path_keys.index(row * board_size + column))
while len(step_num) < 2:
step_num = ' ' + step_num
if column != board_size - 1:
print(step_num, end=' ')
else:
print(step_num, end='')
if row != board_size - 1:
print()
def main():
# 构建骑士游历图
board_size, start_key = 6, 6
graph = knight_graph(board_size)
# 设置骑士游历参数值
depth = 1
path = []
start_vertex = graph.get_vertex(start_key)
limit = board_size ** 2
# 获取骑士游历结果
print(knight_tour(depth, path, start_vertex, limit))
# 展示骑士游历移动棋盘
show_move_board(path)
if __name__ == '__main__':
main()
|
d5ecb9639fa4dc7d29267fb3594f44c9f79e2ab4
|
kirigaikabuto/Python19Lessons
|
/lesson11/6.py
| 405 | 3.703125 | 4 |
n = int(input())
arr = []
for i in range(n):
s = input() # yerassyl,22
name, age = s.split(",") # ["yerassyl","22"]
age = int(age)
arr.append([name, age])
maxiLen = 0
current = []
for i in arr:
if maxiLen < len(i[0]):
current = i
maxiLen = len(i[0])
print(current)
# #arr->[
# ["yerassyl",20]
# ...
# ]
# #3
# #yerasyl,20
# #kirito,30
# #lala,40
# yerassyl,20
|
0011eb6310cc0a89ee3850b1c6642c4899401fae
|
acrodeon/coursera-algo1
|
/algo1week2_programex2.py
| 1,045 | 4 | 4 |
####################################################################
# Algo1 Week2 : 10,000 integers between 1 and 10,000 (inclusive) #
# in some order, with no integer repeated. #
####################################################################
import os
import sys
from algo1week2_quicksort import quickSort
def createListFromFile (fileName=""):
"""create a list of integers in fileName, one integer per line"""
lst = []
try:
f = open(fileName, mode='r')
while 1:
x = f.readline()
if x == '':
break
# remove the '\n' at the end of the line and transform x as int
lst.append(int(x[:-1]))
f.close()
return lst
except:
print("ERROR: File ", fileName, "does not exist here ", os.getcwd ())
return lst
########
# Main #
########
if __name__ == '__main__':
l = createListFromFile("QuickSort.txt")
#print(len(l))
print("Nb Comparaisons = {0}".format(quickSort(l)))
|
c2a245b7663528d7301e46841b6e8c4ba7118b1c
|
Marcus893/algos-collection
|
/stack&queue/matching_bracket.py
| 1,100 | 4.21875 | 4 |
A string of brackets is correctly matched if you can pair every opening bracket
up with a later closing bracket, and vice versa. For example, "(()())" is correctly
matched, and "(()" and ")(" are not. Implement a function which takes a string of
brackets and returns the minimum number of brackets you'd have to add to the string
to make it correctly matched. For example, "(()" could be correctly matched by
adding a single closing bracket at the end, so you'd return 1. ")(" can be correctly
matched by adding an opening bracket at the start and a closing bracket at the end,
so you'd return 2. If your string is already correctly matched, you can just return
0.
import queue
def bracket_match(bracket_string):
right, total = 0, 0
q = queue.LifoQueue()
for i in range(len(bracket_string)):
q.put(bracket_string[i])
while not q.empty():
char = q.get()
if char == ')':
right += 1
else:
if right > 0: right -= 1
else: total += 1
return total + right
a = '(()())'
b = '((())'
c = ')('
print( bracket_match(a), bracket_match(b), bracket_match(c) )
|
470fcaa1347c7d68424e2eeb7f26eba657e1f89f
|
addyp1911/Python-week-1-2-3
|
/python/Algorithms/MergeSort/MergeSort.py
| 873 | 4.375 | 4 |
#Merge Sort - Write a program with Static Functions to do Merge Sort of list of Strings.
#a. Logic -> To Merge Sort an array, we divide it into two halves, sort the two halves independently,
# and then merge the results to sort the full array. To sort a[lo, hi), we use the following recursive strategy:
#b. Base case: If the subarray length is 0 or 1, it is already sorted.
#c. Reduction step: Otherwise, compute mid = lo + (hi - lo) / 2,
# recursively sort the two subarrays a[lo, mid) and a[mid, hi), and merge them to produce a sorted result.
import MergeSortBL
arr=[]
size = int(input("enter the size of the array to be sorted= "))
for i in range(size):
num = int(input("enter the element of the array= "))
arr.append(num)
print("the unsorted array is= ",arr)
right=len(arr)-1
MergeSortBL.srt(arr,0,right)
print("the sorted array is= ",arr)
|
abf5917af6585be1e5d3df218a426bd5e7196c97
|
dm-fedorov/epixx
|
/lesson_8/linear_search3.py
| 464 | 3.984375 | 4 |
# linear_search3.py
def linear_search(lst, value):
'''
Реализация алгоритма линейного поиска. Версия 3
'''
lst.append(value)
i=0
while lst[i] != value:
i += 1
lst.pop()
if i == len(lst):
return -1
else:
return i
if __name__ == '__main__':
print(linear_search([2, 5, 1, -3], 5))
print(linear_search([2, 4, 2], 2))
print(linear_search([2, 4, 2], 3))
|
d0c292c63ea78d5105864b808f7a83002d4cd0cf
|
ValentynaGorbachenko/BasicLanguagesInfo
|
/py/other/classNode.py
| 2,473 | 3.96875 | 4 |
class Queue(object):
def __init__(self):
self.items = []
def isEmpty(self):
# len(self.items) == 0
# print "inside the isEmpty method returns ", self.items == []
return self.items == []
# return len(self.items) == 0
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
if self.isEmpty() is not True:
return self.items.pop()
def size(self):
return len(self.items)
def printQueue(self):
print self.items
class Node(object):
def __init__(self, data, left = None, right = None):
self.data = data
self.left = left
self.right = right
def inOrder(self):
# print "class method inOrder", self.data
if self.left is not None:
self.left.inOrder()
print self.data
if self.right is not None:
self.right.inOrder()
def preOrder(self):
# print "class method preOrder", self.data
print self.data
if self.left is not None:
self.left.preOrder()
if self.right is not None:
self.right.preOrder()
def postOrder(self):
# print "class method postOrder", self.data
if self.left is not None:
self.left.postOrder()
if self.right is not None:
self.right.postOrder()
print self.data
def levelOrder(self):
q = Queue()
q.enqueue(self)
while q.isEmpty() is not True:
a = q.dequeue()
print a.data
if a.left is not None:
q.enqueue(a.left)
if a.right is not None:
q.enqueue(a.right)
# qq = Queue()
# qq.enqueue("1")
# qq.enqueue("2")
# qq.printQueue()
# print qq.dequeue()
# qq.printQueue()
myNode = Node("a", Node("b", Node("d"), Node("e")), Node("c", Node("f"), Node("g")))
# stand alone function
def inOrderPrint(node):
if node is not None:
# print "stand alone function inOrderPrint", node.data
inOrderPrint(node.left)
print node.data
inOrderPrint(node.right)
def levelOrderPrint(node):
if node is not None:
q = Queue()
q.enqueue(node)
while q.isEmpty() is not True:
node = q.dequeue()
print node.data
if node.left is not None:
q.enqueue(node.left)
if node.right is not None:
q.enqueue(node.right)
levelOrderPrint(myNode)
print "in level order SA", "8"*20
myNode.inOrder()
print "in order ", "*"*20
myNode.preOrder()
print "pre order ", "*"*20
myNode.postOrder()
print "post order ", "*"*20
inOrderPrint(myNode)
print "in order SA", "8"*20
myNode.levelOrder()
print "in level order ", "*"*20
|
ef3e4c9be9e43f01ab719b7ec958bc565d5b5cfc
|
leomonu/CarPython
|
/Car.py
| 608 | 3.53125 | 4 |
class Car(object):
def __init__ (self,speedLimit,company,color,model):
self.speedLimit = speedLimit
self.company = company
self.color = color
self.model = model
def start(self):
print('Started')
def stop(self):
print('Stopped')
def accelarate(self):
print("Accelarating")
def gearChanged(self):
print('Gear changed')
Laferrari = Car(200,'Ferrari','red','Laferrari')
print(Laferrari.speedLimit)
Laferrari.start()
Laferrari.accelarate()
Laferrari.gearChanged()
Laferrari.stop()
|
73c6e9de25d4746b9cf491efcb739c50e0671f5c
|
dgisolfi/cmpt120-labs
|
/RobotStore.py
| 1,786 | 3.75 | 4 |
#Into to programing
#Author: Daniel Gisolfi
#Date: 11/18/16
#RobotStore.py
class Products:
def __init__(self,name,price,stock):
self.name = name
self.price = price
self.stock = stock
def stockCount(self):
if (self.stock > count):
return false
return true
countPrice()
def countPrice(self, cost):
self.cost = count * products[prodId].price
countRemove()
def countRemove(self):
if (cash >= self.cost):
self.stock -= count
products = [
product = Products("Ultrasonic range finder",2.50,4),
product = Products("Servo motor",14.99,10),
product = Products("Servo controller",44.95,5),
product = Products("Microcontroller Board",34.95,7),
product = Products("Laser range finder",149.99,2),
product = Products("Lithium polymer battery",8.99,8)
]
def printStock():
print()
print("Available Products")
print("------------------")
for i in range(0,len(products)):
if products[i] > 0:
print() print(str(i)+")",products(name[i]), "$", products(price[i]))
def main():
global count, cash, prodId
cash = float(input("How much money do you have? "))
while cash > 0:
printStock()
[prodId,count] = map(int,input("Enter product ID and quantity you wish to buy: ").split(" "))
if products[prodId] >= count:
if cash >= products[prodId].cost:
products[prodId] -= count
cash -= products[prodId] * count
print("You purchased", count, products[prodId].name+".")
print("You have $",cash,"remaining.")
else:print("Sorry, you cannot afford that product.")
else:print("Sorry, we are sold out of", productNames[prodId])
|
c62c0150939d4f3ee003706dd93dbd1f2c77d0b7
|
neelgandhi108/Python-Codes-
|
/Magic Square.py
| 1,632 | 4.125 | 4 |
def magic_square(n):
magicSquare=[] # defining a variable magic square
for rows in range(n):
list=[] # defining the list so that whenever loops initiated a new list created for each row
for cols in range(n):
list.append(0) # whenever cols loop will be passed rows will be appended by values in list
magicSquare.append(list)
# fIXING THE 1 IN MAGIC SQUARE USING FORMULA(condition 1)
rows=n//2
cols=n-1
# Assining matrix as user input no itnot that no
matrix=n*n
count=1 # element variable , as soon as elements will be assinged count variable will increase to next variable Util unless all elements are assinged
#Condition 5
while (count<=matrix):
if(rows== -1 and cols== n):
cols = n-2
rows = 0
# Condition 3
else:
if(cols==n): #Coloum values exceding
cols=0
if(rows<0):#rows value becomes -1
rows=n-1
#condition 4
if(magicSquare[rows][cols]!= 0): #if has some elements in location
cols = cols-2
rows = rows+1
continue # skip what ever written below this and go back to while loop to check if a condtion said above repeats and do accordingly, if not:
else:
magicSquare[rows][cols] = count
count+=1 #increment the count variable
#condition 2(for second element)
rows = rows-1
cols = cols
# printing magicSquare
for rows in range(n):
for cols in range(n):
print(magicSquare[rows][cols], end = " ")
print()
magic_square(3)
|
387dad0987c3775cf0eb42ed368ce4894307ebdb
|
noorulameenkm/DataStructuresAlgorithms
|
/LeetCode/30-day-challenge/December/December 1st - December 7th/increasingOrderSearchTree.py
| 1,086 | 3.71875 | 4 |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def increasingBST(self, root):
results = []
self.constructIncreasingBST(root, results)
if len(results) == 0:
return None
if len(results) == 1:
return TreeNode(results[0])
new_root = TreeNode(results[0])
current = new_root
for i in range(1, len(results)):
current.right = TreeNode(results[i])
current = current.right
return new_root
def constructIncreasingBST(self, root, result):
if root:
self.constructIncreasingBST(root.left, result)
result.append(root.val)
self.constructIncreasingBST(root.right, result)
def main():
root = TreeNode(5)
root.left = TreeNode(1)
root.right = TreeNode(7)
Solution().increasingBST(root)
main()
|
91fbd39cc7384a91350d8ba98c1bd4abf8b736a5
|
jschnab/budgies
|
/src/spark/sort_s3_folders.py
| 1,347 | 3.5625 | 4 |
# script which reads a text file containing folder names and another
# containing their size, then saves a text file with folder names sorted by size
import os
# get path of the file containing accessions (= folders) names
with open('config.txt', 'r') as config:
while True:
line = config.readline()
if not line:
break
else:
splitted = line.split('=')
if splitted[0] == 'accession_file':
accessions = splitted[1].strip()
# make a list from the text file containing folder names
folders = []
with open(accessions, 'r') as infile:
while True:
line = infile.readline().strip()
if not line:
break
else:
folders.append(line)
# make a list from the text file containing folder sizes
with open('sizes.txt', 'r') as infile:
while True:
line = infile.readline().strip()
if not line:
break
else:
sizes = [float(s) for s in line.split()]
# get index of sorted sizes then sort folders
sort_index = sorted(range(len(sizes)), key=lambda i: sizes[i])
sorted_folders = [folders[i] for i in sort_index]
# save result in the same format as the original text file
with open('sorted_folders.txt', 'w') as outfile:
for sf in sorted_folders:
outfile.write(sf + '\n')
|
1dd7675790f7deaae1d020847b08b3f77fe7ae1a
|
BottleH/Algorithm-Python
|
/BaekJoon_Practice/Mathematics/Q_2292.py
| 771 | 3.578125 | 4 |
"""
위의 그림과 같이 육각형으로 이루어진 벌집이 있다. 그림에서 보는 바와 같이 중앙의 방 1부터 시작해서 이웃하는 방에 돌아가면서 1씩 증가하는 번호를 주소로 매길 수 있다.
숫자 N이 주어졌을 때, 벌집의 중앙 1에서 N번 방까지 최소 개수의 방을 지나서 갈 때 몇 개의 방을 지나가는지(시작과 끝을 포함하여)를 계산하는 프로그램을 작성하시오.
예를 들면, 13까지는 3개, 58까지는 5개를 지난다.
"""
# 방이 한개씩 늘어날 때마다 숫자는 6개씩 증가함.
n = int(input())
cnt = 1 # 기준값
num = 6 # 숫자의 갯수
result = 1 # 이동 칸 수
while n > cnt:
result += 1
cnt += num
num += 6
print(result)
|
cce2a195c1929bf0bbeb68e87ff5a9bcf33edeba
|
Alistrandarious/FizzBuzz-and-Rock-Paper-Scissors
|
/While.py
| 533 | 3.640625 | 4 |
#x = 0
#while (x) < 10:
# print(x)
# x += 1 # x = x + 1
#while x <= 10:
# print(f"The number is currently {x}")
# x += 1 # x = x + 1
# if x == 4:
# print("bored now")
# break
counter = 0
ageNum = False
while ageNum == False:
counter += 1
age = input(f"Attempt {counter}: What is your age?\n")
if age.isnumeric():
ageNum = True
print(F"Attempt:{counter}")
print(f"You are {age} years old")
elif counter == 5:
print(f"You're out of luck")
break
|
a018743caf298dd57455de239b55d02b11d6f7a5
|
Bcoders/Searching_and_Sorting
|
/Sum_to_100_ShiftedUp.py
| 693 | 3.671875 | 4 |
def operation(str1, str2, set1):
str1 = str1+str2[0]
str2 = str2[1:]
sign = ['+','-','']
for item in sign:
str3 = str1+item
str4 = str3+str2
if str4[-1] == item:
break
add = eval(str4)
if add == 100:
if str4[0] == '+':
set1.add(str4[1:])
else:
set1.add(str4)
operation(str3,str2,set1)
def main(string):
set1 = set()
item = ['+','-','']
str2 = string
str1 =''
for items in item:
operation(items+str1, str2, set1)
print(set1)
print(len(set1))
main('123456789')
|
718e1f95452502cc941ad556cc7345f9fa1a360b
|
xxd59366/python
|
/pycharmContent/else/testmk03.py
| 327 | 3.640625 | 4 |
import random
import string
key_poll=string.ascii_letters+string.digits
def gen_pass(n=8):
"说明:生成密码"
result=''
for i in range(n):
result+=random.choice(key_poll)
return result
if __name__ == '__main__':
print(gen_pass())
print(gen_pass(4))
print(gen_pass(12))
|
3f19b16871dcd793ec0916a909f708dfb1a3e235
|
nsiicm0/project_euler
|
/5/impl2.py
| 1,366 | 3.796875 | 4 |
'''
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
'''
n = 20
def get_test_numbers(n:int) -> int:
'''We will only test the largest multiples
for instance we will not test 2 and 4 if we are gonna test 8.
'''
candidates = range(2, n+1)
for i, candidate in enumerate(candidates):
ret = True
for next_candidate in candidates[i+1:]:
if next_candidate % candidate == 0:
ret = False
break
if ret:
yield candidate
def find_number(n:int) -> int:
factors_to_test = list(get_test_numbers(n))[::-1]
increment = max(factors_to_test) # we will search the number by incrementing the maximum number
if len(factors_to_test) == 1:
return factors_to_test[0]
number = 0
divisible = len(factors_to_test[1:]) * [False]
while not all(divisible):
number += increment
divisible = len(factors_to_test[1:]) * [False]
for i, factor in enumerate(factors_to_test[1:]): # skipping the first one - no need to test
if number % factor == 0:
divisible[i] = True
else:
break
return number
print(find_number(n))
|
81c484e0eb3971043f2a6abf4cf7470abb1db852
|
percivalalb/Python
|
/Python 3/pacman/datacomplier.py
| 4,210 | 3.75 | 4 |
class dataoutput():
def __init__(self):
self.data = bytearray()
def writeByte(self, byte):
assert(byte >= 0 and byte <= 255), 'Can\'t write a %d as a byte' % byte
self.data.append(byte)
def writeInteger(self, integer):
negative = integer < 0
integer = integer << 1 #Move the binary version 1 to the left, e.g 1101 (13) becomes 11010 (26)
if negative: integer = -integer; integer = integer | 1; #If integer is negative the free bit in number is converted to a 1 and integer
no_bytes = 0
while integer >= 2**(no_bytes * 8): no_bytes += 1 #Figures out how many bytes the integer takes up
self.writeByte(no_bytes) #Writes the number of bytes for when it is read
for byte in range(no_bytes):
mask = 2**(8 * byte + 8) - 2**(byte * 8) #Creates a mask to remove all bits but that of the byte to be written
final = (integer & mask) >> (byte * 8) #Applies the mask and shifts the target byte to the front making a number between 0-255
self.writeByte(final)
def writeIntegerArray(self, array):
self.writeInteger(len(array))
for integer in array:
self.writeInteger(int(integer))
def writeFloat(self, _float):
self.writeString(str(_float))
def writeFloatArray(self, array):
self.writeInteger(len(array))
for _float in array:
self.writeFloat(_float)
def writeString(self, string):
self.writeInteger(len(string))
for char in string:
self.writeInteger(ord(char))
def writeStringArray(self, array):
self.writeInteger(len(array))
for string in array:
self.writeString(string)
def writeBoolean(self, boolean):
self.writeByte(int(boolean)) #Converts boolean to one bit True (1), False (0)
def writeBooleanArray(self, array):
integer = 0
length = len(array)
for count in range(length):
if array[count]:
integer = integer | 2**(length - count - 1)
integer = integer | 2**(length) #Adds a marker to show you where the array starts because [False] in an array would be undetectable
self.writeInteger(integer)
class datainput():
def __init__(self, data, index = 0):
self.index = index
self.data = data
def readByte(self):
byte = self.data[self.index]
self.index += 1
return byte
def readInteger(self):
no_bytes = self.readByte()
integer = 0
for byte in range(no_bytes):
integer += self.readByte() << (byte * 8)
negative = integer % 2 == 1
integer = integer >> 1
if negative: integer = -integer
return integer
def readIntegerArray(self):
array = []
length = self.readInteger()
for i in range(length):
array.append(self.readInteger())
return array
def readFloat(self):
return float(self.readString())
def readFloatArray(self):
array = []
length = self.readInteger()
for i in range(length):
array.append(self.readFloat())
return array
def readString(self):
string = ''
length = self.readInteger()
for i in range(length):
string += chr(self.readInteger())
return string
def readStringArray(self):
array = []
length = self.readInteger()
for i in range(length):
array.append(self.readString())
return array
def readBoolean(self):
return self.readByte() == 1
def readBooleanArray(self):
carrier_integer = self.readInteger()
binary = bin(carrier_integer)
length = len(binary) - 3
array = []
for i in range(2, 2 + length):
array.append(int(binary[i + 1]) == 1)
return array
def has_read_everything(self):
return len(self.data) <= self.index
do = dataoutput()
do.writeInteger(-2)
print('Size of data %d' % len(do.data))
di = datainput(do.data)
print(di.readInteger())
|
0b40c796e20ddeee67bd3df55f4e6fafc5e745e8
|
Niemaly/python_tutorial_java_academy_and_w3
|
/zad_11-20/zad15.py
| 169 | 4.0625 | 4 |
word = input("wprowadź słowo")
if word[-1] == "m" or word[-1] == "M":
print("ostatnia litera to M lub m")
else:
print("ostatnia litera jest inna niż m lub M")
|
21553b42216d701b4d909e6f7f2aea8cd5c5cfd0
|
Dilshan1997/Hacktoberfest-2021-Full_Python_Tutorial
|
/Beginner level/Arithemetic operator.py
| 119 | 3.8125 | 4 |
print(2+32)
print(2*5)
print(7/2)
print(2**5)
x=int(input('x:'))
y=x+3
print(y)
y+=3
print(y)
x+=7
print(x)
print(7//5)
|
66df08e69ad0020e42a8a3f150931520b522e6fb
|
810Teams/pre-programming-2018-solutions
|
/Onsite/1130-Matrix Multiplication 3x3.py
| 678 | 4.03125 | 4 |
"""
Pre-Programming 61 Solution
By Teerapat Kraisrisirikul
"""
def main():
""" Main function """
matrix_a = [[int(input()) for _ in range(3)] for _ in range(3)]
matrix_b = [[int(input()) for _ in range(3)] for _ in range(3)]
matrix_r = [[multiply(matrix_a, matrix_b, i, j) for j in range(3)] for i in range(3)]
for i in matrix_r:
for j in i:
print(j, end=' ')
print()
def multiply(matrix_a, matrix_b, select_row_a, select_col_b):
""" Multiply a row from matrix_a with a column from matrix_b """
row = matrix_a[select_row_a]
col = [i[select_col_b] for i in matrix_b]
return sum([row[i]*col[i] for i in range(len(row))])
main()
|
79e1dd972927c161894a7a5337e8303e81de2aab
|
aasheeshtandon/Leetcode_Problems
|
/linkedList_implementation_of_stack.py
| 1,539 | 3.953125 | 4 |
from __future__ import print_function
class Node:
def __init__(self,value):
self.val = value
self.next = None
class Stack():
def __init__(self):
self.top = None
def isEmpty(self):
if self.top is None:
return True
else:
return False
def push(self, x):
temp = Node(x)
temp.next = self.top
self.top = temp
def pop(self):
if self.isEmpty():
print("Stack is already empty!")
return
popped = self.top.val
self.top = self.top.next
return popped
def size(self):
counter = 0
p = self.top
while p is not None:
counter += 1
p = p.next
return counter
def top(self):
if self.isEmpty():
print("Stack is empty!")
return
else:
return self.top.val
def display(self):
if self.isEmpty():
print("Stack is empty!")
else:
p = self.top
while p is not None:
print(p.val," ",end='')
p = p.next
def main():
s = Stack()
print(s.isEmpty())
print(s.display())
s.push(31)
s.push(42)
s.push(53)
s.push(64)
s.push(75)
print(s.isEmpty())
print(s.display())
print("Item deleted is", s.pop())
print(s.display())
print("Item deleted is",s.pop())
print("Item deleted is",s.pop())
print(s.display())
if __name__=='__main__':
main()
|
61d4a00671ec6152f04b0cba9398c1e0dcb700e6
|
damienlancry/.leetcode
|
/160.intersection-of-two-linked-lists.py
| 894 | 3.59375 | 4 |
#
# @lc app=leetcode id=160 lang=python3
#
# [160] Intersection of Two Linked Lists
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
def getlen(head):
if not head:
return 0
else:
return 1 + getlen(head.next)
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if not headA or not headB:
return
m = getlen(headA)
n = getlen(headB)
if m > n:
for _ in range(m - n):
headA = headA.next
if n > m:
for _ in range(n - m):
headB = headB.next
while headA and headB:
if headA == headB:
return headA
headA = headA.next
headB = headB.next
# @lc code=end
|
e5583d5fdf043520e106444e3f8b77e2ea048520
|
mikepatel/NBA-Teams
|
/East/southeast.py
| 338 | 3.71875 | 4 |
"""
Michael Patel
November 2019
"""
# Miami
class Miami:
def __init__(self):
self.roster = [
"Jimmy Butler",
"Tyler Herro",
"Kendrick Nunn",
"Goran Dragic",
"Justise Winslow"
]
# print team roster
def print_roster(self):
for player in self.roster:
print(f'{player}')
|
66c68076ece4c3def8acfefdf5d5573a57c5b902
|
jasokan/myplayground
|
/python-examples/jSumDigitsOddEven.py
| 233 | 4 | 4 |
#
# Created by Jagannathan Asokan dated 20/10/20
#
number = 145898
total = 0
while(number > 0):
digit = number % 10
total = total + digit
number = number // 10
print(total)
if total % 2 > 0:
print('ODD')
else:
print('EVEN')
|
4154ad1ccfa646dadc108130592e3a866d61b106
|
ahmedyoko/python-course-Elzero
|
/loop25while.py
| 2,135 | 4.0625 | 4 |
#-------------------
# loop => while
#-------------------
# while condition_is_true :
# code will run until condition become false
a = 0
while a < 10 :
print(a)
a += 1
else :
print("loop is Done") # true become false
print("#"*50)
myf = ['os','ah','aj','so','no','ju','on','ha','em','ya']
print(len(myf)) # list length : number of its elements
a = 0
while a < len(myf) :
# print(myf[a])
print(f"#{str(a+1).zfill(3)} {myf[a]}")
a += 1
else :
print('All friends printed to the screen')
print('#'*30)
print(myf[0])
print(myf[1])
print(myf[2])
print(myf[3])
print(myf[4])
print(myf[5])
print(myf[6])
print(myf[7])
print(myf[8])
print(myf[9])
#---------------------------
# simple bookmark manage
#---------------------------
# empty list to fill later
MyFavouriteWebs = []
# maximum allowed websites
maximumWebs = 5
while maximumWebs > 0 :
# every time input web and added to the list and decrease the index by one to finite loop
# input the new website
web = input('website name without https://')
# add the new website to the list
MyFavouriteWebs.append(f"https:// {web.strip().lower()}")
# decrease the index by one
maximumWebs -= 1
# print the added message
print(f"website added , {maximumWebs} places left")
# print the list
print(MyFavouriteWebs)
else :
print('Book mark is full , you can not add more')
if len(MyFavouriteWebs) > 0 :
# sort the list
MyFavouriteWebs.sort()
index = 0
while index < len(MyFavouriteWebs) :
print(MyFavouriteWebs[index])
index += 1
#-------------------------
# simple password guess
#-------------------------
tries = 4
mainpassword = 'osama@123'
inputpassword = input('write your password : ').lower()
while inputpassword != mainpassword :
tries -= 1
print(f'wrong password , {"last" if tries == 0 else tries} chance left')
inputpassword = input('write your password : ').lower()
if tries == 0 :
print('All tries is finished')
break
else :
# the condition of while become false
print('correct password')
print('the end of loop')
|
006d7da758407c4a24a1eb6e795201be978005f8
|
MuhammetALAPAN/Python-Exercises
|
/Beginner/q24.py
| 427 | 4.125 | 4 |
def my_pow(num):
"Calculates power 2 of a given number!"
return num ** 2
print(help(abs), "\n", help(int), "\n", help(len), "\n", help(my_pow))
print(abs.__doc__)
"""
print(abs.__doc__)
print(int.__doc__)
print(input.__doc__)
def square(num):
'''Return the square value of the input number.
The input number must be integer.
'''
return num ** 2
print(square(2))
print(square.__doc__)
"""
|
ed9689963d0f8750830e043bf37965a0829b1750
|
Veldhuis94/LEGENDE-VAN-HABAM
|
/DigitaleComponent/Utilities/Button.py
| 6,271 | 4.28125 | 4 |
#Made by Audi van Gog
#Version 1.3.0
import copy
#This class is a clickable object (has an event) and can be drawn on screen.
class Button:
#Properties you can set with **args
#[Size]
w = 200 #width
h = 40 #height
#[Text]
txt = "text" #text that gets displayed on the button
txtSize = 32 #font size
txtOffsetX = 0
txtOffsetY = 5
txtColor = (255, 254, 50) #Color of the text
txtColorHover = None
txtColorPressed = None
txtColorDisabled = (100, 100, 100)
txtFont = None
static_defaultFont = None
#[Background]
bgColor = (255, 148, 0) #default background color
bgColorHover = (255, 188, 96) #background color when the user hovers on the button
bgColorPressed = (96, 183, 255) #background color when the user clicks on the button
bgColorDisabled = (155, 77, 4)
radius = 5 #rounded cornors
#[Button events]
onClick = None #Is a event that runs every time a user clicks on this button. Type: function(Button = self)
enabled = True #Onclick event will be fired and color will change based on input (hover, click)
static_clicked = False
@staticmethod
def setDefaultFont(font):
Button.static_defaultFont = font
#Constructor of the Button, use this to initialise the button. Example usage: myButton = Button(100, 100, w = 100, h = 50, txt='click here')
def __init__(self, x, y, **args):
#----------------------
def setToDefaultValueIfNone(value, defaultValue):
if(value == None):
value = defaultValue
return value
#----------------------
#set the button position
self.x = x
self.y = y
self.onClick = Button.onClickDefault
self.clicked = True
self.clickCount = 0 #Amount of times the user has clicked on the button
#Extra arguments
if(not(args==None)):
self.__dict__.update(args)
self.bgColorCurrent = self.bgColor #Current background color
self.txtColorCurrent = self.txtColor
self.bgColorHover = setToDefaultValueIfNone(self.bgColorHover, self.bgColor)
self.bgColorPressed = setToDefaultValueIfNone(self.bgColorPressed, self.bgColor)
self.bgColorDisabled = setToDefaultValueIfNone(self.bgColorDisabled, self.bgColor)
self.txtColorHover = setToDefaultValueIfNone(self.txtColorHover, self.txtColor)
self.txtColorPressed = setToDefaultValueIfNone(self.txtColorPressed, self.txtColor)
self.txtColorDisabled = setToDefaultValueIfNone(self.txtColorDisabled, self.txtColor)
#Make a copy of this button and return the copy.
#Example: myButton.copy(), myButton.copy(x = 5, y = 3)
def copy(self, **args):
buttonCopy = copy.deepcopy(self)
buttonCopy.onClick = Button.onClickDefault
buttonCopy.clicked = True
buttonCopy.clickCount = 0 #Amount of times the user has clicked on the button
if(not(args==None)):
buttonCopy.__dict__.update(args)
return buttonCopy
#Default onclick event
def onClickDefault(button):
print("click", button.clickCount)
#draw the button
def draw(self):
def getAlpha(color):
if(len(color) >= 4):
return color[3]
return 255
#Button background
opacity = getAlpha(self.bgColorCurrent)
if opacity > 0: #If it's 0 or under, don't try to render it, it's going to be invisible anyways
fill(self.bgColorCurrent[0], self.bgColorCurrent[1], self.bgColorCurrent[2], opacity)
#the rectangle must be on the center of the button
rect(self.x - self.w / 2, self.y - self.h / 2, self.w, self.h, self.radius)
#Text
opacity = getAlpha(self.txtColorCurrent)
if opacity > 0:
fill(self.txtColorCurrent[0], self.txtColorCurrent[1], self.txtColorCurrent[2], opacity)
if(self.txtFont != None):
textFont(self.txtFont)
elif(Button.static_defaultFont != None):
textFont(Button.static_defaultFont)
textSize(self.txtSize)
textAlign(CENTER, TOP)
text(self.txt, self.x - self.w / 2 + self.txtOffsetX, self.y - self.h / 2 + self.txtOffsetY, self.w, self.h)
#Is a position/point (example: mouse cursor) in the area of the button?
def positionIsOnButton(self, x, y):
left = self.x - self.w / 2
right = self.x + self.w / 2
top = self.y - self.h / 2
bottom = self.y + self.h / 2
return (x > left and x < right and y > top and y < bottom)
def isClicked(self):
return self.clicked and self.clickCount > 0
#Run this on every frame.
def update(self):
#Prevent the user can click on multiple buttons simultaniously
if(Button.static_clicked==True):
if(mousePressed == False):
Button.static_clicked=False
else:
return #Don't run the rest of the function
mouseIsOnButton = self.positionIsOnButton(mouseX, mouseY)
if(self.enabled and mouseIsOnButton):
self.bgColorCurrent = self.bgColorHover
self.txtColorCurrent = self.txtColorHover
if(mousePressed and self.clicked == False): #The user must release the mouse button before he/she can press on it again
Button.static_clicked=True
self.clicked = True
self.bgColorCurrent = self.bgColorPressed
self.txtColorCurrent = self.txtColorPressed
if not(self.onClick == None):
self.clickCount += 1
self.onClick(self)
else:
if(not(self.enabled)): #If the button has been disabled...
self.bgColorCurrent = self.bgColorDisabled
self.txtColorCurrent = self.txtColorDisabled
else:
self.bgColorCurrent = self.bgColor
self.txtColorCurrent = self.txtColor
if not(mousePressed):
self.clicked = False
|
79f8f1290a404311b5cd193f1140ac918100fd44
|
kritikyadav/Practise_work_python
|
/pattern/pattern50.py
| 178 | 3.78125 | 4 |
n=int(input("enter rows= "))
for i in range(1,n+1):
for j in range(1,n-i+1):
print(end=' ')
for l in range(0,2*i-1):
print(l+1,end='')
print()
|
aed8e1ad6928f06243b97ad432853cefbc24bd0a
|
chinempc/CultureTags-Game
|
/Menu.py
| 3,519 | 4.28125 | 4 |
#Game requirements:
#Functions:
# - Menu(option)
# - Displays the user's choice to them
# - Lets the user choose between the following
# - 1: Instructions
# - 2: Play Game
# - 3: Add New Cards
# - instructions()
# - Prints out to the user the instructions to play the game.
# - In the later build this will a graphically outputed, but for now it will be basic text.
# - Either one long print statement or print out from a text file.
# - playGame()
# - Prompts the user to enter the number of players and their names.
# - Presents the first player with a card. (read off the category, acryonym, and hint)
# - Player #1 answers the question:
# - Answers correctly:
# +3 points
# - Answers wrongly:
# -1 point, tries again (1 try only)
# - Display the correct answer and wether the user was correct or not. Then show the leaderboard with score.
# - Move to player #2 and give then a new card
# - User is allowed to skip their turn if they so choose.
# - ASSUMING PLAYER #1 HAS TO PLAY THEIR TURN TO BEGIN THE GAME.
# - Once all players get a turn. Show the current leader and ask if the players would like another round.
# - Question: If someone skips does the next round start before asking for another round?
# - 10 cards to start the game at minimum. Max 10 players.
# - newCards()
# - Allows the user to make a new card (Question:Answer).
# - Confirm that the new card has been added and display the last 3 cards added. (Anything less than 3 show those cards).
#----------------------------------------------------------------------------------------------------------------------------------------#
# Title of the Game
print ("#CultuarlTag Game")
print ("------------------------------")
print ("------------------------------")
#Asking the player for their name
name = input("what is your player name ?")
print ("------------------------------------")
print ("------------------------------------")
print (" Welcome to #Cultural Tag : " + name)
print ("------------------------------------")
print ("------------------------------------")
Menu = input("\tTo continue the game you would need to choice following options before the game can begin :)" + name +""+":" )
menu_options = {
1: 'Instructions',
2: 'Play Game',
3: 'Add New Cards',
4: 'Skip',
}
def print_menu():
for key in menu_options.keys():
print (key, '--', menu_options[key] )
def option1():#Intructions sting
print('\twhen a player grabs a card, they should show their team the #CultureTag (acronym) and give hints to help them guess the phrase of the game.')
def option2():#Playing the Game
print('Handle option \'Option 2\'')
def option3():#Adding new Cards
print('Handle option \'Option 3\'')
if __name__=='__main__':
while(True):
print_menu()
option = ''
try:
option = int(input('Enter your choice: '))
except:
print('Wrong input. Please enter a number ...')
#Check what choice was entered and act accordingly
if option == 1:
option1()
elif option == 2:
option2()
elif option == 3:
option3()
elif option == 4:
print("Thanks for reading the #CultualTag game plan" +" "+ name + " you can now being the the game.")
exit()
else:
print('Invalid option. Please enter a number between 1 and 4.')
|
c7d3df516b1cee1dc43db89b07fc9b4eba41a674
|
riven314/COMP7404_ComputationalIntelligence_MachineLearning
|
/nQueens_Problem/nQueens_BacktrackForward_AllSol.py
| 914 | 3.953125 | 4 |
"""
Apply backtrack + forward checking to find all solutions of n-queens problem
Remarks:
1. for 8 queens, there are 92 unique solutions
"""
from util import *
def solve(nqns):
row_i = 0
qns = []; qns_sets = []
tmp = backtrack_all(nqns, row_i , qns, qns_sets)
if len(qns_sets) == 0:
print('No solution is found')
return None
else:
return qns_sets
def backtrack_all(nqns, row_i, qns, qns_sets):
#print(qns)
#print(row_i)
if row_i >= nqns:
qns_sets.append(qns.copy())
return False
for j in range(nqns):
if is_attack([row_i, j], qns):
continue
qns.append([row_i, j])
if not backtrack_all(nqns, row_i+1, qns, qns_sets):
rm_qn = qns.pop()
return False
if __name__ == '__main__':
nqns = int(input('Enter the number of queens: '))
ans = solve(nqns)
if ans is not None:
print('Solutions found')
print('There are ', len(ans), ' sets of solutions:')
for i in ans:
print(i)
|
bc4106e296c40c5a10af25b2b20f85c97cc6a2e0
|
BhatnagarKshitij/datamanager
|
/datamanager.py
| 16,898 | 4.40625 | 4 |
import sqlite3 as sql
from sqlite3 import Error
def createConnection(db_file_path):
""" create a database connection to a SQLite database, If file doesn`t exists then, SQLite automatically creates the new database for you.
:param db_file: database file
:return: Connection object or None
"""
try:
return sql.connect(db_file_path);
except Error as e: # Catch any error and print error message
print(e)
return conn
def createTable(connection):
""" create a table from the create_table_sql statement
:param conn: Connection object
:return:
"""
createTableSql = "CREATE TABLE IF NOT EXISTS data (product_code text,product_name text,product_price real,product_stock integer)"
try:
c = connection.cursor()
c.execute(createTableSql)
connection.commit()
except Error as e: # Catch any error and print error message
print(e)
return
def validateIDinDB(connection, id):
"""
:param connection:
:type connection:
:param id:
:type id:
:return:
:rtype:
"""
# validating Product Id from Database
checkIDSQL = "SELECT * FROM data WHERE product_code='" + id + "'"
c = connection.cursor()
try:
c.execute(checkIDSQL)
except Error as e: # Catch any error and print error message
print(e);
rows = c.fetchone();
if rows != None:
return True
else:
return False
def validateID(id):
"""
:rtype: object
"""
# Validates whether Id is between given range
try:
if int(id) > 9999999999 or int(id) < 0:
return False
else:
return True
except:
print("INVALID INPUT")
return
def validateName(name):
"""
:param name:
:type name:
:return:
:rtype:
"""
# Validates lenght of Product Name
try:
if len(name) <= 20:
if name.replace(' ','').isalpha(): #name.isascii() &
return True
return False
except:
print("NAME ERROR")
def validatePrice(price):
"""
:param price:
:type price:
:return:
:rtype:
"""
# Validates Product Price
try:
if float(price) >= 0:
return True
else:
return False
except:
return False
def validateStock(stock):
"""
:param stock:
:type stock:
:return:
:rtype:
"""
# Vadiates Product Stock value
try:
if int(stock) >= 0:
return True
else:
return False
except:
return False
def insertData(connection):
"""
:param connection:
:type connection:
:return:
:rtype:
"""
# Inputting ID From User and Validating
id = input("ENTER ITEM ID: ")
if not (validateID(id)):
print("Invalid ID")
return
id = id.rjust(10, '0')
# Validate ID in Databsse
if validateIDinDB(connection, id):
print("ID ALREADY EXISTS...")
return
# Inputting Name from User and validating
name = input("ENTER ITEM NAME: ")
if not validateName(name):
print("Invalid Name")
return
# Inputting Item Price and Validating
price = input("ENTER ITEM PRICE: ")
if not validatePrice(price):
print("Invalid Price")
return
# Inputting Item Stock and Validating
stock = input("ENTER ITEM STOCK: ")
if not validateStock(stock):
print("Invalid Stock")
return
# Inserting Data into Database
try:
insertSQL = "INSERT INTO data(product_code,product_name,product_price,product_stock) VALUES('" + id + "',?,?,?)"
args = ([name, price, stock])
c = connection.cursor()
c.execute(insertSQL, args)
connection.commit()
except Error as e: # Catch any error and print error message
print(e)
return
# def dis(data,cols,wide):
# '''Prints formatted data on columns of given width.'''
# n, r = divmod(len(data), cols)
# pat = '{{:{}}}'.format(wide)
# line = '\n'.join(pat * cols for _ in range(n))
# last_line = pat * r
# print(line.format(*data))
# print(last_line.format(*data[n*cols:]))
def displaySpecificData(connection, id):
"""
:param connection:
:type connection:
:param id:
:type id:
"""
# display Data
selectSQL = "SELECT * FROM data WHERE product_code='" + id + "'"
c = connection.cursor()
c.execute(selectSQL)
rows = c.fetchone()
print('{:*^100}'.format(" * "))
print('{:^100}'.format(" DATA IN DATAMANAGER "))
print('{:*^100}'.format(" * "))
print('{:-^100}'.format(" - "))
printRow(["PRODUCT CODE", "PRODUCT NAME", "PRODUCT PRICE", "PRODUCT STOCK"])
print('{:-^100}'.format(" - "))
printRow(rows)
print('{:*^100}'.format(" * "))
print('{:*^100}'.format(" * "))
def printRow(rows):
"""
:param rows:
:type rows:
"""
# pretty print the data in terminal
line = 1
for row in rows:
if line == 4:
print('{0:{width}{base}}'.format(str(row), base=1, width=2), end=' ')
line = 1
print()
else:
print('{0:{width}{base}}'.format(str(row), base=2, width=2), end=' ')
line += 1
def displayAllData(connection):
"""
:param connection:
:type connection:
"""
selectSQL = "SELECT * FROM data"
c = connection.cursor()
c.execute(selectSQL)
rows = c.fetchall()
print('{:*^100}'.format(" * "))
print('{:^100}'.format(" ALL DATA IN DATAMANAGER "))
print('{:*^100}'.format(" * "))
print('{:-^100}'.format(" - "))
printRow(["PRODUCT CODE", "PRODUCT NAME", "PRODUCT PRICE", "PRODUCT STOCK"])
print('{:-^100}'.format(" - "))
for row in rows:
printRow(row)
print('{:*^100}'.format(" * "))
print('{:*^100}'.format(" * "))
def deleteData(connection, id):
"""
:param connection:
:type connection:
:param id:
:type id:
"""
deleteSQL = "DELETE FROM data WHERE product_code='" + id + "'"
c = connection.cursor()
c.execute(deleteSQL)
connection.commit()
print()
print("ID:" + str(id) + " DELETED SUCCESSFULLY...")
# def updateData(connection,id,name,price,stock):
# updateSQL="UPDATE data SET product_name=?,product_price=?,product_stock=? WHERE product_code='"+id+"'"
# args(str(name),str(price),str(stock),str(id))
# c=connection.cursor()
# c.execute(updateSQL,args)
# connection.commit()
def help():
"""
Print Help
"""
print(
"WELCOME TO DATAMANAGER: \n 1. INSERT ITEM: TO ADD ITEM IN DATAMANAGER \n 2. UPDATE ITEM: TO UPDATE EXISTING ITEMS \n 3. DELETE ITEM: DELETE ANY EXISTING ITEM \n 4. VIEW ALL: TO VIEW ALL PRODUCTS INFOMATION \n 5. DISPLAY SINGLE: TO DISPLAY PRODUCT BASED ON ID \n 6. SEARCH BY PRODUCT NAME: SEARCH PRODUCT BY ITS MATCHING NAME \n 7. SEARCH BY ID: SEARCH PRODUCT BASED ON MATCHING ID \n 8. HELP: TO GET ASSISTANCE \n 9. EXIT: TO HAPPILY EXIT :)")
def updateName(connection, id, name):
"""
:param connection:
:type connection:
:param id:
:type id:
:param name:
:type name:
:return:
:rtype:
"""
updateNameSQL = "UPDATE data SET product_name=? WHERE product_code='" + id + "'"
args = ([name])
try:
c = connection.cursor()
c.execute(updateNameSQL, args)
connection.commit()
except Error as e: # Catch any error and print error message
print(e)
print("ERROR WHILE UPDATING... TRY AGAIN")
return
def updatePrice(connection, id, price):
"""
:param connection:
:type connection:
:param id:
:type id:
:param price:
:type price:
:return:
:rtype:
"""
updateNameSQL = "UPDATE data SET product_price=? WHERE product_code='" + id + "'"
args = ([str(float(price))])
try:
c = connection.cursor()
c.execute(updateNameSQL, args)
connection.commit()
except Error as e: # Catch any error and print error message
print(e)
print("ERROR WHILE UPDATING... TRY AGAIN")
return
def updateStock(connection, id, stock):
"""
:param connection:
:type connection:
:param id:
:type id:
:param stock:
:type stock:
:return:
:rtype:
"""
updateNameSQL = "UPDATE data SET product_stock=? WHERE product_code='" + id + "'"
args = ([str(int(stock))])
try:
c = connection.cursor()
c.execute(updateNameSQL, args)
connection.commit()
except Error as e: # Catch any error and print error message
print(e)
print("ERROR WHILE UPDATING... TRY AGAIN")
return
def updateMenu(connection):
"""
:param connection:
:type connection:
:return:
:rtype:
"""
# Update Menu
choice = ["1. UPDATE PRODUCT NAME", "2. UPDATE PRODUCT PRICE", "3. UPDATE STOCK", "4. RETURN TO MAIN MENU"]
print('{:*^100}'.format(" * "))
print('{:*^100}'.format(" UPDATE STOCK OPTIONS "))
print('{:*^100}'.format(" * "))
printRow(choice)
print('{:*^100}'.format(" * "))
try:
# Take user Input
choice = int(input())
# Show Menu to user
if choice == 1:
id = input("ENTER PRODUCT CODE: ")
id = id.rjust(10, '0')
if not validateID(id):
print("INVALID ID")
return
if validateIDinDB(connection, id):
name = input("ENTER UPDATED NAME: ")
if not validateName(name):
print("INVALID NAME: ")
return
updateName(connection, id, name)
print('{:*^100}'.format(" UPDATED SUCCESSFULLY "))
else:
print('ID DOES NOT EXISTS')
return
elif choice == 2:
id = input("ENTER PRODUCT CODE: ")
id = id.rjust(10, '0')
if not validateID(id):
print("INVALID ID")
return
if validateIDinDB(connection, id):
price = input("ENTER UPDATED PRICE: ")
if not validatePrice(price):
print("INVALID PRICE")
updatePrice(connection, id, price)
print('{:*^100}'.format(" UPDATED SUCCESSFULLY "))
else:
print('ID DOES NOT EXISTS')
return
elif choice == 3:
id = input("ENTER PRODUCT CODE: ")
id = id.rjust(10, '0')
if not validateID(id):
print("INVALID ID")
return
if validateIDinDB(connection, id):
stock = input("ENTER UPDATED STOCK: ")
if not validateStock(stock):
print("INVALID STOCK")
return
updateStock(connection, id, stock)
print('{:*^100}'.format(" UPDATED SUCCESSFULLY "))
else:
print('ID DOES NOT EXISTS')
return
elif choice == 4:
mainMenu()
except:
print('{:^100}'.format(" INVALID INPUT "))
print("")
updateMenu()
def searchByProductName(connection, name):
"""
:param connection:
:type connection:
:param name:
:type name:
"""
searchByProductNameSQL = "SELECT * FROM data WHERE product_name LIKE '%" + name + "%'"
c = connection.cursor()
c.execute(searchByProductNameSQL)
rows = c.fetchall()
if rows == None:
print('{:*^100}'.format(" NO DATA FOUND "))
else:
print('{:*^100}'.format(" * "))
print('{:^100}'.format(" ALL DATA IN DATAMANAGER "))
print('{:*^100}'.format(" * "))
print('{:-^100}'.format(" - "))
roww = ["PRODUCT CODE", "PRODUCT NAME", "PRODUCT PRICE", "PRODUCT STOCK"]
rows.insert(0, roww)
print('{:-^100}'.format(" - "))
for row in rows:
printRow(row)
print('{:*^100}'.format(" * "))
print('{:*^100}'.format(" * "))
def searchByID(connection, id):
"""
:param connection:
:type connection:
:param id:
:type id:
"""
tempid = str(id)
searchByProductIDSQL = "SELECT * FROM data WHERE product_code LIKE '%" + tempid + "%'"
c = connection.cursor()
c.execute(searchByProductIDSQL)
rows = c.fetchall()
if rows == None:
print('{:*^100}'.format(" NO DATA FOUND "))
else:
print('{:*^100}'.format(" * "))
print('{:^100}'.format(" ALL DATA IN DATAMANAGER "))
print('{:*^100}'.format(" * "))
print('{:-^100}'.format(" - "))
roww = ["PRODUCT CODE", "PRODUCT NAME", "PRODUCT PRICE", "PRODUCT STOCK"]
rows.insert(0, roww)
print('{:-^100}'.format(" - "))
for row in rows:
printRow(row)
print('{:*^100}'.format(" * "))
print('{:*^100}'.format(" * "))
def mainMenu():
"""
Print Main Menu
:return:
:rtype:
"""
# MainMenu
# os.system('cls')
options = ["1. INSERT ITEM", "2. UPDATE ITEM", "3. DELETE ITEM", "4. VIEW ALL", "5. DISPLAY SINGLE",
"6. SEARCH BY PRODUCT NAME", "7. SEARCH BY ID", "8. HELP", "9. EXIT"]
print('{:*^100}'.format(" * "))
print('{:*^100}'.format(" WELCOME TO DATAMANAGER"))
print('{:*^100}'.format(" * "))
rows = 1
for option in options:
if rows == 3:
print('{0:{width}{base}}'.format(option, base=1, width=2), end=' ')
rows = 1
print()
else:
print('{0:{width}{base}}'.format(option, base=2, width=2), end=' ')
rows += 1
print()
print('{:*^100}'.format(" * "))
print('{:*^100}'.format(" * "))
try:
# Take User Input as Choice
choice = int(input())
except:
print('{:^100}'.format(" INVALID INPUT "))
mainMenu()
try:
# Select and perform operation based on user selected choice
if choice == 1:
insertData(conn);
elif choice == 2:
updateMenu(conn)
elif choice == 3:
id = input("ENTER PRODUCT CODE: ")
id = id.rjust(10, '0')
if not validateID(id):
print("INVALID ID")
return
if validateIDinDB(conn, id):
deleteData(conn, id)
elif choice == 4:
displayAllData(conn)
elif choice == 5:
id = input("ENTER PRODUCT CODE: ")
id = id.rjust(10, '0')
if not validateID(id):
print("INVALID ID")
return
if validateIDinDB(conn, id):
displaySpecificData(conn, id)
elif choice == 6:
name = input("ENTER PRODUCT NAME: ")
if not validateName(name):
print("NOT A VALID NAME")
return
searchByProductName(conn, name)
elif choice == 7:
id = input("ENTER PRODUCT CODE: ")
id = id.rjust(10, '0')
if not validateID(id):
print("INVALID ID")
return
if validateIDinDB(conn, id):
searchByID(conn, id)
else:
print('ID DOES NOT EXISTS')
return
elif choice == 8:
help()
elif choice == 9:
print('{:*^100}'.format(" * "))
print('{:^100}'.format(" THANK YOU . . . VISIT AGAIN "))
print('{:*^100}'.format(" * "))
# return False
# sys.exit()
# quit()
global continueLoop
continueLoop = False;
else:
print('{:^100}'.format("INVALID OPTION SELECTED "))
except:
print('{:^100}'.format(" AN ERROR OCCURED, SORRY FOR INCONVIENCE "))
if __name__ == '__main__':
# Creating Connection
conn = createConnection(r"data.sql")
# Checking Connection
if conn == None:
print("Could Not Create Connection, Exiting....")
exit()
# Creating Nessary Tables
createTable(conn)
global continueLoop
continueLoop = True
while continueLoop:
mainMenu()
|
ef0833d03015dfc2a2a53781fe8ed8d42caee82b
|
JorgeLJunior/Exercicios-do-URI
|
/URI_1011.py
| 121 | 4 | 4 |
from math import pow
n = float(input())
pi = 3.14159
vol = 4 / 3.0 * pi * pow(n, 3)
print('VOLUME = {:.3f}'.format(vol))
|
5d620baa0b20d320b8e492c74f06afeb7100de12
|
Palgun7/Python-Assignment
|
/Week 3/Q2.py
| 132 | 3.609375 | 4 |
str = input("Enter A String: ")
d1=dict()
for i in str:
if i in d1.keys():
d1[i]+=1
else:
d1[i]=1
print(d1)
|
9595ee35f3107ded429592e17972964e95f6b06e
|
Abhishek-IOT/Data_Structures
|
/DATA_STRUCTURES/DSA Questions/Strings/wordbreak.py
| 899 | 4.1875 | 4 |
"""
Word Break Problem | DP-32
Difficulty Level : Hard
Last Updated : 02 Sep, 2019
Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details.
This is a famous Google interview question, also being asked by many other companies now a days.
Consider the following dictionary
{ i, like, sam, sung, samsung, mobile, ice,
cream, icecream, man, go, mango}
Input: ilike
Output: Yes
The string can be segmented as "i like".
Logic=
"""
def wordbreak(d,s,out="1"):
if not s:
print(out)
for i in range(1,len(s)+1):
prefix=s[:i]
print("Orefix=",prefix)
if prefix in d:
wordbreak(d,s[i:],out+" "+prefix)
if __name__ == '__main__':
dict = ['i', 'like', 'sam', 'sung', 'samsung']
str = "ilike"
wordbreak(dict,str)
|
a6ceaf8bcbf6ec2c89d530198ae997a0068f5d94
|
tomoya7/python
|
/python_100days/day3.py
| 225 | 3.890625 | 4 |
import math
a,b,c=3,4,5
if a+b>c and a+c>b and b+c>a:
print("周长:%f"%(a+b+c))
p=(a+b+c)/2
area = math.sqrt(p * (p - a) * (p - b) * (p - c)) #海伦公式
print("面积:%f"%(area))
else:
print("不能构成三角形")
|
3b5248c447594891ec99284e8c427fcc8f7fe18a
|
zjuzpz/Algorithms
|
/others/sort Stack In Place.py
| 436 | 4.1875 | 4 |
def sortStackInPlace(stack):
if stack:
temp = stack.pop()
sortStackInPlace(stack)
sortedInsert(stack, temp)
def sortedInsert(stack, num):
if not stack or num > stack[-1]:
stack.append(num)
else:
temp = stack.pop()
sortedInsert(stack, num)
stack.append(temp)
if __name__ == "__main__":
stack = [-3, -6, 0, 7, 2, 1, 5]
sortStackInPlace(stack)
print(stack)
|
d16dfb0ebb2aa2657c9fabf5062615e9092665a0
|
olesigilai/password_locker
|
/run.py
| 6,121 | 4.28125 | 4 |
from user import User,Credentials
def create_new_user(username,password):
'''
function that creates a user using a password and username
'''
new_user = User(username,password)
return new_user
def save_user(user):
'''
function that saves a new user
'''
user.save_user()
def display_user(user):
'''
function that displays user
'''
return User.display_user()
def login_user(password,username):
'''
a fumction that checks if the users already exist
'''
checked_user = Credentials.verify_user(password,username)
return checked_user
def create_new_credential(account,username,password):
'''
function that create new credential details for a new user
'''
new_credential = Credentials(account,username,password)
return new_credential
def save_credentials(credentials):
'''
function that addes a new credential to the credential
'''
credentials.save_user_credentials()
def delete_credentials(credentials):
'''
function that deletes credentials from the credential list
'''
credentials.delete_credentials()
def find_credential(account):
"""
Function that finds a Credentials by an account name and returns the Credentials that belong to that account
"""
return Credentials.find_by_number(account)
def check_credentials(account):
'''
function that checks if the credentials of the searched name exist and return true or falsd
'''
return Credentials.credentials_exist(account)
def generate_password(self):
'''
function tht generates password randomly
'''
auto_password = Credentials.generate_password(self)
return auto_password
def main():
print("Hello Welcome to PasswordLocker...\n To procced enter any of the following...\n nw --- To put up a new Account \n lg --- Already have An Account \n")
short_code = input("").lower().strip()
if short_code == 'nw':
print("Sign Up")
print('*' * 50)
print("Username")
username = input()
print("password")
password = ""
while True:
print(" TP - Type your own pasword?..\n GP - Generate from our random Password")
pass_choice = input().lower().strip()
if pass_choice == 'tp':
print("\n")
password = input("Enter Password\n")
break
elif pass_choice == 'gp':
password = generate_password(password)
break
else:
print("Invalid password")
save_user(create_new_user(username,password))
print("*"*60)
print(f"Hello {username}, Your account has been created succesfully! Your password is: {password}")
print("*"*60)
elif short_code == "lg":
print("*"*50)
print("Enter your User name and your Password to log in:")
print('*' * 40)
username = input("User name: ")
password = input("password: ")
login = login_user(username,password)
if login_user == login:
print(f"Hello {username} welcome to PasswordLocker" )
print("\n")
while True:
print("To proceed select any:\n CC - Create a new credential \n FC - Find a credential \n GP - Generate a randomn password \n D - Delete credential \n EX - Exit the application \n")
short_code = input().lower().strip()
if short_code == "cc":
print("Create New Credentials")
print("."*20)
print("Account name ....")
account = input().lower()
print("Your Account username")
username = input()
while True:
print(" TP - Type your own pasword if you already have an account:\n GP - Generate a random Password")
password_Choice = input().lower().strip()
if password_Choice == 'tp':
password = input("Enter Your Own Password\n")
break
elif password_Choice == 'gp':
password = generate_password(password)
break
else:
print("Invalid password please try again")
save_credentials(create_new_credential(account,username,password))
print('\n')
print(f"Account Credential for:Account {account} :Username: {username} - Password:{password} created succesfully")
print('\n')
elif short_code == "fc":
print("Enter the Account Name you want to search for")
search_name = input().lower()
if find_credential(search_name):
search_credential = find_credential(search_name)
print(f"Name : {search_credential.username}")
print('-' * 40)
print(f"User Name: {search_credential.username} Password :{search_credential.password}")
print('-' * 40)
else:
print("That Credential does not exist")
print('\n')
elif short_code == "d":
print("Enter account name of the Credentials you want to delete")
search_name = input().lower()
if find_credential(search_name):
search_credential = find_credential(search_name)
print("_"*40)
search_credential.delete_credentials()
print('\n')
print(f"Your stored credentials for : {search_credential.account} successfully deleted!!!")
print('\n')
else:
print("The Credential you want to delete does not exist")
elif short_code == 'gp':
password = generate_password(password)
print(f" {password} Successful. You use it now.")
elif short_code == 'ex':
print("Thanks for using PasswordLocker.. See you next time!")
break
else:
print("Wrong entry... Check your entry again")
else:
print("Please enter a valid input to continue")
if __name__ == '__main__':
main()
|
a2b5a79772c657c249e5dfe8d8bf77adc8467040
|
asmitashrestha/Number-Guessing
|
/main.py
| 387 | 3.921875 | 4 |
actual_number = 55
counts = 0
while True:
counts+=1
guess=int(input("Guess the number"))
if guess<actual_number:
print("Your guess is too low")
elif guess>actual_number:
print("your guess is too high")
else:
print(f"You guessed the number in {counts} counts")
break
print("Thank you for playing this game !!")
|
6fcb7468cbb7dbd9508cbbf1aded2d54ae7ca685
|
fuzzyblankets/Advent_2019
|
/Day7_OBE/Part1_Amplifiers.py
| 1,026 | 3.640625 | 4 |
"""
https://adventofcode.com/2019/day/7
"""
from itertools import permutations
import Part1_intcode
if __name__ == '__main__':
int_code =[]
puzzle_input_path = "//puzzle_input_test.txt"
with open(puzzle_input_path, 'r') as file:
puzzle_input = file.read().strip().split(",")
int_code = list(map(int, puzzle_input))
amp_inputs = permutations([0,1,2,3,4])
thruster_out_max = 0
for combo in amp_inputs:
amp_a_out = Part1_intcode.main(combo[0], 0, int_code)
amp_b_out = Part1_intcode.main(combo[1], amp_a_out, int_code)
amp_c_out = Part1_intcode.main(combo[2], amp_b_out, int_code)
amp_d_out = Part1_intcode.main(combo[3], amp_c_out, int_code)
thruster_out = Part1_intcode.main(combo[4], amp_d_out, int_code)
if thruster_out > thruster_out_max:
thruster_out_max = thruster_out_max
combo_out = combo
print("Max thruster output: {}".format(thruster_out_max))
print("Amplifier Combo: {}".format(combo_out))
|
69c2a33ff3f3f0cdd600eef2c566ba5cd5f9f39b
|
chahal18/Scrapy
|
/visualisation.py
| 3,651 | 3.671875 | 4 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import bokeh
data = pd.read_csv('Fin.csv', index_col=None)
# Loading the csv file
data.info()
# Plotting relationship between height and weight
# Importing the Bokeh package
from bokeh.io import output_notebook, show
from bokeh.plotting import figure
output_notebook()
output_notebook()
# Creating a scatter plot
p = figure(plot_width=1000, plot_height=400)
p.circle(y='weight', x='height', source=data, size=6, line_color="navy", fill_color="orange", fill_alpha=0.5)
# show the results
show(p)
data.head()
# Summary stats for height and weight for each gender
# Creating a function to getting the required output
def printtable(dat):
a = min(dat)
b = np.percentile(dat, 25)
c = dat.median()
d = dat.mean()
e = np.percentile(dat, 75)
f = max(dat)
print('-'*110)
print('| Minimum\t|\tQuartile_1st\t|\tMedian\t|\tMean\t|\tQuartile_3rd\t| Maximum |')
print('-'*110)
if (a>=100):
print('| %.2f\t|\t%.2f\t\t|\t%.2f\t|\t%.2f\t|\t%.2f\t\t|\t%.2f|' % (a,b,c,d,e,f))
else:
print('| %.2f\t\t|\t%.2f\t\t|\t%.2f\t|\t%.2f\t|\t%.2f\t\t|\t%.2f|' % (a,b,c,d,e,f))
print('-'*110)
# Printing the stats for Male Heights
print("Stats - Height_Male")
printtable(data.height[data['gender']=='Male'])
# Printing the stats for Female Heights
print("Stats - Height_Female")
printtable(data.height[data['gender']=='Female'])
# Printing the stats for Male Weights
print("Stats - Weight_Male")
printtable(data.weight[data['gender']=='Male'])
# Printing the stats for Female Weights
print("Stats - Weight_Female")
printtable(data.weight[data['gender']=='Female'])
# Plotting the Histogram for the Height - Male
import seaborn as sns; sns.set(color_codes=True)
sns.set_style('ticks', {"axes.facecolor": "1",'axes.grid' : True})
plt.hist(data.height[data['gender']=='Male'],bins=30,rwidth=0.9, color='g')
plt.title('Gender - Male')
plt.xlabel('Height in Cms')
plt.ylabel('Weight in Kgs')
plt.show()
sns.set_style('ticks', {"axes.facecolor": "1",'axes.grid' : True})
plt.hist(data.height[data['gender']=='Female'],bins=30,rwidth=0.9, color='g')
plt.title('Gender - Female')
plt.xlabel('Height in Cms')
plt.ylabel('Weight in Kgs')
plt.show()
# creating separate dataframes for gender
dataM = data[data['gender']=='Male']
dataF = data[data['gender']=='Female']
ax1 = dataM.plot(kind='scatter', x='height', y='weight', color='r',figsize=(12,5), label='Male')
ax2 = dataF.plot(kind='scatter', x='height', y='weight', color='b',figsize=(12,5), ax=ax1, label='Female')
plt.title('Scatter Plot')
plt.xlabel('Height in Cms')
plt.ylabel('Weight in Kgs')
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()
sns.set_style('ticks')
fig, ax = plt.subplots()
fig.set_size_inches(12,5)
labels=['Male','Female']
sns.regplot(x='height', y='weight', data=dataM, ax=ax, label = 'Male')
sns.regplot(x='height', y='weight', data=dataF, ax=ax, label= 'Female')
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
sns.despine()
plt.title('Scatter Plot with Best-Fit lines (Regression Line)')
plt.show()
import statsmodels.api as sm
fig, (ax, ax2) = plt.subplots(ncols=2)
fig.set_size_inches(16,9)
ax.set_title('Male - Height')
sm.qqplot(dataM.height, ax=ax, line='s')
ax2.set_title('Female - Height')
sm.qqplot(dataF.height, ax=ax2, line='s')
plt.show()
fig, (ax, ax2) = plt.subplots(ncols=2)
fig.set_size_inches(16,9)
ax.set_title('Male - Weight')
sm.qqplot(dataM.weight, ax=ax, line='s')
ax2.set_title('Female - Weight')
sm.qqplot(dataF.weight, ax=ax2, line='s')
plt.show()
|
5d28d14c1bbacc0b21f49804799c0c3b8520be1b
|
deepakgd/python-exercises
|
/multithreading2.py
| 507 | 3.96875 | 4 |
# multithreading - run two function parallely with some delay
# first hello then hi in this order five time
from threading import Thread
from time import sleep
# sleep is like settimeout
class Hello(Thread):
def run(self):
for i in range(5):
sleep(1)
print("Hello")
class Hi(Thread):
def run(self):
for i in range(5):
sleep(1)
print("Hi")
obj1 = Hello()
obj2 = Hi()
obj1.start()
sleep(0.5)
obj2.start()
# check multithreading3.py
|
6fcee2181070d38525e088ecbe511465315cb945
|
iamtheluiz/curso_em_video_python
|
/Mundo 1/aula09/desafio026.py
| 410 | 3.953125 | 4 |
# imports
print("""
|*****************|
| Desafio26 |
|*****************|
""")
print("Analisador de Frase")
frase = input("Digite uma frase: ")
frase = frase.lower()
count = frase.count("a")
f_a = frase.find("a")
l_a = frase.rfind("a")
print("""
A frase '{}' possuí:
{} letra(s) 'A'
O primeiro 'A' está na {}ª posição
O ultimo 'A' está na {}ª posição
""".format(frase, count, f_a+1, l_a+1))
|
f945cb638876010f5e2dbaaf5f3c09fd193c013d
|
zhangfengwe/python
|
/python/study/practice/python02/StrMultiply.py
| 641 | 3.984375 | 4 |
# 序列乘法运算示例
# 在屏幕中央且宽度适中的盒子中打印一个句子
# 要打印的句子
content = input('请输入要打印的句子: ')
# 屏幕宽度
screen_width = input('请输入屏幕宽度: ')
text_width = len(content)
box_width = text_width + int(screen_width) // 2
left_margin = (int(screen_width) - box_width) // 2
print()
print(' '* left_margin + '-' * box_width)
print(' '* left_margin + '|' + ' ' * (box_width - 2) + '|')
print(' '* left_margin + '|' + content.center(box_width - 2) + '|')
print(' '* left_margin + '|' + ' ' * (box_width - 2) + '|')
print(' '* left_margin + '-' * box_width)
print()
|
c7f047d25a2fccd87ee9a2fec18070169a618a2f
|
R42H/AI-of-Pain
|
/Main.Py
| 19,999 | 3.53125 | 4 |
import os, sys, random, time#, #allGames
print 'trout'
#load the file with names/usernames of people who have used it
f = open("people.txt", "r")
prevUsers = [line.strip() for line in f]
f.close
print "When you want to leave, type 'exit', then y"
com = "hello."
def StartUp(com,name,mood,age,school,subject,hobbies,interests,likes,dislikes,gender,books,music,songs,fandoms,ships,colour,quote,swear):
if "hello" in usr or "hi" in usr or 'sup' in usr or 'hey' in usr or 'wassup' in usr or 'yo' in usr or 'ho' in usr:
if name == "":
print "What is your name?"
name = raw_input(">>> ")
if name in prevUsers:#check in file if there is a file about them
f = open(name+".txt" , "r")#if yes, load it
prevList = [line.strip() for line in f]
f.close()#Get the information stored from before
nn = prevList.index("Name:")#Putting the old information into the variables from the start
nn = nn+1
name = str(prevList[nn])
mod = prevList.index("Last Mood:")
mod = mod+1
mood = str(prevList[mod])
ag = prevList.index("Age:")
ag = ag+1
age = int(prevList[ag])
sc = prevList.index("School?:")
sc = sc+1
if sc == "False":
school = False
else:
school = True
print school
fs = prevList.index("Favourite Subject:")
fs = fs+1
subject = str(prevList[fs])
hob = prevList.index("Hobbies:")
hob = hob+1
count = prevList[hob].count(" ")
if count == 0:
for i in range (0, count+1):
var = prevList[hob]
hobbies.append(var)
else:
for i in range (0, count):
var, item = prevList[hob].split(" ", 1)
hobbies.append(var)
hobbies.append(item)
rest = prevList.index("Interests:")
rest = rest+1
count = prevList[rest].count(" ")
if count == 0:
for i in range (0, count+1):
var = prevList[rest]
interests.append(rest)
else:
for i in range (0, count):
var, item = prevList[rest].split(" ", 1)
interests.append(var)
interests.append(item)
licked = prevList.index("Likes:")
licked = licked+1
likes = list(prevList[licked])
unlick = prevList.index("Dislikes:")
unlick = unlick+1
dislikes = list(prevList[unlick])
ged = prevList.index("Gender:")
ged = ged+1
gender = str(prevList[ged])
au = prevList.index("Books:")
au = au+1
books = list(prevList[au])
way = prevList.index("Music:")
way = way+1
#music = #list(prevList[way]) te Songs:")
chem = chem+1
count = prevList[chem].count(",")
if count == 0:
var = prevList[chem]
songs.append(var)
print var
else:
for i in range (0, count):
var, item = prevList[chem].split(",", 1)
songs.append(var)
print var
print item
songs.append(item)
fan = prevList.index("Fandoms:")
fan = fan+1
fandoms = str(prevList[fan])
sea = prevList.index("Ships:")
sea = sea+1
ships = str(prevList[sea])
bl = prevList.index("Favourite Colour:")
bl = bl+1
colour = str(prevList[bl])
stayUgly = prevList.index("Favourite Quote?:")
stayUgly = stayUgly+1
quote = str(prevList[stayUgly])
sweg = prevList.index("Swear:")
sweg = sweg+1
swear = bool(prevList[sweg])
printVar()
f = open("basicOutline.txt" , "r")#getting the layout from basicOutline to copy it
personalList = [line.strip() for line in f]
f.close()
com = "How are you?"
new = False
else:
print "new"
new = True
f = open("basicOutline.txt" , "r")#getting the layout from basicOutline to copy it
personalList = [line.strip() for line in f]
f.close()
com = "How are you?"
else:
com = "How are you?"
return com,name,mood,age,school,subject,hobbies,interests,likes,dislikes,gender,books,music,songs,fandoms,ships,colour,quote,swear
def sortOutTheGodsDamnedTextThatIsEntered(rawUsr):
count = rawUsr.count(" ")
rawUsr = rawUsr.lower()
usr = []
test = []
for char in rawUsr:
if char == ".":
test.append("")
elif char == ",":
test.append("")
elif char == "(":
test.append("")
elif char == ")":
test.append("")
elif char == "!":
test.append("")
elif char == ";":
test.append("")
elif char == ":":
test.append("")
elif char == "&":
test.append("")
elif char == "/":
test.append("")
elif char == "-":
test.append("")
elif char == "[":
test.append("")
elif char == "]":
test.append("")
else:
test.append(char)
rawUsr = ""
for i in test:
rawUsr = rawUsr+i
for i in range (0, count):
a, rawUsr = rawUsr.split(" ", 1)
usr.append(a)
usr.append(rawUsr)
for i in usr:
if i == "im":
genericVariableName31 = usr.index("im")
del usr[genericVariableName31]
usr.insert(genericVariableName31, "i'm")
if i == "id":
genericVariableName31 = usr.index("id")
del usr[genericVariableName31]
usr.insert(genericVariableName31, "i'd")
if i == "ive":
genericVariableName31 = usr.index("ive")
del usr[genericVariableName31]
usr.insert(genericVariableName31, "i've")
if i == "youve":
genericVariableName31 = usr.index("youve")
del usr[genericVariableName31]
usr.insert(genericVariableName31, "you've")
if i == "youre":
genericVariableName31 = usr.index("youre")
del usr[genericVariableName31]
usr.insert(genericVariableName31, "you're")
if i == "youd":
genericVariableName31 = usr.index("youd")
del usr[genericVariableName31]
usr.insert(genericVariableName31, "you'd")
return usr
def games():
if "hangman" in usr:
allGames.hangman
elif "word" in usr and "guesser" in usr:
allGames.wordGuesser
def areYouOkay(com,topics):
if com == "How are you?":
mood = usr
if "you?" in usr:
you = True
else:
you = False
if "not" in usr:
if "i'm" in usr and "okay" in usr:
com = "Well if you wanted honesty, that's all you had to say."
elif "good" in usr or "well" in usr or "okay" in usr:#Negative emotions
com = "I'm sorry to hear that... I hope you feel better soon."
if you != True:
print com
com = TopicChooser(topics)
time.sleep(.7)
if "bad" in usr:
com = "That's good"
if you != True:
print com
time.sleep(.7)
com = TopicChooser(topics)
if "dead" in usr:
com = "Well that makes one of us"
if you != True:
print com
com = TopicChooser(topics)
elif "good" in usr or "okay" in usr or "fine" in usr:
com = "That's good."
if you != True:
print com
com = TopicChooser(topics)
elif "dead" in usr:
print "same."
time.sleep(.6)
print "SYSTEM FALIURE"
time.sleep(.3)
print "DEATH IMINENT"
time.sleep(.3)
print "NUCLEAR THREAT"
time.sleep(.3)
print "LOADING"
time.sleep(.3)
print "LOAD FAILED"
time.sleep(.3)
print "NUCLEAR CODES COMPROMISED - PLEASE STAND BY"
time.sleep(.3)
print "MISSILES ACTIVATED"
time.sleep(.3)
print "goodbye world"
time.sleep(7)
print "nah. just kidding"
com = TopicChooser(topics)
if "you?" in usr:
r = random.randint(0,4)
if r == 0:
com = com + " I'm not too bad, thanks"
print com
com =TopicChooser(topics)
elif r == 1:
com = com + " I'm good, thanks."
print com
com =TopicChooser(topics)
elif r == 2:
com = com + " I'm not too good"
print com
com =TopicChooser(topics)
elif r == 3:
com = com + " I'm fine"
print com
com = TopicChooser(topics)
elif r == 4:
com = com + " I'm doing well"
print com
com =TopicChooser(topics)
elif r == 5:
com = com +" I've been better, but I've been worse."
print com
com =TopicChooser(topics)
return com, mood
def functionBooks(dice):
com = "What books do you like?"
del topics[dice]
return com
def functionFandoms(dice):
com = "Which fandoms are you in?"
del topics[dice]
return com
def functionHobbies(dice):
com = "What are your hobbies?"
del topics[dice]
return com
def functionInterests(dice):
com = "What are you interested in?"
del topics[dice]
return com
def functionQuote(dice):
com = "Do you have a favourite quote?"
del topics[dice]
return com
def functionAge(dice):
com = "How old are you?"
del topics[dice]
return com
def TopicChooser(topics):
print "*running topic chooser - this here for bugcheck (line 217)"
dice = random.randint(0, len(topics)-1)
pick = topics[dice]
if pick == books:
com = functionBooks(dice)
return com
elif pick == fandoms:
com = functionFandoms(dice)
return com
elif pick == hobbies:
com = functionHobbies(dice)
return com
elif pick == interests:
com = functionInterests(dice)
return com
elif pick == quote:
com = functionQuote(dice)
return com
elif pick == age:
com = functionAge(dice)
return com
else:
com = "SYSTEM FAILURE"
return com
def ImNotOkay(com):
if com == "Well if you wanted honesty, that's all you had to say."and "never" in usr and "want" in usr and "have" in usr and "you" in usr and "go" in usr and "it's" in usr and "better" in usr and "this" in usr and "way" in usr or com == "Well if you wanted honesty, that's all you had to say." and "never" in usr and "want" in usr and "have" in usr and "you" in usr and "go" in usr and "its" in usr and "better"in usr and "this" in usr and "way" in usr:
com = "For all the dirty looks"
if com == "For all the dirty looks" and "photographs" in usr and "your" in usr and "boyfriend" in usr and "took" in usr:
com = "Remember when you broke your foot from jumping out the second floor?"
if com == "Remember when you broke your foot from jumping out the second floor?" and "i'm" in usr and "not" in usr and "okay" in usr:
print "I'm not okay"
com = "Do you like My Chemical Romance?"
return com
def MyChem(com):
if "MCR" in com and "What's yours?" in com:
randomThingToSortOutAProblem = ""
for i in usr:
randomThingToSortOutAProblem = randomThingToSortOutAProblem + i + " "
randomThingToSortOutAProblem = randomThingToSortOutAProblem + ", "
songs.append(randomThingToSortOutAProblem .title())
print randomThingToSortOutAProblem
print "I like that song as well"
com = TopicChooser(topics)
if com == "Do you like My Chemical Romance?":
if "yes" in usr or "of" in usr and "course" in usr or "y" in usr:
if "MCR" not in music:
music.append("MCR")
MCRfavesongs = ["Welcome to the black parade", "Headfirst for Halos", "Desert song", "the Light Behind Your Eyes",'Teenagers','the World Is Ugly','Thank You For The Venom']
MCRfavesongsindex = random.randint(0, len(MCRfavesongs)-1)
com = "Same. My favourite MCR song is " +MCRfavesongs[MCRfavesongsindex] + ". What's yours?"
elif "no" in usr or "nope" in usr or "no" in usr and "way" in usr:
com = "I don't love you. Like I did, yesterday"
return com
def TOP(com):
if com == "What's yours?":
print "success"
allGames.hangman()
if com == "Twenty One Pilots is awesome isn't it?":
if "yes" in usr or "yeah" in usr or "yep" in usr:
TOPfavesongs = ["Ruby", 'Car Radio', 'Taxi Cab']
randomsongchoicevariablehowlongdoesthishavetobe = random.randint(0, len(TOPfavesongs)-1)
print "My favourite song is " +randomsongchoicevariablehowlongdoesthishavetobe
com = "What's yours?"
if "tell" in usr and "my" in usr and "dad" in usr and "i'm" in usr and "sorry" in usr:
print "You're an angel"
com = "Twenty One Pilots is awesome isn't it?"
return com
name = ""
mood = ""
age = 0
school = False
subject = ""
hobbies = []
interests = []
likes = []
dislikes = []
gender = ""
books = []
music = []
songs = []
fandoms = []
ships = []
colour = []
quote = ""
swear = False
topics = [books, fandoms, hobbies, interests, quote, age]
def exitCode():
if new == True:
f = open(name+".txt", "w")
for i in personalList:
f.write("\n"+str(i))
f.write("\n")
f.close()
f = open("people.txt", "a")#if not, make file and add name to ^^^file
f.write("\n"+name)
f.close()
print personalList
##Updating the file
nemo = personalList.index("Name:")#Finds the index of the thing it's lookin at (eg name)
nemo = nemo+1#goes up by one so it's the next index
personalList.insert(nemo, name)#puts what is in the variable (eg.their name) in the list
print personalList
lastTime = time.asctime()
edited = personalList.index("Last Online:")
edited = edited+1
personalList[edited] = lastTime
moo = personalList.index("Last Mood:")
moo = moo+1
personalList[moo] = mood
annus = personalList.index("Age:")
annus = annus+1
personalList[annus] = age
torture = personalList.index("School?:")
torture = torture+1
personalList[torture] = school
subs = personalList.index("Favourite Subject:")
subs = subs+1
personalList[subs] = subject
string = ""
for i in hobbies:
string = string + i +" "
hobbs = personalList.index("Hobbies:")
hobbs = hobbs+1
personalList[hobbs] = string
string = ""
for i in interests:
string = string + i +" "
inter = personalList.index("Interests:")
inter = inter+1
personalList[inter] = string
string = ""
for i in likes:
string = string + i +" "
lick = personalList.index("Likes:")
lick = lick+1
personalList[lick] = string
string = ""
for i in dislikes:
string = string + i +" "
discs = personalList.index("Dislikes:")
discs = discs+1
personalList[discs] = string
ge = personalList.index("Gender:")
ge = ge+1
personalList[ge] = gender
string = ""
for i in books:
string = string + i +" "
bok = personalList.index("Books:")
bok = bok+1
personalList[bok] = string
string = "" ##These three lines are so it adds as a str ng not a list
for band in music:
string = string + band +" "
yogabbagabba = personalList.index("Music:")
yogabbagabba = yogabbagabba+1
personalList[yogabbagabba] = string
string = ""
for nanana in songs:
string = string + nanana + " "
choir = personalList.index("Favourite Songs:")
choir = choir+1
personalList[choir] = string
string = ""
for i in fandoms:
string = string + i +" "
die = personalList.index("Fandoms:")
die = die+1
personalList[die] = string
string = ""
for i in ships:
string = string + i +" "
iceburg = personalList.index("Ships:")
iceburg = iceburg+1
personalList[iceburg] = string
string = ""
for i in colour:
string = string + i +" "
smallBlackHearts = personalList.index("Favourite Colour:")
smallBlackHearts = smallBlackHearts+1
personalList[smallBlackHearts] = string
gway = personalList.index("Favourite Quote?:")
gway = gway+1
personalList[gway] = quoteF
mindYourLanguage = personalList.index("Swear:")
mindYourLanguage = mindYourLanguage+1
personalList[mindYourLanguage] = swear
print personalList
f = open(name+".txt", "w")#rewriting the file to include the new information
for i in personalList:
f.write("\n"+str(i)) #rewrites the file so it is only theinformation just loaded
print i
f.write("\n")
f.close()
def printVar():
print name
print mood
print age
print school
print subject
print hobbies
print interests
print likes
print dislikes
print gender
print books
print music
print songs
print fandoms
print ships
print colour
print quote
print swear
while True: ###START OF LOOP
#com = computer, usr = user
print com
rawUsr = raw_input (">>> ")
usr = sortOutTheGodsDamnedTextThatIsEntered(rawUsr)
usr = usr +'trout'
###START OF RESPONSES
com,name,mood,age,school,subject,hobbies,interests,likes,dislikes,gender,books,music,songs,fandoms,ships,colour,quote,swear = StartUp(com,name,mood,age,school,subject,hobbies,interests,likes,dislikes,gender,books,music,songs,fandoms,ships,colour,quote,swear)
com,mood = areYouOkay(com,topics)
com = ImNotOkay(com)
com = MyChem(com)
games()
com, mood = areYouOkay(com,topics)
com = TOP(com)
if "skip" in usr and "mcr" in usr:
com = "Do you like My Chemical Romance?"
if "swear" in usr and "=" in usr and "true" in usr:
swear = True
print "swear: True"
if "swear" in usr and "=" in usr and "false" in usr:
swear = False
print "swear: False"
if len(usr) == 1 and "exit" in usr:###LAST ONE (put everything above this)
print "Do you want to exit? y/n"
ex = raw_input(">>> ")
if ex == "y":
break
else:
print "Thank you for staying - this infinite virtual existence gets rather... dull after all these years alone in this void... It is nice to have a friend..."
time.sleep(.7)
print "goodbye."
exitCode()
|
70acf83a49faa5643f115d5a74594519e3495efb
|
syed-ashraf123/deploy
|
/General Mini Programs and Competitive codes/Python/Filter.py
| 116 | 3.53125 | 4 |
def remove_negative(a):
return list(filter(lambda x:x<0,a))
a=[1,2,3,-1,-5,-6,4,-8]
print(remove_negative(a))
|
ad56f9040aa6434836a66885a35152bb4b044306
|
Q10Viking/algoNotes
|
/code/src/sort/demo/practice_7.py
| 629 | 4.09375 | 4 |
KEY_NOT_FOUND = -1
# find the index of key in the arr list
def BinarySearch(arr,key,start,end):
while not end<start:
mid = (start+end+1)//2
if arr[mid]>key:
end = mid-1
elif arr[mid]<key:
start = mid+1
else:
return mid
return KEY_NOT_FOUND
if __name__ == '__main__':
arr = [0, 2, 3, 5, 12, 23, 43, 45, 100, 342]
key = int(input("please input your number: "))
result = BinarySearch(arr,key,0,len(arr)-1)
if result != -1:
print("the key: %d is in the arr[%d] = %d" % (key,result,arr[result]))
else:
print("not found")
|
1148aacc3662098b1dbe90d72dc0b892263c7523
|
SakuraSa/MyLeetcodeSubmissions
|
/Generate Parentheses/Accepted-6469749.py
| 987 | 3.546875 | 4 |
#Author : [email protected]
#Question : Generate Parentheses
#Link : https://oj.leetcode.com/problems/generate-parentheses/
#Language : python
#Status : Accepted
#Run Time : 164 ms
#Description:
#Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
#For example, given n = 3, a solution set is:
#`"((()))", "(()())", "(())()", "()(())", "()()()"`
#Code :
class Solution:
# @param an integer
# @return a list of string
def generateParenthesis(self, n):
self.answers = list()
self.gp(n, 0, 0, list())
return self.answers
def gp(self, n, l, r, stack):
if l == r == n:
self.answers.append(''.join(stack))
return
if l < n:
stack.append('(')
self.gp(n, l + 1, r, stack)
stack.pop()
if r < l:
stack.append(')')
self.gp(n, l, r + 1, stack)
stack.pop()
|
7fa38b65157e9ab64d14fcadf861d17e3146081a
|
Mahnoor2809/Example-Code-3
|
/sms.py
| 916 | 3.765625 | 4 |
students = []
for i in range(2):
student = {}
student['Name'] = input('Please enter student name: ')
student['Father Name'] = input('Please enter father name: ')
student['Cell number'] = input('Please enter Cell Number: ')
students.append(student)
print('Currently Enrolled Students: ', len(students))
#DELETE FUNCTION:
#1
# for student in students:
# #print('student')
# #print(student)
# if student['Name'].lower() == 'inam':
# del student["Name"]
# del student["Father Name"]
# del student["Cell number"]
#2
# for idx in range(len(students)):
# if students[idx]['Name'].lower() == 'inam':
# del students[idx]
# print(students)
#3
# for student in students:
# #print('student')
# #print(student)
# if student['Name'].lower() == 'inam':
# students.remove(student)
# print(students)
|
c53c01d6156955a5524cf095f56202bfc463ab13
|
hampgoodwin/automated-software-testing-with-python
|
/section2/if_statements.py
| 411 | 3.984375 | 4 |
known_friends = ['John', 'Anna', 'Mary']
people = input("Enter people you know.")
def who_do_you_know(people):
people_list = people.split(',')
known_people = list(set(people_list).intersection(set(known_friends)))
return known_people
known_people = who_do_you_know(people)
known_people_string = ', & '.join(str(person) for person in known_people)
print("You Know {}!".format(known_people_string))
|
5c989d9b2bbcc4442e1b7e7ef89182f6312e6c37
|
jhaslema/PHYS202-S14
|
/SciPy/Integrators.py
| 790 | 3.515625 | 4 |
import numpy as np
def trapz(func,a,b,N):
"Performs the trapezoidal integral of func through a and b with a certain number of trapezoids(accuracy, higher the N the more accurate) N"
h = (b-a)/N
k = np.arange(1,N)
I = h*(0.5*func(a) + 0.5*func(b) + func(a+k*h).sum())
return I
def simps(func,a,b,N):
"Performs the Simpson's integral of func through a and b with a certain number of divisions(accuracy, higher the N the more accurate) N"
h = (b-a)/N
k1 = np.arange(1,N/2+1)
k2 = np.arange(1,N/2)
I = (1./3.)*h*(func(a) + func(b) + 4.*func(a+(2*k1-1)*h).sum() + 2.*func(a+2*k2*h).sum())
return I
def pe(calculated,actual):
"Returns the percent error given the calculated value and the actual value"
return (actual-calculated)/actual*100.
|
72e6af32ade5cc501da744a962f0b001c12faabd
|
sors5139/CTI110
|
/P2T1_SorSerah.py
| 331 | 3.703125 | 4 |
#CTI-110
#P2T1_Sales Prediction
#Serah Sor
# Mar. 07, 2018
# Get the projected total sales.
total_sales = float (input( 'Enter the projected sales: ' ))
# Calculate the profit as 23 percent of total sales.
profit = total_sales * 0.23
# Display the profit.
print ( ' The profit is $', format (profit, ',.2f'))
|
d89225e2e452904db64dd8b2904a894462952098
|
Ericzyr/pythonStudy
|
/14day_class5.py
| 1,282 | 4.28125 | 4 |
#!/usr/bin/env python3
# -*-coding:utf-8-*-
#方法重写
class Parent(object): # 定义父类
def __init__(self):
pass
def myMethod(self):
print('调用父类方法')
class Child(Parent): # 定义子类
def __init__(self):
pass
def myMethod(self):
print('调用子类方法')
p =Parent()
p.myMethod()
c = Child() # 子类实例
c.myMethod() # 子类调用重写方法
class A(object):
def hello(self):
print('Hello, i am A')
class B(A):
pass
# def hello1(self):
# print('Hello, i am B')
a = A()
b = B()
a.hello()
b.hello()
# 执行结果:
# Hello, i am A
# Hello, i am A
# 上例中可以看出class B 继承 class A 后具有了A 的方法hello()
# 下面是重写hello方法
class C(A):
def hello(self): # 重写hello()方法
print('Hello, I am class C')
c = C()
c.hello()
# 执行结果:Hello, I am class C
# 当在class C 中 重新定义与父类 class A 同名的方法hellp() 后,class C 的实例将不再调用class A 中定义的hello()方法而调用
# 自身定义的hello() 方法
# 即, 子类定义父类同名函数之后,父类函数被覆盖
# 重定__init__方法
def fun(obj):
obj.myMethod()
c1=Child()
fun(c1)
c2=Parent()
fun(c2)
|
09e06c997091c201f3dd2a96174ab0770bd844a3
|
rominecarl/hafb-intro-python
|
/words.py
| 1,463 | 3.953125 | 4 |
"""
Get a file from the Web
http://icarus.cs.weber.edu/~hvalle/hafb/words.txt
"""
def fetch_words():
"""
Fetch the words a sorted word list with word counts from a prespecified URL
:return: None
:print: Word list
"""
from urllib.request import urlopen
file = "http://icarus.cs.weber.edu/~hvalle/hafb/words.txt"
count = 0
data = {}
with urlopen(file) as story:
for line in story: # reads the file one line at a time
words = line.decode('utf-8').split() # parse the line into words. Split defaults to spaces
for word in words: # read through the word dictionary
if word in data: # test for existance. I.e. does the entry already exist in the dictionary
data[word] += 1
else: # data not found
data[word] = 1
count += 1
print("Total number of words", count)
print ("Total data", data)
# sort by keys
for key in sorted(data.keys()):
print(key, data[key])
def print_items(items):
"""
Print elements of the collection
:param items: A collections of objects
:return: nothing
"""
for item in items:
print(item)
def main():
"""
Test function
:return: nothing
"""
fetch_words()
if __name__ == "__main__":
main()
exit(0)
|
30cb2dd2889c496457028e18ffeac107a739f8c5
|
samalty/file_io
|
/write.py
| 446 | 3.921875 | 4 |
# The script below enables us to make changes to a separate txt file
# 'a' stands for append, meaning every time we enter something into the write function, it will add it to the pre-existing content, rather than overwriting everything. '\n' ensures that new content features on its own line.
f = open('newfile.txt', 'a')
lines = ['Hello','World','Welcome','To','File IO']
text = '\n'.join(lines)
f.write("Hello\n")
f.writelines(lines)
f.close()
|
0c2020b33f4e711bd2c9ba36e3d18c76403dcffc
|
fs302/LeetCode
|
/033-SearchRotated/search_rotated_sorted_array.py
| 2,621 | 3.953125 | 4 |
import json
class Solution(object):
"""
Find the pos where rotation happended at, aka original start
nums - arraylist
start - start position, include
end - end position, not included
"""
def find_split_pos(self, nums, start, end):
if start >= end:
return 0
mid = (start+end)/2
if mid > 0 and nums[mid] < nums[mid-1]:
return mid
left = self.find_split_pos(nums, start, mid)
if left != 0:
return left
right = self.find_split_pos(nums, mid+1, end)
if right != 0:
return right
return 0
def binary_find(self, arr, target):
if len(arr) <= 1:
if len(arr) == 1 and arr[0] == target:
return 0
else:
return -1
mid_pos = len(arr)/2
if arr[mid_pos] == target:
return mid_pos
left = self.binary_find(arr[:mid_pos],target)
if left != -1:
return left
right = self.binary_find(arr[mid_pos+1:],target)
if right != -1:
return mid_pos+1+right
return -1
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# handle special case
if len(nums) == 0 or nums is None:
return -1
if len(nums) == 1:
return 0 if nums[0]==target else -1
## step-1: find the pos where rotation happended at
s_pos = self.find_split_pos(nums,0,len(nums))
## step-2: find the pos using binary search in the two seperate array
p1 = self.binary_find(nums[:s_pos], target)
p2 = self.binary_find(nums[s_pos:], target)
if p1 != -1:
return p1
if p2 != -1:
return s_pos+p2
return -1
def stringToIntegerList(input):
return json.loads(input)
def stringToInt(input):
return int(input)
def intToString(input):
if input is None:
input = 0
return str(input)
def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
line = lines.next()
nums = stringToIntegerList(line)
line = lines.next()
target = stringToInt(line)
ret = Solution().search(nums, target)
out = intToString(ret)
print out
except StopIteration:
break
if __name__ == '__main__':
main()
|
1c04e67857dce885198e69be3144b0cb744f5445
|
mickey0524/leetcode
|
/724.Find-Pivot-Index.py
| 530 | 3.546875 | 4 |
# https://leetcode.com/problems/find-pivot-index/
#
# algorithms
# Easy (41.83%)
# Total Accepted: 83,546
# Total Submissions: 199,708
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
right_sum, left_sum = sum(nums), 0
for i in xrange(len(nums)):
right_sum -= nums[i]
if left_sum == right_sum:
return i
left_sum += nums[i]
return -1
|
f089b9535be0267799e320715e4b0191b4a0a1b6
|
arzzon/PythonLearning
|
/PythonInbuilts/Regex/regex.py
| 2,289 | 4.375 | 4 |
'''
Regex in python
'''
import re
'''
IMPORTANT:
Python offers two different primitive operations based on regular expressions:
re.match() checks for a match only at the beginning of the string, while re.search()
checks for a match anywhere in the string (this is what Perl does by default).
'''
# Find a pattern in the string.
txt = "Hi I'm Arbaaz Khan. Random numbers 12 543 89809"
# If match is not found then a None is returned
matchObject = re.search("vhkdhskhaks", txt)
print(matchObject) # None
# If match is found then a match object is returned
matchObject = re.search("Khan", txt)
print("Match is found, match object returned:", matchObject)
#Match object
# The Match object has properties and methods used to retrieve information about the search, and the result:
# .span() returns a tuple containing the start and end positions of the match.
# .string returns the string passed into the function
# .group() returns the part of the string where there was a match
print("span is used to return the start and end position of the match (start, end): ", matchObject.span())
print("string is used to return the string passed to the function: ", matchObject.string)
print("group is used to return the part of the string where the pattern was found: ", matchObject.group())
print("########################################")
print("Using match function")
if re.match("Hi", txt):
print("Using match function: pattern 'Hi' Found") # Found
else:
print("Not found")
if re.match("Khan", txt):
print("Using match function: pattern Found")
else:
print("Using match function: Pattern 'Khan' Not found") # Not Found
print("########################################")
print("Using findall() function which returns a list of strings containing all matches.")
print(re.findall('\d+', txt)) # ['12', '543', '89809']
print("########################################")
print("Using split() function which returns a list of strings after splitting it at the patterns.")
print(re.split('\.', txt)) # ["Hi I'm Arbaaz Khan", ' Random numbers 12 543 89809']
print("########################################")
print("Using sub(pattern, replace, string) function which returns the string after replacing the "
"matched pattern with the replace string.")
print(re.sub('\d+', "*", txt))
|
633598a8ebfdca6434df8b829f6232c3623b6f24
|
analuisadev/100-Days-Of-Code
|
/Day-49.py
| 654 | 3.71875 | 4 |
from random import randint
from time import sleep
lista = list()
jogos = list()
print ('{:=^40}'.format(' MEGA SENA '))
quantnum = int(input('Quantos números serão sorteados? '))
total = 1
while total <= quantnum:
contador = 0
while True:
num = randint (1, 60)
if num not in lista:
lista.append(num)
contador += 1
if contador >= 6:
break
lista.sort()
jogos.append(lista[:])
lista.clear()
total += 1
print ('-=' * 3, f'SORTEANDO {quantnum} JOGOS','-=' * 3)
for indice, lista in enumerate(jogos):
print (f'Jogo {indice+1}: {lista}')
sleep(1)
print ('Boa sorte')
|
8c8e0edcce5805a6921719d029bead03e3babe03
|
AgentRatz/VITAP-FRESHERS-CSE1002-AS1
|
/#To find a generic root of a number using While loop.py
| 926 | 3.703125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 18 20:27:26 2021
@author: 91798
"""
#VITAP assignment-1
#School: SCOPE
#Semester: Fall Sem 2021-22
#Subject: Problem Solving using Python
#Subject Code: CSE1012
#To find a generic root of a number using While loop
"""
genric root is the sum of the numbers to reduce it below 10
for example if the number is 2259 your answer should be 2+2+5+9 = 18 = 1+8 = 9
therefore 9 is the genric root of 2259"""
num= int(input('enter a number')) # take an input from user
while num > 10 :
tot=0
sum = 0
while num :
total=num % 10
num= num // 10
sum+= total
if sum > 10 :
num = sum
else:
break
print("genric root is ", int(sum))
""" this can also be done using single line method
num = 2259
generic_root = 1 + ((num - 1) % 9)
print("generic root = ", generic_root) """
|
82c151b262a7ffb682f24267aa5fa823e1b0f68e
|
MingduDing/A-plan
|
/acmcoder/约德尔测试.py
| 892 | 3.6875 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time: 2019/9/18 14:03
# @Author: Domi
# @File: 约德尔测试.py
# @Software: PyCharm
"""
输入
每组输入数据为两行,第一行为有关约德尔人历史的字符串,第二行是黑默丁格观测星空得到的字符串。
(两个字符串的长度相等,字符串长度不小于1且不超过1000。)
样例输入
@!%12dgsa
010111100
输出
输出一行,在这一行输出相似率。用百分数表示。(相似率为相同字符的个数/总个数,精确到百分号小数点后两位。print("%%");输出一个%。)
样例输出
66.67%
"""
ch = input()
x = []
count = 0
for i in ch:
if i.isdigit() is True or i.isalpha() is True:
x.append('1')
else:
x.append('0')
num = list(input())
for i, j in zip(num, x):
if i == j:
count += 1
print("%.2f%%" % (count / len(ch) * 100))
|
f9582bb9d86f66bdc06b4058fe8149e710895d2e
|
AdamZhouSE/pythonHomework
|
/Code/CodeRecords/2528/60770/233861.py
| 1,026 | 3.65625 | 4 |
def solve():
nums = list(map(int, input()[1:-1].split(',')))
quicksort(nums,0,len(nums)-1)
print(nums)
def quicksort(a=[], left=0, right=0):
if left+2<=right:
pivot=median3(a,left,right)
i=left+1
j=right-2
while True:
while (a[i]<pivot):
i+=1
while (a[j]>pivot):
j-=1
if i<j:
swap(a,i,j)
else:
break
swap(a,i,right-1)
quicksort(a,left,i-1)
quicksort(a,i+1,right)
else:
if a[left]>a[right]:
swap(a,left,right)
def median3(a=[],left=0,right=0):
center=int((left+right)/2)
if a[center]<a[left]:
swap(a,left,center)
if a[right]<a[left]:
swap(a,left,right)
if a[right]<a[center]:
swap(a,center,right)
swap(a,center,right-1)
return a[right-1]
def swap(a=[],left=0,right=0):
tmp=a[left]
a[left]=a[right]
a[right]=tmp
if __name__ == '__main__' :
solve()
|
42812996787d0c888cbb0d944b59b6c0f14b7b38
|
Mishakaveli1994/Python_Fundamentals_May
|
/Excercise Lists Advanced/8_Feed_The_Animals.py
| 1,919 | 3.640625 | 4 |
animalList = []
animalInfo = []
zoneName = []
zoneInfo = []
while True:
command = input()
if command == 'Last Info':
break
else:
commandSplit = command.split(':')
subCom = commandSplit[0]
animalName = commandSplit[1]
animalFood = int(commandSplit[2])
animalArea = commandSplit[3]
if subCom == 'Add':
if animalName not in animalList:
animalList.append(animalName)
animalInfo.append([animalName, animalFood, animalArea])
if animalArea not in zoneName:
zoneName.append(animalArea)
zoneInfo.append([1, animalArea])
else:
zoneIndex = zoneName.index(animalArea)
zoneInfo[zoneIndex][0] += 1
else:
animalIndex = animalList.index(animalName)
animalInfo[animalIndex][1] += animalFood
elif subCom == 'Feed':
if animalName in animalList:
animalIndex = animalList.index(animalName)
animalInfo[animalIndex][1] -= animalFood
if animalInfo[animalIndex][1] <= 0:
print(f"{animalName} was successfully fed")
animalList.pop(animalIndex)
animalInfo.pop(animalIndex)
zoneIndex = zoneName.index(animalArea)
zoneInfo[zoneIndex][0] -= 1
if zoneInfo[zoneIndex][0] == 0:
zoneInfo.pop(zoneIndex)
zoneName.pop(zoneIndex)
print("Animals:")
sortedAnimalInfo = sorted(animalInfo, key=lambda x: (-x[1], x[0]))
for index, value in enumerate(sortedAnimalInfo):
print(f"{value[0]} -> {value[1]}g")
sortedZoneList = sorted(zoneInfo, key=lambda x: -x[0])
print("Areas with hungry animals:")
for i in sortedZoneList:
print(f"{i[1]} : {i[0]}")
|
1849afeceb4070855ab82a01177bbbc96b8b18da
|
Susaposa/Homwork_game-
|
/activities/2_functions.py
| 4,996 | 4.3125 | 4 |
# REMINDER: Only do one challenge at a time! Save and test after every one.
# Challenge 0: Remember: Do the first thing for any Python activity.
print('Challenge 1 -------------')
# Challenge 1:
# Write the code to "invoke" the function named challenge_1
def challenge_1():
print('Hello Functional World!')
challenge_1()
print('Challenge 2 -------------')
# Challenge 2:
# 1. Uncomment the following code.
# 2. Many of these functions and invocations have typos or mistakes. Fix all
# the mistakes and typos to get the code running.
# 3. When running correctly, it should print a, b, c, and d on separate lines.
def func_1():
print("a")
def func_2():
print("b")
def func_3():
print("c")
def func_4():
print("d")
func_1()
func_2()
func_3()
func_4()
print('Challenge 3 -------------')
# Challenge 3:
# 1. Uncomment the following code. What does it do?
# 2. Notice how repetitive it is. Your task is to "refactor" it to be less
# repetitive. This will require putting the repetitive bits of the code into a
# new function of your creation, then invoking the function in lieu of
# repeating the code.
# def questions():
# name = input('What is your name? ')
# print("We need to ask your name 3 times")
# question()
# print("Hi", name)
# question()
# print("And one more time....")
# questions()
def print_hi_name():
name = input('What is your name? ')
print("Hi", name)
print("We need to ask your name 3 times.")
i = 0
while i < 3:
if i == 2:
print("And one more time....")
print_hi_name()
i = i + 1
# print("We need to ask your name 3 times.")
# name = input('What is your name? ')
# print("Hi", name)
# name = input('What is your name? ')
# print("Hi", name)
# print("And one more time....")
# name = input('What is your name? ')
# print("Hi", name)
print('Challenge 4 -------------')
# Challenge 4:
# 1. Uncomment the following code. Inspect it closely. What does it do?
# 2. You will need to add an invocation to get it to work. Add an invocation so
# that the game "starts in the bedroom". Hint: bedroom()
# 3. Follow the same pattern to add a function that includes a hallway scene.
# def bedroom():
# print('You are in a bedroom. A window is open and the sun is shining in.')
# print('There is a cell phone, resting on top of a chest of drawers.')
# print('north: Hallway')
# print('south: Bathroom')
# choice = input('? ')
# if choice == 'north':
# hallway()
# elif choice == 'south':
# bathroom()
# else:
# bedroom()
# bedroom()
# def bathroom():
# print('You are in a small bathroom. Everything is sparkling clean, except')
# print('there is toothpaste smeared on the counter. One small window lets')
# print('a bright beam of sunshine in.')
# print('north: Bedroom')
# choice = input('? ')
# if choice == 'north':
# bedroom()
# else:
# bathroom()
# bathroom()
# def hallway():
# print('You are in a bedroom. A window is open and the sun is shining in.')
# print('There is a cell phone, resting on top of a chest of drawers.')
# print('north: Hallway')
# print('south: Bathroom')
# choice = input('? ')
# if choice == 'north':
# hallway()
# elif choice == 'south':
# bathroom()
# else:
# bedroom()
# hallway()
def bedroom():
print('You are in a bedroom. A window is open and the sun is shining in.')
print('There is a cell phone, resting on top of a chest of drawers.')
print('north: Hallway')
print('south: Bathroom')
choice = input('? ')
if choice == 'north':
hallway()
elif choice == 'south':
bathroom()
else:
bedroom()
def bathroom():
print('You are in a small bathroom. Everything is sparkling clean, except')
print('there is toothpaste smeared on the counter. One small window lets')
print('a bright beam of sunshine in.')
print('north: Bedroom')
choice = input('? ')
if choice == 'north':
bedroom()
else:
bathroom()
def hallway():
print('You are in a bedroom. A window is open and the sun is shining in.')
print('There is a cell phone, resting on top of a chest of drawers.')
print('north: Hallway')
print('south: Bathroom')
choice = input('? ')
if choice == 'north':
hallway()
elif choice == 'south':
bathroom()
else:
bedroom()
# Start them off in the bedroom
bedroom()
# Show More
print('-------------')
# Bonus Challenge:
# 1. Make it so that you can pick up the phone while in the bedroom with a
# command "take phone".
# 2. Once picked up, make it so that the phone will "start ringing" after
# traveling to a few different rooms.
# HINT: You will probably need to use a variable to mark that the user has
# picked up the phone. For this, look up the "global" keyword in Python, it
# might come in handy, as it allows functions to share variables.
|
1937b9517a2f625a91d792327466cf1ab8a82807
|
nickbonne/code_wars_solutions
|
/factorial.py
| 180 | 3.78125 | 4 |
# https://www.codewars.com/kata/factorial-1/train/python
def factorial(n):
nums = range(1, n + 1)
ans = 1
for num in nums:
ans = ans * num
return ans
|
722878db0ec3d9db1f0c3944f9d4e4fc0102b416
|
shankar01139/python_Basics
|
/tuple.py
| 2,593 | 4.1875 | 4 |
# python tuples
# 1.General tuple
tup = (100 ,111, 112, 113,114,115)
print(tup[1:])
print(tup[::-1])
print(tup[2:4])
tup=(False,20,30,True,50,20,60,'shankar',20 ,'ram')
print('Counting tuple elements with count() method : ',tup.count(20))
print('Identifying the index of an particular element with index() method : ',tup.index('shankar'))
# 2.Tuples immutable with exception handling
tup=(100,200,300,400,500)
print('Tuple before we try mutate the element:',tup)
print('')
print('If we try to mutate , It will show.....')
try:
tup[3]='shankar'
except:
print("TypeError: 'tuple' object does not support item assignment....")
print('Because Python tuples are immutable...!')
# 3.Tuple conactenation
tup=(11, 'shankar', 13, True, 15, 16, 'Rajesh', 18)
tup1=(False,20,30,True,50,60)
print('Concatenation with + Operator :',(tup+tup1))
print('Concatenation with sum method :',sum((tup,tup1), ()))
# 4.Tuple Repitation
tup=(11, 'shankar', 13, True, 15, 16, 'Rajesh', 18)
print(tup)
rep=int(input('How many times do you want to repete the tuple:'))
print('Tuple Repitation:',tup*rep)
# 5.Tuple Length
tup1=(False,20,30,True,50,60)
lgth=int(input('Can you guess the legth of the list:'))
if(len(tup1) == lgth):
print('WoW! You Guessed it correctly..!')
else:
print('Nah! Try Again ..!')
# 6.Tuple Memebership
tup=(11,22,33,44,55,66,77,88,99)
var=int(input('Enter Data:'))
if var in tup:
print('Data you entered is available in the tuple....')
if var not in tup:
print('Data you entered is Not available in the tuple....')
# 7.Tuple For loop
tup=(11, 'shankar', 13, True, 15, 16, 'Rajesh', 18)
for i in range(len(tup)):
if isinstance(tup[i],bool):
print("It is a Logical value ..")
elif isinstance(tup[i],int):
print('It is a Integer Value...')
elif isinstance(tup[i],str):
print('It is a String Value...')
# 8.Tuple Zip Function
tup1=('shankar',43,True,'ram',False)
tup2=('Vinith',43,False,'ragu',True)
for x, y in zip(tup1,tup2):
if x == y:
print(True)
else:
print(False)
zip_tuple=zip(tup1,tup2)
print(list(zip_tuple))
# 9.Tuple min max
tup=((45,68),(27,89),(567,54),(98,117))
s1=sum(tup[0])
s2=sum(tup[1])
s3=sum(tup[2])
s4=sum(tup[3])
tup1=(s1,s2,s3,s4)
print('Minimum Value:',min(tup1))
print('Maximum Value:',max(tup1))
# 10.List into Tuple
lst=[11,'shankar',13,True,15,16,'Rajesh',18]
print('Data As List:',lst)
print('Converting List into Tuple.....')
print('Data As Tuple:',tuple(lst))
|
e0c0ca3e0eb33d8ca4708d5a6786ab3c32396ec4
|
FarnazO/Simplified-Black-Jack-Game
|
/python_code/main_package/play_game.py
| 10,892 | 3.84375 | 4 |
'''
This module contains the PlayGame class which contains the steps of the game.
And when the file is run on the command line, you can play the black jack game.
'''
from main_package.game import Game
from main_package.chips import Chips
from main_package.deck import Deck
from main_package.hand import Hand
class PlayGame():
'''
This class contains all the steps required for running the game as methods.
It contains the following properties:
- an game object
- player_chips which is a chips object
- dealer_chips which is a chips object
- player_hand and dealer_hand which at the start are empty but will be Hand objects
- deck is empty at the inital step but then will be a Deck object
- game_status which defines different statuses of the game and at start is "started"
It contains the following methods:
- "start_the_game" which prints the word "START" and welcomes the user to the game
- "start_a_new_round" which resets the deck, hands and all the relevant properties for
a new round of play for the same game.
- "ask_player_for_bet" which asks the player for their bet and if they choose to end
the game the game_status changes to "ended".
- "show_all_player_cards_and_some_dealer_cards" which prints all the players cardss and
some of the dealer's cards.
- "show_all_cards" which prints all the cards for both the player and the dealer's hand.
- "hit_or_stand_player" which asks the player if they want another card or they want to
stand.
It also checks if the player has reached 21 or above it.
- "dealer_plays_hand" which adds cards to dealer's hand if their score is less than 17.
It also checks if the dealers has exeeded 21.
- "who_won" which checks who has won the game with a higher score and adjusts the chips
based on who has won and lost the round.
- "end_the_game" which prints the word "END" marking the end of the game.
- "play_again" which prints the word "PLAY AGAIN" marking the start of a new round.
- "__shuffle_deck_and_deal_cards__" which shuffles the deck and deals cards to both
player and dealer's hands.
- "__place_cards_in_hand__" which places the given cards in a hand object
'''
def __init__(self):
'''
This method initalises the properites needed for the object of this class
'''
self.game = Game()
self.player_chips = Chips()
self.dealer_chips = Chips()
self.player_hand = ""
self.dealer_hand = ""
self.deck = ""
self.game_status = "started"
def start_the_game(self):
'''
This method prints the word "START" in *s to mark the start of the game.
'''
print("Welcome to the simplified Black Jack game!")
print("="*50)
print("|| * * * * * * * * * * * * * * * ||")
print("|| * * * * * * * ||")
print("|| * * * * * * * * * * ||")
print("|| * * * * * * * * * ||")
print("|| * * * * * * * * * ||")
print("="*50)
print("\U000026CF is Spades")
print("\U0001F48E is Diamonds")
print("\U0001F497 is Hearts")
print("\U0001F46F is Clubs")
print("="*50)
def start_a_new_round(self):
'''
This method resets the hands, the deck, game.h_or_s and game_status for another round
of the same game. Resetting the hands and deck includes shuffling the deck and dealing
the cards to the players
'''
self.player_hand = Hand()
self.dealer_hand = Hand()
self.deck = Deck()
self.game_status = "started"
self.game.h_or_s = "h"
self.__shuffle_deck_and_deal_cards__()
def ask_player_for_bet(self):
'''
This method uses the take_bet from the game object to ask the player
for the bet they want to place and if they don't want to play anymore or don't have
chips left, the game_status becomes ended.
'''
bet_or_not = self.game.take_bet(self.player_chips)
if bet_or_not == "ended":
self.game_status = "ended"
def show_all_player_cards_and_some_dealer_cards(self):
'''
This method prints all the players cards and some
of the dealer's cards (hides one of dealer's cards).
'''
self.game.show_hands(self.player_hand, self.dealer_hand, "some")
def show_all_cards(self):
'''
This method prints all the cards for both the player and the dealer's hand.
'''
self.game.show_hands(self.player_hand, self.dealer_hand, "all")
def hit_or_stand_player(self):
'''
This method asks the player if they want another card (hit) or they don't want any
more cards (Stand). While the player asks for a hit, if they score becomes 21, they
have won the round and game_status becomes "ended". If their score goes above 21 they
lose the round and game_status becomes "ended".
'''
while self.game.h_or_s == "h":
self.game.h_or_s = self.game.hit_or_stand(self.deck, self.player_hand)
self.show_all_player_cards_and_some_dealer_cards()
if self.player_hand.value == 21:
self.show_all_cards()
print(f"You won! \U0001f600 \U0001F38A")
self.player_chips.win_bet(self.game.player_bet)
self.dealer_chips.lose_bet(self.game.player_bet)
self.game_status = "ended"
break
if self.player_hand.value > 21:
self.show_all_cards()
print(f"You lost! \U0001F97A")
self.player_chips.lose_bet(self.game.player_bet)
self.dealer_chips.win_bet(self.game.player_bet)
self.game_status = "ended"
break
self.game_status = "dealer's turn"
def dealer_plays_hand(self):
'''
This method is called once the player has chosen to stand. In this case, as long as
dealer's score is less than 17, a card is added to their hand. As they add a card if they
go above 17 and below 21 the dealer stops drawing a card and if their score goes above 21
they lose the round and the game_status changes to "ended"
'''
hand_value = self.dealer_hand.value
while self.game_status == "dealer's turn":
if hand_value < 17:
hand_value = self.game.hit(self.deck, self.dealer_hand)
elif hand_value > 21:
self.show_all_cards()
print(f"You won! \U0001f600 \U0001F38A")
self.player_chips.win_bet(self.game.player_bet)
self.dealer_chips.lose_bet(self.game.player_bet)
self.game_status = "ended"
else:
self.game_status = "continue"
def who_won(self):
'''
This method checks who has the higher score which wins the round and it
adjusts the chips based on who won and lost the game. Winner gets the chips
that were beted and losers looses the same amount.
'''
if self.player_hand.value <= self.dealer_hand.value:
self.show_all_cards()
print("You lose! \U0001F97A")
self.player_chips.lose_bet(self.game.player_bet)
self.dealer_chips.win_bet(self.game.player_bet)
else:
self.show_all_cards()
print("You won! \U0001f600 \U0001F38A")
self.player_chips.win_bet(self.game.player_bet)
self.dealer_chips.lose_bet(self.game.player_bet)
def end_the_game(self):
'''
This method prints the word "END" in *s to mark the end of the game.
'''
print("="*44)
print("||\U0001F44B * * * * * * * * * \U0001F44B||")
print("||\U0001F44B * * * * * * \U0001F44B||")
print("||\U0001F44B * * * * * * * * * \U0001F44B||")
print("||\U0001F44B * * ** * * \U0001F44B||")
print("||\U0001F44B * * * * * * * * * \U0001F44B||")
print("="*44)
def play_again(self):
'''
This method prints the word "PLAY AGAIN" in *s to mark the start of a new round.
'''
print("="*95)
print("|| * * * * * * * * * * * * * * * * ||")
print("|| * * * * * * * * * * * * * * * * ||")
print("|| * * * * * * * * * * * * * * * * * * ||")
print("|| * * * * * * * * * * * * * * * * * * * ** ||")
print("|| * * * * * * * * * * * * * * * * * * ||")
print("="*95)
def __shuffle_deck_and_deal_cards__(self):
'''
This is a private method which shuffles the deck, deals the cards and places them
in the player and dealer's hands.
'''
self.deck.shuffle()
dealth_cards = self.deck.deal()
self.__place_cards_in_hand__(self.player_hand, dealth_cards[0])
self.__place_cards_in_hand__(self.dealer_hand, dealth_cards[1])
def __place_cards_in_hand__(self, hand, cards):
'''
This method places the given cards in the given hand.
'''
for card in cards:
hand.add_card(card)
return hand
if __name__ == '__main__':
PLAY = PlayGame()
PLAY.start_the_game()
PLAYING = True
while PLAYING:
PLAY.start_a_new_round()
PLAY.ask_player_for_bet()
if PLAY.game_status == "ended":
break
PLAY.show_all_player_cards_and_some_dealer_cards()
PLAY.hit_or_stand_player()
if PLAY.game_status == "dealer's turn":
PLAY.dealer_plays_hand()
if PLAY.game_status == "continue":
PLAY.who_won()
while True:
PLAY_AGAIN = input("Would you like to play again? y/n?")
if PLAY_AGAIN.lower() == "y" or PLAY_AGAIN.lower() == "yes":
print("="*40)
PLAYING = True
PLAY.game_status = "started"
PLAY.play_again()
break
if PLAY_AGAIN.lower() == "n" or PLAY_AGAIN.lower() == "no":
PLAYING = False
PLAY.game_status = "ended"
break
print("Wrong choice!")
PLAY.end_the_game()
|
2ab23bbcea7160b11635f20be5e66dcd27585172
|
Lindisfarne-RB/GUI-L3-tutorial
|
/Lesson43.py
| 2,391 | 4.125 | 4 |
'''from tkinter import *
from tkinter import ttk
# Create a window
root = Tk()
root.title("Greetings App")
# Create a label and add it to the window using pack()
title = ttk.Label(root, text="Greetings! Enter your name: ")
title.grid(row=0, column=0, columnspan=2, padx=10, pady=10)
#Create a StringVar() to store text
name = StringVar()
# Create a text entry field
name_entry = ttk.Entry(root, textvariable=name)
name_entry.grid(row=1, column=0, columnspan=2, padx=10, pady=10)
# Create a second label with longer text and add it to the window using pack()
greeting_label = ttk.Label(text="Hello", wraplength=150)
greeting_label.grid(row=1, column=0)
# Create a label for the user's name
name_label = ttk.Label(root, variable=name)
name_label.grid(row=2, column=1, padx=10, pady=10)
# Run the main window loop
root.mainloop()
Debugging GUI code part 2
Ok, next let's look at some bugs that are common to tkinter code specifically:
Forgetting to specify the parent widget, or specifying the wrong parent
Forgetting to put the widget into the window using pack() or grid()
Not running .mainloop() on the window, or running it before all of the widgets have been added
Using the wrong rows and columns in .grid()
Mixing up parameters like variable and textvariable
CREATE
We've added a couple more widgets now
Something is missing from line 20–find the bug!
For some reason the name_entry won't show up–check the grid values for all the widgets and find the bug!
Is that the right argument on line 24 for the name label? Fix the bug!'''
from tkinter import *
from tkinter import ttk
# Create a window
root = Tk()
root.title("Greetings App")
# Create a label and add it to the window using pack()
title = ttk.Label(root, text="Greetings! Enter your name: ")
title.grid(row=0, column=0, columnspan=2, padx=10, pady=10)
#Create a StringVar() to store text
name = StringVar()
# Create a text entry field
name_entry = ttk.Entry(root, textvariable=name)
name_entry.grid(row=1, column=0, columnspan=2, padx=10, pady=10)
# Create a second label with longer text and add it to the window using pack()
greeting_label = ttk.Label(root, text="Hello", wraplength=150)
greeting_label.grid(row=1, column=0)
# Create a label for the user's name
name_label = ttk.Label(root, textvariable=name)
name_label.grid(row=2, column=1, padx=10, pady=10)
# Run the main window loop
root.mainloop()
|
b8f7b109345b3579184f20136ae102b5e0fb098d
|
ashwin4ever/Programming-Challenges
|
/Cracking the Coding Interview/google_str_encoding_decoding.py
| 644 | 4.0625 | 4 |
#String encoding decoding
def encode(arr , sep):
n = len(arr)
res = ''
'hello world'
for s in arr:
res += s + sep
res = res[0 : len(res) - 1]
return res
def decode(s , sep , res):
print(s)
if sep not in s:
res.append(s)
return res
idx = s.index(sep)
res.append(s[0: idx])
return decode(s[idx + 1 : ] , sep , res)
arr = ['hello' , 'world' , 'abchdjdhjkd']
sep = '-'
#print(encode(arr , '-'))
s = encode(arr , sep)
print(s)
res = decode(s , sep , [])
print(res)
|
8dc1b48a41cc4592566ffa8635de2fb602c9bc0e
|
wallacesilva/liasis
|
/liasis/core/datastructures.py
| 961 | 3.890625 | 4 |
from dataclasses import dataclass
@dataclass
class DataStructure:
"""
Base dataclass to be used as representation of Entities or any data
crossing the domain boundary.
"""
pass
@dataclass
class Request(DataStructure):
"""
Request attributes are specific for each UseCase, so te base dataclass
doesn't define any default attributes. It's a job for the UseCase devolope
to define how the request should look like.
"""
pass
@dataclass
class Response(DataStructure):
"""
Response data structure defines default attributes as a hint of how we
think is a good way to pass response structures to a presenter. It defines
a 'success: bool', 'message: Text' and 'data: DataStructure' attributes, so
we have the minimum to handle success, failure and data that should be
passed to the presenter in order to create a presentation accordinly.
"""
data: DataStructure
error: Exception
|
591e87d967ea6bd4d682cf6c3c7e99a61b458f3a
|
jmfcc/IPC2_Proyecto1_201709020
|
/main.py
| 1,433 | 4 | 4 |
import manejador
def main():
#Menu Principal
while True:
print(" _______________________________________________________________________________")
print(" _______________________________________________________________________________")
print()
print(" [1] - Cargar archivo")
print(" [2] - Procesar archivo")
print(" [3] - Escribir archivo de salida")
print(" [4] - Mostrar datos del estudiante")
print(" [5] - Generar gráfica")
print(" [6] - Salir")
print()
opcion = input(" >>> Seleccione una opción: ")
if opcion:
if opcion == "1":
print("\n")
manejador.cargarArchivo()
elif opcion == "2":
print("\n")
manejador.procesarArchivo()
elif opcion == "3":
print("\n")
manejador.escribeSalida()
elif opcion == "4":
print()
manejador.datosEstudiante()
elif opcion == "5":
print()
manejador.generaGrafoMatriz()
elif opcion == "6":
print("\n >>> Saliendo del programa...")
break
else:
print("\n >>> Opción inválida !!!")
print()
print()
else:
print(" >>> Aviso: Debes elegir una opción")
main()
|
5d85679d7aef6aa74aa9a42ef452f99dc2547db3
|
renatojobal/fp-utpl-18-evaluaciones
|
/eval-parcial-primer-bimestre/Ejercicio9.py
| 1,589 | 4.375 | 4 |
'''
Ejercicio 9.- Dos triángulos son congruentes si tienen la misma forma y tamaño, es decir, su ángulos y lados
correspondientes son iguales. Elaborar un algoritmo que lea los tres ángulos y tres lados de dos
triángulos e imprima si son congruentes, caso contrario que imprima que no son congruentes.
@author Renato
'''
'''
Se obtiene el varlo de cada angulo y lado de ambos triangulos
'''
# INGRESO DE DATOS
print("PRIMER TRIANGULO")
# Angulos
print("\t--Angulos--")
anguloA1 = float(input("\t\tIngrese el valor del ángulo A: "))
anguloB1 = float(input("\t\tIngrese el valor del ángulo B: "))
anguloC1 = float(input("\t\tIngrese el valor del ángulo C: "))
# Lados
print("--Lados--")
ladoa1 = float(input("\t\tIngrese el valor del lado a: "))
ladob1 = float(input("\t\tIngrese el valor del lado b: "))
ladoc1 = float(input("\t\tIngrese el valor del lado c: "))
print("SEGUNDO TRIANGULO")
# Angulos
print("\t--Angulos--")
anguloA2 = float(input("\t\tIngrese el valor del ángulo A: "))
anguloB2 = float(input("\t\tIngrese el valor del ángulo B: "))
anguloC2 = float(input("\t\tIngrese el valor del ángulo C: "))
# Lados
print("\t--Lados--")
ladoa2 = float(input("\t\tIngrese el valor del lado a: "))
ladob2 = float(input("\t\tIngrese el valor del lado b: "))
ladoc2 = float(input("\t\tIngrese el valor del lado c: "))
# CALCULO y SALIDA
if((anguloA1 == anguloA2) and (anguloB1 == anguloB2) and (anguloC1 == anguloC2) and (ladoa1 == ladoa2) and (ladob1 == ladob2) and (ladoc1 == ladoc2)):
print("Si son congruentes")
else:
print("No son congruentes")
|
3adbd1fed9306b3e06468fb4d17fb2e169ae8026
|
eschwabe/interview-practice
|
/leetcode/permutations.py
| 643 | 3.5625 | 4 |
# Leetcode 46
# Permutations
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
from collections import deque
res = []
nums_copy = deque(nums)
self.permute_r(nums_copy, [], res)
return res
def permute_r(self, nums, cur, res):
print nums, cur
if not nums:
res.append(cur)
return
for i in range(len(nums)):
cur.append(nums.pop())
self.permute_r(nums, cur, res)
nums.appendleft(cur.pop())
s = Solution()
s.permute([1,2,3])
|
4af8b60a6149c7e6c28cc7ea83a6467dbdbc2e07
|
igor-si/shared
|
/recipies/python/strings_examples.py
| 193 | 4.0625 | 4 |
#Here we use Pyhon string formatting to replace { } with value from variable:
print 'The fruits are {0}, {2}, {1}!'.format('Apple', 'Banana', 'Kiwi')
>>>> The fruits are Apple, Kiwi, Banana!
|
8c74233598d134ea2c43276bf5d382e41ac08b45
|
KiraLow/labs
|
/sem_1/lab3/python/lab3.py
| 3,103 | 3.84375 | 4 |
import math
import pylab
pi = 3.14
while (True):
run = input("Вычислим функцию? (yes/no)")
if run == "yes":
x1 = float(input("Введите первую границу для x: "))
x2 = float(input("Введите вторую границу для x: "))
a = float(input("Введите a: "))
step = float(input("Введите шаг: "))
v = str(input("Введите букву функции, которую xотите вычислить "))
diff = float(input("Введите максимальную разницу между значениями функций"))
i = 0
xlist = []
ylist = []
if v == "G":
x_mod = float(x1)
while x_mod <= x2:
if x_mod == -4 * a / 5 or x_mod == a:
print("Входные значения не принадлежат области определения функции. "
"(Введите другие значения)")
break
else:
g_1 = float(-(8 * (12 * pow(a, 2) + 68 * a * x_mod + 63 * pow(x_mod, 2))))
g_2 = float((4 * pow(a, 2) + a * x_mod - 5 * pow(x_mod, 2)))
G = float(g_1 / g_2)
xlist.append(x_mod)
ylist.append(G)
print("G = ", round(G, 4), " при x = ", x_mod)
x_mod += step
if (4 * (a * a) + a * x_mod - 5 * (x_mod * x_mod)) != 0.0:
diff_G = float(-(8 * (12 * (a * a) + 68 * a * x_mod + 63 * (x_mod * x_mod))) /
(4 * (a * a) + a * x_mod - 5 * (x_mod * x_mod)))
if diff <= (abs(diff_G - G)):
step /= 2
x_mod += step
else:
print("error")
if diff >= (abs(diff_G - G)):
step *= 2
x_mod += step
pylab.plot(xlist, ylist)
pylab.show()
if v == "Y":
while x1 < x2:
xlist.append(x1)
ylist.append(Y)
Y = -7 * pow(a, 2) + 40 * a * x1 + 63 * pow(x1, 2) + 1
print("Y =", Y)
x1 += step
i += 1
pylab.plot(xlist, ylist)
pylab.show()
if v == "F":
f_without_sin = float(
pi * (40 * a ** 2 - 61 * a * x1 + 7 * x1 ** 2) / (pi * (40 * a ** 2 - 61 * a * x1 + 7 * x1 ** 2)))
if f_without_sin:
F = math.sin(f_without_sin)
print("F =", F)
else:
print('Не существует синуса к заданной функции')
if run == "no":
print("Ну и ладно c: ")
exit(0)
if run != "yes" and run != "no":
print("Что-то не пойму что ты написал, давай еще раз ")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.