blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
f5db3390483024c448d23539a08648f714547d6a | Mshohid/Python-Misc | /bananarama.py | 220 | 3.796875 | 4 | import random
banana = (random.randint(0,10))
print (int(banana))
if banana >= 5:
print ("bunch is large")
elif banana <5 and banana >0:
print ("bunch is small")
else:
banana == 0
print ("No bananas")
|
a0361f8dcf052c07cc19ebb342338b16359a6153 | daniel-reich/ubiquitous-fiesta | /BuwHwPvt92yw574zB_22.py | 109 | 3.78125 | 4 |
def list_of_multiples (num, length):
m = []
for n in range(1,length+1):
m.append(num*n)
return m
|
4dec737bd6f4f289517800ceb81f1107fb47e4a3 | pusparajvelmurugan/ral | /104.py | 98 | 3.828125 | 4 | s=input("Enter 2 numbers:")
num1=int(s.split(" ")[0])
num2=int(s.split(" ")[1])
print(pow(n1,n2))
|
b3dd8a6c559ce6ff1efa0037fb6de735ed3581e3 | Nikhil483/ADA-lab | /selection_sort.py | 272 | 3.671875 | 4 | #selection sort
def sel_sort(a):
for i in range(0,len(a)-1):
mini = i
for j in range(i+1,len(a)):
if a[j]<a[mini]:
mini = j
a[mini],a[i] = a[i],a[mini]
print(a)
a = [5,4,3,2,1]
sel_sort(a)
|
86f5c9fcba0f68a28d3b489ae4455b223b70e3d1 | valleyceo/code_journal | /1. Problems/j. DP/0. Template/a. Path - Optimal Path - The Pretty Printing Problem.py | 1,326 | 3.921875 | 4 | # The Pretty Printing Problem (need to review)
'''
- Given a set of words to create a paragraph and max line length
- Create a paragraph such that messiness is minimized
- Messiness is measured by sum of number of blanks squared at end of each line
'''
# O(nL) time | O(n) space
def minimum_messiness(words: List[str], line_length: int) -> int:
num_remaining_blanks = line_length - len(words[0])
# min_messiness[i] is the minimum messiness when placing words[0:i + 1].
min_messiness = ([num_remaining_blanks**2] +
[typing.cast(int, float('inf'))] * (len(words) - 1))
for i in range(1, len(words)):
num_remaining_blanks = line_length - len(words[i])
min_messiness[i] = min_messiness[i - 1] + num_remaining_blanks**2
# Try adding words[i - 1], words[i - 2], ...
for j in reversed(range(i)):
num_remaining_blanks -= len(words[j]) + 1
if num_remaining_blanks < 0:
# Not enough space to add more words.
break
first_j_messiness = 0 if j - 1 < 0 else min_messiness[j - 1]
current_line_messiness = num_remaining_blanks**2
min_messiness[i] = min(min_messiness[i],
first_j_messiness + current_line_messiness)
return min_messiness[-1]
|
e2e280168d33d4b04b3ff6b63d10233625b6b1a6 | paulopradella/Introducao-a-Python-DIO | /Aula_4/Aula4_3.py | 278 | 3.734375 | 4 | # #Descobrir se é primo for dentro de for
a = int(input('Entre com um valor'))
for num in range(a + 1):
div = 0
for z in range(1, num + 1):
resto = num % z
#print(z, resto)
if resto == 0:
div += 1
if div == 2:
print(num)
|
6031c1ae9f5eeaab62c5b4eb2aa6706b4c60470d | Jinah-engineer/j-python-practice | /doit_python/chapter02/1-1_string_operator.py | 386 | 3.9375 | 4 | # 문자열 더해서 연결하기 (Concatenation)
head = 'python '
tail = 'is fun!'
print(head + tail)
# 문자열 곱하기
a = 'python'
print(a * 2)
# 문자열 곱하기 응용 --> 프로그램 제목을 출력할 때 이런 형식으로 많이 표기한다
print('=' * 50)
print('my program~!')
print('=' * 50)
# 문자열 길이 구하기
a = 'Life is too short'
print(len(a))
|
5e69c76323df044d373e8f04d0f0761bc3292b52 | rajatthosar/leetcode | /108_sorted_array_to_BST.py | 732 | 3.796875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedArrayToBST(self, nums: list) -> TreeNode:
if not nums:
return
med = len(nums) // 2
root = TreeNode(nums[med])
if med == 0:
root.left = self.sortedArrayToBST(nums[:med])
else:
root.left = self.sortedArrayToBST(nums[:med])
root.right = self.sortedArrayToBST(nums[med + 1:])
return root
if __name__ == '__main__':
nums = [-10, -3, 0, 5, 9, 8]
sol = Solution()
root = sol.sortedArrayToBST(nums)
print(root)
|
c1be493a0e506e3c2113d18cfe3780a63f006ff7 | tinitiate/python-machine-learning | /scatter-plot.py | 1,346 | 3.703125 | 4 | import matplotlib.pyplot as plt
import numpy as np
import scipy, pylab
"""
# Creating a Scatter Plot
# -----------------------
marker=['O','X','^']
plt.scatter( [1,2,3]
,[4,5,6]
,500
,color=['red','green','blue']
,marker)
plt.scatter( [1,2,3,4,5,6,7,8,1,2,2,3]
,[4,5,6,3,4,5,6,7,8,6,8,9]
,20
,cmap=plt.cm.Paired)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.show()
num_of_lines = 3
x = np.arange(10)
y = []
# For each line
for i in range(num_of_lines):
# Adds to y according to y=ix+1 function
y.append(x*i+1)
print(x)
print(y)
"""
# Adding Multiple Sets to a Scatter Plot
# --------------------------------------
plt.scatter( [1,2,3,4,5,6,7,8,1,2,2,3]
,[4,5,6,3,4,5,6,7,8,6,8,9]
,150
,marker="^"
,color="lightblue")
plt.scatter( [1,2,3,4,5,6,7,8,1,2]
,[11,12,11,14,14,13,15,15,16,16]
,75
,marker="^"
,color="violet")
plt.scatter( [1,2,3,4,5,6,7,8,1,2]
,[21,22,21,24,24,23,25,25,26,26]
,200
,marker="^"
,color="pink")
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.show()
|
4c6a59f06913429f9c4615518e726307dab0254d | czhang475/molecool | /molecool/visualize.py | 3,809 | 3.6875 | 4 | """
Module containing functions for visualization of molecules
"""
import numpy as np
import matplotlib.pyplot as plt
from .atom_data import *
def draw_molecule(coordinates, symbols, draw_bonds=None, save_location=None, dpi=300):
"""
Draws a picture of a molecule using matplotlib.
Parameters
----------
coordinates : np.ndarray
The coordinates of each atom in the molecule
symbols : np.ndarray
The string of each atom's elemental symbol
draw_bonds : dictionary
Dictionary of bond distances, with keys as the pair of corresponding atom indices
save_location : str
File path to save the outputted figure
dpi : int
Specify the dots per inch (resolution) of the outputted figure
Returns
-------
ax : matplotlib.axes._subplots.Axes3DSubplot
Matplotlib axes object of the molecule
Examples
--------
>>> coordinates = np.array([[1.0, 2.0, 3.0], [3.0, 2.0, 1.0], [2.0, 3.0, 1.0]])
>>> symbols = np.array(['C', 'C', 'C'])
>>> draw_bonds = build_bond_list(coordinates, max_bond=3.0)
>>> draw_molecule(coordinates, symbols, draw_bond, save_location='molecule.png')
<matplotlib.axes._subplots.Axes3DSubplot object at 0x121f57550>
"""
if len(coordinates) != len(symbols):
raise Exception("Make sure coordinates and symbols reference the same number of atoms")
# Create figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Get colors - based on atom name
colors = []
for atom in symbols:
colors.append(atom_colors[atom])
size = np.array(plt.rcParams['lines.markersize'] ** 2)*200/(len(coordinates))
ax.scatter(coordinates[:,0], coordinates[:,1], coordinates[:,2], marker="o",
edgecolors='k', facecolors=colors, alpha=1, s=size)
# Draw bonds
if draw_bonds:
for atoms, bond_length in draw_bonds.items():
atom1 = atoms[0]
atom2 = atoms[1]
ax.plot(coordinates[[atom1,atom2], 0], coordinates[[atom1,atom2], 1],
coordinates[[atom1,atom2], 2], color='k')
# Save figure
if save_location:
plt.savefig(save_location, dpi=dpi, graph_min=0, graph_max=2)
return ax
def bond_histogram(bond_list, save_location=None, dpi=300, graph_min=0, graph_max=2):
"""
Draws a histogram of bond lengths based on a bond list (output from build_bond_list function)
Parameters
----------
bond_list : dictionary
Dictionary of bond distances, with keys as the pair of corresponding atom indices
save_location : str
File path to save the outputted figure
dpi : int
Specify the dots per inch (resolution) of the outputted figure
graph_min : float
Lower bound of bond lengths shown in the outputted histogram
graph_max : float
Upper bound of bond lengths show in the outputted histogram
Returns
-------
hist : matplotlib.axes._subplots.AxesSubplot
Matplotlib axes object of the histogram
Examples
--------
>>> coordinates = np.array([[1.0, 2.0, 3.0], [3.0, 2.0, 1.0], [2.0, 3.0, 1.0]])
>>> bond_list = build_bond_list(coordinates, max_bond=3.0)
>>> bond_histogram(bond_list, save_location='hist.png', graph_min=0.0, graph_max=4.0)
<matplotlib.axes._subplots.AxesSubplot at 0x11c877a58>
"""
lengths = []
for atoms, bond_length in bond_list.items():
lengths.append(bond_length)
bins = np.linspace(graph_min, graph_max)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlabel('Bond Length (angstrom)')
plt.ylabel('Number of Bonds')
ax.hist(lengths, bins=bins)
# Save figure
if save_location:
plt.savefig(save_location, dpi=dpi)
return ax
|
3bfecdd5b707737218985a13c24bd3f4ae4521b2 | vsamanvita/APS-2020 | /Amicable_pair.py | 475 | 3.609375 | 4 | import math
def getfact(n) :
c = 0
d=[]
for i in range(1,math.floor(math.sqrt(n))+1) :
if n%i == 0 :
if n/i == i :
d.append(i)
else :
d.append(i)
d.append(int(n/i))
return(sum(d)-n)
def amicable(a,b):
return((getfact(a)==b) & (getfact(b)==a))
x=220
y=284
res=amicable(x,y)
if res:
print("Amicable Pairs")
else:
print("Non Amicable Pairs") |
d6085813aae65d87ff8ae0e33ab801e856a180ba | johnakitto/project_euler | /euler_004.py | 287 | 3.515625 | 4 | import time
start_time = time.time()
biggest = 0
for n1 in range(100,1000):
for n2 in range(n1,1000):
x = n1 * n2
if str(x) == str(x)[::-1]:
if x > biggest:
biggest = x
print()
print('solution: '+ str(biggest))
print('runtime: %s sec' % (time.time() - start_time))
print()
|
81c27a304811a75e046d26c78a0f55df28937a70 | JRappaz/Panorama | /notebooks/utils/visualization.py | 2,456 | 3.5 | 4 | import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates
import seaborn as sns
import pandas as pd
def plotTweetPerDay(df, title, rolling_window=1, vertical_line_x=None, vertical_line_label="", col_count="published", interval=2):
# Prettier plotting with seaborn
sns.set(font_scale=1.5, style="whitegrid")
fig, ax = plt.subplots(figsize=(12, 8))
# Compute rolling mean of the count if needed
y = df[col_count].rolling(window=rolling_window).mean()
ax.plot(df['date'],
y,
'-o',
color='purple', marker="")
ax.set(xlabel="Date", ylabel="# Tweets",
title=title)
# Plot the vertical line if needed
if vertical_line_x is not None:
plt.axvline(linewidth=4, color='r', x=vertical_line_x, label=vertical_line_label)
# Format the x axis
ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=interval))
ax.xaxis.set_major_formatter(DateFormatter("%d-%m-%y"))
# Ensure ticks fall once every other week (interval=2)
ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=interval))
plt.legend()
plt.show()
def plotTweetPerDay2Axis(df, y_1_col, y_2_col, x, y_1_label="", y_2_label="", vertical_line_x=None, vertical_line_label=""):
# Prettier plotting with seaborn
sns.set(font_scale=1.5, style="whitegrid")
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(df[x],
df[y_1_col].rolling(window=1).mean(),
'-o',
color='purple', label="medias")
ax.set_ylabel(y_1_label, color='purple')
ax.tick_params(axis='y', labelcolor='purple')
ax.set(xlabel="Date",
title="Number of tweets send by users or medias on Coronavirus per day")
ax2 = ax.twinx()
ax2.plot(df[x],
df[y_2_col].rolling(window=1).mean(),
'-o',
color='blue', label="users")
ax2.set_ylabel(y_2_label, color='blue')
ax2.tick_params(axis='y', labelcolor='blue')
if vertical_line_x is not None:
plt.axvline(linewidth=4, color='r', x=vertical_line_x, label=vertical_line_label)
# Format the x axis
ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=2))
ax.xaxis.set_major_formatter(DateFormatter("%d-%m-%y"))
# Ensure ticks fall once every other week (interval=2)
ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1))
#plt.legend()
plt.show()
|
6b3752fd45300fe40db80b0ba1b8022450ac3af4 | karolisdedele/password_generator | /password_generator.py | 1,435 | 4.09375 | 4 | import random
import string
def pw_generator():
password_length=int(input("How long will your password be? "));
i=0;
password=[];
while (i<password_length):
i+=1;
rand_num_for_if=random.randint(0,100);
if(rand_num_for_if%2==0):
number=random.randint(0,9);
password.append(str(number));
elif(rand_num_for_if%2!=0):
letter=random.choice(string.ascii_letters);
password.append(letter);
listToStr = ' '.join([str(elem) for elem in password])
listToStr=listToStr.replace(' ','');
print(listToStr);
ask_to_save=input("Do you wish to save this password? yes/no ");
if(ask_to_save=='no'):
generate_again=input('Generate again? yes/no ');
if(generate_again=='yes'):
pw_generator();
elif(generate_again=='no'):
print("aight, head");
elif(ask_to_save=='yes'):
which_format=input("In which format would you like to save? Txt ")
pass_for_what=input("Name for what that password is used: ");
if(which_format=='txt'):
Pass_file = open("password_file.txt", "a");
Pass_file.write("Password for "); Pass_file.write(pass_for_what);
Pass_file.write(" : ");
Pass_file.write(listToStr);
Pass_file.close();
print("check file named password_file.txt");
print("To generate a password enter 1.");
print("To get a password from DB enter 2.");
option=int(input("What do you want to do? "));
if(option==1):
pw_generator();
|
8c60f7e892cb5147183a0ba2645a65a226322f05 | Ramanagamani1/Pythoncourse2018 | /unit4tests/factormath.py | 907 | 3.53125 | 4 | def get_hcf(list1,list2):
res=[]
list1.extend(list2)
list1.sort()
for i in range(len(list1)-1):
if list1[i][0] == list1[i + 1][0]:
if list1[i][1] < list1[i + 1][1]:
res.append(list1[i])
return res
def get_lcm(list1,list2):
list1.extend(list2)
list1.sort()
for i in range(len(list1) - 2):
if list1[i][0] == list1[i + 1][0]:
if list1[i][1] < list1[i + 1][1]:
list1.remove(list1[i])
return list1
def multiply(list1,list2):
list1.extend(list2)
list1.sort()
if len(list1) == 1:
return list1
for i in range(len(list1)-3):
if list1[i][0] == list1[i + 1][0]:
x = (list1[i][0], list1[i][1] + list1[i + 1][1])
list1.remove(list1[i])
list1.remove(list1[i])
list1.insert(i, x)
return list1 |
161fc96025d8d227a4e8b51e9c63be26d7552513 | tHeMaskedMan981/coding_practice | /theory/data_structures/trie/prefix_set.py | 1,068 | 3.53125 | 4 | import collections
class Node():
def __init__(self):
self.c = [None]*10
self.end = False
root = Node()
def insert(key):
l = len(key)
p = root
for i in range(l):
index = ord(key[i])-ord('a')
if not p.c[index]:
p.c[index] = Node()
p = p.c[index]
p.end = True
def search (key):
l = len(key)
p = root
for i in range(l):
index = ord(key[i]) - ord('a')
if not p.c[index]:
return False
p = p.c[index]
return p is not None and p.end
def check_prefix (key):
l = len(key)
p = root
for i in range(l):
index = ord(key[i]) - ord('a')
if not p.c[index]:
return False
p = p.c[index]
if p.end:
return True
return p is not None
strings = ["aab", "aac","adfafd", "a", "aacghgh", "aabghgh"]
for s in strings:
# print(s)
if check_prefix(s):
print("BAD SET")
print(s)
exit()
insert(s)
print("GOOD SET") |
4e4cd98efb1d900ccf422339aa54513a22580f9c | RuzhaK/PythonOOP | /SOLID/SudentTaxes.py | 661 | 3.640625 | 4 | from abc import ABC,abstractmethod
class StudentTaxes(ABC):
def __init__(self,name, semester_fee,average_grade):
self.average_grade = average_grade
self.semester_fee = semester_fee
self.name = name
@abstractmethod
def get_discount(self):
pass
# if self.average_grade>=5:
# # return self.semester_fee*0.4
# # elif self.average_grade>=4:
# # return self.semester_fee*0.3
class ExcellentStudent(StudentTaxes):
def get_discount(self):
return self.semester_fee*0.4
class AverageStudent(StudentTaxes):
def get_discount(self):
return self.semester_fee * 0.3 |
30f96056447ecfd52f7e2d7ca7d854a064a9bf28 | rshatkin/python_eightball | /magic8ball_new.py | 337 | 3.546875 | 4 | import random
NO_QUESTION = ""
OUTCOMES = open("outcomes.txt", "r").readlines()
while True:
question = raw_input(
"Ask the magic 8 ball a question: " +
"(type question and press enter or just enter to quit) ")
if question == NO_QUESTION:
break
print OUTCOMES[random.randint(0, len(OUTCOMES)-1)]
|
bf91c775632d433032c33f01d96481ba8ce0ad34 | aguerra/exercises | /dynamic_programming/finonacci.py | 777 | 3.875 | 4 | """
f(0) = 0, f(1) = 1
f(n) = f(n-1) + f(n-2)
"""
from functools import cache
@cache
def memoized(n):
"""Return the nth Fibonacci number.
>>> memoized(0)
0
>>> memoized(1)
1
>>> memoized(2)
1
>>> memoized(5)
5
>>> memoized(9)
34
>>> memoized(17)
1597
"""
if n < 2:
return n
return memoized(n-1) + memoized(n-2)
def bottom_up(n):
"""Return the nth Fibonacci number.
>>> bottom_up(0)
0
>>> bottom_up(1)
1
>>> bottom_up(2)
1
>>> bottom_up(5)
5
>>> bottom_up(9)
34
>>> bottom_up(17)
1597
"""
a, b = 0, 1
for _ in range(n):
a, b = b, a+b
return a
if __name__ == '__main__':
import doctest
doctest.testmod()
|
471580a6943a2febdd9ecb587d6385a91637233a | weak-head/leetcode | /leetcode/p0124_binary_tree_maximum_path_sum.py | 598 | 3.578125 | 4 | import math
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def maxPathSum(root: TreeNode) -> int:
"""
Time: O(n)
Space: O(h)
n - number of nodes
h - max height of the tree
"""
m = -math.inf
def maxp(node):
nonlocal m
if node is None:
return 0
v = node.val
l, r = maxp(node.left), maxp(node.right)
m = max(m, v + l + r, v + l, v + r, v)
return max(v, v + l, v + r)
maxp(root)
return m
|
90c864f595292f9a93b8961f570155ce53ae0524 | EdwardDixon/floods | /floodstats.py | 712 | 3.890625 | 4 | #!/usr/bin/python
import pandas as pd
mydf = pd.read_csv('data/number-of-severe-floods-in.csv', names = ["Year", "Severity"], skiprows=1)
print("Dataframe content:")
print(mydf)
print("Select minimum value row:")
min = mydf['Severity'].min()
min_df = mydf.loc[mydf['Severity'] == min ]
print(min_df)
print("Select maximum value row")
max = mydf['Severity'].max()
max_df = mydf.loc[mydf['Severity'] == max]
print(max_df)
severity = mydf["Severity"].mean()
print("Flood severity mean: " + str( severity))
print("With greather than severity mean: ")
mydf["Gts"] = mydf["Severity"] > severity
print(mydf)
print("Data with greather than severity mean \"True\"")
gts_mydf = mydf[mydf['Gts']]
print(gts_mydf)
|
5a43fa12fb9f8a0fce81e60f130f57035d04e11b | lernerbruno/python-trainning-itc | /Pycharm and debuging/encrypt_for_decrypt_1.py | 406 | 3.703125 | 4 | """
Encryptor for the decrypt_1 exercise
Author: Omer Rosenbaum
"""
from random import randint
MY_SECRET = "I used something else..."
def encrypt(string):
encrypted = ""
for character in string:
offset = randint(0, 9)
encrypted += str(offset)
encrypted += chr(ord(character)+offset)
return encrypted
if __name__ == '__main__':
print(encrypt(MY_SECRET))
|
695355269bae1334c7370ee5b99c7d67aa1fc42b | ShanYouGuan/python | /Algorithm/bubble_sort.py | 286 | 4.125 | 4 | def bubble_sort(list):
for i in range(0, len(list)):
for j in range(len(list)-i-1):
if list[j] > list[j+1]:
list[j], list[j+1] = list[j+1], list[j]
lista = [1, 3, 6, 5, 4, 2]
bubble_sort(lista)
for i in range(0, len(lista)):
print(lista[i]) |
95e7968efdc592dd82766198ec2372d2d7bff212 | Nagendra-NR/HackerRank_Python | /Collections/Counter.py | 623 | 3.515625 | 4 | from collections import Counter
earning = 0
#First line = X = number of shoes
X = int(input())
#Second line = list of all shoe size in shop
shoe_size_list = list(map(int, input().split()))
shoe_size_count = dict(Counter(shoe_size_list))
#print (shoe_size_count)
#third line = N = number of customers
N = int(input())
#next N lines = shoesize, prize
for i in range(N):
size, price = map(int, input().split())
if size in shoe_size_count and shoe_size_count[size] > 0:
#print(str(size) + " is pesent with price" + str(price) )
earning += price
shoe_size_count[size] -= 1
print(earning)
|
7a6b240cf7b97ed04685ce9b86910d3ee79c24c7 | PullBack993/Python-OOP | /6.Polymorphism - Lab/2.Instruments.py | 494 | 3.96875 | 4 | # class Guitar:
# def play(self):
# print("playing the guitar")
#
# def play_instrument(instrument):
# return instrument.play()
#
# guitar = Guitar()
# play_instrument(guitar)
from abc import ABC, abstractmethod
class Instrument(ABC):
@abstractmethod
def play(self):
pass
def play_instrument(instrument: Instrument):
return instrument.play()
class Piano:
def play(self):
print("playing the piano")
piano = Piano()
play_instrument(piano)
|
60506356d9c2afd1b97cf8cbfefb884e5bcc371b | Beishenalievv/python-week-sets_2020 | /3/slash_figure.py | 456 | 3.875 | 4 | h = 22
s = '\\'
m = 0
s1 = '/'
m1 = 0
for _ in range(6):
print(s * m, end='')
m += 2
for _ in range(h):
print("!", end='')
print(s1 * m1, end='')
m1 += 2
print('')
h -= 4
h = 22
s = '\\'
m = 0
s1 = '/'
m1 = 0
for _ in range(6):
print(s * m, end='')
m += 2
for _ in range(h):
print("!", end='')
print(s1 * m1, end='')
m1 += 2
print('')
h -= 4
|
e5b43f3a7a837869c5805787002a38385ee89308 | oussamafilani/Python-Projects | /list_nombres_premiers.py | 240 | 3.671875 | 4 | n = int(input("entre un nombre "))
for i in range(2, n) :
premier = True
for j in range(2, i) :
if i % j == 0 :
premier = False
break
if premier:
print(i)
|
87c28d3d584fd70dc995d4a4958da77b3bd6e9ff | ProgFuncionalReactivaoct19-feb20/clase02-Shomira | /Ejercicios/ejemplo4.py | 394 | 3.96875 | 4 | #Ejemplo y ussus del lambda
#Cada elemento de datos, tiene(edad, estatura)
datos = ((30, 1.79), (25, 1.60), (35, 1.68))
#Funcion anonima Lambdab que recoge la posicion 2
dato = lambda x: x[2]
#Funcion anonima Lambdab que recoge la posicion 0
edad = lambda x: x[1] *100
'''
Envio de parametros a las funciones
realiza elanalisis y resolución de dentro hacia fuera
'''
print (edad(dato(datos))) |
1ad74249d657b1a98c9aa4b55b0efd5569603c9f | friessm/math-puzzles | /p0010.py | 966 | 3.765625 | 4 | """
Solution to Project Euler problem 10
https://projecteuler.net/problem=10
"""
def sieve_of_eratosthenes(number):
"""
Sieve of Eratosthenes
Return the sum of all prime numbers from 2 to number.
Standard implementation of Sieve with some optimisations.
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""
# Create list from 0 to number
sieve_list = [True for x in range(0, number+1)]
# Remove multiples of 2
for i in range(4, number+1, 2):
sieve_list[i] = False
# Iterate over the odd numbers
for i in range(3, number+1, 2):
if sieve_list[i] == True:
# i is prime and odd. Use i+i to only iterate over odd
# multiples of i.
for j in range(i*i, number+1, i+i):
sieve_list[j] = False
return sum([i for i in range(2, number+1) if sieve_list[i] == True])
if __name__ == '__main__':
print(sieve_of_eratosthenes(2000000)) |
c784c74ddd750cc8ba50a077e1f8dea84691b6d2 | vltian/some_example_repo | /lesson_3_func/hw_34.py | 711 | 3.984375 | 4 | """4.
Программа принимает действительное положительное число x и целое отрицательное число y.
Необходимо выполнить возведение числа x в степень y.
Задание необходимо реализовать в виде функции my_func(x, y).
При решении задания необходимо обойтись без встроенной функции возведения числа в степень.
"""
def my_func(x, y):
if y > 0:
return my_func(x, y-1) * x
elif y < 0:
return 1 / (x*my_func(x,-y-1))
else:
return 1
print(my_func(125,-4)) |
49293a74b1b01fdce9183dbf36f15c753d5c92d6 | jashby360/Python-Playground | /PythonEx2/ch5.20.py | 580 | 3.75 | 4 | print("Patter A")
for i in range(1, 7):
for j in range(1, i + 1):
print(j, end=" ")
print()
print("\nPatter B")
for i in range(6, 0, -1):
for j in range(1, i + 1):
print(j, end=" ")
print()
print("\nPatter C")
for i in range(1, 7):
num = 1
for j in range(6, 0, -1):
if j > i:
print(" ", end=" ")
else:
print(num, end=" ")
num += 1
print()
print("\nPatter D")
for i in range(6, 0, -1):
for j in range(1, i + 1):
print(j, end=" ")
print()
|
4427195e4cf1aff71fb33206cce1af7c86497943 | Fernando-Psy/geekUniversity | /secao4/10-km_para_metros.py | 330 | 4.03125 | 4 | while True:
try:
km = float(input('Digite a velocidade (Km/h): '))
m = km / 3.6 #formula de conversão
except ValueError:
print('Digite apenas valores númericos...')
else:
print(f'Quilômetro/hora: {km} km/h')
print(f'O mesmo em metros por segundo: {m:.2f} m/s')
break
|
2bdeb07f4ad64c682c35dda4b5de9b0846f72bfe | ljragel/Learning-to-program-with-Python | /store_names_and_dates of births.py | 922 | 4.15625 | 4 | """
Crea un programa que sea capaz de guardar los nombres de tus amigos y sus años de nacimiento.
"""
#Hay algún tipo de bug qye hace que la primera persona no funcione toma el valor del dato de la segunda persona
works = False
data = dict()
while not works:
user_action = input("¿Qué deseas hacer? [Añadir fechas [A] / Consultar fechas [C] / Salir [S]: ").upper()
#Add
if user_action == "A":
print("Añadir fechas")
print("----------------------------")
name = input("Nombre: ")
date = input("Fecha: ")
data[name] = date
print("¡Datos guardados correctamente!")
#Search
elif user_action == "C":
print("Consultar fechas")
print("----------------------------")
question = input("¿De quién quieres saber la fecha de nacimiento?")
print(data[name])
#Exit
elif user_action == "S":
works = True
|
d2855098e3552080412f6d0cdeba4c17c2ad76a0 | arunatuoh/assignment-code | /factorial_of_no.py | 144 | 4 | 4 | def factorial_of_no(n):
if (n == 1 or n == 0):
print(1)
else:
n=int(input("enter a number:"))
factorial_of_no(n) |
01076f5e926d04df688fbc91a433fb676adff806 | qiuyuguo/bioinfo_toolbox | /coursework/online_judge_practice/lintcode/validate-binary-search-tree/non-recursive version.py | 962 | 4 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: True if the binary tree is BST, or false
"""
def isValidBST(self, root):
# write your code here
#use in-order traversal
#gives serialized BST in ascending order
toVisit = [root]
s = [] #s stands for serialization
seen = {}
while toVisit:
cur = toVisit.pop()
if cur is None:
continue
if cur in seen and seen[cur] == True:
s.append(cur.val)
else:
toVisit.append(cur.right)
toVisit.append(cur)
toVisit.append(cur.left)
seen[cur] = True
if len(s) > 1 and s[-1] <= s[-2]:
return(False)
return(True)
|
88e6eb03eb1716384b8da4697bfac89ddf2b0ddd | Jackroll/aprendendopython | /exercicios_udemy/Orientacao_Objetos/agregacao/classes.py | 1,158 | 3.984375 | 4 | #Agregação
#Class CarrinhoDeCompras existe serm a classe Produto, mas precisa da classe produto para funcionar perfeitamente
class CarrinhoDeCompras:
def __init__(self):
self.produtos = []
#Insere um produto que já esta cadastrado na classe Produto
def inserir_produto(self, produto):
self.produtos.append(produto)
#Lista os produtos após inseridos na lista
def lista_produtos(self):
i = 0
for produto in self.produtos:
i += 1
print(i, produto.nome, produto.valor)
print(f'Produtos no carrinho : {float(len(self.produtos))} unidades')
#Faz a soma após os produtos inseridos na lista
def soma_total(self):
total = 0
for produto in self.produtos:
total += produto.valor
print (f'Valor Total R$ {total}')
#Class Produto, independente de outras classes, mas outras classes dependem dela para funcionar
#Responsável por cadastrar o produto com os valor
#Sem a classe Produto, a classe CarrinhoDeCompras não funciona
class Produto:
def __init__(self, nome, valor):
self.nome = nome
self.valor = valor |
fd8f51c528251b27037342270ddd15a916fcab16 | ALSchwalm/sparqllib | /sparqllib/formatter.py | 1,625 | 3.515625 | 4 | import abc
import re
class Formatter:
@abc.abstractmethod
def format(self, query):
''' Should return a human-readable version of the query string
'''
pass
class BasicFormatter(Formatter):
''' Provides a basic default formatting for query strings
This formatter provides only indentation levels and newlines at
open braces.
'''
def __init__(self):
self.indent_str = " "
def format(self, query):
if not isinstance(query, str):
query = query.serialize()
#TODO handle braces inside literals correctly
formatted_query = ""
indent_level = 0
for letter in query:
# newline and reindent on open brace
if letter == "{":
indent_level += 1
formatted_query += "{\n" + self.indent_str*indent_level
# newline and reindent on close brace
elif letter == "}":
indent_level -= 1
formatted_query += "\n" + self.indent_str*indent_level + "}"
# reindent after any newline
elif len(formatted_query) and formatted_query[-1] == '\n':
formatted_query += self.indent_str*indent_level + letter
# otherwise just add the letter
else:
formatted_query += letter
# trim whitespace
formatted_query = re.sub(r'(.)\s+\n', '\g<1>\n', formatted_query, flags=re.MULTILINE)
# remove duplicate newlines
formatted_query = re.sub(r'(\n+)', '\n', formatted_query, flags=re.MULTILINE)
return formatted_query
|
5e3de29a8c0909a5e6f2650893554653feba9b5e | standrewscollege2018/2019-year-13-classwork-padams73 | /functions.py | 298 | 4.34375 | 4 | def is_even(check_number):
""" This function calculates whether a number is even, returning True or False"""
if check_number % 2 == 0:
return True
else:
return False
number = int(input()
if is_even(number)==True:
print("Even")
else:
print("Odd")
|
31d4f52fa1ec86895955a341d239736f0ca269d9 | harshita219/PythonPrograms | /smoothing.py | 1,051 | 4.28125 | 4 | """
The temperature of the air is measured each hour so that after several days a long sequence of values is obtained. This data is required to be more smooth to avoid random jumps in values.
To achieve this, every value is to be substituted by the average of it and its two neighbors. For example, if he have the sequence of 5 values like this:
3 5 6 4 5
- Then the second (i.e. 5) should be substituted by (3 + 5 + 6) / 3 = 4.66666666667,
- the third (i.e. 6) should be substituted by (5 + 6 + 4) / 3 = 5,
- the fourth (i.e. 4) should be substituted by (6 + 4 + 5) / 3 = 5.
- By agreement, the first and the last values will remain unchanged.
"""
num = int(input('Enter number of entries: '))
weather = [0]*num
smoothWeather = [0] * num
weather = input(f'Enter {num} temperatures: ').split()
weather = [int(i) for i in weather]
smoothWeather[0], smoothWeather[num - 1] = weather[0], weather[num - 1]
for i in range(1,num-1):
smoothWeather[i] = (weather[i - 1] + weather[i] + weather[i + 1]) / 3
print('\nSmoothened values: ',smoothWeather) |
7d49b80275ac4e1dc826696d915f0e4fe1aa1669 | zcliang97/toy-social-media | /startClient.py | 4,274 | 3.625 | 4 | from Client import Client
def login(client):
while True:
print 'WELCOME TO SOCIAL MEDIA'
# LOGIN/CREATE USER
print "===== To create user [0]"
print "===== To login to existing user [1]"
action = raw_input()
if action == "0":
firstName = raw_input("Enter first name: ")
lastName = raw_input("Enter last name: ")
middleNames = raw_input("Enter middle name(s): ")
birthday = raw_input("Enter birthday [YYYY-MM-DD]: ")
sex = raw_input("Enter sex [M/F]:")
age = int(raw_input("Enter age: "))
city = raw_input("Enter home city: ")
country = raw_input("Enter home country: ")
job = raw_input("Enter job: ")
currentUser = client.createUser(lastName, firstName, middleNames, birthday, sex, age, city, country, job)
return currentUser
elif action == "1":
print "Enter user id:"
currentUser = int(raw_input())
if currentUser not in client.getPersons():
print "User does not exist"
continue
print "Selected user {personID}".format(personID=currentUser)
return currentUser
else:
print "Please enter correct input [0/1]."
continue
def main(client, currentUser):
while True:
print "===== View new posts [0]"
print "===== View all posts [1]"
print "===== Respond to post [2]"
print "===== React to post [3]"
print "===== Create topic [4]"
print "===== Create subtopic [5]"
print "===== Create friend group [6]"
print "===== Join friend group [7]"
print "===== Create post [8]"
print "===== Add friend [9]"
print "===== Follow topic/subtopic [10]"
print "===== Exit [11]"
action = raw_input()
# ACTIONS
if action == "0":
client.getUnreadRelatedPosts(currentUser)
elif action == "1":
client.getRelatedPosts(currentUser)
elif action == "2":
postID = raw_input("What is the post # you are responding to? \n")
topicID = client.getPostTopic(postID)
body = raw_input("What is your response? \n")
client.respondToPost(currentUser, postID, topicID, body)
elif action == "3":
client.getReactTypes()
postID = raw_input("What post would you like to react to? \n")
reactTypeID = raw_input("What reaction would you like to use? \n")
client.reactToPost(postID, currentUser, reactTypeID)
elif action == "4":
topic = raw_input("What is the topic? \n")
client.createTopic(topic)
elif action == "5":
client.getTopics()
parentTopic = raw_input("What is the parent topic? \n")
subtopic = raw_input("What is the subtopic? \n")
client.createSubtopic(subtopic, parentTopic)
elif action == "6":
groupName = raw_input("What is the group name? \n")
client.createGroup(groupName)
elif action == "7":
client.getGroups()
groupID = raw_input("What is the group #? \n")
client.joinGroup(groupID, currentUser)
elif action == "8":
client.getTopics()
topicID = raw_input("What is the topic id? \n")
body = raw_input("What is the post? \n")
client.createPost(currentUser, topicID, body)
elif action == "9":
client.getPotentialFriends(currentUser)
personID = raw_input("What is the person ID? \n")
client.addFriend(currentUser, personID)
elif action == "10":
client.getTopics()
topicID = raw_input("What is the topic do you want to follow? \n")
client.followTopic(currentUser, topicID)
elif action == "11":
break
else:
print "Please enter an appropriate input."
continue
client = Client()
currentUser = login(client)
main(client, currentUser) |
933edf9c38f2ded226269e851ada79c5e859d7be | krishna9477/pythonExamples | /CountRepeatedCharactersFromAString.py | 437 | 3.875 | 4 | x = input("enter a string:")
dic = {}
for chars in x:
dic[chars] = x.count(chars)
for keys, values in dic.items():
print(keys + " " + str(values))
"""
# Count Repeated Characters From A Given String.
import collections
str1 = 'theeeLLLLL23567744444'
d = collections.defaultdict(int)
for c in str1:
d[c] += 1
for c in sorted(d, key=d.get, reverse=True):
if d[c] > 1:
print('%s %d' % (c, d[c]))
""" |
685f6aed5e002c3d8f7db87072e44b7b8294dc39 | bastoche/adventofcode2017 | /day_2.py | 2,159 | 3.578125 | 4 | def part_one(input):
return sum([max_difference(line) for line in parse(input)])
def max_difference(numbers):
return max(numbers) - min(numbers)
def parse(input):
return [to_number_list(line) for line in input.splitlines()]
def to_number_list(string):
return list(map(int, string.split()))
def part_two(input):
return sum([max_even_division_result(all_pairs(line)) for line in parse(input)])
def max_even_division_result(pairs):
return max([even_division_result(left, right) for left, right in pairs])
def even_division_result(left, right):
smallest = min(left, right)
largest = max(left, right)
if largest % smallest == 0:
return largest // smallest
return 0
def all_pairs(list):
length = len(list)
result = []
for i in range(length):
for j in range(i + 1, length):
result.append((list[i], list[j]))
return result
if __name__ == "__main__":
input = """86 440 233 83 393 420 228 491 159 13 110 135 97 238 92 396
3646 3952 3430 145 1574 2722 3565 125 3303 843 152 1095 3805 134 3873 3024
2150 257 237 2155 1115 150 502 255 1531 894 2309 1982 2418 206 307 2370
1224 343 1039 126 1221 937 136 1185 1194 1312 1217 929 124 1394 1337 168
1695 2288 224 2667 2483 3528 809 263 2364 514 3457 3180 2916 239 212 3017
827 3521 127 92 2328 3315 1179 3240 695 3144 3139 533 132 82 108 854
1522 2136 1252 1049 207 2821 2484 413 2166 1779 162 2154 158 2811 164 2632
95 579 1586 1700 79 1745 1105 89 1896 798 1511 1308 1674 701 60 2066
1210 325 98 56 1486 1668 64 1601 1934 1384 69 1725 992 619 84 167
4620 2358 2195 4312 168 1606 4050 102 2502 138 135 4175 1477 2277 2226 1286
5912 6261 3393 431 6285 3636 4836 180 6158 6270 209 3662 5545 204 6131 230
170 2056 2123 2220 2275 139 461 810 1429 124 1470 2085 141 1533 1831 518
193 281 2976 3009 626 152 1750 1185 3332 715 1861 186 1768 3396 201 3225
492 1179 154 1497 819 2809 2200 2324 157 2688 1518 168 2767 2369 2583 173
286 2076 243 939 399 451 231 2187 2295 453 1206 2468 2183 230 714 681
3111 2857 2312 3230 149 3082 408 1148 2428 134 147 620 128 157 492 2879"""
print(part_one(input))
print(part_two(input))
|
68b8ebe6731f0263e6d97093b18129303a031edc | CQCL/pytket | /examples/python/circuit_generation_example.py | 11,156 | 3.578125 | 4 | # # Circuit generation: tket example
# This notebook will provide a brief introduction to some of the more advanced methods of circuit generation available in `pytket`, including:
# * how to address wires and registers;
# * reading in circuits from QASM and Quipper ASCII files;
# * various types of 'boxes';
# * composition of circuits (both 'horizontally' and 'vertically');
# * use of symbolic gate parameters;
# * representation of classically controlled gates.
# ## Wires, unit IDs and registers
# Let's get started by constructing a circuit with 3 qubits and 2 classical bits:
from pytket.circuit import Circuit
c = Circuit(3, 2)
print(c.qubits)
print(c.bits)
# The qubits have automatically been assigned to a register with name `q` and indices 0, 1 and 2, while the bits have been assigned to a register with name `c` and indices 0 and 1.
#
# We can give these units arbitrary names and indices of arbitrary dimension:
from pytket.circuit import Qubit
new_q1 = Qubit("alpha", 0)
new_q2 = Qubit("beta", 2, 1)
new_q3 = Qubit("gamma", (0, 0, 0))
c.add_qubit(new_q1)
c.add_qubit(new_q2)
c.add_qubit(new_q3)
print(c.qubits)
# We can also add a new register of qubits in one go:
c.add_q_register("delta", 4)
print(c.qubits)
# Similar commands are available for classical bits.
#
# We can add gates to the circuit as follows:
c.CX(0, 1)
# This command appends a CX gate with control `q[0]` and target `q[1]`. Note that the integer arguments are automatically converted to the default unit IDs. For simple circuits it is often easiest to stick to the default register and refer to the qubits by integers. To add gates to our own named units, we simply pass the `Qubit` (or classical `Bit`) as an argument. (We can't mix the two conventions in one command, however.)
c.H(new_q1)
c.CX(Qubit("q", 1), new_q2)
c.Rz(0.5, new_q2)
print(c.get_commands())
# Let's have a look at our circuit:
print(c.get_commands())
# ## Exporting to and importing from standard formats
# We can export a `Circuit` to a file in QASM format. Conversely, if we have such a file we can import it into `pytket`. There are some limitations on the circuits that can be converted: for example, multi-dimensional indices (as in `beta` and `gamma` above) are not allowed.
#
# Here is a simple example:
from pytket.qasm import circuit_from_qasm, circuit_to_qasm
c = Circuit(3, 1)
c.H(0)
c.CX(0, 1)
c.CX(1, 2)
c.Rz(0.25, 2)
c.Measure(2, 0)
qasmfile = "c.qasm"
circuit_to_qasm(c, qasmfile)
with open(qasmfile) as f:
print(f.read())
c1 = circuit_from_qasm(qasmfile)
c == c1
# We can also import files in the Quipper ASCII format:
from pytket.quipper import circuit_from_quipper
quipfile = "c.quip"
with open(quipfile, "w") as f:
f.write(
"""Inputs: 0:Qbit, 1:Qbit
QGate["W"](0,1)
QGate["omega"](1)
QGate["swap"](0,1)
QGate["W"]*(1,0)
Outputs: 0:Qbit, 1:Qbit
"""
)
c = circuit_from_quipper(quipfile)
print(c.get_commands())
# Note that the Quipper gates that are not supported directly in `pytket` (`W` and `omega`) are translated into equivalent sequences of `pytket` gates.
#
# Quipper subroutines are also supported, corresponding to `CircBox` operations in `pytket`:
with open(quipfile, "w") as f:
f.write(
"""Inputs: 0:Qbit, 1:Qbit, 2:Qbit
QGate["H"](0)
Subroutine(x2)["sub", shape "([Q,Q],())"] (2,1) -> (2,1)
QGate["H"](1)
Outputs: 0:Qbit, 1:Qbit, 2:Qbit \n
Subroutine: "sub"
Shape: "([Q,Q],())"
Controllable: no
Inputs: 0:Qbit, 1:Qbit
QGate["Y"](0)
QGate["not"](1) with controls=[+0]
QGate["Z"](1)
Outputs: 0:Qbit, 1:Qbit
"""
)
c = circuit_from_quipper(quipfile)
cmds = c.get_commands()
print(cmds)
# ## Boxes
# The `CircBox` is an example of a `pytket` 'box', which is a reusable encapsulation of a circuit inside another. We can recover the circuit 'inside' the box using the `get_circuit()` method:
boxed_circuit = cmds[1].op.get_circuit()
print(boxed_circuit.get_commands())
# The `CircBox` is the most general type of box, implementing an arbitrary circuit. But `pytket` supports several other useful box types:
# * `Unitary1qBox` (implementing an arbitrary $2 \times 2$ unitary matrix);
# * `Unitary2qBox` (implementing an arbitrary $4 \times 4$ unitary matrix);
# * `ExpBox` (implementing $e^{itA}$ for an arbitrary $4 \times 4$ hermitian matrix $A$ and parameter $t$);
# * `PauliExpBox` (implementing $e^{-\frac{1}{2} i \pi t (\sigma_0 \otimes \sigma_1 \otimes \cdots)}$ for arbitrary Pauli operators $\sigma_i \in \{\mathrm{I}, \mathrm{X}, \mathrm{Y}, \mathrm{Z}\}$ and parameter $t$).
# An example will illustrate how these various box types are added to a circuit:
from math import sqrt
import numpy as np
from pytket.circuit import CircBox, ExpBox, PauliExpBox, Unitary1qBox, Unitary2qBox
from pytket.pauli import Pauli
boxycirc = Circuit(3)
# Add a `CircBox`:
subcirc = Circuit(2)
subcirc.X(0).Y(1).CZ(0, 1)
cbox = CircBox(subcirc)
boxycirc.add_circbox(cbox, args=[Qubit(0), Qubit(1)])
# Add a `Unitary1qBox`:
m1 = np.asarray([[1 / 2, sqrt(3) / 2], [sqrt(3) / 2, -1 / 2]])
m1box = Unitary1qBox(m1)
boxycirc.add_unitary1qbox(m1box, 2)
# Add a `Unitary2qBox`:
m2 = np.asarray([[0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0]])
m2box = Unitary2qBox(m2)
boxycirc.add_unitary2qbox(m2box, 1, 2)
# Add an `ExpBox`:
A = np.asarray(
[[1, 2, 3, 4 + 1j], [2, 0, 1j, -1], [3, -1j, 2, 1j], [4 - 1j, -1, -1j, 1]]
)
ebox = ExpBox(A, 0.5)
boxycirc.add_expbox(ebox, 0, 1)
# Add a `PauliExpBox`:
pbox = PauliExpBox([Pauli.X, Pauli.Z, Pauli.X], 0.75)
boxycirc.add_pauliexpbox(pbox, [0, 1, 2])
print(boxycirc.get_commands())
# The `get_circuit()` method is available for all box types, and returns a `Circuit` object. For example:
print(pbox.get_circuit().get_commands())
# ## Circuit composition
# Circuits can be composed either serially, whereby wires are joined together, or in parallel, using the `append()` command.
#
# For a simple illustration of serial composition, let's create two circuits with compatible set of wires, and append the second to the first:
c = Circuit(2)
c.CX(0, 1)
c1 = Circuit(2)
c1.CZ(1, 0)
c.append(c1)
print(c.get_commands())
# In the above example, there was a one-to-one match between the unit IDs in the two circuits, and they were matched up accordingly. The same applied with named unit IDs:
x, y = Qubit("x"), Qubit("y")
c = Circuit()
c.add_qubit(x)
c.add_qubit(y)
c.CX(x, y)
c1 = Circuit()
c1.add_qubit(x)
c1.add_qubit(y)
c1.CZ(y, x)
c.append(c1)
print(c.get_commands())
# If either circuit contains wires not matching any wires in the other, those are added to the other circuit before composition:
z = Qubit("z")
c1.add_qubit(z)
c1.CY(y, z)
c.append(c1)
print(c.qubits)
print(c.get_commands())
# If the sets of unit IDs for the two circuits are disjoint, then the composition is entirely parallel.
#
# What if we want to serially compose two circuits having different sets of `Qubit`? In that case, we can use the `rename_units()` method on one or other of them to bring them into line. This method takes a dictionary mapping current unit IDs to new one:
c2 = Circuit()
c2.add_q_register("w", 3)
w = [Qubit("w", i) for i in range(3)]
c2.H(w[0]).CX(w[0], w[1]).CRz(0.25, w[1], w[2])
c.rename_units({x: w[0], y: w[1], z: w[2]})
c.append(c2)
print(c.get_commands())
# ## Symbolic parameters
# Many of the gates supported by `pytket` are parametrized by one or more phase parameters, which represent rotations in multiples of $\pi$. For example, $\mathrm{Rz}(\frac{1}{2})$ represents a quarter turn, i.e. a rotation of $\pi/2$, about the Z axis. If we know the values of these parameters we can add the gates directly to our circuit:
c = Circuit(1)
c.Rz(0.5, 0)
# However, we may wish to construct and manipulate circuits containing such parametrized gates without specifying the values. This allows us to do calculations in a general setting, only later substituting values for the parameters.
#
# Thus `pytket` allows us to specify any of the parameters as symbols. All manipulations (such as combination and cancellation of gates) are performed on the symbolic representation:
from sympy import Symbol
a = Symbol("a")
c.Rz(a, 0)
print(c.get_commands())
# When we apply any transformation to this circuit, the symbolic parameter is preserved in the result:
from pytket.transform import Transform
Transform.RemoveRedundancies().apply(c)
print(c.get_commands())
# To substitute values for symbols, we use the `symbol_substitution()` method, supplying a dictionary from symbols to values:
c.symbol_substitution({a: 0.75})
print(c.get_commands())
# We can also substitute symbols for other symbols:
b = Symbol("b")
c = Circuit(1)
c.Rz(a + b, 0)
c.symbol_substitution({b: 2 * a})
print(c.get_commands())
# ## Custom gates
# We can define custom parametrized gates in `pytket` by first setting up a circuit containing symbolic parameters and then converting this to a parametrized operation type:
from pytket.circuit import CustomGateDef
a = Symbol("a")
b = Symbol("b")
setup = Circuit(3)
setup.CX(0, 1)
setup.Rz(a + 0.5, 2)
setup.CRz(b, 0, 2)
my_gate = CustomGateDef.define("g", setup, [a, b])
c = Circuit(4)
c.add_custom_gate(my_gate, [0.2, 1.3], [0, 3, 1])
print(c.get_commands())
# Custom gates can also receive symbolic parameters:
x = Symbol("x")
c.add_custom_gate(my_gate, [x, 1.0], [0, 1, 2])
print(c.get_commands())
# ## Decomposing boxes and custom gates
# Having defined a circuit containing custom gates, we may now want to decompose it into elementary gates. The `DecomposeBoxes()` transform allows us to do this:
Transform.DecomposeBoxes().apply(c)
print(c.get_commands())
# The same transform works on circuits composed of arbitrary boxes. Let's try it on a copy of the circuit we built up earlier out of various box types.
c = boxycirc.copy()
Transform.DecomposeBoxes().apply(c)
print(c.get_commands())
# Note that the unitaries have been decomposed into elementary gates.
# ## Classical controls
# Most of the examples above involve only pure quantum gates. However, `pytket` can also represent gates whose operation is conditional on one or more classical inputs.
#
# For example, suppose we want to run the complex circuit `c` we've just constructed, then measure qubits 0 and 1, and finally apply an $\mathrm{Rz}(\frac{1}{2})$ rotation to qubit 2 if and only if the measurements were 0 and 1 respectively.
#
# First, we'll add two classical wires to the circuit to store the measurement results:
from pytket.circuit import Bit
c.add_c_register("m", 2)
m = [Bit("m", i) for i in range(2)]
# Classically conditioned operations depend on all their inputs being 1. Since we want to condition on `m[0]` being 0, we must first apply an X gate to its qubit, and then measure:
q = [Qubit("q", i) for i in range(3)]
c.X(q[0])
c.Measure(q[0], m[0])
c.Measure(q[1], m[1])
# Finally we add the classically conditioned Rz operation, using the `add_gate()` method:
from pytket.circuit import OpType
c.add_gate(OpType.Rz, [0.5], [q[2]], condition_bits=[m[0], m[1]], condition_value=3)
# Note that many of the transforms and compilation passes will not accept circuits that contain classical controls.
|
aafe9a829b0d8898e985e86c33c1850ce0f10855 | TVareka/School-Projects | /CS_162/Project 8- Decorator Functions/sort_timer.py | 2,737 | 4.34375 | 4 | # Author: Ty Vareka
# Date: 5/18/2020
# Description: This program creates a decorator function and then calls bubble count/insertion count within that
# decorator function. The decorator allows us to see how long it takes to run either bubble or insertion count. We
# then have a function that compares those times and plots them on a graph for the user to see.
import time
import random
from matplotlib import pyplot
def sort_timer(func):
'''This decorator function checks the timer when it starts and when it finishes the function. It then
returns the end time minus the start time to determine the total time it took to run the function'''
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
func(*args, **kwargs)
end_time = time.perf_counter()
return (end_time - start_time)
return wrapper
@sort_timer
def bubble_count(a_list):
"""
Sorts a_list in ascending order
"""
exchanges = 0
comparisons = 0
for pass_num in range(len(a_list) - 1):
for index in range(len(a_list) - 1 - pass_num):
comparisons += 1
if a_list[index] > a_list[index + 1]:
temp = a_list[index]
exchanges += 1
a_list[index] = a_list[index + 1]
a_list[index + 1] = temp
return (comparisons, exchanges,)
@sort_timer
def insertion_count(a_list):
"""
Sorts a_list in ascending order
"""
exchanges = 0
comparisons = 0
for index in range(1, len(a_list)):
value = a_list[index]
pos = index - 1
while pos >= 0 and a_list[pos] > value:
a_list[pos + 1] = a_list[pos]
pos -= 1
exchanges += 1
comparisons += 1
a_list[pos + 1] = value
if pos >= 0:
comparisons += 1
return (comparisons, exchanges,)
def compare_sorts(func_1, func_2):
'''This function compares the bubble count and insertion count functions in terms of how long it takes to run.
It then plots those points on a graph for the user to see'''
bubble_time = []
insert_time = []
for val in range(1000, 10001, 1000):
list_1 = []
for i in range(val):
list_1.append(random.randint(1, 10000))
list_2 = list(list_1)
bubble_time.append(func_1(list_1))
insert_time.append(func_2(list_2))
x_list = [num for num in range(1000, 10001, 1000)]
pyplot.plot(x_list, bubble_time, 'ro--', linewidth=2)
pyplot.plot(x_list, insert_time, 'go--', linewidth=2)
pyplot.show()
if __name__ == '__main__':
compare_sorts(bubble_count, insertion_count)
|
b8823df15aace81d2910453dd39aa5a3e47cfbea | MRosenst/MyProjectEuler | /pe14.py | 512 | 3.8125 | 4 | def collatz(n):
count = 1
while n != 1:
if n % 2 == 0:
n /= 2
else:
n = n * 3 + 1
count += 1
return count
def main():
largestCount = 0
largestNum = 0
for n in range(1000000, 1, -1):
count = collatz(n)
if count > largestCount:
largestCount = count
largestNum = n
print(str(n) + ':\t' + str(count))
print(largestNum)
print(largestCount)
if __name__ == '__main__':
main()
|
4f3f90017e6a637a040a09ef2560bd24bbc0de08 | samwestwood/advent-of-code | /2016-python/1.py | 912 | 3.546875 | 4 | #!/usr/bin/env python3
"""
Advent of Code 2016 solution - part 1
"""
import os.path
DIR_NAME = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
FILE_NAME = open(DIR_NAME + "/2016-inputs/1.txt")
FILE_LINE = FILE_NAME.readline()
DATA = [str.strip(x) for x in FILE_LINE.split(',')]
def solve(data):
"""Returns the final position"""
bearing = 0 # 0 = N, 1 = E, 2 = S, 3 = W
pos_x = 0
pos_y = 0
for direction in data:
distance = int(direction[1:])
if direction[0] == 'R':
bearing = (bearing + 1) % 4
elif direction[0] == 'L':
bearing = (bearing - 1) % 4
if bearing is 0:
pos_y += distance
if bearing is 1:
pos_x += distance
if bearing is 2:
pos_y -= distance
if bearing is 3:
pos_x -= distance
return abs(pos_x) + abs(pos_y)
print(solve(DATA))
|
e25443f6bb23b3cb39630f9160ab38a2b0a0055e | DrZaius62/LearningProgramming | /Python/Scripts/countCharacters.py | 546 | 4.15625 | 4 | #this is a file to count the number of characters in a string
#using the method dictionary.setdefault()
import pprint
message = 'It was a bright cold day in April, an the clocks were striking thirteen.'
count = {}#creates the empty dictioanry count
for character in message:
count.setdefault(character, 0)#adds each new character to the dictionary as a key with value zero
count[character] = count[character] + 1#if a character is already in the dict, the value is aumented by 1, indexing with the character itself
pprint.pprint(count) |
4cf7d99a87c99f55ea5dd565043f6d3c6ad7aac9 | Pavel-Kravchenko/Python-scripts-for-everything | /HW/Kravchenko_pr7_hello.py | 136 | 3.796875 | 4 | a = "What is your name?"
print a
inp = raw_input("Write your name and press Enter")
b = str(inp)
c = "Hello,"
d = "!"
print c, b,d |
66ee6533b021b4567f9a772bbbb11843278a30dd | intmod/learn_tensorflow_by_MNIST | /mnist-1_0-fullconn-1layer.py | 3,301 | 3.5 | 4 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# https://www.tensorflow.org/get_started/mnist/beginners
# https://codelabs.developers.google.com/codelabs/cloud-tensorflow-mnist/
#
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
tf.set_random_seed(0)
# data
mnist = read_data_sets("../MNIST-data/", one_hot=True)
print("MNIST data ready for analysis!\n") # get data ready
batch_size = 100 # how many imgs in each batch?
# model
# neural network with 1 layer of 10 softmax neurons
#
# · · · · · · · · · · (input data, flattened pixels) x [batch, 784]
# \*/*\*/*\*/*\*/*\*/ -- fully connected layer (softmax) W [784, 10] b[10]
# · · · · · · · · y [batch, 10]
#
x = tf.placeholder(tf.float32, [None, 784]) # for inputing imgs, be of batchSize
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b) # model defined here! add b to each line
# softmax(matrix) applies softmax on each line
# softmax(line) exp each value then divides by the norm of the resulting line
y_ = tf.placeholder(tf.float32, [None, 10]) # will be loaded in sess.run()
# loss
# cross-entropy = - sum( Y_i * log(Yi) )
# Y: the computed output vector
# Y_: the desired output vector
# --- note that, y_ and y are not multiplied as matrices
# instead, merely the corresponding elements are multiplied
# so the dim of `y_ * tf.log(y)` is [batch_size, 10]
# reduce_sum works on the 1-th dim (not 0-th), so resulting dim is batchSize
# lastly, reduce_mean works on the batch to get a scalar
#loss = -tf.reduce_mean(tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))*100
# normalized for batches of 100 imgs, to obtain cross-entropy of each img
# only a reduce_mean would also generate the scalar
loss = -tf.reduce_mean(y_ * tf.log(y))*1000 # *100*10
# *10 because "mean" included an unwanted division by 10
# It would be very similar for the Euclidean distance case, as is shown below:
# loss = tf.reduce_mean(tf.reduce_sum(tf.square(y_ - y), reduction_indices=[1]))
train_stepper = tf.train.GradientDescentOptimizer(0.001).minimize(loss)
# initializer
init = tf.global_variables_initializer() # note the version problem
# evaluation
# arg_max : the entry with the highest probability is our prediction
if_prediction_correct = tf.equal(tf.arg_max(y, 1), tf.arg_max(y_, 1)) # T,F,T...
accuracy = tf.reduce_mean(tf.cast(if_prediction_correct, tf.float32)) # 1,0,1...
with tf.Session() as sess:
sess.run(init)
# training
for i in range(10000): # train_step_number
batch_xs, batch_ys = mnist.train.next_batch(batch_size) # load
sess.run(train_stepper, feed_dict={x: batch_xs, y_: batch_ys})
if (i % 1000) == 0: print(i,':\n', sess.run(W), '\n', sess.run(b), '\n')
print("Accuarcy on Test-dataset: ", \
sess.run(accuracy, feed_dict={x:mnist.test.images, y_:mnist.test.labels}))
print("\nDone.") # all done
|
fa210f5a0358dd08b9e23365be85bcbf858790cb | jhn--/sample-python-scripts | /python3/thinkcs-python3/4-functions.py | 271 | 3.734375 | 4 | #! /usr/bin/env python
import turtle
def draw_square(t, sz):
for i in range(4):
t.forward(sz)
t.left(90)
wn = turtle.Screen()
wn.bgcolor("light green")
wn.title("wn blahblahblah whatever")
alex = turtle.Turtle()
draw_square(alex, 50)
wn.mainloop() |
afeb387efef9ca580f613210e5c9040fb76c0e7d | Rwothoromo/hashcode | /2020/slice_practice/slice.py | 1,550 | 3.78125 | 4 | import sys
def knapsack(items, capacity):
selected_pizzas = []
possible_count = 0
for item in items:
if item not in selected_pizzas:
possible_count += item
selected_pizzas.append(item)
if possible_count > capacity:
# print(possible_count, selected_pizzas)
break
len_selected = len(selected_pizzas)
for index in range(len_selected):
if index == 0:
if possible_count - selected_pizzas[0] <= capacity:
return [items.index(i) for i in selected_pizzas[1:]]
elif index < len_selected-1:
if possible_count - selected_pizzas[index] <= capacity:
return [items.index(i) for i in (selected_pizzas[:index] + selected_pizzas[index+1:])]
# if at the last item
else:
return [items.index(i) for i in selected_pizzas[:len_selected-1]]
if __name__ == '__main__':
if len(sys.argv) > 1:
file_location = sys.argv[1].strip()
with open(file_location, 'r') as file:
input_data = file.read()
lines = input_data.split('\n')
_capacity = int(lines[0].split()[0])
_items = [int(item) for item in lines[1].split()]
result = knapsack(_items, _capacity)
result_len = len(result)
result_string = ' '.join(map(str, result))
# print(result_len)
# print(result_string)
output_file = open(sys.argv[2], 'w')
output_file.write("{}\n{}\n".format(result_len, result_string))
|
d679f98babceb7f11c6c7d75947f29757f5a5d68 | ziaurjoy/Python-w3Schools | /Python_Loops/foor_loop.py | 542 | 4.125 | 4 | fruits = ["apple", "banana", "cherry"]
# for i in fruits:
# print(i)
#
# country = "Bangladesh"
# for i in country:
# print(i)
# break statement
fruits = ["apple", "banana", "cherry"]
for i in fruits:
if i == "banana":
break
else:
print(i)
# continue statement
fruits = ["apple", "banana", "cherry"]
for i in fruits:
if i == "banana":
continue
else:
print(i)
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for i in adj:
for j in fruits:
print(i, j) |
85f5c1062e54bed0d4ed0be893101deeaee1ce5b | Runnrairu/record | /ball.py | 621 | 3.625 | 4 | # coding: utf-8
# 自分の得意な言語で
# Let's チャレンジ!!
import math
def o_mod(x,y):
if math.fmod(x,y) <0:
return math.fmod(x,y)+y
else:
return math.fmod(x,y)
a,b,x,y,r,theta,L=[int(i) for i in raw_input().split()]
theta = theta/360.0*2*math.pi
X = L*math.cos(theta)+x-r
Y = L*math.sin(theta)+y-r
a_num = int(math.floor(X/(a-2*r)))
b_num = int(math.floor(Y/(b-2*r)))
if a_num % 2 == 0:
x_out = o_mod(X,a-2*r)+r
else:
x_out = a-(o_mod(X,a-2*r)+r)
if b_num % 2 == 0:
y_out = o_mod(Y,b-2*r)+r
else:
y_out = b-(o_mod(Y,b-2*r)+r)
print str(x_out)+" "+str(y_out)
|
9440d82168abd78397fd503d1cbd452f3cd37c17 | nekapoor7/Python-and-Django | /SANFOUNDRY/Basic Program/Sum Digits.py | 280 | 4.21875 | 4 | """Python Program to Find the Sum of Digits in a Number"""
"""Python Program to Count the Number of Digits in a Number"""
num = int(input())
sum = 0
count = 0
while num > 0:
digits = num % 10
sum = sum + digits
num = num // 10
count += 1
print(sum)
print(count) |
2c43581eec95f3d036b77e12fe7211cf3639831b | Shred18/Notes | /zero to hero python bootcamp/Helpful_Syntaxes.py | 601 | 4.3125 | 4 | #This is the sytax for asking for an input, and if the input
#is incorrect, you will return a statement saying so (using try/except)
def ask_for_int():
while True:
try:
#this is trying the input
result = int(input("Please provide a number: "))
except:
#if the input is incorrect, it defaults to the
#except portion
print("Whoops! That is not a number")
continue
else:
#if the input is correct, it moves to the else portion
print("Yes, thank you")
break
|
1bc3dbad20f4364f367f61b2421e1c30197ff2ae | Tabsdrisbidmamul/PythonBasic | /Chapter_7_user_inputs_and_while_loops/02 restaurant_seating.py | 441 | 4.5 | 4 | # a program that asks the user how many are dining tonight
message = 'How many are dining today? '
# convert the inputted numerical value into a integer
dining_group = abs(int(input(message)))
# a statement to see if the amount wanting to dine is more than 8,
# then print said message, otherwise print this message
if dining_group > 8:
print('You\'ll have to wait for a table')
else:
print('there is a table available to dine at')
|
0a5288fad2549177222ac402f6892a5950eb1b71 | NoroffNIS/Python_Examples | /src/week 1/day 2/debug.py | 216 | 3.9375 | 4 | user_name = input('What is your name? : ')
print('Hello,', user_name, '!')
number_one = input('Type in a number: ')
number_two = input('Type in a number: ')
print('The number is:', number_one, 'and', number_two)
|
aa4533e8ec6a3afa8b4273506db8a79ae27506ec | pavanpandya/Python | /OOP by Telusko/08_Mutlilevel_Inheritance.py | 1,257 | 4.15625 | 4 | # Inheritance = Parent-Child Relationship
'''MULTI-LEVEL INHERITANCE'''
# IN THE EXAMPLE BELOW:
# CLASS A IS SUPER CLASS OR GRAND-PARENT CLASS,
# CLASS B IS SUB CLASS OR CHILD CLASS OF A AND PARENT CLASS OF C,
# CLASS C IS SUB CLASS OR CHILD CLASS OF B.
class A:
def feature1(self):
print("Feature-1 is Working")
def feature2(self):
print("Feature-2 is Working")
# This means that class B is inheriting all the features of class A or we can say B is a Child/Sub Class of A.
class B(A):
def feature3(self):
print("Feature-3 is Working")
def feature4(self):
print("Feature-4 is Working")
# This means that class C is inheriting all the features of class B and A or we can say C is a Child/Sub Class of B.
class C(B):
def feature5(self):
print("Feature-5 is Working")
a1 = A()
a1.feature1()
a1.feature2()
b1 = B()
# Here b1 is able to access all the Functionality of Class A as Class B is child of Class A.
b1.feature1()
b1.feature2()
b1.feature3()
b1.feature4()
c1 = C()
# Here c1 is able to access all the Functionality of Class A and Class B as Class C is child of Class B and Class B is child of Class A.
c1.feature1()
c1.feature2()
c1.feature3()
c1.feature4()
c1.feature5()
|
46323fecf5c03404d61d773ec57cfb6300957eaf | candyer/leetcode | /constructArray.py | 1,260 | 3.65625 | 4 | # https://leetcode.com/problems/beautiful-arrangement-ii/description/
# 667. Beautiful Arrangement II
# Given two integers n and k, you need to construct a list which contains n different positive integers ranging
# from 1 to n and obeys the following requirement:
# Suppose this list is [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|]
# has exactly k distinct integers.
# If there are multiple answers, print any of them.
# Example 1:
# Input: n = 3, k = 1
# Output: [1, 2, 3]
# Explanation: The [1, 2, 3] has three different positive integers ranging from 1 to 3, and the [1, 1] has exactly
# 1 distinct integer: 1.
# Example 2:
# Input: n = 3, k = 2
# Output: [1, 3, 2]
# Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3, and the [2, 1] has exactly
# 2 distinct integers: 1 and 2.
# Note:
# The n and k are in the range 1 <= k < n <= 10^4.
def constructArray(n, k):
"""
:type n: int
:type k: int
:rtype: List[int]
"""
res = range(1, n - k + 1)
last = n - k
tmp = n + 1
for i in range(k):
if i % 2 == 0:
tmp -= 1
res.append(tmp)
else:
last += 1
res.append(last)
return res
print constructArray(10, 9) == [1, 10, 2, 9, 3, 8, 4, 7, 5, 6]
|
5acde7d8537eee221bb0125e03751f5deb28f9b4 | JunaidQureshi05/FAANG-ques-py | /19_validate_binary_search_tree.py | 607 | 3.921875 | 4 | # O(n) Time | O(d) Space Where d is the depth of BST(Binary search tree)
def validate_binary_search_tree_helper(node,min,max):
if node.value >=max or node.value <=min:
return False
if node.left:
if not validate_binary_search_tree(node.left, min, node.value):
return False
if node.right:
if not validate_binary_search_tree(node.right, node.value, max):
return False
return True
def is_valid_bst(root):
if not root:
return True
return validate_binary_search_tree_helper(root, float('-inf'), float('inf')) |
5578c01722dc64115300a3fedfbcbeaab2dd5497 | karuparthijaswanth/python | /game.py | 753 | 4 | 4 | import random
n=str(input("enter your choice :"))
l=["STONE", "PAPER", "SCISSOR"]
m=random.choice(l)
print(m)
if (n=="STONE" and m=="PAPER"):
print("COMPUTER WINS")
elif(n=="STONE" and m=="SCISSOR"):
print("YOU WINS")
elif(n=="STONE"and m=="STONE"):
print("MATCH DRAW!!!!")
elif(n=="PAPER" and m=="SCISSOR"):
print("COMPUTER WINS")
elif(n=="PAPER"and m=="STONE"):
print("YOU WINS")
elif(n=="PAPER" and m=="PAPER"):
print("MATCH DRAW!!!")
elif(n=="SCISSOR"and m=="STONE"):
print("COMPUTER WINS")
elif(n=="SCISSOR" and m=="PAPER"):
print("YOU WINS")
elif(n=="SCISSOR" and m=="SCISSOR"):
print("MATCH DRAW!!!")
else:
print("GAME OVER")
|
a7d45e0f44b5e8e956cfbf04ddc86d346d668b4e | Johndsalas/decoding_activity | /group2.py | 326 | 3.5625 | 4 | def multiply_letters_decryption(message, multiplier = 5):
count = 0
new_message =''
for letter in message:
if letter.isalpha():
count += 1
if count % multiplier == 0:
new_message += letter
else:
new_message += ' '
return new_message |
6ace89cd4aa4db6d65f2953269ffa5df501d9181 | XiangHuang-LMC/ijava-binder | /CSC276/book/ch04-OOP-code/ABA_OOP_A.py | 615 | 4.15625 | 4 | #ABA_OOP_A.py: very simple object-oriented design example.
# Entry and non-persistent storage of name.
def addressBook():
aba = ABA_OOP_A()
aba.go()
class ABA_OOP_A:
def go(self):
book = []
name = input("Enter contact name ('exit' to quit): ")
while name != "exit":
book.append(name)
name = input("Enter contact name ('exit' to quit): ")
print()
print("TEST: Display contents of address book")
print("TEST: The address book contains the following contacts")
for name in book:
print(name)
|
d158efb52c1d979489aad3a74ef934d79340346c | saksham715/Hacktoberfest2020 | /multiThreading.py | 645 | 3.96875 | 4 | from time import sleep
from threading import Thread
class Hello(Thread):
def run():
for i in ramge(5):
print("Hello")
sleep(1)
class Hi(Thread)
def run():
for i in range(5):
print("Hi")
sleep(1)
hello = Hello()
hi = Hi()
hello.start()
sleep(0.2)
hi.start()
hello.join()
hi.join()
print("Bye")
print("Bye2")
# MULTI THREADING WITHOUT USING CLASSES
def hello():
for i in range(5):
Print("Hello")
def hi():
for i in range(5):
print("Hi")
t1 = Thread(target= hello)
t2 = Thread(target= hi)
t1.start()
t2.start()
t1.join()
t2.join()
print("Bye")
|
7670e6e3fc6c1ebc6d770ad5088680424e18ea4f | dominicflocco/CSC-121 | /quiz_6.py | 3,581 | 4.125 | 4 |
"""
Solutions to the programming problems from quiz #6.
Author: Dominic Flocco
"""
def simon_says(instructions):
"""
Returns the instructions that would be obeyed in a game of Simon Says.
Parameters:
instructions - a list of strings, where each element is an instruction
issued by Simon.
Returns:
A list of strings, containing the instructions that were obeyed.
"""
obeyed = []
for phrase in instructions:
if "Simon says" == phrase[:10]:
obeyed.append(phrase[11:])
return obeyed
def min_tiles_to_change(room):
"""
Returns the minimal number of tiles that need to be changed to make the
given room as colorful as possible.
The goal is to achieve a tile configuration where no two adjacent tiles are
the same color.
Parameters:
room - a string containing the colors of the tiles in the room. The i^th
character of room (one of 'R', 'G', 'B', or 'Y') is the color of
the i^th tile.
Returns:
The minimum number of tiles that need to be changed so that no two
neighboring tiles are the same color.
"""
tiles = 0
tile_list = []
for char in room:
tile_list.append(char)
len_list = len(tile_list)
middle = 1
for color in tile_list:
if middle <= len(tile_list):
if len(tile_list) % 2 != 0:
if middle < (len(tile_list) - 1):
if tile_list[middle] == tile_list[middle + 1] or tile_list[middle] == tile_list[middle - 1]:
middle += 2
tiles += 1
else:
middle += 1
else:
if middle < (len(tile_list) - 1):
if tile_list[middle] == tile_list[middle + 1] or tile_list[middle] == tile_list[middle - 1]:
middle += 2
tiles += 1
if middle == (len(tile_list) - 1):
if tile_list[middle] == tile_list[middle -1]:
middle += 1
tiles += 1
else:
middle += 1
return tiles
def main():
""" Tester function. """
# Test cases for Simon Says
print("\nTesting Simon Says")
obeyed = simon_says(["Simon says smile", "Clap your hands",
"Simon says jump", "Nod your head"])
print("Test case 1:", obeyed)
obeyed = simon_says(["simon says wave", "Simon say jump",
"Simon says twist and shout"])
print("Test case 2:", obeyed)
obeyed = simon_says(["simon says wave", "simon says jump",
"simon says clap"])
print("Test case 3:", obeyed)
obeyed = simon_says(["Jump", "Simon says wave"])
print("Test case 4:", obeyed)
print()
# feel free to add more test cases for Simon Says here
# Test cases for Colorful Tiles
print("Testing Colorful Tiles")
tiles = min_tiles_to_change("RRRRRR")
print("Test case 1:", tiles)
tiles = min_tiles_to_change("BBBYYYYYY")
print("Test case 2:", tiles)
tiles = min_tiles_to_change("BRYGYBGRYR")
print("Test case 3:", tiles)
tiles = min_tiles_to_change("RBBBYYYR")
print("Test case 1:", tiles)
print()
# feel free to add more test cases for Colorful Tiles here
if __name__ == "__main__":
main()
|
eb145a00ef7828173d55f742d1e0421942267980 | LeoGraciano/python | /ERRO leia float.py | 970 | 3.734375 | 4 | from os import replace
def leiaint(MSG):
while True:
try:
V = int(input(MSG))
except (ValueError, TypeError):
print("\033[31mERRO!! Digite um valor inteiro valido\033[m")
except KeyboardInterrupt:
print("\nUsuário preferiu não digitar o valor")
return ""
else:
return V
def leiafloat(MSG):
while True:
try:
t = str(input(MSG)).replace(",", ".")
V = float(t)
except (ValueError, TypeError):
print("\033[31mERRO!! Esse Dado não é numero Real\033[m")
except KeyboardInterrupt:
print("\nUsuário preferiu não digitar o valor")
return ""
else:
return f"{V:.2f}".replace(".", ",")
i = leiaint("Digite um numero Inteiro: ")
f = leiafloat("Digite um número Real: ")
print(f"Você digitou Numeros: \n\tInteiro: {i}\n\tReal: {f}")
|
649f71472d0c68efd9c46dd3004d073b1649426c | Zahidsqldba07/PythonExamples-1 | /for_loops/descarta2.py | 553 | 3.65625 | 4 | # coding: utf-8
# Aluno: Héricles Emanuel
# Matrícula: 117110647
# Atividade: Descarta coincidente
descartados = []
aceitos = []
qtd_numeros = int(raw_input())
for i in range(qtd_numeros):
descarta = False
num = raw_input()
for n in range(len(num)):
if int(num[n]) == n:
descarta = True
if descarta:
descartados.append(num)
else:
aceitos.append(num)
print "---"
print "%i aceito(s)" % len(aceitos)
for a in range(len(aceitos)):
print aceitos[a]
print "%i descartado(s)" % len(descartados)
for d in range(len(descartados)):
print descartados[d]
|
d86f1ff3a12683b6b76979f53494d9faccfb5c66 | kristjan/turtle | /chaos_triangle.py | 1,146 | 3.828125 | 4 | #!/usr/bin/env python3
import math
import random
import sys
import turtle
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800
TRIANGLE_SIZE = 10
screen = turtle.Screen()
screen.setup(SCREEN_WIDTH + TRIANGLE_SIZE*4, SCREEN_HEIGHT + TRIANGLE_SIZE*4)
t = turtle.Turtle()
def halfway(a, b):
return (
(a[0] + b[0]) / 2,
(a[1] + b[1]) / 2,
)
def random_point():
return (
random.randint(-SCREEN_WIDTH / 2, SCREEN_WIDTH / 2),
random.randint(-SCREEN_HEIGHT / 2, SCREEN_HEIGHT / 2)
)
def triangle(fill = False):
t.pendown()
if fill:
t.begin_fill()
for i in range(3):
t.forward(TRIANGLE_SIZE)
t.right(120)
if fill:
t.end_fill()
t.penup()
def triangle_at(p, fill = False):
t.goto(p[0], p[1])
triangle(fill)
t.speed(0)
t.left(60)
t.penup()
points = [random_point() for i in range(3)]
for p in points:
triangle_at(p, True)
current = random_point()
triangle_at(current)
for i in range(int(sys.argv[1])):
next = random.choice(points)
current = halfway(current, next)
triangle_at(current)
screen.exitonclick()
|
200951dcb80a93c07f7977e6e3ded87a7fd904f1 | AnhellO/DAS_Sistemas | /Ene-Jun-2022/adrian-led-vazquez-herrera/practica_5/P5_2_1.py | 872 | 4.21875 | 4 | #DAS Práctica 5.2.1
from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def num_of_sides(self):
pass
class Triangle(Polygon):
def __init__(self):
self.sides=3
def num_of_sides(self):
return self.sides
class Square(Polygon):
def __init__(self):
self.sides=4
def num_of_sides(self):
return self.sides
class Pentagon(Polygon):
def __init__(self):
self.sides=5
def num_of_sides(self):
return self.sides
class Hexagon(Polygon):
def __init__(self):
self.sides=6
def num_of_sides(self):
return self.sides
T=Triangle()
S=Square()
P=Pentagon()
H=Hexagon()
shapes=[T,S,P,H]
for shape in shapes:
print(shape.num_of_sides())
|
c3a49ba9a3ddfeb78b1c2cb2ef10132a3800d1e6 | edrielleduarte/jogo-senha-porta-magica | /main.py | 1,202 | 3.703125 | 4 | from jogo_porta_magica import saudacoes, novo_jogo, checagem_palpite_user, palpite_em_int
def main():
global resposta_palpite
import numpy as np
saudacoes()
contador = 0
rodadas = 7 # Quantidade de rodadas
segredo_senha = np.random.randint(1, 101, 1)
print(segredo_senha)
while contador < rodadas:
print('Escolha: [1] para jogar ou [0] para sair:')
resposta = int(input('Digita sua escolha:'))
if resposta == 1:
palpite = input('Informe seu palpite entre 1 e 100: ')
palpite = palpite_em_int(palpite)
if palpite is None:
print('iiih amigão, você deve digitar um numero, vamos de novo!')
continue
if 1 <= palpite <= 100:
resposta_palpite = checagem_palpite_user(palpite, segredo_senha)
if resposta_palpite:
novo_jogo()
segredo_senha = np.random.randint(1, 101, 1)
else:
print('Pena que não finalizou o jogo!')
break
contador += 1
else:
print('INFELIZMENTE VOCÊ NÃO CONSEGUIU ACERTAR, FIM DO GAME!')
if __name__ == '__main__':
main()
|
9595ee35f3107ded429592e17972964e95f6b06e | Abhishek-IOT/Data_Structures | /DATA_STRUCTURES/DSA Questions/Strings/wordbreak.py | 899 | 4.1875 | 4 | """
Word Break Problem | DP-32
Difficulty Level : Hard
Last Updated : 02 Sep, 2019
Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details.
This is a famous Google interview question, also being asked by many other companies now a days.
Consider the following dictionary
{ i, like, sam, sung, samsung, mobile, ice,
cream, icecream, man, go, mango}
Input: ilike
Output: Yes
The string can be segmented as "i like".
Logic=
"""
def wordbreak(d,s,out="1"):
if not s:
print(out)
for i in range(1,len(s)+1):
prefix=s[:i]
print("Orefix=",prefix)
if prefix in d:
wordbreak(d,s[i:],out+" "+prefix)
if __name__ == '__main__':
dict = ['i', 'like', 'sam', 'sung', 'samsung']
str = "ilike"
wordbreak(dict,str)
|
c666446d187973b4361711a5e64baddf0ed0d245 | wjzz/dev-notes | /numerical_analysis/exp/calc_e.py | 913 | 3.609375 | 4 | import decimal
import math
from decimal import Decimal
math_e = math.e
# taylor series
#
# e := sum (k = 0 -> inf) [1 / k!]
# we reach the limit of the float type
# after 20 iterations, ie. n_20 = n_21 = n_22 = ...
def taylor_e():
approx = 0
term = 1.0
k = 0
while True:
approx += term
yield approx
k += 1
term /= k
dec_e = Decimal.exp(Decimal(1.0))
## the same, but using the decimal library
## here we get stuck after 26 iterations
def taylor_dec_e():
approx = Decimal(0)
term = Decimal(1)
k = 0
while True:
approx += term
yield approx
diff = abs(approx - dec_e)
digits = math.floor(-Decimal.log10(diff))
print(f"diff after {k} iters = {digits}")
print(approx)
# print(dec_e)
k += 1
term /= k
def take(generator, n):
for _ in zip(generator, range(n)):
pass
|
db027d14b1995a2ab088ae4bbbbec03544d1d800 | JaiJun/Codewar | /7 kyu/Duplicate sandwich.py | 919 | 3.984375 | 4 | """
Task:
In this kata you will be given a list consisting of unique elements except for one thing that appears twice.
Your task is to output a list of everything inbetween both occurrences of this element in the list.
I think best solution:
def duplicate_sandwich(arr):
start, end = [i for i, x in enumerate(arr) if arr.count(x) > 1]
return arr[start+1:end]
https://www.codewars.com/kata/5f8a15c06dbd530016be0c19
"""
def duplicate_sandwich(arr):
print("Orignal>", arr)
start = 0
end = 0
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] == arr[j]:
start = i
end = j
print(arr[start + 1:end])
Result = arr[start + 1:end]
return Result
if __name__ == '__main__':
input = ['None', 'Hello', 'Example', 'hello', 'None', 'Extra']
duplicate_sandwich(input)
|
145b747adc42a57710acadb702f1adae4c2930a8 | RammasEchor/google-code-jam | /solutions/reversort/python/reversort_cost.py | 1,155 | 3.6875 | 4 | class Case:
def __init__(self, list_length, my_list):
self.list_length = list_length
self.my_list = my_list
self.cost = 0
def compute_cost(self):
for i in range(self.list_length-1):
min_idx = self.my_list.index(\
min(self.my_list[i:])) #Obtaining the index with the minimum value
sublist = self.my_list[i:min_idx + 1] #Obtaining the sublist that will be reversed
sublist.reverse()
self.my_list[i:min_idx+1] = sublist #Inserting the reversed sublist in the main list
self.cost += min_idx - i + 1 #Calculating the cost of reversing the sublist
return self.cost
#End class Case
t = int(input()) #Reading the number of test cases
for i in range(1, t + 1):
list_length = int(input()) #Reading the length of the list
my_list = [int(j) for j in input().split()] #Reading the elements of the list
case = Case(list_length, my_list) #Object that solves the problem
print("Case #{}: {}".format(i, case.compute_cost())) #printing the results
|
1825cedf6b5555874a29518ec0aa4decca595115 | nikk7007/Python | /Exercícios-do-Curso-Em-Video/51-100/074.py | 443 | 3.8125 | 4 | from random import randint
numbers = (randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9))
# menor = maior = numbers[0]
# for i in numbers:
# print(i, end=' ')
# if i > maior: maior = i
# elif i < menor : menor = i
# maior = sorted(numbers)[4]
# menor = sorted(numbers)[0]
maior = max(numbers)
menor = min(numbers)
print(numbers)
print(f'\nO maior numero é {maior} e o menor {menor}')
|
e911ef50f4032187cce28661ea5d39a37465e00a | Sajid16/World-of-Python-and-Machine-Learning | /Basic_python_Practice/ifCondition.py | 802 | 4.3125 | 4 | print("Enter the average number:\n")
# taking input here
a = input()
# converting input from string to integer
a = int(a)
a = a+2
# a = 80
if a >= 80:
print('Congratulations!\nYou have got A+')
elif a>=75:
print('Congratulations!\nYou have got A')
elif a >= 70:
print('Congratulations!\nYou have got A-')
elif a >= 65:
print('Congratulations!\nYou have got B+')
elif a >= 60:
print('Congratulations!\nYou have got B-')
else:
print('You have to do better\nBetter luck next time')
name = input("what is your name?\n" )
print("Welcome "+ name +" to the result maintain system")
if name != 'sajid':
print("thank you unknown for being here")
print(len(name))
# if name is "sajid":
# print("thank you sajid for being here")
else:
print("you are unknown to me") |
992c7ad24e7f61d466eb2a9672c4782e24c2c06b | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter9-Objects-and-Classes/P9_21.py | 1,395 | 3.515625 | 4 | # After closing time, the store manager would like to know how much business was
# transacted during the day. Modify the CashRegister class to enable this functionality.
# Supply methods getSalesTotal and getSalesCount to get the total amount of all sales
# and the number of sales. Supply a method resetSales that resets any counters and
# totals so that the next day’s sales start from zero.
class CashRegister():
def __init__(self):
self._items = []
self._sales = []
def add_item(self, item):
self._items.append(item)
def clear(self):
self._sales.append(self._items)
print(self._sales)
self._items[:] = []
def get_sales_count(self):
return len(self._sales)
def get_sales_total(self):
total = 0
for sale in self._sales:
for item in sale:
total += item.get_price()
return total
def reset_sales(self):
self._sales[:] = []
def get_count(self):
return len(self._items)
def get_total(self):
total = 0
for item_object in self._items:
total += item_object.get_price()
return total
def display_items(self):
output = []
for item_object in self._items:
output.append("{} - {}".format(item_object.get_name(), item_object.get_price()))
return "\n".join(output)
|
eb2047aa7d10feeedd14582b29b077085c19a350 | kwahome/udacity-robotics-ai | /particle-filters/moving_robot.py | 710 | 3.890625 | 4 | # Make a robot called myrobot that starts at
# coordinates 30, 50 heading north (pi/2).
# Have your robot turn clockwise by pi/2, move
# 15 m, and sense. Then have it turn clockwise
# by pi/2 again, move 10 m, and sense again.
#
# Your program should print out the result of
# your two sense measurements.
#
# Don't modify the code below. Please enter
# your code at the bottom.
from math import *
import robot
#### DON'T MODIFY ANYTHING ABOVE HERE! ENTER CODE BELOW ####
myrobot = robot.Robot()
# set noise parameters
myrobot.set_noise(5.0, 0.1, 5.0)
myrobot.set(30, 50, pi / 2)
myrobot = myrobot.move(-pi / 2.0, 15.0)
print myrobot.sense()
myrobot = myrobot.move(-pi / 2.0, 10.0)
print myrobot.sense()
|
1cc8e8cac3b792be5c31b1bc5ec5e9a5387ed0f1 | khasherr/SummerOfPython | /RecursionFirstIndexNumber.py | 1,775 | 3.78125 | 4 | #Sher
#This program finds the first occurence of a numver in list
# Test 0 - false 1 - true
# def FirstIndex (arr, number):
# l = len(arr)
# #means if the list is empty
# if l == 0:
# return 0
#if array at 0th index is the number we want t find then return the number
# if arr[0] == number:
# return 1;
#look into the array from 1st index and see if we can find the number
# return FirstIndex(arr[1:],number)
#
# arr = [1,4,6,7,8]
# # number = 2 #none
# number = 4 1
# print(FirstIndex(arr, number))
def firstIndex(arr, x):
# Please add your code here
l = len(arr)
#means if the list is empty
if l == 0:
return -1
if arr[0] == x:
return 0;
smallerList = arr[1:]
smallListCal = firstIndex(smallerList,x)
if smallListCal == -1:
return -1
else:
return smallListCal +1
# Main - this code was given
from sys import setrecursionlimit
setrecursionlimit(11000)
#takes input sizeof(array)
n=int(input())
#splits basis on space
arr=list(int(i) for i in input().strip().split(' '))
#the number we want to find
x=int(input())
print(firstIndex(arr, x))
#How it works:
#step 1: checks if len(list) == 0 if so returns -1 by len(list) == 0 its mean list is empty. So obvious list is empty .
#if not then proceeds to step 2:
#step 2: checks if list[index] == the number we want to find if so returns 0 means that yes we want found the number if not then
#proceed to step 3
#step 3: store the list from index 1 -- n into some variable (1 --n because we did not find the number at index[0]
#so in that smaller list repeat step1 -2 . If found return it and add to each returning call
#if not found then it will poinbt to empty list and return -1 after each returning call
|
498e4cf78103cd8493a2f67c30a887f07113e858 | mashikro/code-challenges | /ll_prac.py | 795 | 4.125 | 4 | # Make a Node class
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return "<Node: {}>".format(self.data)
# Make some instances of Node
apple = Node('apple')
print(apple)
berry = Node('berry')
cherry = Node('cherry')
apple.next=berry
berry.next=cherry
# Make a LL class with the traverse method
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def traverse_list(self):
print('=======')
current = self.head
while current is not None:
print(current.data)
current = current.next
# Make LL instances
fruit_ll = LinkedList()
fruit_ll.head = apple
fruit_ll.tail = cherry
fruit_ll.traverse_list() |
6ea72479a9dd87c7a9041c05eea473165ed5e67d | spencer-mcguire/Algorithms | /eating_cookies/eating_cookies.py | 1,171 | 4.1875 | 4 | #!/usr/bin/python
import sys
# The cache parameter is here for if you want to implement
# a solution that is more efficient than the naive
# recursive solution
def eating_cookies(n, cache=None):
# fib setup fn = f(n-1) + f(n+2)
# __base_case__
# if n = 1 return 1
# if n = 0 return 0
if cache is None:
cache = [0] * (n + 1)
if n <= 1:
cache[n] = 1
elif n == 2:
cache[n] = 2
elif cache[n] == 0:
cache[n] = eating_cookies(
n - 1, cache) + eating_cookies(n - 2, cache) + eating_cookies(n - 3, cache)
return cache[n]
""" if n < 0:
return 0
elif n == 0:
return 1
else:
# I can either either eat 1 - 2 - 3 cookies at a time
return eating_cookies(n - 1) + eating_cookies(n - 2) + eating_cookies(n - 3)"""
# print(n)
print(eating_cookies(10))
if __name__ == "__main__":
if len(sys.argv) > 1:
num_cookies = int(sys.argv[1])
print("There are {ways} ways for Cookie Monster to eat {n} cookies.".format(
ways=eating_cookies(num_cookies), n=num_cookies))
else:
print('Usage: eating_cookies.py [num_cookies]')
|
f139edcf5d24c0824b560d616fbb814f950c5c3b | fjoalland/metaheuristic-project | /fonctions/population.py | 6,047 | 3.578125 | 4 | import csv
import pandas as pd
import random
import parametre as parametre
#**********************************
#******GENERER UNE POPULATION******
#**********************************
def genererPopulation(taille):
#Contiend la liste de tous les individus d'une nouvelle population
nouvellePopulationListe = []
#On boucle sur la taille renseigné en paramètre de la fonction
for x in range(taille):
#On ordonne les capitales au hasard
random.shuffle(parametre.CapitalesList)
#On renseigne comme premiere ville du chemin, la ville de départ
chemin = [parametre.pointDeDepart]
#Nombre de capitales qui peuvent être visité
#On enlève une capitale correspondant à la ville de départ
capitaleVisitable = parametre.capitaleTotal -1
#Boucle sur le nombre de capitales visitables
for x in range(capitaleVisitable):
#Boucle sur la liste des capitales
for index, uneCapitale in enumerate(parametre.CapitalesList):
#Calcul de la distance entre la ville précedente et la ville en cours
distanceVillePrecedenteVilleActuelle = parametre.distanceInterCapitales.loc[chemin[len(chemin)-1], uneCapitale]
#Verification si il nous reste une ville a visiter
if(len(chemin) == len(parametre.CapitalesList) - 1):
#Calcul de la distance entre la ville actuelle et le point de départ / arrivée
distanceVilleActuellePointDepart = parametre.distanceInterCapitales.loc[parametre.pointDeDepart, uneCapitale]
#Verification que la ville actuelle est bien déservie par la ville précedente et le point d'arrivée
if(distanceVillePrecedenteVilleActuelle!= ""
and distanceVilleActuellePointDepart!= ""
and uneCapitale not in chemin):
#ajout de la ville dans le chemin
chemin.append(uneCapitale)
chemin.append(parametre.pointDeDepart)
#Sinon, si ce n'est pas la deriere ville a visiter.
#Verification que le chemin est bien possible
elif (distanceVillePrecedenteVilleActuelle != "" and uneCapitale not in chemin):
chemin.append(uneCapitale)
#Si le chemin est une graphe hamiltonien, on ajoute ce chemin à la nouvelle population.
if(len(chemin) == parametre.capitaleTotal):
nouvellePopulationListe.append(chemin)
return nouvellePopulationListe
#**********************************
#******CROISEMENT DES PARENTS******
#**********************************
def croisement(parent1, parent2, populationParent):
AdnParent1 = populationParent[parent1[1]].copy()
AdnParent2 = populationParent[parent2[1]].copy()
if(parent1[0]>parent2[0]):
#Si le parent1 a un meilleur score que le parent2
#Point de croisement sera entre 1 et le total des capitales -1
pointDeCroisement=random.randint(1,parametre.capitaleTotal-1)
else:
#Si le parent2 a un meilleur score que le parent1
#Point de croisement sera entre 1 et la moitie du totale des capitales
pointDeCroisement=random.randint(1,parametre.capitaleTotal- (parametre.capitaleTotal // 2))
#Coupage de l'ADN du parent 1 avec le point de croisement
croisementAdnPartie1 = AdnParent1[1:pointDeCroisement-1]
#Supression des gênes (capitales) déjà existantes dans l'enfant dans le Parent 2
for index, geneCapital in enumerate(croisementAdnPartie1):
AdnParent2.remove(geneCapital)
#Creation de l'enfant
enfant = AdnParent2[0:len(AdnParent2)-1] + croisementAdnPartie1 + [parametre.pointDeDepart]
#Chance de mutation de l'enfant
mutationChance = random.randint(1,100)
if(mutationChance<parametre.mutationProbabilite):
#Mutation de l'enfant
enfant = mutation(enfant)
return enfant
#**********************************
#***********TOURNOI****************
#**********************************
def tournament(candidat, scoreListParent):
#On atribue comme vainqueur, le candidat au début du tournoi
vainqueur = candidat
#On boucle sur le nombre combattant définie dans les variables globales
for x in range(parametre.combattantParTournoi):
combattant = random.choice(scoreListParent)
#Si le précédent vainqueur perd contre l'actueur combattant
if(vainqueur[0] > combattant[0]):
#Le nouveau vainqueur est l'actuel combattant
vainqueur = combattant
#On retourne le grand vainqueur du tournoi
return vainqueur
#**********************************
#***********SURVIVANT**************
#**********************************
def survivantElite(scoreListParent):
scoreListParent.sort()
survivantTotale = int(len(scoreListParent)*(1*parametre.survivantElitePourcentage/100))
if(survivantTotale == 0):
survivantTotale = 1
survivantListe = scoreListParent[0:survivantTotale]
return survivantListe
#**********************************
#************MUTATION**************
#**********************************
def mutation(individu):
#Point de mutation aléatoire correspondant à un gêne
pointDeMutation1 =random.randint(1,parametre.capitaleTotal-2)
pointDeMutation2 =random.randint(1,parametre.capitaleTotal-2)
#Recupération des deux gênes qui vont être mutés
villeMutation = individu[pointDeMutation1]
villeMutation2 = individu[pointDeMutation2]
#Inversement des deux gênes pour provoquer une mutation
individu[pointDeMutation1] = villeMutation2
individu[pointDeMutation2] = villeMutation
return individu
#******************************************************
#********VERIFIER SI CHEMIN EST HAMILTONIEN************
#******************************************************
def verichierCheminHamiltonien(individu):
estPossible = True
#On boucle sur les capitales de l'individu
for index, geneCapital in enumerate(individu):
#Verification qu'on est pas sur la dernière ville à visiter
if(index != len(parametre.CapitalesList)):
moyenTransport = parametre.distanceInterCapitales.loc[geneCapital,individu[index+1]].split("/")
#Si la taille de la liste des distances inter capitales est 1, le chemin n'est pas possible
#La liste des distances retournent toujours 3 moyens de transports (voiture, avion, bateau)
if(len(moyenTransport) == 1):
estPossible = False
return estPossible
|
6e60b1b7e655d928edbdfd344ff96740e15d1713 | rohitgupta24/leetcode | /sliding_window.py | 402 | 3.59375 | 4 |
def max_sum(arr, k):
size = len(arr)
if size < k :
print("Invalid Operation")
return -1
window_sum = sum([arr[i] for i in range(k)])
max_sum = window_sum
for i in range(size-k):
window_sum = window_sum - arr[i] + arr[i+k]
max_sum = max(window_sum,max_sum)
return max_sum
arr= [80,-50,90,100]
k = 2
answer = max_sum(arr, k)
print(answer) |
f1efb98f221fd4693d1e913f0c95037a1228f002 | marcoscarvalho9/LusofonaPG | /moo_Exercicio 4.py | 736 | 4.21875 | 4 | #!/usr/bin/python3
# coding: utf-8
# Exercício 4
# * Criar um programa que consiga gerar uma password aleatória, com os seguintes parâmetros:
# - Tamanho da password (entre 8 a 32 caracteres, deve pedir input ao utilizador)
# - Uppercase and Lowercase
# - Caracteres especiais
# - Digitos
# Requisitos Exercício 4:
# * O programa deve guardar a password em um ficheiro de texto
# * Deve ser utilizado os módulos random e string
import random
import string
generate_password = input('Prima qualquer tecla para gerar nova password: ')
new_password = ''.join([random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation) for n in range(32)])
print('Nova password gerada: ' + new_password)
|
3bafbd62c535571dc037b99979296c1dafd4496f | FranciscoGMercado/generala | /funciones.py | 378 | 3.765625 | 4 | # 1 el print va dentro del def
# 2 append para pasar los nombres a una lista vacia.
# Funciones.
def jugadores():
j = [] #J por jugadores.
n = int(input('Ingrese el numero de jugadores para esta partida: '))
for i in range(0,n):
jugador = str(input('ingrese el nombre del jugador: '))
j.append(jugador)
for x in j:
print(x)
jugadores()
|
4761367dbc60327f3b3aa447e1270b0926d49807 | inwk6312winter2019/openbookfinal-nayakdrashtant | /task15.py | 724 | 3.546875 | 4 | # Sub task 5 of Task 1
mydict = dict()
def histgram(Book):
fopen = open(Book,"r")
for re in fopen:
re = re.strip()
re = re.split()
if len(re) != 0:
for r in re:
r = r.lower()
if r[:1] == 'a' or r[:1] == 'e' or r[:1] == 'i' or r[:1] == 'o' or r[:1] == 'u':
if r not in mydict:
mydict[r] = 1
else:
mydict[r] += 1
return mydict
def starts_with_vow():
booklist = ["Book1.txt","Book2.txt","Book3.txt"]
for book in booklist:
histgram(book)
return mydict
#var = input("Enter name of book:")
print("output:",starts_with_vow())
# Drashtant Nayak
|
8982b717b4eb1817e64ce6186a7db6736a721b11 | ahnaf-zamil/async-covid | /example.py | 1,786 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""Sample example used for testing purposes
"""
from async_covid import Covid
import asyncio
async def johnhopkinsdata(covid):
print("John Hopkins University data\n\n")
deaths = await covid.get_total_deaths()
confirmed = await covid.get_total_confirmed_cases()
recovered = await covid.get_total_recovered()
print(f"Confirmed: {confirmed:,}")
print(f"Deaths: {deaths:,}")
print(f"Recovered: {recovered:,}")
cases = await covid.get_status_by_country_id(14)
print(f"Bangladesh Cases: {cases}")
cases = await covid.get_status_by_country_name("US")
print(f"USA Cases: {cases}")
async def worldometersdata(covid):
print("\n\nWorldometers data\n\n")
print(await covid.get_data())
deaths = await covid.get_total_deaths()
confirmed = await covid.get_total_confirmed_cases()
recovered = await covid.get_total_recovered()
active = await covid.get_total_active_cases()
print(f"Confirmed: {confirmed:,}")
print(f"Deaths: {deaths:,}")
print(f"Recovered: {recovered:,}")
print(f"Active: {active:,}")
cases = await covid.get_status_by_country_name("Bangladesh")
print(f"Bangladesh Cases: {cases}")
if __name__ == "__main__":
loop = asyncio.get_event_loop()
hopkins = Covid(source="john_hopkins")
loop.run_until_complete(johnhopkinsdata(hopkins))
"""
Warning: Instantiate this(worldometer) object only when necessary, the worldometers source collects
"all" of the data at once when instantiated so it will slow down your code everytime you make an instance
of this object. But it's not an issue with john hopkins source.
"""
worldometer = Covid(source="worldometers")
loop.run_until_complete(worldometersdata(worldometer))
loop.close() |
16bff159d8119a16b112225ee9012fa0a621c7a3 | M1c17/ICS_and_Programming_Using_Python | /Week4_Good_Programming_Practices/Lecture_4/get_stats.py | 888 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 19 18:39:17 2019
@author: MASTER
"""
# assume were given a class list for a subject: each entry is a list of two
# parts
# a list of first and last name for a student
# a list of grades on assigments
# create a new class list, with name,grades, and an average
def get_stats(class_list):
new_stats = []
for elt in class_list:
new_stats.append([elt[0], elt[1], avg(elt[1])])
return new_stats
def avg(grades):
try:
return sum(grades)/len(grades)
except ZeroDivisionError: # when no grade data
print('no grades data') # return None
return 0.00
test_grades = [[['peter', 'parker'], [10.0, 5.0, 85.0]],
[['bruce','wayne'], [10.0, 8.0, 74.0]],
[['captain', 'america'], [8.0, 10.0, 96.0]],
[['deadepool'],[]]]
|
1a3fd6329adff58c2d03aae2922f458873ce5e17 | JuanPuyo1/8_Puzzle_DLS_DFS_BFS | /Busquedas_API.py | 5,511 | 3.8125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
#Busquedas.py Es una API que se podra utilizar en diferentes proyectos que este en la misma ruta de esta
#con el fin de poder acceder a los metodos de construcción de las estructuras de datos usados en las
#busquedas de solución informadas y no informadas
# Definición de la clase Tree (Árbol) para la contruccion de la estructura de un arbol de orden N
class Tree:
def __init__(self, label, state, children=None):
self.label = label
self.state = state
if children is not None:
self.children = children
else:
self.children=[]
def __str__(self):
return (str(self.label)+" "+str(self.state))
# Para la función de recorrido "pre-order" basta procesar el nodo visitado antes de recorrer recursivamente sus hijos, que luego serán procesados
def preorder(self):
if self is None:
return
print(self)
if len(self.children)>0:
for child in self.children:
child.preorder()
return
# Similarmente, el recorrido "post-order" se consigue explorando recursivamente los hijos de cada nodo visitado antes de procesarlo
def postorder(self):
if self is None:
return
if len(self.children)>0:
for child in self.children:
child.postorder()
print(self.label)
return
# El recorrido por niveles es análogo a los métodos en profundidad
def levelorder(self):
visit_queue=[]
visit_queue.append(self)
while (len(visit_queue)>0):
print (visit_queue[0].data)
node=visit_queue.pop(0)
if len(node.children)>0:
for child in node.children:
visit_queue.append(child)
return
# Definiremos la clase (State) para el manejo de estados que es nacesaria en la clase (Tree)
class State:
def __init__(self, parent, cost=0, is_goal=False):
self.parent = parent
self.cost = cost
self.is_goal = is_goal
def __str__(self):
return str(self.cost)+" "+str(self.parent)+" "+str(self.is_goal)
# Definición de la clase StateGraph (Grafo) para construir la estructura de un grafo no dirigido
class StateGraph:
def __init__(self,data=None,node_content=None):
if data is None:
self.data=[]
else:
self.data=data
if node_content is None:
self.node_content=[]
else:
self.node_content=node_content
def getNodes(self):
keys=list(self.data.keys())
node_content=[]
for key in keys:
node_content.append(key)
return node_content
def getEdges(self):
edge_names=[]
for node in self.data:
for next_node in self.data[node]:
if (node,next_node) not in edge_names:
edge_names.append((node, next_node))
return edge_names
def buscarClave(self,data,clave):
claves = data.keys()
a = 0
for i in claves:
if(clave == i):
a = a+1
if(a!=0):
return True
else:
return False
def agregarVertice(self,data,vertice):
if (data == None):
data[vertice] = []
else:
vali = StateGraph.buscarClave(self,data,vertice)
if(vali):
print("El vertice ya esta agregado")
else:
data[vertice] = []
def agregarArista(self,data,clave,vertice,peso):
vali = StateGraph.buscarClave(self,data,clave)
a =0
if(vali == True):
lista = data[clave]
if(len(lista) > 0):
for i in lista:
for j in i:
if(j != vertice):
a = a + 1
lista.append((vertice,peso))
return True
break
else:
lista.append((vertice,peso))
return True
else:
print("No se encuentra la clave")
def conversion(self,conver):
if conver is not None:
conversion = []
for i in conver:
#print(i[1][1])
#print(i[0])
#print(i[1][0])
a = (i[1][1],i[0],i[1][0])
conversion.append(a)
t = set(conversion)
return t
else:
print("No hay contenido en el grafo")
def conversion2(self, vertices, conver):
from pprint import pprint
dic = {}
for i in vertices:
dic[i]={}
print(dic)
#print(i[0]) clave
#print(i[1][1]) peso
#print(i[1][0]) union
for i in conver:
print(i)
print(i[0])
print(i[1][0])
print(i[1][1])
dic[i[0]][i[1][0]]=i[1][1]
print("--------------------------------------------------------------------------")
pprint(dic)
print("*******-------------------------------------------------------------------")
def union(self,vertices,aristas):
dic = {'vertices':vertices,'aristas':aristas}
return dic
|
842b4b0ffe713a4aa1a6c9929ac82fc169a06d4e | goutam1206/DataScienceMasters_Assignment4.1 | /Assignment4.1.py | 1,146 | 3.640625 | 4 | class Shape:
def __init__(self, a,b,c):
self.a = a
self.b = b
self.c = c
self.sides=[]
def setsides(self):
self.sides = [self.a,self.b,self.c]
return self.sides
class Triangle(Shape):
def __init__(self,a,b,c):
Shape.__init__(self,a,b,c)
super(Triangle,self).__init__(a,b,c)
def findArea(self):
# calculate the semi-perimeter
s = (self.a+self.b+self.c)/2
area = (s*(s-self.a)*(s-self.b)*(s-self.c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
t = Triangle(3,4,5)
t.setsides()
t.findArea()
########
myList = ['Here','is','a','function','which','takes','a','list','of','words','and','an','integer','as','arguments','and','returns','all','the','words','whose','length','is','greater','than','the','integer']
limit = 0
while True:
try:
limit = int(input("Enter an integer: "))
break
except:
print ("Please enter an integer value")
mySizeList = [ element for element in myList if len(element) > limit]
print (mySizeList)
|
d19e1b5c7b3e7d8552b972fba628157dbe77f79e | kunzhang1110/COMP9021-Principles-of-Programming | /Labs/Lab_7/test.py | 414 | 3.71875 | 4 | def check_sublist(ls1, ls2):
# sublist ls1 and list ls2
list_1 = ls1.copy()
list_2 = ls2.copy()
for item in list_1:
found = 0
for i in range(len(list_2)):
if item == list_2[i]:
list_2.pop(i)
found = 1
break
if not found:
return False
return True
a = [0, 1, 2]
b = [0, 2]
print(check_sublist(b, a)) |
24b7b94a0bd4a470cf53b3037ace7ad5c7647604 | dieg0varela/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 160 | 3.640625 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
test = []
for i in matrix:
test.append(list(map(lambda x: (x*x), i)))
return (test)
|
59a0441049b9d8a83c3e07ec0bb0c6c25bd6ce55 | Madhumitha-Pragalathan/Code-Kata | /largest.py | 522 | 4 | 4 | import sys
for i in sys.stdin :
num1 = i
break
for i in sys.stdin :
num2 = i
break
for i in sys.stdin :
num3 = i
break
if(num1 > num2) and (num1 > num3) :
num1 = str(num1)
num2 = str(num2)
num3 = str(num3)
print (num1+" is greater than "+num2+" and"+num3)
elif(num2 > num1) and (num2 > num3) :
num1 = str(num1)
num2 = str(num2)
num3 = str(num3)
print (num2+" is greater than "+num1+" and"+num3)
else:
num1 = str(num1)
num2 = str(num2)
num3 = str(num3)
print (num3+" is greater than "+num1+" and"+num2)
|
8cc7d97abdcc2960a0d6d1bc148639586f18ffef | euribates/advent_of_code_2020 | /day01/second.py | 275 | 3.75 | 4 | import itertools
with open("input", "r") as f:
numbers = [int(x.strip()) for x in f.readlines() if x]
for a, b, c in itertools.permutations(numbers, 3):
if a + b + c == 2020:
print(f"{a}+{b}+{c} = {a+b+c}")
print(f"Solution: {a}*{b}*{c} = {a*b*c}")
|
0d5f0f2503e375895622c191f8736695b2e81440 | knee-rel/CSCI-21-Lab2 | /lab2b.py | 956 | 3.828125 | 4 | # Nirel Marie M. Ibarra
# 192468
# March 8, 2021
# I have not discussed the Python language code in my program
# with anyone other than my instructor or the teaching assistants
# assigned to this course
# I have not used Python language code obatained from another student
# or any other unauthorized source, either modified or unmodified
# If any Python language code or documentation used in my program
# was obtained from another source, such as a textbook or website,
# that has clearly noted with a proper ciration in the comments
# of my program
for num in range(0, 100):
grade = int(input())
if 92 <= grade <= 100:
print('A')
elif 87 <= grade <= 91:
print('B+')
elif 83 <= grade <= 86:
print('B')
elif 79 <= grade <= 82:
print('C+')
elif 75 <= grade <= 78:
print('C')
elif 70 <= grade <= 74:
print('D')
elif grade == -1:
break
else:
print('F')
|
546463ceefa55acaeb49c28d61c2dd31ad956534 | nathanpanchal/courses | /6.00/ps01aSC.py | 1,925 | 4.21875 | 4 | # Problem Set 1
# Name: Nathan Panchal
# Collaborators: n/a
# Time Spent:
#
balance = float(raw_input('Enter the outstanding balance on the credit card: '))
annual_rate = float(raw_input('Enter the annual interest rate: '))
min_payment_rate = float(raw_input('What is minimum monthly payment rate: '))
#test case 1
# balance = 4800
# annual_rate = .2
# min_payment_rate = .02
#test case 2
# balance = 4800
# annual_rate = .2
# min_payment_rate = .04
# #code from line 16 to line 27 is more accurate because the rounding is done at the end during the print statements. However this algorithm does not satisfy the answer key.
# month = 1
# for month in range(1, 12+1):
# min_payment = balance * min_payment_rate
# interest_paid = (annual_rate / 12) * balance
# principle_paid = min_payment - interest_paid
# balance = balance - principle_paid
# total_payment += min_payment
# print 'Month: ', month
# print 'Minimum Monthly Payment: %.2f' % min_payment
# print 'Principle Paid: %.2f' % principle_paid
# # print 'Principle Paid:', round(principle_paid, 2) #used to test different types of rounding in python
# # print 'Principle Paid:', principle_paid #kept unrounded answer to to comparte the various types of rounding
# print 'Remaining Balance: %.2f' % balance
# month =+ 1
# print 'RESTULT'
# print 'Total amount paid:', total_payment
# print 'Remaining balance:', balance
month = 1
total_payment = 0
for month in range(1, 12+1):
min_payment = round(balance * min_payment_rate, 2)
interest_paid = (annual_rate / 12) * balance
principle_paid = round(min_payment - interest_paid, 2)
balance = round(balance - principle_paid, 2)
total_payment += min_payment
print 'Month: ', month
print 'Minimum Monthly Payment:', min_payment
print 'Principle Paid:', principle_paid
print 'Remaining Balance:', balance
month =+ 1
print 'RESTULT'
print 'Total amount paid:', total_payment
print 'Remaining balance:', balance |
674470bcac02ee52f3b7fde63a4887ba5b1d0ad8 | Gogka/ANN | /ANNLayer.py | 829 | 3.75 | 4 | from ANNNeuron import *
class ANNLayer():
### Artificial Neural Network Layer ###
# Initializing
# number_of_inputs - amount inputs for each neuron in layer to generic weights
# number_of_neurons - amount neurons in layer
# parent_layer - parent layer if self layer doesn't beginner
def __init__(self, number_of_inputs = None, number_of_neurons = 1, parent_layer = None):
if parent_layer == None:
self.neurons = [ANNNeuron(number_of_inputs) for _ in range(number_of_neurons)]
else:
self.neurons = [ANNNeuron(len(parent_layer.neurons)) for _ in range(number_of_neurons)]
# Method for getting output values from layer
def get_outputs(self, inputs):
self.outputs = [neuron.get_output(inputs) for neuron in self.neurons]
return self.outputs
|
5175bb68508159210dffac3595f9c071bb357fe6 | JoannaEbreso/PythonProgress | /SecondPlot.py | 320 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 26 22:13:26 2020
@author: DELL USA
"""
import math
import pylab
y_values = []
x_values = []
number = 0.0
while number < math.pi * 2:
y_values.append(math.sin(number))
x_values.append(number)
number += 0.1
pylab.plot(x_values,y_values,'ro')
pylab.show()
|
90b66700830719b5dc75ddd90658fc8f495f21ab | sunn-u/CodingTest | /Programmers/Lv1/add_twovalues.py | 537 | 3.546875 | 4 | # 두 개 뽑아서 더하기
def solution(numbers):
answer = []
for front_idx, num_front in enumerate(numbers):
for back_idx, num_back in enumerate(numbers):
if front_idx == back_idx:
continue
tmp = num_front + num_back
answer.append(tmp)
# another solution(best)
# for front_idx, num in enumerate(numbers):
# for back_idx in range(front_idx+1, len(numbers)):
# answer.append(num + numbers[back_idx])
return sorted(list(set(answer)))
|
2bcbe0becc4d80fd963a4e6ff1d143c25caa81a2 | SindhuMuthiah/100daysofcode | /acc3.py | 197 | 3.53125 | 4 | '''se=set()'''
arr=[]
n=int(input())
for i in range(n):
num=input()
arr.append(num)
'''for j in range(n):
se.add(arr[j])'''
se=set(arr)
print(se)
k=len(se)
print(k)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.