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 |
|---|---|---|---|---|---|---|
e30d4dc7efb2b204c93ba1aa5c08e52e7ebf3549 | preetha2711/CipherChecks | /ElGamal/ElGamal_Verify_Existential_Forgery.py | 462 | 3.609375 | 4 | file = open("public_key.txt", 'r')
q = int(file.readline())
g = int(file.readline())
h = int(file.readline())
file.close()
file = open("forged_sign.txt",'r')
r = int(file.readline())
signature = int(file.readline())
file.close()
file = open("plain_text_forgery.txt", 'r')
plain_text_forgery = int(file.readline())
file.close()
g_m = pow(g,plain_text_forgery,q)
rhs = (pow(h,r,q)*pow(r,signature,q))%q
if(g_m == rhs):
print("True")
else:
print("False") |
e6d0b9eeee0bac49285e51228abafad76e7bc259 | SumaDabbiru/DS-and-Algorithms | /AlgoExpert/LongestPalindromicSubstring(1).py | 3,723 | 3.71875 | 4 | # def longestPalindromicSubstring(string):
# """
# did this comparing with longest peak
# return the length of longest palindrom string
# """
# longestlength = 0
# i = 1
#
# while i < len(string) - 1:
# ispeak = string[i - 1] == string[i + 1]
# while not ispeak:
# i += 1
# continue
#
# leftindex = i - 1
# rightindex = i + 1
# while leftindex >= 0 and rightindex <= len(string)-1 and string[leftindex] == string[rightindex]:
# leftindex -= 1
# rightindex +=1
#
#
# currentpeaklength = rightindex - leftindex - 1
#
# longestlength = max(currentpeaklength, longestlength)
# i = rightindex
#
# return string[leftindex+1:rightindex-1]
# pass
def longestPalindromicSubstring(string):
"""
O(n^2) time | O(1) space
Algoexpert
:param string:
:return:
"""
currentLongest = [0,1]
for i in range(1, len(string)):
odd = getlongestPalindromicSubstring(string, i-1, i+1)
even = getlongestPalindromicSubstring(string, i-1, i)
longest = max(odd, even, key=lambda x: x[1] - x[0])
currentLongest = max(longest, currentLongest, key=lambda x: x[1] - x[0])
return string[currentLongest[0] : currentLongest[1]]
def getlongestPalindromicSubstring(string, leftIdx, rightIdx):
while leftIdx >0 and rightIdx < len(string):
if string[leftIdx] != string[rightIdx]:
break
leftIdx -= 1
rightIdx += 1
return [leftIdx+1, rightIdx]
# def longestPalindromicSubstring(string):
# """
# O(n^3) time | O(1) space
# Algoexpert
# :param string:
# :return:
# """
# longest = ""
# currentLongest = [0,1]
#
# for i in range(1, len(string)):
# for j in range(i,len(string)):
# substring = string[i : j+1]
#
# if len(substring) > len(longest) and isPalindrome(substring):
# longest = substring
# return longest
#
# def isPalindrome(string):
# left=0
# right=len(string)-1
# while left<right:
# if string[left]!=string[right]:
# return False
# left+=1
# right-=1
# return True
# A O(n ^ 2) time and O(1) space program to find the
# longest palindromic substring
# This function prints the longest palindrome substring (LPS)
# of str[]. It also returns the length of the longest palindrome
def longestPalSubstr(string):
maxLength = 1
start = 0
length = len(string)
low = 0
high = 0
# One by one consider every character as center point of
# even and length palindromes
for i in range(1, length):
# Find the longest even length palindrome with center
# points as i-1 and i.
low = i - 1
high = i
while low >= 0 and high < length and string[low] == string[high]:
if high - low + 1 > maxLength:
start = low
maxLength = high - low + 1
low -= 1
high += 1
# Find the longest odd length palindrome with center
# point as i
low = i - 1
high = i + 1
while low >= 0 and high < length and string[low] == string[high]:
if high - low + 1 > maxLength:
start = low
maxLength = high - low + 1
low -= 1
high += 1
#print "Longest palindrome substring is:",
print (string[start:start + maxLength])
return maxLength
pass
string="asdfdsbmdflirilasbdjexyxjhlqwertytrewq"
#print(longestPalindromicSubstring(string))
print(longestPalSubstr(string)) |
8ef0a6baf3995f49d8d005e68d6018ab67a34071 | shubhamnag14/Python-Documents | /Standard Library/gc/PyMOTW/05_When_Cycle_is_Broken.py | 1,037 | 3.625 | 4 | import gc
import pprint
class Graph(object):
def __init__(self, name):
self.name = name
self.next = None
def set_next(self, next):
print(f"Linking nodes {self}.next = {next}")
self.next = next
def __repr__(self):
return f"{self.__class__.__name__}, {self.name}"
def __del__(self):
print(f"{self}.__del__()")
# Construct a graph cycle
one = Graph('one')
two = Graph('two')
three = Graph('three')
one.set_next(two)
two.set_next(three)
three.set_next(one)
print()
one = two = three = None
# Show effect of garbage collection
print()
print("Collecting...")
n = gc.collect()
print("Unrechable objects, {n}")
print("Remaining Garbage")
pprint.pprint(gc.garbage)
# Break the cycle
print()
print("Breaking the cycle")
gc.garbage[0].set_next(None)
print("Removing references is gc.garbage")
del gc.garbage[:]
# Now the objects are removed
print()
print('Collecting')
n = gc.collect()
print(f"Unrechable objects {n}")
print("Remaining Garbage")
pprint.pprint(gc.garbage)
|
ad0635cfc98f860f3335577d5530a21f61340226 | raquelinevr/python | /Avaliaçoes/ATIVIDADE 6.py | 2,915 | 3.984375 | 4 | #C:\Users\Raqueline\AppData\Local\Programs\Python\Python37-32
Utilizando quaisquer dos comandos, funções e operadores vistos até a Semana 6,
faça programas Python para resolver as questões abaixo.
1. Nessa semana ocorrerá a 16a rodada do Brasileirão (Série A). Serão 10 jogos
envolvendo 20 times.
Faça um programa para, em cada um dos 10 jogos dessa rodada, ler os nomes
dos dois times e o placar do jogo (quantidade de gols marcados por cada time
no jogo).
Obs: ao se informar os nomes dos 2 times de cada jogo, o primeiro nome é o
do time “mandante” e o segundo nome é o do time “visitante”.
Ao final, o seu programa deverá calcular e exibir:
Quantidade de vitórias de mandantes;
Quantidade de empates;
Quantidade de vitórias de visitantes;
Total de gols marcados na rodada.
total = emp = t1 = t2 = 0
for i in range(2):
time1=input('Primeiro time\nMandante: ')
time2=input('Segundo time\nVisitante: ')
gol1=int(input('Quantidade de gols do primeiro time: '))
gol2=int(input('Quantidade de gols do segundo time: '))
total=total+gol1+gol2
if gol1>gol2:
t1=t1+1
if gol2>gol1:
t2=t2+1
if gol1==gol2:
emp=emp+1
print('\n===== RESULTADO =====')
print(f'Quantidade de vitórias de mandantes: {t1} ')
print(f'Quantidade de empates: {emp} ')
print(f'Quantidade de vítoria de visitantes: {t2} ')
print(f'Total de gols marcados na rodada: {total} ')
2. Numa determinada festa, os homens tinham que pagar R$ 20,00 pelo ingresso
e as mulheres R$ 10,00. Faça um programa que:
Leia o nome, a idade e o sexo (M ou F) de cada participante da festa (a
leitura do nome FIM indica o final dos dados de entrada);
Determine e exiba o nome e a idade do participante mais jovem e do
participante mais velho (suponha que não haja empates);
Calcule e exiba a média de idade dos participantes da festa;
Calcule e exiba o total arrecadado com os ingressos da festa.
soma=0
cont=0
m=0
f=0
maior=0
menor=999
nomeJ=0
nomeV=0
while True:
nome=input('Informe seu nome: ')
nomeUpper=nome.upper()
if nomeUpper=='FIM':
break
else:
idade=int(input('Informe a idade: '))
sexo=input('Informe o sexo: [M/F] ').upper()
if idade<menor:
menor=idade
nomeJ=nome
if idade>maior:
maior=idade
nomeV=nome
if sexo=='M':
m=m+1
if sexo=='F':
f=f+1
soma=soma+1
cont=cont+idade
total=f*10+m*20
media=cont/soma
print(f'\n{nomeJ} é o participante mais novo(a) com {menor} anos ')
print(f'{nomeV} é o participante mais velho(a) com {maior} anos ')
print(f'Media de idade dos participantes: {media:.0f} anos')
print(f'Total arrecadado com os ingressos: R$ {total:.2f} ')
|
b13053edae610db0dc23fc7364243ed12384d062 | CKZfd/LeetCode | /leetcode/141_hasCycle.py | 781 | 3.96875 | 4 | """
141、环形链表
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置
(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
"""
"""
快慢指针、套圈
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not (head and head.next):
return False
i, j = head, head.next
while j and j.next: # 快的走到头还没有相遇,结束
if i == j:
return True
i, j = i.next, j.next.next
return False |
7059034caa077941efa8b0e491f54555c1616a07 | jitendragangwar123/Python | /ex.py | 118 | 3.875 | 4 | num1,num2,num3=(input("enter the no: ").split(","))
print(f"avg of three no {(int(num1)+int(num2)+int(num3)) / 3}")
|
81ec3425a52ca917d5cacebd63ff7e4b3f16277d | adamny14/LoadTest | /test/as2/p1.py | 243 | 4.0625 | 4 | #-------------------------------------
# Adam Hussain
# print out squares of numbers until n
#-------------------------------------
n = input("Enter number: ");
counter = 1;
while counter <= n:
print(counter * counter);
counter = counter+1;
|
d6481e2ee0d8e2f4e20930b4b3aa547eab801060 | Alin0268/Functions_in_Python | /Linear_Search_(without_any_functions).py | 563 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""Return index of key in mylist. Return -1 if key not present."""
# Вводим числа через пробел
mylist = input('Enter the list of numbers: ')
mylist = mylist.split()
mylist = [int(x) for x in mylist]
key = int(input('The number to search for: '))
indicator = 0
for i in range(len(mylist)):
if mylist[i] == key:
print('first occurrence of {} was found at index {}.'.format(key, i))
indicator = 1
break
if indicator == 0:
print('{} was not found.'.format(key))
|
5e51ec111c22407110292e8f7dd33c47c49e6398 | Nerdylicious/SquareAndMultiply | /squaremultiply.py | 323 | 3.796875 | 4 | import math
#z=x^c mod n
print "\nFormat is z=x^c mod n"
x = raw_input("\nEnter x: ")
c = raw_input("Enter c: ")
n = raw_input("Enter n: ")
x = int(x)
c = int(c)
n = int(n)
c = '{0:b}'.format(c)
z = 1
l = len(c)
for i in range(0, l):
z = (math.pow(z, 2)) % n
if (c[i] == "1"):
z = (z*x) % n
print "\nz = %d" % z
|
83a04176f1bb2fd3a22b8cf2b7a14451c00a994b | tarcisio-neto/PythonHBSIS | /Exercicios Python/Exercicio 52.py | 355 | 3.78125 | 4 | # 52- Faça um algoritmo que calcule e escreva a média aritmética dos números inteiros entre
# 15 (inclusive) e 100 (inclusive).
print('Média aritimética')
soma = 0
divisor = 101-15
for contador in range(15,101,1):
soma = soma + contador
media = (soma /divisor)
print('A média aritimética dos valores entre 15 e 100 é {:.2f}'.format(media))
|
52e3a08ef3f3d47195aeb7545f1f59aacc171472 | juhnowski/FishingRod | /production/pygsl-0.9.5/pygsl/block.py | 3,039 | 3.546875 | 4 | #!/usr/bin/env python
# Author : Pierre Schnizer
import _block
class _generic:
"""
Generic block class. Handles common operation.
"""
# Defines what basis type this class handles. To be defined in a derived
# class. e.g. base = 'vector'
_base = None
def _get_function(self, suffix):
"""
translate some prefix to the full qualified name of the block
"""
if self._type == '':
tmp = '_'
else:
tmp = '_' + self._type + '_'
# base is matrix or vector or .....
assert self._base != None, 'Use a derived class!'
base = self._base
function = eval('_block.gsl_' + base + tmp + suffix)
return function
def __init__(self):
self._fread = self._get_function('fread')
self._fwrite = self._get_function('fwrite')
self._fscanf = self._get_function('fscanf')
self._fprintf = self._get_function('fprintf')
def fread(self, *args):
"""
reads a binary stream of the vector from an open file.
input: file, size of the vector
output: flag, the vector
"""
return apply(self._fread, args)
def fwrite(self, *args):
"""
writes a binary stream of the vector to an open file.
input: file, vector
output: flag if sucessful
"""
return apply(self._fwrite , args)
def fscanf(self, *args):
"""
scans the length of the vector from the file.
input: file, length of the vector to be read
output: flag, the vector
"""
return apply(self._fscanf , args)
def fprintf(self, file, vector, format):
"""
prints the vector to an open file.
input: file, vector, format
file ... an file open for writing
vector ... a vector of data
format ... a "c" type format string. These are similar to the
python ones, but differences exist.
"""
#Some checking if the file type is good ... should go in here.
return self._fprintf(file, vector, format)
class _generic_block(_generic):
"""
Basis functions for vectors and matrices.
"""
def __init__(self):
_generic.__init__(self)
self.set_zero = self._get_function('set_zero')
self.set_all = self._get_function('set_all')
self.swap = self._get_function('swap')
self.isnull = self._get_function('isnull')
if(self._type != 'complex' and self._type != 'complex_float'):
self.max = self._get_function('max')
self.min = self._get_function('min')
self.minmax = self._get_function('minmax')
self.max_index = self._get_function('max_index')
self.min_index = self._get_function('min_index')
self.minmax_index = self._get_function('minmax_index')
|
ce40115d1640232be66eba21ebefa4881582a9cd | kamaihamaiha/Tutorial | /python_tutorial/com/python/chapter9/demo2/user.py | 614 | 3.53125 | 4 | class User():
def __init__(self,first_name,last_name,age):
self.first_name = first_name
self.last_name = last_name
self.age = age
"""登录次数属性"""
self.login_attempts = 0
"""增加登录次数 1次"""
def increment_login_attempts(self):
self.login_attempts+=1
"""重置登录次数"""
def reset_login_attempts(self):
self.login_attempts = 0
def describe(self):
print(self.first_name + '.' + self.last_name + str(self.age) + '岁了!')
def greet(self):
print('Hello ' + self.first_name + '!') |
d3150853d83d56baaee10e9ca75e9c17124059aa | autoolops/python-sh-ops | /day4/上课笔记/06 名称空间与作用域.py | 2,944 | 4.40625 | 4 | '''
1 名称空间Namespaces
存放名字与值绑定关系的地方
2 名称空间的分类
内置名称空间:
存放python解释器自带名字,比如内置的函数名:len,max,sum
创建:随着python解释器启动而创建
销毁:随着python解释器关闭而销毁
全局名称空间
存放文件级别的名字,比如x,f1,z
x=1
def f1():
y=2
if x == 1:
z=3
创建:文件开始执行时则立即创建
销毁:文件开始执行完毕时则销毁
局部名称空间
存放函数内的名字,强调函数的参数也属于局部的
创建:函数执行时才临时创建
销毁:函数执行完毕则立即销毁
def f1():
x=1
y=2
z=3
f1()
3 名称空间的加载顺序
内置名称空间---》全局名称空间-----》局部名称空间
加载的目的是为了吧名字存起来,然而存起的目的就是为取
那么但凡查找一个名字一定会从三种名称空间之一找到
4、名称空间的查找名字顺序
局部名称空间====》全局名称空间===》内置名称空间
'''
# len=10
# def f1():
# # len=3
# print(len)
#
# f1()
# len=10
# def f1():
# len=100
# def f2():
# # len=1000
# def f3():
# # len=10000
# print(len)
# f3()
# len=200
# f2()
# # len=111111111111111111111111111111
#
# f1()
# 名字的查找关系是在函数定义阶段就已经固定死的,与调用位置无关
# x=100
# def f1():
# # x=10
# print(x)
#
#
# def f2():
# x=11111
# f1()
#
# f2()
#
# x=1000
# 作用域:域=范围
# 全局范围:内置名称空间中的名字,全局名称空间中的名字
# 特点:全局有效,全局存活
# 局部范围:局部名称空间中的名字
# 特点:局部有效,临时存活
# 定义在全局作用域的名字称为全局变量
# 定义在局部作用域的名字称为局部变量
# x=1
# def f1():
# print(len)
# print(x)
# def f2():
# print(len)
# print(x)
# def f3():
# def f4():
# print(len)
# print(x)
# f4()
#
# x=111111111111111111111111111111111111111111111111111111
# print(globals()) #查看全局作用域中的名字
# print(locals() is globals())
# def f1():
# y=2
# z=3
# print(locals())
#
# f1()
# global与nonlocal
# l=[]
# def foo():
# l.append(2)
#
# foo()
# print(l)
# x=10
# def foo():
# x=100
# print(x)
#
# foo()
# print(x)
# x=10
# def foo():
# global x
# x=100
#
# foo()
# print(x)
def f1():
# x=10
def f2():
def f3():
nonlocal x # nonlocal会从当前外一层开始查找一直找到最外层的函数,如果还没有则报错
x=11
f3()
f2()
# print(x)
f1()
|
dd8ba1efa929ff16959eca2a972d800336c00a73 | hannesthiersen/zelle-2010 | /10-defining_classes/projectile_tests.py | 2,422 | 3.71875 | 4 | # File: projectile_tests.py
# Date: 2020-06-04
# Author: "Hannes Thiersen" <hannesthiersen@gmail.com>
# Version: 0.1
# Description:
# Testing projectile for problems by graphing the trajectories.
#------------------------------------------------------------------------------
# IMPORTS
#------------------------------------------------------------------------------
from math import sin, cos, sqrt, pi, radians
from matplotlib import pyplot as plt
from projectile import Projectile
#------------------------------------------------------------------------------
# IMPORTS
#------------------------------------------------------------------------------
class Trajectory():
def __init__(self, angle, vel, h0, gravity=-9.8):
self.x0 = 0.0
self.y0 = h0
self.vx0 = vel * cos(radians(angle))
self.vy0 = vel * sin(radians(angle))
self.gravity = gravity
def traveltime(self, y=None):
""" Calculates the trajectory time to a certain value of y. """
if y:
square = self.vy0**2 - 4*self.gravity*(self.y0 - y)
if square > 1:
tmin = (-v - sqrt(square)) / (4*gravity)
tmax = (-v + sqrt(square)) / (4*gravity)
return [ tmin, tmax ]
return None
#------------------------------------------------------------------------------
# FUNCTIONS
#------------------------------------------------------------------------------
def fire(angle, vel, h0, time):
cball = Projectile(angle, vel, h0)
xcoords = [0.]
ycoords = [h0]
while cball.getY() >= 0.0:
cball.update(time)
xcoords.append(cball.getX())
ycoords.append(cball.getY())
plt.plot(xcoords, ycoords, marker=".", label=time/vel)
#------------------------------------------------------------------------------
# MAIN
#------------------------------------------------------------------------------
def main():
# Initial conditions
angle, vel, h0 = 45.0, 25.0, 2.0
path = Trajectory(angle, vel, h0)
print(path.traveltime(y=0.))
# Time intervals to test
time = [ t*.1 for t in range(1,6) ]
plt.figure("Trajectories")
for deltat in time:
fire(angle, vel, h0, deltat)
plt.legend()
plt.tight_layout()
plt.show()
#------------------------------------------------------------------------------
if __name__ == '__main__':
main()
|
74753fe01ab5fb87d60b2b6425fb23a3e14ff4e8 | akshaybogar/DS-Algo | /linked list/doubly_linked_list/insertion.py | 1,737 | 3.703125 | 4 | class Node:
def __init__(self, data, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class DoublyLinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
temp = Node(data)
if not self.head:
self.head = temp
return
temp.next = self.head
self.head.prev = temp
self.head = temp
return
def insert_at_end(self, data):
temp = Node(data)
if not self.head:
self.head = temp
return
last = self.head
while last.next:
last = last.next
last.next = temp
temp.prev = last
return
def insert_after_node(self, prev, data):
if not self.head or not prev:
return
temp = Node(data)
temp.next = prev.next
prev.next = temp
temp.prev = prev
if temp.next:
temp.next.prev = temp
return
def insert_before_node(self, next_node, data):
if not self.head or not next_node:
return
temp = Node(data)
temp.prev = next_node.prev
next_node.prev = temp
temp.next = next_node
if temp.prev:
temp.prev.next = temp
else:
self.head = temp
return
def traverse_list(self):
node = self.head
while node:
print(node.data, end=' ')
node = node.next
return
if __name__ == '__main__':
dll = DoublyLinkedList()
dll.insert_at_beginning(1)
dll.insert_at_end(4)
dll.insert_after_node(dll.head, 2)
dll.insert_before_node(dll.head, 5)
dll.traverse_list()
|
3893855bbb8d8fc779502b43bd5d735fd333966c | gc-ss/hy-lisp-python | /examples_translated_to_python/matplotlib/plot_relu.py | 245 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
def relu(x):
return np.maximum(0.0, x)
X = np.linspace(-8, 8, 50)
plt.plot(X, relu(X))
plt.title('Relu (Rectilinear) Function')
plt.ylabel('Relu')
plt.xlabel('X')
plt.grid()
plt.show()
|
9ab0d857e469cb07d47b677881655ed4a6d07ae6 | karbekk/Python_Data_Structures | /Interview/LC/Dynamic_Programming/198_House_Robber.py | 491 | 3.765625 | 4 | class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
even = 0
odd = 0
for i in range(0,len(nums)):
if i % 2 == 0:
even = even + nums[i]
even = even if even > odd else odd
else:
odd = odd + nums[i]
odd = even if even > odd else odd
return max(even,odd)
obj = Solution()
print obj.rob(nums=[3,2,1,4]) |
6214414b353fe5f4a7ea0272755ae9d959f38e1a | Tatsuro0726/MIT_DS | /practice_Ch3.py | 4,697 | 3.875 | 4 | # -*- coding: utf-8 -*-
# #完全立方の立方根を求める⇒3乗してそのxになるものを探している
# x = int(input('Enter an integer:'))
# ans = 0
# while ans ** 3 < abs(x):
# ans = ans + 1
# if ans ** 3 != abs(x):
# print(x, 'is not a perfect cube')
# else:
# if x < 0:
# ans = -ans
# print('Cube root of',x,'is',ans)
# # practice:p27
# num = int(input('Enter an positive integer:'))
# pwr = 1
# flag = False
# while pwr < 6:
# root = 1
# while root**pwr < num: # rootのpwr乗がnumになるまで or 超えるまで rootを加算していく
# root = root + 1
# if root ** pwr == num:
# print(root, pwr)
# pwr = pwr + 1
# print(root,pwr)
# # 参考の回答
# n = int(input())
# i = 5
# while i > 0:
# root = 1
# while root ** i < n:
# root = root + 1
# if root ** i == n:
# print(root, i)
# i = i - 1
# x = 4
# for j in range(x): # このforは4回繰り返される
# for i in range(x): # j=1のときはx=4が評価されるが、それ以降はx=2が評価されてしまい010101となる
# print(i)
# x=2
# # sample
# #完全立方に対する立方根
# x = int(input('Enter an integer:'))
# for ans in range(0, abs(x) + 1):
# if ans ** 3 >= abs(x):
# break
# if ans ** 3 != abs(x):
# print(x, 'is not perfect cube')
# else:
# if x < 0: # 負の値が入力された場合の処理
# ans = -ans
# print('Cube root of', x, 'is', ans)
# # sample
# total = 0
# for c in '12345678':
# total = total + int(c)
# print(total)
# # practice
# total = 0
# s = '1.23,2.4,3.123'
# for i in range(0, len(s)):
# if i == 0 and s[i] != ',':
# start = i
# if s[i] == ',':
# end = i
# total = total + float(s[start:end])
# start = i + 1 # start位置の更新
# total = total + float(s[start:len(s)])
# print(total)
# # Sample
# # 総当たりを用いた平方根の近似
# x = 0.25
# epsilon = 0.01
# step = epsilon ** 2
# numGuesses = 0
# ans = 0.0
# #while abs(ans ** 2 - x) >= epsilon and ans <= x: #abs(ans ** 2 - x)は誤差 - 誤差がeps以上かつ総当たりの数が25以下
# #⇒この条件だと、xより大きい値が平方根の場合(0<x<1)を考慮できていない。
# while abs(ans**2 - x) >= epsilon and ans*ans <= x:
# ans += step
# numGuesses += 1 # 回数カウント?
# print('numGuesses =', numGuesses)
# if abs(ans ** 2 - x) >= epsilon: #指定の誤差を超えた場合
# print('Failed on square root of', x)
# else:
# print(ans, 'is close to square root of',x)
# #practice
# # 平方根の近似解のための2分法(bisection search)
# #x = float(input('Enter an integer:'))
# x = -25
# epsilon = 0.01
# numGuesses = 0
# low = 0.0
# high = max(1.0, x)
# ans = (high + low) / 2.0
# while abs(ans ** 2 - x) >= epsilon:
# print('low =', low, 'high =', high, 'ans =', ans)
# numGuesses += 1
# if ans ** 2 < x:
# low = ans
# else:
# high = ans
# ans = (high + low) / 2.0 # 探索領域を半分に減らす
# print('numGuesses =', numGuesses)
# print(ans, 'is close to square root of', x)
# #practice
# # 正負の立方根を求める
# x = -0.008
# n = 3
# epsilon = 0.01
# numGuesses = 0
# if x < 0:
# low = min(x,-1)
# high = max(1.0, x)
# ans = (high + low) / 2.0
# while abs(ans ** n - x) >= epsilon:
# print('low =', low, 'high =', high, 'ans =', ans)
# numGuesses += 1
# if ans ** n < x:
# low = ans
# else:
# high = ans
# ans = (high + low) / 2.0 # 探索領域を半分に減らす
# print('numGuesses =', numGuesses)
# print(ans, 'is close to square root of', x)
# Chapter 3.4
# sample
# x = 0.0
# for i in range(10):
# x = x + 0.1
# if x == 1.0:
# print(x, '=1.0')
# else:
# print(x, 'is not 1.0')
# 0.9999999999999999 is not 1.0 :0.1は二進数では表現できないため誤差が生じてしまっている。⇒ EWBのSpreadsheetも同様??
# Newton's method
# 平方根を求めるためのNewton-Raphson method
# x**2-24=0で誤差がepsilon以下になるxを求める
epslion = 0.01
k = 24.0
guess = k / 2.0
cnt_newton = 0
while abs((guess ** 2) - k) >= epslion:
cnt_newton += 1
guess = guess - (((guess ** 2) - k) / (2 * guess))
print('Square root of', k, 'is about', guess)
print('Count_ne =', cnt_newton)
# 2分法
epslion = 0.01
k = 24.0
high = max(1, k)
low = 0
ans = (high + low) / 2
cnt_bisection = 0
while abs(ans ** 2 - 24) >= epslion:
if ans ** 2 < k:
low = ans
else:
high = ans
ans = (high + low)/2
cnt_bisection += 1
print('Count_bi =',cnt_bisection)
|
c968ff4a42eb9f3f60aaf5f6e211165c8ddd6eaa | shinkarenkoalexey/Python | /Labs/lab4/8.py | 107 | 3.703125 | 4 | n = int(input("n..."))
x = 0
y = 0
F = 1
for i in range(2, n+1):
x = y
y = F
F = x + y
print(F) |
136539ca6dae87fa2d0c1845a24a51bdc06ee8ec | kangnamQ/I_Do | /code/pytest2.py | 9,166 | 4.34375 | 4 | print("로봇공학 2주차-1")
print("")
string1 = "Life is too short"
string2 = 'You need python'
print(type(string1), type(string1))
#"",'' < 상관없이 str형
print("Life 'is' too short")
print('You "need" python')
#""와 ''를 구분해서 양쪽에 것과 다른 것을 사용
print("Life \"is\" too short,\nYou \'need\' python")
print("특수문자 \"로 \"자체가 문자로 인식됨 스페이스 또한 인식")
print("안녕? 파이썬")
print("")
print("\n 한줄 넘기기")
print("\t 탭을 쓸 때 사용")
print("\\ \을 쓸 때 사용")
print("\' '을 쓸 때 사용")
print('\" "을 쓸 때 사용')
print(""),print("")
print("can you feel me 나를 느껴 봐요 \ncan you touch me 나를 붙잡아 줘")
print("can you hold me 나를 꼭 안아 줘 \nI want you pick me up")
print(("pick me "*3 + "up ") * 2) #\n을 넣을 경우 한칸 더 뛰어져서 보기힘듬...
print("pick me "*4)
print(("pick me "*3 + "up ") * 3)
print("pick me "*4 + "I want you pick me up")
text = "Life is too short, You need Python"
# Life is too short, You need Python
# 0 1 2 3
# 0123456789012345678901234567890123
print("print t:",text[8], text[16], text[-4])
print(text[:4])
print(text[12:17])
print(text[-6:])
print(text[23:27])
print(text[23:-7]) #앞에서 샌것도 뒤에서 새는 것도 혼용해서 사용가능
#시작이 생략되어 있으면 처음부터, 끝이 생략되있으면 끝까지 가져오는 것이다.
print("")
print(text[-6:] + text[4:-6] + text[:4])
print(text[-6:] + text[4:28] + text[:4])
print("")
_class = "warrior"
print("\n" + "="*30, "\nString formatting 1: %")
print("포맷 코드를 이용")
print("class: %s, HP: %d, DPS: %f" % (_class, 100, 1456.23))
#포맷 코드 : 문자열은 %s, 정수형은 %d, 실수형은 %f를 사용
#보통 C에서 많이 사용
print("format 함수를 이용")
print("class: {}, HP: {}, DPS: {}".format(_class, 100, 1456.23))
# 타입에 상관없이 {}와 {}안에 넣을 값을 쓰면 자동으로 입력
# 이방법도 요즘은 많이 사용하지 않음 - 순서를 맞춰줘야함
print("f문자열 포매팅")
print(f"class: {_class}, HP: {100}, DPS: {1459.23}")
#앞에 f를 쳐줘야 한다. = 그래서 f문자열 포매팅
#직관적으로 좋음. 그냥 {}안에 직접 넣으면 자동으로 타입이 변환됨
print("")
print("pick me pick me pick me up".count('pick me'))
text = "pick me pick me pick me up"
print(text.count("pick me"))
print("")
text = "For the python, of the python, by the python"
pyind = text.find("py")
print("where is 'py?", pyind) #처음 py
pyind = text.find("py", pyind + 1)
print("where is 'py?", pyind) #처음 py 다음자리 부터의 py, 즉 2번째 py
pyind = text.find("py", pyind + 1)
print("where is 'py?", pyind) #3번째 py
pyind = text.find("py", pyind + 1)
print("where is 'py?", pyind) #4번째 py, find는 없으면 -1을 반환하기 때문에 -1
print("\nfind f포매팅")
text = "For the python, of the python, by the python"
pyind = text.find("py")
print(f"'py' found at {pyind} in `{text}`")
pyind = text.find("py", pyind+1)
print(f"'py' found at {pyind} in `{text}`")
#f문자열 포매팅을 사용하면 좀더 직관적이다.
print("\nindex f포매팅")
text = "For the python, of the python, by the python"
pyind = text.index("py")
print(f"'py' indexed at {pyind} in `{text}`")
pyind = text.index("py", pyind +1)
print(f"'py' indexed at {pyind} in `{text}`")
pyind = text.index("py", pyind +1)
print(f"'py' indexed at {pyind} in `{text}`")
#여기서 부터 error뜸
#try : 에러가 뜰 것 같은 구간이 있을 때 시도를 해보고 되면 나오고
#에러가 나면 except로 넘어가 그대로 쭉 실행하게 하는 것
try:
pyind = text.index("py", pyind + 1)
print(f"'py' indexed at {pyind} in `{text}`")
except ValueError as ve:
print(ve)
#index에서는 ValueError가 나온다.
#ValueError이외의 다른 에러가 나는 경우 try에서 죽어도 괜찮다는 말.
#substring not found라는 문구가 뜨며 에러가 났는데 그냥 프린트만 하는 방법임.
pyind = text.index("py")
print(f"'py' indexed at {pyind} in `{text}`")
print("")
mixed = "PYthon"
small = "python"
print(mixed == small)
print(mixed.lower() == small)
print(mixed.lower() == small.lower())
print(mixed.upper() == small.upper())
print(mixed.upper())
print(mixed.lower())
print(mixed.lower() is small.lower())
#객체가 다르기 때문에, 다른 객체이기 때문에 False가 뜬다, 쓸 때 조심
print("")
wise_saying = ' "Walking on water and developing software ' \
'from a specification are easy if both are frozen..." '
print(wise_saying)
print(wise_saying.strip())
#strip() = 공백, 불필요한 시작/끝의 문자을열을 지우는 것
print(wise_saying.strip("\""))
#양쪽의 공백이 있기 때문에 ""가 지워지지 않음
wise_saying1 = wise_saying.strip()
print(wise_saying1.strip("\""))
print("")
print(wise_saying)
wise_saying1 = wise_saying.strip()
print(wise_saying1)
wise_saying2 = wise_saying1.strip("\"")
print(wise_saying2)
wise_saying3 = wise_saying2.strip(".")
print(wise_saying3)
wise_saying4 = wise_saying2.rstrip(".")
print(wise_saying4)
#그냥 .해도 지워지긴 하지만 앞에껀 납두고 뒤에껏만 지우고 싶을 때 같은 곳에 사용 가능할 듯.
#앞쪽만 지우기 : lstrip
#뒤쪽만 지우기 : rstrip
print("")
Lincoln_said = "for the people, by the people, of the people"
print(Lincoln_said)
We_say = Lincoln_said.replace("people", "python")
print("We_say:", We_say)
#특정 문자열을 지우는 것은 안되지만 replace를 사용하여 교체가능
Simply_say = We_say.replace("the ", "")
print("Simply_say:", Simply_say)
print(We_say.split(" "))
print(We_say.split(","))
#기준이 되는 것들은 들어가지 않음, 구분해주기 위해서.
print("")
marble1 = \
"나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" \
"나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" \
"그간 많은 stress 견뎌내며 비로소 대리암이 되었다네\n" \
"모든 게 완벽했던 그 어느 날 난 너를 만나게 된 거야\n" \
"나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" \
"나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" \
"나를 보고 웃기라도 하는 날엔 하루 종일 아무것도 할 수 없네\n" \
"그 눈으로 날 똑바로 바라보면 나는 녹아버릴 거야\n" \
"나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" \
"나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" \
"나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" \
"나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" \
"이것이 염산반응이다\n" \
"이것이 염산반응이다\n" \
"Hcl이다 CaCO3다\n" \
"2Hcl + CaCO3 -> CaCl2 +CO2 + H2O다.\n" \
"나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" \
"나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" \
"나는 대리암 나는 대리암"
#\ 한줄의 코드를 줄을 나눠주기 위해 사용한 것
print("\n1)“대리암”의 가사를 문자열 연산을 통해 만들어 보세오.")
marble2 = \
"나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" * 2 \
+ "그간 많은 stress 견뎌내며 비로소 대리암이 되었다네\n" \
+ "모든 게 완벽했던 그 어느 날 난 너를 만나게 된 거야\n" \
+ "나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" * 2 \
+ "나를 보고 웃기라도 하는 날엔 하루 종일 아무것도 할 수 없네\n" \
+ "그 눈으로 날 똑바로 바라보면 나는 녹아버릴 거야\n" \
+ "나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" * 4 \
+ "이것이 염산반응이다\n" * 2 \
+ "Hcl이다 CaCO3다\n" \
+ "2Hcl + CaCO3 -> CaCl2 +CO2 + H2O다.\n" \
+ "나는 대리암 염산과 반응하면 이산화탄소를 내며 녹는 대리암\n" * 2 \
+ "나는 대리암 나는 대리암" \
print(marble2)
print("\n2)가사에서 “대리암”이 몇 번 나오는지, 세 번째로 나오는 위치는 어디인지 찾아보세요.")
print("대리암",marble1.count("대리암"))
Q2_1 = marble1.find("대리암")
print(Q2_1)
Q2_2 = marble1.find("대리암", Q2_1+1)
print(Q2_2)
Q2_3 = marble1.find("대리암", Q2_2+1)
print("3번 째 대리암의 위치 : ", Q2_3)
print("\n3)가사에서 “대리암”을 “현무암”으로 바꿔보세오.")
print(marble1.replace("대리암", "현무암"))
|
488e8b099c4ecf77ef3159203e85fc99ea538212 | iamjai-3/python-scripts | /Python_Examples.py | 5,547 | 3.828125 | 4 |
# # Try, Except, Finally
# try:
# print(x)
# except:
# print("Error Occured")
# finally:
# c = 2+3
# print(c)
# #Value Validation
# def age(value):
# assert value>0 , "please give"
# print(value)
# inp = int(input("Enter no:"))
# age(inp)
# #Exception Info
# import sys
# a = [5,8,"d",9,7,0,4]
# for i in a:
# try:
# c = 2/i
# print(c)
# except:
# print("Error",sys.exc_info()[0],"occured")
# # Exception
# class Error(Exception):
# pass
# class TooSmallError(Error):
# pass
# class TooLargeError(Error):
# pass
# num =10
# while True:
# try:
# ch = int(input("Number:"))
# if ch < 10:
# raise TooSmallError
# elif ch > 10:
# raise TooLargeError
# break
# except TooSmallError:
# print("Entered small no")
# except TooLargeError:
# print("Entered large no")
# print("Entered actual value")
# #Read Write
# f = open("/home/ennovasys/Jai/python/t.txt", "r+")
# # f.write("Entered Data")
# length = len(f.readlines())
# # str = f.read(5)
# # print(str)
# print(length)
# f.close()
# #Class, Obj , fucnc
# class Ex:
# a = 10
# b = 21
# c = "sa"
# d = 90
# def add(self,x,y):
# c = x+y+self.d
# return c
# obj = Ex()
# print(obj.c)
# ans = obj.add(10,5)
# print(ans)
# # Constructor
# class demo:
# print("constructor:".upper())
# def __init__(self,name,age):
# self.age = age
# self.name = name
# def display(self):
# print("Name is :",self.name)
# print("Age is :",self.age)
# obj = demo("Jai",23)
# obj.display()
# #Inheritance
# class Father:
# f_name = "this.father"
# f_age = 55
# class son(Father):
# s_name = "this.son"
# s_age = 23
# obj = son()
# print("The Fathers name is :", obj.f_name,",", obj.f_age)
# print("The son name is :", obj.s_name,",", obj.s_age)
# #Multi Threading & Naming
# import threading
# import time
# def thread1(x,st):
# for i in range (x):
# time.sleep(st)
# print(threading.current_thread().getName())
# print("Thread 1 Started \n")
# def thread2(x1,st1):
# for i in range (x1):
# time.sleep(st1)
# print(threading.current_thread().getName())
# print("Thread 2 Started \n")
# t1 = threading.Thread(target = thread1, args = (5,1))
# t1.setName("Thread #1")
# t2 = threading.Thread(target = thread2, args = (3,1))
# t2.setName("Thread #2")
# t1.start()
# t2.start()
# #Thread checking (Alive or Dead)
# import threading
# import time
# def thread(i):
# time.sleep(i)
# return
# t1 = threading.Thread(target = thread, args = (60,), name = "Thread 1")
# t1.start()
# t2 = threading.Thread(target = thread, args = (2,), name = "Thread 2")
# t2.start()
# for x in range(5): # To check thread for every 5 secs
# time.sleep(x)
# print("[",time.ctime(),t1.name,t1.is_alive(),"]")
# print("[",time.ctime(),t2.name,t2.is_alive(),"]")
# # Daemon Threading
# import threading
# import time
# def thread1():
# print("Thread 1 Started \n")
# time.sleep(2)
# print("Theread 1 Ended")
# def thread2():
# print("Thread 2 Started")
# print("Thread 2 Ended")
# t1 = threading.Thread(target = thread1, daemon = 'true')
# t1.start()
# t2 = threading.Thread(target = thread2)
# t2.start()
# t1.join() # To Get Deamon thread end point
# t2.join()
# Timer Threading
# import threading
# import time
# def demo():
# print("Timer Started")
# t = threading.Timer(3,demo)
# t.start()
# time.sleep(2) # Cancels the theread if thread not started before 2 seconds
# t.cancel()
import sys
import time
class ex:
def __init__(self, text, hour, min, sec):
self.text = text
self.hour = hour
self.min = min
self.sec = sec
def l(self):
print("op :", self.text)
# def __init__(self, text):
# self.text = text
# def getvalue(self):
# return self.text
def check(self):
c= ":"
while self.hour > -1:
while self.min > -1:
while self.sec > 0:
self.sec=self.sec-1
time.sleep(1)
sec1 = ('%02.f' % self.sec) # format
min1 = ('%02.f' % self.min)
hour1 = ('%02.f' % self.hour)
sys.stdout.write('\r' + str(hour1) + c + str(min1) + c + str(sec1))
if str(hour1) == "00" and str(min1) == "00" and str(sec1) == "07":
playsound.playsound('test.mp3', True)
print("Time up")
self.min=self.min-1
self.sec=60
self.hour=self.hour-1
self.min=59
print('Countdown Complete.')
|
9af235b9a87039cb34744903c34ae216daf48718 | summerbr/Class | /Week2-Python/phonebook_summerbr.py | 1,146 | 4.15625 | 4 | print('Electronic Phone Book')
print('=====================')
print('1. Look up an entry')
print('2. Add an entry')
print('3. Delete an entry')
print('4. List all entries')
print('5. Quit')
#add a function prompt to run again after selection run
#while selection != 5:
phonebook = {
'Harry': '895-3000',
'Ron': '895-3001',
'Hermione': '895-3002',
'Draco': '895-3003',
}
user_entry = int(input('Choose option(1-5)? '))
if user_entry == 1:
lookup_name = input('Enter name: ')
for name in phonebook:
if name == lookup_name:
print(f'Match found: {lookup_name}: {phonebook[lookup_name]}')
else:
print(f'Match not found.')
elif user_entry == 2:
add_name = input('Enter name: ')
add_number = input('Enter number: ')
phonebook[add_name] = add_number
print(f'New entry stored for {add_name}')
elif user_entry == 3:
entry_delete = input('Who do you want to remove? ')
phonebook.pop(entry_delete)
print(f'Deleted entry for {entry_delete}')
elif user_entry == 4:
print(phonebook)
elif user_entry == 5:
print('End')
else:
print(f'Please enter a valid option #.') |
912ad9da5a4281e4df332d909c8861f7a47eb3e6 | yingliufengpeng/python_design_pattern | /P6_Adapter_Pattern/__init__.py | 1,679 | 4 | 4 | import abc
class Player(abc.ABC):
# name = ''
def __init__(self, name):
self.name = name
@abc.abstractmethod
def attack(self):
pass
@abc.abstractmethod
def defense(self):
pass
class ForwardPlayer(Player):
def __init__(self, name):
super().__init__(name)
def attack(self):
print('前锋{}进攻'.format(self.name))
def defense(self):
print('前锋{}防守'.format(self.name))
class CenterPlayer(Player):
def __init__(self, name):
super().__init__(name)
def attack(self):
print('中锋{}进攻'.format(self.name))
def defense(self):
print('中锋{}防守'.format(self.name))
class BackPlayer(Player):
def __init__(self, name):
super().__init__(name)
def attack(self):
print('后卫{}进攻'.format(self.name))
def defense(self):
print('后卫{}防守'.format(self.name))
class ForeignCenter(abc.ABC):
def __init__(self, name):
self.name = name
def foreignattack(self):
print('外国中锋{}进攻'.format(self.name))
def foreigndefense(self):
print('外国中锋{}防守'.format(self.name))
class AdapterPlayer(Player):
def __init__(self, name):
super().__init__(name)
self.foreigin = ForeignCenter(name)
def attack(self):
self.foreigin.foreignattack()
def defense(self):
self.foreigin.foreigndefense()
def clientUI():
b = ForwardPlayer('巴蒂尔')
m = BackPlayer('姚明')
ym = AdapterPlayer('麦克格雷迪')
b.attack()
m.defense()
ym.attack()
if __name__ == '__main__':
clientUI() |
535dc454a2dd8105949a059dc2240115389b27b7 | reni04/IF1311-10219003 | /input user.py | 550 | 3.65625 | 4 | #episode input user
#data yang dimasukan pasti string
data = input("Masukan data : ")
print("data = ", data,",type =", type(data))
#jika kita ingin mengambil int maka
angka = float(input("Masukan angka:"))
print("angka float = ", angka,",type =", type(angka))
angka = int(input("Masukan angka:"))
print("angka int = ", angka,",type =", type(angka))
print("data = ", angka,",type =", type(angka))
#bagaimana denngan boolean
biner = bool(int(input("Masukan nilai boolean :")))
print("data = ", biner,",type =", type(biner))
|
53ed9bb2854e5617fbb47e6c0be485321cb160ff | xbouteiller/DetectBrokenSensor | /ConvertDXD/EmptyList.py | 1,869 | 4.1875 | 4 | def EmptyListofFiles():
'''
# function for crating an empty list for the first day
# should evaluate if file exists and creat it only if file not exists
'''
import os
import pickle
if not os.path.isfile("ListOfFiles.txt"):
ListOfFiles=[]
with open("ListOfFiles.txt", "wb") as fp: #Pickling
pickle.dump(ListOfFiles, fp)
print('Empty ListOfFiles created')
else:
print('ListOfFiles already here, \nnothing done !')
def PreviousListofFiles():
import pickle
import os
with open("ListOfFiles.txt", "rb") as fp: # Unpickling
PreviousLoF = pickle.load(fp)
print('Previous list of file loaded, length is {}'.format(len(PreviousLoF)))
return PreviousLoF
def CurrentListofFiles(dirName):
'''
parse files trought a path from folder tree and sort the files by natural sorting
'''
from natsort import natsorted
import re
import os
listOfFiles = list()
for (dirpath, dirnames, filenames) in os.walk(dirName):
listOfFiles += [os.path.join(dirpath, file) for file in filenames if file.endswith('.dxd')] #&&&
#sort fils by natural ordering
listOfFiles=natsorted(listOfFiles)
print('Current list of file loaded, length is {}'.format(len(listOfFiles)))
return listOfFiles
#diff between lists
def DifferenceBetweenListofFiles(PreviousLoF, CurrentLoF):
s = set(PreviousLoF)
DifferenceLoF = [x for x in CurrentLoF if x not in s]
print('Difference list of file loaded, length is {}'.format(len(DifferenceLoF)))
return DifferenceLoF
def SaveCurrentListofFiles(CurrentLoF):
import pickle
import os
with open("ListOfFiles.txt", "wb") as fp: #Pickling
pickle.dump(CurrentLoF, fp)
print('Current list of file saved, replacing old one')
|
9a2c2af86c6b6dba2151e8f6e5df45fb12a28615 | JosiahRooney/Python | /bubble_sort.py | 572 | 4.03125 | 4 | import random
numbers = []
for i in range(0,100):
numbers.append(round(random.random() * 10000))
print('before ' + str(numbers))
def bubble_sort(input_list):
is_sorted = False
while not is_sorted:
is_sorted = True
for (idx, num) in enumerate(input_list):
if idx < len(input_list) - 1:
if input_list[idx] > input_list[idx + 1]:
input_list[idx], input_list[idx + 1] = input_list[idx + 1], input_list[idx]
is_sorted = False
bubble_sort(numbers)
print('after ' + str(numbers)) |
285a15c0eac1f172f0f3fb033360219e79f6d4bd | dougal428/Daily-Python-Challenges | /Challenge 19.py | 3,082 | 3.84375 | 4 | #Question 19
#This problem was asked by Facebook.
#A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost while
#ensuring that no two neighboring houses are of the same color.
#Given an N by K matrix where the nth row and kth column represents the cost to build the nth house with kth color,
#return the minimum cost which achieves this goal.
#Answer 19
#import sys module
import sys
#cretae functions which takes in matrix, and other input where num houses all in matrix, and colours just in the row
def get_minimum_painting_cost(cost_matrix, num_houses, num_colors):
#return 0 if no matric
if not cost_matrix:
return 0
#set house price to 0
prev_house_min = 0
#set indedx to -1 so works
prev_house_min_index = -1
#set previouse house price to 0
prev_house_second_min = 0
#loop through the matrix
for i in range(num_houses):
#make variables maximum int size
curr_house_min = sys.maxsize
curr_house_second_min = sys.maxsize
#set index to 0
curr_house_min_index = 0
#loop through the row
for j in range(num_colors):
#if index equal to value in colours
if prev_house_min_index == j:
#then make coord in matrix plus the previos house second min
cost_matrix[i][j] += prev_house_second_min
else:
#otherwise make coord in matrix plus the previos house min
cost_matrix[i][j] += prev_house_min
#if current hose min greater then coordinate value in matrux
if curr_house_min > cost_matrix[i][j]:
#then set the second min of house to old minmum
curr_house_second_min = curr_house_min
#and the new min to the coord value in matrix
curr_house_min = cost_matrix[i][j]
#and replade the index woth the j row index
curr_house_min_index = j
#but if curr house min less or same then, and the second min value grreater then coord in matirx
elif curr_house_second_min > cost_matrix[i][j]:
#make second min value the same as coord in cost matrix
curr_house_second_min = cost_matrix[i][j]
#rearrange prev house min the current house min
prev_house_min = curr_house_min
#second minum the other second minum
prev_house_second_min = curr_house_second_min
#and the index new one as well
prev_house_min_index = curr_house_min_index
#return min value in matrix
return min(cost_matrix[num_houses - 1])
cost_matrix = \
[[7, 7, 8, 6, 1, 2],
[5, 6, 7, 2, 4, 3],
[1, 7, 4, 9, 7, 6],
[10, 1, 4, 5, 9, 1],
[10, 1, 4, 5, 9, 8],
[10, 1, 4, 5, 9, 9],
[1, 7, 4, 9, 7, 6],]
get_minimum_painting_cost(cost_matrix,
len(cost_matrix), len(cost_matrix[0]))
|
fb86da14c1eabad139837643f81093f233ffeaa7 | joshianshul2/Python | /arrayfac.py | 251 | 3.703125 | 4 | n=int(input("Enter a No in List "))
a=[]
f=1
print("Enter a No in Array ")
for i in range(n) :
x=int(input())
a.append(x)
for i in range(n):
f=1
b=a[i]
while b>=1 :
f=f*b
b-=1
print("Factorial No is :",f)
|
70086aae3b4f078999a46020021e27296baef025 | hyejun18/daily-rosalind | /prepare/template_scripts/algorithmic-heights/CC.py | 595 | 3.59375 | 4 | ##################################################
# Connected Components
#
# http://rosalind.info/problems/CC/
#
# Given: A simple graph with n <= 10^3 vertices
# in the edge list format.
#
# Return: The number of connected components in
# the graph.
#
# AUTHOR : dohlee
##################################################
# Your imports here
# Your codes here
if __name__ == '__main__':
# Load the data.
with open('../../datasets/rosalind_CC.txt') as inFile:
pass
# Print output
with open('../../answers/rosalind_CC_out.txt', 'w') as outFile:
pass
|
7837432a247ea8553f85e18afd55b490641b8519 | mohsas/PythonScripts | /w2z6.py | 494 | 3.765625 | 4 | <#EBieleninikPWr WIZ136. Napisać program, który tworzy listę 20 liczb
wg poniższego schematu:fn= 2 dla n = 0
1 dla n = 1
fn-1+ fn-2 dla n > 2
Na podstawie pierwszej listy tworzy listę drugą wypełnioną wg schematuf2/f1, f3/f2, ........ fn/fn-1Wyświetla obie listy.Uwaga: Wykorzystać informacje
o listach zamieszczone w pliku Python_cz_2
#>
def Fibonacci(n):
t=[0]x20
f0=2
f1=1
for i in range(1,20):
fn=f0+f1
f1=f0
f0=fn
set |
6ec9aeef4a23f6522b65f6a1af01eeec9664973c | nyashasimango/Practical-Security- | /Lab+Assignment+Ceaser+Cipher.py | 3,752 | 4.15625 | 4 |
# coding: utf-8
# In[4]:
#Function to encrypt
def encrypt(a,b):
h=int(a)
i=int(b)
result=((i+h)%26)
return result
#Function to decrypt
def decrypt(a,b):
h=int(a)
i=int(b)
result=((i-h)%26)
return result
#Function to start execution
def calculate():
x=3
v= int(input("select (1.) To encrypt (2.) To encrypt (3.) To exit :"))
if(v==1):
z=input("input string to encrypt :")
for words in z:
g=convert(words)
answer=encrypt(x,g)
final=converts(answer)
print(final,end='')
elif(v==2):
z=input("input string to decrypt :")
for words in z:
g=convert(words)
answer=decrypt(x,g)
final=converts(answer)
print(final,end='')
else:
print("about to exit")
#Function to convert a letter to int equiv
def convert(letter):
if (letter=="a" or letter=="A" ):
equiv=0
elif (letter=="b" or letter=="B" ):
equiv=1
elif (letter=="c" or letter=="C" ):
equiv=2
elif (letter=="d" or letter=="D" ):
equiv=3
elif (letter=="e" or letter=="E" ):
equiv=4
elif (letter=="f" or letter=="F" ):
equiv=5
elif (letter=="g" or letter=="G" ):
equiv=6
elif (letter=="h" or letter=="H" ):
equiv=7
elif (letter=="i" or letter=="I" ):
equiv=8
elif (letter=="j" or letter=="J" ):
equiv=9
elif (letter=="k" or letter=="K" ):
equiv=10
elif (letter=="l" or letter=="L" ):
equiv=11
elif (letter=="m" or letter=="M" ):
equiv=12
elif (letter=="n" or letter=="N" ):
equiv=13
elif (letter=="o" or letter=="O" ):
equiv=14
elif (letter=="p" or letter=="P" ):
equiv=15
elif (letter=="q" or letter=="Q" ):
equiv=16
elif (letter=="r" or letter=="R" ):
equiv=17
elif (letter=="s" or letter=="S" ):
equiv=18
elif (letter=="t" or letter=="T" ):
equiv=19
elif (letter=="u" or letter=="U" ):
equiv=20
elif (letter=="v" or letter=="V" ):
equiv=21
elif (letter=="w" or letter=="W" ):
equiv=22
elif (letter=="x" or letter=="X" ):
equiv=23
elif (letter=="y" or letter=="Y" ):
equiv=24
elif (letter=="z" or letter=="Z" ):
equiv=25
else:
print("letter not found in the Z26 universe")
return equiv
#Function to convert an int to letter equiv
def converts(equiv):
if (equiv==0):
letter="a"
elif (equiv==1):
letter="b"
elif (equiv==2):
letter="c"
elif (equiv==3):
letter="d"
elif (equiv==4):
letter="e"
elif (equiv==5):
letter="f"
elif (equiv==6):
letter="g"
elif (equiv==7):
letter="h"
elif (equiv==8):
letter="i"
elif (equiv==9):
letter="j"
elif (equiv==10):
letter="k"
elif (equiv==11):
letter="l"
elif (equiv==12):
letter="m"
elif (equiv==13):
letter="n"
elif (equiv==14):
letter="o"
elif (equiv==15):
letter="p"
elif (equiv==16):
letter="q"
elif (equiv==17):
letter="r"
elif (equiv==18):
letter="s"
elif (equiv==19):
letter="t"
elif (equiv==20):
letter="u"
elif (equiv==21):
letter="v"
elif (equiv==22):
letter="w"
elif (equiv==23):
letter="x"
elif (equiv==24):
letter="y"
elif (equiv==25):
letter="z"
else:
print("about to exit hee")
return letter
calculate()
# In[ ]:
# In[ ]:
|
3cd6ed59195671eeb146f1545860aabce47ece9e | SonaliChaudhari/Chaudhari_Sonali_spring2017 | /Assignmen_3_001285029/Q2/Q2_1_Final.py | 1,010 | 3.5625 | 4 |
# coding: utf-8
# # Question 2 Part 1
# In[1]:
#importing all the required lib
import string
import csv, sys
from pandas import Series, DataFrame
import pandas as pd
# In[2]:
# reading the csv file using pandas
df = pd.read_csv('Data/employee_compensation.csv')
# Retrieving only the required columns
s = pd.DataFrame(df[['Organization Group','Department','Total Compensation']])
# Grouping the entries by Department and summing the total compensation for a particular department
s['Total'] = s.groupby(['Department', 'Organization Group'])['Total Compensation'].transform('sum')
# In[3]:
# Eliminating duplicate columns
s = s.drop_duplicates(subset=['Department', 'Organization Group']) #, keep=False)
# In[4]:
## Retrieving only the required columns
p = s[['Organization Group','Department','Total']]
# In[5]:
# Displaying the final output using head()
p.head(10)
# In[7]:
# Storing the result in the csv
with open('Q2_Part1.csv', 'a') as csvfile:
p.to_csv(csvfile, header=True)
|
92e80904bfe060dbf72fb08d2ce94f864cc3f1e4 | MukundaRachamalla/veggie_store | /veggiestore.py | 3,651 | 4.21875 | 4 | print("**********welcome to veggie store**********")
cart = {}
def menu():
mainmenu()
def mainmenu():
print("vegetables:price per kg")
avail_veg = {"carrot":50,"onion":30,"brinjal":30,"tomato":60,"":"",}
print(avail_veg)
choose =input("select vegetables you want to buy")
if choose == "carrot" :
carrot()
elif choose == "onion":
onion()
elif choose == "tomato":
tomato()
elif choose == "brinjal":
brinjal()
else:
print ("invalid choice")
mainmenu()
def carrot():
print("price per kg = 50/-")
quantity = int(input("select the kg's you need: "))
tot_price = 50 * quantity
print("the total price of carrots is -----", tot_price)
select = input("confirm your choice?y/n: ")
if select == "Y" or select =="y":
name = "carrot"
cart[name]= tot_price
print("successfully added to cart")
print("do u like to shop more?Y/N")
ca = input()
if ca == "y" or ca == "Y":
mainmenu()
elif ca == "N" or ca == "n":
cart_item()
else:
print("inavalid choice")
elif select == "n" or select =="N":
mainmenu()
def cart_item():
print(cart)
val = cart.values()
tot_val = sum(val)
print("total value of the cart", tot_val)
print("do you want to continue shopping y/n:")
choice_3 = input()
if choice_3 is "Y" or choice_3 is "y":
mainmenu()
elif choice_3 is "N" or choice_3 is "n":
print("thankyou for shopping / bye...")
else:
print("invalid input")
cart_item()
def onion():
print("price per kg = 30/-")
quantity = int(input("select the kg's you need: "))
tot_price = 30 * quantity
print("the total price of carrots is -----", tot_price)
select = input("confirm your choice?y/n: ")
if select == "Y" or select =="y":
name = "onion"
cart[name]= tot_price
print("successfully added to cart")
print("do u like to shop more?Y/N")
on = input()
if on == "y" or on == "Y":
mainmenu()
elif on == "N" or on == "n":
cart_item()
else:
print("inavalid choice")
elif select == "n" or select =="N":
mainmenu()
def tomato():
print("price per kg = 30/-")
quantity = int(input("select the kg's you need: "))
tot_price = 30 * quantity
print("the total price of tomato is -----", tot_price)
select = input("confirm your choice?y/n: ")
if select == "Y" or select =="y":
name = "tomato"
cart[name]= tot_price
print("successfully added to cart")
print("do u like to shop more?Y/N")
to = input()
if to == "y" or to == "Y":
mainmenu()
elif to == "N" or to == "n":
cart_item
else:
print("inavalid choice")
elif select == "n" or select =="N":
mainmenu()
def brinjal():
print("price per kg = 40/-")
quantity = int(input("select the kg's you need: "))
tot_price = 40 * quantity
print("the total price of brinjal is -----", tot_price)
select = input("confirm your choice?y/n: ")
if select == "Y" or select =="y":
name = "brinjal"
cart[name]= tot_price
print("successfully added to cart")
print("do u like to shop more?Y/N")
br = input()
if br == "y" or br == "Y":
mainmenu()
elif br == "N" or br == "n":
cart_item()
else:
print("inavalid choice")
elif select == "n" or select =="N":
mainmenu()
menu() |
2302452868b51ca7a15f7d1bbff43378dfaca150 | vova0808/KPI-Python-tasks | /lab4_2.py | 456 | 4.0625 | 4 | """
Input data: an arbitrary, greater than zero quantity of arguments
Arguments may be a numbers or a strings, that may contain numbers and letters
without spaces
Output: a string, that consisiting of recieved values in reversible order,
recorded through a gap. The space in the end of string is absent.
"""
import sys
user_input = sys.argv[1:]
user_input = user_input[::-1]
user_input = " ".join(user_input)
print user_input
|
c08d4d681005185bc85e521e05eb12f46fc6da02 | Louisee607/Projects | /Projects/exo4.py | 665 | 3.8125 | 4 | import matplotlib.pyplot as plt
quantity= []
y_utility= []
print('Please enter a product')
product = input()
print('Please enter the maximum quantity')
max = int(input())
i = 0
while (i < max):
print('For',max - i,product,' what added level hapiness do you ?')
quantity.append(max - i)
y_utility.append(int(input()))
i = i + 1
y_utility.reverse()
print (y_utility)
print(quantity)
plt.plot(y_utility,quantity, marker='o', markerfacecolor='blue', markersize=12, color='skyblue', linewidth=4)
plt.axis([y_utility[0] - 2 ,y_utility[i - 1] + 2, 0, max + 2 ])
plt.ylim(0, max + 2, y_utility[0] , y_utility[i - 1] + 2)
plt.ylabel('utility')
plt.show()
|
1c922b07b6b1f011b91bc75d68ece9b8e2958576 | Leah36/Homework | /python-challenge/PyPoll/Resources/PyPoll.py | 2,168 | 4.15625 | 4 | import os
import csv
#Create CSV file
election_data = os.path.join("election_data.csv")
#The list to capture the names of candidates
candidates = []
#A list to capture the number of votes each candidates receives
num_votes = []
#The list to capture the number of votes each candidates gather
percent_votes = []
#The counter for the total number of votes
total_votes = 0
with open(election_data, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
csv_header = next(csvreader)
for row in csvreader:
#Add to our vote-countr
total_votes += 1
#If the candidate is not on our list, add his/her name to our list, along with
#a vote in his/her name.
#If he/she is already on our list, we will simply add a vote in his/her name.
if row[2] not in candidates:
candidates.append(row[2])
index = candidates.index(row[2])
num_votes.append(1)
else:
index = candidates.index(row[2])
num_votes[index] += 1
#Add to percent_votes list
for votes in num_votes:
percentage = (votes/total_votes) * 100
percentage = round(percentage)
percentage = "%.3f%%" % percentage
percent_votes.append(percentage)
#Find the winning candidate
winner = max(num_votes)
index = num_votes.index(winner)
winning_candidate = candidates[index]
#Display the results
print("Election Results")
print("------------")
print(f"Total Votes:{str(total_votes)}")
print("------------")
for i in range(len(candidates)):
print(f"{candidates[1]}: {str[percent_votes[i])} ({str(num_votes[i])})")
print("-----------")
print(f"Winner: {winning_candidate}")
print("----------")
#Print to a text file
output = open("output.txt", "w")
line1 = "Election Results"
line2 = "----------"
line3 = str(f"Total Votes: {str(total_votes)}")
line4 = str("----------")
output.write('{}\n{}\n{}\n{}\n'.formate(line1, line2, line3, line4))
for i in range(len(candidates)):
line = str(f"{candidate[i]}: {str(percent_votes[i])} ({str(num_votes[i])})")
output.write('{}\n'.format(line))
line5 = "-----------"
line6 = str(f"Winner: {winning_candidate}")
line7 = "-----------"
output.write('{}\n{}\n{}\n'.format(line5, line6,line7))
|
92128117095fef38864f9a86a2298b4eea9a7829 | Taraslut/cs50_train | /week6/demo_f_float.py | 88 | 3.671875 | 4 |
change = int(input("Enter your change >> "))
print(f"In 10 years you have {change}") |
f9f415c527cd91765921a9f7d2b66b4634e9e598 | richnakasato/ctci-py | /3.1.three_in_one.0.py | 2,544 | 3.5 | 4 | import random
class TripleStack():
def __init__(self):
self.data = [None] * 9
self.stack_max = 3
self.growth = 2
self.stack_starts = [x * self.stack_max for x in range(3)]
self.stack_sizes = [0] * 3
def __str__(self):
outstring = ''
for idx in range(3):
start = self.stack_starts[idx]
end = start + self.stack_sizes[idx]
outstring += str(start) + ' ' + \
str(end) + ' ' + \
str(self.data[start:end]) + '\n'
return outstring
@staticmethod
def is_valid_idx(idx):
return 0 <= idx <= 2
def push(self, idx, data):
if self.is_full(idx):
raise Exception('full stack!')
else:
start = self.stack_starts[idx]
top = start + self.stack_sizes[idx]
self.data[top] = data
self.stack_sizes[idx] += 1
def pop(self, idx):
if self.is_empty(idx):
raise Exception('empty stack!')
else:
start = self.stack_starts[idx]
last_top = start + self.stack_sizes[idx] - 1
temp = self.data[last_top]
self.stack_sizes[idx] -= 1
return temp
def top(self, idx):
if self.is_empty(idx):
raise Exception('empty stack!')
else:
start = self.stack_starts[idx]
last_top = start + self.stack_sizes[idx] - 1
return self.data[last_top]
def is_empty(self, idx):
if not TripleStack.is_valid_idx(idx):
raise Exception('invalid stack!')
else:
return self.stack_sizes[idx] == 0
def is_full(self, idx):
if not TripleStack.is_valid_idx(idx):
raise Exception('invalid stack!')
else:
return True if self.stack_sizes[idx] == self.stack_max else False
def main():
arr = [x for x in range(9)]
print(arr)
ts = TripleStack()
count = 0
for item in arr:
idx = item//3
ts.push(idx, item)
print(idx)
print(ts)
# test append 0
test_append = TripleStack()
idx = 2
test_append.push(idx, 9)
test_append.push(idx, 99)
test_append.push(idx, 999)
print(test_append)
print(test_append.top(idx))
print(test_append.pop(idx))
print(test_append.top(idx))
print(test_append.pop(idx))
print(test_append.top(idx))
print(test_append.pop(idx))
print(test_append)
if __name__ == "__main__":
main()
|
0614b7b5abd5368e3c15150b9cc21817ac9d3496 | namnamgit/pythonProjects | /aumento_salariov3.py | 609 | 3.78125 | 4 | # rodrigo, apr2513
# escreva um programa que pergunte o salário do funcionário e calcule o valor do aumento.
# para salários superiores a r$ 1.250,00 calcule um aumento de 10%. para os inferiores ou iguais, de 15%
while True:
salario = float(input('Salário: '))
if salario > 1250.00:
aumento = salario * 10 / 100
salario_atual = salario + aumento
print('Aumento de %.2f / Salário atual: %.2f\n' % (aumento, salario_atual))
if salario <= 1250.00:
aumento = salario * 15 / 100
salario_atual = salario + aumento
print('Aumento de %.2f / Salário atual: %.2f\n' % (aumento, salario_atual))
|
6ce6baee09019f8e127601c54ad3f728bac53183 | nishantchaudhary12/w3resource_solutions_python | /Dictionary/concatenatingDict.py | 359 | 3.765625 | 4 | #Write a Python script to concatenate following dictionaries to create a new one
def concatenate(dic1, dic2, dic3):
dic_new = dict()
for dic in dic1, dic2, dic3:
dic_new.update(dic)
print(dic_new)
if __name__ == '__main__':
dic1 = {1: 10, 2: 20}
dic2 = {3: 30, 4: 40}
dic3 = {5: 50, 6: 60}
concatenate(dic1, dic2, dic3) |
855472636b00dff2a60b752663b3b4c111e359ca | Galahad3x/AdventOfCode2020 | /day01/parse_input.py | 182 | 3.515625 | 4 | filename = "input.txt"
inputs = []
with open(filename, "r") as f:
for line in f.readlines():
if line != '\n':
inputs.append(line[:-1])
print("[" + ",".join(inputs) + "]")
|
b3485a4c37b6db7f00790d73a340f270d58c356d | AlexandrZhytenko/solve_tasks | /word_game.py | 614 | 4.15625 | 4 | # function will receive a positive integer and return:
# "Fizz Buzz" if the number is divisible by 3 and by 5
# "Fizz" if the number is divisible by 3
# "Buzz" if the number is divisible by 5
# The number as a string for other cases
def word_game(number):
result = ["Fizz Buzz", "Fizz", "Buzz"]
if number % 3 == 0 and number % 5 == 0:
return result[0]
elif number % 3 == 0:
return result[1]
elif number % 5 == 0:
return result[2]
return str(number)
if __name__ == "__main__":
print word_game(15)
print word_game(6)
print word_game(5)
print word_game(7) |
298a2b4897fed56f276d274fb028e64c11e8e54a | chuliuT/Python3_Review | /LeetCode小卡片/code/转盘锁.py | 1,322 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 22 22:37:09 2020
@author: TT
"""
from typing import List
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
deadends = set(deadends)#转为 set 保证唯一
if '0000' in deadends: return -1 # 初始的值不能为 deadends
# BFS
queue=[('0000',0)]#初始位置,放在队列中 用一个元组(0000,扭动次数)
while queue:
# cnt=1
node,step= queue.pop(0)#取出队列的队首的位置
for i in range(4):#遍历密码锁上的 四个位置
for add in (1, -1):# 扭动一下,当前的值 注意是进位的原因,那么下一位则要减去1
cur = node[:i] + str((int(node[i]) + add) % 10) + node[i + 1:]#当前密码锁的状态
# print(cur)
if cur == target:# 如果是 等于target的值
return step+1
if not cur in deadends:#不在死亡数字里,
queue.append((cur,step+1))#则往队列里添加
deadends.add(cur)#为了不重复
return -1
obj=Solution()
deadends = ["8888"]
target = "0009"
ans=obj.openLock(deadends, target)
print(ans) |
cbf52a4106f02879428506a99236d6bfd55d291c | sanjoycode97/python-programming-beginners | /python tutorial/arithmatic progression/print the sum of n/python programming practice/series.py | 169 | 3.78125 | 4 | sum=0
for i in range(1,11):
sum=sum+1/i
print(1/i)
print(sum)
def fact(i):
fact=1
for x in range(1,i+1):
fact=fact*x
return fact
ft=fact(i)
print(ft) |
bcbc621c951529f4c57a0ed80521f44cb8cf103b | camila-2301/EXAMEN-FINAL-PYTHON | /TRABAJO FINAL ADRIANA ARANIBAR PYTHON/ARCHIVOS PYTHON/MODULO3/credit.py | 607 | 3.5 | 4 | def prob5(numero):
AMEX = [34, 37]
MASTERCARD = [51, 52, 53, 54 , 55]
def convert(numero2):
lista = [ int(x) for x in list(str(numero2)) ]
return sum(lista)
num = str(numero)
size = len(num)
suma = 0
for i in range(size-2, -1, -2):
suma += convert(int(num[i])*2)
for i in range(size-1, -1, -2):
suma += int(num[i])
if suma % 10 == 0:
if int(num[0]) == 4:
return "VISA"
elif int(num[0:2]) in AMEX:
return "AMEX"
elif int(num[0:2]) in MASTERCARD:
return "MASTERCARD"
return "INVALID"
numTarjeta = int(input("Number: "))
print(prob5(numTarjeta)) |
3c380645262b8c236620f4e23db990b0107d99b0 | SNithiyalakshmi/pythonprogramming | /Beginnerlevel/rev.py | 77 | 3.8125 | 4 | b=int(input("enter the number"))
print("\n",''.join(list(reversed(str(b)))))
|
b9342b4aa75e39854d2bfc10991a48ca9083f449 | sonushakya9717/Hyperverge__learnings | /sorting/merge_sort.py | 687 | 4.03125 | 4 | ############ Merge Sort #########
def merge(left,right):
sorted_lst=[]
i=0
j=0
while i<len(left) and j<len(right):
if left[i]<right[j]:
sorted_lst.append(left[i])
i+=1
else:
sorted_lst.append(right[j])
j+=1
while i<len(left):
sorted_lst.append(left[i])
i+=1
while j<len(right):
sorted_lst.append(right[j])
j+=1
return sorted_lst
def merge__sort(a):
if len(a)==1:
return a
else:
mid=len(a)//2
left=merge__sort(a[:mid])
right=merge__sort(a[mid:])
return merge(left,right)
a=[9,8,7,5,6,4,1]
print(merge__sort(a))
|
d7de9f54e70e6ed79128dd545a6261ed18c64340 | hideyk/CodeWars | /Python/Detect Pangram.py | 306 | 3.96875 | 4 | import string
def is_pangram(s):
alphabet = set(string.ascii_lowercase)
return set(s.lower()) >= alphabet
def is_pangram2(s):
return set(string.lowercase) <= set(s.lower())
text = "The quick brown fox jumps over the lazy dog"
text_is_pangram = is_pangram(text)
print(text_is_pangram) |
aab4da2d4a91d9eca0b71c77a88962938a2529b0 | Swati213/pythonbasic | /billing/discount.py | 215 | 3.640625 | 4 | item = input("Enter the total item = ")
discount = input("Enter the discount allowed = ")
amount = input("Enter the total amount = ")
grandtotal = amount-(amount*discount/100)
print grandtotal, "Grand total"
|
c37be9530016679e1b6ad28fe215e52e5ad2a03d | JuanRx19/TallerFinal | /Ejercicio 1.py | 155 | 3.703125 | 4 | b = eval(input("Por favor digite la base: "))
h = eval(input("Por favor digite la altura: "))
a = (b*h)/2
print("El area del triangulo es: " + str(a)) |
fe76456be7816873ed9a8349c4e5f93e3f48e10e | iqballm09/python_proj-team-dta | /module/ConvNumSys.py | 4,839 | 3.71875 | 4 | # Program Konversi Satuan Bilangan
# Pengaturan Input diatur dalam program utama apakah string/int
class NumberSysConverter:
def __init__(self):
self.__input = 0
def destodes(self, val):
self.__input = val
return self.__input
def hextohex(self, val):
self.__input = val
return self.__input
def octtooct(self, val):
self.__input = val
return self.__input
def bintobin(self, val):
self.__input = val
return self.__input
# Fungsi Desimal To Biner
def destobin(self, val):
self.__input = val
self.__hasil = "{0:b}".format(int(self.__input))
return self.__hasil
# Fungsi Desimal To Octal
def destookt(self, val):
self.__input = val
self.__hasil = 0
self.__count = 1
while (self.__input != 0):
self.__remainder = self.__input % 8
self.__hasil += self.__remainder * self.__count
self.__count *= 10
self.__input //= 8
return self.__hasil
# Fungsi Desimal To Heksadesimal
def destohex(self, val):
self.__input = val
self.__hasil = "{0:X}".format(int(self.__input))
return self.__hasil
# Fungsi Biner To Desimal
def bintodes(self, val):
self.__input = val
self.__hasil = int(str(self.__input), 2)
return self.__hasil
# Fungsi Biner To Octal
def bintooct(self, val):
self.__input = val
self.__sementara = int(str(self.__input), 2)
self.__hasil = 0
self.__count = 1
while (self.__sementara != 0):
self.__remainder = self.__sementara % 8
self.__hasil += self.__remainder * self.__count
self.__count *= 10
self.__sementara //= 8
return self.__hasil
# Fungsi Biner To Hexadesimal
def bintohex(self, val):
self.__input = val
self.__sementara = int(str(self.__input), 2)
self.__hasil = "{0:X}".format(int(self.__sementara))
return self.__hasil
# Fungsi Hexadesimal To Desimal
def hextodes(self, val):
self.__input = val
self.__hasil = int(str(self.__input), 16)
return self.__hasil
# Fungsi Hexadesimal To Biner
def hextobin(self, val):
self.__input = val
self.__sementara = int(str(self.__input), 16)
self.__hasil = "{0:b}".format(int(self.__sementara))
return self.__hasil
# Fungsi Hexadesimal To Octal
def hextooct(self, val):
self.__input = val
self.__sementara = int(str(self.__input), 16)
self.__hasil = 0
self.__count = 1
while (self.__sementara != 0):
self.__remainder = self.__sementara % 8
self.__hasil += self.__remainder * self.__count
self.__count *= 10
self.__sementara //= 8
return self.__hasil
# Fungsi Octal To Decimal
def octtodec(self, val):
self.__input = val
return int(self.__input, 8)
# Fungsi Octal To Biner
def octtobin(self, val):
self.__input = val
self.__sementara = int(self.__input, 8)
self.__hasil = bin(self.__sementara)
return self.__hasil[2:]
# Fungsi Octal To Heksadesimal
def octtohex(self, val):
self.__input = val
self.__sementara = int(self.__input, 8)
self.__hasil = "{0:X}".format(int(self.__sementara))
return self.__hasil
def selectFunc(self, val, key):
if key == "DecimalDecimal":
result = self.destodes(val)
elif key == "DecimalBinary":
result = self.destobin(val)
elif key == "DecimalOctal":
result = self.destookt(val)
elif key == "DecimalHexa":
result = self.destohex(val)
elif key == "BinaryDecimal":
result = self.bintodes(val)
elif key == "BinaryBinary":
result = self.bintobin(val)
elif key == "BinaryOctal":
result = self.bintooct(val)
elif key == "BinaryHexa":
result = self.bintohex(val)
elif key == "HexaDecimal":
result = self.hextodes(val)
elif key == "HexaBinary":
result = self.hextobin(val)
elif key == "HexaOctal":
result = self.hextooct(val)
elif key == "HexaHexa":
result = self.hextohex(val)
elif key == "OctalOctal":
result = self.octtooct(val)
elif key == "OctalBinary":
result = self.octtobin(val)
elif key == "OctalDecimal":
result = self.octtodec(val)
elif key == "OctalHexa":
result = self.octtohex(val)
return result
# #Ini Program Uji Coba Bisa Diabaikan
# obj = konvbilangan('1010')
# obj_aa = obj.bintobin()
# print(obj_aa)
|
3e972116cb124d8175735b008efcd2ec1df8ff80 | brucekevinadams/Python | /NormalDistribution.py | 1,398 | 4.21875 | 4 | # Python 3 code
# Bruce Adams
# austingamestudios.com
# ezaroth@gmail.com
# Program problem from Hackerrank.com
# In a certain plant, the time taken to assemble a car is a random variable, X,
# having a normal distribution with a mean of 20 hours and a standard deviation of 2 hours.
# What is the probability that a car can be assembled at this plant in:
#
# Less than 19.5 hours?
# Between and 20 and 22 hours?
# Input Format
#
# There are 3 lines of input (shown below):
#
# 20 2
# 19.5
# 20 22
#
# The first line contains space-separated values denoting the respective mean and standard deviation for X.
# The second line contains the number associated with question 1. The third line contains 2 space-separated
# values describing the respective lower and upper range boundaries for question 2.
#
# Output Format
#
# There are two lines of output. Your answers must be rounded to a scale of decimal places (i.e., format):
#
# On the first line, print the answer to question 1 (i.e., the probability that a car can be assembled in less than 19.5 hours)
# On the second line, print the answer to question 2 (i.e., probability that a car can be assembled in between 20 to 22 hours)
import math
mean, std = 20, 2
cdf = lambda x: 0.5 * (1 + math.erf((x - mean) / (std * (2 ** 0.5))))
# Less than 19.5
print('{:.3f}'.format(cdf(19.5)))
# Between 20 and 22
print('{:.3f}'.format(cdf(22) - cdf(20)))
|
c6a7ca613a9ca94fca9947f02ea16a2b8670842a | inergoul/boostcamp_peer_session | /coding_test/testdome_python_interview_questions/3_BinarySearchTree/solution_anna.py | 412 | 3.65625 | 4 | import collections
Node = collections.namedtuple('Node', ['left', 'right', 'value'])
def contains(root, value):
dq = collections.deque([root])
while dq:
cur = dq.popleft()
if not cur:
continue
if cur.value == value:
return True
if cur.value > value:
dq.append(cur.left)
else:
dq.append(cur.right)
return False
|
713b611e63ca60799b7b775272f54da86ae7ee6c | JpBongiovanni/PythonFunctionLibrary | /commaCode.py | 580 | 4.09375 | 4 |
# def commaCode(list):
# for x in range(len(list)-1):
# print(list[x] + ",", end= " ", sep=', ')
# commaCode(['apples', 'bananas', 'tofu', 'cats'])
# def commaCode(list):
# print(*range(len(list)), sep=", ")
# commaCode(['apples', 'bananas', 'tofu', 'cats'])
def commaCode(list):
for x in range(len(list)-1):
print(list[x] + ",", end= " ", sep=', ')
# test = ''.join(list[:(len(list))-1])
test2 = ''.join(list[(len(list))-1:])
print('and ' + test2)
commaCode(['apples', 'bananas', 'tofu', 'cats', 'elephants', 'zebras', 'monkies'])
|
f75fad306ee7cdaf4cf588fb16c6c64c99e86bc6 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_3_neat/16_0_3_Q112_Program.py | 1,409 | 3.703125 | 4 | import sys
import os
from itertools import *
Out = open(os.path.dirname(os.path.abspath(__file__))+'/'+sys.argv[2],'w')
if sys.argv[1] == 'Test':
N, J = 6,3
elif sys.argv[1] == 'Small':
N, J = 16, 50
elif sys.argv[1] =='Large':
N, J = 32, 500
else:
print('Please enter one of the three options Test, Small or Large')
__name__==''
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
def isprime(n):
for m in range(2, int(n**0.5)+1):
if not n%m:
return m
return True
if __name__ == '__main__':
Out.write('Case #1: \n')
count = 0
S = powerset([i for i in range(1,N-1)])
for s in S:
print(s)
s = list(s)
if len(s)%2 != 0:
continue
if not sum([(-1)**x for x in s]) == 0:
continue
M = 10**(N-1)+1
for i in range(1,N-1):
if i in s:
M += 10**(N-1-i)
Out.write('{} {} {} {} {} {} {} {} {} {} \n'.format(M, 3, 2, 5, 2, 7, 2, 3, 2, 11))
#Numbers with the properties of M automatically produce jam coins with the above prime divisors.
count += 1
if count == J:
break
|
96d953fcdcc787ab8d45849d96d75773023859b3 | xingyazhou/Data-Structure-And-Algorithm | /DynamicProgramming/climbStairs.py | 1,278 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 29 11:24:36 2020
70. Climbing Stairs (Easy)
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Constraints:
1 <= n <= 45
@author: xingya
"""
class Solution(object):
"""
One can reach i step in one of the two ways:
1. Taking a single step from (i-1) step.
2. Taking a step of 2 from (i-2) step.
"""
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
f = [0] * (n+1)
f[1] = 1
f[2] = 2
for i in range(3,n+1):
f[i] = f[i-1] + f[i-2]
return f[n]
n = 3
s = Solution()
print(s.climbStairs(n))
# Output
# 3
"""
Runtime: 12 ms, faster than 95.34% of Python online submissions for Climbing Stairs.
Memory Usage: 13.4 MB, less than 5.25% of Python online submissions for Climbing Stairs.
"""
|
43d2382caa4d00514bce028adbfef36688b28b49 | ZainebPenwala/leetcode-solutions | /self_dividing_number.py | 955 | 4.15625 | 4 | '''A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
Also, a self-dividing number is not allowed to contain the digit zero.
Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.
Example 1:
Input:
left = 1, right = 22
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]'''
# Solution:
class Solution:
def selfDividingNumbers(self, left, right):
final = []
count = ''
for num in range(left, right+1):
if '0' not in str(num):
count = 0
for digit in str(num):
if num%int(digit) != 0:
count += 1
if count == 0:
final.append(num)
return final
sol = Solution()
print(sol.selfDividingNumbers(1, 22))
|
defd32cc6432d12f64ba0abee16531f28431c718 | Ivan-yyq/livePython-2018 | /day12/demon8.py | 506 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/29 23:55
# @Author : yangyuanqiang
# @File : demon8.py
import codecs
ENCODING = "utf-8"
with codecs.open("1.txt", "r", encoding=ENCODING) as f:
print(f.read())
a = lambda x: x*x
print(a)
print([x for x in range(1, 10) if x%2==0])
def startEnd(fun):
def wrap(name):
print("start")
fun(name)
print("end")
return wrap
@startEnd
def hello(name):
print("hello {0}".format(name))
hello("ajing") |
e83f41251e229f5df29ff4dd7f4718cdaca753cb | zacharydenton/montyhall | /montyhall.py | 1,180 | 3.796875 | 4 | #!/usr/bin/env python3
import random
def new_game():
game = [("closed", "goat"), ("closed", "goat"), ("closed", "car")]
random.shuffle(game)
return game
def others(game, choice):
return [i for i, _ in enumerate(game) if i != choice]
def closed(game):
return [i for i, (status, _) in enumerate(game) if status == "closed"]
def open(game, door):
open_door = ("open", game[door][1])
game[door] = open_door
return game
def simulate(swap=False, iterations=10000):
total = 0
success = 0
for _ in range(iterations):
total += 1
game = new_game()
choice = random.randrange(len(game))
goats = [i for i in others(game, choice) if game[i][1] == "goat"]
game = open(game, random.choice(goats))
if swap:
choice = [i for i in closed(game) if i != choice][0]
if game[choice][1] == "car":
success += 1
return success / total
def main():
standard = simulate(False)
swapped = simulate(True)
print("win probability (standard): {}".format(standard))
print("win probability (swapped): {}".format(swapped))
if __name__ == "__main__":
main()
|
e6c43eb53003b3c27c03efcb030a0d7203afccc2 | airje/codewars | /sprayingtrees.py | 358 | 3.640625 | 4 | def task(w,n,c):
dict={'Monday':'James', 'Tuesday':'John', 'Wednesday':'Robert',
'Thursday':'Michael', 'Friday':'William', 'Saturday':'James',
'Sunday':'John'}
for k,v in dict.items():
if k==w:
return f'It is {w} today, {v}, you have to work, you must spray {n} trees and you need {c*n} dollars to buy liquid' |
51677e0add84760f65c0a8c4fde7e3a82eeb92f4 | westgate458/LeetCode | /P0152.py | 2,105 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 20 14:50:31 2019
@author: Tianqi Guo
"""
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# maintain three running records
# minimum product including current number
# maximum product including current number
# the maximum product for answer
min_p, max_p, ans = 1, 1, None
# for each number in the list
for num in nums:
# calculate the two products
# product of previous maximum product with current number
p1 = max_p * num
# product of previous minimum product with current number
p2 = min_p * num
# new minimum product is to choose from
# 1) new minimum product starts from current number,
# 2) new minimum product includes previous numbers
min_p = min(num, p1, p2)
# new maximum product is to choose from
# 1) new maximum product starts from current number,
# 2) new maximum product includes previous numbers
max_p = max(num, p1, p2)
# update answer for maximum product if necessary
ans = max(max_p,ans)
# if num >= p1:
# if p1 >= p2:
# max_p, min_p = num, p2
# elif num >= p2:
# max_p, min_p = num, p1
# else:
# max_p, min_p = p2, p1
# else:
# if num >= p2:
# max_p, min_p = p1, p2
# elif p1 > p2:
# max_p, min_p = p1, num
# else:
# max_p, min_p = p2, num
# if max_p > ans:
# ans = max_p
return ans
tests = [[2,3,-2,4],
[-1,-2,-9,-6],
[-2,0,-2,-2],
[-2,0,-1],
[3,-1,4],
[-2]
]
test = Solution()
for nums in tests:
print nums, test.maxProduct(nums)
|
aabe12abfd09d1f6e8b71850eaddf64e797131d5 | aishwat/missionPeace | /graph/topologicalSort.py | 871 | 3.90625 | 4 | from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def topological_sort(self):
visited = [False] * self.V
stack = []
for i in range(self.V):
# print(self.graph)
if visited[i] == False:
self.dfs(i, visited, stack)
return stack
def dfs(self, vertex, visited, stack):
visited[vertex] = True
for adj in self.graph[vertex]:
if visited[adj] == False:
self.dfs(adj, visited, stack)
stack.insert(0, vertex)
g = Graph(6)
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
print(g.graph)
stack = g.topological_sort()
print(stack)
|
aaefaff964fcb0ed619bbf5b31803f86cc7bba0b | ethem5234/TICT-VrPROG-15 | /les04/ExtraOpdracht 4_1.py | 215 | 3.921875 | 4 | temp= eval(input('wat is de temperatuur vandaag: '))
if temp <= 0:
print('Het vries vandaag')
elif temp >0 and temp <= 15:
print('Het is koud vandaag')
elif temp >15:
print('Het is lekker vandaag') |
e7b7fc883dd87c9e4c3a81a3942b1a344db2beba | arthurdysart/HackerRank | /programming/algorithms/strings/the_love_letter_mystery/python_source.py | 4,609 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
HackerRank - The Love-Letter Mystery
https://www.hackerrank.com/challenges/the-love-letter-mystery
Created on Wed Dec 5 19:53:42 2018
@author: Arthur Dysart
"""
## REQUIRED MODULES
import sys
## MODULE DEFINITIONS
class Solution:
"""
Iteration over all characters in array.
Time complexity: O(n)
- Amortized traverse all elements of array
Space complexity: O(1)
- Update constant number of pointers
"""
def love_letter_mystery(self, n, a):
"""
Evaluate required palindrome moves for each string in array.
:param int n: number of strings in array
:param list[int] a: array of input strings
:return: minimum move counts for all input strings
:rtype: list[int]
"""
if (not n or
not a):
return list()
z = [self.count_palindrome_moves(s)
for s
in a]
return z
def count_palindrome_moves(self, s):
"""
Determine minimum character changes for palindrome transformation.
:param str s: target string
:return: minimum moves to transform target string into palindrome
:rtype: int
"""
if not s:
return 0
p = 0
n = len(s)
# Iterate over external pairs of characters
for i in range(0, n // 2, 1):
# Find left and right characters
l = s[i]
r = s[(n - 1) - i]
if l == r:
# Move to next character pair
continue
elif (l < r and
r != "a"):
# Add changes for right character
p += ord(r) - ord(l)
elif (l > r and
l != "a"):
# Add changes for left character
p += ord(l) - ord(r)
else:
# Fails character conversion
return -1
return p
class Solution2:
"""
Iteration over all characters in array.
Time complexity: O(n)
- Amortized traverse all elements of array
Space complexity: O(k)
- Amortized collect all characters in array for each input string
"""
def love_letter_mystery(self, n, a):
"""
Evaluate required palindrome moves for each string in array.
:param int n: number of strings in array
:param list[int] a: array of input strings
:return: minimum move counts for all input strings
:rtype: list[int]
"""
if (not n or
not a):
return list()
z = [self.count_palindrome_moves(s)
for s
in a]
return z
def count_palindrome_moves(self, s):
"""
Determine minimum character changes for palindrome transformation.
:param str s: target string
:return: minimum moves to transform target string into palindrome
:rtype: int
"""
if not s:
return 0
a = list(x for x in s)
l = 0
r = len(a) - 1
p = 0
while l < r:
if a[l] == a[r]:
# No change required
l += 1
r -= 1
elif (a[l] < a[r] and
a[r] != "a"):
# Modify right character
a[r] = chr(ord(a[r]) - 1)
p += 1
elif (a[l] > a[r] and
a[l] != "a"):
# Modify left character
a[l] = chr(ord(a[l]) - 1)
p += 1
else:
# Found character less than "a"
return -1
return p
class Input:
def stdin(self, sys_stdin):
"""
Imports standard input.
:param _io.TextIOWrapper sys_stdin: standard input
:return: number of input strings and input array of strings
:rtype: tuple[int, list[str]]
"""
inputs = [x for x in sys_stdin]
n = int(inputs[0])
a = [str(x)\
.strip("[]\n\"")
for x
in inputs[1:]]
return n, a
## MAIN MODULE
if __name__ == "__main__":
# Import exercise parameters
n, a = Input()\
.stdin(sys.stdin)
# Evaluate solution
z = Solution()\
.love_letter_mystery(n, a)
print(*z, sep = "\n")
## END OF FILE |
a3c23efec284f5d0f07895f07e839a9fdcc0c83b | prodseanb/Income-Expense-Budget-Analysis | /income_vs_expenses.py | 2,230 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 27 20:56:37 2021
Income/Expense Line Graph Budget Analysis
@author: Sean Bachiller
"""
import matplotlib.pyplot as plt
# plot 1 values
x1 = ["Month 1","Month 2","Month 3", "Month 4", "Month 5", "Month 6"]
y1 = []
# plot 2 values
x2 = ["Month 1","Month 2","Month 3", "Month 4", "Month 5", "Month 6"]
y2 = []
def income():
for i in range(1,7): # loop 6 times
try:
# Prompt for income
print('Enter the amount of income earned for month', i )
plot1 = float(input())
y1.append(plot1) # append to list
except ValueError:
y1.clear()
print('Invalid input.')
income()
while True: # validation -- if user input contains a string, list length will always be < 6
if len(y1) < 6:
y1.clear()
print('\nEvaluation incomplete. Only numeric values are allowed. Please try again.\n')
income()
else:
break
def expenses():
for i in range(1,7): # loop 6 times
try:
# Prompt for expenses
print('Enter the amount spent for month', i )
plot2 = float(input())
y2.append(plot2) # append to list
except ValueError:
y2.clear()
print('Invalid input.')
expenses()
while True: # validation -- if user input contains a string, list length will always be < 6
if len(y2) < 6:
y2.clear()
print('\nEvaluation incomplete. Only numeric values are allowed. Please try again.\n')
expenses()
else:
break
# plotting the points
plt.plot(x1, y1, label = "Income", color='green', marker='o', markerfacecolor='green', markersize=6)
plt.plot(x2, y2, label = "Expenses", color='red', marker='o', markerfacecolor='red', markersize=6)
# naming the x axis
plt.xlabel('evaluation period')
# naming the y axis
plt.ylabel('earned/spent')
# giving a title to my graph
plt.title('A 6-month income/expense budget analysis')
plt.legend() # show a legend
plt.show() # show the plot
|
8a7ac82a81fc894595e299d93b9fc7f42850dea7 | cristinamais/exercicios_python | /Exercicios Colecoes Python/exercicio 19 - secao 07 - p1.py | 268 | 3.71875 | 4 | """
19 - Faça um vetor de tamanho 50 preenchido com o seguinte valor: (i+5*i)%(i+1), sendo i a posição do elemento no vetor.
Em seguida imprima o vetor na tela.
"""
vetor = []
for i in range(50):
vetor.append((i+5*i) % (i+1))
print(f'Vetor[{i}]:{vetor}')
|
35e1541e0d41081f37272c761716e05e55e6c901 | BomberDim/Python-practice | /examples№2/task3/v3pr11_and_17.py | 263 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
a = int(input("a = "))
b = int(input("b = "))
c = int(input("c = "))
if a % 2 == 0 or b % 2 == 0 or c % 2 == 0:
print("Имеются четные числа")
else:
print("Четных чисел нет")
|
0d09ccf67899a9189b9b2502f6b49e6e0bc1aea6 | fpischedda/lsystem | /src/core/user.py | 4,086 | 3.59375 | 4 | # module that define a User object
# a user has list of plants, a credit balance
# and a list of items to use
__author__ = "francescopischedda"
__date__ = "$27-mag-2011 17.04.07$"
from plant import Plant
from environment import Environment
from item import Item
def new_user(username, password, email):
"""
create a new user with a natural environment and a default plant
"""
u = User(username, password, email)
u.add_environment(Environment('natural'))
u.add_plant_to_environment(Plant.randomize_default(), 'natural')
u.add_item(Item('water-tank', 10, False))
u.add_item(Item('water-reserve', 10, True))
u.add_item(Item('magic-bottle', 100, True))
return u
class User(object):
@classmethod
def unserialize(cls, obj):
inst = cls(obj['username'], obj['password'], obj['email'])
for i in obj['items']:
inst.items[i['name']] = Item.unserialize(i)
for e in obj['environments']:
env = Environment.unserialize(e)
inst.environments[env.name] = env
for p in env.plants.values():
inst.plants[p.name] = p
return inst
def __init__(self, username, password, email):
self.username = username
self.password = password
self.email = email
self.environments = {}
self.plants = {}
#items are store as name=>count
#when an item count is <= 0 the entry is removed
self.items = {}
def add_item(self, item):
"""
add an item to the inventory
"""
try:
self.items[item.name].quantity + item.quantity
except KeyError:
self.items[item.name] = item
def use_magic_bottle(self, plant_name):
"""
returns 0 on success, 1 if the item is not found,
"""
if self.use_item('magic-bottle', 1) == 0:
return 1
try:
self.plants[plant_name].fill_water()
except KeyError:
return 2
#do one hour of light_on_cycle and one hour of light_off_cycle
times = 60
p = self.plants[plant_name]
while times > 0:
p.light_on_cycle(60)
p.light_off_cycle(60)
p.fill_water()
times -= 1
return 0
def use_item(self, item_name, quantity):
"""
try to use an item
returns the effectively used quantity
"""
try:
if self.items[item_name].usable is False:
return 0
self.items[item_name].quantity -= quantity
if self.items[item_name].quantity < 0:
quantity += self.items[item_name].quantity
del self.items[item_name]
except KeyError:
return 0
return quantity
def remove_item(self, item_name):
"""
remove an item from the inventory
"""
count = 0
try:
count = self.items[item_name]
finally:
count -= 1
if count > 0:
self.items[item_name] = count
else:
del self.items[item_name]
def add_environment(self, environment):
self.environments[environment.name] = environment
def add_plant_to_environment(self, plant, environment_name):
try:
self.environments[environment_name].add_plant(plant)
self.plants[plant.name] = plant
except KeyError:
print "unavailable environment"
def add_plant(self, plant):
self.plants[plant.name] = plant
def serialize(self):
envs = [e.serialize() for e in self.environments.values()]
plants = [p.serialize() for p in self.plants.values()]
items = [i.serialize() for i in self.items.values()]
ret = {'username': self.username,
'password': self.password,
'email': self.email,
'plants': plants,
'environments': envs,
'items': items}
return ret
|
6f617328ea10c433af7511f65d809cc5dba90986 | jachymb/python2modelica_tests | /testcases/test_0005.py | 249 | 3.71875 | 4 | # Simple test for if statement.
# Returns the absolute value of a 'float'.
# The code is intentionaly redundant to use
# the 'elif' branch.
def abs0005(r):
if r > 0:
return r
elif r < 0:
return -r
else
return 0
|
3dadbed299ace690289242b034fcc6f141cc478f | ereynolds123/introToProgramming | /password.py | 400 | 4.25 | 4 | while True:
password = input("Enter your new password: ")
while True:
if len(password) >=7:
break
print("Your password must be at least 7 characters.")
password= input("Enter your new password: ")
secondPassword = input("Enter your password again: ")
if secondPassword == password:
break
print("Your new password is: ", password) |
545f2e965205889354480b64dff0368da70bcdb7 | TravisDvis/SURF2020 | /Gissenger/Rescale.py | 546 | 3.65625 | 4 | import numpy as np
def rescale(xMatrix):
while True:
rescaled_xMatrix = np.array(xMatrix,copy=True)
x = str(input("Do you want to rescale the dipole values? (Y/N): "))
if x == "Y" or x == "y":
max = np.mean(abs(rescaled_xMatrix[1][:]))
rescaled_xMatrix[1][:] = rescaled_xMatrix[1][:]/max
break
elif x == "N" or x == "n":
break
else:
print("Try again. Please enter \"Y/y\" or \"N/n.\"")
return rescaled_xMatrix
|
8582f222117a17b6383276740a1e189c8837d8ac | dablackwood/my_scripts_project_euler | /specific_solutions/project_euler_059.py | 3,284 | 4.375 | 4 | """
Each character on a computer is assigned a unique code and the preferred
standard is ASCII (American Standard Code for Information Interchange).
For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryption method is to take a text file, convert the bytes to
ASCII, then XOR each byte with a given value, taken from a secret key.
The advantage with the XOR function is that using the same encryption key
on the cipher text, restores the plain text; for example, 65 XOR 42 = 107,
then 107 XOR 42 = 65.
For unbreakable encryption, the key is the same length as the plain text
message, and the key is made up of random bytes. The user would keep the
encrypted message and the encryption key in different locations, and
without both "halves", it is impossible to decrypt the message.
Unfortunately, this method is impractical for most users, so the modified
method is to use a password as a key. If the password is shorter than the
message, which is likely, the key is repeated cyclically throughout the
message. The balance for this method is using a sufficiently long password
key for security, but short enough to be memorable.
Your task has been made easy, as the encryption key consists of three lower
case characters. Using cipher1.txt
(right click and 'Save Link/Target As...'), a file containing the
encrypted ASCII codes, and the knowledge that the plain text must
contain common English words, decrypt the message and find the sum of the
ASCII values in the original text.
"""
import time
t1 = time.time()
def bin(x):
d = {0:'000', 1:'001', 2:'010', 3:'011', \
4:'100', 5:'101', 6:'110', 7:'111'}
return ''.join([d[int(dig)] for dig in oct(x)])
def stringify(wordlist):
strung = ''
for index in xrange(len(wordlist)):
strung += chr(int(wordlist[index]))
return strung
def check_english(string):
#print string[:20]
if 'The' in string and 'Gospel' in string:# or 'you' in string:
print string[:40]
proceed = input("Does this look right? (1=yes, 2=no) ")
if proceed == 1:
return True
elif proceed == 2:
return False
else:
return check_english(string)
else:
return False
def decrypt(numbers, password):
copied = []
for character in xrange(len(numbers)):
key = password[character % 3]
copied.append(str(int(numbers[character]) ^ key))
#print "--->", copied[:20]
return stringify(copied)
def text_sum(text):
tally = 0
for character in text:
tally += ord(character)
return tally
in_file = open('project_euler_059_cipher1.txt', 'r')
text = in_file.read()
text = text[:-1]
numbers = text.split(',')
#print len(numbers)
#print text_sum('abc')
quick = decrypt(numbers, (103, 111, 100))
print quick
"""
for key1 in xrange(97, 123):
for key2 in xrange(122, 96, -1):
for key3 in xrange(97, 123):
password = (key1, key2, key3)
# print password
decrypted = decrypt(numbers, password)
if check_english(decrypted):
print password
print text_sum(decrypted)
print decrypted
break
"""
#print strung
print time.time() - t1
|
bc9ed8a112a5dd8c9c0c4e1a3f308a3cf39e25c0 | tsankesara/CodeChef-Submissions | /Beginner/Byte to Bit - BITTOBYT.py | 781 | 3.9375 | 4 | ##Username: chefteerth ## https://www.codechef.com/users/chefteerth
#Question URL: https://www.codechef.com/problems/BITOBYT
# Problem Name: Byte to Bit
# Problem Code: BITOBYT
# Programming Lang: Python3
def BytetoBit(Test):
for i in range(Test):
N = int(input())
ans=0
k=0
bit,nibble,byte=0,0,0
N-=1
ans=int(N%26)
N/=26
k=int(pow(2,int(N)))
if ans<2:
bit=k
elif ans<10:
nibble = k
else:
byte=k
ans = str(bit) + ' ' + str(nibble) + ' ' + str(byte)
return ans
test = int(input())
ans_lst = []
while 0 < test:
ans = BytetoBit(test)
ans_lst.append(ans)
test = test -1
for i in range(len(ans_lst)):
print(ans_lst[i]) |
63cf20d96eff8cf98cde846eb497b7735356c1f4 | learn-cloud/cisco | /EE/api.py | 148 | 3.828125 | 4 | a = 10
b = 20
c = a+b
print('------------------------------')
print ("adittion of two numbers is: ",c)
print('------------------------------')
|
3e1d911ae8fac586903da2bdd28dd8f8e26d94ea | gundlacc/CS362-Testing-Project | /datetime_helper.py | 2,865 | 3.9375 | 4 | from math import floor
def initial_date_calc(total_days, four_years, years_passed, extra_days):
if total_days >= four_years:
years_passed = floor(total_days / four_years)
years_passed = years_passed * 4
extra_days = total_days % four_years
else:
if total_days < 365:
years_passed = 0
extra_days = total_days
if 365 < total_days < 730:
years_passed = 1
extra_days = total_days - 365
if 730 < total_days < 1096:
years_passed = 2
extra_days = total_days - 730
if 1096 < total_days < four_years:
years_passed = 3
extra_days = total_days - 1096
return years_passed, extra_days
def initial_extra_days_plus_years(extra_days, years_passed):
if extra_days > 365:
if extra_days > 365:
extra_days -= 365
years_passed += 1
if extra_days > 365:
extra_days -= 365
years_passed += 1
if extra_days > 366:
extra_days -= 366
years_passed += 1
if extra_days > 365:
extra_days -= 365
years_passed += 1
return extra_days, years_passed
else:
return extra_days, years_passed
def extra_day_from_ly(final_year, extra_days):
# Used https://docs.microsoft.com/en-us/office/troubleshoot/excel/determine-a-leap-year#:~:
# text=Any%20year%20that%20is%20evenly,and%201996%20are%20leap%20years
# to help calculate missing days. Had to split the URL for PEP8
first_leap_year = 1972
while first_leap_year <= final_year:
if first_leap_year % 100 == 0 and first_leap_year % 400 != 0:
extra_days += 1
first_leap_year += 4
if final_year % 4 == 0 and extra_days >= 366:
final_year += 1
extra_days -= 366
if final_year % 4 != 0 and extra_days >= 365:
final_year += 1
extra_days -= 365
return final_year, extra_days
def final_months_days(extra_days, days_passed, total_days, months_passed, final_year):
reg_year = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
leap_year = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days = 0
months = 0
if final_year % 4 == 0:
for d in leap_year:
days += d
if extra_days < days:
months_passed = months
days_passed = extra_days - (days - d)
break
months += 1
if final_year % 4 != 0:
for d in reg_year:
days += d
if extra_days < days:
months_passed = months
days_passed = extra_days - (days - d)
break
months += 1
return days_passed, months_passed
|
4b0df9a0deb4143a7c6fdb4a349c057d1df04945 | davidenoma/python-introduction | /fifth_class_assignment.py | 2,226 | 3.828125 | 4 | import random
def main():
cities = ['New york','Boston', 'Atlanta', 'Dallas']
outfile = open('cities.txt','w')
for item in cities:
outfile.write(item + '\n')
outfile.close()
#Question1
file = open('number_list.txt', 'a')
for i in range(1,6):
file.write(str(i)+"\n")
file.close()
#Question 2
file = open('number_list.txt','r')
for ln in file:
print(ln)
file.close()
#Question 3
file = open('number_list.txt','r')
total = 0
for ln in file:
print(ln)
total += int(ln)
print("\n", "The sum is: ",total)
file.close()
#Question 4
numRand = int(input("How many Random numbers do you want to generate? "))
rands = open('randnos.txt','w')
for i in range(1, numRand+1):
rands.write(str(random.randint(1,100))+"\n")
rands.close()
#Question 5
rands = open('randnos.txt','r')
total = 0
count = 0
for ln in rands:
total += int(ln)
count += 1
print("Total is: ", total)
print("Number of Random Numbers is: ",count)
rands.close()
#Question 6
integers = open('randnos.txt','r')
for ln in integers:
total += int(ln)
count += 1
try:
print("Average of all numbers is: ", total/count)
except IOError:
print("File is opened ad data is read from it ")
except ValueError:
print("Items read from the file are converted to a number")
integers.close()
#Question 7
print("Welcome to Spring Fork Amateur Golf Club")
print("-----------------------------------------")
print("When done enter 'done' as a value")
golf = open("golf.txt", "w")
golf.write("Name"+"\t"+"Score\n")
golf.close()
check = True
while (check == True):
name = input("Player's Name: ")
if name == "done" :
break
score = int(input("Player's Score: "))
golf = open("golf.txt", "a")
golf.write(name + "\t" + str(score) + "\n")
golf.close()
print("Finished...")
#Question 8
golf = open('golf.txt', 'r')
for ln in golf:
print(ln)
golf.close()
main()
|
0d964d588e0e52d69ce2522bace27594c421ae60 | nikatov/tmo | /prog4.py | 4,479 | 3.875 | 4 | # -*- coding: utf-8 -*-
# +-------------------------------+
# | Многоканальная СМО без |
# | ограничений на длину очереди, |
# | но с ограниченным временем |
# | ожидания в очереди. |
# +-------------------------------+
from math import factorial
import matplotlib.pyplot as plt
def multiply(lst):
result = 1
for i in lst:
result *= i
return result
# Приведенная интенсивность потока
def p_f(Tc, Ts):
l = 1 / Tc
m = 1 / Ts
return l / m
# Приведенная интенсивность потока ухода
def b_f(Ts, Tw):
v = 1 / Tw
m = 1 / Ts
return v / m
# Вероятность того, что все каналы обслуживания свободны
def p0_f(p, b, n: int, m: int):
sum = 1
for k in range(1, n + 1):
sum += (p ** k) / factorial(k)
for i in range(1, m + 1):
sum += (p ** n / factorial(n)) * (p ** i) / multiply([n + l * b for l in range(1, i + 1)])
return 1 / sum
# Вероятность того, что k каналов обслуживания заняты
def pk_f(p0, p, b, k: int, n: int):
if k <= n:
return (p ** k) * p0 / factorial(k)
i = k - n
return pk_f(p0, p, b, n, n) * p ** i / multiply([n + l * b for l in range(1, i + 1)])
def m_f(p, b, n, eps):
m = 0
p0 = p0_f(p, b, n, m)
delta = p0 ** m - p0 ** (m + 1)
while delta >= eps:
m += 1
p0 = p0_f(p, b, n, m)
delta = p0 ** m - p0 ** (m + 1)
return m
# Математическое ожидание среднего числа занятых каналов
def ksr_f(p, b, n, m):
p0 = p0_f(p, b, n, m)
sum = 0
for k in range(0, n + 1):
# sum += k * pk_f(p0, p, b, k, n)
sum += (k * (p ** k) * p0) / factorial(k)
sum2 = 0
for i in range(1, m + 1):
sum2 += (p ** i) / multiply([n + l * b for l in range(1, i + 1)])
sum2 *= (n * (p ** n) * p0) / factorial(n)
sum += sum2
return sum
# Коэффициент загрузки операторов
def q_f(p, b, n, m):
return ksr_f(p, b, n, m) / n
# Вероятность существования очереди
def poch_f(p, b, n, m):
if p / n >= 1:
return 1
p0 = p0_f(p, b, n, m)
sum = 1
for i in range(1, m):
sum += p ** i / multiply([n + l * b for l in range(1, i + 1)])
return (p ** n * p0 / factorial(n)) * sum
# Математическое ожидание длины очереди
def loch_f(p, b, n, m):
p0 = p0_f(p, b, n, m)
sum = 0
for i in range(1, m + 1):
sum += i * (p ** i) / multiply([n + l * b for l in range(1, i + 1)])
return (p ** n * p0 / factorial(n)) * sum
# Функция отрисовки графиков
def plot(x_list: list,
y_list: list,
x_tytle: str = "",
y_tytle: str = ""):
fig, ax1 = plt.subplots()
plt.grid(True)
ax1.plot(x_list, y_list, 'r-')
ax1.set_xlabel(x_tytle)
ax1.set_ylabel(y_tytle)
if __name__ == '__main__':
# Константы
Tc = 39 # время возникновения заявки
Ts = 229 # время обслуживания заявки
Tw = 517 # приемлемое время ожидания
n_lim = 12 # предельное количество операторов
oper_tytle = "Количество операторов"
ksr_tytle = "Мат. ожидание числа занятых операторов"
q_tytle = "Коэффициент загрузки операторов"
poch_tytle = "Вероятность существования очереди"
loch_tytle = "Мат. ожидание длины очереди"
p = p_f(Tc, Ts)
b = b_f(Ts, Tw)
n_list = [n + 1 for n in range(n_lim)]
m_list = [m_f(p, b, n, 0.000001) for n in n_list]
ksr_list = [ksr_f(p, b, n, m) for n, m in zip(n_list, m_list)]
q_list = [q_f(p, b, n, m) for n, m in zip(n_list, m_list)]
poch_list = [poch_f(p, b, n, m) for n, m in zip(n_list, m_list)]
loch_list = [loch_f(p, b, n, m) for n, m in zip(n_list, m_list)]
plot(n_list, ksr_list, oper_tytle, ksr_tytle)
plot(n_list, q_list, oper_tytle, q_tytle)
plot(n_list, poch_list, oper_tytle, poch_tytle)
plot(n_list, loch_list, oper_tytle, loch_tytle)
plt.show()
|
3d5d2f3ae9d0eb0c1eb6cceec6d13b049a674d25 | sugengriyadi31/python | /if else.py | 521 | 3.65625 | 4 | nilai = 101
if nilai >=80 and nilai <=100:
print("Nilai kamu A")
elif nilai >=75 and nilai <80:
print("Nilai Kamu B+")
elif nilai >=70 and nilai <75:
print("Nilai Kamu B")
elif nilai >=65 and nilai <70:
print("Nilai Kamu C+")
elif nilai >=60 and nilai <65:
print("Nilai Kamu C")
elif nilai >=55 and nilai <60:
print("Nilai Kamu D+")
elif nilai >=50 and nilai <55:
print("Nilai Kamu D")
elif nilai >=0 and nilai <50:
print("Nilai Kamu E")
else:
print("Nilai yang dimasukkan salah") |
ed79efb3dfd620f4e0f6a0dcf726f0e821221f2d | sr-utkarsh/python-TWoC-TwoWaits | /day_6/13th.py | 530 | 3.8125 | 4 |
n=int(input("Enter the size of list: "))
A=[]
print("Enter the elements: ")
for i in range (n):
el=float(input())
A.append(el)
A.sort()
flag=0
for i in range(0,n-2):
j=i+1
k=n-1
while (j < k):
if( A[i] + A[j] + A[k]>1 and A[i] + A[j] + A[k]<2):
print(A[i]," ",A[j]," ",A[k])
flag=1
j=k
elif( A[i] + A[j] + A[k]>=2):
k-=1
else:
j+=1
if(flag==0):
print("No such triplets")
|
5081a058ad5e0c021702d4812a05a31f621e7dda | fabriciovale20/AulasExercicios-CursoEmVideoPython | /Exercícios Mundo 3 ( 72 à 115 )/ex098.py | 1,142 | 4.15625 | 4 | """
Exercício 98
Faça um programa que tenha uma função chamada contador(), que receba três parâmetros: início, fim e passo e realize
a contagem.
Seu programa tem que realizar três contagens através da função criada:
a) De 1 até 10, de 1 em 1;
b) De 10 até 0, de 2 em 2;
c) Uma contagem personalizada.
"""
from time import sleep
def contador(inicio, fim, passo):
passo = abs(passo)
if passo == 0:
passo = 1
print('=-'*20)
print(f'Contagem de {inicio} até {fim} de {passo} em {passo}')
if inicio > fim:
for c in range(inicio, fim-1, -passo):
print(c, end=' ')
sleep(0.5)
else:
for c in range(inicio, fim+1, passo):
print(c, end=' ')
sleep(0.5)
print('FIM!')
contador(1, 10, 1)
contador(10, 0, -2)
print('=-'*20)
print('Agora é sua vez de personalizar a contagem: ')
definir_inicio = int(input('Início: '))
definir_fim = int(input('Fim: '))
definir_passo = abs(int(input('Passo: '))) # Utilizado abs() para pegar o valor absoluto sem o sinal de negativo
contador(definir_inicio, definir_fim, definir_passo)
|
a407ec5976ad6ad812b5d636f3e252d931854fe9 | anobhama/Intern-Pie-Infocomm-Pvt-Lmt | /OOPS concept/multiple_inheritance.py | 863 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 14 10:44:26 2020
@author: Anobhama
"""
#multiple inheritance
#many base classes in a single child classes
class room:
def __init__(self,length,breath):
self.length = length
self.breath = breath
def arearect(self):
area = self.length * self.breath
return area
class cost:
def costpermeter(self):
c=100
return c
class paintingcost(room,cost):
def __init__(self,length,breath):
super().__init__(length,breath)
def paintcost(self):
room.arearect(self)
print("The painting cost is",self.arearect() * self.costpermeter())
p = paintingcost(100,3)
p.paintcost()
#user input
l=int(input("Enter the length of the room: "))
b=int(input("Enter the height of the room: "))
p1 = paintingcost(l,b)
p1.paintcost() |
b9777587a1a396d8c062a0158589af1d62e0e6e0 | fernandopreviateri/Exercicios_resolvidos_curso_em_video | /ex069.py | 1,042 | 4.09375 | 4 | '''Crie um programa que leia a idade e o sexo de várias pessoas. A
cada pessoa cadastrada, o programa deverá perguntar se o usuário
quer ou não continuar. No final, mostre:
a) Quantas pessoas tem mais de 18 anos;
b) Quantos homens foram cadastrados;
c) Quantas mulheres tem menos de 20 anos.'''
print('CADASTRO DE PESSOAS')
maior18 = total = totm = man = 0
while True:
idade = int(input('Digite a idade: '))
sexo = str(input('Digite [M/F]: ')).strip().upper()[0]
while sexo not in 'MF':
print('Opção Inválida!\nDigite corretamente.')
sexo = str(input('Digite [M/F]: ')).strip().upper()[0]
total += 1
if idade < 20 and sexo == 'F':
totm += 1
if sexo == 'M':
man += 1
if idade >= 18:
maior18 += 1
resp = ' '
while resp not in 'SN':
resp = str(input('Deseja continuar? [S/N]: ')).strip().upper()[0]
if resp == 'N':
break
print(f'Você cadastrou {total} pessoa(s).\n--> {maior18} é/são maior(es) de 18 anos.\n--> {man} é/são homens.\n--> {totm} é/são mulheres menores de 20 anos.')
|
9abebc1e539c54df6e0083992260420efad3cca7 | MuratArda-coder/Python_Tutorials | /Python_Tutorials/Lab5/Lab5.6.py | 152 | 3.65625 | 4 | #!/usr/bin/python3
a = int(input("a= "))
d = int(input("d= "))
n = int(input("n= "))
sum1 = 0
for index in range(n):
sum1 += a+(index*d)
print(sum1)
|
e79f7059e10ce9e651e65dafca68e33c4d37b6e6 | BackToTheStars/Theano_Keras | /Theano/Keras/mnist.py | 5,126 | 3.5 | 4 | #%% #creates separate cell to execute
from keras.datasets import mnist #import MNIST dataset
from keras.models import Sequential #import the type of model
from keras.layers.core import Dense, Dropout, Activation, Flatten #import layers
from keras.layers.convolutional import Convolution2D, MaxPooling2D #import convolution layers
from keras.utils import np_utils
import matplotlib #to plot import matplotlib
import matplotlib.pyplot as plt
#%% #in this cell we define our parameters
batch_size = 128 #batch size to train
nb_classes = 10 #number of output classes
nb_epoch = 12 #number of epochs to train
img_rows, img_cols = 28, 28 #input image dimensions
nb_filters = 32 #number of convolutional filters to use in each layer
nb_pool = 2 #size of pooling area for max pooling, 2x2
nb_conv = 3 #convolution kernel size, 3x3
#%%
# the data, shuffle and split between train and test sets
# X_train and X_test are pixels, y_train and y_test are levels from 0 to 9
# you can see what is inside by typing X_test.shape and y_test shape commands
# X_train are 60000 pictures, 1 channel, 28x28 pixels
# y_train are 60000 labels for them
# X_test are 10000 pictires, 1 channel, 28x28 pixels
# y_test are 10000 labels for them
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# reshape the data
# X_train.shape[0] - number of samples,
# 1 - channel, img_rows - image rows, img_cols - image columns
X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
#convert X_train and X_test data to 'float32' format
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
#then we normalize the data, dividing it by 255, the highest intensity
X_train /= 255
X_test /= 255
# Print the shape of training and testing data
print('X_train shape:', X_train.shape)
# Print how many samples you have
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')
# convert class vectors to binary class matrices,
# for example from "2" to "[0 0 1 0 0 0 0 0 0 0]
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
#now let's plot X_train example #4606
i = 4606
plt.imshow(X_train[i, 0], interpolation = 'nearest')
print("label :", Y_train[i,:])
#%% in this cell we define a model of neural network
model = Sequential() # we will use sequential type of model
# we add first layer to neural network, type of the layer is Convolution 2D,
# with 32 convolutional filters, kernel size 3x3
model.add(Convolution2D(nb_filters, nb_conv, nb_conv,
border_mode = 'valid',
input_shape = (1, img_rows, img_cols))) # number of channels 1, 28x28 pixels
# now we add activation function to convolutional neurons of the 1st layer,
# it will be "Rectified Linear Unit" function, RELU
convout1 = Activation('relu')
# we add activation function to model to visualize the data
model.add(convout1)
# we add second convolutional layer
model.add(Convolution2D(nb_filters, nb_conv, nb_conv))
# and add to 2nd layer the activation function
convout2 = Activation('relu')
model.add(convout2) # add this one to visualize data later
# we add 3rd layer, type maxpooling, pooling area 2x2
model.add(MaxPooling2D(pool_size = (nb_pool, nb_pool)))
# we add 4th layer, type dropout, which works as a regularizer
model.add(Dropout(0.25))
model.add(Flatten())
#we add 5th layer, consisting of 128 neurons
model.add(Dense(128))
model.add(Activation('relu')) # activation function for them is RELU as well
#add 6th dropout layer
model.add(Dropout(0.5))
#last 7th layer will consist of 10 neurons, same as number of classes for output
model.add(Dense(nb_classes))
model.add(Activation('softmax')) # for last layer we use SoftMax activation function
# and define optimizer and a loss function for a model
model.compile(optimizer='adadelta', loss='categorical_crossentropy',
metrics=['accuracy'])
#%% in this cell we will train the neural network model
model.fit(X_train, Y_train, batch_size = batch_size, nb_epoch = nb_epoch,
show_accuracy=True, verbose=1, validation_data = (X_test, Y_test))
model.fit(X_train, Y_train, batch_size = batch_size, nb_epoch = nb_epoch,
show_accuracy = True, verbose = 1, validation_split = 0.2)
#%% in this cell we evaluate the model we trained
score = model.evaluate(X_test, Y_test, show_accuracy = True, verbose = 0)
print('Test score:', score[0])
print('Test accuracy:', score[1])
# here we will predict what is six elements of data we have in X_test
# to see how neural network model works and recognize the numbers
print(model.predict_classes(X_test[1:7]))
#and let's see what labels these images have
print(Y_test[1:7])
# this neural network model can recognize 20000 numbers in 1 minute, using CPU
|
96df16c30d124979cacaf4ccc22ec8ab0f139090 | AnvilOfDoom/PythonKursus2019 | /Bogopgaver/Kap 8/8-14.py | 1,022 | 4.5 | 4 | """8-14, Cars
Write a function that stores information about a car in a dictionary. the function
should always receive a manufacturer and a model name. It should then accept an
arbitrary number of keyword arguments. Call the function with the required
information and two other name-value pairs, such as a color or an optional
feature. Your function should work for a call like this one:
car = make_car('subaru', 'outback', color='blue', tow_package=True)
Print the dictionary that’s returned to make sure all the information
was stored correctly."""
def make_car(manufacturer, model_name, **features):
car = {} #empty dictionary for the car
car["manufacturer"] = manufacturer #adding first argument to dictionary
car["model_name"] = model_name #adding second argument to dictionary
for key, value in features.items(): #adding remaining arguments to dictionary
car[key] = value
return car
car = make_car("toyota", "camry", color="black", car_thing="a car thing")
print(car)
|
88f81b42ef2beae05b568a289a42d203370a7df9 | kartikay89/Python-Coding_challenges | /getAvgDifficulty.py | 1,848 | 3.703125 | 4 | """
While submitting each task I ask you "how difficult was this it?" in order to adjust the difficulty level of
next tasks. Write a function called get_avg_difficulty(list_of_lists) that takes as input a list of lists ,
for example l = [[1,0,8,4], [2, 5, 6, 2], [8,8,1,7], ..., [1,9,4,5]] where each list in l shows the difficulty
scores for 1 tasks, and returns the average difficulty score given by all participants for all
len(list_of_lists) tasks (as float). Assume that the length of each of the sublists is same. If you are able
to (hope you are!), write an additional function called get_median_difficulty(list_of_lists) that returns the
median instead of the average of the difficulty scores
"""
# Average difficulty score
def get_avg_difficulty(list_of_lists):
avgScores = [[scores for scores in row] for row in list_of_lists]
avgSums = [sum(scores) / len(scores) for scores in avgScores]
return avgSums
l = [[1,0,8,4], [2, 5, 6, 2], [8,8,1,7], [1,9,4,5]]
print(get_avg_difficulty(l))
# Median difficulty score
from statistics import median
def get_median_difficulty(list_of_lists):
medScores = [[scores for scores in row] for row in list_of_lists]
medSums = [median(scores) for scores in medScores]
return medSums
print(get_median_difficulty(l))
"""
l = [[1,0,8,4], [2, 5, 6, 2], [8,8,1,7], [1,9,4,5]]
print(get_avg_difficulty(l))
testyourcode.check_funcion(get_avg_difficulty)
# advanced
def median(lst):
sortedLst = sorted(lst)
lstLen = len(lst)
index = (lstLen - 1) // 2
if (lstLen % 2):
return sortedLst[index]
else:
return (sortedLst[index] + sortedLst[index + 1])/2.0
def get_median_difficulty(list_of_lists):
all_scores = []
for subl in list_of_lists:
all_scores = all_scores + subl
return median(all_scores)
print(get_median_difficulty(l))
"""
|
7e65c5af3e44a17fea767e2bb985ccb23de2522d | francososuan/3-PracticePythonOrg | /8-MaxofThree.py | 479 | 4.25 | 4 | num_1 = input("Please input first number: ")
num_2 = input("Please input second number: ")
num_3 = input("Please input third number: ")
print("First Number: {}" .format(num_1))
print("Second Number: {}" .format(num_2))
print("Third Number: {}" .format(num_3))
if num_1 >= num_2 and num_1>=num_3:
print("Highest Number: {}" .format(num_1))
elif num_2 >= num_1 and num_2>num_3:
print("Highest Number: {}".format(num_2))
else:
print("Highest Number: {}".format(num_3)) |
ce197b8a5bf612cb2cbfa5fe4496bdb76d4489b8 | ehnana/Data-Analysis-Notebook | /DataManagement/Pandas_Data.py | 1,304 | 3.984375 | 4 | # Import pandas package
import pandas as pd
# Import Data
data = pd.read_csv("country_vaccinations.csv")
# Activate column names
pd.set_option('display.max_columns', None)
# Three first line
Three_first_line = data.head(3)
# Dataframe column
print(data.columns)
# Columns to drop
to_drop = ['source_name', 'source_website', 'iso_code', ]
data.drop(columns = to_drop, inplace=True)
# Select daily vaccination per million for the selected country (single condition)
#First method
daily_vaccination_per_million_country = data[data.country == 'France'].daily_vaccinations_per_million
#Second method
print(data.loc[data["country"] == 'France'])
# Select daily vaccination per million for the selected country and Data (Multiple condition)
daily_vaccination_per_million_country_date = data[(data.country == 'France') & (data.date == '2020-12-31')].\
daily_vaccinations_per_million
# Filtering for data related to france and Germany
Germany_France_Data = data[data.country.isin(['France', 'Germany'])]
# Filtering for data not related to france and Germany
Not_Germany_France_Data = data[~data.country.isin(['France', 'Germany'])]
# Add a column based in a dataframe based on a column value
data["vaccine quality"] = data["vaccines"].apply(lambda x: "good" if x == "Pfizer/BioNTech" else "bad")
|
c6fce2951e9edca3a9d6107e567a1ff3d6adbb0d | c940606/leetcode | /297. Serialize and Deserialize Binary Tree.py | 3,511 | 4.0625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: strt
"""
def height(root):
if not root: return 0
return max(height(root.left), height(root.right)) + 1
res = ["#"] * (2 ** height(root) - 1)
def helper(root, loc):
if loc >= len(res): return
if not root: return
res[loc] = str(root.val)
helper(root.left, 2 * loc + 1)
helper(root.right, 2 * loc + 2)
helper(root, 0)
# print(res)
return ",".join(res)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if not data: return
data = data.split(",")
# print(data)
# if not data: return
def helper(loc):
if loc >= len(data) or data[loc] == "#": return
node = TreeNode(int(data[loc]))
node.left = helper(2 * loc + 1)
node.right = helper(2 * loc + 2)
return node
return helper(0)
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
class Codec1:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
res = []
def preorder(root):
if not root:
res.append("#")
return
res.append(str(root.val))
preorder(root.left)
preorder(root.right)
preorder(root)
return ",".join(res)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
d = iter(data.split(","))
def helper():
tmp = next(d)
# print(tmp)
if tmp == "#": return
node = TreeNode(int(tmp))
node.left = helper()
node.right = helper()
return node
return helper()
class Codec2:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
from collections import deque
res = []
queue = deque()
if root: queue.appendleft(root)
while queue:
tmp = queue.pop()
if tmp:
res.append(tmp.val)
queue.appendleft(tmp.left)
queue.appendleft(tmp.right)
else:
res.append("#")
return ",".join(res)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
data = iter(data.split(","))
root = TreeNode(next(data))
queue = deque([root])
while queue:
tmp = queue.pop()
left_val = next(data)
if left_val != "#":
tmp.left = TreeNode(int(left_val))
queue.appendleft(tmp.left)
right_val = next(data)
if right_val != "#":
tmp.right = TreeNode(int(right_val))
queue.appendleft(tmp.right)
return root
|
0b57619f0973cc13ecf7bdaa9651429d8b773ea5 | pondycrane/algorithms | /python/tree/preorder/split_bst.py | 2,025 | 3.796875 | 4 | import collections
from typing import List
import base.solution
from lib.ds_collections.treenode import TreeNode
class Solution(base.solution.Solution):
def split_bst(self, root: List[int], V: int) -> List[List[int]]:
root = TreeNode.deserialize(root)
def preorder(node):
if node is None: return (None, None)
if node.val <= V:
left, right = preorder(node.right)
node.right = left
return (node, right)
else:
left, right = preorder(node.left)
node.left = right
return (left, node)
left, right = preorder(root)
return [TreeNode.serialize(left), TreeNode.serialize(right)]
"""
776. Split BST
Medium
Given a Binary Search Tree (BST) with root node root, and a target value V, split the tree into two subtrees where one subtree has nodes that are all smaller or equal to the target value, while the other subtree has all nodes that are greater than the target value. It's not necessarily the case that the tree contains a node with value V.
Additionally, most of the structure of the original tree should remain. Formally, for any child C with parent P in the original tree, if they are both in the same subtree after the split, then node C should still have the parent P.
You should output the root TreeNode of both subtrees after splitting, in any order.
Example 1:
Input: root = [4,2,6,1,3,5,7], V = 2
Output: [[2,1],[4,3,6,null,null,5,7]]
Explanation:
Note that root, output[0], and output[1] are TreeNode objects, not arrays.
The given tree [4,2,6,1,3,5,7] is represented by the following diagram:
4
/ \
2 6
/ \ / \
1 3 5 7
while the diagrams for the outputs are:
4
/ \
3 6 and 2
/ \ /
5 7 1
Note:
The size of the BST will not exceed 50.
The BST is always valid and each node's value is different.
"""
|
ac36b419700cc844f3ddeca1da85ea1935932a7b | snmsaj/Digital-Craft | /Week-2/Day-3/apphend-to-file.py | 294 | 3.703125 | 4 | file = open("I-love-programming.txt", "w")
file.close()
while True:
reason = input("Enter a reason why you like programming or press q to quit: ")
if reason == "q":
break
else:
with open("I-love-programming.txt", "a") as file:
file.write(f"{reason}\n") |
3330f1440cc95fa25babd711441e16a2fd3e328e | mfarizalarfn/Pertemuan9-praktikum4 | /membuat list-module4.py | 1,215 | 4.09375 | 4 | print("===================================================================")
print("Nama : Mohamad Farizal Arifin")
print("NIM : 312010231")
print("Kelas : TI.20.B1")
print("Mata Kuliah : Bahasa Pemrograman")
print("===================================================================")
# membuat list
print("Buat sebuah list sebanyak 5 elemen dengan nilai bebas")
list = [1, 2, 3, 4, 5]
print(list)
# mengakses list
print("Menampilkan elemen 3")
print(list[2])
print("ambil nilai elemen 2 sampai ke 4")
print(list[1:4])
print("ambil elemen terakhir")
print(list[-1])
# mengubah elemen list
print("ubah elemen 4 dengan nilai lainnya")
list[4]=10
print(list[3])
print("ubah elemen 4 sampai dengan elemen terakhir")
list[4:5]=[20,11]
print(list)
# Tambah elemen list
print("Ambil 2 bagian dari list pertama(A) dan jadikan list ke 2(B)")
list_pertama=list[3:5]
print(list_pertama)
print("tambah list B dengan nilai string")
list_pertama.append("guest")
print(list_pertama)
print("Tambah list B dengan 3 nilai")
list_pertama.append(["guest",7,8])
print(list_pertama)
print("Menggabungkan list B dengan list A")
gabung=list_pertama+list
print(gabung)
print("===================================================================") |
11b75ccb3fdedf546c5aea49970fcd65798049b5 | joelstanner/codeeval | /python_solutions/ARMSTRONG_NUMBERS/ARMSTRONG_NUMBERS.py | 979 | 4.53125 | 5 | """
An Armstrong number is an n-digit number that is equal to the sum of the n'th
powers of its digits. Determine if the input numbers are Armstrong numbers.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Each
line in this file has a positive integer. E.g.
6
153
351
OUTPUT SAMPLE:
Print out True/False if the number is an Armstrong number or not. E.g.
True
True
False
"""
from sys import argv
def armstrong_number(number):
"""Compute and return the armstrong number"""
total = 0
num_len = len(number)
for i in range(len(number)):
total += int(number[i]) ** num_len
return total
def main(input_file):
with open(input_file, 'r') as file:
for line in file:
num = line.rstrip()
arm_num = armstrong_number(num)
if (arm_num) == int(num):
print(True)
else:
print(False)
if __name__ == '__main__':
main(argv[1])
|
1ba06c10324ab01de9bc4ea3eeb0a57f009b34f7 | DerickMathew/adventOfCode2020 | /Day11/01/solution.py | 1,707 | 3.765625 | 4 | def getLines():
inputFile = open('../input.txt', 'r')
lines = inputFile.readlines()
return map(lambda line: line.split('\n')[0], lines)
def getNeigbourCount(seatingMap, x, y):
neighbourCount = 0
for neighbourY in xrange(y-1, y+2):
for neighbourX in xrange (x-1, x+2):
if 0 <=neighbourX < len(seatingMap[0]) and 0 <= neighbourY < len(seatingMap):
if not(x == neighbourX and y == neighbourY):
neighbourCount += 1 if seatingMap[neighbourY][neighbourX] == '#' else 0
return neighbourCount
def getUpdatedSeatingMap(seatingMap):
updatedSeatingMap = map(lambda line: map(lambda seat: seat, line), seatingMap)
for y in xrange(len(updatedSeatingMap)):
for x in xrange(len(updatedSeatingMap[y])):
location = seatingMap[y][x]
if seatingMap[y][x] != '.':
neighbourCount = getNeigbourCount(seatingMap, x, y)
if neighbourCount == 0:
location = '#'
elif neighbourCount > 3:
location = 'L'
updatedSeatingMap[y][x] = location
return updatedSeatingMap
def getOccupiedSeatCount(seatingMap):
return sum(map(lambda row: len(filter( lambda seat: seat == '#', row)), seatingMap))
def isIdenticalMap(map1, map2):
for y in xrange(len(map1)):
for x in xrange(len(map1[y])):
if map1[y][x] != map2[y][x]:
return False
return True
def solution():
lines = getLines()
seatingMap = map(lambda line: map(lambda seat: seat, line), lines)
updatedSeatingMap = getUpdatedSeatingMap(seatingMap)
while not isIdenticalMap(seatingMap, updatedSeatingMap):
seatingMap = []
for y in xrange(len(updatedSeatingMap)):
seatingMap.append(updatedSeatingMap[y][:])
updatedSeatingMap = getUpdatedSeatingMap(seatingMap)
print getOccupiedSeatCount(seatingMap)
solution()
|
c3a5f8d923cefb0fd79299b792a75636fb869f5f | ikaushikpal/Hacker_Rank_Problems | /Problem solving/A Chessboard Game/A Chessboard Game.py | 378 | 3.734375 | 4 | def chessboardGame(x, y):
x = x % 4
y = y % 4
if((y == 0) or (y == 3) or (x == 0) or (x == 3)):
return "First"
else:
return "Second"
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
xy = input().split()
x = int(xy[0])
y = int(xy[1])
result = chessboardGame(x, y)
print(result)
|
6844afb8a6115ed169881367b72ea73c5ef58b06 | Kanefav/exercicios | /ex073.py | 521 | 3.71875 | 4 | times = ('Flamengo', 'Santos', 'Palmeiras', 'Grêmio', 'Athletico-PR',
'São Paulo', 'Internacional', 'Corinthians', 'Fortaleza', 'Goiás',
'Bahia', 'Vasco', 'Atlético-MG', 'Fluminense', 'Botafogo', 'Ceará',
'Cruzeiro', 'CSA', 'Chapecoense', 'Avaí')
print('-='* 20)
print(f'Lista de times do Brasileirão {times}',)
print('-='*20)
print(f'Os primeiros são {times[0:5]}')
print('-='*20)
print(f'Os 4 ultimos sao {times[-1:-4]}',)
print('-='*20)
print(f'Em ordem alfabetica {sorted(times)}',) |
0c664f1c39d04d1fd674edaf096095757a523160 | sarmisthamaity/pythonLogicalquestion | /addreturn.py | 1,939 | 3.984375 | 4 | # def add_numbers(number_x, number_y):
# number_sum = number_x + number_y
# return number_sum
# sum1 = add_numbers(20, 40)
# print (sum1)
# sum2 = add_numbers(560, 23)
# a = 1234
# b = 12
# sum3 = add_numbers(a, b)
# print (sum2)
# print (sum3)
# number_a = add_numbers(20, 40) / add_numbers(5, 1)
# print (number_a)
# def add_numbers_print (numbers_x,numbers_y):
# add_numbers=numbers_x+numbers_y
# print (add_numbers)
# sum1=add_numbers_print(4,5)
# print (sum1)
# print (type(sum1))
# def add_numbers_more(number_x, number_y):
# number_sum = number_x + number_y
# print ("Hello from NavGurukul")
# return number_sum
# number_sum = number_x + number_x
# print ("Kya main yahan tak pahunchunga?")
# return number_sum
# number_sum=add_numbers_more(100, 20)
# print (number_sum)
# def menu(day):
# if day == "monday":
# return "Butter Chicken"
# elif day == "tuesday":
# return "Mutton Chaap"
# else:
# return "Chole Bhature"
# print ("Kya main print ho payungi? :-(")
# mon_menu = menu("monday")
# print (mon_menu)
# tues_menu = menu("tuesday")
# print (tues_menu)
# fri_menu = menu("friday")
# print (fri_menu)
# def menu(day):
# if day == "monday":
# food = "Butter Chicken"
# elif day == "tuesday":
# food = "Mutton Chaap"
# else:
# food = "Chole Bhature"
# print ("Kya main print ho payungi? :-(")
# return food
# print ("Lekin main toh pakka nahi print hounga :'(")
# mon_menu=menu("monday")
# print(mon_menu)
# tues_menu=menu("tuesday")
# print (tues_menu)
# fri_menu=menu("friday")
# print (fri_menu)
def menu(day):
if day == "monday":
food = "Butter Chicken"
elif day == "tuesday":
food = "Mutton Chaap"
else:
food = "Chole Bhature"
print ("Kya main print ho payungi? :-(")
return food
print ("Lekin main toh pakka nahi print hounga :'(")
|
2f244d77e648c7dbe3cb48499c71bd0dd1433252 | laszlokiraly/LearningAlgorithms | /ch04/dynamic_heap.py | 2,742 | 4.15625 | 4 | """
max binary Heap that can grow and shrink as needed. Typically this
functionality is not needed. self.size records initial size and never
changes, which prevents shrinking logic from reducing storage below
this initial amount.
"""
from ch04.entry import Entry
class PQ:
"""Priority Queue implemented using a heap."""
def __init__(self, size):
self.size = size
self.storage = [None] * (size+1)
self.N = 0
def __len__(self):
"""Return number of values in priority queue."""
return self.N
def is_empty(self):
"""Determine whether Priority Queue is empty."""
return self.N == 0
def is_full(self):
"""If priority queue has run out of storage, return True."""
return self.size == self.N
def enqueue(self, v, p):
"""Enqueue (v, p) entry into priority queue."""
if self.N == len(self.storage) - 1:
self.resize(self.N*2)
self.N += 1
self.storage[self.N] = Entry(v, p)
self.swim(self.N)
def less(self, i, j):
"""
Helper function to determine if storage[i] has higher
priority than storage[j].
"""
return self.storage[i].priority < self.storage[j].priority
def swap(self, i, j):
"""Switch the values in storage[i] and storage[j]."""
self.storage[i],self.storage[j] = self.storage[j],self.storage[i]
def swim(self, child):
"""Reestablish heap-order property from storage[child] up."""
while child > 1 and self.less(child//2, child):
self.swap(child, child//2)
child = child//2
def sink(self, parent):
"""Reestablish heap-order property from storage[parent] down."""
while 2*parent <= self.N:
child = 2*parent
if child < self.N and self.less(child, child+1):
child += 1
if not self.less(parent, child):
break
self.swap(child, parent)
parent = child
def dequeue(self):
"""Remove and return value with highest priority in priority queue."""
if self.N == 0:
raise RuntimeError('PriorityQueue is empty!')
max_entry = self.storage[1]
self.swap(1, self.N)
self.storage[self.N] = None
self.N -= 1
self.sink(1)
storage_size = len(self.storage)
if storage_size > self.size and self.N < storage_size // 4:
self.resize(self.N // 2)
return max_entry.value
def resize(self, new_size):
"""Resize storage array to accept more elements."""
replace = [None] * (new_size+1)
replace[0:self.N+1] = self.storage[0:self.N+1]
self.storage = replace
|
19e181501bc3fccaad883557870bff7421a53c12 | kogos/Scipy_codes | /input.py | 818 | 3.921875 | 4 | __author__ = 'stephen'
from object_task import *
"""
#def f(shape, length, width):
#=['rectangle', '5', '4']
a = ['', '', '']
a[0] = input("Enter the shape")
a[1] = input("Enter the length")
a[2] = input("Enter the width")
a[0] = str.capitalize(a[0])
a[1] = float(a[1])
a[2] = float(a[2])
c = 'a[1], a[2]'
#b = {'a[0]': c}
#print(type(b))
#print(a[0])
#print(b['a[0]'])
#print(a[1]+a[2])
#length = int(a[1])
#width = int(a[2])
#area = length * width
#print(area)
"""
#print(dic[a[0]])
if __name__ == "__main__":
a = ['', '', '']
a[0] = input("Enter the shape")
a[1] = input("Enter the length")
a[2] = input("Enter the width")
a[0] = str.capitalize(a[0])
a[1] = float(a[1])
a[2] = float(a[2])
c = 'a[1], a[2]'
rectangle = a[0](a[1], a[2])
print(rectangle)
rectangle.draw() |
ff5c7c9415bd7bb1447644414dc454c7cf82ffc7 | ivansharma/snake_coder | /Python in general/supermarket.py | 126 | 3.65625 | 4 | produce_department = input('Would you like to buy someting from the produce department? ')
if input yes:
bill = bill + 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.