blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
41903211a3bc4d4b96ba076a998845d6988b4a23 | bonifasiustrg/Hacktoberfest-4 | /Python/Number Guessing.py | 870 | 4.21875 | 4 | # Number Guessing
# Importing Libraries
import random
# Generating a random number
lower = int(input("Enter Lower Value: "))
upper = int(input("Enter Upper Value: "))
# Declaring Variables
count = 1
chance = 3
random_number = random.randint(lower, upper)
print("You have "+ str(chance) + " chances.")
while True:
if count > 3:
print("The number is " + str(random_number) + ".")
print("Better luck next time!")
break
guess = int(input("Enter Your Guess: "))
if guess != random_number:
count += 1
chance -= 1
print("You have " + str(chance) + " chances left.")
elif guess == random_number:
print("You guessed it right in " + str(count) + " times.")
break
elif guess > upper:
print("You guessed too high!")
elif guess < lower:
print("You guessed too small!")
|
ec32a5b59c4462488ed4cd46e78f4702877ecd1b | KristoferGauti/Forritun-1-HR | /sideprojects/hangman.py | 2,602 | 4.03125 | 4 | import random
# Constants to be used in the implementation
WORD_LIST = [
"lion", "umbrella", "window", "computer", "glass", "juice", "chair", "desktop",
"laptop", "dog", "cat", "lemon", "cabel", "mirror", "hat"
]
MAX_GUESS = 12
CHAR_PLACEHOLDER = '-'
def random_seed():
seed = int(input("Random seed: "))
random.seed(seed)
def guess_word(the_word):
length_word = CHAR_PLACEHOLDER * len(the_word)
length_word_list = [line for line in length_word]
print("The word you need to guess has {} characters".format(len(the_word)))
print("Word to guess: {}".format(" ".join(length_word_list)))
return length_word, length_word_list
def check_win(counter, char_lines_list, the_word):
if counter == 12:
print("You lost! The secret word was {}".format(the_word))
return False
if CHAR_PLACEHOLDER not in char_lines_list:
print("You won!")
return True
def game_loop(char_lines, the_word, char_lines_list):
choose = input("Choose a letter: ")
guess_counter = 0
old_guesses = []
while choose.isalpha():
if choose not in old_guesses:
old_guesses.append(choose)
if choose in the_word:
for index, char in enumerate(the_word):
if choose == char:
if char_lines_list[index] == CHAR_PLACEHOLDER:
char_lines_list[index] = choose
guess_counter += 1
print("You guessed correctly!")
print("You are on guess {}/{}".format(guess_counter, MAX_GUESS))
print("Word to guess: {}".format(" ".join(char_lines_list)))
else:
print("The letter is not in the word!")
guess_counter += 1
print("You are on guess {}/{}".format(guess_counter, MAX_GUESS))
print("Word to guess: {}".format(" ".join(char_lines_list)))
else:
print("You have already guessed that letter!")
print("You are on guess {}/{}".format(guess_counter, MAX_GUESS))
print("Word to guess: {}".format(" ".join(char_lines_list)))
guess_counter += 0
#Check if the user has won
win = check_win(guess_counter, char_lines_list, the_word)
if win == True:
print("word to guess: {}".format(" ".join(char_lines_list)))
break
elif win == False:
break
choose = input("Choose a letter: ")
def main():
random_seed()
random_word = random.choice(WORD_LIST)
char_lines, char_lines_list = guess_word(random_word)
game_loop(char_lines, random_word, char_lines_list)
main() |
1002b36b34a1c23195f062e53e9e04864368b52b | iCodeIN/Project-Euler | /p043.py | 1,633 | 3.53125 | 4 | #!/usr/bin/env python
## SOLVED ##
# Project Euler: problem 43
# https://projecteuler.net/problem=43
# The number, 1406357289, is a 0 to 9 pandigital number because it is
# made up of each of the digits 0 to 9 in some order, but it also has a
# rather interesting sub-string divisibility property.
#
# Let d_1 be the 1st digit, d_2 be the 2nd digit, and so on. In this
# way, we note the following:
# - d_2d_3d_4=406 is divisible by 2
# - d_3d_4d_5=063 is divisible by 3
# - d_4d_5d_6=635 is divisible by 5
# - d_5d_6d_7=357 is divisible by 7
# - d_6d_7d_8=572 is divisible by 11
# - d_7d_8d_9=728 is divisible by 13
# - d_8d_9d_10=289 is divisible by 17
#
# Find the sum of all 0 to 9 pandigital numbers with this property.
if __name__=="__main__":
import itertools
primes = [2,3,5,7,11,13,17] # for iterating through divisibility
ans = [] # list with all such pandigital numbers
# clever permutations thing from: http://stackoverflow.com/a/16630306
digits = [int(i) for i in "0123456789"]
perms = itertools.permutations(digits)
n_power = len(digits)-1
#for num in [sum(v * (10**(n_power-i)) for i,v in enumerate(item)) for item in perms]:
#for num in [(1,4,0,6,3,5,7,2,8,9)]:
for num in perms:
tmpdigits = list(num)
# do each of the divisibility checks
passes = True
for i in xrange(1,7+1):
#print i
tmpnum = tmpdigits[i]*10**2+tmpdigits[i+1]*10+tmpdigits[i+2]
#print tmpnum
if(tmpnum % primes[i-1] != 0):
passes = False
break
if not passes: continue
else:
realnum = sum(v * (10**(n_power-i)) for i,v in enumerate(num))
ans.append(realnum)
#print realnum
print sum(ans)
|
472cb9ba04865bab2211b30d634e043ccc16e0cc | Naohiro2g/Raspberry-Pi-Misc | /python/robot/3-driving.py | 1,663 | 3.71875 | 4 | #!/usr/bin/env python3
# CamJam EduKit 3 -Robotics
# Worksheet 3–Driving and Turning
import RPi.GPIO as GPIO # Import the GPIO Library
import time # Import the Time library
# Set the GPIO modes
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Set variables for the GPIO motor pins
pinMotorAForwards = 7
pinMotorABackwards= 8
pinMotorBBackwards= 9
pinMotorBForwards =10
# Set the GPIO Pin mode
GPIO.setup(pinMotorAForwards, GPIO.OUT)
GPIO.setup(pinMotorABackwards, GPIO.OUT)
GPIO.setup(pinMotorBForwards, GPIO.OUT)
GPIO.setup(pinMotorBBackwards, GPIO.OUT)
# Turn all motors off
def StopMotors():
GPIO.output(pinMotorAForwards,0)
GPIO.output(pinMotorABackwards,0)
GPIO.output(pinMotorBForwards,0)
GPIO.output(pinMotorBBackwards,0)
# Turn both motors forwards
def Forwards():
GPIO.output(pinMotorAForwards,1)
GPIO.output(pinMotorABackwards,0)
GPIO.output(pinMotorBForwards,1)
GPIO.output(pinMotorBBackwards,0)
# Turn both motors backwards
def Backwards():
GPIO.output(pinMotorAForwards,0)
GPIO.output(pinMotorABackwards,1)
GPIO.output(pinMotorBForwards,0)
GPIO.output(pinMotorBBackwards,1)
# Turn Right
def TurnRight():
GPIO.output(pinMotorAForwards,1)
GPIO.output(pinMotorABackwards,0)
GPIO.output(pinMotorBForwards,0)
GPIO.output(pinMotorBBackwards,1)
# Turn Left
def TurnLeft():
GPIO.output(pinMotorAForwards,0)
GPIO.output(pinMotorABackwards,1)
GPIO.output(pinMotorBForwards,1)
GPIO.output(pinMotorBBackwards,0)
Forwards()
time.sleep(1)
StopMotors()
time.sleep(1)
TurnRight()
time.sleep(1)
TurnLeft()
time.sleep(1)
StopMotors()
GPIO.cleanup()
|
5e4f8257522b168afc8a995b56c8a2d6688c395e | emmerichLuang/byte-of-python | /chapter5_fun/fun_return.py | 281 | 4.03125 | 4 |
def get_max(x, y):
'''Prints the maximum of two numbers.
The two values must be integers.'''
if x > y:
return x
elif x == y:
return 'the same'
else:
return y
print(get_max.__doc__)
print(get_max(199, 200))
print(get_max(200, 200))
|
e613716fd7cd453d1ef274e35e8db759d5ee795d | agmatthews/LoRaTracker | /RockAir/lib/geometry.py | 888 | 3.90625 | 4 | from math import radians, degrees, cos, sin, asin, sqrt, atan2
def gDistance(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
d = c * r
return d
def gBearing(lon1, lat1, lon2, lat2):
"""
Calculate the bearing between two points
on the earth (specified in decimal degrees)
"""
b = atan2(sin(lon2-lon1)*cos(lat2), cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon2-lon1))
b = degrees(b)
b = (b + 360) % 360
return b
|
49bc46e07c391d3e64c2d1cbb47a92c3c2d6349b | ncullen93/pyBN | /pyBN/utils/data.py | 1,153 | 3.90625 | 4 | """
These are functions for dealing with datasets
that have strings as values - as those values
must be converted to integers in order to be
used in many structure learning functions, for
example.
There is, of course, the issue of how to get those
string values back into the underlying representation
after the learning occurs..
"""
import numpy as np
from copy import copy
def replace_strings(data, return_values=False):
"""
Takes a dataset of strings and returns the
integer mapping of the string values.
It might be useful to return a dictionary of the
string values so that they can be mapped back in
the actual BayesNet object when necessary.
"""
data = copy(data)
i = 0
value_dict = {}
for col in data.T:
vals,_,ret, = np.unique(col, True, True)
data[:,i] = ret
value_dict[i] = list(vals)
i+=1
if return_values:
return np.array(data,dtype=np.int32), value_dict
else:
return np.array(data, dtype=np.int32)
def unique_bins(data):
"""
Get the unique values for each column in a dataset.
"""
bins = np.empty(len(data.T), dtype=np.int32)
i = 0
for col in data.T:
bins[i] = len(np.unique(col))
i+=1
return bins |
c8cb412cff1f1265b2f21c2fff837d5329b8ee37 | mrbeesley/PythonTraining | /PythonGettingStarted/helloworld.py | 4,398 | 4.71875 | 5 | print("hello world")
print("----------------------------------------")
#example of string interpolation
name = "Hello"
desc = "World"
print(f"string interpolation, name: {name} desc: {desc}")
print("----------------------------------------")
#example of basic list and for-loop
student_names = ["Michael", "Jessica", "Noah", "Emelia", "Estella", "Chris", "Christen", "Roger", "Ginny"]
for name in student_names:
print("the name is: {0}".format(name))
print("----------------------------------------")
#example of range in a for-loop
x = 0
for index in range(20):
x += 100
print("x is {0}".format(x))
print("----------------------------------------")
# example of range as a list
y = range(10)
for index in y:
print("y is {0}".format(index))
print("----------------------------------------")
#example of loop with if-else
for name in student_names:
if name == "Noah":
print("Found Noah!")
else:
print(f"current name is: {name}")
print("----------------------------------------")
#example of loop with break
for name in student_names:
if name == "Noah":
print("Found Noah!")
break
else:
print(f"current name is: {name}")
print("----------------------------------------")
#example of loop with continue
for name in student_names:
if name == "Noah":
continue
else:
print(f"current name is: {name}")
print("----------------------------------------")
#example of a while loop
x = 0
while x < 10:
print(f"while x < 10 currently x is {x}")
x += 1
print("----------------------------------------")
#example of a dictionary
dict = { "Name":"Michael", "Grade":12, "Score":98 }
print("name: {0}".format(dict["Name"]))
print("grade: {0}".format(dict.get("Grade", "Unknown")))
print("badkey: {0}".format(dict.get("badkey", "Unknown")))
print("----------------------------------------")
#example of a list of dictionarys
all_students = [
{ "Name":"Michael", "Grade":12, "Score":97 },
{ "Name":"Jessica", "Grade":11, "Score":99 },
{ "Name":"Noah", "Grade":1, "Score":100 },
{ "Name":"Emie", "Grade":0, "Score":98 }
]
for student in all_students:
display = ""
for key in student.keys():
display += "{0}:{1} ".format(key, student[key])
print(display)
print("----------------------------------------")
#example of a try catch block
student = {
"name": "Mark",
"student_id": 15163,
"feedback": None
}
student.update()
try:
last_name = student["last_name"]
test = "name" + 3
except KeyError:
print("key doesn't exist in dictionary")
except TypeError:
print("you cant add those together!")
except Exception as error:
print("Unknown Error")
print(error)
print("exception was caught and code executed.")
print("----------------------------------------")
# example of a function
students = []
def get_students_titlecase_fe():
students_titlecase = []
for student in students:
students_titlecase = student.title()
return students_titlecase
def print_students_titlecase_fe():
students_titlecase = get_students_titlecase_fe()
print(students_titlecase)
def add_student_fe(name, student_id = 332):
student = {"name": name, "student_id": student_id}
students.append(student)
def var_args(name, *args):
print(name)
print(args)
def var_kwargs(name, **kwargs):
print(name)
print(kwargs)
student_list_fe = get_students_titlecase_fe()
add_student_fe("Mark")
print(students)
var_args("michael", "loves python", None, "hello", True)
var_kwargs("michael", description="loves python", feedback=None, pl_subscriber=True)
print("----------------------------------------")
# adding students to our app, by getting input
students = []
def get_students_titlecase():
students_titlecase = []
for student in students:
students_titlecase = student["name"].title()
return students_titlecase
def print_students_titlecase():
students_titlecase = get_students_titlecase()
print(students_titlecase)
def add_student(name, student_id = 332):
student = {"name": name, "student_id": student_id}
students.append(student)
student_list = get_students_titlecase()
student_name = input("Enter student name: ")
student_id = input("Enter student id: ")
add_student(student_name, student_id)
print_students_titlecase()
print("----------------------------------------")
|
303ff13c493e003283cb3e5359007c5cb84e9028 | gravesprite/seq2seq_with_deep_attention | /runners/run_pointer_nets_multi_features.py | 6,149 | 3.65625 | 4 | ###!/usr/bin/env python
#%% Pointer networks example
"""
Pointer network example:
This example shows how to use pointer networks to sort numbers.
In this case, we use multiple features as input to the decoder and decoder parts.
Therefore, each instance in the dataset is a tuple ((array, weights), sorted_array).
For more details, see the SortingDataset class.
"""
__author__ = "AL-Tam Faroq"
__copyright__ = "Copyright 2020, UALG"
__credits__ = ["Faroq AL-Tam"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Faroq AL-Tam"
__email__ = "ftam@ualg.pt"
__status__ = "Production"
import sys
sys.path.append("..")
# local files
from seq2seq_with_deep_attention.datasets.SortingDataset import SortingDataset
from seq2seq_with_deep_attention.models.MaskedPointerNetwork import MaskedPointerNetwork
# torch
import torch
import torch.nn as nn
import torch.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.sampler import SubsetRandomSampler # to do train-validate spilit
# plot
import matplotlib.pyplot as plt
# utilis
import random
import math
random_seed = torch.manual_seed(45)
# constants
IN_FEATURES = 2
HIDDEN_SIZE = 256
BATCH_SIZE = 64
RANGE = [0, 100] # range of generated numbers in a sequence
SOS_SYMBOL = 1.0 # start of sequence symbol
DATASET_SIZE = 2000
EPOCHS = 50
def plot_attention(attention, input_word, generated_word, size_=(10,10)):
""" Plot the attention matrix between the input and output sequences.
"""
print('\nAttention matrix')
# plot last attention
plt.matshow(attention)
plt.xlabel('generated sequence')
plt.xticks(range(size_[0]),generated_word)
plt.ylabel('input sequenece')
plt.yticks(range(size_[1]),input_word)
plt.show(block=False)
def main():
# dataset generator
ds = SortingDataset(use_weights= True, range_=RANGE, SOS_SYMBOL=SOS_SYMBOL, num_instances=DATASET_SIZE)
# loaders
train_dataloader = DataLoader(ds,
batch_size=BATCH_SIZE,
num_workers=0)
# The Masked Pointer Network model
pointer_network = MaskedPointerNetwork(in_features=IN_FEATURES,
hidden_size=HIDDEN_SIZE,
batch_size=BATCH_SIZE,
sos_symbol=SOS_SYMBOL,
device='gpu')
# loss function and optimizer
loss_func = nn.MSELoss()
opitmizer = optim.Adam(pointer_network.parameters(), lr=0.00025)
################## Training #############
#torch.autograd.set_detect_anomaly(True)
print('Training ...')
pointer_network.train()
epochs_loss = []
for _ in range(EPOCHS):
losses = []
for batch, target_seq in train_dataloader:
# put them in the same device as the model
batch = batch.float().to(pointer_network.device)
target_seq = target_seq.to(pointer_network.device)
# fix dims order to (batch_size, seq_size, features)
batch = batch.permute(0,2,1)
# handel last batch size problem
last_batch_size, sequence_length,_ = batch.shape
pointer_network.update_batch_size(last_batch_size)
# zero grad
pointer_network.zero_grad()
pointer_network.encoder.zero_grad()
pointer_network.decoder_cell.zero_grad()
# apply model
attentions, pointers = pointer_network(batch)
# loss calculation
loss = 0
# can be replaced by a single elegant line, but I do it like this for better readability
# the one_hot can be moved to the dataset for a better optimization of resources
for i in range(sequence_length):
loss += loss_func(attentions[:, i, :].to(pointer_network.device), \
nn.functional.one_hot(target_seq[:, i], num_classes=ds.lengths[0]).float())
#backpropagate
loss.backward()
opitmizer.step()
# loss curve
losses.append(loss.detach().cpu().item())
# uncomment this line to store all training tuples
#samples.append((target_seq.detach().cpu().numpy(), pointers.detach().cpu().numpy()))
epochs_loss.append(sum(losses) / len(losses))
# plot loss
plt.figure()
plt.title("Training")
plt.plot(epochs_loss)
plt.xlabel('Episode')
plt.ylabel('Loss')
plt.show()
################## Testing #############
pointer_network.eval() # trun off gradient tracking
test_sequence_length = 12
test_batches = 1 # one batch for testing
print('\n\n\nTesting using a higher length %d'% test_sequence_length)
ds = SortingDataset(use_weights=True,
range_=RANGE,
lengths=[test_sequence_length],
SOS_SYMBOL=SOS_SYMBOL,
num_instances=test_batches*last_batch_size)
test_dataloader = DataLoader(ds,
batch_size=last_batch_size,
num_workers=0)
print('\ninput\tweights\ttarget\tpointer')
for batch, target_sequences in test_dataloader:
# fix dims order to (batch_size, seq_size, features)
batch = batch.permute(0,2,1)
batch = batch.float().to(pointer_network.device) # add another dim for features
attentions, pointers = pointer_network(batch)
pointers = pointers.detach().cpu().numpy().astype(int)
input_sequences = batch.squeeze(2).detach().cpu().numpy()
i = 0
for input_seq, target_seq, pointer in zip(input_sequences, target_sequences, pointers):
print(input_seq[:,0], input_seq[:,1], input_seq[target_seq,0], input_seq[pointer,0])
plot_attention(attentions[i].t().detach().cpu().numpy(), input_seq[:,0].astype(int), input_seq[pointer, 0].astype(int), size_=(test_sequence_length, test_sequence_length))
i += 1
if __name__ is '__main__':
main()
# %%
|
79b0de4a50e56b7b5536e19d89ae833d8a95a2d2 | PreshConqueror/py-functions | /class61910198.py | 435 | 4 | 4 | class cat1:
def __init__(self, name, age):
self.name= name
self.age= age
def populate (self, name, age):
self.name= name
self.age= age
def display(self):
print('The cats name is:', self.name)
print ('The cats age is:', self.age)
print('enter variables to demonstrate the cat class')
name=input('enter name')
age=input('enter age')
CatObj= cat1(name, age)
CatObj.display()
|
6b5e6d2203f3ec9fcfaeb77dc99951e63ee1775f | LuAzamor/exerciciosempython | /repeticao5.py | 188 | 4 | 4 | # tabuada mostrando a tabuada, a partir do que o usuário digita. Ex: tabuada de 7.
n = int(input ("Tabuada de: "))
x = 0
while x <= 9:
x = x + 1
print((x), "x", (n), "=", (n*x)) |
3b4b695197940896484b16125826e9f62c96fce5 | KaanPY/PythonBaslangicOrnekleri | /listede bulunan çift sayıları ekrana yazdırınız....py | 180 | 3.515625 | 4 | # Yukarıdaki listede bulunan çift sayıları ekrana yazdırınız.
sayilar=[10,11,12,13,14,15,16,17,18,19,20]
for sayi in sayilar:
if sayi%2==0:
print(sayi)
|
f48b716386d9337956c64732fa8fd1f1ed16870a | aakriti1435/Django-HTML-to-PDF | /takess/pythonsscode.py | 1,000 | 3.59375 | 4 | import pyautogui
screenshot = pyautogui.screenshot()
screenshot.save("screen.png")
import pyautogui, time
time.sleep(6)
screenshot = pyautogui.screenshot()
screenshot.save("screenshot1.png")
from PIL import ImageGrab
image = ImageGrab.grab(bbox=(0,0,700,800))
image.save('sc.png')
# pip install keyboard
from PIL import ImageGrab
import keyboard
while True:
try:
if keyboard.is_pressed('p'):
image = ImageGrab.grab()
image.save("screenshot.png")
break
else:
pass
except:
break
import pyautogui # import PyAutoGUI library
import tkinter as tk # import tkinter library
# create main window
window = tk.Tk()
# define a method that will call whenever button will be clicked
def take():
image = pyautogui.screenshot("tkscreen.png")
# create a button
shot_btn = tk.Button(window,text = "Take Screenshot", command= callback)
# place the button on the window
shot_btn.place(x=50, y=50)
window.mainloop() |
e1f353b66f9b7113f94a72cfb9b4575b7e05c0b6 | jiangzuochen/leetcode | /002.Add Two Numbers/Add Two Numbers.py | 845 | 3.8125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
str1=''
str2=''
while l1 is not None or l2 is not None:
if l1 != None:
str1=str(l1.val)+str1
l1=l1.next
if l2 != None:
str2=str(l2.val)+str2
l2=l2.next
l3=resultList=ListNode(None)
for y in str(int(str1)+int(str2))[::-1]:
if l3.val is None:
l3.val = int(y)
else:
l3.next = ListNode(int(y))
l3 = l3.next
return resultList |
95d97a1f0e07a9d965ddcc8c1bc6bc64d1c16821 | lbu0413/python-study | /SWEA-PYTHON-BASIC-2/6257.py | 497 | 3.890625 | 4 | # 리스트의 원소를 키로 하고, 그 원소의 length를 값으로 갖는 딕셔너리 객체를 생성하는 코드를 작성해봅시다.
# 이 때 딕셔너리 내포 기능을 사용하며, 원소의 공백은 제거합니다.
# 리스트 fruit는 다음과 같습니다. fruit = [' apple ','banana',' melon']
# 출력
# {'apple': 5, 'banana': 6, 'melon': 5}
fruit = [" apple ", "banana", " melon"]
fruit_dict = {i.strip(): len(i.strip()) for i in fruit}
print(fruit_dict)
|
e849ca49cf2d9ea04d62b5e3e0da10bb4bae096c | kanhaichun/ICS4U | /Ivy232/Mandy/A11/A11 Mandy.py | 4,546 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 13 13:06:24 2018
@author: Mandy
Assignment 11 - Linear, Random and Binary Searching - Benchmarking
(1) Create a class with functions for three search algorithms - random, linear and binary.
(2) Write a program that determines the amount of time taken to search lists of 1000000 random numbers.
(3) Sample output of the program:
Random search algorithm:
trial# time
1 2.23
2 2.67
3 2.88
4 2.92
5 2.11
Average: 2.56
Linear Search Algorithm:
trial# time
1 3.45
2 3.97
3 3.21
4 1.23
5 2.23
Average ...
Binary Search algorithm:
trial# time
1 0.56
2 0.87
3 0.23
4 0.34
5 0.12
Average ....
"""
import random
import time
# If you have a problem, please re-run the program!
class Guess():
def Ran(n):
n.sort()
lowest = 0
highest = 10000
while True:
num = random.randint(lowest,highest) # guess the index of the list
if n[num] > 0.7: #zoom in the limit
highest = num + 1
#print("index",num)
if highest - lowest == 1:
##print(n[highest])
break
elif highest - lowest == 2:
##print(n[lowest+1])
break
elif n[num] < 0.7: #zoom in the limit
lowest = num
if highest+1 - lowest == 1:
##print(n[highest])
break
elif highest+1 - lowest == 2:
##print(n[lowest+1])
break
def Linear(n):
a = []
for i in n: # compare the num one by one
if i > 0.7 and i <0.8: # put the nums between 0.7 and 0.8 in a list
a.append(i)
a.sort() # pick out the smallest one by sorting
##print(a[0])
def Binary(n):
lowest = 0
highest = 10000
while True:
mid = (lowest + highest - 1) // 2 # 2 keep zooming in the limit
if highest - lowest == 2: # 3 when finally you have three nums left
if n[highest-1] > 0.7:
##print(n[highest-1])
pass
else:
##print(n[highest])
pass
break
elif highest - lowest == 1: # 3 when finally younhave two nums left
if n[highest-1] > 0.7:
##print(n[highest-1])
pass
else:
##print(n[highest])
pass
break
else: # 1 compare the num in the middle with 0.7
if n[mid] > 0.7: #zoom in the limit
highest = mid
elif n[mid] < 0.7: #zoom in the limit
lowest = mid
#Ran(n)
#Linear(n)
#Binary(n)
####test the time################
print("Random Search:")
print("Trial: ","Time:")
sum = 0
for t in range (1,6):
n = []
for i in range(0,10000):
n.append(random.random()) # print a list with 10000 terms between 0-1
t0 = time.time()
Ran(n)
t1 = time.time()
total = t1-t0
print("",t," ",total)
sum += total
print("")
print("Average1:",total/5)
print("")
print("Liner Search:")
print("Trial: ","Time:")
sum = 0
for t in range (1,6):
n = []
for i in range(0,10000):
n.append(random.random()) # print a list with 10000 terms between 0-1
t0 = time.time()
Linear(n)
t1 = time.time()
total = t1-t0
print("",t," ",total)
sum += total
print("")
print("Average2:",total/5)
print("")
print("Binary Search:")
sum = 0
for t in range (1,6):
n = []
for i in range(0,10000):
n.append(random.random()) # print a list with 10000 terms between 0-1
t0 = time.time()
Binary(n)
t1 = time.time()
total = t1-t0
print("",t," ",total)
sum += total
print("")
print("Average3:",total/5)
##################################
print("")
print("Unblock '##code' to see the number you are looking for!")
|
a843c63bb4ec1657ad35f1d4c2a973e25ef37114 | Giselle02/proyecto-final | /productos.py | 1,320 | 4 | 4 | print(" PRODUCTOS ")
print("*-"*15)
productos = dict()
productos ={
1: "Perfumes: $85",
2: "Lapiz labial: $20",
3: "Esmalte de uñas: $15",
4: "Crema de piel: $45",
5: "Maquillaje para ojos: $25"
}
lista_Nro = []
lista_nombres = []
for k, v in productos.items():
print("%s -> %s" % (k,v))
lista_Nro.append(k)
lista_nombres.append(v)
print("*"* 35)
print("Ingrese el nombre del primer producto: ")
p1 = input()
print("Cantidad comprada de ", p1)
p1_cant = int(input())
print("Valor de la unidad de ", p1)
p1_vu = int(input())
print("Ingrese 1 nombre del segundo producto: ")
p2 = input()
print("Cantidad comprada de ", p2)
p2_cant = int(input())
print("Valor de la unidad de ", p2)
p2_vu = int(input())
print("Ingrese el nombre del tercer producto: ")
p3 = input()
print("Cantidad comprada de ", p3)
p3_cant = int(input())
print("Valor de la unidad de ", p3)
p3_vu = int(input())
p1_st = p1_cant * p1_vu
p2_st = p2_cant * p2_vu
p3_st = p3_cant * p3_vu
sutTot = p1_st + p2_st + p3_st
Total = sutTot
print("El total a pagar por ", p1, "es:", p1_st)
print("El total a pagar por ", p2, "es:", p2_st)
print("El total a pagar por ", p3, "es:", p3_st)
print("El total a pagar es", Total)
|
214e3aa6810a43a5a7b8bd6a52c1d8d5a67e1568 | Hallas23/Algoritmer | /edge_list_graph.py | 6,127 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 21 09:03:22 2020
@author: Simon
"""
class Vertex:
def __init__(self, e):
self._element = e
def __str__(self):
return str(self._element)
def element(self):
return self._element
def label(self):
return str(self.label)
def setLabel(self, l):
self.label = l
class Edge:
def __init__(self, e, v1, v2):
self._element = e
self._endpoints = [v1, v2]
def __str__(self):
return str(self._element)
def element(self):
return self._element
def endpoints(self):
return self._endpoints
def label(self):
return str(self.label)
def setLabel(self, l):
self.label = l
class Graph:
def __init__(self):
self._vertices = []
self._edges = []
#Inserts and returns a new vertex containing the element e.
#Input: V; Output: Vertex
def insert_vertex(self, e):
v = Vertex(e)
self._vertices.append(v)
return v
#Removes the vertex v and all its incident edges
#Input: Vertex; Output: nothing
def remove_vertex(self, v):
self._edges = [e for e in self._edges if v not in e.endpoints()]
self._vertices.remove(v)
#Inserts and returns a new edge between the vertices v and w.
#The element of the edge is o.
def insert_edge(self, o, v, w):
e = Edge(o, v, w)
self._edges.append(e)
return e
#Removes the edge e.
#Input: Edge; Output: nothing
def remove_edge(self, e):
self._edges.remove(e)
#Returns the count of vertices in the graph.
#Input: nothing; Output: int
def num_vertices(self):
return len(self._vertices)
#Returns the count of edges in the graph.
#Input: nothing; Output: int
def num_edges(self):
return len(self._edges)
#Returns an iterator on the vertices in the graph.
#Input: nothing; Output: Iterator
def vertices(self):
return iter(self._vertices)
#Returns an iterator on the edges in the graph.
#Input: nothing; Output: Iterator
def edges(self):
return iter(self._edges)
#Returns the degree of the vertex v.
#Input: Vertex; Output: int
def degree(self, v):
d = 0
for e in self._edges:
if v in e._endpoints:
d += 1
return d
#Returns an iterator on the vertices that are adjacent to v.
#Input: Vertex; Output: Iterator
def adjacent_vertices(self, v):
a = []
for e in self._edges:
if v == e._endpoints[0]:
a.append(e._endpoints[1])
elif v == e._endpoints[1]:
a.append(e._endpoints[0])
return iter(a)
#Returns an iterator on the edges that are incident to v.
#Input: Vertex; Output: Iterator
def incident_edges(self, v):
i = []
for e in self._edges:
if v in e._endpoints:
i.append(e)
return iter(i)
#Returns a list with the two vertices at the ends of the edge e.
#Input: Edge; Output: list with 2 vertices
def end_vertices(self, e):
return e._endpoints[:]
#Returns the vertex opposite v along the edge e.
#Input: Vertex, Edge; Output: Vertex
def opposite(self, v, e):
if e._endpoints[0] == v:
return e._endpoints[1]
else:
return e._endpoints[0]
#Returns whether the vertices v and w are adjacent.
#Input: Vertex, Vertex; Output: boolean
def are_adjacent(self, v, w):
for e in self._edges:
if v in e._endpoints and w in e._endpoints:
return True
return False
class dfs_iterator:
def __init__(self):
self._graph = None
self._visited = []
def _dfs_visit(self, v):
self._visited.append(v)
for x in self._graph.adjacent_vertices(v):
if x not in self._visited:
self._dfs_visit(x)
def iterator_dfs(self, g, v):
self._graph = g
self._visited = []
self._dfs_visit(v)
return iter(self._visited)
def is_connected(graph):
dfs = dfs_iterator()
visited = list(dfs.iterator_dfs(graph, 15))
return len(visited) == graph.num_vertices()
def path(graph, v1, v2):
dfs = dfs_iterator()
visited = list(dfs.iterator_dfs(graph, v1))
if v2 in visited:
return True
return False
def DFSS(g):
for i in g.vertices():
i.setLabel("UNEXPLORED")
for i in g.edges():
i.setLabel("UNEXPLORED")
for i in g.vertices():
if i.label == "UNEXPLORED":
DFS(g,i)
def DFS(g,v):
v.setLabel("VISITED")
for i in g.incident_edges(v):
if (i.label == "UNEXPLORED"):
w = g.opposite(v, i)
if (w.label == "UNEXPLORED"):
i.setLabel("DISCOVERY")
DFS(g,w)
else:
i.setLabel("BACK")
vlist =[]
max=-1
counter =0
def findLargestElement(v: Vertex, graph: Graph):
global vlist
global max
global counter
counter +=1
vlist.append(v)
adj = graph.adjacent_vertices(v)
if max < v:
max = v
for i in adj:
if i not in vlist:
findLargestElement(i,graph)
return max
graph1 = Graph()
graph1.insert_vertex(15)
graph1.insert_vertex(6)
graph1.insert_vertex(38)
graph1.insert_vertex(66)
graph1.insert_vertex(123)
graph1.insert_vertex(160)
graph1.insert_edge(90,15,66)
graph1.insert_edge(23,15,6)
graph1.insert_edge(10,15,38)
graph1.insert_edge(8,6,66)
graph1.insert_edge(7,6,123)
graph1.insert_edge(2,66,38)
graph1.insert_edge(76,66,123)
graph1.insert_edge(55,38,123)
v = next(graph1.vertices())
dfsVisitor = dfs_iterator()
visited = dfsVisitor.iterator_dfs(graph1, 6)
DFSS(graph1)
for v in graph1.vertices():
print(v.label)
|
3a998bdcff8cdfff6747ea8d18771a17fab8d89a | paulamachadomt/estudos-python-Guanabara | /Python_Guanabara_mundo123/ex032.py | 395 | 3.90625 | 4 | #indica se o ano digitado é bissexto ou não
from datetime import date
ano = int(input('digite o ano que deseja verificar. Para o ano atual, digite 0: '))
if ano == 0:
ano = date.today().year #seleciona o atual da data do computador
if ano % 4 == 0 and ano % 100 != 0 or ano % 400 ==0:
print('o ano {} É bissexto.'.format(ano))
else:
print('o ano {} NÃO É bissexto.'.format(ano)) |
982f93002b95417945e0d38fa72c2ed972e2fb39 | aeocista/pythonPractice | /problemCode.py | 807 | 4.0625 | 4 | # Getting a none?
n = [3, 5, 7, 8]
def print_list(x):
for i in range(0, len(x)):
print x[i]
return
# The problem was here:
print print_list(n)
# Should do this instead:
print_list(n)
# Double your list!
n = [3, 5, 7]
# Don't forget to return your new list!
def double_list(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x
print double_list(n)
# Ranges are a lot like lists
# range(6) # => [0, 1, 2, 3, 4, 5]
# range(1, 6) # => [1, 2, 3, 4, 5]
# range(1, 6, 3) # => [1, 4]
def my_function(x):
for i in range(0, len(x)):
x[i] = x[i]
return x
print my_function(range(0,3)) # Add your range between the parentheses!
# The sum of a list
n = [3, 5, 7]
def total(numbers):
result = 0
for i in range(len(numbers)):
result = result + numbers[i]
return result
|
b84b6159281e7e51ddcb6b452d51994c4e8732ee | coreyhermanson/100daysofcode | /7_python_data_structures/pybites_21_query_nested_data_structure.py | 2,926 | 4 | 4 | cars = {
'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'],
'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'],
'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'],
'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'],
'Jeep': ['Grand Cherokee', 'Cherokee', 'Trailhawk', 'Trackhawk']
}
def main():
# 1. Get all Jeeps
all_jeeps = get_all_jeeps(cars)
print(f'String of Jeep models in order: {all_jeeps}', end='\n')
# 2. Get the first car of every manufacturer.
first_models = get_first_model_each_manufacturer(cars)
print(f'List of first model of each manufacturer in order: {first_models}', end='\n')
# 3. Get all vehicles containing the string Trail in their names (should work for other grep too)
matching_models = get_all_matching_models(cars, grep='trail')
print(f'List of vehicles matching search term: {matching_models}', end='\n')
# 4. Sort the models (values) alphabetically
sorted_models = sort_car_models(cars)
print(f'Sorted car models dictionary: {sorted_models}', end='\n')
def get_all_jeeps(cars_dict: dict) -> str:
"""return a comma separated string of jeep models (original order)"""
jeeps = cars_dict['Jeep']
jeeps_string = ', '.join(jeeps)
assert jeeps_string == 'Grand Cherokee, Cherokee, Trailhawk, Trackhawk' # exercise test
return jeeps_string
def get_first_model_each_manufacturer(cars_dict: dict) -> list:
"""return a list of matching models (original ordering)"""
models_list = []
for models in cars_dict.values():
models_list.append(models[0])
assert models_list == ['Falcon', 'Commodore', 'Maxima', 'Civic', 'Grand Cherokee'] # exercise test
return models_list
def get_all_matching_models(cars_dict: dict, grep='trail') -> list:
"""return a list of all models containing the case insensitive
'grep' string which defaults to 'trail' for this exercise,
sort the resulting sequence alphabetically"""
models_list = []
for model in cars_dict.values():
for car in model:
if grep.lower() in car.lower():
models_list.append(car)
models_list.sort()
assert models_list == ['Trailblazer', 'Trailhawk'] # exercise test
return models_list
def sort_car_models(cars_dict: dict) -> dict:
"""sort the car models (values) and return the resulting cars dict"""
for k, v in cars_dict.items():
sorted_values = sorted(v)
cars_dict[k] = sorted_values
expected = {
'Ford': ['Fairlane', 'Falcon', 'Festiva', 'Focus'],
'Holden': ['Barina', 'Captiva', 'Commodore', 'Trailblazer'],
'Honda': ['Accord', 'Civic', 'Jazz', 'Odyssey'],
'Jeep': ['Cherokee', 'Grand Cherokee', 'Trackhawk', 'Trailhawk'],
'Nissan': ['350Z', 'Maxima', 'Navara', 'Pulsar'],
}
assert cars_dict == expected
return cars_dict
if __name__ == '__main__':
main()
|
022e26bc4455ef6b067a881008e0571b39ea45f3 | terrifyzhao/educative4 | /8_dfs/3.py | 707 | 3.84375 | 4 | class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_sum_of_path_numbers(root):
return find(root, 0)
def find(root, num):
if root is None:
return 0
num = num * 10 + root.val
if root.left is None and root.right is None:
return num
return find(root.left, num) + find(root.right, num)
def main():
root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(1)
root.left.left = TreeNode(1)
root.right.left = TreeNode(6)
root.right.right = TreeNode(5)
print("Total Sum of Path Numbers: " + str(find_sum_of_path_numbers(root)))
main()
|
a30e0c05d3af0662ca01aa7ea881643e0123680b | fishleongxhh/LeetCode | /LinkedList/142_LinkedListCycle2.py | 1,410 | 3.875 | 4 | # -*- coding: utf-8 -*-
# Author: Xu Hanhui
# 此程序用来求解LeetCode142: Linked List Cycle2问题
from LinkedList import *
#找出链表中环的入口节点,如果没有环,则返回None
def detectCycle(head):
#首先判断是否有环,返回快指针和慢指针首次相遇的节点
meetNode = hasCycle(head)
if not meetNode:
return None
#再判断环包含的节点个数
p, cnt = meetNode.nextNode, 1
while p != meetNode:
p, cnt = p.nextNode, cnt+1
#用两个指针确定环的入口位置
slow = fast = head
for i in range(cnt):
fast = fast.nextNode
while slow != fast:
slow, fast = slow.nextNode, fast.nextNode
return slow
def hasCycle(head):
slow = fast = head
while fast:
if fast.nextNode:
slow, fast = slow.nextNode, fast.nextNode.nextNode
if slow == fast:
return slow
else:
return None
return None
if __name__ == "__main__":
nums = [1]
headNode = initLinkedList(nums)
printLinkedList(headNode)
tailNode = headNode
"""
while tailNode.nextNode:
tailNode = tailNode.nextNode
tailNode.nextNode = headNode
for i in range(0):
tailNode.nextNode = tailNode.nextNode.nextNode
"""
inNode = detectCycle(headNode)
if inNode:
print(inNode.val)
else:
print(inNode)
|
1ed0171e63b82319c279f8a9436efc670ffda6f8 | nzralc/GlobalAIHubPythonHomework | /Homework2-nzralc.py | 422 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
user=[]
name = input("Ad: ")
user.append(name)
sname = input("Soyad: ")
user.append(sname)
age = int(input("Yaş: "))
user.append(age)
bday = int(input("Doğum Yılı: "))
user.append(bday)
print(user)
if user[2] <= 18:
print("Çok tehlikeli olduğu için dışarı çıkamazsınız")
else:
print("Dışarı çıkabilirsiniz")
# In[ ]:
# In[ ]:
|
4a0eb12809091e214ee50384eef9437298e7d631 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4060/codes/1876_1598.py | 154 | 3.515625 | 4 | from numpy import*
from math import*
compra=eval(input("compras: "))
aux=sum(compra)
for i in compra:
if (i >= 80 ):
aux=aux-5
print(round(aux, 2)) |
f7a3dbc0812c42fcc58083514e95e81a23c01d0f | TehWeifu/Tic-tac-toe | /Problems/Running average/task.py | 270 | 3.90625 | 4 | digits_string = input()
digit_array = []
average_array = []
for n in range(len(digits_string)):
digit_array.append(int(digits_string[n]))
for n in range(len(digit_array) - 1):
average_array.append((digit_array[n] + digit_array[n+1]) / 2)
print(average_array)
|
5f37d8d41c8884bb608cb25b1e84dd6f360cf179 | parkx676/Python | /Lab 6/stretch2.py | 297 | 3.765625 | 4 | import turtle
t = turtle.Turtle()
def drawsquare(t, x):
t.pendown()
t.forward(x)
t.left(90)
t.forward(x)
t.left(90)
t.forward(x)
t.left(90)
t.forward(x)
def squares(t, y):
i = 1
while i <= y:
drawsquare(t, 100)
t.left(360)
i += 1
|
627e361a2d457b33a3a14423bab3edb8fec30d02 | laimich/NYC-Restaurant-Data-Analysis | /nyc-restaurant-data-analysis.py | 3,089 | 3.875 | 4 | # -----------------------------------------------------------------------------
# Purpose: CS 122 Mini Project 2
# Read NYC restaurant inspection data, find mean score and number
# of unique restaurants per valid zipcode
#
# Author: Michelle Lai
# Date: March 2, 2018
# -----------------------------------------------------------------------------
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
def get_combined_zip_mean_size(df):
"""
Creates a new data frame with the columns,
zip code, mean score, and number of resturants
:param
df (data frame) data frame with the correct zip codes
:return: new data frame with the mean score and number
of resturants calculated for each zip code
"""
# group resturants by their zip code
group_zip = df.groupby('ZIPCODE')
# find count/size and mean score of each of the zip codes
group_size = group_zip.size()
group_mean = group_zip.mean().SCORE
# put the zip codes, count, and mean into lists
list_zip = group_size.index.tolist()
list_mean = group_mean.tolist()
list_count = group_size.tolist()
print("Groups for, zip codes: ", len(list_zip), ", mean: ", len(list_mean), ", count: ", len(list_count))
# put the lists into one dictionary, then put into data frame
combined = {'CODE': list_zip, 'MEAN': list_mean, 'SIZE': list_count}
combined_df = pd.DataFrame(data=combined)
return combined_df
# read csv file
df = pd.read_csv('data.txt', sep="\",\"", engine='python')
# fix naming of columns and data
df.rename(columns = {'"CAMIS':'CAMIS', 'RECORDDATE"':'RECORDDATE'}, inplace = True) # remove quote on the first and last columns
df['CAMIS'] = df['CAMIS'].str.strip('"') # remove quote on data of first column
df['RECORDDATE'] = df['RECORDDATE'].str.strip('"') # remove quote on data of last column
#df.shape # row, column (531935, 15)
# remove duplicate resturants
df = df.sort_values(by=['INSPDATE'], ascending=False) # sort by most recent inspection date (highest to lowest date)
df = df.drop_duplicates(subset='CAMIS', keep='first') # drop duplicate unique resturant identifiers, keep first or most recent entry
print("After removing duplicates: ", df.shape) # (25232, 15)
# remove zip codes below the minimum, 10001
df_range = df[(df.ZIPCODE >= 10001)]
print("After removing zip codes below minimum: ", df_range.shape) # (25228, 15)
# get the data frame with columns for zipcode (NYC valid), mean score, number of resturants
combined_valid = get_combined_zip_mean_size(df_range)
# filter out zip codes where count < 100
combined_valid = combined_valid[combined_valid.SIZE > 100]
print("After filtering out groups with < 100 resturants: ", combined_valid.shape)
# sort by mean in descending order
combined_valid = combined_valid.sort_values(by=['MEAN'], ascending=False)
print("After removing all invalid resturants: ", sum(combined_valid.SIZE.tolist()))
# create list of tuples for each row in data frame
tuples_valid = [tuple(x) for x in combined_valid.values]
print(tuples_valid)
|
88ac4468ce5e81aef7a6f2593b78d44fef70b53c | yangyang9768/python | /Spreadsheet Analysis.py | 964 | 3.890625 | 4 | #1. Read the data from the spreadsheet
#2. Collect all of the sales from each month into a single list
#3. Output the total sales across all months
import csv
from collections import OrderedDict
from typing import Any
import random
def read_data():
data = []
with open('Student_file.csv', 'r') as student_csv:
spreadsheet = csv.DictReader(student_csv)
for row in spreadsheet:
data.append(row)
return data
def run():
data = read_data()
students = []
for row in data:
student = row['name']
students.append(student)
return students
run()
def choose_house():
random_house = ['Gryffindor', 'Ravenclaw', 'Slytherin', 'Hufflepuff']
students = run()
chosen_house = random.choice(random_house)
chosen_student = random.choice(students)
print('Who has the next turn? {}'.format(chosen_student))
print('Which house are they in? {}'.format(chosen_house))
choose_house() |
31327f7a1b3a51b0cb8185cd70b572827e3ed4d5 | elootje98/DataProcessing | /Homework/Week_4/tojason.py | 871 | 3.765625 | 4 | import pandas
import csv
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import json
def main():
data = load_csv("data.csv")
# Only keep the year 2017
data = data[data['Year'] == 2017]
# Remove the row with World
data = data[data['Region'] != "World"]
# Drop the other columns
data = data.drop(columns=["0-27 days", "1-59 months", "Year"])
data = data.reset_index()
data_json = data.to_json(orient='records')
write_to_json("file.json", data_json)
def load_csv(input):
"""Loads the data from csv file into a pandas dataframe
Returns pandas dataframe"""
data = pd.read_csv(input)
return data
def write_to_json(outfile, data):
""" Writes data to a json file"""
file = open("file.json", "w")
file.write(data)
file.close()
if __name__ == "__main__":
main()
|
9487a2b061b53334ce0dea8edaca079bc65901c3 | netfj/Project_Stu02 | /stu04/02_iterator.py | 630 | 3.875 | 4 | #coding:utf-8
# 构造一个类,即是迭代器(generator),又是生成器(iterator)
from itertools import islice
class fib:
def __init__(self):
print('__init__')
self.prev=0
self.curr=1
def __iter__(self):
print('__iter__')
return self
def __next__(self):
print('__next__')
value = self.curr
self.curr += self.prev
self.prev = value
return value
f = fib()
for i in range(5):
print(next(f)) #iterator: 利用了fib类的迭代器性质
c = fib()
print(list(islice(c,0,4))) # generator: 利用类fib的生成器性质
|
eaae31ef73509454770db0f92bb9703b85ab2e18 | djfrigid/Projects | /Modules/creation.py | 2,584 | 3.5625 | 4 | from entities import player
import re
def create():
availablePoints = 10
while availablePoints > 0:
canAdd = True
print("You can still improve on yourself. Select one of the following to increase: " + "\n")
print("STR(currently " + str(player["STR"]) + ") : Your physical strength will affect the amount of damage you deal in combat." + "\n")
print("DEX(currently " + str(player["DEX"]) + ") : Your dexterity determines your odds of evading your opponents blows. " + "\n")
print("WIS(currently " + str(player["WIS"]) + ") : Your wisdom will determine both the number and quality of hints available to you. " + "\n")
print("STA(currently " + str(player["STA"]) + ") : Your stamina will determine the amount of special attacks you can use in combat. " + "\n")
print("CON(currently " + str(player["CON"]) + ") : Your body's constitution will determine the amount of health you have access to. " + "\n")
print("You have " + str(availablePoints) + " points left.")
choice = input("> ")
choice = choice.upper()
choice = choice.strip()
choice = re.sub(r"[^STR, DEX, WIS, STA, CON]", "", choice)
number = int(input("And how many points? "))
while number <= 0:
print("Thats not a number. Try again")
number = int(input("And how many points? "))
if availablePoints - number < 0:
print("You cannot assign that many points." + "\n" + "\n" + "You only have " + str(availablePoints) + " remaining" + "\n")
canAdd = False
if canAdd == True:
if choice == "STR":
player["STR"] += number
availablePoints -= number
elif choice == "DEX":
player["DEX"]+= number
availablePoints -= number
elif choice == "WIS":
player["WIS"]+= number
availablePoints -= number
elif choice == "STA":
player["STA"]+= number
availablePoints -= number
elif choice == "CON":
player["CON"]+= number
availablePoints -= number
else:
print("That's not an aspect of yourself, unless of course you are being a deliberate pain.You don't need to improve on that ")
player["MAXCON"] = player["CON"] |
0555e49171b4acba65e27b1409fdfd8cfca41c1a | victorlincoln/Python_Atividades | /OR- desconto loja.py | 382 | 4.03125 | 4 | # Cálculo de desconto loja, utilizando o conectivo lógico and
valor_compra = float(input("Digite o valor da compra"))
forma_pagamento = int(input(" 1 - Dinheiro / 2 - Cartão"))
if valor_compra > 100 or forma_pagamento == 1:
valor_compra = valor_compra * 0.9
print("Você tem direito a um desconto !!! ")
print("O valor a pagar é {}".format(valor_compra))
|
c5ff64dc1469281b959659bec448e3ce97ca8ba0 | rtjohnson12/rtjohnson12 | /python/games/monte hall/monte carlo proof.py | 427 | 3.671875 | 4 |
import random
num_runs = int(1e6)
first_choice_wins = 0
change_doors_wins = 0
doors = ['a', 'b', 'c']
for i in range(num_runs):
winner = random.choice(doors)
pick = random.choice(doors)
if pick == winner:
first_choice_wins += 1
else:
change_doors_wins += 1
print("Wins with original pick - {:.2%}\nWins with changed pick - {:.2%}".format(first_choice_wins / num_runs, change_doors_wins / num_runs))
|
bdf1108a9ae510f62a1883bdd7575aa24ab7fb8c | paul0920/leetcode | /question_leetcode/212_1.py | 1,369 | 3.640625 | 4 | class Solution(object):
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
y_size = len(board)
x_size = len(board[0])
visited = set()
res = []
for y in range(y_size):
for x in range(x_size):
self.dfs(board, set(words), visited, y, x, "", res)
return res
def checkValidPos(self, y, x, size_y, size_x):
if y < 0 or y >= size_y or x < 0 or x >= size_x:
return False
return True
def dfs(self, board, words, visited, y, x, path, res):
if not self.checkValidPos(y, x, len(board), len(board[0])) or (y, x) in visited:
return
path += board[y][x]
if path in words and not path in res:
res += [path]
visited.add((y, x))
for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
next_y = y + dy
next_x = x + dx
self.dfs(board, words, visited, next_y, next_x, path, res)
visited.remove((y, x))
board = [["b", "b", "a", "a", "b", "a"], ["b", "b", "a", "b", "a", "a"], ["b", "b", "b", "b", "b", "b"],
["a", "a", "a", "b", "a", "a"], ["a", "b", "a", "a", "b", "b"]]
words = ["abbbababaa"]
obj = Solution()
print obj.findWords(board, words)
|
6eb0ddf1a377afd2c845da32e79e89999f09ceee | Deniks/algorihmsForSchool | /water_cycle/paid_work.py | 298 | 3.859375 | 4 | daysInMoth = 28
weekends = 4 * 2 # 4 weeks multiplying by 2 days ( saturday, sunday )
wage = int(input("Your wage per day - ")) # we pay daily
workingDays = daysInMoth - weekends
print(wage * workingDays)
for i in range(workingDays):
i+=1
print(f'{i} day: {wage * i}') # income every day |
88e55d7410c2525cd696fd96b83f77b243d20598 | joanaritacouto/fdpython | /FDP/aula6/ex1e.py | 295 | 3.8125 | 4 | def listanum():
lista=[]
while True :
x= input('Número? ')
if len(x) == 0:
break
else:
x= float(x)
lista.append(x)
return lista
def maximo():
import math
max=-math.inf
l=listanum()
for i in l:
if i>max:
max=i
print ('máximo', max)
maximo()
|
72047fcd2c6b7159d2a9a140afd67e42b155df58 | CodingSoldier/python-learn | /python核心/a_/l04_rlock.py | 848 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import threading
from threading import RLock
total = 0
# 普通锁,同一个线程连续acquire两次,会造成死锁
# lock = threading.Lock()
# 重入锁,同一个线程中可以多次acquire,不会造成死锁,acquire多少次就得release多少次
lock = RLock()
def add():
global lock
global total
for i in range(1000000):
lock.acquire()
dosomething()
total += 1
lock.release()
def desc():
global total
global lock
for i in range(1000000):
lock.acquire()
total -= 1
lock.release()
def dosomething():
lock.acquire()
print("dosomething")
lock.release()
t1 = threading.Thread(target=add)
t2 = threading.Thread(target=desc)
t1.start()
t2.start()
t1.join()
t2.join()
print(total)
|
722e17b31dd9b655921307e57aa60a641bb35b5e | xczhang07/Python | /thread/thread_basic_1.py | 1,306 | 3.828125 | 4 | '''
learning script for python threading module, includes:
1. how to create thread target function
2. how to pass the target function into thread constructor
3. how to pass arguments to thread target function
4. how to set a thread as daemon thread (a daemon thread does not block the main program exit)
04/07 2018
author Xiaochong Zhang
'''
import threading
import time
import logging #logging is thread safe
logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] (%(threadName)-10s) %(message)s')
def worker(num):
logging.debug('starting')
print "Worker : %s" % num
logging.debug('ending')
return
def daemon():
logging.debug('starting')
time.sleep(5) # we should not see the ending message of daemon thread, the main program has already exit
logging.debug('ending')
def generate_threads(num):
threads = []
for i in range(num):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
def generate_daemon_thread():
dt = threading.Thread(name="daemon_thread", target=daemon) # using the "name" attribute of Thread can specify the name of a thread
dt.setDaemon(True)
dt.start()
dt.join() #after calling join() function of thread, main program will wait until all sub-thread ending
if __name__ == "__main__":
generate_threads(3)
generate_daemon_thread()
|
a9922e3c3060a02ea2c4357b43c5cdf556817527 | Rich43/rog | /albums/3/challenge102_easy/code.py | 1,388 | 4.375 | 4 | '''
In tabletop role-playing games like Dungeons & Dragons,
people use a system called dice notation to represent a
combination of dice to be rolled to generate a random
number. Dice rolls are of the form AdB (+/-) C, and are
calculated like this:
Generate A random numbers from 1 to B and add them together.
Add or subtract the modifier, C.
If A is omitted, its value is 1; if (+/-)C is omitted,
step 2 is skipped. That is, "d8" is equivalent to "1d8+0".
Write a function that takes a string like "10d6-2" or
"d20+7" and generates a random number using this syntax.
Here's a hint on how to parse the strings, if you get stuck:
Split the string over 'd' first; if the left part is empty, A = 1,
otherwise, read it as an integer and assign it to A. Then determine
whether or not the second part contains a '+' or '-', etc.
'''
import re
import random
def roll_dice(code):
pass
A = re.findall('^\d+|^\d', code)
try:
A = int(A[0])
except:
A = 1
B = re.findall('d(\d+|\d)', code)
B = int(B[0])
C = re.findall('([+|-]\d+|\d)', code)
C = int(C[-1])
sum_rand = 0
accum = 0
while accum < A:
random_number = random.randint(1, B)
sum_rand += random_number
accum += 1
sum_rand += C
return (sum_rand)
if __name__ == '__main__':
roll = '10d6-2'
ans = roll_dice(roll)
print(ans) |
5874713c34a7d44fa6e4c2a9a7cac3d28964556a | Navaneet-Butani/python_concept | /MySQL/join_table.py | 1,459 | 3.921875 | 4 | import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="123",
database="college"
)
my_curs = mydb.cursor()
# INNER JOIN
my_curs.execute("SELECT student.name, student.branch, teacher.t_name FROM student INNER JOIN teacher ON student.branch = teacher.branch")
result_inner = my_curs.fetchall()
print("Inner join result:")
for record in result_inner:
print(record)
# LEFT JOIN
my_curs.execute("SELECT student.name, student.branch, teacher.t_name FROM student LEFT JOIN teacher ON student.branch = teacher.branch")
result_left = my_curs.fetchall()
print("LEFT join result:")
for record in result_left:
print(record)
# RIGHT JOIN
my_curs.execute("SELECT student.name, student.branch, teacher.t_name FROM student RIGHT JOIN teacher ON student.branch = teacher.branch")
result_left = my_curs.fetchall()
print("LEFT join result:")
for record in result_left:
print(record)
# FULL JOIN
# We can't directly do FULL JOIN in MySQL
# But we can do that by the UNION of LEFT JOIN and RIGHT
my_curs.execute("SELECT student.name, student.branch, teacher.t_name FROM student LEFT JOIN teacher ON student.branch = teacher.branch \
UNION \
SELECT student.name, student.branch, teacher.t_name FROM student RIGHT JOIN teacher ON student.branch = teacher.branch")
result_full = my_curs.fetchall()
print("FULL JOIN result:")
for record in result_full:
print(record)
|
48b45266402daf7c6b2eae0d1128fce382265d0c | marcvernet31/redditScrapper | /userFunctions.py | 791 | 3.515625 | 4 |
"""
User functions are functions that by default don't do anything, but can be
modifyed by the end-user.
"""
"""
Conditional value for retrieveComments() function, that decides whether a comment
has to be stored. Can be used for example to filter out very short or low effort
comments, or to just keep comments with a certain word in it.
"""
def commentSpecs(comment):
# EX.: Just keep comments longer that 50 characters:
# if len(str(comment.body)) > 50: return True
# else: return False
return True
"""
Conditional value for retrievePosts() function, that decides if a post has
to be saved and it's conments explored. Useful to filter posts with little
comments or filter based on the topic of the submission body.
"""
def postSpecs(submission):
return True
|
eb0e70b1bc55f8c9abc72a8eb3797324b514d584 | Nico0106/CA268 | /w3-Sequences-set-and-maps/has_previous.py | 240 | 3.546875 | 4 | s = input()
list = []
while s != '-1':
list.append(s)
s = input()
a = []
i = 1
while i < len(list):
seen = list[:i]
if list[i] in seen:
a.append(list[i])
i += 1
print("Enter numbers (-1 to end):", " ".join(a))
|
a739292c6b91fb13eb0866c9cf45042e3a0ddc91 | SigCon/LED | /led.py | 3,010 | 3.734375 | 4 | import time
import random
from datetime import datetime
import RPi.GPIO as GPIO
# set a score for each player
scores = [0, 0]
listoftimes = []
names = []
# Say who won
def wingame(player):
"""The function wingame accepts the player who won as the only parameter"""
print names[player] + ' won!'
scores[player] += 1
def printline(repetition):
output = '---' * repetition
print output
# Print date and time
def printdate(repetition):
'''The function printdate accepts the number
of repetitions for the '---' string as the only parameter'''
now = datetime.now()
print '%s-%s-%s %s:%s:%s' % (now.day, now.month, now.year, now.hour, now.minute, now.second)
printline(repetition)
def printscore():
print ""
print ''
print "Scores:"
print " " + names[0] + ": " + str(scores[0])
print " " + names[1] + ": " + str(scores[1])
print "The LED went out after the following times in seconds: " + str(listoftimes)
print printdate(6)
# Make sure the GPIO pins are ready
GPIO.setmode(GPIO.BOARD)
# Choose which GPIO pins to use
led = 23
rightButton = 3
leftButton = 5
# Set the buttons as input and the LED as an output
GPIO.setup(led, GPIO.OUT)
GPIO.setup(rightButton, GPIO.IN)
GPIO.setup(leftButton, GPIO.IN)
# Find out the names of the players
leftPlayerName = raw_input("What is the left player's name? ")
rightPlayerName = raw_input("What is the right player's name? ")
games = int(raw_input("How many games do you want to play? "))
printline(10)
# Put the names in a list
names = [leftPlayerName, rightPlayerName]
# Play all the games
for game in range(0, games):
# Turn the LED on
printline(6)
print 'Game ' + str(game +1) + ' out of ' + str(games)
GPIO.output(led, 1)
# Generate a random time the led will be on
randnumber = int(random.uniform(1, 5))
# randnumber = random.uniform(1, 5)
listoftimes.append(randnumber)
# print randnumber
print ''
# Wait for a random length of time, between 1 and 5 seconds
time.sleep(randnumber)
'''One odd thing is that the buttons are on if they are not pressed and off when they are. This is why
the code says 'Left button pressed' when it finds that 'leftButton' is 'False'.
'''
# Check to see if a button is pressed
# If so, the other player wins
if GPIO.input(leftButton) == False:
print names[0] + " cheated!!!"
wingame(1)
elif GPIO.input(rightButton) == False:
print names[1] + " cheated!!!"
wingame(0)
else:
# Turn the led off
GPIO.output(led, 0)
# Wait until a button has been pressed
while GPIO.input(leftButton) and GPIO.input(rightButton):
pass # Do nothing!
# See if the left button has been pressed
if GPIO.input(leftButton) == False:
wingame(0)
# See if the right button has been pressed
if GPIO.input(rightButton) == False:
wingame(1)
printscore()
# Cleanup
GPIO.cleanup() |
d462c142b99a3168ea4b2f757e232dbdde6b58ad | Jeremy277/exercise | /pytnon-month01/month01-class notes/day14-fb/demo01.py | 1,422 | 3.734375 | 4 | #手雷炸了 伤害敌人/玩家的生命
#还有可能伤害未知生命(动物\花草...)
#增加事物时 不影响手雷
#手雷
class Grenade:
def __init__(self,atk=100):
self.atk = atk
def attack(self,victim):
if not isinstance(victim, Victim):
raise ValueError('目标对手雷免疫')
print('开始手雷攻击')
victim.damage(self.atk)
#从子类 抽象类
class Victim:
def damage(self,value):
raise NotImplementedError('如果子类不重写则异常')
#抽象代码
#-------------------------------------------
#具体代码
#敌人
class Enemy(Victim):
def __init__(self,hp=100):
self.hp = hp
def damage(self,value):
print('敌人减血')
self.hp -= value
if self.hp <= 0:
print('敌人死了')
#玩家
class Player(Victim):
def __init__(self, hp=101):
self.hp = hp
def damage(self, value):
print('玩家减血')
self.hp -= value
if self.hp <= 0:
print('玩家死了')
#小动物
class Critter(Victim):
def __init__(self, hp=20):
self.hp = hp
def damage(self, value):
print('小动物减血')
self.hp -= value
if self.hp <= 0:
print('小动物死了')
g01 = Grenade()
e01 = Enemy()
c01 = Critter()
p01 = Player()
g01.attack(e01)
g01.attack(p01)
g01.attack(p01)
g01.attack(c01)
|
6191b90ab6d4b1231687340867cb6098718f7566 | dimioan/My_Python | /exercises/chapter_7/F2.py | 410 | 3.609375 | 4 | # Exercise 7.11: F2.py
class F2:
def __init__(self, a, w):
self.a, self.w = a, w
def __call__(self, x):
a, w = self.a, self.w
r = (exp(-a*x))*sin(w*x)
return r
def __str__(self):
return 'exp(-a*x)*sin(w*x); a = %g, w = %g' %(self.a, self.w)
# code snippet for testing
from math import *
f = F2(1.0, 0.1)
print f(pi)
f.a = 2
print f(pi)
print f
|
dfd6525431fa459b0a934d9238977b274ab2e384 | Florence-TC/Zookeeper | /Topics/Taking input/Sum/main.py | 160 | 3.890625 | 4 | # put your python code here
number1 = int(input())
number2 = int(input())
number3 = int(input())
total_number = number1 + number2 + number3
print(total_number)
|
95d2f8d31e4b38733226bea9fa14c8b3cabcd4c9 | Maria-Lasiuta/geegs_girls_lab3 | /Olia V Lab 3 (1,6,11)/Question 1.py | 650 | 4.40625 | 4 | '''Question 1
The Fibonacci numbers are the sequence below, where the first two numbers are 1,
and each number thereafter is the sum of the two preceding numbers. Write a
program that asks the user how many Fibonacci numbers to print and then prints
that many
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …'''
count = int(input("How many fibonacci numbers would you like to print? "))
i = 1
if count == 0:
fib = []
elif count == 1:
fib = [1]
elif count == 2:
fib = [1,1]
elif count > 2:
fib = [1,1]
while i < (count - 1):
fib.append(fib[i] + fib[i-1])
i += 1
print(f'The number of Fibonacci: ',fib)
|
1106fecb260ff54cdd95e55860eeb2965215f075 | meexwaal/MarkOffProcessor | /opencv/path_planning.py | 2,169 | 3.65625 | 4 | import queue
neighborLists = {}
def initGraph(x, y):
return [[True for i in range(y)] for j in range(x)]
def neighbors(node, graph):
if node in neighborLists:
return neighborLists[node]
dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]]
result = []
for dir in dirs:
nx = node[0] + dir[0]
ny = node[1] + dir[1]
if 0 <= nx < len(graph) and 0 <= ny < len(graph[0]) and graph[nx][ny]:
result.append((nx, ny))
neighborLists[node] = result
return result
def dist(a, b):
(x1, y1) = a
(x2, y2) = b
return abs(x1 - x2) + abs(y1 - y2)
def aStarSearch(graph, start, goal, cameFrom):
pq = queue.PriorityQueue()
pq.put((0, start))
costSoFar = {}
costSoFar[start] = 0
while not pq.empty():
(ret, current) = pq.get()
if current == goal:
break
for next in neighbors(current, graph):
newCost = costSoFar[current] + 1
if next not in costSoFar or newCost < costSoFar[next]:
costSoFar[next] = newCost
priority = newCost + dist(goal, next)
pq.put((priority, next))
cameFrom[next] = current
if pq.empty():
return False,None
return True,cameFrom
def removeNodes(nodesList, graph):
for n in nodesList:
(x, y) = n
graph[x][y] = False
return graph
def planPathRecurse(start, nodesList, graph, path):
if not nodesList:
return path
cameFrom = {}
cameFrom[start] = None
mindist = None
minnode = None
for node in nodesList:
if mindist == None or dist(start, node) < mindist:
mindist = dist(start,node)
minnode = node
success,cameFrom = aStarSearch(graph, start, minnode, cameFrom)
nodesList.remove(minnode)
if success:
pathNew = reconstructPath(cameFrom, minnode)
pathNew.pop()
pathNew.reverse()
path.extend(pathNew)
else:
minnode = start
return planPathRecurse(minnode, nodesList, graph, path)
def reconstructPath(cameFrom, end):
path = []
while not end == None:
path.append(end)
end = cameFrom[end]
return path
def planPath(start, goodNodes, badNodes, x, y):
graph = initGraph(x, y)
graph = removeNodes(badNodes, graph)
return planPathRecurse(start, goodNodes, graph, [start])
|
988c75d475b91eb17ca96891598756251501962d | acamilass/learning-python | /parte1/ex-23/ex-23.py | 1,050 | 3.796875 | 4 | import func
print("CÁLCULO DO IMC\n")
valid_peso = False
valid_alt = False
valid_gen = False
while valid_gen == False:
genero = input("Informe o seu genero (M/F): ").lower()
if genero == "m" or genero == "f":
valid_gen = True
else:
print("Informe um genero válido M ou F")
while valid_peso == False:
peso = input("Informe o seu peso: ")
try:
peso = float(peso)
if peso <= 0:
print("Informe um peso maior que zero")
else:
valid_peso = True
except:
print("Informe um peso válido, separando as casas decimais por '.' ")
while valid_alt == False:
altura = input("Informe a sua altura: ")
try:
altura = float(altura)
if altura <= 0:
print("Informe uma altura maior que zero")
else:
valid_alt = True
except:
print("Informe uma altura válida, separando as casas decimais por '.' ")
print("O seu imc é: ", func.imc(peso, altura))
print(func.type_imc(genero, peso, altura))
|
4101611c547c9d978c38ebc958f5954fb31ffb13 | kxhsing/calculator-2 | /calculator-infix.py | 2,148 | 4.09375 | 4 | """A prefix-notation calculator.
Using the arithmetic.py file from Calculator Part 1, create the
calculator program yourself in this file.
"""
from arithmetic import *
# Your code goes here
while True:
guest_input = raw_input(">>>")
guest_input = guest_input.split(" ")
try:
if guest_input[0] == "q":
break
elif guest_input[1] == "+":
if len(guest_input) == 3:
print int(guest_input[0]) + int(guest_input[2])
else:
print "Please only input 2 numbers"
elif guest_input[1] == "-":
if len(guest_input) == 3:
print int(guest_input[0]) - int(guest_input[2])
else:
print "Please only input 2 numbers"
elif guest_input[1] == "*":
if len(guest_input) == 3:
print int(guest_input[0]) * int(guest_input[2])
else:
print "Please only input 2 numbers"
elif guest_input[1] == "/":
if len(guest_input) == 3:
print float(guest_input[0]) / int(guest_input[2])
else:
print "Please only input 2 numbers"
elif guest_input[0] == "square":
if len(guest_input) == 2:
print int(guest_input[1]) ** 2
else:
print "Please only input 1 number"
elif guest_input[0] == "cube":
if len(guest_input) == 2:
print int(guest_input[1])**3
else:
print "Please only input 1 number"
elif guest_input[1] == "**":
if len(guest_input) == 3:
print int(guest_input[0])**int(guest_input[2])
else:
print "Please only input 2 numbers"
elif guest_input[1] == "%":
if len(guest_input) == 3:
print int(guest_input[0]) % int(guest_input[2])
else:
print "Please only input 2 numbers"
else:
print "not a valid math operator. Please use + - * / mod cube pow or square."
except:
print "Not a valid number or math operator"
|
42e2c9966f5d5152ec16378745e65362bcc55caa | cvlong/data-structures | /sorting.py | 2,646 | 4.3125 | 4 | """SORTING ALGORITHMS."""
def bubble_sort(lst):
"""Return sorted list by checking side-by-side pairs; swapping if out of order.
>>>bubble_sort([5, 8, 2, 5, 9, 10, 1])
[1, 2, 5, 5, 8, 9, 10]
"""
# move through list first time
for i in range(len(lst) - 1):
# keep track of whether we made a swap
swapped = False
# move through list second time, only for unsorted portion
for j in range(len(lst) -1 -i):
# switch if out of order
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
swapped = True
if not swapped:
# if nothing swapped, then the list is already sorted, donezo
break
return lst
def merge_lists(lst1, lst2):
"""Merge two sorted lists into one sorted list.
>>>merge_lists([2, 6, 8], [4, 7, 9])
[2, 4, 6, 7, 8, 9]
"""
merged = []
while len(lst1) > 0 or len(lst2) > 0:
if lst1 == []:
merged.append(lst2.pop(0))
elif lst2 == []:
merged.append(lst1.pop(0))
elif lst1[0] > lst2[0]:
merged.append(lst2.pop(0))
else:
merged.append(lst1.pop(0))
return merged
def merge_sort(lst):
"""Divides input into lists of one element, then merges sorted lists.
>>>merge_sort([38, 27, 43, 3, 9, 82, 10])
[3, 9, 10, 27, 38, 43, 82]
"""
# base case: list contains one element, so it's sorted
if len(lst) < 2:
return lst
# divide list in half
mid = len(lst) / 2
left_lst = lst[:mid]
right_lst = lst[mid:]
# sort each half
left_lst = merge_sort(left_lst)
right_lst = merge_sort(right_lst)
# initialize output list
merged = []
# merge sorted sublists
while left_lst or right_lst:
# if one list is empty, add the remainder of the other list to output
if not left_lst:
merged.append(right_lst.pop(0))
elif not right_lst:
merged.append(left_lst.pop(0))
# if items in both lists, remove the smallest first item and add to output
elif left_lst[0] > right_lst[0]:
merged.append(right_lst.pop(0))
else:
merged.append(left_lst.pop(0))
return merged
# Alternative way with len(lst):
# while len(left_lst) > 0 or len(right_lst) > 0:
# if left_lst == []:
# merged.append(right_lst.pop(0))
# elif lst2 == []:
# merged.append(left_lst.pop(0))
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n ALL TESTS PASSED!! \n" |
f7022133d8fc88902a67ce68ded376c6483aca54 | ktown5422/LC101 | /initials/initials.py | 283 | 3.859375 | 4 | def get_initials(my_name):
name_list = my_name.split(" ")
init = ""
for name in name_list:
init += name[0]
return init.upper()
def main():
my_name = input("What is your full name?")
print(get_initials(my_name))
if __name__ == "__main__":
main() |
96df34232867fcb0e5786ddb1e4d63685a73488a | Sapna20dec/loop | /counting.py | 133 | 3.75 | 4 | # i=0
# while i<100:
# print(i)
# i=i+1
# i=0
# while i<100:
# if i%2==0 and i%5==0:
# print(i)
# i=i+1
|
b34066f10920c510f0bd80ea5eb42bd7171375c5 | pogross/bitesofpy | /221/nyt.py | 1,111 | 3.625 | 4 | import requests
YOUR_KEY = "42"
DEFAULT_LIST = "hardcover-nonfiction"
URL_NON_FICTION = (
f"https://api.nytimes.com/svc/books/v3/lists/current/"
f"{DEFAULT_LIST}.json?api-key={YOUR_KEY}"
)
URL_FICTION = URL_NON_FICTION.replace("nonfiction", "fiction")
def get_best_seller_titles(url=URL_NON_FICTION):
"""Use the NY Times Books API endpoint above to get the titles that are
on the best seller list for the longest time.
Return a list of (title, weeks_on_list) tuples, e.g. for the nonfiction:
[('BETWEEN THE WORLD AND ME', 86),
('EDUCATED', 79),
('BECOMING', 41),
('THE SECOND MOUNTAIN', 18),
... 11 more ...
]
Dev docs: https://developer.nytimes.com/docs/books-product/1/overview
"""
with requests.Session() as s:
data = s.get(url).json()
longest_on_list = [
(book["title"], int(book["weeks_on_list"])) for book in data["results"]["books"]
]
return sorted(longest_on_list, key=lambda x: x[1], reverse=True)
if __name__ == "__main__":
ret = get_best_seller_titles()
print(ret)
|
fd53eeeab9aee3d6e9d0a84182dcdfb8e60c7a54 | afnanenayet/DS-A | /generate_subsets.py | 1,506 | 4.21875 | 4 | # generate_subsets.py
# Afnan Enayet
# an algorithm to generate all subsets of a set
# note that this does not currently work likely because of an issue with
# references, but it gets the general idea
def gen_subsets(arr):
""" generates all subsets of a set of elements/list
Works by backtracking: every element either is or
isn't in a set. The recursive call stack essentially
is a tree where every left branch is not including the
element in the subset and every right branch is including
that element in the subset
:type arr: list
:rtype: List[list]
"""
subsets = [[]]
curr_sub = []
return subset_helper(arr, curr_sub, subsets, 0)
def subset_helper(arr, curr_sub, subsets, k):
""" helper method for gen_subsets that includes a list of subsets to
push to
:type arr: list
:type curr: list
:type ret: list
:type k: int
:rtype: List[list]
"""
# process subset
if k == len(arr):
print(curr_sub)
return subsets.append(curr_sub)
# Two cases: we either add the current element, or we don't
# this creates a new "branch", and from there we call the
# function again
minus_one = curr_sub
if curr_sub is None:
plus_one = [arr[k]]
minus_one = []
else:
plus_one = curr_sub.append(arr[k])
subset_helper(arr, minus_one, subsets, k + 1)
subset_helper(arr, plus_one, subsets, k + 1)
return subsets
# Test
test_arr = [1, 2]
print(gen_subsets(test_arr))
|
f21f77ad0d80e7602373db8ce4ae8d0e9bbd172e | Kontowicz/Daily-coding-problem | /day_129.py | 485 | 4.15625 | 4 | # Given a real number n, find the square root of n. For example, given n = 9, return 3.
def solution(value):
if value == 0 or value == 1:
return value
start = 1
end = value
while start <= end:
mid = (start + end) // 2
midPow = mid * mid
if midPow == value:
return mid
if midPow < value:
start = mid + 1
ans = mid
else:
end = mid - 1
return ans
print(solution(9)) |
49c197897455211007a81b3dde19bb0221dbcf42 | snowdj/Lab | /WB_wdi_all.py | 2,252 | 3.6875 | 4 | """
Messing around with World Bank data. We start by reading in the whole WDI
from the online csv. Since the online file is part of a zipped collection,
this turned into an exploration of how to handle zip files -- see Section 1.
Section 2 (coming) does slicing and plotting.
Prepared for the NYU Course "Data Bootcamp."
More at https://github.com/NYUDataBootcamp/Materials
References
* http://datacatalog.worldbank.org/
* http://stackoverflow.com/questions/19602931/basic-http-file-downloading-and-saving-to-disk-in-python
* https://docs.python.org/3.4/library/urllib.html
Written by Dave Backus @ NYU, September 2014
Created with Python 3.4
"""
import pandas as pd
import urllib
import zipfile
import os
"""
1. Read data from component of online zip file
"""
# locations of file input and output
url = 'http://databank.worldbank.org/data/download/WDI_csv.zip'
file = os.path.basename(url) # cool tool via SBH
# the idea is to dump data in a different directory, kill with data = ''
data = '' # '../Data/'
#%%
# copy file from url to hard drive (big file, takes a minute or two)
urllib.request.urlretrieve(url, data+file)
#%%
# zipfile contains several files, we want WDI_Data.csv
print(['Is zipfile?', zipfile.is_zipfile(file)])
# key step, give us a file object to work with
zf = zipfile.ZipFile(data+file, 'r')
print('List of zipfile contents (two versions)')
[print(file) for file in zf.namelist()]
zf.printdir()
#%%
# copy data file to hard drive's working directory, then read it
csv = zf.extract('WDI_Data.csv')
df1 = pd.read_csv('WDI_Data.csv')
print(df1.columns)
#%%
# alternative: open and read
csv = zf.open('WDI_Data.csv')
df2 = pd.read_csv(csv)
print(df3.columns)
#%%
# same thing in one line
df3 = pd.read_csv(zf.open('WDI_Data.csv'))
print(df3.columns)
# zf.close() #??
# do we want to close zf? do we care?
# seems to be essential with writes, not so much with reads
# if so, can either close or use the "with" construction Sarah used.
# basic open etc:
# https://docs.python.org/3.4/tutorial/inputoutput.html#reading-and-writing-files
# on with (go to bottom): http://effbot.org/zone/python-with-statement.htm
#%%
# could we further consolidate zip read and extract? seems not.
#zf = zipfile.ZipFile(url, 'r')
|
90b09d8eafa7303ffe45c5cfa1171b33216b1441 | yamogi/Python_Exercises | /ch03/maitre_d.py | 469 | 3.796875 | 4 | # Maitre D'
# Demonstrates treating a value as a condition
print("Welcome to the Chateau D' Food")
print("It seems we are quite full this evening.\n")
money = int(input("\t How many dollars do you slip the maitre D'? "))
print()
if money: # if any money at all
print("Ah, I am reminded of a table. Right this way.") # money == true
else: # if zero (0) money is given
print("Please sit. It may be a while.") # money == false
input("\n\nPress enter to exit.")
|
a2c04e9b2f0b6aef548368cd4a73ce56fcc0bb0d | lingshanng/my-python-programs | /Fun/Battleship.py | 1,651 | 4.15625 | 4 | # Battleship game
from random import randint
# create board
ROW = 5
COL = 5
board = [["0" for COL in range(COL)] for row in range(ROW)]
def print_board(board):
for row in board:
print (" ".join(row))
print_board(board)
# generate random battleship position
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
CHANCES = 4
for turn in range(CHANCES): # 4 chances
print ("Turn", turn + 1) # indicates turn num
thisturn = True
while thisturn:
guess_row = input("Guess Row (0-4): ") # player guess
guess_col = input("Guess Col (0-4): ")
if len(guess_row) == 0 or len(guess_col)== 0:
print("Missing coordinates.")
elif int(guess_row) not in range(ROW) or int(guess_col) not in range(COL):
print("Oops, out of range.")
elif board[int(guess_row)][int(guess_col)] == "X":
print( "You guessed that one already." )
else:
thisturn = False
guess_row = int(guess_row)
guess_col = int(guess_col)
if guess_row == ship_row and guess_col == ship_col:
print ("Congratulations! You sank my battleship!") # correct guess
break
else:
print ("You missed my battleship!")
board[guess_row][guess_col] = "X"
if (turn == CHANCES - 1):
print ("Game Over")
board[ship_row][ship_col] = "S" # reveal answer
print_board(board)
else:
print_board(board) # show status of board
# improvements:
# multiple battleships + bigger board - no overlap
# diff size battleship - connecting sides, no lying off board
# two player
|
9c78c5a95e3b79113b22c9e1632d60f5cb99f196 | ling-lin/LeetCode-with-Python | /566_reshape-the-matrix.py | 1,014 | 3.53125 | 4 | class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
rownums = len(nums)
colnums = len(nums[0])
if r*c != rownums*colnums:
return nums
if c == 0:
return []*r
nums_new = []
for i in range(rownums):
nums_new = nums_new + nums[i]
re_nums = []
for i in range(r):
re_nums.append(nums_new[c*i:c*(i+1)])
return re_nums
##another code
class Solution(object):
def matrixReshape(self, nums, r, c):
if len(nums) * len(nums[0]) != r * c:
return nums
if c == 0:
return [] * r
res = []
sub = []
for row in nums:
for num in row:
sub.append(num)
if len(sub) == c:
res.append(sub)
sub = []
return res
|
2a104dcc371d71a156fb9659b072a2141cee9bfb | angq515/upythoncentos-master | /函数的参数_作业.py | 800 | 3.890625 | 4 | # 练习
# 以下函数允许计算两个数的乘积,请稍加改造,变成可接收一个或多个数并计算乘积:
# _*_ codiong: utf-8 -*-
def product(*x):
if x == ():
raise TypeError()
jieguo = 1
for i in x:
jieguo *= i
return jieguo
# 测试
print('product(5) =', product(5))
print('product(5, 6) =', product(5, 6))
print('product(5, 6, 7) =', product(5, 6, 7))
print('product(5, 6, 7, 9) =', product(5, 6, 7, 9))
if product(5) != 5:
print('测试失败!')
elif product(5, 6) != 30:
print('测试失败!')
elif product(5, 6, 7) != 210:
print('测试失败!')
elif product(5, 6, 7, 9) != 1890:
print('测试失败!')
else:
try:
product()
print('测试失败!')
except TypeError:
print('测试成功!')
|
cbb91c77e3f76e8fa8091a15959cc8b785e006f4 | romeorizzi/temi_prog_public | /2018.12.05.provetta/all-CMS-submissions-2018-12-05/2018-12-05.12:06:02.288887.VR437227.conta_inversioni.py | 629 | 3.53125 | 4 | """
* user: VR437227
* fname: DAVIDE
* lname: COPPOLA
* task: conta_inversioni
* score: 100.0
* date: 2018-12-05 12:06:02.288887
"""
# -*- coding: utf-8 -*-
# Template per la soluzione del problema conta_inversioni
from __future__ import print_function
import sys
if sys.version_info < (3, 0):
input = raw_input # in python2, l'equivalente di input è raw_input
def numero_di_inversioni(p):
c=0
for i in range (len(p)):
for j in range(i+1,len(p)):
if p[i]>p[j]:
c=c+1
return c
p = list(map(int, input().strip().split()))
print(numero_di_inversioni(p))
|
7ba588d081a53485cbf542da76639fb863f9332a | sxz1537/PATtest | /1011 A+B 和 C (15 分).py | 364 | 3.609375 | 4 | def isTrue(x,y,z):
if x+y>z:
return True
return False
N=int(input())
for i in range(1,N+1):
x,y,z=map(int,input().split())
t=isTrue(x,y,z)
if t:
print ("Case #",end="")
print (i,end="")
print (': true')
else:
print ("Case #",end="")
print (i,end="")
print (': false') |
c3db6e40e20d3b746432443038ce632c370654b3 | stein212/turtleProject | /tryTurtle.py | 1,856 | 4.21875 | 4 | import turtle
# hide turtle
turtle.ht() # or turtle.hideturtle()
# set turtle speed to fastest
turtle.speed(0)
# fastest: 0
# fast: 10
# normal: 6
# slow: 3
# slowest: 1
# draw square manually
for i in range(4):
turtle.forward(10)
turtle.left(90)
# move turtle position
turtle.penup()
turtle.setpos(30, 0)
turtle.pendown()
# draw circle using turtle's api
turtle.circle(10) # the circle draws from the bottom -> top -> bottom
# move turtle position
turtle.penup()
turtle.setpos(60, 0)
turtle.pendown()
# draw an arc
turtle.circle(10, 90)
# move turtle position
turtle.penup()
turtle.setpos(90, 0)
turtle.pendown()
# draw a diamond
turtle.setheading(0) # set the direction the turtle is facing
turtle.circle(10, steps = 4)
# move turtle position
turtle.penup()
turtle.setpos(120, 0)
turtle.pendown()
# draw a square
turtle.left(45)
turtle.circle(10, steps = 4)
# move turtle position
turtle.penup()
turtle.setpos(0, 30)
turtle.pendown()
# draw a blue line
turtle.color("blue")
turtle.forward(10)
# set color back to black
turtle.color("black")
# move turtle position
turtle.penup()
turtle.setpos(30, 30)
turtle.pendown()
# draw rectangle with green fill and black stroke
turtle.setheading(0)
turtle.color("black", "green")
turtle.begin_fill()
turtle.forward(10)
turtle.left(90)
turtle.forward(5)
turtle.left(90)
turtle.forward(10)
turtle.left(90)
turtle.forward(5)
turtle.left(90)
turtle.end_fill()
# move turtle position
turtle.penup()
turtle.setpos(60, 30)
turtle.pendown()
# write some text
turtle.write("Hello World!", font=("Arial", 8, "normal"))
# move turtle position
turtle.penup()
turtle.setpos(120, 30)
turtle.pendown()
# write some text
turtle.write("Hello World Again!", font=("Arial", 10, "bold"))
# turtle.write has 2 more parameters which is align and move, align is more important in this project
turtle.exitonclick() |
ff2ee8d69b3cc4adaecd46489e2d2cd45a30d481 | kdeng/python-tutorials | /10.advance_funcs/do_map.py | 203 | 3.640625 | 4 | def normalize(name):
if isinstance(name, str):
return name.lower().capitalize()
else:
return None
L1 = ['adam', 'LISA', 'barT', 123, []]
L2 = list(map(normalize, L1))
print(L2)
|
d9f10ad3358a9bb2325b2aaecfad504c1b746c53 | Sathyasree-Sundaravel/sathya | /Program_to_print_the_Kth_odd_number.py | 166 | 3.515625 | 4 | #Program to print the Kth odd number
a,b=map(int,input().split())
c=list(map(int,input().split()))
L=[]
for i in c:
if(i%2!=0):
L.append(i)
print(L[b-1])
|
07fbe1fbfafdd61be0f9f6bcd58f35741e257383 | diego-sepulveda-lavin/bill-splitter | /Bill Splitter/task/billsplitter.py | 1,821 | 4.0625 | 4 | from random import choice
def lucky_winner(luck_enabled, payment_detail):
luck_enabled = luck_enabled.lower()
if luck_enabled == 'no' or luck_enabled == 'n':
print("No one is going to be lucky")
return None
elif luck_enabled == "yes" or luck_enabled == 'y':
participants = []
for friend_name in payment_detail:
participants.append(friend_name)
winner = choice(participants)
print(f"{winner} is the lucky one!")
return winner
else:
print('Incorrect choice. "NO" is assumed')
return None
def calculate_bill(friends_number, payment_detail, total, winner):
if winner:
friends_number -= 1
payment_per_person = round(total / friends_number, 2)
for friend in payment_detail:
if winner == friend:
continue
payment_detail[friend] = payment_per_person
def generate_empty_bill(friends_number):
payment_detail = {}
for i in range(friends_number):
name = input()
payment_detail[name] = 0
return payment_detail
try:
print("Enter the number of friends joining (including you):")
friends_qty = int(input())
if friends_qty < 1:
print("No one is joining for the party")
else:
print("Enter the name of every friend (including you), each on a new line:")
bill_detail = generate_empty_bill(friends_qty)
print("Enter the total bill value:")
bill_total = int(input())
print('Do you want to use the "Who is lucky?" feature? Write Yes/No:')
luck_feature = input()
lucky_one = lucky_winner(luck_feature, bill_detail)
calculate_bill(friends_qty, bill_detail, bill_total, lucky_one)
print(bill_detail)
except ValueError:
print("Please enter a valid number")
|
88ca098d3032b124c5e6c72dfcaa3a4a4216cac5 | gjwlsdnr0115/Computer_Programming_Homework | /lab9_2015198005/lab9_p3.py | 1,283 | 4.375 | 4 | def is_Palindrome(s):
'''
A recursive function that returns whether input string is a palindrome
:param s: input string
:return: boolean result
'''
#stopping case 1
if len(s) <= 1: #string length is 1
return True
#stopping case 2
if s[0] != s[len(s)-1]: #first character and last character are not identical
return False
#recursive call of is_Palindrome()
short_s = s[1:len(s)-1] #make a substring by striping the first and last character
return is_Palindrome(short_s) #recursively call the function with the substring as input
#print welcome statement
print('This program can determine if a given string is a palindrome\n')
print('(Enter return to exit)')
#init boolean variable
more = True
while more:
#user input
chars = input('Enter string to check: ')
if chars == '':
more = False #stop program
else:
#input has one letter
if len(chars) == 1:
print('A one letter word is by definition a palindrome\n')
else:
result = is_Palindrome(chars)
if result: #result is True
print(chars, 'is a palindrome\n')
else: #result is False
print(chars, 'is NOT a palindrome\n')
|
cb3a81ddcac32d0931335242ad0684b837bc6fc2 | islomov/python-point-of-sale | /utils/geometry.py | 687 | 3.953125 | 4 | def get_line_equation(beginning_point, ending_point):
"""
Y = Slope*X + b
get_slope -> Slope
get_b -> b
"""
def get_slope():
return (beginning_point.y - ending_point.y) / (beginning_point.x - ending_point.x)
def get_b(s):
return beginning_point.y - beginning_point.x * s
slope = get_slope()
b = get_b(slope)
return slope, b
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __call__(self, *args, **kwargs):
return self.x, self.y
def __str__(self):
return '{},{}'.format(self.x, self.y)
def __repr__(self):
return '{},{}'.format(self.x, self.y)
|
162fa46454367322ec6b8531e5e0366da234c37b | andrewwhwang/AoC2020 | /01.py | 802 | 3.734375 | 4 | def parse(input):
res = input.split('\n')
res = [int(num) for num in res]
return res
# O(n), Use set for constant look up times
def complement_product(target, nums):
num_set = set(nums)
for num in nums:
complement = target - num
if complement in num_set:
return num * complement
return None
if __name__ == "__main__":
# get list of nums from input
with open('inputs/01.txt', 'r') as file:
input = file.read()
nums = parse(input)
# part 1
complement = complement_product(2020, nums)
print(complement)
# part 2
for num in nums:
complement1 = 2020 - num
complement2 = complement_product(complement1, nums)
if complement2:
print(num * complement2)
break
|
ffd055d8d84659b78b1b99bc875802d39dd7bfc0 | Seaworth/Python-learning | /day02/day02_ex05.py | 428 | 3.75 | 4 | # -*- coding: utf-8 -*-
# Python 2.7.14
# 练习5:
# 分三次输入当前的小时,分钟和秒数
# 打印此时距离0:0:0已过了多少秒
hour_num=int(input('please input hour now:'))
minute_num=int(input('please input minute now:'))
second_num=int(input('please input second now:'))
second_total=hour_num*3600+minute_num*60+second_num
print '此时距离0:0:0已过了{}秒'.format(second_total)
# 练习5 over
|
18f1b02b07d448ee1e8ba0b784805d953b9699e6 | rajsingh661/python-lab | /to check duplicates in a string.py | 166 | 4.09375 | 4 | def removeDuplicate(str):
s=set(str)
s="".join(s)
print("resultant string:",s)
t=""
str=input("Enter the string")
removeDuplicate(str)
|
f3b84340dee2cd807bebc0a8a31618fd5c0e6fbd | azhou5211/recipeat | /modules/comparator.py | 3,531 | 3.5 | 4 | import requests
from bs4 import BeautifulSoup
class Compare:
"""
Class that is used to compare recipes.
"""
@staticmethod
def nutrient_compare(recipe_list):
"""
returns HTML response with a information on nutrients in given recipes
Args:
recipe_list: list of recipe objects
Returns: list of HTML responses with nutrition information graphics
"""
nutr_html_list = []
for recipe in recipe_list:
url = (
"https://spoonacular-recipe-food-nutrition-"
"v1.p.rapidapi.com/recipes/{id}"
"/nutritionWidget?defaultCss=true"
).format(id=recipe.recipe_id)
payload = {}
headers = {
"accept": "text/html",
"x-rapidapi-key": ("c65a4130b1msh767c11b9104"
"ee56p1a93cdjsn9f1028eb2e98"),
"x-rapidapi-host": ("spoonacular-recipe-food"
"-nutrition-v1.p.rapidapi.com"),
}
response = requests.request("GET", url,
headers=headers, data=payload)
soup = BeautifulSoup(response.text, "html.parser")
for div in soup.find_all("div", {'style': ('margin-top:3px;margin-'
'right:10px;text-align:'
'right;')}):
div.decompose()
nutr_html_list.append(
'<div class="header"><h3>{recipe_name}</h3></div>'.format(
recipe_name=recipe.recipe_name
) + str(soup)
)
return nutr_html_list
@staticmethod
def ingredient_compare(recipe_list):
"""
returns HTML response with a information
on ingredients in given recipes
Args:
recipe_list: list of recipe objects
Returns: list of HTML responses with ingredient graphics
"""
ingrd_html_list = []
for recipe in recipe_list:
url = (
"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com"
"/recipes/{id}"
"/ingredientWidget?defaultCss=true"
).format(id=recipe.recipe_id)
payload = {}
headers = {
"accept": "text/html",
"x-rapidapi-key": ("c65a4130b1msh767c11b9104"
"ee56p1a93cdjsn9f1028eb2e98"),
"x-rapidapi-host": ("spoonacular-recipe-food-"
"nutrition-v1.p.rapidapi.com"),
}
response = requests.request("GET", url,
headers=headers, data=payload)
soup = BeautifulSoup(response.text, "html.parser")
for div in soup.find_all("div", {'class': ('spoonacular-ingredient'
's-menu')}):
div.decompose()
for div in soup.find_all("div", {'style': ('margin-top:3px;margin-'
'right:10px;text-align:'
'right;')}):
div.decompose()
ingrd_html_list.append(
'<div class="header"><h3>{recipe_name}</h3></div>'.format(
recipe_name=recipe.recipe_name
) + str(soup)
)
return ingrd_html_list
|
effb359fc503f9b7dcd6f8eb7389ef528e666e4b | ashcoder2020/Numpy | /eye_function.py | 489 | 3.828125 | 4 | import numpy as np
#Eye() #set diagonal values
x = np.eye(5) #draw 5*5 diagonal matrix
print(x)
x = np.eye(2,3) #2 row 3 column with diagonal matrix
print(x)
x = np.eye(4,k=-1) #lower diagonal 1 is -ve index k=-ve
print(x)
x = np.eye(4,k=1) #upper diagonal 1 is +ve index k=+ve
print(x)
x = np.identity(4) #return identity matrix 4*4
print(x)
|
52bb2741efd30fb1c8ab720013c4f9180511f32f | fedexrv24/autoevaluacion-tecnicas | /001.py | 136 | 4.15625 | 4 | caracter = ""
string = input("Ingresar cadena de texto: ").strip()
for i in string:
print(caracter + i)
caracter += "_" |
0d8f34918e970df44e301418272ba12732f80b22 | anuragdandge/Python-Basic-Programs | /function .py | 255 | 3.84375 | 4 |
def add(a,b):
return a+b
def sub(a,b):
return a-b
def div(a,b):
return a/b
def mul(a,b):
return a*b
a = int(input("Enter a "))
b = int(input("Enter b "))
print(add(a,b))
print(sub(a,b))
print(div(a,b))
print(mul(a,b))
|
f18f3db739a057e686063bb73dc844f2245d8407 | kiiikii/ptyhon-learn | /lab-operator-expression.py | 291 | 4.3125 | 4 | # Scenario
# ------------------
# Your task is to complete the code in order to evaluate the following expression:
# 1 / x + 1 / x + 1 / x + 1 / x
x = float(input("Enter value for x: "))
# put your code here
y = round((x ** 3) + (2 * x)) / ((x ** 4) + (3 * x ** 2) + 1)
print("y =", y) |
44ac8dda2cbd75af1eaf7f94a106ad3172f3df4b | masterfon/Rodnam | /school/compsciprinc/tomsencrypt.py | 878 | 3.796875 | 4 | #!/usr/bin/python3
import sys
#Input
filename = sys.argv[1]
file = open(filename, 'r')
passage = file.read()
new = []
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet += alphabet.upper()
#Encrypt/ decrypt passage
words = passage.split(' ')
for word in words:
total = 0
letters = 0
for letter in word:
if letter not in alphabet:
pass
else:
index = alphabet.index(letter) + 1
total += index
letters += 1
if letters is not 0:
rotation = int(round(total/letters))
else:
continue
newword = ''
for letter in word:
if letter not in alphabet:
newword += letter
else:
index = alphabet.index(letter) + 1
index += rotation
if index > 26:
index = abs(26-index)
newword += alphabet[index - 1]
new.append(newword)
#Output
file.close()
filenew = open(filename, 'w')
filenew.write(" ".join(new))
filenew.close()
print(" ".join(new)) |
6c6881afaf3113d545fc81f11ae7c1e16b1c2c1f | tcsirvine/colors | /colors.py | 567 | 3.53125 | 4 | import turtle
def getGradient():
colors = []
rgb = [255, 0, 0]
rateofchange = 10
for i in range(2):
for j in range(255/rateofchange):
rgb[i + 1] += rateofchange
colors.append(list(rgb))
rgb[i + 1] = 255
for j in range(255/rateofchange):
rgb[i] -= rateofchange
colors.append(list(rgb))
rgb[i] = 0
return colors
colors = getGradient()
turtle.speed(0)
for i in range(1000):
index = int(i/10) % len(colors)
color = colors[index]
turtle.color(color)
turtle.forward(i)
turtle.right(95)
|
f4a44e0c0046af1fabd7455b0c3ee35069ad6297 | qinqiang2000/machine-learning-andrew | /ex6_svm/svm_spam.py | 3,704 | 4 | 4 | """
Machine Learning Online Class
Exercise 6 | Spam Classification with SVMs """
import numpy as np
import scipy.io as sio # Used to load the OCTAVE *.mat files
from sklearn import svm
from processEmail import processEmail, getVocabList
## ==================== Part 1: Email Preprocessing ====================
# To use an SVM to classify emails into Spam v.s. Non-Spam, you first need
# to convert each email into a vector of features. In this part, you will
# implement the preprocessing steps for each email. You should
# complete the code in processEmail.m to produce a word indices vector
# for a given email.
print("Preprocessing and extracting features sample email (emailSample1.txt)")
# Extract Features
with open('emailSample1.txt', 'r') as f:
features =processEmail(f.read())
print('length of vector = {}\nnum of non-zero = {}'
.format(len(features), int(features.sum())))
print(features.shape)
## =========== Part 2: Train Linear SVM for Spam Classification ========
# In this section, you will train a linear classifier to determine if an
# email is Spam or Not-Spam.
# Load the Spam Email dataset
# You will have X, y in your environment
mat = sio.loadmat('spamTrain.mat')
X, y = mat['X'], mat['y']
print("\nTraining Linear SVM (Spam Classification)")
print("(this may take 1 to 2 minutes) ...")
C = 0.1
clf = svm.SVC(C, kernel='linear') # model
clf.fit(X, y.ravel()) # train
p = clf.predict(X)
print("C = %.1f, the accuracy of train data set: %f" %(C, clf.score(X, y)))
## =================== Part 3: Test Spam Classification ================
# After training the classifier, we can evaluate it on a test set. We have
# included a test set in spamTest.mat
# Load the test dataset
# You will have Xtest, ytest in your environment
mat = sio.loadmat('spamTest.mat')
Xtest, ytest = mat['Xtest'], mat['ytest']
print("C = %.1f, the accuracy of test data set: %f" %(C, clf.score(Xtest, ytest)))
## ================= Part 4: Top Predictors of Spam ====================
# Since the model we are training is a linear SVM, we can inspect the
# weights learned by the model to understand better how it is determining
# whether an email is spam or not. The following code finds the words with
# the highest weights in the classifier. Informally, the classifier
# 'thinks' that these words are the most likely indicators of spam.
#
# Sort the weights and obtin the vocabulary list
idx = np.argsort(clf.coef_, axis=None )[::-1] #[::-1] 表示数组反转
vocabList = getVocabList()
print('\nTop predictors of spam: ')
for i in range(15):
j = idx[i]
print("{} ".format(vocabList[j]))
## =================== Part 5: Try Your Own Emails =====================
# Now that you've trained the spam classifier, you can use it on your own
# emails! In the starter code, we have included spamSample1.txt,
# spamSample2.txt, emailSample1.txt and emailSample2.txt as examples.
# The following code reads in one of these emails and then uses your
# learned SVM classifier to determine whether the email is Spam or
# Not Spam
# Set the file to be read in (change this to spamSample2.txt,
# emailSample1.txt or emailSample2.txt to see different predictions on
# different emails types). Try your own emails as well!
files = ['spamSample1.txt', 'spamSample2.txt', 'emailSample1.txt', 'emailSample2.txt']
for filename in files:
# Read and predict
# Extract Features
with open(filename, 'r') as f:
features =processEmail(f.read())
# 转换为2D array
x = features.reshape(1, -1)
p = clf.predict(x)
print("\nProcessed %s\nSpam Classification: %d" % (filename, p))
print("(1 indicates spam, 0 indicates not spam)\n") |
09d77119cacda6b6e1dd301d5cf6ccbeafe203c6 | AuroraBoreas/language-review | /20210523LangReview/Python/10-property/property.py | 1,220 | 3.9375 | 4 | """
Python
@poperty
@classmethod
@staticmethod
>> these two methods are accessible at class-level
>> BUT, @staticmethod is immutable via inheritance
>> while, @classmethod is inheritable
"""
class Point:
def __init__(self, a: int, b: int):
self._a = a
self._b = b
# ^ simpler implementation of getter/setter in Python
# ^ the concept under the hood is same with C#
@property
def center(self):
return (self._a + self._b) / 2
@classmethod
def hello(cls):
return "class Point says hello"
@staticmethod
def call():
return "u call i come"
class Derived(Point):
def normal_method(self):
return "normal method"
@classmethod
def hello(cls):
return "class Derived says hello"
@staticmethod
def call():
return "class Derived says U call I come"
if __name__ == "__main__":
p1: Point = Point(1, 2)
print(p1.center)
print(Point.hello())
print(p1.call())
print(Point.call())
# $ test difference between classmethod vs staticmethod
p2: Derived = Derived(2, 3)
print(p2.call()) # % OK?
print(p2.hello()) # % OK? |
98ee85a5102b4526babab9eb2266767ebed54c27 | jorzel/codefights | /bots/godaddybot/domainType.py | 1,125 | 3.71875 | 4 | """
GoDaddy makes a lot of different top-level domains available to its customers. A top-level domain is one that goes directly after the last dot ('.') in the domain name, for example .com in example.com. To help the users choose from available domains, GoDaddy is introducing a new feature that shows the type of the chosen top-level domain. You have to implement this feature.
To begin with, you want to write a function that labels the domains as "commercial", "organization", "network" or "information" for .com, .org, .net or .info respectively.
For the given list of domains return the list of their labels.
Example
For domains = ["en.wiki.org", "codefights.com", "happy.net", "code.info"], the output should be
domainType(domains) = ["organization", "commercial", "network", "information"].
"""
def domainType(domains):
domains_dict = {
'com': 'commercial',
'org': 'organization',
'net': 'network',
'info': 'information'
}
types = []
for domain in domains:
_type = domain.split('.')[-1]
types.append(domains_dict.get(_type))
return types
|
1791aabe69dd2adf7d58ccdd76b447e8ac19f42b | tanaypatil/code-blooded-ninjas | /bit_manipulation/set_ith_bit.py | 335 | 3.859375 | 4 | """
You are given two integers N and i. You need to make ith bit of binary representation of N to 1 and return the updated N.
"""
## Read input as specified in the question.
## Print output as specified in the question.
def main():
n, i = map(int, input().split())
print(n|(1<<i))
if __name__ == "__main__":
main()
|
b73e6e8b73b14847abd26ad237386d3ad7367904 | Vovanuch/python-basics-1 | /elements, blocks and directions/classes/class1_MyClass.py | 280 | 3.90625 | 4 | ''' Классы. Начало. '''
class MyClass:
a = 10
def func(self=None):
print('Hello from MyClass!')
print(MyClass.a)
print(MyClass.func())
print()
mc = MyClass()
mc.func()
print(f'mc type is {type(mc)}' )
print(f'MyClass type is {type(MyClass)}' )
|
b6be044ff47384cbdcf87a359e924dc7fe30ab87 | marcw1/Project | /Node.py | 1,613 | 3.5 | 4 | from copy import deepcopy
import random
class Node:
def __init__(self, pred, board, action):
self.pred = pred
self.children = []
self.wins = 0
self.visits = 0
self.board = board
self.value = 0
self.action = action
if pred is None:
self.depth = 0
else:
self.depth = pred.depth + 1
self.untriedActions = self.board.checkActions()
random.shuffle(self.untriedActions)
# used for min heap
def __lt__(self, other):
return self.total < other.total
# hashes based on board
def __hash__(self):
return hash(self.board)
def __str__(self):
myString = "move: " + str(self.action) + \
'\n wins:' + str(self.wins) + \
'\n visits:' + str(self.visits) + \
'\n depth:' + str(self.depth)
return myString
# randomly expands an action to return a child node
def expand(self):
action = self.untriedActions.pop()
newBoard = deepcopy(self.board)
newBoard.doAction(action)
child = Node(self, newBoard, action)
self.children.append(child)
return child
# evaluates a board
#def boardEval(self, board):
''' f = no. my teams pieces - no. enemy team pieces
'''
'''
f = board.pieces[board.current_team] - board.pieces[board.enemy_team]
value = f
self.value = value
return value
# evaluates an action
def actionEval(self, board, action):
pass
'''
|
45c66893deb44636d2bd1687c389e57355376ce5 | vgrozev/SofUni_Python_hmwrks | /Programming Basics with Python - април 2018/02. Прости пресмятания/10. Radians to Degrees.py | 78 | 3.578125 | 4 | import math
rad = float(input())
deg = rad * 180/math.pi
print(round(deg))
|
530572b138bb5c71efeab827e1c2b6162dd5a812 | Kartikey252/Short-Python-Programs | /Check-Disarium.py | 566 | 4.40625 | 4 | """
A number is said to be the Disarium number when the sum of its digit raised to the power of their respective positions is equal to the number itself.
For example, 175 is a Disarium number as follows
1^1 + 7^2 + 5^3 = 1 + 49 + 125 = 175
"""
# Gives A List Of Disariums up till the Number You Entered
try:
range_ = int(input())
except:
print('You Didn\'t Entered a Number.\nTaking Input as : 1000')
range_ = 1000
for num in range(range_+1):
if num == sum(map(int(i)**(x+1) for i, x in enumerate(str(num)))):
print(f'{num} is Disarium.') |
9979019ae3756682e49c046e347d5d778b15e3a3 | tkoz0/problems-project-euler | /p032a.py | 1,551 | 3.625 | 4 | import math
# n1 digits, n2 digits, n1*n2 digits
# n1*n2 will have either n1+n2 or n1+n2-1 digits
# suppose n1 has a digits and n2 has b digits
# min is 10^(a-1) * 10^(b-1) = 10^(a+b-2) has a+b-1 digits
# max is (10^a-1) * (10^b-1) < 10^(a+b) has a+b digits
# possibilities for digits in (n1,n2,n1*n2) are
# (1,4,4), (4,1,4), (2, 3, 4), (3, 2, 4) since
# 4+(4 or 3) cant be 9, 5+(5 or 4) can be 9, 6+(6 or 5) cant be 9
# n1,n2 must have 5 digits together
# a, b, c combined must have each digit 1-9 once
def has_all_digits(a, b, c):
return '123456789' == ''.join(sorted(str(a)+str(b)+str(c)))
# method 1, for possible products, find factors
total = 0
for p in range(1000, 10000): # product must be 4 digits
found_pandigital = False
for f in range(2, int(math.sqrt(p))+1): # find a factor
# not a factor or a pandigital was found for this product alreday
if p % f != 0 or found_pandigital: continue
if has_all_digits(f, p//f, p):
total += p
found_pandigital = True # dont count products more than once
print(':', f, '*', p//f, '=', p)
print(total)
# method 2, create products from looping on factors
# multiple factor pairs may generate same product so use a set to ensure unique
prods = set() # store unique products in a set
# f1,f2 must have 1,4 or 2,3 digits (see above)
for f1 in range(2, 100):
for f2 in range(f1+1, 10000//f1 + 1):
if has_all_digits(f1, f2, f1*f2):
prods.add(f1*f2)
print(': found product', f1*f2)
print(sum(prods))
|
004de696f3025515142d6cb9a2543c2d2c0e6c45 | breynaUC/py-clase06 | /ejerc05.py | 157 | 3.875 | 4 | dividendo = int(input("N1: "))
divisor = int(input("N2: "))
if divisor!=0:
print("La división es:",dividendo/divisor)
else:
print("Error")
|
dc94cbc735d0f12a02aaadd7c8df189dba17f0ba | Alex-Noll/wems | /slackbot_wems/chris/slacklib.py | 488 | 3.59375 | 4 | # Put your commands here
COMMAND1 = "what do you think of chris?"
COMMAND2 = "say hello to your friend"
# Your handling code goes in this function
def handle_command(command):
"""
Determine if the command is valid. If so, take action and return
a response, if necessary.
"""
response = ""
if command.find(COMMAND1) >= 0:
response = "He's goofy! :joy:"
elif command.find(COMMAND2) >= 0:
response = "@sirexa hello"
return response
|
6f8523f6dafd4db8bd34302746afce49cbd1d316 | Brunocfelix/Exercicios_Guanabara_Python | /Desafio 039.py | 984 | 4.15625 | 4 | """Desafio 039: Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com sua idade:
Se ele ainda vai se alistar ao serviço militar;
Se é a hora de ele se alistar;
Se já passou do tempo do alistamento.
Seu programa também deverá mostrar o tempo que falta ou o tempo que passou do prazo."""
from datetime import date
ano = int(input('Digite o ano de nascimento: '))
ano2 = date.today().year
idade = ano2 - ano
print('Quem nasceu em {} tem {} anos em {}.' .format(ano, idade, ano2))
if idade < 18:
saldo = 18 - idade
print('Ainda falta(m) {} ano(s) para o alistamento.' .format(saldo))
anofuturo = ano2 + saldo
print('Seu alistamento será em {}' .format(anofuturo))
elif idade > 18:
saldo = idade - 18
print('Você já deveria ter se alistado há {} ano(s).' .format(saldo))
anopassado = ano2 - saldo
print('Seu alistamento foi em {}.' .format(anopassado))
else:
print('Você tem que ir se alistar IMEDIATAMENTE!') |
2b86c64f1cdd7399535efbfa9808a9d2c5c053fa | Sean-Horner-SmoothStack/smoothstack_pce_training | /assignment_4.a/main.py | 6,274 | 3.90625 | 4 |
def assignment4_a_1():
def func():
print("Hello World")
func()
def assignment4_a_2():
def func1(name):
print(f"Hi, my name is {name}")
username = input("Please enter your name: ")
func1(username)
def assignment4_a_3():
def func3(x, y, z: bool):
if z:
return x
else:
return y
func3("hello", "goodbye", True)
def assignment4_a_4():
def func4(x, y):
return x * y
num1 = int(input("Please enter the first number: "))
num2 = int(input("Please enter the second number: "))
print(func4(num1, num2))
def assignment4_a_5():
def is_even(num: int) -> bool:
return num % 2 != 1
num = int(input("Please enter the number you'd like to test the evenness of: "))
print(f"is_even({num}) = {is_even(num)}")
def assignment4_a_6():
def greater_than(num1: int, num2: int):
return num1 > num2
num1 = int(input("Please enter the first number: "))
num2 = int(input("Please enter the second number: "))
print(f"greater_than({num1}, {num2}) = {greater_than(num1, num2)}")
def assignment4_a_7():
def conglom(*nums):
return sum(nums)
num_list = [1, 6, 7, 2, 45, 234, 34, 26]
print(f"Orig list: {num_list}")
print(f"Summed: {conglom(num_list)}")
def assignment4_a_8():
def filter_evens(*nums):
return [n for n in nums if n % 2 == 0]
num_list = [1, 6, 7, 2, 45, 234, 34, 26]
print(f"Orig list: {num_list}")
print(f"Filtered: {filter_evens(num_list)}")
def assignment4_a_9():
def camel_catastrophe(text: str):
result = ""
for i in range(0,len(text)):
if (i+1) % 2 == 1:
result += text.upper()[i]
else:
result += text.lower()[i]
return result
line = input("Please enter the string you'd like to morph: ")
print(camel_catastrophe(line))
def assignment4_a_10():
def complex_comparison(num1: int, num2: int) -> int:
if num1 % 2 == 0 and num2 % 2 ==0:
if num1 < num2:
return num1
else:
return num2
else:
if num1 > num2:
return num1
else:
return num2
num1 = int(input("Please enter the first number you'd like to test: "))
num2 = int(input("Please enter the second number you'd like to test: "))
print(f"The result of our complex comparison is: {complex_comparison(num1, num2)}")
def assignment4_a_11():
def start_the_same(text1: str, text2: str) -> bool:
return text1.lower()[0] == text2.lower()[0]
word1 = input("Please enter the first word you'd like to compare: ")
word2 = input("Please enter the second word you'd like to compare: ")
if start_the_same(word1, word2):
print("The two words start the same!")
else:
print("These words start differently.")
def assignment4_a_12():
def twice_the_other_side_of_seven(num: int) -> int:
diff = num - 7
return 7 + 2 * diff
number = int(input("Please enter the number you'd like to calculate from: "))
print(f"The number twice this side of seven is: {twice_the_other_side_of_seven(number)}")
def assignment4_a_13():
def pre_determined_cameling(word: str) -> str:
result = ""
for i in range(0, len(word)):
if i == 0 or i == 3:
result += word.upper()[i]
else:
result += word[i]
return result
line = input("Please enter the word you'd like to disfigure: ")
print(pre_determined_cameling(line))
def main():
print("Welcome to the Assignment 4.a runner created by Sean Horner")
selection = -1
print("\n")
while selection != 0:
print("")
print("********************************************")
print("* 1) Run question 1 *")
print("* 2) Run question 2 *")
print("* 3) Run question 3 *")
print("* 4) Run question 4 *")
print("* 5) Run question 5 *")
print("* 6) Run question 6 *")
print("* 7) Run question 7 *")
print("* 8) Run question 8 *")
print("* 9) Run question 9 *")
print("* 10) Run question 10 *")
print("* 11) Run question 11 *")
print("* 12) Run question 12 *")
print("* 13) Run question 13 *")
print("* *")
print("* 0) Exit the program *")
print("********************************************")
print("")
# add try/except handling
selection = int(input("Please enter your choice: "))
if selection == 1:
assignment4_a_1()
elif selection == 2:
assignment4_a_2()
elif selection == 3:
assignment4_a_3()
elif selection == 4:
assignment4_a_4()
elif selection == 5:
assignment4_a_5()
elif selection == 6:
assignment4_a_6()
elif selection == 7:
assignment4_a_7()
elif selection == 8:
assignment4_a_8()
elif selection == 9:
assignment4_a_9()
elif selection == 10:
assignment4_a_10()
elif selection == 11:
assignment4_a_11()
elif selection == 12:
assignment4_a_12()
elif selection == 13:
assignment4_a_13()
elif selection == 0:
continue
else:
print("That wasn't an acceptable option, please try again.")
print("\n")
input("Press enter to continue")
print("\n\n~~~ Thanks for checking my assignment work :D! ~~~")
if __name__ == "__main__":
main()
|
dd75c5dd56bcdd945f02f4af1f50d7a5e6ba9263 | Durbek1/1-Lineyniy-algoritm | /38-пример.py | 168 | 3.515625 | 4 | # V=A*x+B=0, A!=0. x-ni aniqlash kerak
A=float(input('A='))
B=float(input('B='))
if A==0:
print('net resheniya')
else:
A==0 and B==0
x=-B/A
print (x)
|
b3c59bb817121e8d34b76560beb5d8716eb316fb | PatrickLenis/PythonProject_ClientServer | /myServer.py | 2,223 | 3.6875 | 4 | import threading
import socket
import sys
#Host and port declaration (uses localhost)
host = '127.0.0.1'
port = 8080
#Creates socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Server binding
server.bind((host, port))
server.listen()
#Handles the client messeges
def clientHandler(client, address):
#Constanlty checks for incoming messages
while True:
#Brodcasts message to client
try:
message = client.recv(1024).decode('ascii')
#Checks for client request to disconect
if message == '#exit':
#Sends disconect confirmation to client
client.send(f"You have been disconecded".encode('ascii'))
client.close()
#Prints disconected message on server
print(f"Client({address}) has chosen to disconect")
break
#Runs the normal message reciver
else:
#Prints client message confirmation on server
print(f"recived '{message}' from Client({address})")
#Sends message confirmation to client
client.send(f"SERVER : '{message}' recived by server".encode('ascii'))
#Closes connection on error
except:
client.close()
print(f"Client({address}) has disconected // ERROR occured!")
break
#Closes thread
else:
sys.exit()
#Runs the server (accepts new connections and creates a thread for client handler function)
def runServer():
#Prints confirmation message
print("The server is running")
#port = input("Give port : ")
while True:
#Acnoleges and accepts client connection
client, address = server.accept()
print(f"Connection achived with Client({str(address)})")
#Gives client the connection confirmation
client.send('You have been connected to the server'.encode('ascii'))
#Creates a thread to handle the connected client
thread = threading.Thread(target = clientHandler, args = (client, address))
thread.start()
#Call to the runServer main method
runServer() |
5245918775761d6409db9cf4986fe73b3a48f4ae | imidya/leetcode | /4XX/496_next_greater_element1.py | 719 | 3.578125 | 4 | class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
results = []
for i, findNum in enumerate(findNums):
cands = None
for num in nums[nums.index(findNum):]:
if num > findNum:
cands = num
break
if cands:
results.append(cands)
else:
results.append(-1)
return results
if __name__ == '__main__':
s = Solution()
print(s.nextGreaterElement([4, 1, 2], [1, 3, 4, 2]))
print(s.nextGreaterElement([2, 4], [1, 2, 3, 4]))
|
2e995bf6fc60cd252e7c449264567f037fad4386 | gabriellaec/desoft-analise-exercicios | /backup/user_084/ch84_2020_04_22_12_13_43_311627.py | 152 | 3.5 | 4 | def inverte_dicionario(i):
f={'',[]}
for c,v in i.items():
if v in f.keys():
f[v].append(c)
f[v]=c
return f
|
ed798facf62444a834798c0604ad6dc447b6e411 | SirMatix/Python | /PracticePython.org/cwiczenie 9 guessing game one.py | 1,224 | 4.125 | 4 | from random import randint
print('This is a guessing game. You need to guess number from 1 to 9.')
rand_list = [x for x in range(1,10)]
play = 1
while play == 1:
computer = rand_list[randint(1,10)]
count = 0
#game loop
while True:
player = int(input('guess a number from 1 to 9: '))
if player == computer:
print('You guess correct! You win!')
count += 1
break;
elif player > computer:
print('You guessed too high. Try again!')
count += 1
elif player < computer:
print('You guessed too low. Try again!')
count += 1
if count == 1:
print('You finished game in:', count, 'move', sep=' ')
elif count > 1:
print('You finished game in:', count, 'moves', sep=' ')
#exit/again loop
while True:
play = str(input('type "exit" to finish or "again" to try one more time: '))
play = play.lower()
if play == 'exit':
play = 0
break;
elif play == 'again':
play = 1
break;
else:
print('wrong input try again!')
|
b2da4eb26eb6dff6326bd7219eabffe91ec7514f | Jadams29/Coding_Problems | /Map_Filter/Function_Annotations.py | 333 | 3.578125 | 4 | def random_func(name : str, age : int, weight : float) -> str:
print("Name :", name)
print("Age :", age)
print("Weight :", weight)
return "{} is {} years old and weighs {}".format(name, age, weight)
print(random_func("Derek", 41, 165.5))
print(random_func(89, 'Derek', 'Turtle'))
print(random_func.__annotations__) |
6b5f4623ec00ac0b3445418f41880952fdbcb1a1 | mohitsharma2/Training-Forsk-2019 | /Day_03/anagram.py | 837 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 9 16:26:02 2019
@author: Harsh Anand
"""
"""
Two words are anagrams if you can rearrange the letters of one to spell the second.
For example, the following words are anagrams:
['abets', 'baste', 'bates', 'beast', 'beats', 'betas', 'tabes']
Hint: How can you tell quickly if two words are anagrams?
Dictionaries allow you to find a key quickly.
"""
li=[]
lii=[]
counter=0
while True:
str1=input("enter string")
if not str1:
break
li.append(str1)
for i in li[0]:
lii.append(i)
lii.sort()
print(lii)
list1=[]
for item in li:
for j in item:
list1.append(j)
list1.sort()
#print(list1)
if list1==lii:
counter+=1
else:
counter=0
list1.clear()
if counter>0:
print("anagrams")
else:
print("NO anagrams")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.