blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
a3d780ba0d331d8cfb4ab4744ca5e72a52e46c16 | pjy08062/Winterschool2018 | /버튼2.py | 238 | 3.65625 | 4 | from tkinter import *
window=Tk()
btnList=[None]*3
for i in range(0,3) :
btnList[i]=Button(window, text='버튼'+str(i+1))
for btn in btnList :
btn.pack(side=TOP, fill=X, ipadx=30, ipady=30, padx=10, pady=10)
window.mainloop()
|
9b93247f815bb4e7d34b5315a7bee02f1e32dc21 | Dhivan/Python-All-basics | /class&obj.py | 247 | 3.8125 | 4 | class student:
def details(self,name,age):
self.name=name
self.age=age
print('the name is {} age is {}'.format(name,age))
s=student()
name=input('Enter name ')
age=int(input('enter the age'))
s.details(name,age) |
7d4b27b0166758cbf9616cb370d81c6b6b7a8d1e | Dhivan/Python-All-basics | /First.py | 229 | 3.5625 | 4 | from tkinter import *
root = Tk()
def printname():
print('Welcome')
frame = Frame(root,width=300, height=300)
frame.pack()
button1=Button(root,text='click here', command=printname)
button1.pack()
root.mainloop()
|
856ff95bf41c2893b19f02dfc920e6c57ada8cf9 | collielester86/think-link | /python/wicow_stats/noun_pair_freqs.py | 1,435 | 3.703125 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
Count the frequency of each noun that co-occurs with a key noun, but
which is not part of the same noun-phrase as that noun.
We want nouns that seem to have a subject-verb-object relationship with
they keynoun.
"""
import fileinput
import operator as op
import nltk
import sys
freqs = {}
stopwords = ["s",'"',"way","t","fact","more","day","people","best","something","person"]
def count_nouns(nouns):
for noun in nouns:
noun = noun.replace("\t","").replace("\s","").replace("\n","")
if not (noun in stopwords) and noun.isalpha():
freqs[noun] = freqs.get(noun,0) + 1
def sorted_freqs():
return sorted(freqs.iteritems(),key=op.itemgetter(1),reverse=True)
def drop_html(nouns):
if "<" in nouns:
return nouns[0:nouns.index("<")]
else:
return nouns
def contains_badword(phrase,badwords):
for badword in badwords:
if badword in phrase: return True
return False
def main(args):
keynoun = args[1]
infile = args[2]
for line in file(infile):
if not ("<" in line) and keynoun in line:
nouns = set(line.split("\t")[1:])
badwords = set()
for noun in nouns:
if keynoun in noun:
badwords = badwords.union(noun.split(" "))
nouns = [noun for noun in nouns if not contains_badword(noun,badwords)]
count_nouns(nouns)
freqs = sorted_freqs()
for k,v in freqs:
if(v > 4):
print k+"\t"+str(v)
if __name__ == '__main__':
main(sys.argv)
|
eb646e71880136b0624ab1253cfac575e1c81604 | YuliaChornenko/model-classification | /parser/toxic_data.py | 1,995 | 3.71875 | 4 | import pandas as pd
class ToxicComments:
"""
Creating list of toxic comments from default file
"""
@staticmethod
def read_file(file_name=None):
"""
Reading default file
:param file_name: file with toxic comments
:return: read file
"""
fixed_df = pd.read_csv(file_name, delimiter=',',
names=['text', 'toxic'])
return fixed_df
@staticmethod
def create_toxic_list(fixed_df=None):
"""
Creating list of degree of toxicity
:param fixed_df: read file
:return: new list with toxic
"""
new_toxic_list = list()
for ls in fixed_df['toxic']:
new_toxic_list.append(int(ls))
return new_toxic_list
@staticmethod
def create_text_list(fixed_df=None):
"""
Creating list of comment text
:param fixed_df: read file
:return: new list with text
"""
new_text_list = list()
for ls in fixed_df['text']:
new_text_list.append(ls)
return new_text_list
@staticmethod
def create_final_toxic(new_text_list=None, new_toxic_list=None):
"""
Creating list of the most toxiс comments
:param new_text_list: list with toxic comments
:param new_toxic_list: list with toxic category
:return: list of toxic comments
"""
print('Cобираем хулиганские сообщения...')
new_toxic = list()
n = 0
for comments in new_text_list:
new_toxic.append([new_text_list[n], new_toxic_list[n]])
n += 1
toxic_list = new_toxic[:200]
for ls in toxic_list:
if ls[1] == 1:
ls[1] = 'Hooligan'
else:
toxic_list.remove(ls)
for ls in toxic_list:
if ls[1] == 0 or ls[1] == 1:
toxic_list.remove(ls)
return toxic_list
|
e8e552236d727cf005e980829600bc52a20cc74f | fvaldecan/Mock-Python-Interpreter | /input2.py | 252 | 3.90625 | 4 | #Double ForLoop
a = 22
b = 11
c = 2
d = c * b
first = a / d
name = "nicky" *3
print name
e = 5 == 5 == 5
f = 5 == 5 == 1
print "Double For loop"
for i in range(10):
for j in range( 10 ):
print "*"* (i+j)
print a
print b
print c
print first |
71a9c0b288e51cd72b57c6d6aa27679be3add042 | ravernhe/python_random_stuff | /Algo/binary_search.py | 505 | 3.703125 | 4 | #!/usr/bin/python
# -*-coding:utf-8 -*
def binary_search(x, sorted_list):
if len(sorted_list) == 1:
return False
half = len(sorted_list)//2
if x == sorted_list[half]:
return half
if x < sorted_list[half]:
return binary_search(x, sorted_list[:half])
if x > sorted_list[half]:
return half + binary_search(x, sorted_list[half:])
i = 0
sorted_list = []
while i < 20000:
sorted_list.append(i)
i += 1
x = 15897
print(binary_search(x, sorted_list)) |
5462c5fdcd69d749bd600c8318f3dff86b9781e9 | snakespear/GitHub_code | /python_practice/ex4.py | 733 | 3.890625 | 4 | cars = 100
space_in_the_car = 4
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_the_car
average_passengers_in_the_car = passengers/cars_driven
print("There are", cars, "cars available")
print("There are only", drivers, "drivers available")
print("There will be", cars_not_driven, "empty cars today")
print("We can transport", carpool_capacity, "People today")
print("We have", passengers, "to carpool today")
print("we need to put about", average_passengers_in_the_car, "in each car")
# the explanation is the variable names declared needs to be used exactly as such. here we have and extra underscore
# if we change 4.0 to 4 the 120.0 changes to 120
|
27989368586ffa54f5ac5a9599a95b0b3c726709 | Raylend/PythonCourse | /hw_G1.py | 681 | 4.15625 | 4 | """
Написать декоратор, сохраняющий последний результат функции в .txt файл с названием функции в имени
"""
def logger(func):
def wrapped(*args, **kwargs):
# print(f'[LOG] Вызвана функция {func.__name__} c аргументами: {args}, {kwargs}')
f_name = func.__name__ + '.txt'
f = open(f_name, "w")
result = func(*args)
f.write(f'Last result: {result}')
f.close()
return result
return wrapped
@logger
def my_func(a):
c = list(map(lambda x: x ** 3, a))
return c
a = {1, 2, 3, 4, 5, 6, 7, 8, 9}
b = my_func(a)
|
00712b16c692eb709c0f76adb4bc374fbecd0e72 | Raylend/PythonCourse | /hw_C1.py | 993 | 3.9375 | 4 | """
Пользователь задаёт список чисел,
выведите все элементы списка,
которые больше предыдущего элемента
"""
list = []
t = input("Input your first number or a list of numbers in format x, y, z, ...\nThen press ENTER.\n")
if len(t) == 1:
t = float(t)
list.append(t)
while t!="":
t = input("Enter another number or just press ENTER to finish entering numbers\n")
if t!="":
t = float(t)
list.append(t)
for i in range(len(list)):
for j in range(i, len(list)):
if list[j] > list[i]:
print(list[j])
quit()
elif len(t) == 0:
print("You had to input smth!")
quit()
elif len(t) > 1:
t = t.split(", ")
for i in t:
i = float(i)
list.append(i)
for i in range(len(list)):
for j in range(i, len(list)):
if list[j] > list[i]:
print(list[j])
quit()
|
d8b7483f9865f27bb583581d5487746833df1d48 | Aron-A/python_learn | /Exercícios/Ex_15.py | 449 | 4 | 4 | def desenha(largura, altura):
while (largura > 0):
n = altura
while n > 0:
if (n == largura) and (largura > 1 or n > 1):
print(" ")
else:
print("#", end = "")
n = n - 1
print()
largura = largura - 1
n = altura
colunas = int(input("Digite a largura: "))
linhas = int(input("Digite a altura: "))
desenha(colunas, linhas) |
341afb9ce294b6e65e308f0e322d91fe189f79da | Aron-A/python_learn | /Exercícios/Ex_13.py | 232 | 3.734375 | 4 | def vogcons(n):
vogal = ["a" , "e", "i", "o", "u", "A", "E", "I", "O", "U"]
if n in vogal:
print("Vogal")
else:
print("Consoante")
x = input("Digite uma letra: ")
vogcons(x)
|
7d35f00e993320446346889c2a91ef7007fd1592 | ranjitharaju/pyyashu | /game1.py | 406 | 4.09375 | 4 | import random
a={1:'rock',2:'paper',3:'scissors'}
while True:
p=input("Your choice rock/paper/scissors:")
c=a[random.randint(1,3)]
print("You chose:",p,"Computer chose::",c)
if(p==c):
print("draw")
elif(p=="rock"):
if(c=="scissors"):
print("u win")
elif(p=="paper"):
if(c=="rock"):
print("computer win")
elif(p=="scissors"):
if(c=="rock"):
print("computer win")\
else:
break |
d2822cfa674d1c3701c46e6fd305bf665f26ace4 | nkpydev/Algorithms | /Sorting Algorithms/Selection Sort/selection_sort.py | 1,030 | 4.34375 | 4 | #-------------------------------------------------------------------------#
#! Python3
# Author : NK
# Desc : Insertion Sort Implementation
# Info : Find largest value and move it to the last position.
#-------------------------------------------------------------------------#
def sort_selection(user_input):
l = len(user_input)
for i in range(l-1,0,-1):
max = 0
for j in range(1,i+1):
if user_input[j]>user_input[max]:
max = j
user_input[max],user_input[i] = user_input[i],user_input[max]
return user_input
if __name__ == '__main__':
final_sorted = []
get_user_input = [int(x) for x in input('\nEnter numbers to be sorted [seperated by ","]:').split(',')] #int(x) is import as we are looking forward to integers and not string value
print('\nUser Input before Sorting:\t',get_user_input)
final_sorted = sort_selection(get_user_input)
print('\nUser Input after Bubble Sort:\t',get_user_input) |
83639850939bbc6784df9a5f0062dce0bcca4bfc | daniel2078/Climaduino-web-controller | /settings/climaduino_programming_sentry.py | 2,578 | 3.53125 | 4 | '''
This code checks whether the Climaduino parameters should be changed based on
day of the week and time of day.
It will be triggered at regular intervals. The code will not check for the exact time,
but will rather adjust for whatever the interval it is using is. So, if a 5 minute interval
is being used, it is 11:02, and the programming called for the temperature to change at 11,
it will still be changed.
The code will directly read the database using Django libraries. It will change parameters
using a queue that is passed in. The queue is used by the climaduino_controller which will
send the settings to the Climaduino.
'''
## Django stuff
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'climaduino.settings'
from models import Setting, Program
from django.utils import timezone
import time, datetime
##
def main(queue, interval_in_seconds=300):
'''Queue is used to communicate with the climaduino_controller. Interval is
how often to check the database for program settings.'''
# BUG: Does not work when interval wraps around between days. If interval is 5 minutes
# then times between 23:55 and 00:00 (midnight) do not work properly
# set process niceness value to lower its priority
os.nice(1)
print("Climaduino Programming Sentry Active")
while 1:
now = datetime.datetime.now()
current_settings = Setting.objects.last()
# find out the day 0 is Monday
current_day = now.weekday()
# find out the time
current_time = now.time()
# calculate the time minus interval_in_seconds
earliest_time = now - datetime.timedelta(seconds=interval_in_seconds)
earliest_time = earliest_time.time()
# query DB with interval_in_seconds "fudge factor"
program_query = Program.objects.filter(mode=current_settings.mode, day=current_day, time__range=(earliest_time, current_time))
# if program exists, find out what should be changed and then change it
for program in program_query:
setting_record = Setting(time=now, source=3, mode=program.mode, temperature=program.temperature, humidity=program.humidity)
setting_record.save()
if program.temperature != current_settings.temperature:
queue.put("%sF" % program.temperature)
if program.humidity != current_settings.humidity:
queue.put("%s%%" % program.humidity)
# sleep for interval_in_seconds so we only check once during that interval
time.sleep(interval_in_seconds)
# if called directly from the command line
if __name__ == "__main__":
print("Can not be run directly from the command line.") |
dae243bca04bd1b8280263941aed9d73cdd7c463 | mktsy/MiniProject-SmartLight | /relay4port/script5on.py | 457 | 3.53125 | 4 | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# init list with pin numbers
pinList = [27]
# loop through pins and set mode and state to 'high'
for i in pinList:
GPIO.setup(i, GPIO.OUT)
# GPIO.output(i, GPIO.HIGH)
# main loop
try:
GPIO.output(27, GPIO.LOW)
print ("ON")
# End program cleanly with keyboard
except KeyboardInterrupt:
print (" Quit")
# Reset GPIO settings
GPIO.cleanup()
|
41bb37210fcca7004f21be255ff40fc47466ad00 | SayidDerder/DofusProject | /venv/Include/Utilities/GetNeighbors.py | 1,615 | 4.09375 | 4 | def get_neighbors(state_matrix, x, y):
"""
For a given cell, computes the neighbors, check if they are valid and returns a list.
:param state_matrix: Matrix containing the state of the game
:param x: x coordinate of cell of interest
:param y: y coordinante of cell of interest
:return: List of valid neighbor cells
"""
# initialize list of neighbors
neighbors = []
# Upper left neighbor, check if in the matrix
if x - 1 >= 0 and y - 1 >= 0:
# Check if the neighbor cell is playable
if state_matrix[int(x) - 1, int(y) - 1] != -1:
# Append the cell the the neighbor list
neighbors.append([x - 1, y - 1])
# Upper right neighbor, check if in the matrix
if x + 1 < state_matrix.shape[0] and y - 1 >= 0:
# Check if the neighbor cell is playable
if state_matrix[x + 1, y - 1] != -1:
# Append the cell the the neighbor list
neighbors.append([x + 1, y - 1])
# Lower right neighbor, check if in the matrix
if x + 1 < state_matrix.shape[0] and y + 1 < state_matrix.shape[1]:
# Check if the neighbor cell is playable
if state_matrix[x + 1, y + 1] != -1:
# Append the cell the the neighbor list
neighbors.append([x + 1, y + 1])
# Lower left neighbor, check if in the matrix
if x - 1 >= 0 and y + 1 < state_matrix.shape[1]:
# Check if the neighbor cell is playable
if state_matrix[x - 1, y + 1] != -1:
# Append the cell the the neighbor list
neighbors.append([x - 1, y + 1])
return neighbors |
9b8f6fca950cfe0852fa5daf70666d356000066f | minhtannguyen/SRSGD | /experiments_with_quadratic_function/Optimizer_Compare_DecayingVarianceNoise.py | 13,471 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Compare different optimization algorithms with exact gradient
1. GD
2. GD + Constant momentum
3. GD + Constant momentum (Pytorch)
4. GD + Constant momentum (Sutskever)
5. Nesterov Accelerated Gradient
6. Nesterov Accelerated Gradient (Pytorch)
7. Nesterov Accelerated Gradient (Sutskever)
8. Nesterov Accelerated Gradient + Scheduled Restart
9. Nesterov Accelerated Gradient + Scheduled Restart (Pytorch)
10. Nesterov Accelerated Gradient + Scheduled Restart (Sutskever)
11. Nesterov Accelerated Gradient + Adaptive Restart
12. Nesterov Accelerated Gradient + Adaptive Restart (Pytorch)
13. Nesterov Accelerated Gradient + Adaptive Restart (Sutskever)
14. Nesterov Accelerated Gradient + Adaptive Restart + Laplacian Smoothing
15. Nesterov Accelerated Gradient + Adaptive Restart + Laplacian Smoothing (Pytorch)
16. Nesterov Accelerated Gradient + Adaptive Restart + Laplacian Smoothing (Sutskever)
"""
import matplotlib.pyplot as plt
import numpy as np
#------------------------------------------------------------------------------
# Define the function
# Here we consider the convex quadratic function
# f(x) = 0.5*x*P*x - b*x
# nabla f(x) = P*x - b = 0 ==> opt = inv(P)*b
#------------------------------------------------------------------------------
n = 1000
A = np.zeros((n, n))
for i in range(1, n-1):
A[i, i+1] = 1.
A[i, i-1] = 1.
A[0, 1] = 1.
A[n-1, n-2] = 1.
P = 2.*np.eye(n) - A
b = np.zeros(n)
b[0] = 1
opt = np.dot(np.linalg.pinv(P), b)
def path(x):
return 0.5*np.dot(x, np.dot(P, x)) - np.dot(x, b)
def pathgrad(x, iter_count):
return np.dot(P, x) - b
def noisygrad(x, iter_count):
return np.dot(P, x) - b + np.random.normal(0, 0.1/(iter_count/100.+1.), (n)) # Small noise will destroy NAG + restarting, e.g. 0.005
#return np.dot(P, x) - b + np.random.normal(0, 0.01, (n))
def LS_noisygrad(x, iter_count):
vec = np.dot(P, x) - b + np.random.normal(0, 0.1/(iter_count/100.+1.), (n))
#vec = np.dot(P, x) - b + np.random.normal(0, 0.01, (n))
# Perform Laplacian Smoothing
ndim = len(vec)
vec_LS = np.zeros(shape=(1, ndim))
order = 1
if order >= 1:
Mat = np.zeros(shape=(order, 2*order+1))
Mat[0, order-1] = 1.; Mat[0, order] = -2.; Mat[0, order+1] = 1.
for i in range(1, order):
Mat[i, order-i-1] = 1.; Mat[i, order+i+1] = 1.
Mat[i, order] = Mat[i-1, order-1] - 2*Mat[i-1, order] + Mat[i-1, order+1]
Mat[i, order-i] = -2*Mat[i-1, order-i] + Mat[i-1, order-i+1]
Mat[i, order+i] = Mat[i, order-i]
for j in range(0, i-1):
Mat[i, order-j-1] = Mat[i-1, order-j-2] - 2*Mat[i-1, order-j-1] + Mat[i-1, order-j]
Mat[i, order+j+1] = Mat[i, order-j-1]
for i in range(order+1):
vec_LS[0, i] = Mat[-1, order-i]
for i in range(order):
vec_LS[0, -1-i] = Mat[-1, order-i-1]
sigma=10. #1. #100. # For high dimensional problem reduce sigma
if order >= 1:
vec = np.squeeze(np.real(np.fft.ifft(np.fft.fft(vec)/(1+(-1)**order*sigma*np.fft.fft(vec_LS)))))
return vec
#------------------------------------------------------------------------------
# Optimization algorithms
#------------------------------------------------------------------------------
def gd(x0, gradient, smoothness=1., n_iterations=100):
'''
Gradient descent for a smooth function with Lipschitz constant = smoothness
The optimal step size: 1./smoothness
'''
x = x0
xs = [x0]
for t in range(0, n_iterations):
x = x - (1./smoothness)*gradient(x, t)
xs.append(x)
return xs
def mgd(x0, gradient, smoothness=1., n_iterations=100):
'''
Gradient descent with constant momentum for a smooth function with Lipschitz function
with Lipschitz constant = smoothness
'''
x = x0
y = x0
xs = [x0]
for t in range(1, n_iterations+1):
#x2 = y - (1./smoothness/(10**(t/10000)))*gradient(y, t)
x2 = y - (1./smoothness)*gradient(y, t)
y2 = x2 + 0.9*(x2-x)
x = x2
y = y2
xs.append(y)
return xs
def nag(x0, gradient, smoothness=1., n_iterations=100):
'''
Nesterov accelerated gradient descent for smooth function with Lipschitz constant = smoothness
'''
x = x0
y = x0
xs = [x0]
for t in range(1, n_iterations+1):
#x2 = y - (1./smoothness/(10**(t/10000)))*gradient(y, t)
x2 = y - (1./smoothness)*gradient(y, t)
y2 = x2 + (t-1.)/(t+2.)*(x2-x)
x = x2
y = y2
xs.append(y)
return xs
def nag_s(x0, gradient, smoothness=1., n_iterations=100):
'''
Nesterov accelerated gradient descent for smooth function with Lipschitz constant = smoothness
Sutskever's version
'''
x = x0
y = x0
xs = [x0]
for t in range(1, n_iterations+1):
x2 = (t-1.)/(t+2.)*x + (1./smoothness)*gradient(y, t)
y2 = y - x2
x = x2
y = y2
xs.append(y)
return xs
def nag_p(x0, gradient, smoothness=1., n_iterations=100):
'''
Nesterov accelerated gradient descent for smooth function with Lipschitz constant = smoothness
Pytorch version
'''
x = x0
y = x0
xs = [x0]
for t in range(1, n_iterations+1):
x2 = (t-1.)/(t+2.)*x + gradient(y, t)
y2 = y - (1./smoothness)*x2
x = x2
y = y2
xs.append(y)
return xs
def nag_adaptive_restarting(x0, func, gradient, smoothness=1., n_iterations=100):
'''
Nesterov accelerated gradient descent with adaptive restarting for smooth
function with Lipschitz constant = smoothness.
'''
x = x0
y = x0
xs = [x0]
k = 1
for t in range(1, n_iterations+1):
#x2 = y - (1./smoothness/(10**(t/10000)))*gradient(y, t)
x2 = y - (1./smoothness)*gradient(y, t)
y2 = x2 + (k-1.)/(k+2.)*(x2-x)
# Restarting
if func(x2) > func(x):
k = 1
else:
k += 1
x = x2
y = y2
xs.append(y)
return xs
def nag_s_adaptive_restarting(x0, func, gradient, smoothness=1., n_iterations=100):
'''
Nesterov accelerated gradient descent with adaptive restarting for smooth function with Lipschitz constant = smoothness
Sutskever's version
'''
x = x0
y = x0
xs = [x0]
k = 1
for t in range(1, n_iterations+1):
x2 = (k-1.)/(k+2.)*x + (1./smoothness)*gradient(y, t)
y2 = y - x2
# Restarting
if func(x2) > func(x):
k = 1
else:
k += 1
x = x2
y = y2
xs.append(y)
return xs
def nag_p_adaptive_restarting(x0, func, gradient, smoothness=1., n_iterations=100):
'''
Nesterov accelerated gradient descent with adaptive restarting for smooth function with Lipschitz constant = smoothness
Pytorch version
'''
x = x0
y = x0
xs = [x0]
k = 1
for t in range(1, n_iterations+1):
x2 = (k-1.)/(k+2.)*x + gradient(y, t)
y2 = y - (1./smoothness)*x2
# Restarting
if func(x2) > func(x):
k = 1
else:
k += 1
x = x2
y = y2
xs.append(y)
return xs
def nag_scheduled_restarting(x0, gradient, smoothness=1., n_iterations=100):
'''
Nesterov accelerated gradient descent with scheduled restarting for smooth
function with Lipschitz constant = smoothness.
'''
x = x0
y = x0
xs = [x0]
k = 1#0
for t in range(1, n_iterations+1):
#x2 = y - (1./smoothness/(10**(t/10000)))*gradient(y, t)
x2 = y - (1./smoothness)*gradient(y, t)
y2 = x2 + (k-1.)/(k+2.)*(x2-x)
'''
#if k >= 1000: # 20, 20*2^1, 20*2^2, ...
if k >= 200: # Constant scheduling, no noise
k = 1
else:
k += 1
'''
if t < 10000:
if k >= 200:
k = 1
else:
k += 1
elif t < 30000:
if k >= 200*(2*1):
k = 1
else:
k += 1
'''
elif t < 50000:
if k >= 200*(2**2):
k = 1
else:
k += 1
'''
x = x2
y = y2
xs.append(y)
return xs
def nag_s_scheduled_restarting(x0, gradient, smoothness=1., n_iterations=100):
'''
Nesterov accelerated gradient descent with scheduled restarting for smooth function with Lipschitz constant = smoothness
Sutskever's version
'''
x = x0
y = x0
xs = [x0]
k = 1
for t in range(1, n_iterations+1):
x2 = (k-1.)/(k+2.)*x + (1./smoothness)*gradient(y, t)
y2 = y - x2
'''
#if k >= 1000: # 20, 20*2^1, 20*2^2, ...
if k >= 1000: # Constant scheduling, no noise
k = 1
else:
k += 1
'''
if t < 2000:
if k >= 20:
k = 1
else:
k += 1
elif t < 10000:
if k >= 20*(2*1):
k = 1
else:
k += 1
elif t < 50000:
if k >= 20*(2**2):
k = 1
else:
k += 1
x = x2
y = y2
xs.append(y)
return xs
def nag_p_scheduled_restarting(x0, gradient, smoothness=1., n_iterations=100):
'''
Nesterov accelerated gradient descent with scheduled restarting for smooth function with Lipschitz constant = smoothness
Pytorch version
'''
x = x0
y = x0
xs = [x0]
k = 1
for t in range(1, n_iterations+1):
x2 = (k-1.)/(k+2.)*x + gradient(y, t)
y2 = y - (1./smoothness)*x2
'''
#if k >= 1000: # 20, 20*2^1, 20*2^2, ...
if k >= 1000: #1000: # Constant scheduling, no noise
k = 1
else:
k += 1
'''
if t < 2000:
if k >= 100:
k = 1
else:
k += 1
elif t < 10000:
if k >= 100*(2*1):
k = 1
else:
k += 1
elif t < 50000:
if k >= 100*(2**2):
k = 1
else:
k += 1
x = x2
y = y2
xs.append(y)
return xs
#------------------------------------------------------------------------------
# Test the optimization algorithms
#------------------------------------------------------------------------------
its = 50000
# GD
xs_gd = gd(np.zeros(n), noisygrad, 4, its)
ys_gd = [abs(path(xs_gd[i]) - path(opt)) for i in range(0, its)]
# GD + constant momentum
xs_mgd = mgd(np.zeros(n), noisygrad, 4, its)
ys_mgd = [abs(path(xs_mgd[i]) - path(opt)) for i in range(0, its)]
# NAG
xs_nag = nag(np.zeros(n), noisygrad, 4, its)
ys_nag = [abs(path(xs_nag[i]) - path(opt)) for i in range(0, its)]
# NAG + adaptive restarting
xs_nag_ar = nag_adaptive_restarting(np.zeros(n), path, noisygrad, 4, its)
ys_nag_ar = [abs(path(xs_nag_ar[i]) - path(opt)) for i in range(0, its)]
# NAG + scheduled restarting
xs_nag_sr = nag_scheduled_restarting(np.zeros(n), noisygrad, 4, its)
ys_nag_sr = [abs(path(xs_nag_sr[i]) - path(opt)) for i in range(0, its)]
SMALL_SIZE = 11
MEDIUM_SIZE = 11
BIGGER_SIZE = 11
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title
f1 = plt.figure()
ax = plt.subplot(111, xlabel='x', ylabel='y', title='Stochastic Optimization Algorithms -- Quadratic Function')
#for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
# ax.get_xticklabels() + ax.get_yticklabels()):
# item.set_fontsize(30)
plt.figure(1, figsize=(6.5,6))
plt.clf()
plt.plot(ys_gd, 'b', lw=1, label='GD')
plt.plot(ys_mgd, 'g', lw=1, label='GD + Momentum')
plt.plot(ys_nag, 'r', lw=1, label='NAG')
plt.plot(ys_nag_ar, 'k', lw=1, label='NAG + Adaptive Restart')
plt.plot(ys_nag_sr, 'm', lw=1, label='NAG + Scheduled Restart')
#plt.xscale('log')
plt.yscale('log')
plt.legend()
plt.xlim([0, its])
plt.ylim(1e-5, 1e1)
plt.grid()
plt.xlabel('Iterations')
plt.ylabel('|f(x) - f(x*)|')
#plt.show()
plt.savefig('Quadratic_Decaying_Noise.pdf')
# Save data to txt for visualization
with open('GD_Quadratic_Decaying_Noise.txt', 'w') as filehandle:
filehandle.writelines("%20.14f\n" % item1 for item1 in ys_gd)
with open('MGD_Quadratic_Decaying_Noise.txt', 'w') as filehandle:
filehandle.writelines("%20.14f\n" % item1 for item1 in ys_mgd)
with open('NAG_Quadratic_Decaying_Noise.txt', 'w') as filehandle:
filehandle.writelines("%20.14f\n" % item1 for item1 in ys_nag)
with open('NAGAR_Quadratic_Decaying_Noise.txt', 'w') as filehandle:
filehandle.writelines("%20.14f\n" % item1 for item1 in ys_nag_ar)
with open('NAGSR_Quadratic_Decaying_Noise.txt', 'w') as filehandle:
filehandle.writelines("%20.14f\n" % item1 for item1 in ys_nag_sr)
|
9197d3d60ded6acd8d76c581de16cc68dc495b5a | ezhk/algo_and_structures_python | /Lesson_2/5.py | 691 | 4.375 | 4 | """
5. Вывести на экран коды и символы таблицы ASCII, начиная с символа
под номером 32 и заканчивая 127-м включительно.
Вывод выполнить в табличной форме: по десять пар "код-символ" в каждой строке.
"""
def print_symbols(pairs_per_line=10):
results_in_line = 0
for i in range(32, 127 + 1):
print(f"{i}. {chr(i)}\t", end='')
results_in_line += 1
if results_in_line == pairs_per_line:
print()
results_in_line = 0
print()
return True
if __name__ == '__main__':
print_symbols()
|
332dd6971f3b52129b320f93d189f02a688376fd | ezhk/algo_and_structures_python | /Lesson_3/7.py | 1,384 | 4.34375 | 4 | """
7. В одномерном массиве целых чисел определить два наименьших элемента.
Они могут быть как равны между собой (оба являться минимальными), так и различаться.
"""
def search_two_min(arr):
absolute_min = second_min = None
for el in arr:
if absolute_min is None:
absolute_min = el
continue
if second_min is None:
# добавляем с учетом сортировки значения:
# absolute_min - самый минимальный, second_min - максимальный из минимальных
(absolute_min, second_min) = (el, absolute_min) if el < absolute_min else (absolute_min, el)
continue
if absolute_min > el:
absolute_min, second_min = el, absolute_min
continue
if second_min > el:
second_min = el
return absolute_min, second_min
if __name__ == "__main__":
init_array = input("Введите начальный массив целых чисел, как список элементов через запятую: ").split(',')
init_array = list(map(int, init_array))
print(f"Два наименших значения {init_array}: {search_two_min(init_array)}")
|
5fa54b880761ceeeff5b9e622dc7068361097774 | ezhk/algo_and_structures_python | /Lesson_3/1.py | 520 | 3.796875 | 4 | """
1. В диапазоне натуральных чисел от 2 до 99 определить,
сколько из них кратны каждому из чисел в диапазоне от 2 до 9.
"""
def get_init_range():
i = 2
while i <= 9:
yield i
i += 1
def get_numbers(number):
return 99 // number
if __name__ == "__main__":
for i in get_init_range():
print(f"Для числа {i} кратных чисел в диапазоне [2, 99]: {get_numbers(i)}")
|
c277bb58a33df34ead39e4ed445d32e4a1f0bf42 | ezhk/algo_and_structures_python | /Lesson_1/6.py | 666 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 6. Пользователь вводит номер буквы в алфавите. Определить, какая это буква.
def get_symbol_by_positiion(pos):
init_value = ord('a')
return chr(init_value + pos - 1)
if __name__ == '__main__':
symbol_pos = int(input("Введите номер буквы в алфавите: "))
if 1 > symbol_pos or symbol_pos > 26:
raise ValueError("В анлгийском алфавите 26 букв, введите число от 1 до 26")
print(f"Под номером {symbol_pos} символ {get_symbol_by_positiion(symbol_pos)}")
|
8fe3f6fd02e6becf608ec08ca42874b842ba6dc2 | gaobo816/0809 | /test1.py | 1,106 | 3.53125 | 4 | class Person:
def __init__(self,name,life_value,gre):
self.name = name
self.gre = gre
self.life_value = life_value
def attack(self,emy):
emy.life_value = emy.life_value -self.gre
return self.life_value
class Dog:
def __init__(self,name,dlife_vale,dagres):
self.name = name
self.dlife_value = dlife_vale
self.dagres = dagres
def d_bite(self, person_o):
person_o.life_value = person_o.life_value - self.dagres
return person_o.life_value
agg = Person("egon",2000,88)
alex = Person("alex",1000,55)
dog_g = Dog("旺财",500,100)
print(alex.life_value)
agg.attack(alex)#1000 -88
print(alex.life_value)
print(agg.life_value)
dog_g.d_bite(agg) #2000 - 100
print(agg.life_value)
# print(agg.age)
# print(agg.life_value)
#
# class Dog:
#
# def __init__(self,name,dlife_vale,dagres):
# self.name = name
# self.dlife_value = name
# self.dagres = dagres
#
# def d_bite(self, emy):
# self.life_value = self.life_value - emy.gre
#
# return self.life_value
|
831d9c6295bcca33ed0fee5449775e2579fe7638 | VineetPrasadVerma/Hackerearth | /Challenge/JohnAndBuildings.py | 395 | 3.59375 | 4 | def FindCost(C, Height, N):
Height = list(Height)
C = list(C)
total_cost = 0
for i in range(N-1):
if Height[i]>=Height[i+1]:
total_cost += 0
else:
total_cost += C[i]
return total_cost
# Write your code here
N = int(input())
Height = map(int, input().split())
C = map(int, input().split())
out_ = FindCost(C, Height, N)
print(out_) |
23cc7b751ee666d2eb0e57ef8fa23f2b21b239ff | VineetPrasadVerma/Hackerearth | /BasicProgramming/BasicOfInputAndOutput/PalindromicString.py | 133 | 4.09375 | 4 | input_string = input()
reverse_string = input_string[::-1]
if input_string == reverse_string:
print('YES')
else:
print('NO')
|
333cd5174594e7e613a49787fc4dedf783b2edc0 | PyLamGR/PyLam-Edu | /Workshops/25.11.2017 - Python. The Basics - Volume 1 -/Python Codes/6/3_if_elseif_else.py | 165 | 4.25 | 4 | x = int(input("Give a number: "))
if x == 5:
print("The number is 5")
elif x == 6:
print("The number is 6")
else:
print("The number is neither 5 or 6")
|
076d47563c9a8852ea3ca389e3abca680676bb52 | melvinkoopmans/high-performance-python | /fibonnaci.py | 416 | 4.125 | 4 |
def fibonacci_list(num_items):
numbers = []
a, b = 0, 1
while len(numbers) < num_items:
numbers.append(a)
a, b = b, a+b
return numbers
def fibonacci_gen(num_items):
a, b = 0, 1
while num_items:
yield a
a, b = b, a+b
num_items -= 1
if __name__ == '__main__':
# for n in fibonacci_list(100_000):
for n in fibonacci_gen(100_000):
pass |
d8c00698f2baf4274685c62c4433182cab511656 | chanchalsinghla/HacktoberFest2021-9 | /implement_a_trie.py | 1,923 | 4.09375 | 4 | class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.trie = {}
self.trie["value"] = False
def find(self, h, key):
try:
ans = h[key]
except:
return 0
else:
return ans
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
pointer = self.trie
i = 0
for a in word:
if i == len(word)-1:
if self.find(pointer, a):
# pointer = pointer[a]
pointer[a]["value"] = True
else:
pointer[a] = {"value":True}
# pointer = pointer[a]
else:
if self.find(pointer, a):
pointer = pointer[a]
else:
pointer[a] = {"value":False}
pointer = pointer[a]
i+=1
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
pointer = self.trie
i = 0
for a in word:
if i==len(word)-1:
if self.find(pointer, a):
pointer = pointer[a]
value = pointer["value"]
else:
return False
else:
if self.find(pointer, a):
pointer = pointer[a]
else:
return False
i+=1
return value
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
pointer = self.trie
for a in prefix:
if self.find(pointer, a):
pointer = pointer[a]
else:
return False
return True
|
15a13e472a6057a0b3e119af3cba7c1038e6edaf | Abhishekjain0112/My_Python_Codes | /HackerRank_programs/Sub string.py | 432 | 3.78125 | 4 | name = input("Enter the String:")
x, y = 0, 0
l = len(name)
mylist=list()
tup =('A', 'E', 'I', 'O','U')
for i in range(l):
for j in range(i+1, l+1):
s=name[i]
#print(s)
mylist.append(s)
if s[0] in tup:
x = x + 1
else:
y = y + 1
if x > y:
print("Vowel", x)
elif x == y:
print("draw")
else:
print("Consonent", y) # your code goes here
#print(mylist)
|
71be18f0e2ead5265dffa730bf3f56291f5ad948 | Abhishekjain0112/My_Python_Codes | /TrainingAssigment1/02_p3.py | 189 | 3.8125 | 4 | n = int(input('Enter Number of rows :'))
for i in range(0, n):
for j in range(n, i, -1):
print(' ', end='')
for k in range(0,i+1):
print('* ', end='')
print()
|
a833dbd9b7e00f11934243080f9683fd9ea65bee | Abhishekjain0112/My_Python_Codes | /TrainingAssigment1/02_p2.py | 132 | 3.765625 | 4 | n = int(input("Enter Number of rows :"))
for i in range(0, n):
for j in range(1, n-i+1):
print(j, end=' ')
print()
|
c331c40d8dba63b4172eaee80c7ce4cf6c1002a5 | ebentz73/Python_test | /test.py | 227 | 3.53125 | 4 | try:
# Python 2
xrange
except NameError:
# Python 3, xrange is now named range
xrange = range
for i in xrange(1, 101):
print(i if i % 5 else "Buzz") if i % 3 else (
"Fizz" if i % 5 else "FizzBuzz")
|
224aa6988f06d6912e7648eb7241ef6214ac1edb | madbeck/projects | /hashmap/hashmap.py | 5,831 | 3.671875 | 4 |
#Hashmap implementation (python)
'''
################################################TEST SUITE for hashmap
>>> new_map = hashmap()
>>> new_map.constructor(10)
[None, None, None, None, None, None, None, None, None, None]
>>> new_map.boolean_set('bob',1)
1
>>> new_map
[[('bob', 1)], None, None, None, None, None, None, None, None, None]
>>> new_map.boolean_set('bob', 1)
1
>>> new_map
[[('bob', 1)], None, None, None, None, None, None, None, None, None]
>>> new_map.get('bob')
1
>>> new_map.boolean_set('bob', 2)
1
>>> new_map
[[('bob', 2)], None, None, None, None, None, None, None, None, None]
>> new_map.set('bob')
2
>>> new_map.boolean_set('mary', 2)
1
>>> new_map
[[('bob', 2)], [('mary', 2)], None, None, None, None, None, None, None, None]
>>> new_map.delete('mary')
2
>>> new_map
[[('bob', 2)], [], None, None, None, None, None, None, None, None]
>>> new_map.delete('bobby')
>>> new_map
[[('bob', 2)], [], None, None, None, None, None, None, None, None]
>>> new_map.flat_load()
0.1
>>> new_map.num_items
1
>>> new_map.boolean_set('joe', 3)
1
>>> new_map.boolean_set('james', [1,2,3])
1
>>> new_map.boolean_set('sam', 'no')
1
>>> new_map.boolean_set('lee', 20)
1
>>> new_map.boolean_set('sara', 0)
1
>>> new_map.boolean_set('tom', {'cat':4})
1
>>> new_map.boolean_set('jess', 5)
1
>>> new_map.boolean_set('nigel', 8)
1
>>> new_map.boolean_set('miranda', 4)
1
>>> new_map.num_items
10
>>> new_map.boolean_set('josephine', 4)
0
>>> new_map.boolean_set('miranda', 5)
1
################################################
'''
class Node:
def __init__(self, tup):
self.data = tup #tup is (key, value)
self.next = None #allows nodes to point to each other
def set_data(self, new_tup):
self.data = new_tup #allows us to mutate the tuple
def get_data(self):
return self.data
def set_next(self, next_item):
self.next = next_item
def get_next(self):
return self.next
def __repr__(self):
return repr(self.data)
class LinkedList: #uses node class to create a linked list of nodes
def __init__(self):
self.top = None
def add_element(self, element): #element is a tuple of form (string, data)
#if key already exists, overwrite value with element[1] using set_data
curr_element = self.top
while curr_element != None:
if curr_element.data[0] == element[0]: #if key already in LL
curr_element.set_data(element) #change value to new value
return 1 #if success
curr_element = curr_element.next
#if key of element is not in the nodes, create a new node with element
n = Node(element) #create new node if key is not in LL
n.set_next(self.top) #self.top is still the previous linked list, will be moved to the pointer of n
self.top = n #self.top reset to n
def get_value(self, key): #self is LL
curr_element = self.top #first element in LL
while curr_element != None:
if curr_element.get_data()[0] == key:
return curr_element.get_data()[1]
else:
curr_element = curr_element.get_next()
return None
def delete_value(self, key):
previous_element = None
curr_element = self.top
while curr_element != None:
if curr_element.data[0] == key:
if previous_element == None:
self.top = curr_element.get_next()
return 1
else:
previous_element.set_next(curr_element.get_next())
return 1
else:
previous_element = curr_element
curr_element = curr_element.get_next()
return 1
return 0 #returns 0 if we never find the value associated with the key or if process does not work
def __repr__(self):
array = []
curr_element = self.top
while curr_element != None:
array.append((curr_element))
curr_element = curr_element.get_next()
return str(array)
###################################################
class hashmap: #implements both Node and LinkedList
def __init__(self):
self.size = 0
self.num_items = 0
self.map = [] #array that will hold hashmap pairs
def constructor(self, size): #return an instance of the class with pre-allocated space for the given number of objects
self.size = size
self.map = [None]*size
return self.map
def boolean_set(self, key, value): #stores the key and value in the map and returns True or False if the operation succeeds
#key is a string
new_hash = hash(key)
index = new_hash%self.size
if self.map[index] == None: #no collision
LL = LinkedList()
LL.add_element((key, value))
self.num_items += 1
self.map[index] = LL
return 1
else: #collision! just add key, value pair to linked list
assert(self.map[index]!= None)
LL = self.map[index]
if LL.get_value(key) == None:
LL.add_element((key, value))
self.num_items += 1
return 1
else:
LL.add_element((key, value))
return 1
return 0 #if value is not added for some reason
def get(self, key): #returns value associated with the key or None if no value exists
index = hash(key)%self.size
if self.map[index] == None:
return None
else:
LL = self.map[index]
return LL.get_value(key)
def delete(self, key): #deletes the value associated with the given key, returns the value if successful
index = hash(key)%self.size
if self.map[index]!= None:
LL = self.map[index]
if LL.get_value(key) != None:
value = LL.get_value(key)
LL.delete_value(key)
self.num_items = self.num_items - 1
return value
else:
return None
else: #if key has no value
assert(self.map[index] == None)
return None
def flat_load(self): #returns (items in hash map)/(size of hash map)
return float(self.num_items)/self.size
def __repr__(self):
array = []
index = 0
while index < len(self.map):
curr_list = self.map[index]
array.append(curr_list)
index += 1
return str(array)
if __name__ == "__main__": #runs doctests at the top of the file
import doctest
doctest.testmod()
|
b182a92891ae553fd27aaaa2fd0f654e6d3e0938 | mcormc/udacity-ipnd | /python/count_character.py | 229 | 4.03125 | 4 | def count_character(string, target):
total = 0
for ch in string:
if ch == target:
total += 1
return total
# This should return 3, since there are three "o"s:
print(count_character("bonobo", "o"))
|
3efd7833a98ba96e292114d979cd76ca7e9aadcd | qpwoeirut/ConnectFour | /main.py | 3,289 | 4.15625 | 4 | ROWS = 6
COLUMNS = 7
EMPTY = '.'
PLAYER_ONE = 'B'
PLAYER_TWO = 'R'
board = [[EMPTY for _ in range(COLUMNS)] for _ in range(ROWS)]
def print_board(): # utility function to print the board to console
print()
print(' '.join([str(n) for n in range(COLUMNS)])) # print column numbers
for row in board:
print(' '.join(row)) # use str.join to concatenate all the row chars
def get_input():
while True: # keep asking until we get valid input
col = input("What column do you want to place in?\n> ")
if col.isnumeric() is False: # check if the input's a number
print("Please input a number!")
continue
col = int(col) # convert from string to number
if not (0 <= col < COLUMNS): # check if column is valid, using 0-index for now
print(f"Please input a number between 0 and {COLUMNS-1}")
continue
if board[0][col] != EMPTY: # check if column is already full (top cell will be taken)
print(f"Column {col} is full already!")
continue
return col
def make_move(col, color):
for r in reversed(range(ROWS)): # start from the bottom and go up
if board[r][col] == EMPTY: # find the lowest empty cell
board[r][col] = color
return # we only want to place once, so return once we're done
raise ValueError(f"Unable to place {color} in column {col}")
# this shouldn't ever happen since we've verified the top cell is empty in get_input, but let's make sure
def check_diag(row, col, player, inc): # check column, always going down and either left or right
cur_count = 0
while row < ROWS and 0 <= col < COLUMNS: # if we're out of bounds we can stop
if board[row][col] == player: # if player matches we count that cell
cur_count += 1
if cur_count == 4: # check if 4 in a row has been reached
return True
else: # if it's not the player, we have to restart
cur_count = 0
row += 1
col += inc # go either left or right
return False
def check_winner(player):
for row in range(ROWS): # check all rows
cur_count = 0
for col in range(COLUMNS):
if board[row][col] == player:
cur_count += 1
if cur_count == 4:
return True
else:
cur_count = 0
for col in range(COLUMNS): # check all columns
cur_count = 0
for row in range(ROWS):
if board[row][col] == player:
cur_count += 1
if cur_count == 4:
return True
else:
cur_count = 0
for row in range(ROWS):
if check_diag(row, 0, player, 1) or check_diag(row, COLUMNS - 1, player, -1):
return True
for col in range(COLUMNS):
if check_diag(0, col, player, 1) or check_diag(0, col, player, -1):
return True
return False
def main():
print("Welcome to Connect Four!")
for move in range(ROWS * COLUMNS):
print_board()
col = get_input()
if move % 2 == 0:
make_move(col, PLAYER_ONE)
if check_winner(PLAYER_ONE):
print("Player one wins!")
break
else:
make_move(col, PLAYER_TWO)
if check_winner(PLAYER_TWO):
print("Player two wins!")
break
if not check_winner(PLAYER_ONE) and not check_winner(PLAYER_TWO):
print("Draw.")
print_board()
if __name__ == "__main__":
main() |
89e34d107352ac4d53f14dfa1b1b0871094b85b0 | wardDes/SandwichMaker | /SandwichMaker.py | 3,344 | 3.625 | 4 | import pyinputplus as pyip, time
costs = {
'wheat': 0.20,
'white': 0.10,
'sourdough': 0.30,
'tofu': 0.10,
'turkey': 0.20,
'chicken': 0.30,
'ham': 0.40,
'cheddar': 0.10,
'swiss': 0.20,
'mozzarella': 0.30,
'mayo': 0.10,
'mustard': 0.10,
'lettuce': 0.10,
'tomato': 0.20,
}
# wheat,ham,swiss,mayo,mustard,lettuce, tomato, = 0.2+0.4+0.2+-0.1+0.1+0.1+0.1= 1.2
# sourdough, chicken,mozzarella, mayo,mustard, tomato = 0.30+0.30+0.30+0.30 = 1.2
ordTot = 0.00
ordSndwichTot = 0.00
mtbrdchz= {}
condmnts ={}
while True:
breadType = pyip.inputMenu(['wheat', 'white', 'sourdough'],
prompt="Enter the desired type of bread\n", numbered=True)
#print(breadType, costs[breadType])
ordSndwichTot += costs[breadType]
mtbrdchz['bread']= breadType
#print("{0:.2f}".format(ordSndwichTot))
print()
meatType = pyip.inputMenu(['chicken', 'turkey','ham','tofu'],
prompt="Enter the type of meat for the sandwich\n", numbered=True)
#print(meatType, costs[meatType])
mtbrdchz['meat']= meatType
ordSndwichTot += costs[meatType]
#print("{0:.2f}".format(ordSndwichTot))
print()
optCheese = pyip.inputYesNo("Would you like cheese on you sandwich?")
if optCheese =='yes':
cheeseType = pyip.inputMenu(['cheddar','swiss','mozzarella'], numbered=True)
mtbrdchz['cheese']= cheeseType
#print(cheeseType, costs[cheeseType])
ordSndwichTot += costs[cheeseType]
ordSndwichTot = round(ordSndwichTot, 2)
#print("{0:.2f}".format(ordSndwichTot))
print()
optMayo = pyip.inputYesNo("Would you like mayo on you sandwich?")
if optMayo == 'yes':
# add 'mayo' to complete sandwich dictionary or list
print('mayo added')
ordSndwichTot += costs['mayo']
condmnts['mayo']=True
print()
optMustard = pyip.inputYesNo("Would you like mustard on you sandwich?")
if optMustard == 'yes':
# add 'mayo' to complete sandwich dictionary or list
print('mustard added')
ordSndwichTot += costs['mustard']
condmnts['mustard']=True
print()
optLettuce = pyip.inputYesNo("Would you like lettuce on you sandwich?")
if optLettuce == 'yes':
# add 'mayo' to complete sandwich dictionary or list
print('lettuce added')
ordSndwichTot += costs['lettuce']
condmnts['lettuce']=True
print()
optTomato = pyip.inputYesNo("Would you like tomato on you sandwich?")
if optTomato == 'yes':
# add 'mayo' to complete sandwich dictionary or list
print('tomato added')
ordSndwichTot += costs['tomato']
condmnts['tomato']=True
print()
numSndwchs = pyip.inputNum('Enter number of sandwiches of this type desired: ',
min=1, lessThan=6)
#print("{0:.2f}".format(ordSndwichTot))
print()
print('Your sandwich order:')
for i in mtbrdchz:
print(i, ":", mtbrdchz.get(i))
for i in condmnts:
print(i, ":", condmnts.get(i))
print()
ordSubmit = pyip.inputYesNo('Confirm sandwich ingredients correct: ')
if ordSubmit == 'yes':
ordSndwichTot *= numSndwchs
ordTot = ordSndwichTot
print("Total: ${0:.2f}".format(ordTot))
break
else:
print('Please resubmit your sandwich order.')
mtbrdchz.clear()
condmnts.clear()
print()
time.sleep(2)
continue
|
0c1b80b214878c7d27d9a1aca3a7d6ddb0a07cb2 | srikanthraju536/code | /scripts/gny07a.py | 1,060 | 3.734375 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: dvdreddy
#
# Created: 03/11/2012
# Copyright: (c) dvdreddy 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import string
import math
def toint(s): return int(s)
def get_int():
s=raw_input()
return int(s)
def get_line_int():
s=raw_input()
arr=string.split(s)
arr=map(toint,arr)
return arr
def get_float():
s=raw_input()
return float(s)
def main():
t=get_int()
x=1
while t:
s=raw_input()
arr=string.split(s)
i=int(arr[0])-1
temp=''
if(i==0):
temp=arr[1][1:]
elif(i==len(arr[1])-1):
temp=arr[1][0:len(arr[1])-1]
else:
temp=arr[1][0:i]+arr[1][i+1:]
print x,temp
x+=1
t-=1
pass
if __name__ == '__main__':
main()
|
4e216faa7112377481e2db396167e631b94d6610 | srikanthraju536/code | /scripts/iwgbs.py | 702 | 3.546875 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: dvdreddy
#
# Created: 17/02/2012
# Copyright: (c) dvdreddy 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
def get_int():
s=raw_input()
return int(s)
def main():
t=get_int()
a=[]
for i in range(t):
a.append([0]*2)
a[t-1][0]=1
a[t-1][1]=1
for i in range(t-2,-1,-1):
a[i][0]=a[i+1][1]
a[i][1]=a[i+1][0]+a[i+1][1]
print a[0][0]+a[0][1]
pass
if __name__ == '__main__':
main()
|
046cb14334380ac239796cd65f1d8d1eb7731094 | srikanthraju536/code | /scripts/bhishop.py | 549 | 3.515625 | 4 | #!/usr/bin/env python
import string
def toint(s): return int(s)
def get_int():
s=raw_input()
return int(s)
def get_line_int():
s=raw_input()
arr=string.split(s)
arr=map(toint,arr)
return arr
def size(s): return len(s)
def main():
while 1:
try:
s=raw_input()
if(s=='1'): print '1'
elif(s=='0'): print '0'
else: print 2*(long(s)-1)
except(EOFError):
break
pass
if __name__ == '__main__':
main()
|
8515e351074e62e8e69e9dc17ea2eb6cdc128e0e | farhanaroslan/python-playground | /veggies.py | 567 | 4.03125 | 4 | #Farhana Roslan and Koshi Murakoshi
import csv
vegetables = [
{"name": "eggplant", "color": "purple"},
{"name": "tomato", "color": "red"},
{"name": "corn", "color": "yellow"},
{"name": "okra", "color": "green"},
{"name": "arugula", "color": "green"},
{"name": "broccoli", "color": "green"},
]
#In the loop, write the name of each vegetable and the color into a CSV called vegetables.csv
with open('vegetables.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(['Name of Vegetable', 'Color'])
for veg in vegetables:
writer.writerow([veg["name"],veg["color"]])
|
298b0658d737ee604cc21b1edcdf5ce725dbfef3 | colinwd/ctci | /chapter1/question8.py | 271 | 3.84375 | 4 | # Assume you have a method `isSubstring` which checks if one word is a substring of another. Given two strings, `s1` and
# `s2`, write code to check if `s2` is a rotation of `s1` using only one call to `isSubstring` (e.g., "waterbottle" is a
# rotation of "erbottlewat"). |
4cb75a34e0f6806c8990bc06079272effbc2451c | patrickdeyoreo/holbertonschool-interview | /0x19-making_change/0-making_change.py | 1,161 | 4.15625 | 4 | #!/usr/bin/python3
"""
Given a list of coin denominations, determine the fewest number of coins needed
to make a given amount.
"""
def makeChange(coins, total):
"""
Determine the fewest number of coins needed to make a given amount.
Arguments:
coins: list of coin denominations
total: total amount to make
Return:
If the amount cannot be produced by the given denominations, return -1.
Otherwise return the fewest number of coins needed to make the amount.
"""
if total > 0:
checked = [True]
checked.extend(False for _ in range(total))
n_coins = 0
queue = [0]
while queue:
n_coins += 1
level = []
for value in queue:
for coin in coins:
if value + coin == total:
return n_coins
if value + coin >= total:
continue
if not checked[value + coin]:
checked[value + coin] = True
level.append(value + coin)
queue = level
return -1
return 0
|
703548dbe6d9ab7fc7eb26c7145a4967deb77201 | Sakshi-2020/My-Captain-Python- | /file_extension.py | 197 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 11 22:13:41 2021
@author: ssing
"""
fn= input("Input the Filename: ")
f = fn.split('.')
print ("The extension of the file is : " + f[-1]) |
4c4662c3f87c4fbc0be7d8322a741df187d2f5b5 | Nikita53/python-class | /pie.py | 150 | 4.09375 | 4 | PI = 3.1416
radius = raw_input('enter radius of circle(meters):')
area = PI * float(radius) ** 2
print("\narea of circle = %.2f sq. meters" % area) |
31d07fd3332e0b6ca050f4ee3df184451287d710 | gauborg/code_snippets_python | /14_power_of_two.py | 1,220 | 4.625 | 5 | '''
Description: The aim of this code is to identify if a given numer is a power of 2.
The program requires user input.
The method keeps bisecting the number by 2 until no further division by 2 is possible.
'''
def check_power_of_two(a, val):
# first check if a is odd or equal to zero or an integer
if (a <= 0):
print("Number is zero!")
return None
elif (a%2 != 0):
print("Odd number! Cannot be a power of 2!")
return None
else:
residual = a
count = 0
while((residual != 0)):
if (residual%2 == 1):
return None
# go on dividing by 2 every time
half = residual/2
residual -= half
count += 1
# stop when the final residual reaches 1
if (residual == 1):
break
return count
# user input for number
number = int(input("Enter a number = "))
# call function to check if the number is power of 2.
power = check_power_of_two(number, 0)
if (power != None):
print("The number is a power of 2, power =", power)
elif(power == None):
print("The number is not a power of 2.") |
f65d53c042bebae591090aebbf16b3b155e0eee2 | gauborg/code_snippets_python | /7_random_num_generation.py | 1,416 | 4.5 | 4 | '''
This is an example for showing different types of random number generation for quick reference.
'''
# code snippet for different random options
import os
import random
# generates a floating point number between 0 and 1
random1 = random.random()
print(f"\nRandom floating value value between using random.random() = {random1}\n")
# generates a floating number between a given range
random2 = random.uniform(1, 5)
print(f"Random floating vlaue between 1 and 5 using random.uniform() = {random2}\n")
# generates a number using Gaussian distribution
random3 = random.gauss(10, 2)
print(f"Gaussian distribution with mean 10 and std deviation 2 using random.gauss() = {random3}\n")
# generates a random integer between a range
random4 = random.randrange(100)
print(f"Random integer value between using random.randrange() = {random4}\n")
# generates a random integer between a range with inclusion
random5 = random.randrange(0, 100, 11)
print(f"Random integer value with spacing 11 between using random.randrange() = {random5}\n")
# choosing an element from a list at random
random6 = random.choice(['win', 'lose', 'draw'])
print(f"Random element chosen from the list using random.choice() = {random6}")
print("If sequence is empty, it will raise IndexError.\n")
# shuffling a list
some_numbers = [1.003, 2.2, 5.22, 7.342, 21.5, 76.3, 433, 566, 7567, 65463]
random.shuffle(some_numbers)
print(some_numbers)
|
1a43399846eb6fb18cb1d67f98e89a2b48ad6591 | itwill009/TL | /prepare for coding test/structure/linkedlist.py | 1,380 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 28 17:16:29 2018
@author: cdh66
"""
class Node:
def __init__(self,item):
self.val = item
self.next = None
class LinkedList:
def __init__(self,item):
self.head = Node(item)
def add(self,item):
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(item)
def printlist(self):
cur = self.head
while cur is not None:
print(cur.val)
cur = cur.next
def remove(self,item):
if self.head.val == item:
self.head = self.head.next
else:
cur = self.head
while cur.next is not None:
if cur.val == item:
self.removeItem(item)
return
cur = cur.next
print('does not exist')
def removeItem(self,item):
cur = self.head
while cur.next is not None:
if cur.next.val == item:
nextnode= cur.next.next
cur.next = nextnode
break
ll = LinkedList(3)
print(ll.head.val, ll.head.next)
ll.add(4)
print(ll.head.val,ll.head.next.val,ll.head.next.next)
ll.add(1)
ll.add(5)
ll.remove(3)
ll.printlist()
ll.remove(5)
ll.printlist()
|
0fa0b497237955c3d8206973c25f8932b2e383f0 | jkamby/portfolio | /docs/trivia/commandLineArguments/twoints.py | 657 | 3.5625 | 4 | # -----------------------------------------------------------------------
# twoints.py
# -----------------------------------------------------------------------
import stdio
import sys
# Accept two +ve integers as command-line arguments. Writes 'Both' if
# they are mutually divisible, 'One' if one is divisible by the other but
# not the other by the first (or vice versa) and 'Neither' if neither is
# divisible by the other.
a = int(sys.argv[1])
b = int(sys.argv[2])
if ((a % b == 0) and (b % a == 0)):
stdio.writeln('Both')
elif ((a % b == 0) or (b % a == 0)):
stdio.writeln('One')
else:
stdio.writeln('Neither')
|
7ee6bdfa257c5b815d07d96df0e886826146606c | jkamby/portfolio | /docs/trivia/arrays/transpose.py | 669 | 4 | 4 | # -----------------------------------------------------------------------
# transpose.py
# -----------------------------------------------------------------------
import stdio
import sys
# Transposing a two-dimensional array (of ints).
# This program is designed to prompt for input
stdio.writeln('Prepare to enter the original matrix.')
stdio.write('How many rows? ')
n = stdio.readInt()
stdio.write('How many columns? ')
m = stdio.readInt()
original = [[stdio.readInt() for i in range(m)] for j in range(n)]
# stdio.writeln(original) - debugging code
transposed = [[row[x] for row in original] for x in range(m)]
stdio.writeln(transposed)
|
2c17e2b6ed89bebf30bbf9a2f25bb8f0793c0019 | jkamby/portfolio | /docs/trivia/modulesAndClients/realcalc.py | 1,358 | 4.15625 | 4 | import sys
import stdio
def add(x, y):
"""
Returns the addition of two floats
"""
return float(x) + float(y)
def sub(x, y):
"""
Returns the subtraction of two floats
"""
return float(x) - float(y)
def mul(x, y):
"""
Returns the multiplication of two floats
"""
return float(x) * float(y)
def div(x, y):
"""
Returns the division of two floats
"""
if(float(y) == 0):
stdio.writeln("The divisor must not be zero.")
return
else:
return float(x) / float(y)
def mod(x, y):
"""
Returns the modulo of two ints
"""
if(int(y) == 0):
stdio.writeln("The mudulo operand may not be zero.")
return
else:
return int(x) % int(y)
def exp(x, y):
"""
Returns the result of one float raised to the power of the other
"""
return float(x) ** float(y)
def main():
a = sys.argv[1]
b = sys.argv[2]
stdio.writeln("Addition: " + str(add(a, b)))
stdio.writeln("Subtraction: " + str(sub(a, b)))
stdio.writeln("Multiplication: " + str(mul(a, b)))
stdio.writeln("Division: " + str(div(a, b)))
stdio.writeln("Modulo: " + str(mod(a, b)))
stdio.writeln("Exponentiation: " + str(exp(a, b)))
if __name__ == '__main__':
main()
|
bf6cbe715b8b69eb6986923928f979b8bfdcdafe | shajia1234/PIAIC_python | /june18.py | 1,160 | 3.765625 | 4 | # #*********ADD SUBTRACT MUTIPLY DIVIDE****************
# a=int(input("enter 1st no."))
# b=int(input("enter 2nd no."))
# def add(num1 , num2):
# sum=num1+num2
# print(sum)
# add(a,b)
# def sub(num1 , num2):
# minus=num1-num2
# print(minus)
# def mult(num1 , num2):
# prdct=num1*num2
# print(prdct)
# def div(num1 , num2):
# divide=num1/num2
# print(divide)
# sub(a,b)
# mult(a,b)
# div(a,b)
# #**********positioning in udf***********#
# def my_pet(owner , pet):
# print(owner,"is an owner of", pet)
# my_pet(owner="john",pet="cat")
# #*********even\odd*********#
# def chk_num(number):
# if number % 2 == 0:
# print("number is even")
# else:
# print("number is odd")
# num = int(input("enter num"))
# chk_num(num)
#***************************8
def display_result(winner, score, **other_info):
print("The winner was " + winner)
print("The score was " + score)
for key, value in other_info.items():
print(key + ": " + value)
display_result(winner="Real Madrid", score="1-0",
overtime ="yes", injuries="none", test ="done") |
322198418ae857e1cf588edf7202b4c0ec469dff | helenefialko/python_basic_course | /l5_functions/homework/functions_hw.py | 2,790 | 3.65625 | 4 | import os
def card_has_errors():
region = os.environ.get('CARD_TYPE', 'Europe')
if region == 'China':
num = card_has_errors_china()
else:
num = card_has_errors_europe()
return num
def card_has_errors_china():
temp_num = []
while True:
if len(temp_num) == 3:
print('Your card number is correct!')
return temp_num
else:
temp_num = []
num = input(str('Please, enter the number of your credit card in format XXXX XXXX XXXX: ')).split(
' ')
for i in num:
if len(i) != 4:
temp_num = []
break
try:
n = int(i)
except Exception as e:
temp_num = []
break
else:
temp_num.append(n)
def card_has_errors_europe():
temp_num = []
while True:
if len(temp_num) == 4:
print('Your card number is correct!')
return temp_num
else:
temp_num = []
num = input(str('Please, enter the number of your credit card in format XXXX XXXX XXXX XXXX: ')).split(' ')
for i in num:
if len(i) != 4:
temp_num = []
break
try:
n = int(i)
except Exception as e:
temp_num = []
break
else:
temp_num.append(n)
def print_bank(num):
if num[0] == 5167:
print('You use PrivatBank credit card')
elif num[0] == 5375:
print('You use Monobank credit card')
else:
print('You use credit card from the unknown bank')
def cvv_has_errors():
cvv = 0
date = 0
exc = 0
while True:
if exc == 1 and len(date) == 2 and len(cvv) == 3:
print('Your exp_date and cvv is correct!')
return False
else:
list_t = []
date_without_split = input('Please, enter expiration date in format mm/yy: ')
date = date_without_split.split('/')
if len(date) != 2:
continue
cvv = input('Please, enter CVV: ')
list_t.append(cvv)
list_t.append(date[0])
list_t.append(date[1])
for i in list_t:
try:
int_er = int(i)
except Exception as e:
exc = 0
list_t = []
break
if len(list_t) == 3:
if int(list_t[1]) <= 0 or int(list_t[1]) > 12 or int(list_t[2]) <= 18:
break
else:
exc = 1
|
ac438a71aaa9ce9aa8a1a060e228233cefdb6131 | cwroblew/ud036_StarterCode | /media.py | 773 | 3.53125 | 4 | import webbrowser
class Movie():
""" This class provides a way to store movie related information
Args:
movie_title (str): Title of movie
movie_storyline (str): Brief description of the story line of the movie
poster_image (str): URL of an image to be used for the movie ie poster
trailer_youtube (str): URL of a trailer video for the movie
"""
VALID_RATINGS = ["G", "PG", "PG-13", "R"]
def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
webbrowser.open(self.trailer_youtube_url)
|
468f67d5824d3a42ce0d7d5ee80b13c67199c86b | Dianeha/TIL | /00_startcamp/day03/quiz.py | 1,983 | 3.84375 | 4 | # words = input('입력하세요: ') # 사용자의 입력을 받으면 그것이 숫자든 문자든 다 str(문자열)로 받는다
# print(type(words)) # 124d, 하다연, sdfff든 다 str
# # words 의 첫 글자와 마지막 글자를 출력하라.
# print(words[0], words[-1])
# # 이렇게 쓰는 것은 리스트에서 쓰는 방법 아닌가요? string도 리스트처럼 메모리에 저장 > 리스트뿐 아니라 문자열도 인덱스 접근이 가능하다.
# # 문자열은 리스트로 형변환 가능하다
# my_list = list('123456')
# print(type(my_list))
# print(my_list[0], my_list[-1])
# 첫 글자와 마지막 글자를 출력
import random
length = random.choice(range(1, 100))
numbers = list(range(length))
print(numbers[length-1])
print(numbers[-1]) # list[-1]은 리스트의 뒤에서 첫번째 요소를 지칭
print(numbers[-2])
# # range() 함수는 list 생성함수는 아니지만 range()는 for문으로 돌려서 리스트처럼 출력 가능
# list화 하려면 numbers = list(range(length)) 이런 식으로 해야한다.
# <자연수 n을 입력받고, 1부터 n까지 출력하라>
n = input('원하시는 자연수를 입력해주세요: ')
# print(type(n))
n = int(n)
# print(type(n))
# print(n)
# for number in numbers:
# print(number)
for i in range(n):
print(i + 1, end=' ')
# <짝수/홀수를 구분하자> 2 => '짝' 출력
number = int(input('원하시는 숫자를 입력하세요: '))
if number % 2 == 0:
print('짝!')
else:
print('홀!')
numbers = range(4, 9)
for num in numbers:
print(num)
# <fizz buzz => 3의 배수에서 fizz, 5의 배수에서 buzz, 15의 배수 fizzbuzz 출력>
n = int(input('원하시는 숫자를 입력하세요: '))
for num in range(1, n + 1):
if num % 15 == 0:
print('fizzbuzz', end=' ')
elif num % 3 == 0:
print('fizz', end=' ')
elif num % 5 == 0:
print('buzz', end=' ')
else:
print(num, end=' ')
|
e097d14d0842c7f614d200a0ad1364924d06512e | Dianeha/TIL | /Algorithm/patternmatching.py | 445 | 3.546875 | 4 | def BruteForce(p, t):
i = 0
j = 0
while j < len(p) and i < len(t):
if t[i] != p[j]:
i = i - j
j = -1
i = i + 1
j = j + 1
if j == len(p):
return i - len(p)
else:
return -1
print(BruteForce("is", "This is a book~!"))
def Bmoore(pt, test):
skip = [x for x in range(len(pt)+1)]
pt = 'rithm'
test = 'a pattern matching algorithm'
print(Bmoore(pt, test)) |
297b0702c3e1bd5059c4d401155898ce4dc0298d | Day2543/Data_Structure | /Caesar_Cipher.py | 2,017 | 3.515625 | 4 | from Lab3 import MyQueue
def EnDe(mode,code,text):
FinalText = MyQueue()
if (mode == 'E' or mode == 'e'):
for i in text:
if(i != ' '):
num = ord(i) + code.deQueue()
if num > ord('z') and ord(i) >= 97 and ord(i) <= 122: # small
temp = int(num - ord('z'))
num = 96 + temp
if num > ord('Z') and ord(i) >= 65 and ord(i) <= 90:#big
temp = int(num - ord('Z'))
num = 64 + temp
FinalText.enQueue(chr(num))
else:
FinalText.enQueue(' ')
elif(mode == 'D' or mode == 'd'):
for i in text:
if(i != ' '):
num = ord(i) - code.deQueue()
if num < ord('A') and ord(i) >= 65 and ord(i) <= 90: #big
temp = int(ord('A') - num)
num = 91 - temp
if num < ord('a')and ord(i) >= 97 and ord(i) <= 122:#small
temp = int(ord('a') - num)
num = 123 - temp
FinalText.enQueue(chr(num))
else:
FinalText.enQueue(' ')
return FinalText.items
text_input = input('Enter text : ')
code_input = input('Enter code : ')
mode_input = input('Encode(E) or Decode(D) : ')
j=0
n=0
code = MyQueue()
for i in text_input:
if(i != ' '):
j+=1
for i in range(j):
code.enQueue(ord(code_input[n])-48)
n+=1
if (n == len(code_input)):
n = 0
print(EnDe(mode_input,code,text_input))
#256183
#decode
|
0612db1c4fe32040e402f033d1d12e9173599946 | brnjohnson1991/WorkingStuff | /VendingMachineSite/Program2Design.py | 1,536 | 3.625 | 4 | # Bradley Johnson, 010, 2/22/16
# Purpose: Generate a random fraction problem based on a difficulty input
# Pre-conditions: Difficulty Input, a "L" or "R" answer
# Post-conditions: Random Fractions, a comparison question, and a correct or incorrect statement
# display title
# ask the user "difficulty?" (1-3)
#
# input a difficulty value
#
# generate 4 random integers using difficulty above
# if difficulty is less than or equal to 1 generate in range 1-9 and assign as Num1,Den1,Num2,Den2
# if difficulty is greater than 1 and less than 3 generate in range 5-15 and assign as Num1,Den1,Num2,Den2
# if difficulty is greater than or equal to 3 generate in range 10-18 and assign as Num1,Den1,Num2,Den2
# ensure the two fractions don't have the same denominator (that would be too easy)
# if Den1 equals Den2 regenerate a number over same range (use 3 nested ifs to replicate the ranges) and assign to Den2
# else execute the following as a print statement
#
# display as 2 fractions, one near left side of screen, other one to the right of that
#
# calculate which one is less (cross multiply)
# if Num1*Den2 is greater than Num2*Den1 then variable "correct" is assigned R
# if Num1*Den2 is less than Num2*Den1 then variable "correct" is assigned L
# ask the user "which one is less L or R"
# assign L or R input to variable "answer"
# tell the user if they got it right or not
# if "answer" matches "correct" print the correct statement
# else print the incorrect statement
|
b5b87e0444e3c59c193d29f14d90f6526568f024 | brnjohnson1991/WorkingStuff | /VendingMachineSite/lab 4 practice.py | 660 | 3.828125 | 4 | from graphics import *
def main():
win = GraphWin("Triangles", 500, 500)
click_prompt = Text(Point(250, 250), "Click three times")
click_prompt.draw(win)
click_prompt.setSize(20)
click_prompt.setFill("blue")
pt1 = win.getMouse()
circ1 = Circle (pt1, 5)
circ1.draw(win)
pt2 = win.getMouse()
circ2 = Circle (pt2, 5)
circ2.draw(win)
pt3 = win.getMouse()
circ3 = Circle(pt3, 5)
circ3.draw(win)
poly1 = Polygon (pt1, pt2, pt3)
poly1.draw(win)
poly1.setWidth(3)
# pause program so user can see window
win.getMouse()
win.close()
main() |
aa154320cffa9bac85743231bc0e5e5a01e5280f | Sguerra1702/Calculadora-Complejos | /vectores.py | 5,632 | 3.75 | 4 | import numpy as np
def vectores():
np_vector_1 = [3 + 4j, 2 - 3j, 5 + 8j]
np_vector_2 = [5 + 4j, 1 - 9j, 4 + 6j]
vector_1 = np.array(np_vector_1)
vector_2 = np.array(np_vector_2)
print(vector_1)
print(vector_2)
print("")
print("")
return vector_1, vector_2
def sumavectores(vector_1, vector_2):
vector_suma = vector_1 + vector_2
print("El vector resultante de sumar A y B es", vector_suma)
print("")
print("")
def restavectores(vector_1, vector_2):
vector_resta = vector_1 - vector_2
print("El vector resultante de sumar A y B es", vector_resta)
print("")
print("")
def inverso_aditivo(vector_1, vector_2):
inverso_ad_1 = -1 * vector_1
inverso_ad_2 = -1 * vector_2
print("Los inversos aditivos de los vectores A y B son", inverso_ad_1, "y", inverso_ad_2, "respectivamente")
print("")
print("")
def escalar_vector(vector_1, vector_2):
print("digite un complejo escalar")
escalar = complex(input())
resultante_1 = escalar * vector_1
resultante_2 = escalar * vector_2
print("Los vectores resultantes de multiplicar el escalar", escalar, "por los vectores A y B son", resultante_1, "y", resultante_2)
print("")
print("")
def matrices():
np_matriz_1 = [[3 + 5j, 8 - 2j, 4 - 8j], [8 - 2j, 6 + 5j, 1 - 8j], [2 + 5j, 3 - 8j, 4 + 7j]]
np_matriz_2 = [[4 + 5j, 6 - 3j, 5 - 1j], [9 - 3j, 5 + 5j, 1 - 2j], [5 + 8j, 7 - 4j, 3 + 5j]]
matriz_1 = np.array(np_matriz_1)
matriz_2 = np.array(np_matriz_2)
print(matriz_1)
print("")
print(matriz_2)
print("")
print("")
return matriz_1, matriz_2
def suma_matriz(matriz_1, matriz_2):
suma = matriz_1 + matriz_2
print("la matriz resultante es:")
print(suma)
print("")
print("")
def inverso_aditivo_matriz(matriz_1, matriz_2):
inv_aditivo_matriz_1 = (-1) * matriz_1
inv_aditivo_matriz_2 = (-1) * matriz_2
print("los inversos aditivos de las matrices son")
print(inv_aditivo_matriz_1)
print(inv_aditivo_matriz_2)
print("")
print("")
def mult_matriz_escalar(matriz_1, matriz_2):
print("Digite un número complejo")
escalar = complex(input())
escalar_matriz_1 = escalar * matriz_1
escalar_matriz_2 = escalar * matriz_2
print("Las matrices resultantes de multiplicar el escalar", escalar, "por las matrices A y B son", escalar_matriz_1, "y", escalar_matriz_2)
print("")
print("")
def transpuesta_matriz(matriz_1, matriz_2):
transpuesta_1 = np.transpose(matriz_1)
transpuesta_2 = np.transpose(matriz_2)
print("Las transpuestas de las matrices son")
print(transpuesta_1)
print(transpuesta_2)
def conjugado_matriz(matriz_1, matriz_2):
conjugado_1 = np.conjugate(matriz_1)
conjugado_2 = np.conjugate(matriz_2)
print("Los conjugados de las matrices son")
print(conjugado_1)
print(conjugado_2)
print("")
print("")
def conjugado_vector(vector_1, vector_2):
conjugado_vector_1 = np.conjugate(vector_1)
conjugado_vector_2 = np.conjugate(vector_2)
print("Los conjugados de los vectores son")
print(conjugado_vector_1)
print(conjugado_vector_2)
print("")
print("")
def adjunta_matriz(matriz_1, matriz_2):
adjunta_1 = np.matrix(matriz_1)
adjunta_2 = np.matrix(matriz_2)
print("Las adjuntas de las matrices son")
print(adjunta_1)
print(adjunta_2)
print("")
print("")
def mult_matrices(matriz_1, matriz_2):
multi_matriz = np.matmul(matriz_1, matriz_2)
print("La matriz producto es")
print(multi_matriz)
print("")
print("")
def producto_interno(vector_1, vector_2):
interno = np.dot(vector_1, vector_2)
print("El producto interno de los vectores es:", interno)
print("")
print("")
def norma_vector(vector_1, vector_2):
suma_cuadrados_1 = 0
suma_cuadrados_2 = 0
n = len(vector_1)
for cont in range(n - 1):
suma_cuadrados_1 = suma_cuadrados_1 + (vector_1[cont] ** 2)
suma_cuadrados_2 = suma_cuadrados_2 + (vector_2[cont] ** 2)
norma1 = np.sqrt(suma_cuadrados_1)
norma2 = np.sqrt(suma_cuadrados_2)
print("La norma del vector A es:")
print(norma1)
print("La norma del vector B es:")
print(norma2)
print("")
print("")
def si_matriz_hermitiana(matriz_1, matriz_2):
adjunta_1 = np.matrix(matriz_1)
adjunta_2 = np.matrix(matriz_2)
if matriz_1 == adjunta_1:
print("La matriz A es hermitiana")
else:
print("La matriz A NO es hermitiana")
if matriz_2 == adjunta_2:
print("La matriz A es hermitiana")
else:
print("La matriz A NO es hermitiana")
print("")
print("")
def producto_tensor(vector_1, vector_2):
tensor = np.tensordot(vector_1, vector_2, axes=0)
print("El producto tensor de los dos vectores es ")
print(tensor)
print("")
print("")
def main():
vector_1, vector_2 = vectores()
sumavectores(vector_1, vector_2)
restavectores(vector_1, vector_2)
inverso_aditivo(vector_1, vector_2)
escalar_vector(vector_1, vector_2)
matriz_1, matriz_2 = matrices()
suma_matriz(matriz_1, matriz_2)
inverso_aditivo_matriz(matriz_1, matriz_2)
mult_matriz_escalar(matriz_1, matriz_2)
transpuesta_matriz(matriz_1, matriz_2)
conjugado_matriz(matriz_1, matriz_2)
conjugado_vector(vector_1, vector_2)
adjunta_matriz(matriz_1, matriz_2)
mult_matrices(matriz_1, matriz_2)
producto_interno(vector_1, vector_2)
norma_vector(vector_1, vector_2)
si_matriz_hermitiana(matriz_1, matriz_2)
producto_tensor(vector_1, vector_2)
main()
|
d73e431b1d060340e19c996baab44ac656119088 | michaelrbock/ctci-solutions | /ch4/4-1-fixed.py | 892 | 3.609375 | 4 | def is_balanced(root):
if root == None or (root.l_child == None and root.r_child == None):
return True
if root.l_child == None:
l_height = 0
else:
l_height = count_height(root.l_child, 1) # small fix
if root.r_child == None:
r_height = 0
else:
r_height = count_height(root.r_child, 1)
return is_balanced(root.l_child) and is_within_one(l_height, r_height) and is_balanced(root.r_child)
def count_height(root, height):
if root.l_child == None and root.r_child == None:
return height
elif root.l_child == None:
return count_height(root.r_child, height + 1)
elif root.r_child == None:
return count_height(root.l_child, height + 1)
l_height = count_height(root.l_child, height + 1)
r_height = count_height(root.r_child, height + 1)
return max(l_height, r_height)
def is_within_one(num1, num2):
return (num1 - num2 == 0) or (num1 - num2 == 1) or (num1 - num2 == -1)
|
d116c100ac210b90344af07285f03a30a1acceae | michaelrbock/ctci-solutions | /ch1/1-7-paper.py | 231 | 3.625 | 4 | def set_zeros(matrix):
for i, row in enumerate(matrix):
for j, element in enumerate(row):
if element == 0:
# change row to 0's
for k in row:
k = 0
# change col to 0's
for row1 in matrix:
row1[j] = 0
|
c60646383287e231c961f426aaa146e7cb7bc3b0 | gmmack/ProjectEuler | /P6/p6.py | 419 | 3.984375 | 4 | """Calculates the difference between the sum of the squares
of the first one hundred natural numbers and the square
of the sum and prints the result. Project Euler #6"""
def sum_of_squares ():
summ = 0
for i in range(1,101):
summ += i**2
return summ
def square_of_sums ():
summ = 0
for i in range(1,101):
summ += i
return summ**2
print square_of_sums()-sum_of_squares()
|
a743debf018b5322b6a681783aa0a009fbfd3b61 | karingram0s/karanproject-solutions | /fibonacci.py | 722 | 4.34375 | 4 |
#####---- checks if input is numerical. loop will break when an integer is entered
def checkInput(myinput) :
while (myinput.isnumeric() == False) :
print('Invalid input, must be a number greater than 0')
myinput = input('Enter number: ')
return int(myinput)
#####---- main
print('This will print the Fibonacci sequence up to the desired number.')
intinput = checkInput(input('Enter number: '))
while (intinput < 1) :
print('Number is 0, please try again')
intinput = checkInput(input('Enter number: '))
a = 0
b = 1
temp = 0
for i in range(intinput) :
print('{0} '.format(a+b), end='', flush=True)
if (i < 1) :
continue
else :
temp = a + b
a = b
b = temp
print('')
|
b49f2181faed685fb72d09530d2740d42c701044 | liulichao1/python-0426 | /day03/tuple-test.py | 318 | 4.0625 | 4 | tup = ('Hello','World')
print(tup)
numbers = (1,)
print(numbers)
print(len(numbers))
names = tuple(('test','test'))
print(names.count('test'))
print(names.index('test'))
superstars = ['Tom','Jerry']
names = (superstars,'Spike')
print(names)
names[0].append('Mike')
print(names)
for name in names:
print(name) |
6d9bf0a0dda331efeea914b1afdd999db0df82c0 | liulichao1/python-0426 | /day01/string.py | 210 | 3.9375 | 4 | s = 'Hello, Word!'
s = 'hello, Word!'
print(s[0])
print(s*3)
print(s[4:8])
print('He' in s)
print(s.capitalize())
print(s.center(20,'-'))
print(s.count('o'))
print(s.endswith('!',0,13))
print(s.find(',',10,13)) |
f21f60d58db7d6c55caf9d962bbf5e4e54165d12 | TheRareFox/Socket-programming | /client-1.py | 443 | 3.90625 | 4 | import socket
#Creates a new socket
my_socket = socket.socket()
#Gets the address of the server
address = input('Enter IPv4 address of server: ')
#Gets the port of the server
port = int(input('Enter port number of server: '))
#all the names of the host
host = socket.gethostname()
#Connects to the server
my_socket.connect((address,port))
#prints out the data recieved from server
print(my_socket.recv(1024))
my_socket.close()
|
6df19549a6ed132b6f3704ff950db87599b80777 | TheRareFox/Socket-programming | /game.py | 12,727 | 3.625 | 4 | import random
import time
class Map:
def __init__(self):
self.map = []
ran = random.randint(1,19)
for i in range(20):
a = ['|']
recent = True
treasure = True
for j in range(18):
if j == ran and i == 13:
a.append('T')
elif random.randint(0,10) == 10 and recent:
a.append('E')
recent = False
else:
a.append('.')
a.append('|')
self.map.append(a)
def get_map(self):
return self.map
def change_map(self,x,y):
self.map[x][y] = "."
def show(self,char_pos):
#print(self.map)
char_x = char_pos[0]
lower_x = char_x - 3 if char_x - 4 > 0 else 0
upper_x = char_x + 5 if char_x +4 < len(self.map)-1 else len(self.map)-1
char_y = char_pos[1]
lower_y = char_y - 3 if char_y - 4 > 0 else 0
upper_y = char_y + 5 if char_y +4 < len(self.map[1])-1 else len(self.map[1])
for x in range(lower_x,upper_x):
for y in range(lower_y,upper_y):
if y == char_y and x == char_x:
print('C',end = "")
else:
print(self.map[x][y],end = "")
print()
def show_map(self,char_pos):
for x in range(len(self.map)):
for y in range(len(self.map[x])):
if x == char_pos[0] and y == char_pos[1]:
print('C',end = "")
else:
print(self.map[x][y],end = "")
print()
def enemy_encounter(self,char_pos):
if self.map[char_pos[0]][char_pos[1]] == "E":
print("Enemy encountered!")
return True
else:
return False
def treasure_encounter(self,char_pos):
if self.map[char_pos[0]][char_pos[1]] == "T":
print("Treasure picked up!")
return True
else:
return False
def add_enemy(self):
for i in range(len(self.map)):
for j in range(len(self.map[i])):
a = random.randint(1,10)
if a == 1 and self.map[i][j] == ".":
self.map[i][j] = "E"
class Enemy:
def __init__(self,difficulty):
self.health = difficulty*5
self.attack = difficulty/2*3
def get_health(self):
return self.health
def get_attack(self):
return self.attack
def hit(self,dmg):
self.health -= dmg
def damage(self):
return self.attack + random.randint(-3,3)
def status(self):
return "Enemy health left: {}".format(self.health)
def get_sprite(self):
return """
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░▒▒░░░░░░░░░░░░▒▒░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░██ ▓▓░░░░░░░░▓▓ ▓▓░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░██ ▓▓░░░░░░▓▓ ▓▓░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░██ ▓▓░░░░░░▓▓░░ ▓▓░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░██ ░░ ▓▓░░░░▓▓ ░░ ▓▓░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░██ ░░ ▓▓░░░░▓▓ ░░░░ ▓▓░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░▓▓ ▓▓░░ ▓▓▓▓ ░░▓▓░░ ▓▓░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░▓▓ ░░▓▓▒▒ ▓▓▓▓ ▓▓▓▓▒▒ ▒▒░░░░░░░░░░░░
░░░░░░░░░░░░░░░░▓▓ ░░▓▓▓▓░░░░░░░░░░▓▓▓▓░░ ▓▓░░░░░░░░░░░░
░░░░░░░░░░░░░░▒▒░░ ░░▓▓▒▒ ░░░░▒▒▒▒ ▓▓░░░░░░░░░░░░
░░░░░░░░░░░░░░▓▓░░░░ ▓▓ ░░ ▓▓░░░░░░░░░░░░
░░░░░░░░░░░░░░▓▓░░░░ ░░ ████░░ ▒▒██░░░░░░░░░░░░░░
░░░░░░░░░░░░░░▓▓░░░░░░ ██▓▓▓▓▓▓ ▓▓▓▓░░░░░░░░░░░░░░
░░░░░░░░██▓▓▓▓▒▒▒▒░░░░ ▓▓▓▓▓▓▓▓ ▓▓▓▓░░░░░░░░░░░░░░
░░░░░░██░░ ▓▓▒▒▒▒░░ ▓▓▓▓▓▓▓▓░░ ░░▓▓▓▓░░░░░░░░░░░░░░
░░░░░░▓▓░░░░ ▒▒▒▒░░ ░░▓▓▓▓▓▓▒▒░░ ▓▓ ▓▓░░░░░░░░░░░░
░░░░░░▓▓▓▓░░░░ ░░░░░░ ▓▓▓▓░░░░ ░░ ▓▓░░░░░░░░░░░░
░░░░░░░░▓▓▒▒░░░░ ░░ ░░▓▓░░░░░░░░ ░░▓▓░░░░░░░░░░░░
░░░░░░░░▓▓▓▓▓▓░░░░ ░░ ░░░░▓▓░░░░▓▓▓▓░░░░▓▓░░░░░░░░░░░░
░░░░░░░░▓▓▓▓▓▓▒▒░░ ░░░░ ░░░░░░▒▒░░░░░░▒▒▒▒░░░░░░░░░░░░░░
░░░░░░██▓▓▒▒▓▓▓▓▓▓░░ ░░░░ ░░░░░░░░░░▓▓██░░░░░░░░░░░░░░░░
░░░░██▓▓▒▒▒▒▒▒▓▓▓▓▓▓░░ ░░░░░░░░░░▒▒██░░░░░░░░░░░░░░░░░░░░
░░██▓▓▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓░░ ████▓▓▓▓▓▓░░░░░░░░░░░░░░░░░░░░░░
░░▓▓▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓░░░░▓▓▓▓▓▓░░ ▓▓░░░░░░░░░░░░░░░░░░░░
░░▓▓▓▓▒▒▒▒▒▒▒▒▒▒▓▓▒▒▓▓▓▓░░ ▓▓▓▓▒▒░░▓▓░░░░░░░░░░░░░░░░░░░░
░░▓▓▓▓░░░░▒▒▒▒▓▓▓▓▓▓▒▒▓▓░░ ▓▓▓▓▓▓░░░░▒▒░░░░░░░░░░░░░░░░░░
░░▓▓░░░░ ▓▓▓▓▓▓░░▓▓▓▓▒▒░░▒▒▓▓▓▓▓▓░░ ▓▓░░░░░░░░░░░░░░░░░░
░░▓▓░░░░▒▒▓▓▓▓░░░░▒▒▓▓▒▒ ▓▓▓▓▓▓▓▓░░▒▒░░░░░░░░░░░░░░░░░░░░
░░░░██ ▓▓ ▓▓░░░░░░░░▓▓██░░░░▓▓░░ ██░░░░░░░░░░░░░░░░░░░░
░░░░██ ░░░░▓▓░░░░░░░░░░░░░░░░▓▓▓▓░░░░░░░░░░░░░░░░░░░░░░
░░░░░░██ ██░░▓▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░██░░██░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
"""
class Character:
def __init__(self):
self.pos = [0,1]
self.health = 20
self.attack = 5
def move(self,direction,mp):
if direction.lower() == "up":
if self.pos[0] - 1 >= 0:
self.pos[0] -= 1
else:
print("False move, try again")
elif direction.lower() == "down":
if self.pos[0] + 1 <= 20:
self.pos[0] += 1
else:
print("False move, try again")
elif direction.lower() == "left":
if self.pos[1] - 1 > 1:
self.pos[1] -= 1
else:
print("False move, try again")
elif direction.lower() == "right":
if self.pos[1] + 1 < 19:
self.pos[1] += 1
else:
print("False move, try again")
if mp.treasure_encounter(self.pos):
print("YOU FOUND THE TREASURE! YOU WIN!")
return False
elif mp.enemy_encounter(self.pos):
print("Fighting enemy...")
enemy = Enemy(random.randint(1,4))
while True:
print(enemy.get_sprite())
print("1. Attack 2. Run(50% chance)")
a = input("Enter action(1,2): ")
while a != '1' and a != '2':
print("Invalid input")
a = input("Enter action(1,2): ")
print(enemy.status())
print("Your health: {}".format(self.health))
if a == '1':
dmg = self.attack + random.randint(-3,3)
enemy.hit(dmg)
print("Attacked enemy for {} damage!".format(dmg))
print(enemy.status())
if enemy.get_health()< 0:
print("Enemy defeated!")
break
elif a == '2':
if 1 == random.randint(1,2):
print("Ran away successfully!")
break
else:
print("Failed to run away!")
dmg = enemy.damage()
print("Enemy hit you for {} damage! {} health remaining".format(dmg,self.health - dmg))
self.health -= dmg
if self.health <0:
print("You have been killed!")
return False
time.sleep(2)
mp.change_map(self.pos[0],self.pos[1])
mp.show(self.pos)
else:
mp.show(self.pos)
return True
def get_pos(self):
return self.pos
mp = Map()
char = Character()
mp.show_map(char.get_pos())
print("Legend: C - character position E- enemy position T - Treasure position")
print("WELCOME TO NET, WHERE YOUR GOAL IS TO OBTAIN ALL THE TREASURES WHILE FIGHTING ENEMIES! GOOD LUCK!")
index = 0
while True:
if index >7:
index = 0
print("ENEMIES ADDED!")
mp.add_enemy()
mp.show_map(char.get_pos())
movement = input("WHERE DO YOU WANT TO GO?(up,down,left,right): ").lower()
while movement != 'up' and movement != 'down' and movement != 'left' and movement != 'right':
print("Please only input up,down,left or right")
movement = input("WHERE DO YOU WANT TO GO?(up,down,left,right): ").lower()
bo = char.move(movement,mp)
if not bo:
print("Game over!")
break
index += 1
|
7f7574401f70130f37f3237cd877907693aaec37 | ZLester/maximum-compatibility-matrix | /scratch/example2.py | 2,577 | 3.5 | 4 | # A Participant is a member of a group. The participant
# has a list of other participants they like and dislike
class Participant:
def __init__(self):
self.group = None
self.likes = []
self.dislikes = []
def addToGroup(group):
self.group = group
def removeFromGroup(group):
self.group = None
def likes(self, participant):
self.likes.append(participant)
def dislikes(self, participant):
self.dislikes.append(participant)
# A Group is a list of participants.
class Group:
def __init__(self):
self.participants = []
def addParticipant(participant):
self.participants.append(participant))
def removeParticipant(participant):
self.participants.remove(participant)
# I don't want to be able to add a participant to a group without having that
# group also set in the participants group property.
# Right now I have to make 2 calls to accomplish it.
Cohort
cohort.addParticipantToGroup
newParticipant.addToGroup(newGroup)
newGroup.addParticipant(newParticipant)
# This seems bad. What's the best way to handle this?
# I want to make sure it is impossible for the two
# to be out of sync.
# An Arrangement is a list of groups with participants.
class Arrangement:
def __init__(self):
self.participants = []
self.groups = []
def addGroup(self, group):
self.groups.append(group)
def addParticipant(self, participant):
self.participants.append(participant)
# A Strategy is a way to calculate the compatibility
# score of an Arrangement.
class Strategy:
def __init__(self, arrangement):
self.arrangement = arrangement
self.mutateRate = 0.1
self.maximumExpectedValueWeight = 1.0
self.minimumSacrificialGoatWeight = 0.2
self.allowGroupWithDislikes = True
self.startingPopulation = 10
def score(self, arrangement):
score = 0
for group in arrangement.groups:
score += group.getScore()
# Perform other modifications using properties in __init__
return score
# Different situations could call for different strategies.
# What's the best way to decouple Strategies and Arrangements
# so that the strategy can work with different arrangements.
# For example:
# What if the participants are Flowers and we want
# to create 5 groups of flowers that are most similar in color
# while minimizing the height difference between the flowers
# of a group and adding some weight to flowers that smell
# similarly.
# So now where do we go?
myArrangement.score(Strategy(param1, param2, param3))
# or
myStrategy.score(myArrangement)
|
a45c6b736f50bc170c61d4fbb5cccc786b342f89 | njzapata0602/capture-5-Python- | /Exercise 1.py | 169 | 3.609375 | 4 | #Nick Zapata - ch 5 - ex 1 - 2/15/18
fruit = input('Enter a string: ')
index = len(fruit)
while index > 0:
letter = fruit[index-1]
print (letter)
index = index - 1 |
45160bc5073ba2a31baba734a12b6439068b79cc | RaymondUW/Class-Projects-at-UW | /Insomnia and its impact/testingq.py | 2,919 | 3.75 | 4 | """
Mingyang Xue, Coco Cheng
CSE 163 AG, AF
This file implements test functions for the final project.
"""
import pandas as pd
import matplotlib.pyplot as plt
import q1CleanData
import q1
import q2
def testq1Num(dt, num):
"""
Takes in the cleaned dataset dt and the num from q1
Tests q1 by calculating the average sleeping time
and tests the accuracy of the plot by calculating
the min value of the number of the insomniac
people
"""
avg_sleeptime = dt['Avg hrs per day sleeping'].mean()
print("The average sleeping time of the entire experiment is ",
avg_sleeptime)
min_num = num['Number of Insomniac People'].min()
min_year = num[num['Number of Insomniac People'] == min_num]
print(min_year)
def testq2mean(df):
"""
Takes in the cleaned dataset data2
Tests the accuracy of average sleep quality measurement for different
groups of patients by calculating those values in a different way.
"""
q2.sex_stat(df)
print(df.loc[df['sex'] == 'Female']['KSQ_OverallSleepQuality'].mean())
print(df.loc[df['sex'] == 'Male']['KSQ_OverallSleepQuality'].mean())
q2.age_groups_stat(df)
print(df.loc[df['AgeGroup'] == 'Old']['KSQ_OverallSleepQuality'].mean())
print(df.loc[df['AgeGroup'] == 'Young']['KSQ_OverallSleepQuality'].mean())
q2.educ_level_stat(df)
print(df.loc[df['EducationLevel'] == 0]['KSQ_OverallSleepQuality'].mean())
print(df.loc[df['EducationLevel'] == 1]['KSQ_OverallSleepQuality'].mean())
print(df.loc[df['EducationLevel'] == 2]['KSQ_OverallSleepQuality'].mean())
print(df.loc[df['EducationLevel'] == 3]['KSQ_OverallSleepQuality'].mean())
def testq3Relation(df):
"""
Takes in the cleaned dataset data2
Tests the accuracy of q3's plots by running similar
codes which draw scatter plots on similar dataset
"""
fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, figsize=(20, 10), ncols=2)
d1 = df[['HADS_Anxiety', 'KSQ_OverallSleepQuality']]
d1.plot(x='KSQ_OverallSleepQuality', y='HADS_Anxiety',
ax=ax1, kind='scatter', c='HADS_Anxiety')
d3 = df[['HADS_Depression', 'KSQ_OverallSleepQuality']]
d3.plot(x='KSQ_OverallSleepQuality', y='HADS_Depression',
ax=ax3, kind='scatter', c='HADS_Depression')
d2 = df[['KSQ_HealthProblem', 'KSQ_OverallSleepQuality']]
d2.plot(x='KSQ_OverallSleepQuality', y='KSQ_HealthProblem',
ax=ax2, kind='scatter', c='KSQ_HealthProblem')
d4 = df[['BMI1', 'KSQ_OverallSleepQuality']]
d4.plot(x='KSQ_OverallSleepQuality', y='BMI1',
ax=ax4, kind='scatter', c='BMI1')
fig.savefig('q3Quality.png')
def main():
data = pd.read_excel('/home/data1.xlsx')
dt = q1CleanData.cleanData(data)
num = q1.numberOfPeople(dt)
testq1Num(dt, num)
df = pd.read_csv('/home/data2.csv')
testq2mean(df)
testq3Relation(df)
if __name__ == '__main__':
main()
|
db41fbd8af8497b8223a0d5fe12cd0bfaad064b7 | jinxilongjxl/algorithm-diagram | /chapter6/breadth_first_search.py | 932 | 3.65625 | 4 | from collections import deque
# 准备数据
graph = {}
graph["you"] = ["bob","claire","alice"]
graph["bob"] = ["anuj","peggy"]
graph["claire"] = ["thon","jonny"]
graph["alice"] = ["peggy"]
graph["anuj"] = []
graph["peggy"] = []
graph["thon"] = []
graph["jonny"] = []
graph["peggy"] = []
# 定义函数判断是否为销售商
def is_seller(name):
return name[-1] == 'm'
# 广度优先搜索算法
def bfs(name):
search_quene = deque()
search_quene += graph[name]
searched = []
while search_quene:
# 取出队列中的第一人
person = search_quene.popleft()
if person not in searched:
# 判断是否为销售商
if is_seller(person):
print("%s is a seller!" % (person))
return True
else:
search_quene += graph[person]
searched.append(person)
return False
print(bfs("you"))
|
e8820945ee5fc464b745d97a54f5a04733794b45 | jinxilongjxl/algorithm-diagram | /chapter3/recursion_count.py | 230 | 3.84375 | 4 | def count_element(list):
# 基线条件
if list == []:
return 0
# 递归条件
else:
return 1 + count_element(list[1:])
# 测试
print(count_element([1,2,3]))
print(count_element([1,2,3,4]))
|
e6ebf5a16461af6ea607d48c38b782e141d89f1c | mnaufal121/Map_Filter_Function | /nfom2.py | 472 | 3.8125 | 4 | numbers = ((1, 7), (2, 0), (4, 5))
plus = []
minus = []
devide = []
cubic = []
for x in range(len(numbers)):
plus.append(list(numbers[x]))
minus.append(list(numbers[x]))
devide.append(list(numbers[x]))
cubic.append(list(numbers[x]))
for y in range(len(numbers[x])):
plus[x][y] += 2
minus[x][y] -= 2
devide[x][y] /= 2
cubic[x][y] = pow(cubic[x][y], 3)
print(numbers)
print(plus)
print(minus)
print(devide)
print(cubic)
|
cccb7b1963c7a1e211eb2ef7f142e579d17f8787 | Ernest-Macharia/Data-Structures-in-Python | /squares.py | 74 | 3.671875 | 4 | squares = [x**2 for x in range(10) ]
print("squares are: " + str(squares)) |
6dc641d3b1e777c33c5ed1cbf1a1753ee97527af | Ernest-Macharia/Data-Structures-in-Python | /indexoflist.py | 129 | 3.75 | 4 | x = ["kiatu", "shuka", "kitabu", "kitanda"]
indx = [i for i, k in enumerate(x) if k == "kitabu" ]
print("index: " + str(indx[0])) |
77b2f5298767983904bb8f15d770a7acf7bb7e61 | aojuolaa/WorkMarketExercise | /Friendly_Competition.py | 2,163 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 09:24:56 2016
@author: DEBOLA
"""
import pandas as pd
#read file
c=pd.read_csv("NYC_Jobs.csv")
#use pandas aggregation function to group by Agency
grouped = c['# Of Positions'].groupby(c['Agency'])
#sum the result and sort in descending order
u=grouped.sum().sort_values(ascending=False)
print '\n'
#print the highest value
print 'Most Openings: ' + u.keys()[0] + ' -' +" " + str(u[0])
#the "Posting Updated column provides the status of job
#convert the column to date format.
c['Posting_Updated']=pd.to_datetime(c['Posting Updated'])
#change the index of the dataframe to a date format for easy slicing
c.index=c.Posting_Updated
#for recent job openings we use February 2016 and the status with
d=c['2016-02']
print '\n'
print "Highest and Lowest paying positions "
print "current job openings: February 2016"
print '\n'
print "FOR ANNUAL RATE: "
#print '\n'
# we extract both annual and hour rate
annual=d[d['Salary Frequency']=='Annual']
hourly=d[d['Salary Frequency']=='Hourly']
#find the highest annual salary
high = max(annual['Salary Range To'])
highest_salary = annual[annual['Salary Range To']==high]
x= highest_salary['Agency'].unique()
print 'Highest:'
for i in x:
print i + ' ' + "pays " +str(high)+'/Annum'
print '\n'
#find the lowest annual salary
low = min(annual['Salary Range To'])
#compute all rows equivalent to the highest salary
lowest_salary = annual[annual['Salary Range To']==low]
#return just unique values of Agency
y=lowest_salary['Agency'].unique()
print 'Lowest:'
for i in y:
print i + ' ' + "pays " +str(low)+'/Annum'
print'\n'
#calculate highest and lowest hourly rate
print 'FOR HOURLY RATE:'
high = max(hourly['Salary Range To'])
highest_salary = hourly[hourly['Salary Range To']==high]
x= highest_salary['Agency'].unique()
print "Highest:"
for i in x:
print i + ' ' + "pays " +str(high)+'/Hour'
print '\n'
low = min(hourly['Salary Range To'])
lowest_salary = hourly[hourly['Salary Range To']==low]
y=lowest_salary['Agency'].unique()
print 'Lowest:'
for i in y:
print i + ' ' + "pays " +str(low)+'/Hour'
|
2703b1a704fcd51a6675abef900bd8564c3ad4e4 | sravanidonthana14/sravani | /Alphabet or Not.py | 109 | 3.984375 | 4 | x=raw_input()
if((x>='a' and x<='z')or(x>='A' ana x<='Z')):
print(("Alphabet")
else:
print("No")
|
f427ee4ead3b36d59b61983fbd336148f06aa7fa | muthu048/guvi | /sum of n number.py | 110 | 3.921875 | 4 | n=int(input())
sum=0
if n>0:
for i in range (1,n+1):
sum=sum+i
print ('the sum is',sum)
|
34e19fa750992c4512119b1c688628eec5aa91ce | jbartos3/pynet_test | /strex1.py | 208 | 3.65625 | 4 | name1 = 'Huey'
name2 = 'Dewey'
name3 = 'Louie'
name4 = raw_input('Who is the head duck?: ')
print '{:>30}'.format(name1)
print '{:>30}'.format(name2)
print '{:>30}'.format(name3)
print '{:>30}'.format(name4)
|
35fb678edb2369ca09c40eecfb4b8856b5ded353 | jlocamuz/Mi_repo | /clase12-08-20/main.py | 711 | 4.15625 | 4 | class Clase():
def __init__(self, atributo=0):
# Que yo ponga atributo=0 significa que si yo no le doy valor
# A ese atributo por defecto me pone 0
self.atributo = atributo
def get_atributo(self):
# setter and getter: darle un valor a un atributo y obtener
# el valor del atributo
return self.atributo
def set_atributo(self, value):
self.atributo = value
if __name__ == "__main__":
objeto1 = Clase(1)
objeto2 = Clase(2)
# objeto1 = Clase(1)
# objeto2 = Clase(2)
# es lo mismo hacerlo con el setter y getter
objeto1.set_atributo(1)
objeto2.set_atributo(2)
print(objeto1.__dict__)
print(objeto2.__dict__)
|
972a1b992737d16d31e3b2d1492be3f42bd666a2 | starcaptain123/Stepic-Lessons | /1/3 Functions, Dictionaries, Files/3_7_3.py | 464 | 3.546875 | 4 | d = int(input()) # кол-во слов в словаре
Dictionary = [] # словарь
Text = []
result = []
for i in range(d):
Dictionary.append(input().lower())
l = int(input()) # кол-во строк текста
for k in range(l):
List = [i for i in input().lower().split()]
Text.extend(List)
for i in range(len(Text)):
if Text[i] not in Dictionary and Text[i] not in result:
result.append(Text[i])
for i in result:
print(i) |
2b356a3847e1f94fe9e8b3d4c7a32b5929967d5d | 05anushka/loop | /sevenstar.py | 166 | 3.734375 | 4 | i=1
while i<=4:
b=1
while b<7:
print(" ",end="")
b=b+2
k=1
while k<=4:
print("*", end="")
k=k+2
print()
i=i+1
|
2cc1d886719e3d3dbd49876f3010d85ddf147b33 | Diego8791/bucles_python | /ejercicios_practica.py | 16,738 | 4.1875 | 4 | #!/usr/bin/env python
'''
Bucles [Python]
Ejercicios de práctica
---------------------------
Autor: Inove Coding School
Version: 1.1
Descripcion:
Programa creado para que practiquen los conocimietos
adquiridos durante la semana
'''
__author__ = "Inove Coding School"
__email__ = "alumnos@inove.com.ar"
__version__ = "1.1"
# Variable global utilizada para el ejercicio de nota
notas = [70, 82, -1, 65, 55, 67, 87, 92, -1]
# Variable global utilizada para el ejercicio de temperaturas
temp_dataloger = [12.8, 18.6, 14.5, 20.8, 12.1, 21.2, 13.5, 18.6,
14.7, 19.6, 11.2, 18.4]
def ej1():
print('Comenzamos a ponernos serios!')
'''
Realice un programa que pida por consola dos números que representen
el principio y fin de una secuencia numérica.
Realizar un bucle "for" que recorra esa secuencia armada con "range"
y cuente cuantos números ingresados hay, y la sumatoria de todos los números
Tener en cuenta que "range" no incluye el número de "fin" en su secuencia,
sino que va hasta el anterior
'''
# inicio = ....
inicio = int(input('Indique el primer número de la secuencia:\n'))
# fin = ....
fin = int(input('Indique el último número de la secuencia:\n'))
# cantidad_numeros ....
cantidad_numeros = 0
# sumatoria ....
sumatoria = 0
# bucle.....
for i in range(inicio, fin +1):
cantidad_numeros += 1
sumatoria += i
# Al terminar el bucle calcular el promedio como:
# promedio = sumatoria / cantidad_numeros
promedio = sumatoria / cantidad_numeros
# Imprimir resultado en pantalla
print('La cantidad de números son', cantidad_numeros)
print('La sumatiria de la secuencia es:', sumatoria)
print('El promedio de la secuencia es', promedio)
def ej2():
print("Mi Calculadora (^_^)")
'''
Tome el ejercicio de clase:
<condicionales_python / ejercicios_practica / ej3>,
copielo a este ejercicio y modifíquelo, ahora se deberá ejecutar
indefinidamente hasta que como operador se ingrese la palabra "FIN",
en ese momento debe terminar el programa
Se debe debe imprimir un cartel de error si el operador ingresado no es
alguno de lo soportados o no es la palabra "FIN"
'''
opción = ' '
while opción != 'FIN':
numero_1 = float(input("Ingrese el primer número: "))
numero_2 = float(input("Ingrese el segundo número: "))
print(" - Suma (+)")
print(" - Resta (-)")
print(" - Multiplicación (*)")
print(" - División (/)")
print("- Exponente/Potencia (**)")
simbolo = input("Ingrese la operación a realizar: ")
if simbolo == '+':
print(f"La suma de {numero_1} y {numero_2} es {numero_1 + numero_2}")
elif simbolo == '-':
print(f"La resta de {numero_1} y {numero_2} es {numero_1 - numero_2}")
elif simbolo == '*':
print(f"La multiplicación de {numero_1} y {numero_2} es {numero_1 * numero_2}")
elif simbolo == '/':
print(f"La división de {numero_1} y {numero_2} es {numero_1 / numero_2}")
elif simbolo == '**':
print(f"La potencia de base {numero_1} y exponente {numero_2} es {numero_1 ** numero_2}")
else:
print("Esta calculadora no realiza la operación pedida. ¡Lo siento!")
opción = input('¿Desea continuar?, ingresando FIN termina el programa\n')
def ej3():
print("Mi organizador académico (#_#)")
'''
Tome el ejercicio de "calificaciones":
<condicionales_python / ejercicios_clase / ej3>,
copielo a este ejercicio y modifíquelo para cumplir
el siguiente requerimiento
Las notas del estudinte se encuentran almacenadas en una
lista llamada "notas" que ya hemos definido al comienzo del archivo
Debe caluclar el promedio de todas las notas y luego transformar
la califiación en una letra según la escala establecida en el ejercicio
"calificaciones" <condicionales_python / ejercicios_clase / ej3>
A medida que recorre las notas, no debe considerar como válidas aquellas
que son negativas, en ese caso el alumno estuvo ausente
Debe contar la cantidad de notas válidas y la cantidad de ausentes
'''
# Para calcular el promedio primero debe obtener la suma
# de todas las notas, que irá almacenando en esta variable
sumatoria = 0 # Ya le hemos inicializado en 0
cantidad_notas = 0 # Aquí debe contar cuantas notas válidas encontró
cantidad_ausentes = 0 # Aquí debe contar cuantos ausentes hubo
# Realice aquí el bucle para recorrer todas las notas
# y cacular la sumatoria
for nota in notas:
if nota > 0:
sumatoria += nota
cantidad_notas += 1
else:
cantidad_ausentes += 1
# Terminado el bucle calcule el promedio como
promedio = sumatoria / cantidad_notas
# Utilice la nota promedio calculada y transformela
# a calificación con letras, imprima en pantalla el resultado
# Imprima en pantalla al cantidad de ausentes
# Si el promedio es mayor igual a 90 --> imprimir A
# Si el promedio es mayor igual a 80 --> imprimir B
# Si el promedio es mayor igual a 70 --> imprimir C
# Si el promedio es mayor igual a 60 --> imprimir D
# Si el promedio es manor a 60 --> imprimir F
# Debe imprimir en pantalla la calificacion
# Utilizar "if" anidados
if promedio >= 90:
print("Calificación: A")
else:
if promedio >= 80:
print("Calificación: B")
else:
if promedio >= 70:
print("Calificación: C")
else:
if promedio >= 60:
print("Calificación: D")
else:
print("Calificación: F")
print('El promedio de las notas es', promedio)
print('La cantidad de clases ausentes son:', cantidad_ausentes)
def ej4():
print("Mi primer pasito en data analytics")
'''
Tome el ejercicio:
<condicionales_python / ejercicios_practica /ej5>,
copielo a este ejercicio y modifíquelo para cumplir el
siguiente requerimiento
En este ejercicio se lo provee de una lista de temperatuas,
esa lista de temperatuas corresponde a los valores de temperaturas
tomados durante una temperorada del año en Buenos Aires.
Ustede deberá analizar dicha lista para deducir
en que temporada del año se realizó el muestreo de temperatura.
La variable con la lista de temperaturas se llama "temp_dataloger"
definida al comienzo del archivo
Debe recorrer la lista "temp_dataloger" y obtener los siguientes
resultados
1 - Obtener la máxima temperatura
2 - Obtener la mínima temperatura
3 - Obtener el promedio de las temperatuas
Los resultados se deberán almacenar en las siguientes variables
que ya hemos preparado para usted
'''
temperatura_max = -300 # Aquí debe ir almacenando la temp máxima
temperatura_min = 300 # Aquí debe ir almacenando la temp mínima
temperatura_sumatoria = 0 # Aquí debe ir almacenando la suma de todas las temp
temperatura_promedio = 0 # Al finalizar el loop deberá aquí alamcenar el promedio
temperatura_len = 0 # Aquí debe almacenar cuantas temperatuas hay en la lista
# Colocar el bucle aqui......
for temperatura in temp_dataloger:
if temperatura > temperatura_max:
temperatura_max = temperatura
if temperatura < temperatura_min:
temperatura_min = temperatura
temperatura_sumatoria += temperatura
temperatura_len += 1
print('La temperatura máxima registrada es',temperatura_max)
print('La temperatura mínima registrada es', temperatura_min)
print('La sumatoria de temperaturas es', round(temperatura_sumatoria, 2))
print('La cantidad de registros en temp_dataloguer son', temperatura_len)
# Al finalizar el bucle compare si el valor que usted calculó para
# temperatura_max y temperatura_min coincide con el que podría calcular
# usando la función "max" y la función "min" de python
# función "max" --> https://www.w3schools.com/python/ref_func_max.asp
# función "min" --> https://www.w3schools.com/python/ref_func_min.asp
print('¿temperatura_max dá igual que la función max()?')
if temperatura_max == max(temp_dataloger):
print('¡SI!')
else:
print('¡NO!')
print('¿temperatura_min dá igual que la función min()?')
if temperatura_min == min(temp_dataloger):
print('¡SI!')
else:
print('¡NO!')
# Al finalizar el bucle debe calcular el promedio como:
# temperatura_promedio = temperatura_sumatoria / cantidad_temperatuas
temperatura_promedio = temperatura_sumatoria / temperatura_len
print('El promedio de temperaturas es', round(temperatura_promedio, 2))
# Corroboren los resultados de temperatura_sumatoria
# usando la función "sum"
# función "sum" --> https://www.w3schools.com/python/ref_func_sum.asp
print('¿temperatura_sumatoria dá igual que la función sum()?')
if temperatura_sumatoria == sum(temp_dataloger):
print('¡SI!')
else:
print('¡NO!')
'''
Una vez que tengamos nuestros valores correctamente calculados debemos
determinar en que epoca del año nos encontramos en Buenos Aires utilizando
la estadística de años anteriores. Basados en el siguiente link realizamos
las siguientes aproximaciones:
verano --> min = 19, max = 28
otoño --> min = 11, max = 24
invierno --> min = 8, max = 14
primavera --> min = 10, max = 24
Referencia:
https://es.weatherspark.com/y/28981/Clima-promedio-en-Buenos-Aires-Argentina-durante-todo-el-a%C3%B1o
'''
# En base a los rangos de temperatura de cada estación,
# ¿En qué época del año nos encontramos?
# Imprima el resultado en pantalla
# Debe utilizar temperatura_max y temperatura_min para definirlo
if temperatura_min >= 19 and temperatura_max <= 28:
print('Estamos en verano')
else:
if temperatura_min >= 11 and temperatura_max <= 24:
print('Estamos en otoño')
else:
if temperatura_min >= 8 and temperatura_max <= 14:
print('Estamos en invierno')
else:
if temperatura_min >= 10 and temperatura_max <= 24:
print('Estamos en primavera')
def ej5():
print("Ahora sí! buena suerte :)")
'''
Tome el ejercicio:
<condicionales_python / ejercicios_practica / ej4>,
copielo a este ejercicio y modifíquelo para cumplir
el siguiente requerimiento
Realize un programa que corra indefinidamente en un bucle, al comienzo de la
iteración del bucle el programa consultará al usuario con el siguiente menú:
1 - Ordenar por orden alfabético (usando el operador ">")
2 - Ordenar por cantidad de letras (longitud de la palabra)
3 - Salir del programa
En caso de presionar "3" el programa debe terminar e informar por
pantalla de que ha acabado,
en caso contrario si se presionar "1" o "2" debe continuar con la siguiente tarea
NOTA: Si se ingresa otro valor que no sea 1, 2 o 3 se debe enviar
un mensaje de error y volver a comenzar el bucle
(vea en el apunte "Bucles - Sentencias" para encontrar
la sentencia que lo ayude a cumplir esa tarea)
Si el bucle continua (se presionó "1" o "2") se debe ingresar a otro bucle
en donde en cada iteración se pedirá una palabra. La cantidad de iteración
(cantidad de palabras a solicitar) lo dejamos a gusto del alumno, intente que esa
condición esté dada por una variable (ej: palabras_deseadas = 4)
Cada palabra ingresada se debe ir almacenando en una lista de palabras, dicha
lista la debe inicializar vacia y agregar cada nuevo valor con el método "append".
Luego de tener las palabras deseadas almacenadas en una lista de palabras
se debe proceder a realizar las siguientes tareas:
Si se ingresa "1" por consola se debe obtener la palabra
más grande por orden alfabético
Luego de terminar de recorrer toda la lista (utilizar un bucle "for")
se debe imprimir en pantalla cual era la palabra
más grande alfabeticamente.
Recuerde que debe inicializar primero su variable
donde irá almacenando la palabra que cumpla dicha condición.
¿Con qué valor debería ser inicializada dicha variable?
Si se ingresa "2" por consola se debe obtener la palabra
con mayor cantidad de letras
Luego de terminar de recorrer toda la lista (utilizar un bucle "for")
se debe imprimir en pantalla cual era la palabra con
mayor cantidad de letras.
Recuerde que debe inicializar primero su variable
donde irá almacenando la palabra que cumpla dicha condición.
¿Con qué valor debería ser inicializada dicha variable?
NOTA: Es recomendable que se organice con lápiz y papel para
hacer un bosquejo del sistema ya que deberá utilizar 3 bucles en total,
1 - El bucle principal que hace que el programa corra hasta ingresar un "3"
2 - Un bucle interno que corre hasta socilitar todas las palabras deseadas
que se deben ir guardando en una lista
3- Otro bucle interno que corre luego de que termine el bucle "2" que
recorre la lista de palabras y busca la mayor según el motivo ingresado ("1" o "2")
'''
print('-----------------NUEVO EJERCICIO 5-----------------------------------')
lista_palabras = []
anulador_2 = 0
contador = 0
cant_palabras = int(input("Indique cuantas palabras desea ingresar: "))
for i in range(cant_palabras):
contador = 0
if i == 0:
palabra = input("Ingrese una palabra: ")
lista_palabras.append(palabra)
else:
palabra = input("Ingrese una palabra: ")
for j in range(len(lista_palabras)):
if palabra == lista_palabras[j]:
# Quería hacer terminar el programa pero no me finaliza
print("¡ATENCIÓN!, ha repetido una palabra")
print("La repetición de una palabra no se registra")
else:
if contador == 0:
lista_palabras.append(palabra)
contador += 1
if len(palabra) == len(lista_palabras[j]):
print("Palabra con igual cantidad de letras")
print("No será posible ordenar por letras")
anulador_2 += 1
opcion = 0
while True:
if anulador_2 == 0:
print('------------------------------------------')
print('Elija su opción:')
print('1 - Ordenar palabras por orden alfabético')
print('2 - Ordenar palabras por cantidad de letras')
print('3 - Salir del programa')
print('------------------------------------------')
opcion = int(input('Ingrese su opción: '))
else:
print('------------------------------------------')
print('Elija su opción')
print('1 - Ordenar palabras por orden alfabético')
print('3 - Salir del programa')
print('------------------------------------------')
opcion = int(input('Ingrese su opción'))
if opcion == 1:
lista_palabras.sort(reverse=True)
print(lista_palabras)
print('La palabra mas grande alfabéticamente es', lista_palabras[0])
break
elif opcion == 2:
for i in range(len(lista_palabras)-1):
if len(lista_palabras[i+1]) > len(lista_palabras[i]):
cant_letras = lista_palabras[i+1]
print(cant_letras)
break
elif opcion == 3:
break
else:
print('Ha ingresado una opción no válida')
if __name__ == '__main__':
print("Ejercicios de práctica")
#ej1()
#ej2()
#ej3()
#ej4()
ej5()
|
1e62380b2c9933cfa82f3d7571a3c41e0538303f | kcboggs/OPS301 | /Personal/lists.py | 186 | 4 | 4 |
friends = ["mochi", "bori", "ally", "brandon", "max"]
# to get after index 1
print(friends[1:])
# to get up to
print(friends[1:3])
# to modify
friends[1] = "fox"
print(friends[1])
|
b018ab7a30564d373c154ec2f298ac332e88adf8 | kcboggs/OPS301 | /Personal/getting-input.py | 170 | 4.28125 | 4 | name = input("Enter your name: ") # we want to get a input from user
print("Hellow " + name + "!")
age = input("Enter your age: ")
print("you are " + age + " years old") |
eea3b413c62201f1a4d5ba654833aca32e535fe5 | Workaholicws/Workaholicws | /findReapet.py | 1,100 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 6 08:08:51 2015
@author: WangS
"""
from __future__ import unicode_literals
import os
# This program is used to find repeat element in TXT.
# Check.txt is for original element and mayRepeat.txt is for element include repeat.
# Result.txt save the check results.
# PS:it may run twice.
os.chdir("/Users/genius/Desktop/LOOK/PulsarResult_WS")
f = open("findReapetResults.txt","w")
checkList=[]
mayRepeat = open('mayRepeat.txt', 'r') # Put String in mayRepeat.txt, each String per line.
i = 0
for line in mayRepeat.readlines():
i = i+1
if line[-1] == '\n': # If the last String is \n, delete.
line = line[0:-1]
if line in checkList:
print("Repeat Element: %s at line%d (first line at LINE %d)\n" %(line, i, checkList.index(line)+1),file=f )
# os and ,file=f can put print into Results.txt. Donot Forget \n! or you will get nothing :-)
checkList[len(checkList):] = [''] # Give the space for the repeat element
else:
checkList[len(checkList):] = [line]
mayRepeat.close()
|
9cf2e808ae2b3169759629c1b3b904d4a68bd774 | DennyJohnsonp/Lab-Sem-06-Programs | /MT6P1/EX3_3.PY | 595 | 3.5 | 4 | from sympy import Matrix
dim_v=3
a=Matrix([[1,-1,0],[2,0,1],[1,1,1]])
r=a.rank()
b=a.rref()
print(f'Range Space of A is Spanned by First {r} Rows of:\n',b[0])
a_nullspace=a.transpose().nullspace()
print('Nullspace of A is Generated by the Columns of:',a_nullspace)
lhs= r+len(a_nullspace)
rhs=dim_v
print('Rank of A: ',rhs)
print('Nullity of A:',len(a_nullspace))
print('Dimension of the Domain of T is',dim_v)
if lhs==rhs:
print("18MEC24006-DENNY JOHNSON P")
print('Rank and Nullity Theorem is Verified')
else:
print("18MEC24006-DENNY JOHNSON P")
print('Rank and Nullity Theorem is Not Verified') |
8c86875cdd88d2d0382b1e13d2102f7d7c4f7035 | jellythewobbly/mars-rover-py | /mars_rover.py | 921 | 3.6875 | 4 | class Marsrover:
def __init__(self, xcoor, ycoor, facing):
self.x = xcoor
self.y = ycoor
self.facing = facing
def return_coordinates(self):
return [self.x, self.y, self.facing]
def movement(self, commands):
for i in commands:
if (i == 'f'):
self.move_forward()
elif (i == 'b'):
self.move_backward()
def move_forward(self):
if self.facing == 'N':
self.y += 1
elif self.facing == 'S':
self.y -= 1
elif self.facing == 'E':
self.x += 1
elif self.facing == 'W':
self.x -= 1
def move_backward(self):
if self.facing == 'N':
self.y -= 1
elif self.facing == 'S':
self.y += 1
elif self.facing == 'E':
self.x -= 1
elif self.facing == 'W':
self.x += 1
|
60563127f676d720fd28b3dd5bbe1826aeac6f9a | caelan/TJHSST-Artificial-Intelligence | /Word Ladders/Lab01.py | 528 | 3.546875 | 4 | #Caelan Garrett, 9/10/09, Neighboors
#
wlist=open('words.txt').read().split('\n')[:-1] # emoticon is like chomp
while 1:
ustr=raw_input('String (quit): ')
if ustr == 'quit':
break
neigh = 0
if ustr in wlist:
for word in wlist:
nonmatches = 0
index = 0
for letter in word:
if ustr[index]!= letter:
nonmatches+= 1
if nonmatches>1:
break
index+= 1
if nonmatches==1:
print word
neigh = 1
elif neigh == 0:
print 'No matches'
else:
print 'No, %s is not a word.' % (ustr)
print 'Done!'
|
913dcacb92d06e1a6b5f3578faf55d42b276333f | capital37/Object-Oriented-Python | /basic_inheritance/basic_inheritance.py | 641 | 3.8125 | 4 |
class ContactList(list):
def search(self, name):
'''return all contacts that contain the search value in their name'''
self.matching_contacts = []
for contact in self:
if name in contact.name:
self.matching_contacts.append(contact)
return self.matching_contacts
class Contact:
#all_contacts = []
all_contacts = ContactList()
def __init__(self, name, email):
self.name = name
self.email = email
#Contact.all_contacts.append(self)
self.all_contacts.append(self)
class Supplier(Contact):
def order(self, order):
print("If this were a real system we would send {} order to {}".format(order, self.name))
|
0975de3423366a05312087b3b7a440f7beae0817 | TomTomW/mayaScripts | /scripts_from_school/problem1.py | 4,028 | 3.53125 | 4 | '''Thomas Whitzer 159005085'''
import math
class Point:
def __init__(self, x = 0, y=0):
self.x = x
self.y = y
def translate(self, s, t):
self.x += s
self.y += t
def rotate(self, angle):
x = self.x
angle = math.radians(angle)
self.x = (x * math.cos(angle)) - (self.y * math.sin(angle))
self.y = (x * math.sin(angle)) + (self.y * math.cos(angle))
def distance(self, p):
distance = (self.x - p.x)**2 + (self.y - p.y)**2
distance = math.sqrt(distance)
return distance
def left_of(self, q, r):
return (((r.x * self.y - self.x * r.y) + (q.x * r.y - q.x * self.y) + (q.y * self.x - q.y * r.x)) > 0)
def right_of(self, q, r):
return (((r.x * self.y - self.x * r.y) + (q.x * r.y - q.x * self.y) + (q.y * self.x - q.y * r.x)) < 0)
def __str__(self):
return'({0}, {1})'.format(self.x, self.y)
def __repr__(self):
return str(self)
class SimplePoly:
def __init__(self, *vertices):
self.poly = [v for v in vertices]
self.idx = 0
def translate(self, s, t):
for el in self.poly:
el.translate(s,t)
def rotate(self, angle):
for el in self.poly:
el.rotate(angle)
def __iter__(self):
return self
def __next__(self):
stop = len(self.poly)
if self.idx <= stop:
i = self.poly[self.idx]
self.idx += 1
return i
else:
raise StopIteration
def __len__(self):
return len(self.poly)
def __getitem__(self, i):
if i > len(self.poly) or i < 0:
IndexError
else:
return self.poly[i]
def __str__(self):
return str(self.poly)
def __repr__(self):
x = str(self)
return x
def perimeter(self):
perim = 0
for el in range(len(self.poly) - 1):
if el == len(self.poly):
perim += self.poly[el].distance(self.poly[0])
else:
perim += self.poly[el].distance(self.poly[el + 1])
return perim
class ConvPoly(SimplePoly):
def __init__(self, *vertices):
templist = [v for v in vertices]
for el in range(len(templist)):
if (el + 2) >= len(templist):
if (el+1) >= len(templist):
if templist[el].left_of(templist[0], templist[1]) == False:
Exception ('This is not a Convex Poly')
elif templist[el].left_of(templist[el+1], templist[0]) == False:
Exception ('This is not a Convex Poly')
elif templist[el].left_of(templist[el+1], templist[el+2]) == False:
Exception ('This is not a Convex Poly')
return super().__init__(*vertices)
class EquiTriangle(ConvPoly):
def __init__(self, length):
self.length = length
a = Point(0,0)
b = Point(length, 0)
c = Point((length/2),(length *(math.sqrt(3)/2)))
vertices = [c, a, b]
self.tri = vertices
return super().__init__(c,a,b)
def area(self):
a = self.tri[0].distance(self.tri[1])
A = ((math.sqrt(3)/4) * (a**2))
return A
class Rectangle(ConvPoly):
def __init__(self, length, width):
self.length = length
self.width = width
a = Point(0,0)
b = Point(length,0)
c = Point(length, width)
d = Point(0, width)
vertices = [a,b,c,d]
self.rec = vertices
return super().__init__(a,b,c,d)
def area(self):
a = self.length * self.width
return a
class Square(Rectangle):
def __init__(self, length):
a = Point(0,0)
b = Point(length, 0)
c = Point(length, length)
d = Point(0, length)
vertices = [a,b,c,d]
self.square = vertices
return super().__init__(length, length)
|
70b3aaa3f15d06d070a3490c0de3b9d8a393af8e | capKopper/maps-drupal-import-automaton | /lib/transport.py | 2,181 | 3.59375 | 4 | """AlertTransport class."""
import abc
import smtplib
class AlertTransportInterface(object):
"""Abstract class definition."""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def send(self):
"""Send an alert."""
pass
class AlertTransportMail(AlertTransportInterface):
"""Implementation for a email alert."""
def __init__(self, smtp_host, smtp_port,
smtp_user, smtp_password, smtp_starttls,
sender, recipients, subject, message, headers):
"""
Constructor.
Additionnal RFC 822 headers can be added:
- each headers must be separated with the new line character
"""
self.smtp_host = smtp_host
self.smtp_port = smtp_port
self.smtp_user = smtp_user
self.smtp_password = smtp_password
self.smtp_starttls = smtp_starttls
self.sender = sender
self.recipients = recipients
self.subject = subject
self.message = message
self.additionnal_headers = headers
def _connect(self):
"""Establish the connexion to the SMTP host."""
smtp = smtplib.SMTP(self.smtp_host, self.smtp_port)
smtp.ehlo()
if self.smtp_starttls:
smtp.starttls()
smtp.ehlo()
smtp.login(self.smtp_user, self.smtp_password)
return smtp
def send(self, override_message=None):
"""
Send the message from 'sender' to 'recipients'.
The 'default' email message can be override be 'override_message'.
"""
# create the message in RFC 822 format.
# - this include message headers like subject
msg_rfc822 = ""
msg_rfc822 += "MIME-Version: 1.0" + "\n"
msg_rfc822 += "Subject: " + self.subject + "\n"
msg_rfc822 += "Content-Type: text/plain" + "\n"
msg_rfc822 += self.additionnal_headers + "\n"
if override_message is None:
msg_rfc822 += self.message
else:
msg_rfc822 += override_message
# send the message
smtp = self._connect()
smtp.sendmail(self.sender, self.recipients, msg_rfc822)
smtp.close()
|
112f44cb5083c63580ec76da625f1e21abf73a33 | antdevelopment1/python104 | /guess_the_number_play_again.py | 1,190 | 4.03125 | 4 | import random
random_num = 5 #random.randint(1, 10)
print("I am thinking of a number between 1 and 10. ")
user_input = int(input("Please guess a number? "))
correct_guess = False
limit_guess = 3
while correct_guess == False:
if user_input == random_num:
print("Yay you won!!!")
ask_to_play = input("Would you like to play again? Y/N").lower()
if ask_to_play == "y":
user_input = int(input("Please guess a number? "))
elif ask_to_play == "n":
print("Thanks for playing.")
correct_guess = True
elif user_input != random_num:
limit_guess -= 1
print("No you have %d turns left" % limit_guess)
if limit_guess > 0:
user_input = int(input("Please guess a number? "))
elif limit_guess == 0:
print("Sorry you lost the game!!!")
ask_to_play = input("Would you like to play again? Y/N").lower()
if ask_to_play == "y":
limit_guess = 3
user_input = int(input("Please guess a number? "))
elif ask_to_play == "n":
print("Thanks for playing.")
correct_guess = True |
6e2da1b625ccaecb23a96a65b17dd5990e06cc1d | antdevelopment1/python104 | /multiplication_table.py | 80 | 3.5 | 4 | for number in range(1, 10):
print(number, 'X', number ,'=', number * number) |
8fe2316d8b6417057f965117e532e8ad1166ff31 | elisangelayumi/Jeu-ConnectFour_Console | /connectfour/case.py | 793 | 3.71875 | 4 | class Case:
'''
Classe représentant une case de la grille de jeu.
Une case est consitutée d'un attribut Jeton, initialement None.
Certaines fonctions y sont aussi implémentées pour permettre
un affichage élégant de chacune des cases.
Cette classe vous est fournie, vous n'avez pas à la modifier.
'''
def __init__(self):
self.jeton = None
def mettre_jeton(self, jeton):
self.jeton = jeton
def est_de_couleur(self, couleur):
return self.jeton is not None and self.jeton.couleur == couleur
def obtenir_couleur(self):
return self.jeton.couleur if self.jeton else ""
def surligner(self):
self.jeton.surligner()
def __str__(self):
return str(self.jeton) if self.jeton else ' '
|
529091e9ea0d6a0bf3dca540f4ef487fc118efb5 | MReinhart1/LinkedListPython | /LinkedList.py | 4,020 | 4.1875 | 4 | """
---------------------------------
Assignment 3 "Linked list"
Student Name: Michael Reinhart
Student Number: 20001556
Date Modified : March 17 2017
---------------------------------
"""
import urllib.request
# Reads in a web page and assigns each row to a node in our linked list
def readHtml():
toDoList = None
response = urllib.request.urlopen("http://research.cs.queensu.ca/home/cords2/todo.txt")
html = response.readline()
data = html.decode('utf-8').split()
toDoList = addIn(toDoList, data)
while len(html) != 0:
html = response.readline()
data = html.decode('utf-8').split()
toDoList = addIn(toDoList, data)
# This will 'Delete' the first item in our linked list, which is the empty data set
toDoList = toDoList['next']
return toDoList
# Used for testing purposes, this prints out the contents of the linked list
def printList(aList):
ptr = aList
while ptr != None:
print(ptr['data'], "->", end="")
ptr = ptr['next']
print("None")
# This function adds a new node containing data to the beggining of a linked list and returns the new linked list
def addIn(aList, value):
newNode = {}
newNode["data"] = value
newNode["next"] = aList
return newNode
def addToHead(linkedList, value):
newnode = {}
newnode["data"] = value
# set the next pointer of this new node to the head of the list, linkedList
# newnode is now the head of the list, so we return this node (which is
# connected to the rest of the list
newnode["next"] = linkedList
return newnode
# This 'removes' a task from the to do list and moves it to the did it list
def executeTask(toDo, Task, didIt):
ptr = toDo
while ptr['next'] != None:
if ptr['data'] == None:
print("This is not in the todo list")
break
elif ptr['next']["data"][0:-3] == Task:
# First gets rid of the task from the to do list
didIt, ptr['next'] = addToHead(didIt, ptr['next']['data']), ptr['next']['next']
# After the task is deleted from the to do list, it is added to the DidIt list
# ASK IF I CAN DO IT THIS WAY OR IF I AM NEVER ALOUD TO USE A NEW NODE
return toDo, didIt
# This function will open the command file and run the program appropriately
def Driver():
# Initializing the toDo and didIt lists
toDoList = readHtml()
didItList = None
# This runs through for the first instruction on the command list
response = urllib.request.urlopen("http://research.cs.queensu.ca/home/cords2/driver.txt")
html = response.readline()
data = html.decode('utf-8').split()
if data[0] == 'PrintToDo':
print("Todo list:")
printList(toDoList)
elif data[0] == 'PrintDidIt':
print("Didit list:")
printList(didItList)
elif data[0] == 'ExecuteTask,':
finishedTask = data[1:-1]
toDoList, didItList = executeTask(toDoList, finishedTask, didItList)
elif data[0] == 'AddTask,':
task = data[1:]
toDoList = addIn(toDoList, task)
else:
print("Sorry that's not a valid function")
# After the first command is made, this section of code will carry out the remainder of the commands
while len(html) != 0:
html = response.readline()
data = html.decode('utf-8').split()
if len(html) != 0:
if data[0] == 'PrintToDo':
print("Todo list:")
printList(toDoList)
elif data[0] == 'PrintDidIt':
print("Didit list:")
printList(didItList)
elif data[0] == 'ExecuteTask,':
finishedTask = data[1:-1]
toDoList, didItList = executeTask(toDoList, finishedTask, didItList)
elif data[0] == 'AddTask,':
task = data[1:]
toDoList = addIn(toDoList, task)
else:
print("Sorry that's not a valid function")
Driver()
|
4fc8b327ad4c3c6186bfad23a7ba9ebb6fde6df3 | kylegarrettwilson/Python-Madlib | /reusable-lib/library.py | 4,763 | 4.15625 | 4 | # store user inputs and then encapsulate
# calc check total
# calc overtime total
# calc total hours worked each week on average
# calc some type of bonus
class JobData(object): # this is a data object to hold the items from the form
def __init__(self): # initializing function
self.__name = '' # these are temp holding spots for the items to be entered
self.__hours = 0 # these are temp holding spots for the items to be entered
self.__pay = 0 # these are temp holding spots for the items to be entered
self.__over = 0 # these are temp holding spots for the items to be entered
@property # This is a getter for the private attribute above self.__name
def name(self): #This is the function which can be accessed by name for the setter
return self.__name # this is returning the private attribute above so it can be changed using the setter
@name.setter # This is the setter for the getter titled name
def name(self, n): # This is the function for the setter which passes in "n" and uses that value to set the new value for self.__name
self.__name = n # This is updating the private function above with the new "n" value
@property # This is a getter for the private attribute above self.__over
def over(self): #This is the function which can be accessed by over for the setter
return self.__over # this is returning the private attribute above so it can be changed using the setter
@over.setter # this is the setter for the getter titled over
def over(self, o): # this is a function that passes in "o" as a way of updating the self.__over
if o > 60: # this setter is actually doing more then just setting it to a new value, it is calculating an if else statement
print "You need to talk to an adviser" # if o is greater than 60 then print this
else: # if o is not greater then 60
self.__over = o # the private attribute above is replaced with the value of "o"
@property # I want the hours to be private so it can't be easily messed with, this is a getter
def hours(self): # this is what the new reference name will be for the private hours above
return self.__hours # returning the private attribute above so the setter can update it
@hours.setter # this is the setter for the hours worked for private attribute self.__hours
def hours(self, h): # method for updating using a passed in value for "h"
if h > 40: # cannot work more than 40 hours a week, it would be overtime for extra
print "Any overtime needs be calculated in the overtime field" # change input fields
else: # if h is not greater than 40
self.__hours = h # the new hours setter is updating the private attribute
@property # the pay is private so I set upa getter and a setter
def pay(self): # method for retrieving the private pay amount above
return self.__pay # return the private attribute so it can be updated using setter
@pay.setter # this is the setter for changing the amount paid per hour
def pay(self, p): # passing in "p" as a way of updating the value for self.__pay above
# checking if info is correct
if p > 43: # we do not pay our employees over 43 dollars an hour
print "Invalid Hourly Rate" # prints to console
else: # if p is not greater than 43
self.__pay = p # returned as p
def calc_check(self): # this is a function that calcs the check total depending on pay per hour and hours worked
total = int(self.hours) * int(self.pay) # this is hours worked times by pay for a check total
return str(total) # total returned for the check amount
def over_time(self): # this is a funciton that calcs the overtime pay
num = int(self.over) * (int(self.pay * 2)) # overtime is charged as double pay
return str(num) # return num for overtime amount
def total_time(self): # this is the average amount of hours worked per week
time = (int(self.hours) + int(self.over)) / 4 # hours plus overtime divided by four weeks in a month
return str(time) # return total time
def bonus(self): # bonus calculator
if int(self.over) > 35: # if you work greater than 35 overtime hours then you get a bonus
return str('You have qualified for a bonus!') # return this string to let them know
else:
return str('Keep up the good job!') # return this if lower then 35
|
07976f5fc9d8f5afe905f255e61cb6079eca0631 | SerhiiPodibka/Lv-367.PythonCore | /1012new.py | 732 | 3.515625 | 4 | import pygame
pygame.init()
gameDisplay=pygame.display.set_mode((500,500))
pygame.display.set_caption("my second game")
x=50
y=50
width=40
height=60
vol=5
run=True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys=pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x>vol:
x=x-vol
if keys[pygame.K_RIGHT] and x<500-width-vol:
x=x+vol
if keys[pygame.K_UP] and y>vol:
y=y-vol
if keys[pygame.K_DOWN] and y<500-height-vol:
y=y+vol
gameDisplay.fill((0,0,0))
pygame.draw.rect(gameDisplay,(0,0,255),(x,y,width,height))
pygame.display.update()
pygame.quit() |
2c7f65f1e7816d0e259c17932668172825f560f8 | SerhiiPodibka/Lv-367.PythonCore | /1212classwork.py | 843 | 4 | 4 | class Figure:
def __init__(self, color):
self.color=color
def get_color (self):
return self.color
#print("Color is" color )
def info (self):
print("Figure")
print("Color:"+self.color)
class Rectangle(Figure):
def __init__(self, color,width=100, height=100):
super().__init__(color)
self.width=width
self.height=height
# print(input("Enter side x"))
#print(input("Enter side y"))
def square(self):
return self.width*self.height
def info(self):
print("Rectangle")
print("Color: " + self.color)
print("Width: " + str(self.width))
print("Height: " + str(self.height))
print("Square: " + str(self.square()))
fig1 = Figure("green")
fig1.info()
fig2=Rectangle("red",89,65)
fig2.info()
|
b97a94399afac9b9f793d680ffb01892f041ff25 | arononeill/Python | /Variable_Practice/Dictionary_Methods.py | 1,290 | 4.3125 | 4 | import operator
# Decalring a Dictionary Variable
dictExample = {
"student0" : "Bob",
"student1" : "Lewis",
"student2" : "Paddy",
"student3" : "Steve",
"student4" : "Pete"
}
print "\n\nDictionary method get() Returns the value of the searched key\n"
find = dictExample.get("student0")
print find
print "\n\nDictionary method items() returns view of dictionary's (key, value) pair\n"
view = dictExample.items()
print "\n", view
print "\n\nDictionary method keys() Returns View Object of All Keys\n"
keys = dictExample.keys()
print "\n", keys
print "\n\nDictionary method popitem() Returns the dictionary contents\nminus the top key and value as they have been popped off the stack\n"
dictExample.popitem()
print dictExample
print "\n\nDictionary method pop() removes and returns element having given key, student4\n\n"
dictExample.pop("student4")
print dictExample
print "\n\nDictionary method max() returns largest key\n"
print "max is ", max(dictExample)
print "\nDictionary method min() returns smallest key\n"
print "min is ", min(dictExample)
print "\nDictionary method sorted() returns sorted keys in ascending order\n"
print (sorted(dictExample))
print "\nDictionary method sorted() returns sorted keys in descending order\n"
print (sorted(dictExample, reverse=True)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.