blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1bf6eb006f8a5c96c30acd0863b64fa0024b4263 | arishavelle18/PythonProject | /SimpleCalculator.py | 7,446 | 4.09375 | 4 | from tkinter import *
import tkinter.font as font
root = Tk()
root.title("Simple Calculator") # title must be Simple Calculator
myFont = font.Font(family="calibri",size=20,weight="bold") # generate a font
e = Entry(root,width=25,borderwidth=5,font=myFont,justify="right") # create the entry
e.grid(row=0,column=0,columnspan=3,padx=10,pady=10,) # position the entry
global identifier
identifier = "" # identifier must globally declare to determine what operation you want to do
def type_checker(data): #check if it is not int then convert to float
if type(data) is not int:
return float(data)
def AddNum(number): # add the number in the entry
current = e.get()# 10 # get all the value in the entry
e.delete(0,END) # delete all in the entry
e.insert(0,str(current)+str(number)) # insert the number in the entry in the position 0 and concatenate it in current
def Num_Clear(): # just clear the number in the entry
e.delete(0,END)
def Button_Add(first_number): # adding the number
if len(e.get())==0: # check if the entry length is equal to zero then you cant go to this function
return
try:
first_number = int(first_number) # check if it is integer
except:
first_number = type_checker(first_number) # if it is not an integer change it to float
e.delete(0,END) #delete all character in the entry
global f_num # declare f_num globally so that you can use to other function and change it if necessary
f_num = first_number
global identifier # since the identifier is globally declare change it to addition
identifier="+"
def Num_Sub(first_number): # subtract the number
if len(e.get())==0: # check if the entry length is equal to zero then you cant go to this function
return
try:
first_number = int(first_number) # check if it is integer
except:
first_number = type_checker(first_number) # if it is not an integer change it to float
e.delete(0,END) #delete all character in the entry
global f_num # since the f_num is globally declare then change it to the first_number
f_num = first_number
global identifier # since the identifier is globally declare change it to subtraction
identifier = "-"
def Num_Mul(first_number): # multiplication the number
if len(e.get())==0: # check if the entry length is equal to zero then you cant go to this function
return
try:
first_number = int(first_number) # check if it is integer
except:
first_number = type_checker(first_number) # if it is not an integer change it to float
e.delete(0,END) # delete all the character in the entry
global f_num # since the f_num is globally declare then change it to the first_number
f_num = first_number
global identifier # since the identifier is globally declare change it to multiplication
identifier = "*"
def Num_Div(first_number): # divide the number
if len(e.get()) == 0: # check if the length is equal to zero
return
try:
first_number = int(first_number) # check if it is integer
except:
first_number = type_checker(first_number) # convert to float
e.delete(0,END) # delete all the charater in the entry
global f_num # change the f_num value
f_num = first_number
global identifier # change the identifier to division
identifier="/"
def Num_Equal():
print(identifier)
if identifier =="+":
try:
second_number = int(e.get()) //check if the second number is int
except:
second_number = type_checker(e.get()) // convert second number to float
e.delete(0,END) // delete all character in the entry
e.insert(0,f_num+second_number) // add f_num and second number then this procedure apply to all operation
elif identifier =="-":
try:
second_number = int(e.get())
except:
second_number = type_checker(e.get())
e.delete(0,END)
e.insert(0,f_num-second_number)
elif identifier == "*":
try:
second_number = int(e.get())
except:
second_number = type_checker(e.get())
e.delete(0,END)
e.insert(0,f_num * second_number)
elif identifier =="/":
try:
second_number = int(e.get())
except:
second_number = type_checker(e.get())
e.delete(0,END)
if second_number == 0:
e.insert(0,"Cannot divide by zero")
else:
div = f_num / second_number
e.insert(0, div)
else:
pass
# creating a button
button_1 = Button(root,text="1",padx=40,pady=20,command=lambda:AddNum(1),fg="white",bg="black")
button_2 = Button(root,text="2",padx=40,pady=20,command=lambda:AddNum(2),fg="white",bg="black")
button_3 = Button(root,text="3",padx=40,pady=20,command=lambda:AddNum(3),fg="white",bg="black")
button_4 = Button(root,text="4",padx=40,pady=20,command=lambda:AddNum(4),fg="white",bg="black")
button_5 = Button(root,text="5",padx=40,pady=20,command=lambda:AddNum(5),fg="white",bg="black")
button_6 = Button(root,text="6",padx=40,pady=20,command=lambda:AddNum(6),fg="white",bg="black")
button_7= Button(root,text="7",padx=40,pady=20,command=lambda:AddNum(7),fg="white",bg="black")
button_8 = Button(root,text="8",padx=40,pady=20,command=lambda:AddNum(8),fg="white",bg="black")
button_9 = Button(root,text="9",padx=40,pady=20,command=lambda:AddNum(9),fg="white",bg="black")
button_0 = Button(root,text="0",padx=40,pady=20,command=lambda:AddNum(0),fg="white",bg="black")
button_clear = Button(root,text="CLEAR",padx=81,pady=20,command=Num_Clear,fg="white",bg="black")
button_add = Button(root,text="+",padx=39,pady=20,command=lambda:Button_Add(e.get()),fg="white",bg="black")
button_equal = Button(root,text="=",padx=95,pady=20,command=Num_Equal,fg="white",bg="black")
button_subtract = Button(root,text="-",padx=40,pady=20,command=lambda : Num_Sub(e.get()),fg="white",bg="black")
button_multiply = Button(root,text="x",padx=40,pady=20,command=lambda : Num_Mul(e.get()),fg="white",bg="black")
button_division = Button(root,text="/",padx=40,pady=20,command=lambda : Num_Div(e.get()),fg="white",bg="black")
# use a grid
button_1.grid(row=3,column=0,pady=3)
button_2.grid(row=3,column=1,pady=3)
button_3.grid(row=3,column=2,pady=3)
button_4.grid(row=2,column=0,pady=3)
button_5.grid(row=2,column=1,pady=3)
button_6.grid(row=2,column=2,pady=3)
button_7.grid(row=1,column=0,pady=3)
button_8.grid(row=1,column=1,pady=3)
button_9.grid(row=1,column=2,pady=3)
button_0.grid(row=4,column=0,pady=3)
button_clear.grid(row=5,column=1,columnspan=2,pady=3)
button_add.grid(row=5,column=0,pady=3)
button_equal.grid(row=6,column=1,columnspan=2,pady=3)
button_subtract.grid(row=6,column=0,pady=3)
button_multiply.grid(row=4,column=1,pady=3)
button_division.grid(row=4,column=2,pady=3)
root.mainloop()
|
093b9922f0d21c036036fecda959219263809b78 | satriopangestu17/catatan1 | /day6whileloopsoalifelsepass.py | 4,149 | 3.859375 | 4 | # password = '12345'
# input('ketik password')
# input('password salah! ketik password:')
# input('password benar")
password = '12345'
inputuser = ''
while inputuser != password:
inputuser = input('ketik password')
if inputuser != password:
print('password salah')
else:
print ('password benar')
#ada limit 5 kali masukin salah password berhenti
# password = '12345'
# inputuser1 = ''
# inputuser2 = ''
# inputuser3 = ''
# while inputuser1 != password: #salah ni
# inputuser1 = input('ketik password')
# if inputuser1 != password:
# x = 'password salah'
# print(x)
# elif inputuser2 != 'password salah' :
# print('password salah, tinggal 2 kali kesempatan')
# else:
# print ('password benar') belum kelar salahh ini
#ada limit 5 kali masukin salah password berhenti
#SOAL
# password = '12345'
# input('ketik password')
# input('password salah! ketik password:')
# input('password benar")
#** well programmed **
# password = '12345'
# inputuser = '' # bikin variable baru ='' untuk membuktikan while sesuai atau benar jadi berlanjut
# jumlahinput = 0
# batasinput = 5
# lebih = False #True and False meaning real true or false
# while inputuser != password and not lebih: #while with two conditions #ditambahkan and not lebih agar berhenti loop whilenya, tapi bakal proses dulu ke if loop while
# if jumlahinput < batasinput: # because counting from 0,1,2,3,4. then same as 5 elements
# inputuser = input(f' input ke - {jumlahinput+1} ketik password : ')
# jumlahinput = jumlahinput + 1 # jumlahinput += 1
# else:
# lebih = True # this one is for stopinggg, because *True will stop while syntax without showing any output and continue to another if conditions. and False will make an error continuity
# if lebih:
# print('kesempatan habis, tunggu 24 jam')
# else:
# print('password benar!')
# # * Hasilnya akan sama seperti diatas. well programmed.
# password = '12345'
# inputpass = '1'
# jumlahinput = 1
# batasinput = 5
# lebih = False
# while password != inputpass and not lebih:
# if jumlahinput <= batasinput:
# inputpass = input(f'input pass ke -{jumlahinput }: ')
# jumlahinput += 1
# else:
# lebih = True
# if lebih: #lebih disini artinya True, lanjutan else?
# print ('coba lagi dalam waktu 24 jam')
# else:
# print ('password anda benar')
# #*soal sama diatas *if else nya bisa dibalik=
# password = '12345'
# inputpass = '1'
# jumlahinput = 1
# batasinput = 5
# lebih = False
# while password != inputpass and not lebih:
# if jumlahinput <= batasinput:
# inputpass = input(f'input pass ke -{jumlahinput }: ')
# jumlahinput += 1
# else:
# lebih = True
# if not lebih: #lebih disini artinya True, lanjutan else?, lanjutan if and not
# print ('password anda benar')
# else:
# print ('coba lagi dalam waktu 24 jam')
#* sama hasilnya sama diatas, tapi dibalik true falsenya
# password = '12345'
# inputpass = '1'
# jumlahinput = 1
# batasinput = 5
# lebih = True
# while password != inputpass and lebih:
# if jumlahinput <= batasinput:
# inputpass = input(f'input pass ke -{jumlahinput }: ')
# jumlahinput += 1
# else:
# lebih = False
# if lebih: #lebih disini artinya True, lanjutan else?
# print ('password anda benar')
# else:
# print ('coba lagi dalam 24 jam')
# password = '12345'
# inputpass =''
# inputpass = input('ketik password') # has to be after while, so it won't repeat all over again.
# while inputpass != password:
# if inputpass != password:
# print('salah')
# else:
# print('benar') # the first on top is the right way.
# password ='12345'
# inputpass='12345'
# while password == inputpass: # kalau while ==, maka akan mengeluarkan print 'benar' saja, dan tidak akan merepetisi loop
# inputpass = input('ketik password: ')
# if inputpass == inputpass:
# print('benar')
# else:
# print('salah') #the first on top is the right way
|
7405b9359ba8a4190ae9a87fe6ee72283585f019 | zhengchaoxuan/Lesson-Code | /Python/Python基础/day 8/exercise2_定义一个类描述平面上的点并提供移动点和计算到另一个点距离的方法.py | 1,178 | 4.75 | 5 | """
exercise2:定义一个类描述平面上的点并提供移动点和计算到另一个点距离的方法
描述:
1)一个初始化 __init__
3)一个改变移动点位置 move_by
4)一个到另外一个点的距离 distance
Version : 1
Author : 郑超轩
Date : 2020/02/11
"""
from math import sqrt
class Point(object):
"""初始化"""
def __init__(self,x=0,y=0):
self.x =x
self.y =y
def move_by(self,dx,dy):
"""移动"""
self.x +=dx
self.y +=dy
def distance(self,other):
"""计算距离"""
distance_x = self.x - other.x
distance_y = self.y - other.y
distance_all = sqrt(distance_x**2+distance_y**2)
return distance_all
def __str__(self):
"""描述对象,字符"""
return "%s ,%s" % (str(self.x),str(self.y))
def main():
p1 =Point(3,8)
p2 =Point()
p1.move_by(-1,2)
#1. print(p1) 直接使用会出现错误,<__main__.Point object at 0x03759160> -->改变方法:加入__str__函数,返回一个字符串,当做这个对象的描写
print(p1)
print(p1.distance(p2))
if __name__ == "__main__":
main() |
c223febdbafceefcca858ae6900789524bfd30ff | darraes/coding_questions | /v1/Tree/lower_2_right.py | 1,026 | 3.9375 | 4 | # http://www.careercup.com/question?id=5214848900136960
class TreeNode:
def __init__(self, left, right, value):
self._left = left
self._right = right
self._value = value
self._onLeft = 0
def _place(node, value, smallerAbove):
if value >= node._value:
if node._right == None:
node._right = TreeNode(None, None, value)
return smallerAbove + 1
else:
return _place(node._right, value, smallerAbove + node._onLeft + 1)
else:
node._onLeft += 1
if node._left == None:
node._left = TreeNode(None, None, value)
return smallerAbove
else:
return _place(node._left, value, smallerAbove)
def solve(data):
result = [0]*len(data)
index = len(data) - 2
root = TreeNode(None, None, data[index + 1])
while index >= 0:
result[index] = _place(root, data[index], 0)
index -= 1
return result
print solve([1,3,2,4,5,4,2]) |
c53c3f36d479cbdb8f9f98619b1ee545323e3700 | MiIyama/d301-correcao_ex | /ex4.py | 412 | 3.734375 | 4 | # Ja estao organizados em ordem
meninos = ['Luiz', 'João', 'Alex', 'Guilherme']
meninas = ['Lais', 'Lolo','Ana']
i = 1
for menino in meninos:
for menina in meninas:
print(f'Casalsinho {i}:{menino} e {menina}')
i +=1
# **********************************************************************************
# Se quiser ser sem organizar usar a função usar o shuffle do exercicio 2 |
0786bf960da968137bbe199b0c1fa33a53df1d58 | Gafanhoto742/Python-3 | /Python (3)/Aula/aula16_tuplas.py | 1,165 | 3.96875 | 4 |
# for sem mostrar posição
lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim')
for comida in lanche:
print(f'Eu vou comer {comida}')
print ('Comi pra caramba!')
#For demonstrando a posição
lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim', 'Batata Frita')
for cont in range(0, len(lanche)):
print(f'Eu vou comer {lanche[cont]} na posição {cont}')
print ('Comi pra caramba!')
lanche = ('Hambúrguer', 'Suco', ' Pizza', ' Pudim', 'Batata Frita')
for pos, comida in enumerate(lanche):
print (f'Eu vou comer {comida} na posição {pos}')
print ('Comi pra caramba!')
#Demonstrar em ordem (Alfabetica)
lanche = ('Hambúrguer', ' Suco', 'Pizza', 'Batata Frita')
print (sorted(lanche))
print(lanche)
#Tupla que junta A e B
a = (2, 5, 4)
b = (5, 8, 1, 2)
c = b + a
print (c)
# Len de c (quantos elementos)
a = (2, 5, 4)
b = (5, 8, 1, 2)
c = b + a
print (len(c))
'''# Cont de c (quantas vezes aparece o numero 5)
a = (2, 5, 4)
b = (5, 8, 1, 2)
z = b + a
print (z.cont(5))'''
# Index de c (em que posição aparece o numero 8)
a = (2, 5, 4)
b = (5, 8, 1, 2)
c = b + a
print (c)
print (c.index(8))
#
pessoa = ('Henrique', 35, 'M', 70.20)
print (pessoa) |
e25e25d21427bd39ef2d0257cc783dd60509c7ac | mazuecos3/Python-Begginer | /Unidad8/ejercicio_III_u8_areas.py | 444 | 3.765625 | 4 | # Calculamos el area de el rectangulo
def area_rectangulo():
base = 5
altura = 9
resultado = base * altura
return resultado
# Calculamos el area de el Triangulo
def area_triangulo():
base = 5
altura = 13
resultado = base * altura / 2
return resultado
# Calculamos el area de el circulo
def area_circulo():
pi = 3.14
radio = 5
resultado = pi * (radio**2)
return resultado |
ddb6467a40efe525bd4969201fcbc1981a391476 | monisha9379/project2 | /func.py | 372 | 3.96875 | 4 |
import operator
x=str(input("please enter a string "))
def most_frequent(string):
d=dict()
for k in string:
if k not in d:
d[k] = 1
else:
d[k] +=1
return d
z = most_frequent(x)
sorted_z = dict(sorted(z.items(),key=operator.itemgetter(1),reverse=True))
for i in sorted_z:
print(i," = ",sorted_z[i])
|
f0679a70d2f6caeb5b29ffbadee8903f99e1959c | ZDawang/leetcode | /57_insert_interval.py | 1,740 | 3.6875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#author : zhangdawang
#data:2017-4-
#difficulty degree:
#problem: 57_insert_interval
#time_complecity:
#space_complecity:
#beats:
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution(object):
def merge(self, intervals):
i = 0
if not intervals:
return []
temp = intervals[0]
for interval in intervals:
if interval.start <= temp.end:
temp.end = max(interval.end,temp.end)
else:
intervals[i], temp, i = temp, interval, i + 1
return intervals[:i] +[temp]
def insert(self, intervals, newInterval):
#插入
if not intervals:
return [newInterval]
len_intervals = len(intervals)
l, r = 0, len_intervals - 1
mid = 0
if newInterval.start > intervals[-1].start:
mid = len_intervals
intervals = intervals + [newInterval]
else:
while(l <= r):
mid = (l + r) // 2
if intervals[mid].start < newInterval.start <= intervals[mid + 1].start:
mid += 1
break
if newInterval.start <= intervals[mid].start:
r = mid - 1
else:
l = mid + 1
intervals.insert(mid, newInterval)
#merge
mid_temp = mid - 1 if mid >= 1 else 0
res = self.merge(intervals[mid_temp:])
return intervals[:mid_temp] + res
intervals = [Interval(1,5)]
solute = Solution()
res = solute.insert(intervals, Interval(2,3))
for r in res:
print(r.start, r.end)
|
bec3dc67a66973a3f35ebebb7332fb4d895ce1ff | power19/homework4 | /Homework4.py | 1,997 | 4.03125 | 4 | """
Create a global variable called myUniqueList.
It should be an empty list to start
"""
# Global Variables
myUniqueList = []
myLeftovers = []
"""
Next, create a function that allows you to add things to that list.
Anything that's passed to this function should get added to myUniqueList,
unless its value already exists in myUniqueList.
If the value doesn't exist already,
it should be added and the function should return True.
If the value does exist, it should not be added,
and the function should return False;
Add another function that pushes all the rejected inputs into a separate global
array called myLeftovers.
If someone tries to add a value to myUniqueList but it's rejected (
for non-uniqueness),
it should get added to myLeftovers instead.
"""
def leftovers(leftover):
if leftover in myUniqueList:
myLeftovers.append(leftover)
return myLeftovers
def addValues(toAppend):
result = False
if toAppend not in myUniqueList:
result = True
myUniqueList.append(toAppend)
else:
leftovers(toAppend)
return print(result)
var0 = 0
var1 = 1
var2 = 2
var3 = 3
var4 = 4
var5 = 5
var6 = 6
var7 = 7
addValues(var0)
addValues(var1)
addValues(var2)
addValues(var3)
addValues(var4)
addValues(var5)
addValues(var6)
addValues(var7)
addValues(var1)
addValues(var2)
addValues(var3)
addValues(var4)
addValues(var5)
addValues(var6)
addValues(var7)
addValues(var1)
addValues(var2)
addValues(var3)
addValues(var4)
addValues(var5)
addValues(var6)
addValues(var7)
addValues(var1)
addValues(var2)
addValues(var3)
addValues(var4)
addValues(var5)
addValues(var6)
addValues(var7)
addValues(var1)
addValues(var2)
addValues(var3)
addValues(var4)
addValues(var5)
addValues(var6)
addValues(var7)
addValues(var1)
addValues(var2)
addValues(var3)
addValues(var4)
addValues(var5)
addValues(var6)
addValues(var7)
print(myUniqueList)
print(myLeftovers) |
50f626f212e22f1d579c2b33ee010961c88362fc | boaass/Leetcode | /190. Reverse Bits/Reverse Bits/main.py | 1,945 | 4.0625 | 4 | # Reverse bits of a given 32 bits unsigned integer.
#
# Example 1:
#
# Input: 00000010100101000001111010011100 Output: 00111001011110000010100101000000 Explanation: The input binary
# string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its
# binary representation is 00111001011110000010100101000000. Example 2:
#
# Input: 11111111111111111111111111111101 Output: 10111111111111111111111111111111 Explanation: The input binary
# string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its
# binary representation is 10111111111111111111111111111111.
#
# Note:
#
# Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output
# will be given as signed integer type and should not affect your implementation, as the internal binary
# representation of the integer is the same whether it is signed or unsigned. In Java, the compiler represents the
# signed integers using 2's complement notation. Therefore, in Example 2 above the input represents the signed
# integer -3 and the output represents the signed integer -1073741825.
#
# Follow up:
#
# If this function is called many times, how would you optimize it?
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
s = ""
# for i in range(32):
# if n != 0:
# s = str(n % 2) + s
# n //= 2
# else:
# s = '0' + s
#
# print s
# r = 0
# for i in range(32):
# if int(s[i]) == 1:
# r += pow(2, i)
# return r
r = 0
for i in range(32):
r += pow(2, 32-i-1) if (n % 2) == 1 else 0
n //= 2
return r
if __name__ == '__main__':
n = 43261596
s = Solution()
print s.reverseBits(n) |
a55f182764b5d5d322c7bece325935a920824aef | dane-piper/ELements-of-Computing-Projects | /MonteCarlo.py | 2,381 | 3.953125 | 4 | import random
from math import pi
import math
import os
import random
import re
import sys
class Queue (object):
def __init__ (self):
self.queue = []
# add an item to the end of the queue
def enqueue (self, item):
self.queue.append (item)
# remove an item from the beginning of the queue
def dequeue (self):
return (self.queue.pop(0))
# check if the queue is empty
def is_empty (self):
return (len (self.queue) == 0)
# return the size of the queue
def size (self):
return (len (self.queue))
# function for testing. displays the contents of your queue
def display(self):
for item in self.queue:
print(item + ", ", end="")
print()
#
# This is the 'main' function, make the program work by writing HELPER FUNCTIONS.
#
# The function is expected to return a List of strings.
# The function accepts a list of strings numbers as parameter.
#
#input is a char and returns a number value from dictionary
def chartonum(c, dict):
return dict.get(c, '')
def sort(numbers, dict):
longest = len(numbers[0])
for lens in range(1, len(numbers)):
current = len(numbers[lens])
if current > longest:
longest = current
print(longest)
queues = []
length = len(numbers)
for i in range(35):
queues.append(Queue())
for n in range(longest):
for idx in range(len(numbers)):
nums = numbers.pop(0)
x = chartonum(nums[-n], dict)
print(x)
queues[x].enqueue(nums)
for que in queues:
que.display()
size = que.size()
for l in range(size):
numbers.append(que.dequeue())
print('pass: ' + str(n))
return numbers
def main():
# We went ahead and created the dictionary for you
dict = {
'0': 0, '1': 1, '2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9,
'a': 10,'b': 11,'c': 12,'d': 13,'e': 14,'f': 15,'g': 16,'h': 17,'i': 18,
'j': 19,'k': 20,'l': 21,'m': 22,'n': 23,'o': 24,'p': 25,'q': 26,'r': 27,
's': 28,'t': 29,'u': 30,'v': 31,'w': 32,'x': 33,'y': 34,'z': 35
}
numbers = ['311', '96', '495', '137', '158', '84', '145', '63','10000']
sort(numbers, dict)
main()
|
6f1533a29c51722cfc5a4374c3bbc96ae04f11a7 | neequole/my-python-programming-exercises | /level2_solutions/question17.py | 831 | 3.921875 | 4 | """ Question 17
Level 2
Question:
Write a program that computes the net amount of a bank account based a
transaction log from console input. The transaction log format is shown as following:
D 100
W 200
¡
D means deposit while W means withdrawal.
Suppose the following input is supplied to the program:
D 300
D 300
W 200
D 100
Then, the output should be:
500
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
"""
net_amount = 0
while True:
try:
action, amount = input("Enter new transaction log:").split()
except ValueError:
break
else:
action = action.upper()
amount = float(amount)
if action == 'D':
net_amount += amount
elif action == 'W':
net_amount -= amount
print(net_amount)
|
3649f61724864e9db42b2781a9346aff2c214bde | JiahangGu/leetcode | /All Problems/33-search-in-rotated-sorted-array.py | 1,439 | 3.828125 | 4 | #!/usr/bin/env python
# encoding: utf-8
# @Time:2020/9/28 15:15
# @Author:JiahangGu
from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> int:
"""
根据二分减治法的原理,区分什么情况左移,什么情况右移即可。
首先找到哪半部分是有序的,如果nums[l] < nums[mid],则左半部分有序,否则右半部分有序。判断是否在有序部分,不在就移动到另一部分
关键点在于,二分搜索只能在有序序列中进行,所以必须要明确哪部分序列是有序的,并在这个有序序列中判断是否存在。
此外还有先用二分找到旋转点,然后根据此得到两个有序序列,并进一步查找target的方法,不再实现。
:param nums:
:param target:
:return:
"""
l, r = 0, len(nums) - 1
while l <= r:
mid = l + (r - l) // 2
if nums[mid] == target:
return mid
elif nums[l] <= nums[mid]:
if nums[l] <= target < nums[mid]:
r = mid - 1
else:
l = mid + 1
else:
if nums[mid] < target <= nums[r]:
l = mid + 1
else:
r = mid - 1
return -1
s = Solution()
nums = [3,1]
target = 1
print(s.search(nums, target))
|
a3ea79bb36d56fe1166ac69b2aa39a56fa5bb30b | aimanaaw/oop_python | /something.py | 753 | 4.0625 | 4 | class Dog():
species = 'mammal'
def __init__(self, mybreed, name):
self.mybreed = mybreed
self.name = name
# Operations/Actions ---> Methods
def bark(self, number):
print("woof! My name is {} and the number is {}".format(self.name, number))
my_dog = Dog('lab', 'sammy')
print(type(my_dog))
print('dog name is', my_dog.name)
print('dog has species defined? ', my_dog.species)
my_dog.bark(5)
class Circle():
# Class object attribute
pi = 3.14
def __init__(self, radius = 1):
self.radius = radius
self.area = radius*radius*self.pi
#
def get_circumference(self):
return self.radius * self.pi * 2
my_circle = Circle(30)
print(my_circle.radius)
print(my_circle.get_circumference())
print(my_circle.area) |
cbc4d6392ca96661765b1bb5bbfb4fba8cc0b3b9 | mustafabozkaya/tutorials | /support-vector-machine-svm/svm_machine_learning.py | 2,422 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
#Support Vector Machines (SVM) Introduction - Machine Learning
* Tutorial: https://news.towardsai.net/svm
* Github: https://github.com/towardsai/tutorials/tree/master/support-vector-machine-svm
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#classic datasets from sklearn library
from sklearn import datasets
from sklearn.model_selection import train_test_split
#Support Vector Classification-wrapper around SVM
from sklearn.svm import SVC
#different matrices to score model performance
from sklearn import metrics
from sklearn.metrics import classification_report,confusion_matrix
"""## Load data"""
#loading WINE dataset
cancer_data = datasets.load_wine()
#converting into DataFrame
df = pd.DataFrame(cancer_data.data, columns = cancer_data.feature_names)
df['target'] = cancer_data.target
df.head()
"""## Exploratory data analysis"""
#analysing target variable
sns.countplot(df.target)
plt.show()
#visualizing datapoints seperability
fig, axes = plt.subplots(4, 3, figsize=(22,14))
axes = [ax for axes_rows in axes for ax in axes_rows]
columns = list(df.columns)
columns.remove('target')
columns.remove('alcohol')
#looping through every columns of data
#and plotting against alcohol
for i, col in enumerate(columns):
sns.scatterplot(data=df, x='alcohol', y=col, hue='target', palette="deep", ax=axes[i])
"""## Splitting data"""
#splitting data into 80:20 train test ratio
X = df.drop('target', axis=1)
y = df.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=10)
"""## Model training and performance evaluation"""
#training SVM model with linear kernel
model = SVC(kernel='linear',random_state = 10)
model.fit(X_train, y_train)
#predicting output for test data
pred = model.predict(X_test)
#building confusion matrix
cm = confusion_matrix(y_test, pred)
#defining the size of the canvas
plt.rcParams['figure.figsize'] = [15,8]
#confusion matrix to DataFrame
conf_matrix = pd.DataFrame(data = cm,columns = ['Predicted:0','Predicted:1', 'Predicted:2'], index = ['Actual:0','Actual:1', 'Actual:2'])
#plotting the confusion matrix
sns.heatmap(conf_matrix, annot = True, fmt = 'd', cmap = 'Paired', cbar = False,
linewidths = 0.1, annot_kws = {'size':25})
plt.xticks(fontsize = 20)
plt.yticks(fontsize = 20)
plt.show()
print(classification_report(y_test,pred))
|
48f1f8796c58dec0e6f31fac219ee049dbb1c64d | tolyamba75/hello_andrei | /wordgame.py | 1,095 | 3.5 | 4 | class WordGame:
def __init__(self, letter):
self.ans_opt = ['правильно.', 'слово уже было отгадано.', 'попытайся еще раз.']
self.letter = letter.lower()
self.lst = []
# id: кол-во отгаданных
self.lst_part = {}
def rules(self, word):
if self.letter == word[:1]:
return True
return False
def answer(self, word, user_id):
word = word.lower()
# угадал
if self.rules(word) and not(word in self.lst):
self.lst.append(word)
try:
self.lst_part[user_id] += 1
except KeyError:
self.lst_part[user_id] = 1
return self.ans_opt[0]
# слово отгадано
elif self.rules(word):
return self.ans_opt[1]
# не корректный ответ
else:
return self.ans_opt[2]
def game_over(self):
self.letter = ' '
return self.lst
def win(self):
return self.lst_part
|
99f69fc323e6c9ff526b2f5bbe85dcb904b56680 | jellyseafood/python | /linkedlistXD03.py | 1,609 | 3.953125 | 4 | class nud:
def __init__(self, data):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = nud(None)
def append(self, data):
new_node = nud(data)
cur = self.head #nud(None)
while cur.next != None:
# print(cur.next)
cur = cur.next #None
cur.next = new_node #cur.next = nud(data)
def append02(self, data):
new_node = nud(data)
cur = self.head # nud(None)
oldnode = self.head.next
self.head.next = new_node
cur.next = new_node
new_node.next = oldnode
def display(self):
list = []
cur = self.head
while cur.next != None:
cur = cur.next
list.append(cur.data)
return list
def remo02(self, index):
cur = self.head
# tempo = cur
for s in range(-1, index):
if cur.next != None:
cur = cur.next
else: break
self.head.next = cur
l_list1 = linked_list()
l_list1.append02(2)
l_list1.append02(6)
l_list1.append02(9)
l_list1.append02(5)
l_list1.append02(12)
l_list1.append02(0)
# l_list1.append(100)
# l_list1.append(2)
# l_list1.append(6)
# l_list1.append(9)
# l_list1.append(5)
# l_list1.append(12)
# l_list1.append(0)
print("List constructed")
print(l_list1.display())
# print(l_list1.display())
l_list1.remo02(3)
print(l_list1.display())
# l_list1.remo02()
# print(l_list1.display())
# l_list1.remo02()
# print(l_list1.display()) |
380e873347aa753d095515f4d4f0b00df76b374c | geri-brs/machine-learning | /1-python-learning/time_converter.py | 892 | 3.75 | 4 | def time_converter(time):
splitted = time.split(":")
hh = int(splitted[0])
mm = int(splitted[1][0:2])
period = splitted[1][-4:]
new_time = ""
if (hh == 12 and mm == 00):
return "00:00"
if (period == "a.m."):
if (hh < 10):
new_time += "0" + str(hh)
else:
new_time += str(hh)
if (mm < 10):
new_time += ":" + "0" + str(mm)
else:
new_time += str(mm)
if (period == "p.m."):
if (hh < 12):
hh += 12
new_time += str(hh)
else:
new_time += str(hh)
if (mm < 10):
new_time += ":" + "0" + str(mm)
else:
new_time += ":" + str(mm)
return new_time
if __name__ == '__main__':
print("Example:")
print(time_converter('12:00 p.m.'))
|
7d2408be8a32c7c3d064ad3f0871c5c5fc3e9b0b | desve/netology | /tasks/6/6-4.py | 285 | 3.875 | 4 | # Утренняя пробежка
print("Введите начальную дистанцию x=")
x = int( input())
print("Введите конечную дистанцию y=")
y = int( input())
xn = x
i = 0
while xn <= y:
xn = xn + 0.1 * xn
i += 1
else:
print(i+1) |
f9c14d1ffa07f7c09c60a65e8d61e1db100ae601 | maddyvn/Robot-framework_Test | /Libraries/CSVLibrary.py | 3,726 | 3.984375 | 4 | import csv
from collections import defaultdict
class CSVLibrary(object):
def read_csv_file(self, filename, header='FALSE'):
'''
Returns a list of rows, with each row being a list of the data in each column
Specify header as 'True' will show header row\n
I.e. Given data.csv\n
Name,Age,Title\n
Lex,30,QC\n
Dora,28,QC\n
read csv file data.csv | true
>>> [['Name','Age','Title'],['Lex','30','QC'],['Dora','28','QC']]
'''
data = []
with open(filename) as f:
reader = csv.reader(f, skipinitialspace=True)
for row in reader:
data.append(row)
if header.lower() == 'false':
del data[0]
return data
def read_csv_file_dict(self, filename):
'''
Returns a list of dictionary from csv content\n
I.e. Given data.csv\n
Name,Age,Title\n
Lex,30,QC\n
Dora,28,QC\n
read csv file dict data.csv
>>> [['Name':'Lex','Age':'30','Title':'QC'],['Name':'Dora','Age':'28','Title':'QC']]
'''
with open(filename) as f:
reader = csv.reader(f, skipinitialspace=True)
header = next(reader)
data = [dict(zip(header, map(str, row))) for row in reader]
return data
def get_csv_column(self, filename, column):
'''
Return a full column from csv file\n
I.e. Given data.csv\n
Name,Age,Title\n
Lex,30,QC\n
Dora,28,QC\n
Alan,26,Dev\n
Lex,30,Dev\n
get csv column data.csv | Name
>>> ['Lex',''Dora,'Alan','Lex']
'''
data = defaultdict(list)
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
for k, v in row.items():
data[k].append(v)
return data[column]
def lookup_csv_value(self, filename, lookupKey, lookupVal, returnKey, index=1):
'''
Return the value of the desired column base on a reference of lookup value
Specify the index for the no of returned value\n
I.e. Given data.csv\n
Name,Age,Title\n
Lex,30,QC\n
Dora,28,QC\n
Alan,26,Dev\n
Lex,30,Dev\n
lookup csv value data.csv | Name | Lex | Title | 2
>>> Dev
'''
with open(filename) as f:
reader = csv.reader(f, skipinitialspace=True)
header = next(reader)
listDict = [dict(zip(header, map(str, row))) for row in reader]
count = 0
if index < 1: index = 1
for d in listDict:
if d[lookupKey] == lookupVal:
count = count + 1
if count >= int(index):
return d[returnKey]
return None
def lookup_csv_list(self, filename, lookupKey, lookupVal, returnKey):
'''
Return a list of values match a lookup refecence\n
I.e. Given data.csv\n
Name,Age,Title\n
Lex,30,QC\n
Dora,28,QC\n
Alan,26,Dev\n
Lex,30,Dev\n
lookup csv list data.csv | Name | Lex | Title
>>> ['QC','Dev']
'''
list = []
with open(filename) as f:
reader = csv.reader(f, skipinitialspace=True)
header = next(reader)
data = [dict(zip(header, map(str, row))) for row in reader]
for sRow in data:
if sRow[lookupKey] == lookupVal:
list.append(sRow[returnKey])
return list
def lookup_csv_row(self, filename, lookupKey, lookupVal, index=1):
'''
Return a row base on a reference of lookup value
Specify the index for the no of returned row\n
I.e. Given data.csv\n
Name,Age,Title\n
Lex,30,QC\n
Dora,28,QC\n
Lex,30,Dev\n
lookup csv row data.csv | Name | Lex | 2
>>> ['Name':'Lex','Age':'30','Title':'Dev']
'''
with open(filename) as f:
reader = csv.reader(f, skipinitialspace=True)
header = next(reader)
listDict = [dict(zip(header, map(str, row))) for row in reader]
count = 0
if index < 1: index = 1
for d in listDict:
if d[lookupKey] == lookupVal:
count = count + 1
if count >= int(index):
return d
return None |
4f5f011a2b297758ff17559df8b073ba0421aef2 | yanxurui/keepcoding | /python/algorithm/cracking/18.8.py | 3,043 | 3.59375 | 4 | # -*- coding:utf-8 -*-
class Trie:
def __init__(self, s=None):
self.isWord = False
self.d = dict()
if s is not None:
if s == '':
self.isWord = True
else:
self.d[s[0]] = Trie(s[1:])
def insert(self, s):
if s == '':
self.isWord = True
else:
c = s[0]
sub = self.d.get(s[0], None)
if sub:
sub.insert(s[1:])
else:
self.d[s[0]] = Trie(s[1:])
def prefix(self, s):
if s == '':
return self.isWord
cur = self
for i, c in enumerate(s):
sub = cur.d.get(c, None)
if sub:
cur = sub
else:
return 0
if cur.isWord:
return i+1 # the first i+1 chars in s appears in the tree
def find(self, s):
if s == '':
return self.isWord
sub = self.d.get(s[0], None)
if not sub:
return False
return sub.find(s[1:])
def delete(self, s):
if s == '' and self.isWord:
self.isWord = False
return
cur = self
stack = []
for c in s:
sub = cur.d.get(c, None)
if sub:
stack.append((cur, c))
cur = sub
else:
return
if cur.isWord:
# find
cur.isWord = False
# no subtree
while stack:
cur, c = stack.pop()
if cur.isWord:
break
if not cur.d[c].d:
# no subtree
del cur.d[c]
else:
break
class Substr:
def chkSubStr(self, p, n, s):
# write code here
d = {}
root = Trie()
for w in p:
root.insert(w)
import pdb
# pdb.set_trace()
for i in range(len(s)):
while True:
j = root.prefix(s[i:i+8])
if j > 0:
w = s[i:i+j]
d[w] = True
root.delete(w)
else:
break
return [d.get(w, False) for w in p]
if __name__ == '__main__':
from testfunc import test
from common import TreeNode, ListNode
test_data = [
(
(
["a","b","c","d"],4,"abc"
),
[True,True,True,False]
),
(
(
["a","ab","abc","d"],4,"abc"
),
[True,True,True,False]
),
(
(
["bav","yacv","wez","p","zei","m","ypx","oqlz","by","tudp","vcwb","bwkw","tjc","hs","gbjg","c","qmfe","wvc","cw"],19,"bwkwby"
),
[False,False,False,False,False,False,False,False,True,False,False,True,False,False,False,False,False,False,False]
),
]
test(Substr().chkSubStr, test_data)
|
d5babd4aa7b3b1d11ea7e4321dced7d1356cd68f | nitinverma99/Codeforces---900 | /Kana_and_dragon_quest_game.py | 291 | 3.546875 | 4 | for cases in range(int(input())):
x, n ,m = list(map(int, input().split()))
for i in range(n):
if x>= 12:
x = ((x//2) + 10)
else:
continue
for i in range(m):
x -= 10
if x <= 0:
print("YES")
else:
print("NO") |
f2cbc232974d13e686e00c7f57436104ecbccd5e | pymsmile/pam | /pam/samplers/basic.py | 472 | 3.859375 | 4 | import random
def freq_sample(freq: float, sample: float):
"""
Down or up sample a frequency based on a sample size. Sub unit frequencies are
rounded probabalistically.
:param freq: pre sampled frequency (integer)
:param sample: sample size (float)
:return: new frequency (integer)
"""
new_freq = freq * sample
remainder = new_freq - int(new_freq)
remainder = int(random.random() < remainder)
return int(new_freq) + remainder
|
6181852777fb8cd5615af9f647f50f8b73cfba43 | jreiher2003/code_challenges | /leetcode/move_zeros1.py | 224 | 3.65625 | 4 |
def move_zeros(nums):
len_zero_list = len([x for x in nums if x == 0])
nums[:] = [x for x in nums if x != 0]
nums[:] += [0] * len_zero_list
return nums
nums = [0,1,0,3,12]
print move_zeros(nums) |
ce10464ec1f730e89692c6b57c45f834563c9575 | anudishjain/Scientific-Calculator-Desktop-App | /Calculator_Main.py | 4,892 | 4.21875 | 4 | from tkinter import *
from math import sin,cos,tan,log
# the collection of operators and digits
# entered in a Specific Order as they appear in Layout of Calculator
operators=['7','8','9','C','AC','sin','4','5','6','+','/','cos','1','2','3','-','*','tan','0','.','=','(',')','ln']
evaluate=''
# function bounded with buttons adds operators to "evaluate" string
def add(operator):
global evaluate,expression
if operator is 'C':
evaluate=evaluate[:-1] ## removes the last entered character in 'evaluate' string
expression.delete(0,END)
expression.insert(0, evaluate)
elif operator is 'AC':
evaluate='' ## reassignes String hence cleanes all data
expression.delete(0, END) # Clears ENTRY and deletes all output
expression.insert(0, evaluate) # gives the new Output in ENTRY
elif operator is '=':
expression.delete(0, END)
try:
eval(evaluate) # try is used to first check if eval() can operate over evaluate string
expression.insert(0, eval(evaluate))
except : # exception is handled with message on screen
expression.insert(0, 'Error')
else:
if operator is (('sin')or('cos')or('tan')):
evaluate=evaluate+operator+'(' # bracket is pre added in case of Trigonometric Functions
elif operator is 'ln':
evaluate=evaluate+'log'+'(' # similarly bracket added for ln function
else:
evaluate = evaluate + operator
expression.delete(0,END) # Clears ENTRY and deletes all output
expression.insert(0, evaluate) # gives the new Output in ENTRY
'''-----------------------------------------------------------------------------------------------------------------'''
def keyBoard(event):
# Keyboard Input
global evaluate, expression,panel
if event.char is not '=':
evaluate = evaluate + event.char # event.char carries info about the key pressed on keyboard
else:
expression.delete(0, END)
expression.insert(0, eval(evaluate))
evaluate = ''
def solver(event): # as soon as ENTER key is hit from keyboard
# it gives output in ENTRY
global evaluate, expression
try:
eval(evaluate)
expression.delete(0, END)
expression.insert(0, eval(evaluate))
except:
expression.delete(0, END)
expression.insert(0, 'Error')
finally:
evaluate=''
''' --------------------------------------- MAIN CALCULATOR SCREEN LAYOUT -----------------------------------------'''
panel=Tk()
panel.title('Py Calc')
panel.wm_minsize(405,313)
panel.wm_maxsize(405,313)
panel.iconbitmap('icon_main.ico')
panel.configure(bg='grey10')
'''------------------------------------------------Input Panel ------------------------------------------------------'''
expression=Entry(panel)
expression.configure(bg='grey10',fg='white',font=('courier new','15'),borderwidth=0,justify=RIGHT)
expression.bind('<Key>',keyBoard) # binding ENTRY to KeyBoard Input
expression.bind('<Return>',solver) # binding ENTRY to ENTER KEY OPERATION
expression.place(x=130,y=8)
'''----------------------------------------------- Button Top to Bottom ---------------------------------------------'''
k=0
'''Creates layout of the Calculator'''
for y in range(1,5):
for x in range(0,6):
i = operators[k]
if x<3 :
button = Button(panel,text=operators[k],command=lambda i=i:add(i))
button.configure(bg='grey80', fg='grey10', borderwidth=0, width=3, height=1,
font=('courier new', '25', 'bold'))
button.place(x=68*x,y=63*y)
elif x is 5 :
button = Button(panel, text=operators[k],command=lambda i=i:add(i))
button.configure(bg='royalblue3', fg='white', borderwidth=0, width=3, height=1,
font=('courier new', '25','bold'))
button.place(x=68 * x, y=63 * y)
else :
button = Button(panel,text=operators[k],command=lambda i=i:add(i))
button.configure(bg='darkorange2', fg='white', borderwidth=0, width=3, height=1,
font=('courier new', '25', 'bold'))
button.place(x=68*x,y=63*y)
k=k+1
'''------------------------------------------------------------------------------------------------------------------'''
panel.mainloop()
|
ed44f23bac3540f0a8d4a98249b38b5db8b4de3b | subhan/python-code | /word.py | 273 | 3.5 | 4 | import os
def count(f,word):
content = open(f).read()
return content.count(word)
if __name__ == "__main__":
import sys
f,word = sys.argv[1:]
f = os.path.abspath(f)
count = main(f,word)
print "'%s' word encountered %s times in '%s' file"%(word,count,f)
|
2a2510c563ea1ff3043247e7eb91ba9c8952689b | andjelicjovana/Projekat1 | /prikaz_akcija.py | 1,484 | 3.625 | 4 | from import_books import *
def prikaz_akcija():
akcije = knjige_i_cene()
#print(akcije)
while True:
print('odaberite zeljenu akciju')
print('1. soritranje po sifri')
print('2. soritranje po datumu')
print('3. izlaz')
izbor = input('unesite vas izbor: ')
while izbor == '':
print('unos nije validan \n')
izbor = input('ponovo unesite zeljenu vrednost: ')
if izbor == '1':
for recnik in akcije:
if recnik['valid_until'] < datetime.datetime.now():
akcije.remove(recnik)
for i in range(len(akcije)):
for j in range(len(akcije)):
if akcije[i]['ida'] < akcije[j]['ida']:
akcije[i], akcije[j] = akcije[j], akcije[i]
break
elif izbor == '2':
for recnik in akcije:
if recnik['valid_until'] < datetime.datetime.now():
akcije.remove(recnik)
for i in range(len(akcije)):
for j in range(len(akcije)):
if akcije[i]['valid_until'] < akcije[j]['valid_until']:
akcije[i], akcije[j] = akcije[j], akcije[i]
break
elif izbor == '3':
return
else:
print('uneli ste nepostojecu akciju')
pretty_print(akcije)
if __name__ == '__main__':
prikaz_akcija() |
4faa72daa6737c54645f8e8378e51e9184b7811f | dipty-survase-automatonai/test | /exam-reverse.py | 181 | 3.671875 | 4 | import io
import re
fname=input("enter filename:")
f=open(fname)
line=f.readline()
#print(line)
while line != "":
y = line[::-1]
print(y)
line= f.readline()
|
31fb4f84ad6a4ac5d2852d58ac0435fcd6606650 | shrutijai1/21-DAYS-OF-PROGRAMMING-CHALLENGE-ACES | /#day4.py | 4,964 | 4.46875 | 4 | ########## Learn most of the concept of list(specially adding and removing of elements ###############
thislist = [1,2,3,45,56,67,23,44,56]
while True:
print("OPERATIONS ON THE LIST")
print(" Enter 1 for printing list")
print(" Enter 2 for finding the length of the list")
print(" Enter 3 for print the list in reverse order")
print(" Enter 4 for change the value of the list")
print(" Enter 5 for checking whether the item is present in the list or not")
print(" Enter 6 for performing accessing task")
print(" Enter 7 for performing adding and removing operations ")
choice= int(input(" Enter your choice : "))
if choice == 1:
print("list is : ")
for x in thislist:
print(x)
elif choice == 2:
print(" Lenght of the list is", len(thislist))
elif choice == 3:
thislist.reverse()
print(" Reverse list is: ",thislist)
break
elif choice == 4:
index = int(input(" Enter the index value that you want to change the item value: "))
changevalue = int(input("Enter change value: "))
thislist[index] = changevalue
print(" NEW LIST IS ")
for x in thislist:
print(x)
elif choice == 5:
item = int(input(" Enter the item that you want to check: "))
if item in thislist:
print(" YES",item,"is persent in thislist")
elif choice == 6:
print(" Enter 1 for access any index value of list")
print(" Enter 2 for starting till you want to print the list")
print(" Enter 3 from you want to print the list till end of the list")
print(" Enter 4 for access a list in range")
print(" Enter 5 for accessing the last value of the list")
h = int(input(" Enter your choice : "))
if h == 1:
index = int(input(" Enter the index value of that you want to access from the list: "))
print(thislist[index])
elif h == 2:
end = int(input(" Enter the index value till you want to print the list: "))
print(thislist[:end+1])
elif h == 3:
start = int(input(" Enter the index value from you want to start acess: "))
print(thislist[start:])
elif h == 4:
start = int(input(" Enter the index value from you want to start acess: "))
end = int(input(" Enter the index value till you want to print the list: "))
print(thislist[start:end+1])
elif h == 5:
print("The last value in list is: ",thislist[-1])
else:
print("INVALID CHOICE")
elif choice == 7:
print(" Enter 1 for performing adding task")
print(" Enter 2 for performing removing task")
ch = int(input(" Enter your choice: "))
if ch == 1:
print(" LET'S PERFORM SOME ADDING TASK ")
print(" Enter 1 for add item from last in the present list")
print(" Enter 2 for adding item at which postion that want add in the present list")
i = int(input(" Enter your choice: "))
if i == 1:
item = int(input(" Enter item that you want to add in the list: "))
thislist.append(item)
print("NOW LIST BECOME",thislist)
elif i == 2:
item = int(input(" Enter item that you want to add in the list: "))
index = int(input(" Enter the position at you want to add the item in the list: "))
thislist.insert(index,item)
print(" NOW LIST BECOME",thislist)
else:
print("INVALID CHOICE")
elif ch == 2:
print(" Enter 1 for removing particular item from the list")
print(" Enter 2 for removing last item from the list")
print(" Enter 3 for removing item from particular index value")
print(" Enter 4 for removing whole list")
j = int(input(" Enter your choice: "))
if j == 1:
item = int(input(" Enter item that you want to remove from the present list: "))
thislist.remove(item)
print(" NOW LIST BECOME",thislist)
elif j == 2:
thislist.pop()
print(" NOW LIST BECOME",thislist)
elif j == 3:
index = int(input(" Enter the position at which you want to remove the item : "))
del thislist[index]
print(" NOW LIST BECOME",thislist)
elif j == 4:
thislist.clear()
print(" NOW LIST BECOME",thislist)
else:
print(" INVALID CHOICE")
else:
print("INVALID CHOICE")
|
5c80073d9b7462b26dca1130b2bb5a80e0154861 | number09/atcoder | /abc100-a.py | 108 | 3.515625 | 4 | int_a, int_b = map(int, input().split())
if int_a > 8 or int_b > 8:
print(":(")
else:
print("Yay!") |
cd8efe136892cbfdd6d09e8723d950baef14707c | shinyben/project-euler | /Problems/std.py | 1,159 | 3.984375 | 4 | import math
import re
"""
Num methods
"""
def prime_factors(N):
"""
Returns list of N's prime factors
"""
for i in range(2,int(math.sqrt(N)+1)):
if N % i == 0:
return [i] + prime_factors(N/i)
return [int(N)]
def proper_divisors(N):
"""
Returns list of N's divisors
"""
out = []
for i in range(2, N//2 + 1):
if N%i == 0:
out.append(i)
return out + [1] # to get 1
def is_prime(N):
"""
Returns True if N is prime, False else
"""
for i in range(2,int(math.sqrt(N)+1)):
if N % i == 0:
return False
return True
"""
Str methods
"""
def is_palindrome(S):
"""
Returns True if S is a palindrome
"""
for i in range(int(len(S)/2)):
if S[i] != S[-1-i]:
return False
return True
def without(S, L):
"""
Returns the string S without the substrings defined in L
"""
for element in L:
S = re.sub(element, "", S)
return S
"""
List/set methods
"""
def sum(L):
"""
Returns sum of elements in L
"""
sum = 0
for element in L:
sum += element
return sum
|
686bd775404f0a76f812ef130bdd6b5b7a8c3c2a | koumik/Python_Practice | /numoflines in txt file.py | 289 | 3.921875 | 4 | # 10) To count the number of lines in a text file
def file_lengthy(numoflines):
with open(numoflines) as f:
for i, l in enumerate(f):
pass
return i + 1
print("Number of lines in the file: ",file_lengthy("numoflines.txt"))
|
49bc5306d85aa775b5ff68b0bbd2b79e8ebc8808 | fwangboulder/DataStructureAndAlgorithms | /#38CountAndSay.py | 1,110 | 3.640625 | 4 | """
38. Count and Say Add to List QuestionEditorial Solution My Submissions
Total Accepted: 116602
Total Submissions: 355840
Difficulty: Easy
Contributors: Admin
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
Hide Company Tags Facebook
Hide Tags String
Hide Similar Problems (M) Encode and Decode Strings
"""
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
s = '1'
for i in range(n - 1):
ns = prev = ''
count = 0
for q in s:
if prev != '' and q != prev:
ns += str(count) + prev
count = 1
else:
count += 1
prev = q
ns += str(count) + prev
s = ns
return s
|
9d31f299cc510a6c5e99a3e7bef0c8740d37fd5f | jakelevi1996/backprop2 | /optimisers/linesearch.py | 4,706 | 3.8125 | 4 | import numpy as np
class LineSearch:
def __init__(self, s0=0.1, alpha=0.5, beta=0.5, max_its=15):
""" Initialise a LineSearch object. This object can be passed to a
minimisation function (such as gradient_descent or generalised_newton),
and to the initialiser for a Result object.
Inputs:
- s0: initial step size, default is 1.0
- alpha: minimum ratio of reduction to expected reduction to accept,
in (0, 1). A higher value of alpha means more steps will be taken
per iteration when backtracking, to get a step size which gives a
better reduction in error function. Default is 0.5.
- beta: ratio to scale the step size by when backtracking (and inverse
ratio to scale the step size by when forward tracking). Smaller beta
means that the changes in step size will be bigger, so iterations
will generally end faster, but the step size which is found might
not be very optimal. Default is 0.5
- max_its: maximum number of iterations to perform every time
get_step_size is called. Fewer iterations per function call might
help to prevent the line-search from overfitting a certain batch,
but will prevent finding the optimal step size every time
get_step_size is called. Default is 10.
"""
self._s0 = s0
self.s = s0
self.alpha = alpha
self.beta = beta
self.max_its = max_its
def get_step_size(self, model, x, y, w, delta, dEdw):
""" Find the approximate locally best step size to use to optimise the
model for the current batch of training data. This function is called
by the AbstractOptimiser.optimise method (if a valid LineSearch object
is passed to it).
Note that at the beginning of this method we do not propagate the input
x through the network again, because we are assuming it has just been
propagated during the call to the _get_step method in
AbstractOptimiser.optimise for the same batch of training data and the
same set of parameters, therefore we call model.mean_total_error(y)
straight away, without first propagating the data through the network.
Inputs:
- model: instance of NeuralNetwork to be optimised
- x: inputs for the current batch of training data
- y: targets for the current batch of training data
- w: current parameters of the model, from which the step will be
taken
- delta: direction in which to take a step
- dEdw: gradient of the error function at the current parameters
"""
# Calculate initial parameters
E_old = E_0 = model.mean_total_error(y)
model.set_parameter_vector(w + self.s * delta)
model.forward_prop(x)
E_new = model.mean_total_error(y)
delta_dot_dEdw = np.dot(delta, dEdw)
# Check initial backtrack condition
if self._must_backtrack(E_new, E_0, delta_dot_dEdw):
# Reduce step size until reduction is good and stops decreasing
for _ in range(self.max_its):
self.s *= self.beta
E_old = E_new
model.set_parameter_vector(w + self.s * delta)
model.forward_prop(x)
E_new = model.mean_total_error(y)
if (
(not self._must_backtrack(E_new, E_0, delta_dot_dEdw))
and E_new >= E_old
):
break
if E_new > E_old:
self.s /= self.beta
else:
# Track forwards until objective function stops decreasing
for _ in range(self.max_its):
self.s /= self.beta
E_old = E_new
model.set_parameter_vector(w + self.s * delta)
model.forward_prop(x)
E_new = model.mean_total_error(y)
if E_new >= E_old:
break
if E_new > E_old:
self.s *= self.beta
return self.s
def _must_backtrack(self, E_new, E_0, delta_dot_dEdw):
""" Compares the actual reduction in the objective function to that
which is expected from a first-order Taylor expansion. Returns True if a
reduction in the step size is needed according to this criteria,
otherwise returns False. """
reduction = E_0 - E_new
expected_reduction = -self.s * delta_dot_dEdw
return reduction < (self.alpha * expected_reduction)
def reset(self):
self.s = self._s0
|
58e621e94bf5c60a58eee10b02dfe56229beef89 | Aravind2595/MarchPythonProject | /collections/list/demo7.py | 222 | 3.65625 | 4 | lst=[]
print(lst)
#append :to add one element to the list
lst.append(100)
lst.append(1000)
lst.append('luminar')
print(lst)
#extend to add multiple elements to the list at the same time
lst.extend([2,5,7,8])
print(lst) |
27d65979ea5945894c73fa64d5f2d8de2b8878e1 | iripo/python_lesson1 | /hw06_normal.py | 3,046 | 3.609375 | 4 | class Classroom:
def __init__(self, class_room):
self.class_room = {
'class_num': int(class_room.split()[0]),
'class_letter': class_room.split()[1]
}
def get_name(self):
return str(self.class_room['class_num']) + ' ' + self.class_room['class_letter']
class Person:
def __init__(self, name, father_name, surname):
self.name = name
self.surname = surname
self.father_name = father_name
def get_full_name(self):
return self.surname + ' ' + self.name + ' '+ self.father_name
def get_short_name(self):
return '{} {}.{}.'.format(self.surname.title(), self.name[0].upper(), self.father_name[0].upper())
class Student(Person):
def __init__(self, name, father_name, surname, class_room, father, mother):
Person.__init__(self, name, father_name, surname)
self.class_room = class_room
self.father = father
self.mother = mother
def get_class_room(self):
return self.class_room
def get_parents(self):
return self.father.get_full_name(), self.mother.get_full_name()
class Teacher(Person):
def __init__(self, name, father_name, surname, classes, subject):
Person.__init__(self, name, father_name, surname)
self.classes = classes
self.subject = subject
def get_subject(self):
return self.subject
def get_classes(self):
return self.classes
if __name__ == '__main__':
class_room = ['5 А', '6 Б', '7 В']
parents = [Person('Валерий', 'Павлович', 'Чкалов'),
Person('Василиса', 'Петровна', 'Чкалова'),
Person('Николай', 'Францевич', 'Гастелло'),
Person('Нина', 'Федоровна', 'Гастелло'),
Person('Юрий', 'Алексеевич', 'Гагарин'),
Person('Юлия', 'Андреевна', 'Гагарина')]
students = [Student('Виктория', 'Валерьевна', 'Чкалова', class_room[0], parents[0], parents[1]),
Student('Никита', 'Николаевич', 'Гастелло', class_room[1], parents[2], parents[3]),
Student('Юлий', 'Юрьевич', 'Гагарин', class_room[2], parents[4], parents[5])]
teachers = [Teacher('Иван', 'Иванович', 'Иванов', [class_room[0], class_room[1]], 'Алгебра'),
Teacher('Петр', 'Петрович', 'Петров', [class_room[2], class_room[1]],'Физика'),
Teacher('Сидор', 'Сидорович', 'Сидоров', [class_room[0], class_room[2]], 'Химия')]
st = set([val.get_class_room() for val in students])
print(st)
for cl_room in class_room:
st_list = [val.get_short_name() for val in students if val.get_class_room() == cl_room]
print(cl_room)
print(st_list)
student = students[0]
parents = student.get_parents()
print(parents) |
91f8a575fe48df1dab860130464397858a052e65 | CountessCherry/ShevaLabs | /laboratory_work_10.py | 1,552 | 3.6875 | 4 | # 1
s = input('введіть прізвище та ім\'я: ')
print(s[2])
y = len(s)
print(s[y - 2])
print(s[0:5])
print(s[0:y - 2])
print(s[0::2])
print(s[1::2])
print(s[y::-1])
print(s[y::-2])
print(y)
# 2
s = input('введіть символьний рядок: ')
whitespace = 1
for i in range(len(s) - 1):
if s[i] == ' ' and s[i + 1] != ' ' and s[i + 1] != '.':
whitespace = whitespace + 1
print('words =', whitespace)
s = s.replace(' ', ' ').replace(' ', ' ').replace(' ', ' ')
print(s)
# 3
def revers(s):
s = s.split()
s.reverse()
print(s[0], end=' ')
print(s[1])
string = input('введіть прізвище та ім\'я ')
revers(string)
# 4
s = input('введіть прізвище та ім\'я ')
y = len(s) // 2
s1 = s[0:y+1]
s2 = s[y:len(s)]
print(s2 + s1)
# 5
s = input('введіть рядок ')
sn = ''
for i in range(1, len(s)):
if i % 3 != 0:
sn = sn + s[i]
else:
sn = sn + ' '
print(s[0] + sn)
# 6
s = input('введіть прізвище, ім\'я, по батькові ')
s = s.split()
m = s[1]
n = s[2]
print(s[0], '{}.{}.'.format(m[0], n[0]))
# 7
s = input('введіть арифметичний вираз ').split()
dic = {'*': lambda a, b: int(a) * int(b), '/': lambda a, b: int(a) / int(b),
'+': lambda a, b: int(a) + int(b), '-': lambda a, b: int(a) - int(b)}
if (s[1] == '+' or s[1] == '-') and (s[3] == '*' or s[3] == '/'):
m = dic[s[1]](s[0], dic[s[3]](s[2], s[4]))
else:
m = dic[s[3]](dic[s[1]](s[0], s[2]), s[4])
print(m) |
238da82ef62cf39e288fd188dd25e6ab400ebb36 | johnrick10234/hello-world | /Homework-3/Homework_3_10.15.py | 633 | 3.71875 | 4 | #John Rick Santillan #1910045
class Team:
def __init__(self):
self.team_name="none"
self.team_wins=0
self.team_losses=0
def get_win_percentage(self):
percent = self.team_wins/(self.team_wins+self.team_losses)
return percent
if __name__=="__main__":
team = Team()
team_name=input()
team_wins = int(input())
team_losses = int(input())
team.team_wins = team_wins
team.team_losses=team_losses
if team.get_win_percentage()>=0.5:
print('Congratulations,','Team',team_name,"has a winning average!")
else:
print('Team',team_name,'has a losing average.') |
bc21f3453df80a210a8395815d8f80cb03e9237d | mehulawasthi20/leet-code-medium | /Solutions/count_tree_nodes.py | 646 | 3.640625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def countNodes(self, root: TreeNode) -> int:
def trav(root,count):
if root is None:
return count
else:
count += 1
count = trav(root.left,count)
count = trav(root.right,count)
return count
c = trav(root,0)
return c
|
9b21584f5fce4f1f63b21f1003c26400bd28e7a6 | mwsmales/YNAB_file_importer | /functions.py | 969 | 4.03125 | 4 | # Define a function to insert a column
def insert_col(header, data_array, header_to_insert, num_rows):
col_to_follow = len(header)
header.insert(col_to_follow + 1, header_to_insert)
# Next, insert the blank column into the data_array
for i in range(0, num_rows):
data_array[i].insert(col_to_follow + 1, '')
# function to delete a column
def delete_col(header, data_array, header_to_delete, num_cols, num_rows):
if 'Balance' in header:
for i in range(0, num_cols):
if header[i] == header_to_delete:
col_to_delete = i
del header[col_to_delete]
for i in range(0, num_rows):
del data_array[i][col_to_delete]
else:
print('Error, value does not exist in array')
quit()
# define a function to find a keyword in the header
def get_col_index(header, keyword, num_cols):
for i in range(0, num_cols):
if header[i] == keyword:
return i
|
00a97803fa93bc5e4e0c1ec184d38c4be10b5aa4 | abishamathi/python-program- | /number of words.py | 87 | 3.578125 | 4 | fname=input('Enter file name:')
num words=0
print('Number of words:')
print(num-words)
|
919dd0d1d05f5fc4ede905e8e41b24e37e8bd226 | lokymm/Proyectos-Python | /Clase32_Importar_Librerias.py | 144 | 3.8125 | 4 | import math
x=int(input("Ingrese el número a calcular la raiz Cuadrada: "))
Y=math.sqrt(x)
print("\nLa raiz cuadrada de ",x,"es",int(Y),"\n") |
4262a6a1c54ab81fe86be1a8fab49aea6983c453 | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200313/listas10.py | 553 | 3.953125 | 4 | #10-Escribe un programa que pida una palabra por pantalla y muestre por patnalla una lista con las consonantes, y el número de veces que aprecen en la palabra.
consonantes=[["b","c","d","f","g","h","j","k","l","m","n","ñ","p","q","r","s","t","v","w","x","y","z"],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]
print("Palabra:")
palabra=input()
for n in palabra:
if(n in consonantes[0]):
consonantes[1][consonantes[0].index(n)] += 1
for n in range(len(consonantes[0])):
if(consonantes[1][n]):
print(consonantes[0][n], ":", consonantes[1][n])
|
66f7100f8310832453a2063e47033b577ae898b6 | Ianh4526/Code | /Data Science and Machine Learning with Python - Hands On!/Distributions/NormaoGaussD.py | 373 | 3.65625 | 4 |
#Probability density Function
#Normal / Gaussian
import matplotlib.pyplot as plt
from scipy.stats import norm
x = np.arange(-3,3,0.001)
#creating a range of values
#range from -3 to 3
#incrementing 0.001
plt.plot(x, norm.pdf(x))
#probability density function PDF
plt.show()
mu = 5.0
sigma = 2.0
values = np.random.normal(mu, sigma, 10000)
plt.hist(values,50)
plt.show()
|
4e0aaabcaf9fe880a0dd1fe0fdf64a2be1948f70 | dfarfel/QA_Learning_1 | /Set/Set_task_8.1.py | 318 | 3.59375 | 4 | set1=set()
set2=set()
set3=set()
set1={10,150,6,32,28}
set2={32,200,15,10,3}
set3=set1|set2
print(set3)
set3.pop()
print(set3)
print(f'Maximum- {max(set3)}\nMinimum- {min(set3)}\nLength- {len(set3)}')
set4=set3.copy()
for i in range(1000,5000,1500):
set4.add(i)
print(set4)
set1.clear()
set2.clear()
set3.clear()
|
4d0ff1042542a5700d8c35fce90b7245387b12f1 | lucasbanksys/iniciandoPython | /Variados/Ex03.py | 323 | 3.953125 | 4 | maiorIdade = 0
menorIdade = 0
for i in range(1,8):
nascimento = int(input("Digite o ano de nascimento: "))
idade = 2021 - nascimento
if idade >= 18:
maiorIdade += 1
else:
menorIdade += 1
print(f"""
Das 7 pessoas inseridas sao:
{maiorIdade} maior de idade,
{menorIdade} menor de idade.
""") |
29f54807b5f379f0687083c0d26ab4c9e935d624 | rahultimbadiya/PythonDailyAssignment | /Assignment2/insert_into_list.py | 125 | 3.953125 | 4 | list1 = []
for i in range(5):
a = input("Please enter something to insert into list:")
list1.append(a)
print(list1) |
7cd310321237694630c418bd97b499777f516bcc | journeyluuuu/IE531_assignments | /HW2/prog_ass_HW2/Randomized_Selection_Rev.py | 3,214 | 3.78125 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Experimentally determining the statistics of the running-time of
# picking the k-th smallest number in an unordered/unsorted list of numbers
# using a randomly selected pivot (instead of the Median-of-Medians) and
# Recursion
#
# IE531: Algorithms for Data Analytics
# Written by Prof. R.S. Sreenivas
#
import sys
import argparse
import random
import numpy as np
import time
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
sys.setrecursionlimit(3000)
def sort_and_select(current_array, k) :
# sort the array
sorted_current_array = np.sort(current_array)
return sorted_current_array[k-1]
def randomized_select(current_array, k) :
if (len(current_array) == 1) :
return current_array[0]
else :
# pick a random pivot-element
p = current_array[random.randint(0,len(current_array)-1)]
# split the current_array into three sub-arrays: Less_than_p, Equal_to_p and Greater_than_p
Less_than_p = []
Equal_to_p = []
Greater_than_p = []
for x in current_array :
if (x < p) :
Less_than_p.extend([x])
if (x == p) :
Equal_to_p.extend([x])
if (x > p) :
Greater_than_p.extend([x])
if (k < len(Less_than_p)) :
return randomized_select(Less_than_p, k)
elif (k >= len(Less_than_p) + len(Equal_to_p)) :
return randomized_select(Greater_than_p, k - len(Less_than_p) - len(Equal_to_p))
else :
return p
# Number of Trials
number_of_trials = 1000
# arrays containing mean- and std-dev of running time as a function of
# array size starting from 100 to 100000 in steps of 100
mean_running_time = []
std_dev_running_time = []
# cycle through a bunch of array sizes, where "k" is randomly chosen
for j in range(1, 40) :
array_size = 100*j
k = random.randint(1,array_size)
# fill the array with random values
my_array = [random.randint(1,100*array_size) for _ in range(array_size)]
# run a bunch of random trials and get the algorithm's running time
running_time = []
for i in range(1, number_of_trials) :
t1 = time.time()
answer1 = randomized_select(my_array,k-1)
t2 = time.time()
answer2 = sort_and_select(my_array, k)
running_time.extend([t2-t1])
print(answer1,answer2)
if (answer1 != answer2) :
print ("Something went wrong")
exit()
mean_running_time.extend([np.mean(running_time)])
std_dev_running_time.extend([np.std(running_time)])
# linear fit
t = np.arange(100, 4000, 100)
z1 = np.polyfit(t, mean_running_time, 1)
p1 = np.poly1d(z1)
z2 = np.polyfit(t, std_dev_running_time, 1)
p2 = np.poly1d(z2)
# plot the mean and standard deviation of the running-time as a function of
# array-size
plt.plot(t, mean_running_time, 'r', t, std_dev_running_time, 'g', t, p1(t), 'r-', t, p2(t), 'g-')
plt.show()
# printing the slopes of the Linear Regressor
print("Slope of the Linear Regressor for Mean-Running-Time = ", z1[0])
print("Slope of the Linear Regressor for Std-Dev-Running-Time = ", z2[0])
|
3a3344bd2d3f79f78b73cc91d14a28dc4f5b358d | Axoxl/python-lessons | /урок 2/2.6.py | 358 | 4.03125 | 4 | a = input("Введите название товара")
b = input("Введите цену товара")
c = input("Введите количество товара")
e = input("Введите единицу измерения товара")
my_goods = dict(name=a, price=b, count=c, mes=e)
for i, my_goods in enumerate(my_goods, 1):
print(my_goods)
|
942cb1353ef06295782f7d9b39d42d3cff0983e0 | Art-And/python_basics | /prime_numbers.py | 885 | 4.09375 | 4 | def its_prime(number):
counter = 0
for i in range(1, number + 1):
if i == 1 or i == number:
continue
if number % i == 0:
counter += 1
if counter == 0:
return True
else:
return False
def run():
number = int(input("Write a number: "))
if its_prime(number):
print("It's prime number")
else:
print("It isn't prime number")
# def factorial(n):
# fact = 1
# if n < 0:
# return 0
# elif n == 0:
# return 1
# while (n > 1):
# fact *= n
# n -= 1
# return fact
# def main():
# numero = int(input("Escoge un numero: "))
# wilson = factorial(numero - 1) + 1
# #print(wilson)
# if wilson % numero == 0:
# print("El numero es primo")
# else:
# print("No es primo")
if __name__ == '__main__':
run() |
9c1ed3463c632490fea2827be07c3e6522205140 | jaford/thissrocks | /Python_Class/py3intro3day/EXAMPLES/strings.py | 480 | 3.703125 | 4 | #!/usr/bin/env python
a = "My hovercraft is full of EELS"
#print("original:", a)
# print("upper:", a.upper())
# print("lower:", a.lower())
# print("swapcase:", a.swapcase()) # <1>
# print("title:", a.title()) # <2>
# print("e count (normal):", a.count('e'))
#print("e count (lower-case):", a.lower().count('e')) # <3>
#print("found EELS at:", a.find('EELS'))
#print("found WOLVERINES at:", a.find('WOLVERINES')) # <4>
#
b = "graham"
print("Capitalized:", b.capitalize()) # <5>
|
94765f4ddb10e8330785221fcae6ae99d2e69863 | crosse331/postApoc | /postApoc.py | 7,477 | 3.5 | 4 | #Первый прототип
import random as rnd
import math
import numpy
print("Данная игра про выживание в постапокалипсисе (многое еще не реализовано), графона тоже нету, т.к. прототип")
print("P - игрок, E - враг, W - стена, D - дверь, Q - закрытая дверь(нужен ключ), 0 - пустое место, K - переход на след. уровень, k - ключ для Q, m - аптечка, восстанавливает 3 хп, движение происходит с помощью набора w/a/s/d + Enter для движения вверх, влево, вправо, вниз соответственно, атаковать врага - дивжение в его сторону, враг атакует двигаясь на игрока")
input("Нажмите Enter, что бы продолжить")
Field = [[] for i in range(6)]
for i in range(6):
for j in range(6):
Field[i].append('0')
Actions = ['a','d','w','s']
Items = ['k','K','m']
QuestItems = ['K']
class Player:
x = 0
y = 0
Hp = 10
MaxHp = 10
Shoots = 2
MaxShoots = 6
Score = 0
inventory = []
def __init__(self):
self.x = 0
self.y = 0
def SecureTryToMove(self,_x = 0,_y = 0):
if (self.x+_x<0 or self.x+_x>5 or self.y+_y<0 or self.y+_y>5):
return
if Interact(self.y+_y, self.x+_x) == 1:
Field[self.y][self.x] = '0'
self.x+=_x
self.y+=_y
Field[self.y][self.x] = 'P'
self.Score-=1
def __str__(self):
result = "Игрок: ХП:%s/%s,Заряды:%s/%s"%(self.Hp,self.MaxHp,self.Shoots,self.MaxShoots)
result+='\n'
result+= "Инвентарь: " + str(self.inventory) + '\n'
result+= "Ваш счет: " + str(self.Score)
return result
def UpdateLogic(self):
if self.Shoots<self.MaxShoots:
if self.UseItemFromInv('p') == 1:
self.Shoots+=1
if self.inventory.count('K')>0:
self.inventory.remove('K')
StartNewLevel()
if self.Hp<7 and self.inventory.count('m')>0:
self.inventory.remove('m')
self.Hp+=3
def AddToInv(self,item):
self.inventory.append(item)
self.Score+=3
self.inventory.sort()
def UseItemFromInv(self,item):
if self.inventory.count(item) == 0:
return 0
else:
self.inventory.remove(item)
return 1
class Enemy:
hp=3
x=0
y=0
isSeePlayer = 0
def __init__(self,_x,_y):
self.x = _x
self.y = _y
def RandomMove(self):
_x = rnd.randint(-1,1)
_y = 0
if _x == 0:
_y = rnd.randint(-1,1)
if (self.x+_x<0 or self.x+_x>5 or self.y+_y<0 or self.y+_y>5):
return
if EnemyInteract(self.y+_y, self.x+_x,self) == 1:
Field[self.y][self.x] = '0'
self.x+=_x
self.y+=_y
Field[self.y][self.x] = 'E'
def Move(self,_x,_y):
if (self.x+_x<0 or self.x+_x>5 or self.y+_y<0 or self.y+_y>5):
return
if EnemyInteract(self.y+_y, self.x+_x,self) == 1:
Field[self.y][self.x] = '0'
self.x+=_x
self.y+=_y
Field[self.y][self.x] = 'E'
def MoveToPlayer(self):
_x = player.x-self.x
_y = player.y-self.y
if _x != 0:
self.Move(numpy.sign(_x),0)
elif _y != 0:
self.Move(0,numpy.sign(_y))
def CheckPlayer(self):
if math.sqrt((player.x-self.x)**2 + (player.y-self.y)**2)<2:
self.isSeePlayer = 1
else:
self.isSeePlayer = 0
def UpdateLogic(self):
self.CheckPlayer()
if self.isSeePlayer == 0:
self.RandomMove()
else:
self.MoveToPlayer()
player = Player()
enemies = []
def StartNewLevel():
player.x=0
player.y=0
player.Score+=10
Clear()
GenerateField()
def DrawWorld():
#Должно быть приблизительно 19 строк для нормального обновления экрана
print("\n\n\n")#\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
print(str(player))
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
global Field
for i in range(6):
for j in range(6):
if Field[i][j] == 'P':
Field[i][j] = '0'
if Field[i][j] == 'E':
Field[i][j] = '0'
Field[player.y][player.x] = 'P'
for i in enemies:
Field[i.y][i.x] = 'E'
for i in range(6):
for j in range(6):
#if math.sqrt((player.x-j)**2 + (player.y - i)**2)<2.5:
print(Field[i][j],end='')
#else:
# print(' ',end = '')
print()
def Interact(y,x):
global Field
a = -1
try:
a = Items.index(Field[y][x])
except ValueError:
a = -1
if a>=0:
player.AddToInv(Items[a])
Field[y][x] = '0'
return 1
if Field[y][x] == '0':
return 1
elif Field[y][x] == 'D':
Field[y][x] = '0'
return 0
elif Field[y][x] == 'Q':
if player.UseItemFromInv('k') == 1:
Field[y][x] = '0'
elif Field[y][x] == 'E':
e = FindEnemy(y,x)
if type(e) is Enemy:
e.hp-=1
else:
return 0
def FindEnemy(y,x):
for e in enemies:
if e.y == y and e.x == x:
return e
def EnemyInteract(y,x,enemy):
if Field[y][x] == '0':
return 1
elif Field[y][x] == 'P':
player.Hp-=1
#enemy.hp-=1
return 0
else:
return 0
def GenerateField():
a = rnd.randint(0,2)
needToBeSpawned = ['K']
numOfFloor = 0
if a == 0:
startx = rnd.randint(1,3)
starty = rnd.randint(1,3)
for i in range(starty,starty+3):
for j in range(startx,startx+3):
if i == starty or i == starty+2 or j == startx or j == startx+2:
Field[i][j] = 'W'
if i == starty+1 and j != startx+2:
if rnd.randint(0,1) == 0:
Field[i][j] = 'D'
else:
Field[i][j] = 'Q'
needToBeSpawned.append('k')
else:
Field[i][j] = 'FF'
numOfFloor+=1
if a == 1:
startx = rnd.randint(1,2)
starty = rnd.randint(1,2)
for i in range(starty,starty+4):
for j in range(startx,startx+4):
if i == starty or i == starty+3 or j == startx or j == startx+3:
Field[i][j] = 'W'
if i == starty+1 and j != startx+3:
if rnd.randint(0,1) == 0:
Field[i][j] = 'D'
else:
Field[i][j] = 'Q'
needToBeSpawned.append('k')
else:
Field[i][j] = 'FF'
numOfFloor+=1
numOfAddectiveItems = rnd.randint(0,2)
for i in range(numOfAddectiveItems):
needToBeSpawned.append(Items[rnd.randint(0,len(Items)-1)])
for i in needToBeSpawned:
count = 0
while(1):
a = rnd.randint(0,5)
b = rnd.randint(0,5)
if a == 0 and b == 0:
continue
if QuestItems.count(i)>0 and numOfFloor>0:
if Field[a][b] == 'FF':
Field[a][b] = str(i)
break
else:
if Field[a][b] == '0':
Field[a][b] = str(i)
break
count+=1
if count>100:
break
for i in range(6):
for j in range(6):
if Field[i][j] == 'FF':
Field[i][j] = '0'
c = rnd.randint(0,3)
for i in range(c):
count = 0
while(1):
a = rnd.randint(0,5)
b = rnd.randint(0,5)
if a == 0 and b == 0:
continue
if Field[a][b] == '0':
enemies.append(Enemy(b,a))
break
count+=1
if count>100:
break
def Clear():
global Field
for i in range(6):
for j in range(6):
Field[i][j] = '0'
enemies.clear()
def Command(d):
if d == 0:
player.SecureTryToMove(_x = -1, _y = 0)
elif d == 1:
player.SecureTryToMove(_x = 1,_y = 0)
elif d == 2:
player.SecureTryToMove(_x = 0,_y = -1)
else:
player.SecureTryToMove(_x = 0,_y = 1)
Clear()
GenerateField()
DrawWorld()
while (1):
player.UpdateLogic()
for e in enemies:
if e.hp>0:
e.UpdateLogic()
else:
enemies.remove(e)
player.Score+=10
DrawWorld()
inp = str(input())
try:
ind = Actions.index(inp)
except ValueError:
ind = -1
if ind>=0:
Command(ind)
|
d635deb052b4e52a00a83d7266b94db9eda1cfa5 | 1Bitcoin/python-old | /TrashPython/подготовка/работа с массивами/create_kv_matrix_python_style.py | 228 | 3.890625 | 4 | '''
создать за 1 цикл кв. матрицу (выше гл. диаг = *, ниже #, на диаг. @)
'''
N = 5
a = [0]*N
for i in range(N):
a[i] = ['*']*i + ['@'] + ['#']*(N-i-1)
for row in a:
print(row)
|
934e33dc26fbaeb695ac44b8f9addafa5dc1168e | TesterlifeRaymond/LearningFluentyPython | /tests/test_proptery.py | 1,777 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
LearningFluentyPython.test_proptery
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
learning python cookbook
:copyright: (c) 2018 by Raymond.
:license: LICENSE_NAME, see LICENSE for more details.
:last modified by 2018-07-02 16:38:38
"""
import math
def check_attributes(**kwargs):
def decorate(cls):
for key, value in kwargs.items():
try:
assert type(getattr(cls, key)) is value,\
"TypeError: {} is must be {}". format(key, value)
except AssertionError as err:
print("[ AssertionError ]: {} attr ".format(cls.__name__), err)
return cls
return decorate
@check_attributes(
name=str,
age=int
)
class CheckString:
name = "Ray"
age = "10"
class LazyProperty:
def __init__(self, func):
"""
init LazyProperty
@func: func or method
"""
self.func = func
def __get__(self, instance, cls):
"""
descriptor prot
"""
if instance is None:
return self
else:
value = self.func(instance)
setattr(instance, self.func.__name__, value)
return value
class Circle:
def __init__(self, radius):
self.radius = radius
@LazyProperty
def area(self):
print("Computing area")
return math.pi * self.radius ** 2
class Data:
""" data struct """
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
if __name__ == "__main__":
data = Data("Ray", 20, "北京")
print(type(vars(data)), vars(data))
circle = Circle(4.0)
print(circle.area)
circle.radius = 15.0
print(circle.area)
|
d4e23323e3a7d8b58d71b96b241c7043e374f4a6 | tiagosantos-dev/curso-python | /while.py | 598 | 3.96875 | 4 | import math
print("Informe o valor de A --")
a = float(input())
while a == 0:
print("Informe o valor de A")
a = float(input())
if a == 0:
print("não é permitido o valor zero")
a = float(input())
print("Informe o valor de B")
b = float(input())
print("Informe o valor de C")
c = float(input())
sim_or_nao = input("Ja acabou jessica")
while sim_or_nao != "nao":
sim_or_nao = input("Ja acabou jessica")
while True:
result = input("Digite Sair para sair:")
result= result.lower()
if result == "sair":
break
print("Bye")
|
fd25669a7b56cf47034b3911d8517f2626f06d47 | S-VIN/education | /geekbrains/python/lesson7/1.py | 1,838 | 3.609375 | 4 | # Отсортируйте по убыванию методом пузырька одномерный целочисленный массив, заданный случайными числами на промежутке [-100; 100).
import random
import cProfile
def createList(n):
mas = []
for i in range(0, n):
mas.append(random.randint(-100, 99))
return mas
def checkMas(mas):
for i in range(0, len(mas) - 1):
if(mas[i] < mas[i + 1]):
return False
return True
# идея усовершенствования такая: мы 10 раз проверяем отсортирован ли массив.
# Если он отсортировался за половину проходов, то дальше можно не сортировать.
# Практика показала, что на случайных массивах прирост в производительности
# незначительный, однако на почти отсортированных массивах это должно сильно
# ускорять сортировку.
def newBubbleSort(mas):
check = int(len(mas) / 10)
for i in range(0, len(mas)):
if(i % check == 0):
if(checkMas(mas)):
return mas
for j in range(0, len(mas) - 1):
if(mas[j] < mas[j + 1]):
mas[j], mas[j + 1] = mas[j + 1], mas[j]
return mas
def bubbleSort(mas):
for i in range(0, len(mas)):
for j in range(0, len(mas) - 1):
if(mas[j] < mas[j + 1]):
mas[j], mas[j + 1] = mas[j + 1], mas[j]
return mas
def main():
newBubbleSort(createList(10000))
bubbleSort(createList(10000))
print(bubbleSort(createList(int(input('write the length of array\n')))))
cProfile.run('main()')
|
3277d29c89b9dc25d279105a6560cba6783a4903 | kivhift/pu | /src/pu/linelistio.py | 2,503 | 3.734375 | 4 | #
# Copyright (c) 2011-2012 Joshua Hughes <kivhift@gmail.com>
#
import os
class LineListIO(object):
'''
This class wraps a list of lines so as to be able to use them as a
file-like object. The main objective is to be able to have a read method
that will return the "file data" with new lines automatically added to the
ends of lines. The main reason for the existence of this class is to be
able to take POP3.retr()ed line lists and write them to file without having
to build the whole file in memory since email can sometimes be bloated due
to attachments and the like.
'''
def __init__(self, linelist = []):
self.setLineList(linelist)
def setLineList(self, linelist):
'''
Set the internal list of lines to the new value and reset the
internal state.
'''
self._lines = linelist
self._ln = 0
self._intralnpos = 0
self._pos = 0
def __size(self):
sz = 0
for ln in self._lines:
sz += len(ln) + 1
return sz
def read(self, n = None):
if n is not None:
to_go = n
else:
to_go = self.__size() - self._pos
if 0 == to_go: return ''
buf = ''
while self._ln < len(self._lines):
delta = len(self._lines[self._ln]) - self._intralnpos
if to_go < delta: delta = to_go
if self._intralnpos < len(self._lines[self._ln]):
buf += self._lines[self._ln][
self._intralnpos : self._intralnpos + delta]
self._intralnpos += delta
to_go -= delta
if to_go > 0 and self._intralnpos == len(self._lines[self._ln]):
buf += '\n'
to_go -= 1
self._ln += 1
self._intralnpos = 0
if 0 == to_go: break
self._pos += len(buf)
return buf
def tell(self):
return self._pos
def seek(self, offset, whence = os.SEEK_SET):
if os.SEEK_SET == whence:
if 0 != offset:
raise NotImplementedError('Can only seek to start of file.')
self._ln = self._pos = 0
elif os.SEEK_END == whence:
if 0 != offset:
raise NotImplementedError('Can only seek to end of file.')
self._ln = len(self._lines)
self._pos = self.__size()
else:
raise ValueError('Invalid whence.')
self._intralnpos = 0
|
ff890854c93bc8953aae7b9658eadefb03decf62 | Levintsky/topcoder | /python/leetcode/string/1392_longest_happy_prefix.py | 1,156 | 3.90625 | 4 | """
1392. Longest Happy Prefix (Hard)
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
"""
class Solution(object):
def longestPrefix(self, s):
"""
:type s: str
:rtype: str
"""
res, l, r, mod = 0, 0, 0, 10**9 + 7
for i in xrange(len(s) - 1):
l = (l * 128 + ord(s[i])) % mod
r = (r + pow(128, i, mod) * ord(s[~i])) % mod
if l == r: res = i + 1
return s[:res] |
6ed2372020c38106f49276ac87c77a322df49068 | parduman/lovebabbar450 | /tree/mirror Tree.py | 1,163 | 3.984375 | 4 |
class Node:
def __init__(self, data) -> None:
self.data = data
self.left = None
self.right = None
def mirriorTree(node):
# print(node.data, end=' ')
if(not node):
return
mirriorTree(node.left)
mirriorTree(node.right)
swap = node.right
node.right = node.left
node.left = swap
# print(node.right.data if node.right else '', node.left.data if node.left else '')
# Function to convert a given binary tree into its mirror
def convertToMirror(root):
# base case: if the tree is empty
if root is None:
return
# convert left subtree
convertToMirror(root.left)
# convert right subtree
convertToMirror(root.right)
# swap left subtree with right subtree
temp = root.left
root.left = root.right
root.right = temp
def preorder(root):
if root is None:
return
print(root.data, end=' ')
preorder(root.left)
preorder(root.right)
tree = Node(5)
tree.left = Node(6)
tree.right = Node(7)
tree.left.left = Node(2)
tree.left.right = Node(4)
preorder(tree)
print()
mirriorTree(tree)
# convertToMirror(tree)
preorder(tree)
|
e430935e6ca6b5fadf8821e30913219ef30ee80d | pastorcmentarny/DomJavaKB | /python/src/tools/generators/parkrun.py | 2,438 | 3.515625 | 4 | import json
distance = float(5)
def check_for_personal_best(result: dict) -> str:
if result["personal_best"]:
return "it is my new personal best."
else:
return "my personal best stays at {}".format(result["personal_best_time"])
def generate_for_instagram(data):
result = """My {} #parkrun #run event number {} at #rickmansworth.
I was {} out of {} runners.
My time was {} with an average pace of {}min/km and an average speed of {}km/h, and {}.
My #running report can be found here: {{URL}}""" \
.format(str(data['event']['my_run']), str(data['event']['number']),
str(data['result']['place']), str(data['result']['all_runners']),
str(data['result']['time']),
calculate_pace(str(data['result']['time'])),
calculate_average_speed(str(data['result']['time'])),
check_for_personal_best(data['result']))
print(result)
def calculate_pace(time) -> str:
minutes, seconds = time.split('.')
total_seconds = (int(minutes) * 60) + int(seconds)
seconds_per_kilometer = float(total_seconds) / distance
minutes_per_kilometer = int(seconds_per_kilometer / 60)
seconds_remainder = int(seconds_per_kilometer - (minutes_per_kilometer * 60))
return '{}:{:0=2d}'.format(minutes_per_kilometer, seconds_remainder)
def calculate_average_speed(time) -> str:
minutes, seconds = time.split(".")
result_in_second = int(minutes) * 60 + int(seconds)
h = result_in_second / 3600
result = distance / h
return '{:.2f}'.format(result)
def generate_for_blog():
"""I ran in Rickmansworth Parkrun no.XXX on XXXX.2019.
Pictures from the race can be found on my Instagram: {{URL}}
The weather was XXXX. It was XXXX and temperature around 18°C.
RESULTS:
My weight on that day was XXX.X kg.
My result was XX.XX, and I was XXXth out of XXX.
My personal best remains at XX.XX.
In my age category: I was XX out of XX runners in today's run.
In Top performances table in all Rickmansworth's parkrun runs, I am XXX out of XXX."""
def generate_data():
data = config()
if data['attend']:
generate_for_instagram(data)
generate_for_blog()
else:
print("I didn't run, so why I print this?")
def config() -> dict:
path = 'cfg.json'
with open(path, 'r') as email_config:
return json.load(email_config)
if __name__ == '__main__':
generate_data()
|
8cb2b2b5e664931550e283a30cce438220b05b7e | madduradithya/The-Python-Workbook | /Ex20_Ideal_Gas_Law.py | 1,355 | 3.828125 | 4 | # Exercise 20: Ideal Gas Law
# The ideal gas law is a mathematical approximation of the behavior of gasses as
# pressure, volume and temperature change. It is usually stated as:
# PV = nRT, where P is the pressure in Pascals, V is the volume in liters, n is the amount of
# substance in moles, R is the ideal gas constant, equal to 8.314 J / mol K , and T is the
# temperature in degrees Kelvin.
# Write a program that computes the amount of gas in moles when the user supplies
# the pressure, volume and temperature. Test your program by determining the number
# of moles of gas in a SCUBA tank. A typical SCUBA tank holds 12 liters of gas at
# a pressure of 20,000,000 Pascals (approximately 3,000 PSI). Room temperature is
# approximately 20 degrees Celsius or 68 degrees Fahrenheit.
# Hint: A temperature is converted from Celsius to Kelvin by adding 273.15
# to it. To convert a temperature from Fahrenheit to Kelvin, deduct 32 from it,
# multiply it by 5/9 and then add 273.15 to it.
pressure = float(input("Enter the pressure: "))
volume = float(input("Enter the volume: "))
temperature_in_celsius = float(input("Enter the temperature (in celsius): "))
temperature_in_kelvin = temperature_in_celsius + 273.15
amount_of_gas_in_moles = (pressure * volume) / (8.314 * temperature_in_kelvin)
print("Amount of gas in moles:", amount_of_gas_in_moles)
|
c141f14302dd823895c3525485d0e7de053c96b5 | ArunPrasad017/python-play | /leet-coded/strings/ip_address_defang.py | 195 | 3.609375 | 4 | def defangIPaddr(address):
str2 = ""
for i in range(0, len(address)):
if address[i] == ".":
str2 += "[.]"
else:
str2 += address[i]
return str2
|
6b733b42b591047fb1dfafe92f5eee14e408b8f2 | dbarbella/analogy | /separate_analogy/separate_analogy.py | 3,132 | 3.703125 | 4 | import csv
import statistics
sampleRatings = {} # dict to hold the data from csv file
incompleteRating = {}
analogySample = {}
notAnalogySample = {}
unsureSample = {}
# Method to load data from csv to sampleRatings
def loadData(fileName):
with open(fileName, 'r') as file:
fileReader = csv.reader(file)
next(fileReader, None)
duplicates = []
# reading the csv row
for row in fileReader:
id = row[0]
text = row[1]
if id in duplicates:
continue
duplicates.append(id)
# Append if dict has an entry
if id in sampleRatings:
if row[2] == '': continue
try:
rating = int(row[2])
if rating<1 or rating>3:
print("Error: Wrong rating type (Needs to be 1, 2 or 3)\n" + str(row))
break
sampleRatings[id][1].append(rating)
except ValueError:
print("Error: Wrong rating type (Needs to be 1, 2 or 3)\n" + str(row))
# Create a new entry if not found
else:
if row[2] == '':
continue
rating = int(row[2])
sampleRatings[id]=(text,[rating])
# filter the data with threshold reviews of (n)
def filterData(threshold):
# Copy incomplete data to incompleteRating
for key, value in sampleRatings.items():
if len(value[1]) < threshold:
incompleteRating[key] = value
# remove incomplete rating from sampleRatings
for key in incompleteRating:
del sampleRatings[key]
# sort analogies by average of ratings
def analogyRelegate():
for key, value in sampleRatings.items():
if statistics.mean(value[1]) < 2:
analogySample[key] = value
elif statistics.mean(value[1]) > 2:
notAnalogySample[key] = value
elif statistics.mean(value[1]) == 2:
unsureSample[key] = value
# Method to export dictionary as CSV files
def exportCSV(fileName, samples):
with open(fileName, 'w') as csvfile:
writer = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
writer.writerow(['id', 'text', 'ratings'])
for key, value in samples.items():
text = value[0]
ratingList = [rating for rating in value[1]]
outputRow = [key, text]
outputRow.extend(ratingList)
writer.writerow(outputRow)
print(fileName+".csv export sucess.")
def main():
# csv file names to import from
files = ['Reviewer 1.csv','Reviewer 2.csv','Reviewer 3.csv']
# loading data from files list
for fileName in files:
loadData(fileName)
filterData(3)
analogyRelegate()
exportCSV('analogy_sample.csv', analogySample)
exportCSV('not_analogy_sample.csv', notAnalogySample)
exportCSV('unsure_sample.csv', unsureSample)
print("Success")
main() |
21231f9e261f2479ba07e1fff8788e598a23aefa | Spas52/Python_Fundamentals | /Functions - Exercise/09. Factorial Division.py | 512 | 3.953125 | 4 | first_number = int(input())
second_number = int(input())
def factorial_division(num1=first_number, num2=second_number):
first_number_factorial = 1
second_number_factorial = 1
for number1 in range(1, num1 + 1):
first_number_factorial *= number1
for number2 in range(1, num2 + 1):
second_number_factorial *= number2
final_result = first_number_factorial / second_number_factorial
print(f"{final_result:.2f}")
return exit()
print(factorial_division()) |
14fa09c56cd3a5ca5a69a2de50a6034a755e7a61 | stonarini/codewars | /kyu-5/where_my_anagrams_at.py | 1,234 | 4.03125 | 4 | # https://www.codewars.com/kata/523a86aa4230ebb5420001e1
# Where My Anagrams At?
# First Implementation 15/10/2021
def anagrams(word, words):
# create array for valid anagrams
anagramArray = []
# set that the current word is a valid anagram
isAnagram = True
# for every word (possible anagram) in the list of words
for possibleAnagram in words:
# if the length of the word and the possible anagram differ
if len(word) != len(possibleAnagram):
# the possible anagram is not an anagram
continue
# for every letter in the word
for letter in word:
# if the count of letters in the word and in the possible anagram differ
if word.count(letter) != possibleAnagram.count(letter):
# the current possible anagram is not an anagram
isAnagram = False
# exit the loop because it cannot be an anagram
break
if isAnagram:
# add the anagram to the anagrams array
anagramArray.append(possibleAnagram)
else:
# reset the isAnagram boolean
isAnagram = True
#return the array of anagrams
return anagramArray
|
f220dde29b7623e09188c0410389b115787c0a6c | bencam/data-structures-and-algorithms | /binary_search.py | 793 | 4.3125 | 4 | #!/usr/bin/env python
def binary_search(input_array, value):
"""Returns the index of the value passed in or a -1 if
the value does not exist in the list.
Assumes the array (input_array) contains only unique items
Assumes the array is organized in increasing order"""
low = 0
high = len(input_array) - 1
while low <= high:
mid = (low + high) / 2 # See note below
if input_array[mid] == value:
return mid
elif value > input_array[mid]:
low = mid + 1
else:
high = mid - 1
return -1
"""
Note: in Python 3, normal division yields decimals
(e.g. `7 / 2` returns `3.5`), which would cause problems
for this algorithm. Floor division (i.e. `//`) in Python 3,
however, yields whole integers.
"""
|
e59123f9394bac3a8c0590914bad72e7799dfb18 | shivaenigma/bitcointools | /bitcointools/jsonToCSV.py | 555 | 3.53125 | 4 | #!/usr/bin/env python
#
# Reads an array of JSON objects and writes out CSV-format,
# with key names in first row.
# Columns will be union of all keys in the objects.
#
import csv
import json
import sys
json_string = sys.stdin.read()
json_array = json.loads(json_string)
columns = set()
for item in json_array:
columns.update(set(item))
writer = csv.writer(sys.stdout)
writer.writerow(list(columns))
for item in json_array:
row = []
for c in columns:
if c in item: row.append(str(item[c]))
else: row.append('')
writer.writerow(row)
|
c9d39727413dd42838581f7c8a96c6ff29ca909a | christopher-henderson/thesis | /backtrack/fib.py | 966 | 3.71875 | 4 | # Don't...pay too much attentinon to this, because I didn't spend a whole lot of time on it.
# This is a terrible way to solve the Fibonacci sequence, but it does add evidence towards the idea that
# if you can represent your problem as a graph, then this function can drive the solution.
from backtrack import backtrack
N = 6
mod = N % 2
memo = {
0: 1,
1: 1
}
def first(candidate):
return None if candidate is 1 or candidate is 0 else candidate - 1
def next(candidate):
if candidate is N:
return None
if candidate % 2 is mod:
return None
return candidate - 1
def reject(P, candidate):
return False
def accept(P):
if len(P) is not 0 and P[-1] in memo:
return True
return False
def add(P, candidate):
P.append(candidate)
def remove(P):
P.pop()
def output(P):
for val in P[-2::-1]:
memo[val] = memo[val - 1] + memo[val - 2]
print(memo[N])
if __name__ == '__main__':
backtrack(N, first, next, reject, accept, add, remove, output) |
dd2362cd863ccde01188192eb53850fceaf42e76 | suddu99/FileHandling | /File.py | 1,268 | 4.03125 | 4 | import sys
import os
import fileinput
# read the first file
file1 = open("usermanual.txt", "r")
# read the second file
file2 = open("usermanual1.txt", "r+")
#open third file
file3 = open("usermanual2.txt", "w")
# copy contents of first in second
op = input("Which feature to execute?")
if op == "copy":
for data in file1:
file2.write(data)
#replace a particular word in the file
elif op == "replaceWord":
file2 = open("usermanual1.txt", "rt")
word1 = str(input("Enter word to be replaced"))
word2 = str(input("Enter the new word"))
for line in file2:
file3.write(line.replace(word1, word2))
file2.close()
#length of the string
elif op == "len":
file2 = open("usermanual1.txt","rt")
n=file2.read()
l=len(n)
print("Length of file ",l)
file2.close()
#convert to upper case
elif op == "upper":
file2 = open("usermanual1.txt","rt")
for letter in file2:
file3.write(letter.upper())
file2.close()
#conver to lower case
elif op == "lower":
file2 = open("usermanual1.txt","rt")
for letter in file2:
file3.write(letter.lower())
file2.close()
else:
print("No operation")
file1.close()
file2.close()
file3.close()
|
acc7c38560017e0fe248cc15a3c98ec05b136a97 | aishwarya9879/python-learnings | /ifcondition.py | 891 | 3.953125 | 4 | def getnumber():# declaring a method
return 1#returing a value
result =getnumber() # storing a functions return value in temp
print(result) #printing the value of temp
def getresult(name): #decaring a method with arguments with variable name name
return name #retuning a value tothe method with argument "ashgulli"
output = getresult("ash") #calling a function with argument value
print(output)
#printing a value of temp variable
output = getresult("gulli") #calling a function with argument value
print(output)
def getname(person1,person2):
print(person1 ,"-----" ,person2)
return person1+person2
out= getname("a","g")
print(out)
str =getname("prasad","ashlee")
print(str)
def getpetname(one,two):
print(one,"---" ,two)
returnone+two
out = getname("ash","gulli")
print(out)
out = getname("tinko","bujii")
print(out)
|
017caf136889956ad0148e6c86574c29b5d6bacc | mattheww22/COOP2018 | /Chapter03/U03_Ex_16_fibonacci.py | 839 | 4.28125 | 4 | # U03_Ex_16_fibonacci.py
#
# Author: Matthew Wiggans
# Course: Coding for OOP
# Section: A3
# Date: 29 Oct 2018
# IDE: PyCharm
#
# Assignment Info
# Exercise: 16
# Source: Python Programming
# Chapter: 3
#
# Program Description
#
# This program computes the number of fibonacci numbers defined by a user.
#
# Algorith (pseudocode)
#
# print program description
# Get input of number of sequences
# if terms is 1 print 1
# if terms = 2 print 1 1
# if else, compute other terms, print as you go
#
def main():
print("This program prints the fibonacci sequence.")
n = int(input("How many numbers do you want? "))
a = 1
b = 1
if n == 1:
print("1")
elif n == 2:
print("1 1")
for i in range(2, n):
c = a + b
print(c, end=" ")
a = b
b = c
main()
|
722b99fc537dcb5dc0d406a2adac53d8847fe824 | cianconway/Interview_Questions | /object_oriented.py | 511 | 3.75 | 4 | class Person(object):
def __init__(self, name):
self.name = name
def reveal_identity(self):
print "My name is {}".format(self.name)
class SuperHero(Person):
def __init__(self, name, hero_name):
super(SuperHero, self).__init__(name)
self.hero_name = hero_name
def reveal_identity(self):
super(SuperHero, self).reveal_identity()
print ".. and my alter ego is {}".format(self.hero_name)
cian = Person('Cian')
cian.reveal_identity()
wade = SuperHero('Wade Wilson', 'Deadpool')
wade.reveal_identity() |
9359a05fbde99f2daba07b84cf7fd44be8af5261 | magicandcode/python-study-circle | /hangman/game_helpers.py | 4,933 | 3.96875 | 4 | from typing import Any, Callable, Dict, List, Optional
import random
# Seed to make our randomness more predictable during development.
random.seed(42)
def get_words(word_count: Optional[int] = None,
filename: str = './words.txt') -> List[str]:
"""Return list with unique upper case words from text file.
Number of words can be less but never greater than word_count.
"""
try:
# Open file in reading mode to read each line and save as a list.
with open(filename, 'r') as f:
words = f.readlines()
# Each word ends with a newline character (\n) and could be in any case.
# To normalise the words we remove trailing whitespace and convert to
# upper case. Normally one would choose lowercase but we want the
# answer in upper case anyway for a prettier output.
normalised_words = [word.strip().upper() for word in words]
# Remove duplicate words.
normalised_words = list(set(normalised_words))
# Randomise words before slicing.
random.shuffle(normalised_words)
# If word_count is not set, return all words.
if word_count is None:
return sorted(normalised_words)
# Sort after slicing; we want randomised words in our slice.
return sorted(normalised_words[:word_count])
except FileNotFoundError:
raise ValueError(f'Invalid file path: {filename}')
def get_game_solution(words: List[str]):
"""Get random word from list of words to use as game solution.
Remove word from list to ensure that each solution is unique
during a game session.
"""
solution = random.choice(words)
# Remove any duplicates of solution.
while solution in words:
words.remove(solution)
return solution
def guess_is_valid(guess: str) -> bool:
"""Checks if guess is valid.
Not the same as guess being correct.
A guess can be a lower or upper case string with a letter A-Za-z.
Normalise guess by converting to lower case and check if its ASCII
number is in the range of 97-122 (a-z).
Any string with more than one character will throw an exception
that is caught and returns False.
"""
try:
return 97 <= ord(guess.lower()) <= 122
except (AttributeError, TypeError):
return False
def get_valid_guess() -> str:
"""Get valid guess, reprompting player until guess is valid.
Note that validity is not same as guess being correct and present
in the solution string.
"""
guess: str = input('Guess a letter A-Z: ').upper()
if not guess_is_valid(guess):
print(f'Invalid guess: {guess}, please try again.')
guess = get_valid_guess()
return guess
def guess_is_correct(guess: str, solution: str) -> bool:
"""Check if guess is in solution string."""
return guess.upper() in solution.upper()
def player_wins(result: str, solution: str) -> bool:
"""Check if player wins by comparing result with solution."""
return result == solution
def player_loses(guess_count: int, max_guess_count: int = 5) -> bool:
"""Check if player loses; the number of incorrect guesses is
greater than the max number allowed guesses.
"""
return guess_count > max_guess_count
def play(game: Callable[[Any], None], *args, **kwargs):
"""Start new game session and loop game until user quits.
As long as the game session is running, each new solution is removed from
the list of words and reset if words is empty. This ensures that the user
gets non-repeated solutions as far as possible.
"""
# Get initial list of words from which to pick game solutions.
words: List[str] = get_words()
game_count: int = 1
# Start game session.
print("Get ready to play Hangman's Game!")
while True: # Warning, infinte loop!
# Reset words if each words has been selected as solution at least once.
if not words:
print('\nGenerating new words...\n') # Debugging only
words = get_words()
# Start new game.
game(*args, words=words, game_count=game_count, **kwargs)
# Ask user if they want to play again or quit.
play_again: bool = input('Do you want to play again? Y/n ').lower()
# Start another game if user answers yes.
if play_again in ('y', 'yes'):
game_count += 1
continue
# Else quit the game session by breaking out of the loop and returning to
# the console prompt.
print("\nThank's for playing, bye!")
break
# Set initial game state.
initial_game_state: Dict[str, Any] = {
'words': [],
'answer': '',
'max_attempts': 5,
'remaining_attempts': 5,
'result': '',
'win': None,
'loss': None,
}
if __name__ == '__main__':
pass
|
eb9cd110c503f41dd92bbb4c8c73b46c01212505 | ShriBuzz/IW-PythonLogic | /Assignment I/Data Types/17.py | 132 | 4.25 | 4 | # Write a Python program to multiplies all the items in a list.
list = [2, 2, 3]
temp = 1
for i in list:
temp *= i
print(temp)
|
84fe8803a973620d6b11e8d171d28bd7f13fed02 | Mana-Lv/Notes-python | /Pandas/Part 5 - Update Rows and Columns/Update Exemple.py | 2,147 | 3.78125 | 4 | import pandas as pd
people = {"First" : ['Alex', 'Tom', 'Maxime'],
"Age" : [26, 28, 30],
"email" : ["Exemple1@mail.com", "Exemple2@mail.com", "Exemple3@mail.com" ]}
df = pd.DataFrame(people)
# Travail sur les colonnes
df.columns # Récupère len nom des colonnes
df.columns = ['First_name', 'Age_test', 'email'] # Définir le nom des colonnes à l'aide d'une liste
df.columns # Les colonnes ont changés
df.columns = [x.lower() for x in df.columns] # Change le nom des colonnes en minuscule
df.columns = df.columns.str.replace("_", " ") # Ne marche pas mais plus
# Autre méthode : rename
df.rename(columns={'first name' : 'first', 'age test' : 'age'}, inplace = True) # Inplace permet de conserver les changements
# Travail sur une lignes loc/at or iloc
df.loc[2] = ['Maxime',32,"MaximeExemple@mail.com"]
df.loc[2, ['age','email']] = [33, 'Exemple3@mail.com'] # Pour changer seulement certains éléments du df
df.loc[2, 'email'] = ['Exemple3modif@mail.com'] # ... Avec un seul élément par exemple
# Exemples de travail sur l'ensemble des lignes
df['email'].str.lower()
df['email'].str.replace('mail.com', 'yahoo.fr')
# Travail plus ciblé avec les fonction apply/lambda
df['email'].apply(len) # Permets d'avoir des informations sur nos datas en appliquant une fonction, le nombre de caractère de chaque email
df.apply(len) # Le nombre de lignes
def update_email(email):
return email.upper()
df['email'].apply(update_email) #... Fonction personalisée également
df['email'] = df['email'].apply(update_email) # Pour changer les valeurs du df
df['email'] = df['email'].apply(lambda x : x.lower())
df['first'].apply(str.lower)
df.apply(pd.Series.min) #Récupère les valeurs minimum, par ordre alphabétique ou croissant pour les nombres
df.apply(lambda x : x.min()) # Pareil avec une utilisation de la fonction lambda
df.min() # plus simplement ..
df.applymap(len) # Applique la fonction à tous les éléments
df['first'] = df['first'].map({'Alex' : 'Alan', 'Tom' : 'Mateo'}) # Les valeurs non prise en compte par la méthode map sont transformée en NaN, utiliser replace si on veut conserver les anciennes valeurs non préçisées
df.loc[2,'first'] = 'John'
|
08d04439e8fdb140de8ccdfdb9c125e5ca8b6fa1 | Nakwon-Lee/cs402cw3 | /verifier.py | 21,299 | 3.71875 | 4 | import sys
import os
def isType(token): # check whether the token is type keyword or not
result = False
if token == "int":
result = True
elif token == "boolean":
result = True
elif token == "void":
result = True
else:
pass
return result
def isValidName(token): # check whether the token is valid name of method or not
result = False
if token[0] != '<':
result = True
else:
pass
return result
def isTargetMethod(st_line): # check whether the string line is target method or not
result = False
tokens = st_line.split()
if len(tokens) <= 0:
pass
else:
if tokens[0] == "public":
if isType(tokens[1]):
if isValidName(tokens[2]):
result = True
return result
def isAssignment(line): # check whether the given line is assignment or not
result = False
# is not := but is =
if line.find(":=") == -1 and line.find("=") != -1:
result = True
return result
def isAssertion(line): # check whether the given line is start of assertion or not
result = False
if line.find("$assertionsDisabled") != -1:
result = True
return result
def isReturn(token): # check whether the given token has return statement
result = False
if token.find("return") != -1:
result = True
return result
def isIf(token): # check whether the given token is if
result = False
if token == "if":
result = True
return result
def isLabel(token): # check whether the given token has label
result = False
# containing "label" and finish with :
if token.find("label") != -1 and token[len(token)-1] == ':':
result = True
return result
def isGoto(token): # check whether the given token is goto only statement
result = False
# if the token is goto, it is goto only statement
if token == "goto":
result = True
return result
def isParenthesisNumberLine(token): # check whether the given token is (?)
result = False
# if the token is wrapped with ( and ), it is (?)
if token[0] == '(' and token[len(token)-1] == ')':
result = True
return result
def isThrow(token): # check whether the given token is throw
result = False
if token == "throw":
result = True
return result
def isSemanticAssign(line): # check whether the given line is semantic assignment
result = False
if line.find(":=") != -1:
result = True
return result
def whatLine(line): # determine what actions are needed for given line
result = 0
tokens = line.split()
if len(tokens) <= 0:
pass
else:
# if the line is start with parenthesisNumber (num 9)
if isParenthesisNumberLine(tokens[0]):
result = 9
elif isSemanticAssign(line): # if the line is semantic assignment (num 11)
result = 11
elif isAssertion(line): # if the line is start of assertion (num 3)
result = 3
elif isIf(tokens[0]): # if the line is if statement (num6)
result = 6
elif isGoto(tokens[0]): # if the line is goto statement (goto only) (num 8)
result = 8
elif isThrow(tokens[0]): # if the line is throw only statement (num 10)
result = 10
elif isLabel(tokens[0]): # if the line is label statement (num 7)
result = 7
elif isType(tokens[0]): # if first token is type, it is declation of variables (num 1)
result = 1
elif isAssignment(line): # if the line is assignment (num 2)
result = 2
elif isTargetMethod(line): # if the line is start of target method (num 4)
result = 4
elif isReturn(tokens[0]): # if the first token is return statement (num 5)
result = 5
else:
pass
return result
def writeFormDVars(line, filename, varset): # write the variable declaration smt formula
# given line should be the variable declaration statement
tokens = line.split()
for i in range(1, len(tokens)):
var = tokens[i]
if var.find(',') != -1:
var = var[0:len(var)-1]
if var.find(';') != -1:
var = var[0:len(var)-1]
if var not in varset:
varset.add(var)
if tokens[0] == "int":
smtf = open(filename,'a')
data = "(declare-const %s Int)\n" % var
smtf.write(data)
smtf.close()
elif tokens[0] == "boolean":
smtf = open(filename,'a')
data = "(declare-const %s Bool)\n" % var
smtf.write(data)
smtf.close()
def writeFormAssignPhi(filename, right, data, left):
right = right[right.find('(')+1:len(right)-1]
tokens = right.split(',')
totokens = []
for i in range(len(tokens)):
totokens.append(tokens[i].split())
for i in range(len(totokens)):
temptoken = totokens[i]
temptoken[1] = temptoken[1][1:len(temptoken)]
data2 = data + "(=> tempbool" + temptoken[1] + " (= " + left + " " + temptoken[0] + "))" + "))\n"
smtf = open(filename, 'a')
smtf.write(data2)
smtf.close()
# print totokens
def writeFormAssign(line, filename, varset, conddic, clabel):
tokens = line.split('=')
assert len(tokens) == 2, "writeFormAssign: len(tokens) is not two"
left = tokens[0]
left = left.lstrip()
left = left.rstrip()
right = tokens[1]
right = right.lstrip()
right = right.rstrip()
if right.find(';') != -1:
right = right[0:len(right)-1] # remove the semicolon
# print "l:", left, " r:", right
data = None
# prefix
if conddic[clabel] == "":
data = "(assert (=> true "
else:
data = "(assert (=> " + conddic[clabel] + " "
# assumption! right of assignment statement is expression of only one
# binary operator or just a variable or Phi
if right.find('+') != -1:
righttokens = right.split('+')
writeFormAssignRightSub(filename, righttokens, data, left, "(+ ")
elif right.find('-') != -1:
righttokens = right.split('-')
writeFormAssignRightSub(filename, righttokens, data, left, "(- ")
elif right.find('*') != -1:
righttokens = right.split('*')
writeFormAssignRightSub(filename, righttokens, data, left, "(* ")
elif right.find('/') != -1:
righttokens = right.split('/')
writeFormAssignRightSub(filename, righttokens, data, left, "(mydiv ")
elif right.find("Phi") != -1:
writeFormAssignPhi(filename, right, data, left)
else:
temptokens = right.split()
if temptokens[0] == "new": # not a binary operator. class initiation
pass
else: # it may be assignment of jsut a variable, right may be just a variable
righttokens = []
righttokens.append(right)
writeFormAssignRightSub(filename, righttokens, data, left, None)
def writeFormAssignRightSub(filename, righttokens, prefix, left, opst):
data = ""
rightleft = righttokens[0]
rightleft = rightleft.lstrip()
rightleft = rightleft.rstrip()
if len(righttokens) == 2:
rightright = righttokens[1]
rightright = rightright.lstrip()
rightright = rightright.rstrip()
data = prefix + "(= " + left + " " + opst + rightleft + " " + rightright + "))" + "))\n"
else:
data = prefix + "(= " + left + " " + rightleft + ")" + "))\n"
smtf = open(filename,'a')
smtf.write(data)
smtf.close()
# get label for safe asserting from if statement which is appeared first since assertion start
def getLabelHint(line):
issafelabel = None
labelhint = None
tokens = line.split("goto")
# assumption! tokens have two elements
if tokens[0].find("!=") != -1: # label is safe label
issafelabel = True
elif tokens[0].find("==") != -1: # label is unsafe label
issafelabel = False
resultlabel = tokens[1]
resultlabel = resultlabel.lstrip()
resultlabel = resultlabel.rstrip()
if resultlabel.find(';') != -1: # remove the semicolon
resultlabel = resultlabel[0:len(resultlabel)-1]
labelhint = resultlabel
return issafelabel, labelhint
def getLabelHintFromGotoOnly(line):
issafelabel = True
labelhint = None
tokens = line.split()
# assumption! tokens have two elements
assert len(tokens) == 2, "label hint from goto only: len(tokens) is not two"
resultlabel = tokens[1]
resultlabel = resultlabel.lstrip()
resultlabel = resultlabel.rstrip()
if resultlabel.find(';') != -1: # remove the semicolon
resultlabel = resultlabel[0:len(resultlabel)-1]
labelhint = resultlabel
return issafelabel, labelhint
def subFormGen(token, varset):
result = ""
result2 = ""
ttokens = None
if token.find("==") != -1:
result = "(= "
result2 = ")"
ttokens = token.split("==")
elif token.find("!=") != -1:
result = "(not (= "
result2 = "))"
ttokens = token.split("!=")
elif token.find(">=") != -1:
result = "(>= "
result2 = ")"
ttokens = token.split(">=")
elif token.find("<=") != -1:
result = "(<= "
result2 = ")"
ttokens = token.split("<=")
elif token.find(">") != -1:
result = "(> "
result2 = ")"
ttokens = token.split(">")
elif token.find("<") != -1:
result = "(< "
result2 = ")"
ttokens = token.split("<")
# ttokens should be length two
assert len(ttokens) == 2
ttokens[0] = ttokens[0].lstrip()
ttokens[0] = ttokens[0].rstrip()
ttokens[1] = ttokens[1].lstrip()
ttokens[1] = ttokens[1].rstrip()
# variable names must be valid (but tokens cannot be variable)
data = result + ttokens[0] + " " + ttokens[1] + result2
# print data,
return data
def formgenSafeNFound(token, varset):
result = ""
data = subFormGen(token, varset)
result = "(assert " + data + ")\n"
return result
def formgenSafeFound(token, varset):
result = ""
data = subFormGen(token, varset)
result = "(assert (not " + data + "))\n"
return result
def formgenUSafeNFound(token, varset):
result = ""
data = subFormGen(token, varset)
result = "(assert (not " + data + "))\n"
return result
def formgenUSafeFound(token, varset):
result = ""
data = subFormGen(token, varset)
result = "(assert " + data + ")\n"
return result
def writeFormAssertIf(line, filename, varset, issafeassert, labelhint):
tokens = line.split("goto")
# assumption! in assert if line, there must be a goto and a target label.
# So, len(tokens) must be two
assert len(tokens) == 2, "writeformassertif: len(tokens) must be two"
# assumption! split with if must produce two tokens [whitespaces] and [logical relation]
lefttokens = tokens[0].split("if",1)
assert len(lefttokens) == 2, "writeformassertif: len(lefttokens must be two)"
lefttokens[1] = lefttokens[1].lstrip()
lefttokens[1] = lefttokens[1].rstrip()
# print lefttokens[1],
if issafeassert: # hint label is safe label
if tokens[1].find(labelhint) != -1: # safe label found!
# print "safe label found!",
# string generation for safe found statement (only one logical relation operator)
data = formgenSafeFound(lefttokens[1], varset)
else: # safe label not found!
# print "safe label not found!",
# string generation for safe not found statement (only one logical relation operator)
data = formgenSafeNFound(lefttokens[1], varset)
else: # hint label is unsafe label
if tokens[1].find(labelhint) != -1: # unsafe label found!
# print "unsafe label found!",
# string generation for unsafe found statement (only one logical relation operator)
data = formgenUSafeFound(lefttokens[1], varset)
else: # unsafe label not found!
# print "unsafe label not found!",
# string generation for unsafe not found statement (only one logical relation operator)
data = formgenUSafeNFound(lefttokens[1], varset)
# print data,
smtf = open(filename, 'a')
smtf.write(data)
smtf.close()
def extractCond(line, varset):
tokens = line.split("goto")
# assumption! in assert if line, there must be a goto and a target label.
# So, len(tokens) must be two
assert len(tokens) == 2, "writeformassertif: len(tokens) must be two"
# assumption! split with if must produce two tokens [whitespaces] and [logical relation]
lefttokens = tokens[0].split("if",1)
assert len(lefttokens) == 2, "writeformassertif: len(lefttokens must be two)"
lefttokens[1] = lefttokens[1].lstrip()
lefttokens[1] = lefttokens[1].rstrip()
# print lefttokens[1],
return subFormGen(lefttokens[1], varset)
def fileCut(filename):
result = ""
tokens = filename.split(".java")
# print tokens
# tokens should be length of one
assert len(tokens) == 2
result = tokens[0]
# print result
return result
def initiationOfVeri(conddic):
conddic["label0"] = ""
return "label0"
def getLabelFromStatement(lines, conddic):
tokens = lines.split()
assert len(tokens) == 1, "getLabelFromStatement: label statement must have one token"
assert tokens[0].find(':') != -1, "getLabelFromStatement: token must have colon"
token = tokens[0]
token = token[0:len(token)-1]
assert token in conddic, "getLabelFromStatement: label must be added before finding"
return token
def addLabelToCondDic(conddic, line):
tokens = line.split()
# assumption! tokens have two elements
assert len(tokens) == 2, "label hint from goto only: len(tokens) is not two"
resultlabel = tokens[1]
resultlabel = resultlabel.lstrip()
resultlabel = resultlabel.rstrip()
if resultlabel.find(';') != -1: # remove the semicolon
resultlabel = resultlabel[0:len(resultlabel)-1]
labelst = resultlabel
if labelst not in conddic:
conddic[labelst] = ""
return labelst
def addLabelToCondDicIf(conddic, line):
tokens = line.split("goto")
assert len(tokens) == 2, "addlabeltoconddicif: len(tokens) must be two"
righttoken = tokens[1]
righttoken = righttoken.lstrip()
righttoken = righttoken.rstrip()
assert righttoken.find(';') != -1, "addlabeltoconddicif: righttoken must have semicolon"
righttoken = righttoken[0:len(righttoken)-1]
if righttoken not in conddic:
conddic[righttoken] = ""
return righttoken
def addLabelToCondDicLabel(conddic, line):
tokens = line.split()
assert len(tokens) == 1, "addlabeltoconddiclabel: len(tokens) must be one"
tokens[0] = tokens[0][0:len(tokens[0])-1]
if tokens[0] not in conddic:
conddic[righttoken] = ""
return tokens[0]
def updateCondAnd(clabel, newcond, conddic): # update condition of current label with not newcond
assert clabel in conddic, "updatecondand: label must be in conddic"
assert newcond != "", "updatecondand: newcond must be a proposition"
if conddic[clabel] == "": # current label is no cond
conddic[clabel] = "(not " + newcond + ")"
else:
conddic[clabel] = "(and " + conddic[clabel] + " " + "(not " + newcond + "))"
# print "condic and ", newcond, conddic[clabel]
def updateCondOr(tlabel, clabel, conddic): # update condition of label (or)
assert tlabel in conddic and clabel in conddic, "updateCondOr: labels must be in conddic"
if conddic[clabel] == "": # current label is no cond
pass
else:
if conddic[tlabel] == "": # target label is no cond
conddic[tlabel] = conddic[clabel]
else: # both labels have cond
conddic[tlabel] = "(or " + conddic[tlabel] + " " + conddic[clabel] + ")"
# print "condic or ", conddic[clabel], conddic[tlabel]
def updateCondNewOr(tlabel, clabel, newcond, conddic): # update condition of label with newcond (or)
assert tlabel in conddic and clabel in conddic, "updateCondNewOr: labels must be in conddic"
assert newcond != "", "updatecondnewor: newcond must be a proposition"
if conddic[clabel] == "": # current label is no cond
if conddic[tlabel] == "": # target label is no cond
conddic[tlabel] = newcond
else: # target label has cond
conddic[tlabel] = "(or " + conddic[tlabel] + " " + newcond + ")"
else:
if conddic[tlabel] == "": # target label is no cond
conddic[tlabel] = "(and " + conddic[clabel] + " " + newcond + ")"
else: # both labels have cond
conddic[tlabel] = "(or " + conddic[tlabel] + " " + "(and " + conddic[clabel] + " " + newcond + "))"
# print "condic new or ", newcond, conddic[clabel], conddic[tlabel]
def writeFormParen(token, clabel, conddic, parenvarset, filename):
# token may be the form (??
tokens = token.split('(')
assert len(tokens) == 2, "writeformparen: len(tokens) must be two"
parenvarset.add(int(tokens[1]))
data1 = "(declare-const tempbool" + tokens[1] + " Bool)\n"
data2 = "(assert (= " + conddic[clabel] + " tempbool" + tokens[1] + "))\n"
smtf = open(filename, 'a')
smtf.write(data1)
smtf.write(data2)
smtf.close()
def writeTheAssertionProperty(clabel, conddic, filename):
data = "(assert (not "
last = "))\n"
data = data + conddic[clabel] + last
smtf = open(filename, 'a')
smtf.write(data)
smtf.close()
def identifyParameter(line, paramvarset):
tokens = line.split(":=")
assert len(tokens) == 2, "identifyparameter: len(tokens) must be two"
if tokens[1].find("@parameter") != -1: # the statement is semantic assignment of parameter
tokens[0] = tokens[0].lstrip()
tokens[0] = tokens[0].rstrip()
paramvarset.add(tokens[0])
def verify(filename):
inbody = False
inassert = False
labelget = False
endofmethod = False
smtfilename = "verifile.smt2"
issafelabel = None
labelhint = None
classname = fileCut(filename)
string = "./soot.sh " + classname
jimplename = classname + ".shimple"
tf = open(jimplename, 'w')
tf.close()
os.remove(jimplename)
os.system(string)
defineMydiv = "(define-fun mydiv ((x Int) (y Int)) Int (if (not (= y 0)) (div x y) 0))\n"
smtf = open(smtfilename, 'w')
smtf.write(defineMydiv)
smtf.close()
varset = set()
parenvarset = set()
paramvarset = set()
labelconddic = {}
currentlabel = ""
key = 0
lines = open(jimplename).readlines()
i = 0
while (not endofmethod): # each line including newline
key = whatLine(lines[i])
if key == 1: # declaration of variables
if inbody:
writeFormDVars(lines[i], smtfilename, varset)
# print varset
# print "var decl"
elif key == 2: # assignment
if inbody:
writeFormAssign(lines[i], smtfilename, varset, labelconddic, currentlabel)
# print "assign"
elif key == 3: # start of assertion
if inbody:
inassert = True
# print "st assert"
elif key == 4: # start of target method
inbody = True
currentlabel = initiationOfVeri(labelconddic)
# print labelconddic, currentlabel,
# print "st target method"
elif key == 5: # return statement
if (inbody and inassert):
inbody = False
inassert = False
endofmethod = True
# print "return"
elif key == 6: # if statement
if inbody:
t_label = addLabelToCondDicIf(labelconddic, lines[i])
# print labelconddic
if inassert:
if labelget:
# writeFormAssertIf(lines[i], smtfilename, varset, issafelabel, labelhint)
newcond = extractCond(lines[i], varset)
updateCondNewOr(t_label, currentlabel, newcond, labelconddic)
updateCondAnd(currentlabel, newcond, labelconddic)
# print "assert if"
else:
issafelabel, labelhint = getLabelHint(lines[i])
# print issafelabel, labelhint,
# print "label hint if"
if issafelabel:
labelget = True
else:
newcond = extractCond(lines[i], varset)
updateCondNewOr(t_label, currentlabel, newcond, labelconddic)
updateCondAnd(currentlabel, newcond, labelconddic)
# print "if\n"
elif key == 7: # label statement
if inbody:
if currentlabel != "": # be reached from current label
t_label = addLabelToCondDicLabel(labelconddic, lines[i])
updateCondOr(t_label, currentlabel, labelconddic)
del labelconddic[currentlabel]
currentlabel = ""
currentlabel = getLabelFromStatement(lines[i],labelconddic)
if inassert:
if currentlabel == labelhint: # clabel is safe label!
writeTheAssertionProperty(currentlabel, labelconddic, smtfilename)
# print labelconddic
# print "assert label"
# if current label is only one label, it has no condition
if len(labelconddic) == 1:
labelconddic[currentlabel] = ""
# print currentlabel
# print labelconddic
elif key == 8: # goto only statement
if inbody:
t_label = addLabelToCondDic(labelconddic, lines[i])
# print labelconddic
if inassert:
# if inassert and if not labelget, it should be unsafe label
if not labelget:
issafelabel, labelhint = getLabelHintFromGotoOnly(lines[i])
labelget = True
# print issafelabel, labelhint,
# print "assert goto"
else:
updateCondOr(t_label, currentlabel, labelconddic)
# print "assert labelget goto"
else:
updateCondOr(t_label, currentlabel, labelconddic)
# print "goto"
del labelconddic[currentlabel]
currentlabel = ""
elif key == 9: # (?) statement
if inbody:
# print "(?)",
tempsplit = lines[i].split(')', 1)
assert len(tempsplit) == 2, "(?) statement must be splitted with two parts"
writeFormParen(tempsplit[0], currentlabel, labelconddic, parenvarset, smtfilename)
lines[i] = tempsplit[1]
# print lines[i],
i = i - 1
elif key == 10: # throw only statement
if inbody:
# print "throw"
del labelconddic[currentlabel]
currentlabel = ""
elif key == 11: # semantic assginment statement
if inbody:
identifyParameter(lines[i], paramvarset)
# print ":="
else:
pass
i = i + 1
# print paramvarset
getvalueparam = "(get-value ("
for i in paramvarset:
getvalueparam = getvalueparam + i + " "
getvalueparam = getvalueparam[0:len(getvalueparam)-1] + "))\n"
smtf = open(smtfilename, 'a')
smtf.write("(check-sat)\n")
smtf.write(getvalueparam)
smtf.close()
outputfilename = "z3output"
outputfile = open(outputfilename, 'w')
outputfile.close()
os.system("z3 -smt2 \"verifile.smt2\" >> z3output")
showResults(outputfilename)
def showResults(filename):
lines = open(filename).readlines()
if lines[0].find("unsat") != -1: # result is unsat valid!!!
print "VALID"
else:
for i in range(1,len(lines)):
print lines[i],
if __name__ == '__main__':
verify(sys.argv[1])
|
166cf1b89922ef0f8b705442f7f5677a73f244d9 | DiegoSilvaHoffmann/Curso-de-Python | /Meus_dessafios/Exercicios2021/ex077.py | 234 | 3.90625 | 4 | palavras = ('CURSO', 'TRABALHO', 'ESTUDAR', 'SONHO', 'TRANQUILIDADE')
for p in palavras:
print(f'\nA palavra {p} tem as vogais: ', end=' ')
for letra in p:
if letra.upper() in 'AEIOU':
print(letra, end='')
|
71e0fcd92bf6c90f74e63babb6d7b7b68e0c6102 | PurpleCornflakes/Tictactoe_search | /DFS.py | 3,444 | 3.5625 | 4 | # This program searches all possible moves of tic tac toe via DFS
# by Chen and Ling
# 09052017
Nfirst = 0
Nsecond = 0
Tie = 0
class State:
'''
state of the chess board
'''
def __init__(self, num=3):
self.num = num
self.player = {0: "X", 1: "O"}
self.turn = 0 # turn of the next player
self.first_move = 0
self.moves = []
self._state = []
def vacancy(self):
return [x for x in range(9) if x not in self._state]
def update(self, pos):
self.moves.append("{}{}".format(self.player[self.turn], pos))
self._state.append(pos)
self.turn = {1:0, 0:1}[self.turn]
def cancel(self):
if self._state:
self._state.pop()
if self.moves:
self.moves.pop()
self.turn = {1:0, 0:1}[self.turn]
def is_final(self):
if len(self._state) <= 4:
return (False, -1)
pos = self._state[-1]
row = int(pos/self.num)
col = pos%self.num
win = False
row_win = True
for j in [(col+1)%self.num, (col+2)%self.num]:
ind = row * self.num + j
if ind not in self._state:
row_win = False
break
if self.turn == 1:
if self._state.index(ind) % 2 != self.first_move % 2:
row_win = False
else:
if self._state.index(ind) % 2 == self.first_move % 2:
row_win = False
col_win = True
for i in [(row+1)%self.num, (row+2)%self.num]:
ind = i * self.num + col
if ind not in self._state:
col_win = False
break
if self.turn == 1:
if self._state.index(ind) % 2 != self.first_move % 2:
col_win = False
else:
if self._state.index(ind) % 2 == self.first_move % 2:
col_win = False
win = win or (row_win or col_win)
if row == col:
rdia_win = True
for (i,j) in [((row+1)%self.num, (col+1)%self.num), ((row+2)%self.num, (col+2)%self.num)]:
ind = i * self.num + j
if ind not in self._state:
rdia_win = False
break
if self.turn == 1:
if self._state.index(ind) % 2 != self.first_move % 2:
rdia_win = False
else:
if self._state.index(ind) % 2 == self.first_move % 2:
rdia_win = False
win = win or rdia_win
if (row + col == self.num -1):
ldia_win = True
for (i,j) in [((row-1)%self.num, (col+1)%self.num), ((row-2)%self.num, (col+2)%self.num)]:
ind = i * self.num + j
if ind not in self._state:
ldia_win = False
break
if self.turn == 1:
if self._state.index(ind) % 2 != self.first_move % 2:
ldia_win = False
else:
if self._state.index(ind) % 2 == self.first_move % 2:
ldia_win = False
win = win or ldia_win
if win:
return (True, 1 if self.turn==0 else 0)
elif len(self._state) == self.num*self.num:
return (True, -1)
else:
return (False, -1)
def search(state):
'''
searches all possible moves starting from current state
'''
global Nfirst, Nsecond, Tie
final, winner = state.is_final()
if final:
if winner == -1:
Tie += 1
result="tie"
elif winner == 0:
Nfirst += 1
result="{} win".format(state.player[0])
else:
Nsecond += 1
result="{} win".format(state.player[1])
print(state.moves, result)
state.cancel()
return 1
for pos in state.vacancy():
state.update(pos)
search(state)
state.cancel()
return 0
state = State()
# test code
# state.update(0)
# state.update(1)
# state.update(2)
# state.update(3)
# state.update(4)
# state.update(5)
# state.update(6)
# print(state.is_final())
# quit()
search(state)
print("offensive move: ", Nfirst, "\ndefensivin move", Nsecond, "\ntie: ", Tie)
|
296838c31c5c389d5b4a6706b11188c77368847e | nitinworkshere/algos | /algos/Arrays/FlipBinaryMetrics.py | 201 | 3.59375 | 4 | def flip_an_invert_image(matrix):
C = len(matrix)
for row in matrix:
for i in range((C + 1) // 2):
row[i], row[C - i - 1] = row[C - i - 1] ^ 1, row[i] ^ 1
return matrix |
daab11457ff2796cd1d91f683337f15be321c758 | Ranjith8796/Python-programs | /Task-3 (change_date_time).py | 431 | 3.65625 | 4 | import pandas as pd
def change_datetime(i):
year=i[-4:]
month='-09-'
date=i[:2]
convertedformat=year+month+date
return convertedformat
'''input'''
Dates= {'dates': ['05Sep2009','13Sep2011','21Sep2010']}
df=pd.DataFrame(Dates)
oldlist=df['dates'].tolist()
newlist=[]
for i in oldlist:
newlist.append(change_datetime(i))
Dates['dates']=newlist
'''output'''
print(Dates)
|
cd4098c8a15e99284d2ae6f40a3ebb2d51c88385 | arinmsn/My-Lab | /Books/PythonCrashCourse/Ch8/8-11_UnchangedMagicians.py | 919 | 4.25 | 4 | # Start with your work from Exercise 8-10. Call the
# function make_great() with a copy of the list of magicians’ names. Because the
# original list will be unchanged, return the new list and store it in a separate list.
# Call show_magicians() with each list to show that you have one list of the origi-
# nal names and one list with the Great added to each magician’s name.
magicians = ["Albus Dumbledor","Lord Voldemort","Newt Scamander","Harry Potter","Sirius Black","Mad-Eye Moody"]
def show_magicians():
for m in magicians:
m = magicians.split(',')
print("---- Original list of magicians ----")
print(m + "\n")
def make_great(magician):
print("---- Great magicians ----")
for m in magician:
print(f'Great {m}')
# if a list is passed, use that, otherwise use .split()
show_magicians()
# show_magicians()
# show two lists, original names,
# and the other list with Great+name of maigician |
52d84156d0f08a7e71808c0feea1b6fef7b71aa8 | abhinandanpathak/Numerical-Methods | /Single_variable/Fixed_point.py | 673 | 3.640625 | 4 | import pandas as pd
(p0 , TOL , N) = (1.5 , 0.0001 , 30)
def g(x):
return 0.5 * ((10 - (x ** 3)) ** 0.5)
data = []
pd.options.display.float_format = "{:,.10f}".format
def Fixed_point(p0 , TOL , N):
i = 1
while i <= N:
p = g(p0)
data.append([i , p0 , p , abs(p - p0)])
if(abs(p - p0) < TOL):
print("Value of p is : " , round(p , 10))
break
i = i + 1
p0 = p
table = pd.DataFrame(data , columns = ['n' , 'p0' , 'p1' , 'relative error'])
print(table.to_string(index = 0))
if (i - 1 == N):
print("Method failed after {} iterations".format(N))
Fixed_point(p0 , TOL , N) |
ce821ba8a123bfaeed38245c2e7cb1ad657281f7 | vidyarthiprashant/python-codes | /sumevenprododd.py | 186 | 4 | 4 | i=int(input("enter number ="))
sum=0
pro=1
while i>0:
d=i%10
if d%2==0:
sum=sum+d
else:
pro=pro*d
i=i//10
print("sum of even:",sum,"product of odd:",pro)
|
06bb1ebc292090379ca46f8b57def8d5e121084b | fayyazj/Python-Challenge | /PyBank/main.py | 2,412 | 4.125 | 4 | #import needs
import csv
#Initializing Variables
Number_Of_Months = 0
Net_Total = 0
Total_Monthly_Change = 0
Greatest_Increase = 0
Greatest_Decrease = 0
#read in csv file
File_Name = "/Users/celiakresser/Documents/GitHub/Python-Challenge/PyBank/Budget_Data.csv"
#create object that will maintain the data in Budget_Data
with open(File_Name, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',')
#Skip first line or header in row
next(csvreader)
#parse csv for:
for row in csvreader:
#The total number of months included in the dataset
Number_Of_Months = Number_Of_Months + 1 #Alternative short hand is Number_of_Months+=1
#The net total amount of "Profit/Losses" over the entire period
Monthly_Profit = int(row[1])
Net_Total = Net_Total + Monthly_Profit
#The average of the changes in "Profit/Losses" over the entire period
if Number_Of_Months == 1:
Prev_Profit = Monthly_Profit
else:
Monthly_Change = Monthly_Profit - Prev_Profit
Prev_Profit = Monthly_Profit
Total_Monthly_Change = Total_Monthly_Change + Monthly_Change
#The greatest increase in profits (date and amount) over the entire period
if Monthly_Change > Greatest_Increase:
Greatest_Increase = Monthly_Change
Greatest_Increase_Date = row[0]
#The greatest decrease in losses (date and amount) over the entire period
elif Monthly_Change < Greatest_Decrease:
Greatest_Decrease = Monthly_Change
Greatest_Decrease_Date = row[0]
#Defining Average Change at the end of the for loop
Average_Change = round(Total_Monthly_Change/(Number_Of_Months - 1), 2)
#Output to terminal and text file
Financial_Analysis = "Financial Analysis\n--------------------------------------------------\nTotal Months: {}\nTotal: ${}\nAverage Change: ${}\nGreatest Increase In Profits: {} (${})\nGreatest Decrease In Profits: {} (${})".format(Number_Of_Months, Net_Total, Average_Change,Greatest_Increase_Date, Greatest_Increase, Greatest_Decrease_Date, Greatest_Decrease)
print(Financial_Analysis)
File = "/Users/celiakresser/Documents/GitHub/Python-Challenge/PyBank/Financial Analysis.txt"
Output_Object = open(File, 'w')
Output_Object.write(Financial_Analysis)
Output_Object.close |
c04ee7394a1cb0e5af8d2b460639790bc98b54e8 | henrique17h/Aprendizado_Python | /desafio26.py | 492 | 3.84375 | 4 | from random import randint
from time import sleep
computador= randint(0,5)#faz o computador esperar
print('===#===' *20)
print('Vou pensar em un número entre 0 e 5 tente adivinhar...')
print('===#===' *20)
jogador= int(input('Em que número pensei? '))#jogador tenta advinhar
print('Processando...')
sleep(3)
if jogador == computador:
print('PARABÉNS! VOCÊ CONSEGUIU ME VENCER -.-')
else:
print('Ganhei eu pensei no número {} e não no {}'.format(computador, jogador)) |
a4006d19be15584474afdd517a18e84c8f16c310 | ayush-09/Binary-Tree | /Level Order Traversal in spiral form.py | 2,474 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 16 19:06:26 2021
@author: Ayush
"""
# Recursive O(n^2)
class Node():
def __init__(self,key):
self.left = None
self.right = None
self.data = key
def printSpiral(root):
h = height(root)
ltr = False
for i in range(1,h+1):
printGivenLevel(root,i,ltr)
ltr = not ltr
def printGivenLevel(root,level,ltr):
if root == None:
return
if level==1:
print(root.data,end=" ")
elif level>1:
if ltr:
printGivenLevel(root.left, level-1, ltr)
printGivenLevel(root.right, level-1, ltr)
else:
printGivenLevel(root.right, level-1, ltr)
printGivenLevel(root.left, level-1, ltr)
def height(node):
if node == None:
return 0
else:
lheight = height(node.left)
rheight = height(node.right)
if (lheight>rheight):
return lheight+1
else:
return rheight+1
if __name__=="__main__":
av= Node(3)
av.left = Node(1)
av.right = Node(2)
av.left.left = Node(7)
av.left.right = Node(6)
av.right.left = Node(5)
av.right.right = Node(4)
print("Spiral Order traversal of binary tree is")
printSpiral(av)
#Iterative
class newNode():
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def printSpiral2(root):
if root==None:
return
s1=[]
s2=[]
s1.append(root)
while not len(s1)==0 or not len(s2)==0:
while not len(s1)==0:
temp=s1[-1]
s1.pop()
print(temp.data, end=" ")
if temp.left:
s2.append(temp.left)
else:
s2.append(temp.right)
while not len(s2)==0:
temp=s2[-1]
s2.pop()
print(temp.data, end=" ")
if temp.left:
s1.append(temp.left)
else:
s1.append(temp.right)
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(7)
root.left.right = newNode(6)
root.right.left = newNode(5)
root.right.right = newNode(4)
print("Spiral Order traversal of",
"binary tree is ")
printSpiral(root)
|
a0b64c9daf22d2e64695cd6341cfd7643628cf5b | djiamnot/transience | /prototypes/class_stack_cycle/class_stack_cycling.py | 644 | 4 | 4 | #!/usr/bin/env python
class A():
def __init__(self):
self.stack = [1,2,3,4,5,6]
self.num = 0
self.stack = iter(self.stack)
def advance_stack(self):
self.num = self.stack.next()
class C():
def __init__(self):
self.c = A()
aa = A()
print("num variable {}".format(aa.num))
cc = C()
print("this is the c instance of A: {}".format(cc))
print("The current aa.num: {}".format(aa.num))
print("run cc.c.advance_stack()")
cc.c.advance_stack()
print("cc.c.num is now : {}".format(cc.c.num))
print("run cc.c.advance_stack()")
cc.c.advance_stack()
print("cc.c.num is now : {}".format(cc.c.num))
|
881188f7c420eb0999bbc4ee534f72e883bd7687 | ankurjain8448/python_code | /max_sum_subarray.py | 332 | 3.75 | 4 | def max_sum_subarray(arr):
temp_ans = arr[0]
ans = arr[0]
for i in xrange(1,len(arr)):
temp_ans = max(arr[i],temp_ans+arr[i])
ans = max(ans,temp_ans)
return ans
arr=map(int,raw_input("Enter array to fing max_subarray\n").split())
l = len(arr)
if l >0 :
print max_sum_subarray(arr)
else :
print "Please provide some input" |
75b827eb31a18ed05a8a0cc2b6634cddc59da759 | upendra-k14/code-mixing | /ortho.py | 1,329 | 3.78125 | 4 | """Orthagraphic syllable splitting."""
import numpy as np
def ortho_syllable(word):
"""Split word to orhtographic syllable."""
vector = vectorize(word)
grad_vec = gradient(vector)
SW = ""
i = 0
w_len = len(word)
while(i < w_len):
SW = SW + word[i]
if (i+1) < w_len:
if i == 0 and grad_vec[i] == -1:
SW = SW + word[i+1] + " "
i += 1
elif grad_vec[i] == -1 and i != w_len-1:
if word[i+1] in ['r', 's', 't', 'l', 'n', 'd'] and i+1 != w_len-1:
if vector[i+2] == 0:
SW = SW + word[i+1]
i += 1
SW = SW + " "
i += 1
# pdb.set_trace()
return SW.split()
def is_vowel(char):
"""Check if it is vowel."""
return char in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
def gradient(vector):
"""Get the gradient of the vector."""
vec2 = vector[1::]
vec2.append(0)
vec2 = np.array(vec2)
vec = np.array(vector)
return vec2-vec
def vectorize(word):
"""Vectorize based on consonant and vowel."""
vec = list()
for i in range(len(word)):
vec.append(int(is_vowel(word[i])))
return vec
if __name__ == "__main__":
vec = ortho_syllable("prarthna")
print(vec)
|
30f68f765db7b46afc7a0f08bbe0ed202ede79d7 | sylvanl/flappy_bird_wsf | /Flappy-bird.py | 9,476 | 3.609375 | 4 | """This is an independant python game created specially for the Web School Factory students to have fun with."""
import random
import pygame
import os
from pygame.locals import *
pygame.init()
# Window size
GAME_HEIGHT: int = 600
FLOOR_HEIGHT: int = 100
WINDOW_WIDTH: int = 600
# Settings
FRAME_RATE: int = 60
PIPE_WIDTH: int = 60
MIN_WHOLE_HEIGHT: int = 100
HOLE_SIZE: int = 140
GRAVITY: int = 4
FLEIGHT_TIME: int = 20
FLIGHT_HEIGHT: int = 3
WHITE = (255, 255, 255)
FONT = pygame.font.SysFont('sitkasmallsitkatextboldsitkasubheadingboldsitkaheadingboldsitkadisplayboldsitkabannerbold', 60)
SMALL_FONT = pygame.font.SysFont('sitkasmallsitkatextboldsitkasubheadingboldsitkaheadingboldsitkadisplayboldsitkabannerbold', 40)
# Display creation
DISPLAY = pygame.display.set_mode((WINDOW_WIDTH, GAME_HEIGHT + FLOOR_HEIGHT))
pygame.display.set_caption('Flappy WSF')
# Import images
BACKGROUND_IMAGE = pygame.image.load("bg.png")
FLOOR = pygame.image.load("ground.png")
PIPE_BODY = pygame.image.load("pipe_body.png")
PIPE_END = pygame.image.load("pipe_end.png")
BIRD_UP = pygame.image.load("bird_wing_up.png")
BIRD_DOWN = pygame.image.load("bird_wing_down.png")
# Pipe pairs
def pipe_pair(pipe_position, top_height, bottom_height):
"""This function represents a pair of pipes."""
# Convert arguments into int format
pipe_position = int(pipe_position)
top_height = int(top_height)
bottom_height = int(bottom_height)
# Top Pipe
DISPLAY.blit(pygame.transform.scale(PIPE_BODY, (PIPE_WIDTH, top_height)), (pipe_position, 0))
DISPLAY.blit(pygame.transform.scale(PIPE_END, (PIPE_WIDTH, 30)), (pipe_position, top_height - 30))
# Bottom Pipe
DISPLAY.blit(pygame.transform.scale(PIPE_BODY, (PIPE_WIDTH, bottom_height)), (pipe_position, GAME_HEIGHT - bottom_height))
DISPLAY.blit(pygame.transform.scale(PIPE_END, (PIPE_WIDTH, 30)), (pipe_position, GAME_HEIGHT - bottom_height))
def floor(floor_position, top_height, bottom_height):
"""This function generates the floor."""
# Convert arguments into int format
floor_position = int(floor_position)
top_height = int(top_height)
bottom_height = int(bottom_height)
# Display floor
DISPLAY.blit(pygame.transform.scale(FLOOR, (WINDOW_WIDTH, top_height)), (floor_position, 0))
class Bird(pygame.sprite.Sprite):
"""Class representing the player :
- It's position
- it's flying capabilities
- It's illustration"""
def __init__(self, climb_time, up_image, down_image):
"""Player constructor"""
self.x_position: int = WINDOW_WIDTH / 4
self.y_position: int = GAME_HEIGHT / 2
self.climb_time: int = climb_time
self.up_image = up_image
self.down_image = down_image
# Shows player once generated
self.update()
def update(self):
"""Player position update function"""
# Update visual
DISPLAY.blit(pygame.transform.scale(self.up_image, (60, 60)), (self.x_position, self.y_position))
def gravity(self):
"""Gravity effects on player function"""
# pygame.transform.rotate(self.up_image.convert(), 100)
self.up_image = pygame.transform.rotate(BIRD_UP, -30)
self.y_position += GRAVITY
self.update()
def fly(self):
"""Player flight function"""
self.up_image = pygame.transform.rotate(BIRD_UP, 15)
self.y_position -= FLIGHT_HEIGHT
self.update()
def x_position(self):
"""Testing"""
return self.x_position
def y_position(self):
"""Testing"""
return self.y_position
# This timer is set to 1 ms, it is used to move the pipes
UPDATE = pygame.USEREVENT+1
pygame.time.set_timer(UPDATE, FRAME_RATE)
# clock = pygame.time.Clock()
def main():
"""This function contains the events."""
once: bool = True
pause: bool = True
flying: int = 0
pipe_position_a: int = WINDOW_WIDTH
pipe_position_b: int = WINDOW_WIDTH + ((WINDOW_WIDTH + PIPE_WIDTH) / 2)
player = Bird(5, BIRD_UP, BIRD_DOWN)
score = 0
high_score = 0
speed: int = 1
# Event loop
while True:
# Game background
if GAME_HEIGHT > WINDOW_WIDTH:
DISPLAY.blit(pygame.transform.scale(BACKGROUND_IMAGE, (GAME_HEIGHT, GAME_HEIGHT)), (0, 0))
else:
DISPLAY.blit(pygame.transform.scale(BACKGROUND_IMAGE, (WINDOW_WIDTH, WINDOW_WIDTH)), (0, 0))
DISPLAY.blit(pygame.transform.scale(FLOOR, (WINDOW_WIDTH, FLOOR_HEIGHT)), (0, GAME_HEIGHT))
player_collision = pygame.Rect(0, 0, 4, 4)
# Screen update
if pause == False:
# Pipe generation and movement
if once == True:
once = False
score = 0
top_height_a: int = random.randint(MIN_WHOLE_HEIGHT, GAME_HEIGHT - MIN_WHOLE_HEIGHT - HOLE_SIZE)
bottom_height_a: int = GAME_HEIGHT - top_height_a - HOLE_SIZE
top_height_b: int = random.randint(MIN_WHOLE_HEIGHT, GAME_HEIGHT - MIN_WHOLE_HEIGHT - HOLE_SIZE)
bottom_height_b: int = GAME_HEIGHT - top_height_b - HOLE_SIZE
bottom_pipe_y_position_a: int = GAME_HEIGHT - bottom_height_a
bottom_pipe_y_position_b: int = GAME_HEIGHT - bottom_height_b
elif pipe_position_a <= 0 - PIPE_WIDTH:
top_height_a: int = random.randint(MIN_WHOLE_HEIGHT, GAME_HEIGHT - MIN_WHOLE_HEIGHT - HOLE_SIZE)
bottom_height_a: int = GAME_HEIGHT - top_height_a - HOLE_SIZE
pipe_position_a: int = WINDOW_WIDTH
bottom_pipe_y_position_a: int = GAME_HEIGHT - bottom_height_a
elif pipe_position_b <= 0 - PIPE_WIDTH:
top_height_b: int = random.randint(MIN_WHOLE_HEIGHT, GAME_HEIGHT - MIN_WHOLE_HEIGHT - HOLE_SIZE)
bottom_height_b: int = GAME_HEIGHT - top_height_b - HOLE_SIZE
pipe_position_b: int = WINDOW_WIDTH
bottom_pipe_y_position_b: int = GAME_HEIGHT - bottom_height_b
# Player generation and mouvment
if flying > 0:
flying -= 1
player.fly()
else:
player.gravity()
# Add pipe visualls
pipe_pair(pipe_position_a, top_height_a, bottom_height_a)
pipe_pair(pipe_position_b, top_height_b, bottom_height_b)
# Move pipe
pipe_position_a -= speed
pipe_position_b -= speed
# Add collision elements
floor_hitbox = pygame.Rect(0, GAME_HEIGHT, WINDOW_WIDTH, FLOOR_HEIGHT)
top_pipe_a = pygame.Rect(pipe_position_a, 0, PIPE_WIDTH, top_height_a)
bottom_pipe_a = pygame.Rect(pipe_position_a, bottom_pipe_y_position_a, PIPE_WIDTH, bottom_height_a)
top_pipe_b = pygame.Rect(pipe_position_b, 0, PIPE_WIDTH, top_height_b)
bottom_pipe_b = pygame.Rect(pipe_position_b, bottom_pipe_y_position_b, PIPE_WIDTH, bottom_height_b)
collisions = [floor_hitbox, top_pipe_a, bottom_pipe_a, top_pipe_b, bottom_pipe_b]
player_collision = pygame.Rect(player.x_position + 15, player.y_position + 15, 30, 30)
# Debug (show hitboxes)
# pygame.draw.rect(DISPLAY, (255,0,255), floor_hitbox)
# pygame.draw.rect(DISPLAY, (255,0,255), top_pipe_a)
# pygame.draw.rect(DISPLAY, (255,0,255), bottom_pipe_a)
# pygame.draw.rect(DISPLAY, (255,0,255), top_pipe_b)
# pygame.draw.rect(DISPLAY, (255,0,255), bottom_pipe_b)
# pygame.draw.rect(DISPLAY, (255,0,255), player_collision)
# Collision and reset
if player_collision.collidelist(collisions) != -1:
pause = True
once = True
pipe_position_a: int = WINDOW_WIDTH
pipe_position_b: int = WINDOW_WIDTH + ((WINDOW_WIDTH + PIPE_WIDTH) / 2)
player = Bird(5, BIRD_UP, BIRD_DOWN)
speed = 1
# Scoring counter
if player.x_position == pipe_position_a or player.x_position == pipe_position_b:
score += 1
# Accelerates speed every 5 pipes
if score %4 == 0:
speed += 1
if score > high_score:
high_score = score
display_score = FONT.render(str(score), False, WHITE)
DISPLAY.blit(display_score, (WINDOW_WIDTH / 2 - 20, 20))
else:
display_game_over = FONT.render("GAME OVER", False, WHITE)
DISPLAY.blit(display_game_over, (WINDOW_WIDTH / 2 - 200, 60))
display_score = SMALL_FONT.render("Score : " + str(score), False, WHITE)
DISPLAY.blit(display_score, (WINDOW_WIDTH / 2 - 100, 130))
display_score = SMALL_FONT.render("High score : " + str(high_score), False, WHITE)
DISPLAY.blit(display_score, (WINDOW_WIDTH / 2 - 160, 180))
# Game events
for event in pygame.event.get():
# Quit game
if event.type == QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if pause == True:
pause = False
else:
flying = FLEIGHT_TIME
player.update()
pygame.display.update()
if __name__ == '__main__':
main()
|
01d96da084f251aab6d1fa3722bb779733497762 | ijuarezb/InterviewBit | /05_Hashing/fraction.py | 2,069 | 4.21875 | 4 | #!/usr/bin/env python3
import sys
# Fraction
# https://www.interviewbit.com/problems/fraction/
#
# Given two integers representing the numerator and denominator of a fraction,
# return the fraction in string format.
#
# If the fractional part is repeating, enclose the repeating part in parentheses.
#
# Example 1:
# Input: numerator = 1, denominator = 2
# Output: "0.5"
#
# Example 2:
# Input: numerator = 2, denominator = 1
# Output: "2"
#
# Example 3:
# Input: numerator = 2, denominator = 3
# Output: "0.(6)"
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Solution:
# @param numerator : integer
# @param denominator : integer
# @return a string
def fractionToDecimal(self, numerator, denominator):
if denominator == 0:
return "NaN"
if numerator * denominator >= 0:
positive = True
else:
positive = False
num = abs(numerator)
den = abs(denominator)
result = str(num//den)
rem = num % den
if not rem: return result
d = {}
result += '.'
i = len(result)
while rem:
#print(rem, result, d)
num = rem * 10
digit = str(num//den)
if rem in d:
result = result[:d[rem]] + "(" + result[d[rem]:] + ")"
break
else:
result += digit
d[rem] = i
rem = num % den
i += 1
return result if positive else "-" + result
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if __name__ == '__main__':
s = Solution()
# print(s.fractionToDecimal(10,3))
# print(s.fractionToDecimal(1,2))
print(s.fractionToDecimal(-2,1))
# print(s.fractionToDecimal(2,3))
# print(s.fractionToDecimal(4,9))
print(s.fractionToDecimal(4,333))
print(s.fractionToDecimal(4,9))
# print(s.fractionToDecimal(7,-6))
|
5edac900cc65dc4b9abf28b4bb2a907486006d50 | VikasOO7/Python | /Nptel python programs/primepartition.py | 889 | 4.125 | 4 | '''
A positive integer m can be partitioned as primes if it can be written as p + q where p > 0, q > 0 and both p and q are prime numbers.
Write a Python function primepartition(m) that takes an integer m as input and returns True if m can be partitioned as primes and False otherwise. (If m is not positive, your function should return False.)
Here are some examples of how your function should work.
>>> primepartition(7)
True
>>> primepartition(185)
False
>>> primepartition(3432)
True
'''
#Program
from math import *
def primepartition(m):
if m <= 0:
return False
else:
for i in range(2, m//2):
l, h = i, m-i
flag = 0
for j in range(2, int(sqrt(h)+1)):
if (j <= int(sqrt(l))) and (l%j == 0):
flag = 1
break
if (h%j == 0):
flag = 1
break
if flag == 0:
return True
return False
|
c9290407e0e90bbfe9df855d305d390dfa654b24 | bugo99iot/imdb_sentiment_analysis | /main.py | 850 | 3.65625 | 4 | from imdb_class import Imdb
#performa a statistical and sentiment analysis of reviews parsed from the Internet Movie Data Base (IMDB)
csv_file = "raw_data.csv"
#create instance of imdb class
imdb_object = Imdb(csv_file)
#plot histograms
imdb_object.plot_dicts()
#perform two-sample wilcoxon test for independent samples
# a.k.a Mann Whitney U
imdb_object.u_test()
#print n most common word in dictionaries, choose "plus" for positive reviews, "minus for the negative"
n = 30
print imdb_object.common_words(n, "plus")
#remove 65 overly common words (mostly articles, connectives and adverbs)
#as for the remaining words, plot only those with a count discrepancy of 80
imdb_object.plot_significant()
string = "The movie was awful, don't go watch it! It was bad in all aspects, you wouldn't believe it! Stay homme!"
imdb_object.classify(string)
|
05ef3d24bbe13b2023ff16c49d6a56d7a7babb6d | Vk-Demon/vk-code | /ckstring1.py | 219 | 3.890625 | 4 | def rdup(rstr): # remove duplicates in string
unr = ''
for x in rstr:
if not(x in unr):
unr = unr + x
return unr
rstr=input()
if(len(rstr)%2==1):
rstr=sorted(rstr)
print(rdup(rstr))
|
c6931b090b85079c1461859cf9516076b7cea954 | StasyaZlato/Home-Work | /2016-2017/classworks/1 | 1,816 | 3.984375 | 4 | #Задание1
# opentext(fname)
#1 открывает файл с названием fname
#2 переводить текст в нижний регистр
#3 делить на слова
#4 удалить знаки препинания
#5 возвращать массив всех словоформ
def opentext(fname):
with open(fname, 'r', encoding = 'utf-8') as f:
text = f.readlines()
for line in text:
line = line.split()
list_ = []
for i in range (0, len(line)):
a = line[i]
a = a.lower()
a = a.strip('.,?!";:"*()')
list_.append(a)
return list_
#Задание2
# first_letter(letter)
#1 возвращает массив слов из текста, которые начинаются на букву letter
#2 использовать функцию opentext(fname)!!!
def first_letter(letter):
fname = input('введите название файла: ')
text = opentext(fname)
words_letter = []
for i in range(len(text)):
if text[i].startswith(letter) == True:
words_letter.append(text[i])
else:
continue
return words_letter
#Задание3
# questions()
#1 спрашивае букву, имя файла и число
#2 распечатывает результат работы first_letter(letter), есди длина слов больше опр. числа
def questions():
letter = input('введите первую букву: ')
number = int(input('введите число: '))
words = first_letter(letter)
result = []
for i in range(len(words)):
if len(words[i]) > number:
result.append(words[i])
else:
continue
return result
print (questions())
|
cd7d8d37fc4e8898fd44a6b9a74e82c2ff6105ea | tsumo/solutions | /algorithms/sorting/quick_sort.py | 1,411 | 4.125 | 4 | #!/usr/bin/env python3
"""
Memory: O(1)
Can sort array in place
Time: O(n^2), generally O(n log n)
Divide and conquer algorithm.
First it chooses an arbitrary point in given array (last element here)
and divides all other elements in two piles - smaller than chosen
element and bigger than chosen element. Then it sorts those halves and
combines all of them.
"""
import sorting_utils
random_list = sorting_utils.random_list(50, 1000000)
def conquer(A):
if len(A) == 0: # Base case, nothing to sort
return []
# Split array in two halves:
left, pivot, right = divide(A) # elements smaller than pivot
# and elements bigger than pivot.
left = conquer(left) # Do the same to both halves,
right = conquer(right)
return [*left, pivot, *right]
def divide(A):
pivot = A[-1] # Choose last element as pivot
left = [] # Array for numbers smaller and
right = [] # bigger than pivot.
for x in A[:-1]: # Go through whole array,
if x <= pivot: # put elements in either left or right
left.append(x) # array.
else:
right.append(x)
return left, pivot, right
random_list = conquer(random_list)
print(random_list)
assert random_list == sorted(random_list)
|
f33559e2dafc267f2997a0917254640d54acafc5 | ytf513/python_code | /learn/functional.py | 1,654 | 3.765625 | 4 | #encoding=utf8
#函数式编程,python提供部分支持,因为python允许使用变量
#高阶函数:变量可以指向函数,函数可以作为另一个函数的参数
def add(x,y,f):
return f(x)+f(y)
print "abs(-6)+abs(2):",add(2,-6,abs)
print "*"*40
print "Map/Reduce函数测试"
# reduce的功能是:首先接收两个参数,然后把计算结果继续和序列的下一个函数做累积计算
alist=['adam', 'LISA', 'barT']
print map(lambda x:x.capitalize(),alist)
print reduce(lambda x,y:x*y,[1,2,3,4])
print 'filter()过滤函数,根据第一个参数的True、False过滤列表'
from math import sqrt
def sushu(n):
i=2
while i<sqrt(n):
if n%i==0:
return False
i=i+1
return True
print filter(sushu,range(1,1001))
print "*"*40
# 函数作为返回值:闭包
def calc_sum(*args):
def sum():
total=0
for x in args:
total=total+x
return total
return sum
f=calc_sum(1,2,3,4)
print f
print f()
# 利用lambda关键字可以生成匿名函数,python对匿名函数的支持有限
print "*"*40
print "装饰器:在代码运行期间动态增加功能的方式为,装饰器Decorator"
# 接受一个函数作为参数,并返回一个函数
def log(func):
def wrapper(*args,**kw):
print 'call %s' % func.__name__
return func(*args,**kw)
return wrapper
@log # 相当于执行了now=log(now)
def now():
print "2015-10-21"
now()
print log(now)()
print now.__name__
#装饰器之后的函数已不是原来的函数,为了避免这样的副作用,可以在函数之前加上functools.wraps
print "*"*40
print "偏函数,用functools.partical模块实现偏函数,可以固定某个参数"
|
06e35c64fb5248583031c1f75f1c872469228d0e | yongwang07/leetcode_python | /rotate_list.py | 808 | 3.609375 | 4 | from remove_nth_node_from_end import visit, Node
def rotate_right(head, k):
if head is None:
return None
cur = head
n = 0
while cur is not None:
n += 1
cur = cur.next
k %= n
fast = head
slow = head
for i in range(k):
if fast is None:
break
fast = fast.next
if fast is None:
return head
while fast.next is not None:
fast = fast.next
slow = slow.next
fast.next = head
fast = slow.next
slow.next = None
return fast
if __name__ == '__main__':
print('leetcode 61')
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
print(visit(head))
print(visit(rotate_right(head, 2)))
|
a2c472aab6824ceeee0a3bc80d7dba1e9817159e | marcusvinysilva/blue_mod1 | /aula14/aula14_codelab_Q06.py | 662 | 4.09375 | 4 | # 6. Escreva uma função que, dado um número nota representando a nota de um estudante, converte o valor de nota para um conceito (A, B, C, D, E e F).
# Nota Conceito
# >=9.0 A
# >=8.0 B
# >=7.0 C
# >=6.0 D
# >=5.0 E
# <=4.9 F
def conceito(nota):
if nota >= 9:
return 'A'
elif nota >= 8:
return 'B'
elif nota >= 7:
return 'C'
elif nota >= 6:
return 'D'
elif nota >= 5:
return 'E'
elif nota <= 4.9:
return 'F'
nota = float(input('Informe a nota do aluno: ').replace(',','.'))
print()
print(f'O conceito do aluno é: {conceito(nota)}') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.