blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
46b66032cccdd783dabc35635b030c8a279b4956 | stephenrods-21/python-test | /circle.py | 629 | 4.0625 | 4 | from math import pi
class Circle:
def __init__(self, radius=1.0):
self.radius = radius
def __str__(self):
return 'Circle with radius of {:.2f}'.format(self.radius)
def get_area(self):
return 'Area of circle with radius {0} is {1:.2f}'.format(self.radius, self.radius ** 2 * pi)
def get_perimeter(self):
return 'Perimeter of circle with radius {0} is {1:.2f}'.format(self.radius, pi * (2 * self.radius))
if __name__ == '__main__':
radius = int(input('Enter the radius\n'))
circle_a = Circle(radius)
print(circle_a.get_area())
print(circle_a.get_perimeter())
|
7248cdf41d9aa9a44446945ebd33bc2362cc5a1c | krishnadhara/programs-venky | /oops_concept/encapsulation/encapsul2.py | 244 | 3.875 | 4 | class person:
def __init__(self):
self.name = "venkatesh"
self.__lname = "babu"
def display(self):
return self.name+' '+self.__lname
p = person()
print(p)
print(p.name)
print(p._person__lname)
print(p.display())
|
e4fc40e212a0bbee9a40c4e1a710418c7245bfc7 | mridulrb/Basic-Python-Examples-for-Beginners | /SumDigit.py | 150 | 4.125 | 4 | print ("Sum of Digits")
x=input("Enter the number")
s=0
while x>=1:
k=x%10
s+=k
x=x/10
print ("The sum of digits is",s)
|
ef20ef8eb10198871feb6ed443643f2497828a07 | RomanAdriel/AlgoUnoDemo | /Gera/Ejercicios UBA/Funciones/Ejercicio8.py | 1,759 | 3.65625 | 4 | """Dada una serie de datos de la forma mes (1 a 12, no vienen ordenados), cantidad
recaudada (en pesos) y costo total (en pesos), hacer un algoritmo que calcule e
imprima cuál fue el mes que arrojó mayor ganancia. La serie termina con mes
igual a cero. No se deben guardar los datos.
"""
def ingresar_datos():
recaudacion = float(input("ingrese recaudacion en $"))
costo = float(input("ingrese costo en $ "))
mes = int(input("ingrese numero de mes: "))
return mes, recaudacion, costo
def calcular_mes_ganancia(datos_ingresados):
mes, recaudacion, costo = datos_ingresados
ganancia = recaudacion - costo
return mes, ganancia
def comparar_ganancias(ganancia_mensual1, ganancia_mensual2):
indice_ganancia = 1
if ganancia_mensual1[indice_ganancia] > ganancia_mensual2[indice_ganancia]:
mayor_ganancia = ganancia_mensual1
else:
mayor_ganancia = ganancia_mensual2
return mayor_ganancia
def mes_maximo():
indice_mes = 0
ganancia_max = calcular_mes_ganancia(ingresar_datos())
if ganancia_max[indice_mes] != 0:
comparar_ganancia = calcular_mes_ganancia(ingresar_datos())
while comparar_ganancia[indice_mes] != 0:
ganancia_max = comparar_ganancias(ganancia_max, comparar_ganancia)
comparar_ganancia = calcular_mes_ganancia(ingresar_datos())
return ganancia_max
def imprimir_resultado(datos_mes_maximo):
indice_mes = 0
indice_ganancia = 1
if datos_mes_maximo:
print("El mes", datos_mes_maximo[indice_mes], "tuvo una ganancia de $", datos_mes_maximo[indice_ganancia], "y fue el máximo")
else:
print("Datos insuficientes")
def main():
test = mes_maximo()
imprimir_resultado(test)
__init__: main()
|
536541854a3ed21e3a068c5fa16231a0ee47389c | Sprokr/AlgorithmProblems | /GeeksForGeeks/selectionSort.py | 522 | 4.3125 | 4 | # https://www.geeksforgeeks.org/selection-sort/
# complexity O(n^2)
def selectionSort(arr):
i = 0
for i in range(0,len(arr)):
minIndex = i
for j in range(i, len(arr)):
if arr[j] < arr[minIndex]:
minIndex = j
tmp = arr[i]
arr[i] = arr[minIndex]
arr[minIndex] = tmp
return
# Driver Code
print "Provide the input array :"
arr = map(int, raw_input().split(" "))
selectionSort(arr)
print "Array in sorted order : "
for x in arr:
print x,
|
d3412e0caad3fa0d9ca9c32cbaa9ad594ae94b98 | KAY2803/PythonPY1001 | /Занятие3/Лабораторные_задания/task2_2/main.py | 552 | 3.96875 | 4 | if __name__ == "__main__":
def palindrom(str):
# определяет, является ли строка палиндромом
str = str.lower()
letters = []
new_letters = []
for letter in str:
if letter != " " and letter != ",":
letters.append(letter)
new_letters = letters[::-1]
if letters == new_letters:
print('ДА')
else:
print('НЕТ')
return letters
print(palindrom('Я иду с мечем судия'))
|
ea33edbf48ed27352e00dd71b1683ea2722ee082 | attacker2001/Algorithmic-practice | /Codewars/123.py | 1,562 | 4.375 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
The galactic games have begun!
It's the galactic games! Beings of all worlds come together to compete in
several interesting sports, like nroogring, fredling and buzzing (the
beefolks love the last one). However, there's also the traditional marathon
run.
Unfortunately, there have been cheaters in the last years, and the committee
decided to place sensors on the track. Committees being committees, they've
come up with the following rule:
A sensor should be placed every 3 and 5 meters from the start, e.g. at 3m, 5m, 6m, 9m, 10m, 12m, 15m, 18m….
Since you're responsible for the track, you need to buy those sensors. Even
worse, you don't know how long the track will be! And since there might be
more than a single track, and you can't be bothered to do all of this by
hand, you decide to write a program instead.
Task
Return the sum of the multiples of 3 and 5 below a number. Being the galactic
games, the tracks can get rather large, so your solution should work for
really large numbers (greater than 1,000,000).
Examples
solution (10) # => 23 = 3 + 5 + 6 + 9
solution (20) # => 78 = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18
"""
def solution(number, length):
for i in xrange(number):
str_len = len(str(i))
if str_len <= length:
s = '0' * (length - str_len)
s += str(i)
print s
if __name__ == '__main__':
print solution(99999999, 8)
"""
Solution 1:
def solution(number):
return sum(x for x in range(number) if x % 3 == 0 or x % 5 == 0)
""" |
323681cce1b371b87d1f3e5e4c241524a1035641 | d1618033/recursion-tree | /examples.py | 1,314 | 3.671875 | 4 | from recursion_tree import recursion_tree
from random import choice
@recursion_tree(save_to_file=True)
def fibo(n):
if n <= 2:
return 1
else:
return fibo(n - 1) + fibo(n - 2)
@recursion_tree(save_to_file=True)
def permutations(array, soFar=None):
if soFar is None:
soFar = []
if len(array) == 0:
print(soFar)
else:
for index, value in enumerate(array):
permutations(array[:index] + array[index+1:], soFar + [value])
@recursion_tree(save_to_file=True)
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n - 1)
@recursion_tree(save_to_file=True)
def quick_sort(array):
if len(array) <= 1:
return array
pivot = choice(array)
left = quick_sort([a for a in array if a < pivot])
right = quick_sort([a for a in array if a > pivot])
middle = [a for a in array if a == pivot]
return left + middle + right
@recursion_tree(save_to_file=False)
def ackermann(m, n):
if m == 0:
return n + 1
elif m > 0:
if n == 0:
return ackermann(m - 1, 1)
else:
return ackermann(m - 1, ackermann(m, n - 1))
ackermann(2, 2)
ackermann(1, 1)
quick_sort([1, 9, 2, 4, 8, 6, 10, 5, 3, 11])
fibo(7)
factorial(4)
permutations(['a', 'b', 'c'])
|
78d9991c7df74a59d68e00bf08d330e9fd13dd6d | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4352/codes/1850_1278.py | 476 | 3.65625 | 4 | from numpy import*
from numpy.linalg import*
c1 = input("digite a cidade 1:")
m = array([[0,2,11,6,15,11,1],
[2,0,7,12,4,2,15],
[11,7,0,11,8,3,13],
[6,12,11,0,10,2,1],
[15,4,8,10,0,5,13],
[11,2,3,2,5,0,14],
[1,15,13,1,13,14,0]])
t = 0
i = 0
j = 1
while (c1 != "-1"):
if (i != j):
i = int(c1[0]) - 1
c1 = input("digite novamente: ")
elif (c1 != "-1"):
j = int(c1[0]) - 1
t = t + m[i,j]
c1 = input("digite novamente: ")
i = j
print(t) |
b8d6c6e67bb948241778225479d6474ced1d7129 | levypan666/lvp_python_learn | /unit_7/parrot_2.py | 241 | 3.515625 | 4 | prompt = "\n Tell me something, and i will repeat it back to you:"
prompt +="\n Enter 'quit to end the progtam."
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print (message) |
07bd3cc25ddc88eca7d1e26c1137e7b15f27021e | suriyaganesh97/pythonbasicprogs | /basic/greaterof3.py | 305 | 4.125 | 4 | num1 = int(input('enter no 1 '))
num2 = int(input('enter no 2 '))
num3 = int(input('enter no 3 '))
if (num1 >= num2 and num1 >= num3):
print('greater no is',num1)
if (num2 >= num3 and num2 >= num1):
print('greater no is',num2)
if (num3 >= num1 and num3 >= num2):
print('greater no is',num3) |
8c473faff0e7f5307f3667d6d3fc6ffef38b12a2 | vale2201/practicas | /practica 1/version antigua/prueba1.py | 119 | 3.640625 | 4 | print("introduce en primer numero?")
x=(int(input()))
print("introduce elsegundo numero?")
y=int((input()))
print (x+y) |
9d2969920a090651ac3dc7d10fbdd6f9120a1d79 | javis-code/ericundfelix | /lorenz/Quiz(Final).py | 3,612 | 3.703125 | 4 | a = 0
##########Frage 1##########
while True:
print(" ")
print("Frage 1")
print(" ")
print("Welche Farbe haben Bananen?")
List_1 = ["(A) Blau", "(B) Grün", "(C) Gelb", "(D) Rot"]
for item in List_1:
print(item)
Antwort = input("Ihre Antwort hier (A, B, C oder D): ")
if Antwort.lower().strip() == "a":
a+=0
break
elif Antwort.lower().strip() == "b":
a+=0
break
elif Antwort.lower().strip() == "c":
a+=1
break
elif Antwort.lower().strip() == "d":
a+=0
break
else:
print("")
print("Bitte überprüfen sie Ihre eingabe und versuchen es nochmal!")
##########Frage 2##########
while True:
print(" ")
print("Frage 2")
print(" ")
print("Wie heiß ist die Sonnenoberfläche?")
List_2 = ["(A) 1.600°C","(B) 6.000°C","(C) 24.000°C","(D) 100.000°C"]
for item in List_2:
print(item)
Antwort_2 = input("Ihre Antwort hier (A, B, C oder D): ")
if Antwort_2.lower().strip() == "a":
a+=0
break
elif Antwort_2.lower().strip() == "b":
a+=1
break
elif Antwort_2.lower().strip() == "c":
a+=0
break
elif Antwort_2.lower().strip() == "d":
a+=0
break
else:
print("")
print("Bitte überprüfen sie Ihre eingabe und versuchen es nochmal!")
##########Frage 3##########
while True:
print(" ")
print("Frage 3")
print(" ")
print("Wie hoch ist der Mount Everest?")
List_3 = ["(A) 8849 Meter","(B) 8953 Meter","(C) 8603 Meter","(D) 7973 Meter"]
for item in List_3:
print(item)
Antwort_3 = input("Ihre Antwort hier (A, B, C oder D): ")
if Antwort_3.lower().strip() == "a":
a+=1
break
elif Antwort_3.lower().strip() == "b":
a+=0
break
elif Antwort_3.lower().strip() == "c":
a+=0
break
elif Antwort_3.lower().strip() == "d":
a+=0
break
else:
print("")
print("Bitte überprüfen sie Ihre eingabe und versuchen es nochmal!")
##########Frage 4##########
while True:
print(" ")
print("Frage 4")
print(" ")
print("Wie viele Kubikkilometer Wasser sind im Pazifik?(Gerundet")
List_4 = ["(A) 600 Millionen km³","(B) 700 Millionen km³","(C) 800 Millionen km³","(D) 900 Millionen km³"]
for item in List_4:
print(item)
Antwort_4 = input("Ihre Antwort hier (A, B, C oder D): ")
if Antwort_4.lower().strip() == "a":
a+=0
break
elif Antwort_4.lower().strip() == "b":
a+=1
break
elif Antwort_4.lower().strip() == "c":
a+=0
break
elif Antwort_4.lower().strip() == "d":
a+=0
break
else:
print("")
print("Bitte überprüfen sie Ihre eingabe und versuchen es nochmal!")
##########Ergebnis##########
print(" ")
print("Ihr Ergebnis")
print(" ")
if a == 4:
print("Glückwunsch! Sie haben 4 von 4 Fragen richtig beantwortet!")
elif a == 3:
print("Das war eine gute Leistung. Sie haben 3 von 4 Fragen richtig beantwortet!")
elif a == 2 :
print("Fürs erste nicht schlecht. Sie haben 2 von 4 Fragen richtig beantwortet!")
elif a == 1:
print("Sie haben 1 von 4 Fragen richtig beantwortet. Probieren sie es doch nochmal!")
elif a == 0:
print("Es ist noch kein Meister vom Himmel gefallen. Sie haben 0 von 4 Fragen richtig beantwortet. Wenn sie ein bisschen lernen schaffen sie es beim nächsten mal bestimmt Besser!")
else:
print("Ups... Es ist ein Fehler aufgetreten!") |
67f4c8383c2ea197990863d7e93b014546d0b2f4 | ElisonSherton/python4everybody | /ch2ex5.py | 378 | 4.375 | 4 | # Exercise 5: Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature.
# Vinayak Nayak
# 27/12/2018
# IST 11:52 am
Celsius = float(input("Enter the temperature in degrees celsius: "))
Farenheit = Celsius * 1.8 + 32
print(str(Celsius) + " Celsius = " + str(round(Farenheit,2)) + " Farenheit." )
|
34864edded22b85eee866ae1b3cd5ddcbfd2f2f6 | Huangxx00/isdhw | /01/main.py | 181 | 3.78125 | 4 | for i in range(1,10):
print(" "*7*i,end="")
for j in range(i,10):
a=str.format("{0:1}*{1:1}={2:<3}",i,j,i*j)
print(a,end="")
print()
|
a62a0b60221e21713a3faa14302aa2bc6fdce75a | DavidAnacona/MisionTic-Universidad-El-Bosque--Python- | /cadenas.py | 1,080 | 4.28125 | 4 | """
Fundamentos de Programacion
Programa que simula los metodos para manejo de cadenas
Universidad El Bosque - Min Tic
"""
reiniciar = "s"
while reiniciar=="s":
print ("\n\t Universidad El Bosque - Min Tic ")
print ("\n\t Aplicacion con Metodos de Cadenas")
#Entradas
cadena = input("\n\t Digite una secuencia de caracteres= ")
tamaño = len(cadena)
print ("\n\t tamaño de la Cadena",tamaño)
#Imprima todas los elementos de la cadena posicion por posicion
for contador in range (0, tamaño):
letra= cadena[contador]
print ("\n\t Posicion[",contador,"]=",letra)
for contador in cadena:
print ("\t" ,contador)
print ("\t Imprimir los tres primeros datos de la cadena" ,cadena[0:3])
print ("\t Imprimir los tres primeros datos de la cadena" ,cadena[:3])
print ("\t Imprimir desde el quinto dato de la cadena hasta el final" ,cadena[5:])
print ("\t Imprimir los ultimo tres caracteres de la cadena",cadena[tamaño-3:])
print ("\t Imprimir los ultimo tres caracteres de la cadena",cadena[-3:]) |
7b7f086f3c95ce0cde3474bb2a42202b095c877d | kamleshkalsariya/Python_basic | /DSA/hashtable.py | 1,877 | 3.546875 | 4 | class HashTable:
def __init__(self):
self.Max = 10
self.arr = [None for i in range(self.Max)]
def get_hash(self,key):
hash = 0
for char in key:
hash += ord(char)
return hash % self.Max
def __setitem__(self, key, value):
h = self.get_hash(key)
self.arr[h] = value
def __getitem__(self, item):
h = self.get_hash(item)
return self.arr[h]
H = HashTable()
with open('nyc_weather.csv','r') as f:
for line in f:
tokens = line.split(',')
day = tokens[0]
temp = float(tokens[1])
H[day] =temp
print(H['Jan-09'])
print(H['Jan-04'])
class complex_HashTable:
def __init__(self):
self.MAX = 10
self.arr = [{} for i in range(self.MAX)]
def get_hash(self, key):
hash = 0
for char in key:
hash += ord(char)
return hash % self.MAX
def __getitem__(self, key):
h = self.get_hash(key)
return self.arr[h][key]
def __setitem__(self, key,value):
h = self.get_hash(key)
found = False
if (key in self.arr[h].keys()):
self.arr[h][key] += value
found = True
if not found:
self.arr[h][key] = 1
C =complex_HashTable()
with open('poem.txt','r') as f:
for line in f:
tokens = line.split()
for item in tokens:
C[item] = 1
for i in range(10):
print(C.arr[i])
print(C['Two'])
#####
word_count = {}
with open("poem.txt","r") as f:
for line in f:
tokens = line.split(' ')
for token in tokens:
token=token.replace('\n','')
if token in word_count:
word_count[token]+=1
else:
word_count[token]=1
print(word_count) |
6c5440924db0a3f21bac5950f35284938ac07b3c | SantoshKumarSingh64/December-2020-LeetCode-Monthly-Challenge | /D28_ReachANumber.py | 1,126 | 4.21875 | 4 | '''
Question Description :-
Reach a Number
You are standing at position 0 on an infinite number line. There is a goal at position target.
On each move, you can either go left or right. During the n-th move (starting from 1), you take n steps.
Return the minimum number of steps required to reach the destination.
Example 1:
Input: target = 3
Output: 2
Explanation:
On the first move we step from 0 to 1.
On the second step we step from 1 to 3.
Example 2:
Input: target = 2
Output: 3
Explanation:
On the first move we step from 0 to 1.
On the second move we step from 1 to -1.
On the third move we step from -1 to 2.
Note:
target will be a non-zero integer in the range [-10^9, 10^9].
'''
def reachNumber(target):
sum = 0
step = 0
target = abs(target)
while(sum < target):
sum += step
step += 1
while ((sum-target) % 2) != 0:
sum += step
step += 1
return step-1
print(reachNumber(2))
#Reference :- https://www.youtube.com/watch?v=JYbU8RH1OSQ |
67eaf0416a1da38d80eac948c0d59b60f153d614 | EricLin24/SSW810 | /HW09_ZiangLin.py | 4,547 | 3.71875 | 4 | """read the data from each of the three files(students.txt, grade.txt, instructors.txt) and store it in a data structure """
import collections
import os
from prettytable import PrettyTable
class Repository:
__slots__ = ['stu', 'ins', 'gra', 'studic', 'insdic']
def __init__(self):
self.stu = []
self.ins = []
self.gra = []
self.studic = collections.defaultdict(StuInf)
self.insdic = collections.defaultdict(InsInf)
def get_inf(self):
pre_path = os.getcwd()
while True:
# post_path = input("Please input the file of students' information:")
post_path = 'students.txt'
filename = os.path.join(pre_path, post_path)
try:
file = open(filename, 'r')
break
except FileNotFoundError:
print('You input a wrong file name, please try again.')
with file:
# cwid name major
for line in file.readlines():
cwid, name, major = line.split('\t')
self.stu.append([cwid, name, major.split('\n')[0]])
while True:
# post_path = input("Please input the file of instructors' information:")
post_path = 'instructors.txt'
filename = os.path.join(pre_path, post_path)
try:
file = open(filename, 'r')
break
except FileNotFoundError:
print('You input a wrong file name, please try again.')
with file:
# ins_id name dept
for line in file.readlines():
ins_id, name, dept = line.split('\t')
self.ins.append([ins_id, name, dept.split('\n')[0]])
while True:
# post_path = input("Please input the file of grades' information:")
post_path = 'grades.txt'
filename = os.path.join(pre_path, post_path)
try:
file = open(filename, 'r')
break
except FileNotFoundError:
print('You input a wrong file name, please try again.')
with file:
# cwid course grade ins_id
for line in file.readlines():
cwid, course, grade, ins_id = line.split('\t')
self.gra.append([cwid, course, grade, ins_id.split('\n')[0]])
def get_stu(self):
for cwid, name, major in self.stu:
stu_inf = StuInf()
stu_inf.cwid = cwid
stu_inf.name = name
stu_inf.major = major
for id, course, grade, ins_id in self.gra:
if stu_inf.cwid == id:
if grade not in ['A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'F']:
stu_inf.courses[course] = 'No grades yet'
else:
stu_inf.courses[course] = grade
self.studic[cwid] = stu_inf
return self.studic
def get_ins(self):
for iid, name, dept in self.ins:
ins_inf = InsInf()
ins_inf.ins_id = iid
ins_inf.name = name
ins_inf.dept = dept
for cwid, course, grade, ins_id in self.gra:
if ins_inf.ins_id == ins_id:
ins_inf.course[course] += 1
self.insdic[iid] = ins_inf
return self.insdic
def gen_stu_smy(self):
pt = PrettyTable(field_names=['CWID', 'Name', 'Completed Courses'])
for stu in self.studic.values():
pt.add_row([stu.cwid, stu.name, sorted(stu.courses.keys())])
print(pt)
return pt
def gen_ins_smy(self):
pt = PrettyTable(field_names=['CWID', 'Name', 'Dept', 'Course', 'Students'])
for ins in self.insdic.values():
for course, stu_num in ins.course.items():
pt.add_row([ins.ins_id, ins.name, ins.dept, course, stu_num])
print(pt)
return pt
class StuInf:
__slots__ = ['cwid', 'name', 'major', 'courses']
def __init__(self):
self.cwid = ''
self.name = ''
self.major = ''
self.courses = collections.defaultdict(str)
class InsInf:
__slots__ = ['ins_id', 'name', 'dept', 'course']
def __init__(self):
self.ins_id = ''
self.name = ''
self.dept = ''
self.course = collections.defaultdict(int)
def main():
rep = Repository()
rep.get_inf()
rep.get_stu()
rep.get_ins()
rep.gen_stu_smy()
rep.gen_ins_smy()
if __name__ == '__main__':
main() |
66cb253286b1948f8314cef8826cbf99908856ec | gadsone/genderbias | /backcompare.py | 4,097 | 3.6875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from tkinter import Tk, Label, Button
import tkinter as tk
df = pd.read_csv("genderbias.csv")
class MyFirstGUI:
def __init__(self, master):
self.master = master
master.title("Scholarly Hazing")
self.label = Label(master, text="What would you like to see?")
self.label.pack()
self.greet_button = Button(master, text="Show data", command=self.showdata)
self.greet_button.pack()
self.graph_button = Button(master, text="Show gender graph", command = self.showgraph)
self.graph_button.pack()
self.belief_button = Button(master, text="Show student beliefs", command = self.belief)
self.belief_button.pack()
self.same_button = Button(master, text="Show interaction", command = self.samegen)
self.same_button.pack()
self.close_button = Button(master, text="Close", command=master.quit)
self.close_button.pack()
df = pd.read_csv("genderbias.csv")
def showdata(self):
window = tk.Toplevel(root)
df.to_csv("pain.csv", encoding='utf-8', index=False)
print(df.tail)
def showgraph(self):
labels = 'Male','Female','Other'
gender_sizes = [25,40,1]
colors=['blue','green','orange']
explode = (0,0,0)
plt.pie(gender_sizes, explode=explode, labels=labels, colors=colors, shadow=True, startangle=90)
plt.title('Gender of Participants')
plt.show()
def belief(self):
"""Gender belief with options recoded to yes, no, not sure and professor recoded into yes category"""
labels = 'Yes', 'No', 'Not sure'
gb_sizes1 = [26,38,2]
colors = ['yellow','red','purple']
explode = (0,0,0)
plt.pie(gb_sizes1, explode=explode, labels=labels, colors=colors, shadow=True, startangle=90)
plt.title('Gender Bias Exists in USG Classrooms with Professors recoded into Yes Option')
plt.show()
def samegen(self):
answers = ('Never', 'Rarely','Sometimes','Often','Always', 'N/A')
responses = [4,9, 14, 27,10,2]
y_pos = np.arange(len(answers))
##colors = ['blue','red','orange','green','purple','yellow']
plt.bar(y_pos, responses, align='center',alpha=0.5, colors=colors)
plt.xticks(y_pos,answers)
plt.ylabel('Number of Responses')
plt.xlabel('Options for Question')
plt.title('Classroom Interaction with People of Same Gender')
plt.show()
root = Tk()
root.geometry("500x200+300+300") ##width x height + position right + position down
my_gui = MyFirstGUI(root)
root.mainloop()
"""
class comparewind:
def __init__(self, parent):
self.parent = parent
self.filename = "genderbias.csv"
self.df = None
self.text = tk.Text(self.parent)
self.text.pack()
self.button = tk.Button(self.parent, text = "Show Data", command = self.display)
self.button.pack()
def load(self):
name = "genderbias.csv"
if name:
if name.endswith('.csv'):
self.df = pd.read_csv(name)
else:
self.df = pd.read_excel(name)
self.filename = name
# display directly
#self.text.insert('end', str(self.df.head()) + '\n')
def display(self):
# ask for file if not loaded yet
if self.df is None:
self.load()
text = tk.Text(self)
text.insert(tk.END, str(df.iloc[:6,1:2]))
text.pack()
# display if loaded
if self.df is not None:
self.text.insert('end', self.filename + '\n')
self.text.insert('end', str(self.df.head()) + '\n')
# --- main ---
if __name__ == '__main__':
root = tk.Tk()
top = comparewind(root)
root.mainloop()
"""
|
1a04ac70f3eead114287bb22031a83f29b4a794d | pavel-prykhodko96/source | /Python/CrashCourse/Chapter8/8_9_to_8_11.py | 488 | 3.546875 | 4 | #8_9
def show_m(list_m):
for m in list_m:
print(m)
def make_great(list_m):
for n in range(len(list_m)):
list_m[n] = "Great " + list_m[n]
def make_great_no_change(list_m):
for n in range(len(list_m)):
list_m[n] = "Great " + list_m[n]
return list_m
magicians = ["Gendalf", "Saruman", "Dambldor", "Potter"]
new_mag = []
new_mag = make_great_no_change(magicians[:])
show_m(magicians)
show_m(new_mag)
make_great(magicians)
show_m(magicians)
|
f40124cdb4a630461f9f32fbfd08e54775a0fbb2 | sudhir33/TCS_NQT_Practice | /Integer_roman.py | 469 | 3.75 | 4 | def intToRoman(num):
list1 = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
list2 = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
roman= ''
n=len(list1)
for i in range(n):
if num<list1[i]:
continue
num = num - list1[i]
roman = roman + list2[i]
return roman
#main program
num=int(input())
res=intToRoman(num)
print(res)
|
f279f64bd84040a8165edc3d50f435e0211f4c1e | zebasare/Ejercicio_Clases_y_Objetos | /main.py | 1,376 | 3.96875 | 4 | import math
class Punto:
def __init__(self,x=0,y=0):
self.x=x
self.y=y
def __str__(self):
return f"Punto ubicado en {self.x,self.y}"
def cuadrante(self):
if self.x>0 and self.y>0:
print("El punto esta en el primer cuadrante")
elif self.x<0 and self.y>0:
print("El punto esta en el segundo cuadrante")
elif self.x<0 and self.y<0:
print("El punto se encuentra en el tercer cuadrante")
elif self.x>0 and self.y<0:
print("El punto se encuatra en el cuarto cuadrante")
else:
print("El punto se encuentra en el origen")
def vector(self,p):
vectX=(p.x-self.x)
vectY=(p.y-self.y)
print(f"Vector resultante : {vectX,vectY}")
def distancia(self,p):
dist=math.sqrt( (p.x-self.x)**2 + (p.y-self.y)**2)
print(f"Distancia del vector generado : ",dist)
class Rectangulo:
def __init__(self,inicial=Punto(0,0),final=Punto(0,0)):
self.inicial=inicial
self.final=final
def base_altura_area(self):
base=self.final.x-self.inicial.x
altura=self.final.y-self.inicial.y
print("Base :",base)
print("Altura: ",altura)
print("Area: ", base * altura)
unpunto=Punto()
otropunto=Punto(2,3)
unpunto.cuadrante()
unpunto.vector(otropunto)
unpunto.distancia(otropunto)
rect=Rectangulo(unpunto,otropunto)
rect.base_altura_area()
|
66499a2ede128ed6701aeaffc82dd74e8f6eff48 | SanjeevPhilip/python_assingments_problems | /jumbled_words.py | 726 | 3.890625 | 4 | import pandas as pd
import itertools
def sort_list(temp_li):
temp_li.sort()
temp_li = "".join(temp_li)
return temp_li
df = pd.read_csv("/usr/share/dict/words",header=None)
df["letters"] = (df[0].str.lower()).apply(list)
df["letters"] = df["letters"].apply(sort_list)
input_text = raw_input('Enter jumbled letters: ')
input_text = input_text.lower()
input_text_list = list(input_text)
all_combo_set = set()
for L in range(1, len(input_text_list)+1):
for subset in itertools.permutations(input_text_list, L):
combo = "".join(sorted(subset))
all_combo_set.add(combo)
for word in all_combo_set:
if len(df[df["letters"]== word]):
print((df[df["letters"]== word][0]).tolist())
|
fbf4c9ffe3572944319d2ea84e17ac3397cf0a6f | andonyan/Python-Advanced | /Lists as Stacks and Queues - Lab/Water Dispenser.py | 812 | 3.796875 | 4 | from collections import deque
queue = deque()
water_quantity = int(input())
while True:
name = input()
if name != 'Start' and name != 'End':
queue.append(name)
else:
if name == 'Start':
while len(queue) > 0:
quantity_required = input().split()
if 'refill' not in quantity_required:
if int(quantity_required[0]) <= water_quantity:
print(f'{queue.popleft()} got water')
water_quantity -= int(quantity_required[0])
else:
print(f'{queue.popleft()} must wait')
else:
water_quantity += int(quantity_required[1])
else:
print(f'{water_quantity} liters left')
break
|
57ec10fb850ddb33bda353631857748979f79054 | ATLAS-P/Introduction | /Workshop 1/Exercises/Guess the Number/Step 3.py | 410 | 3.765625 | 4 | import random
guessed = False
N = random.randint(1, 100)
def get_guess():
global guessed
guess = int(input("What's your guess, sir? "))
if guess == N:
print("Whoo! That's correct!")
guessed = True
elif guess < N:
print("Oops. That's too small.")
else:
print("Oops. That's too large.")
for i in range(7):
if guessed:
break
get_guess()
|
2af4149984573978a4bdc588f4b041fe7587bb9e | rohangala3105/FE_595 | /10432287_HW_1_FE_595.py | 945 | 3.796875 | 4 |
'''
Rohan Gala
10432287
FE 595
HW 1
Python Refresher
'''
# Importing numpy for creating the graphs
import numpy as np
# Importing matplotlib.pyplot for ploting the graphs
import matplotlib.pyplot as plt
# Taking values from 0 to 360(2pi) for the cycle of sine/cosine.
period = np.arange(0,2*np.pi,0.01)
# Sine Graph and Cosine Graph
sine = np.sin(period )
cosine = np.cos(period )
tan = np.tan(period) ###added the tangent function
# Plotting both the graphs
plt.plot(period , sine , period , cosine, period, tan)
####defining the x and y axis
plt.axis([0, 2*np.pi, -1, 1])
# Creating Legends
plt.subplot().legend(['Sine','Cosine','tan']) #
# Creating X and Y axes
plt.subplot().axhline(y=0, color='k')
plt.subplot().axvline(x=0, color='k')
# Displaying the plot
plt.show()
###Saving the file locally
plt.savefig("tangent.png")
|
bb579477790f8d93f12b5239d3dec515d8404188 | fausecteam/ctf-gameserver | /src/ctf_gameserver/lib/date_time.py | 989 | 3.65625 | 4 | import datetime
def ensure_utc_aware(datetime_or_time):
"""
Ensures that a datetime or time object is timezone-aware.
For naive objects, a new object is returned with its timezone set to UTC. Already timezone-aware objects
are returned as-is, without any timezone change or conversion.
"""
if datetime_or_time is None:
return None
# This is how timezone-awareness is officially defined
if datetime_or_time.tzinfo is not None:
if isinstance(datetime_or_time, datetime.datetime):
if datetime_or_time.tzinfo.utcoffset(datetime_or_time) is not None:
return datetime_or_time
elif isinstance(datetime_or_time, datetime.time):
if datetime_or_time.tzinfo.utcoffset(None) is not None:
return datetime_or_time
else:
raise TypeError('ensure_utc_aware() can only handle datetime and time objects')
return datetime_or_time.replace(tzinfo=datetime.timezone.utc)
|
6d411bd602e15d4ced1d157485121462fdd1e0e1 | proleaders/python_problem_solving | /Plus Minus.py | 634 | 3.640625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
def plusMinus(arr):
positive_number = []
negative_number = []
zeroes = []
for i in arr:
if i < 0:
negative_number.append(i)
if i > 0:
positive_number.append(i)
if i == 0:
zeroes.append(i)
print(float(len(positive_number)/len(arr)))
print(float(len(negative_number)/len(arr)))
print(float(len(zeroes)/len(arr)))
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr)
|
2b89f3147644410bcce525911efd663bbcc2a561 | Minkov/python-oop-2021-02 | /decorators/lab/vowels_filter.py | 482 | 3.765625 | 4 | def vowel_filter(func):
vowels = set('aeiou' + 'aeiou'.upper())
def wrapper():
result = func()
return [c for c in result if c in vowels]
return wrapper
@vowel_filter
def get_letters():
return ["a", "b", "c", "d", "e"]
@vowel_filter
def get_hello_message():
return f'Hello, I am Pesho'
@vowel_filter
def get_current_temperature():
return '3\' celsius'
print(get_letters())
print(get_hello_message())
print(get_current_temperature())
|
7c88ae6133534d5c583782446f68d7f5b3e29c55 | alejandrocca/machine-learning-projects | /mnist.py | 4,415 | 3.703125 | 4 | '''
Name : Xingjia Wang
Date : 10/02/2018
Project Name: PyTorch Based MNIST Demo with Linear Models
Project Description:
A simple machine learning project with a self-built neural network linear model based on the
MNIST handwritten number training (60000 samples) and testing datasets (10000 samples.) Training takes
10 epochs, and each epoch is set with a batch size of 64 samples. The accuracy after 10 epochs reached
96% on my computer.
'''
import torch
from torch.autograd import Variable # Container for tensors which a neural network model will take in
import torch.nn as nn # For building neural network
import torch.nn.functional as F # Activation functions
import torch.optim as optim # Optimizer
import torchvision # MNIST datasets
import torchvision.transforms as transforms # Data to tensor transformation
# ---------------- PREP -----------------
# Training settings
#
# Note:
# 1 epoch = 1 time training through the entire dataset
# 1 iteration = 1 time training through the set of BATCH_SIZE number of samples
BATCH_SIZE = 64
# Function to transform mnist pics to tensors
transform = transforms.ToTensor()
# Load Datasets from MNIST
train_set = torchvision.datasets.MNIST('./mnist_data/', train = True, download = True, transform = transform)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=BATCH_SIZE, shuffle = True, num_workers = 2)
test_set = torchvision.datasets.MNIST('./mnist_data/', train = False, download = True, transform = transform)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=BATCH_SIZE, shuffle = False, num_workers = 2)
# Note-to-self question: What is the significance of num_workers?
# ------------ MODEL BUILDING ------------
# Building the neural network model
class nnMNIST(nn.Module):
def __init__(self):
super(nnMNIST, self).__init__() # inheriting class structure
self.lin1 = nn.Linear(28*28, 512) # MNIST images have sizes of 28*28 pixels
self.lin2 = nn.Linear(512, 256)
self.lin3 = nn.Linear(256, 128)
self.lin4 = nn.Linear(128, 10) # four hidden layers in total, outputting 0-9 (10 in total)
def forward(self, x):
x = x.view(-1, 784) # flattening the original 2d dataset
x = F.relu(self.lin1(x))
x = F.relu(self.lin2(x))
x = F.relu(self.lin3(x)) # calling activation function through each inner layer
y_hat = self.lin4(x)
return y_hat
model = nnMNIST()
# Parameters for Training
criterion = nn.CrossEntropyLoss() # Loss function with softmax
optimizer = optim.SGD(model.parameters(), lr = 0.01, momentum = 0.5) # Optimizing with gradient descent, learning rate = 0.01
# also consider optim.Adam()
# Function to train the neural network
def train(epoch):
model.train()
for batch_pos, (data, target) in enumerate(train_loader):
data, target = Variable(data), Variable(target) # Tensors -> Variables
optimizer.zero_grad() # Standardized step: need to look up why this step... something to clear out?
output = model(data) # Put data through the network model and get the output
loss = criterion(output, target) # Calculate loss
loss.backward() # Standardized step: something related to gradient descent... also need to look up
optimizer.step() # Standardized step: same as above... I don't quite remember
# Screen output
# Sample: Train Epoch: 1 [0/60000] (0%) Loss: 2.000000
if batch_pos % 10 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(epoch, batch_pos * len(data), len(train_loader.dataset), 100. * batch_pos / len(train_loader), loss.data[0]))
# Function to test the neural network
def test():
model.eval() # I don't remember why... need to look up
test_loss = 0
correct = 0
for data, target in test_loader:
data, target = Variable(data, volatile = True), Variable(target)
output = model(data)
test_loss += criterion(output, target).data[0] # sum up batch loss
pred = output.data.max(1, keepdim = True)[1] # get index of max
correct += pred.eq(target.data.view_as(pred)).cpu().sum()
test_loss /= len(test_loader.dataset)
# Screen output
# Sample: Test set: Average loss: 0.1000, Accuracy: 9700/10000 (97%)
print ('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(test_loss, correct, len(test_loader.dataset), 100. * correct / len(test_loader.dataset)))
# ---------------- MAIN -----------------
for epoch in range(1, 11):
train(epoch)
test()
|
12e070af78b92bfdf90ac27f3d81440cacf8aaab | MifengbushiMifeng/Data-Structure-and-Algorithms | /Python/Missing-Number/Math.py | 169 | 3.640625 | 4 | class Math:
def missingNumber(self, nums):
expected_sum = len(nums)*(len(nums)+1)//2
actual_sum = sum(nums)
return expected_sum - actual_sum
|
d00810642ca021d2ae6af795eccfb6c1ee2fd709 | Sequd/python | /Patterns/FactoryMethod.py | 733 | 3.9375 | 4 | class Car:
"""Base car"""
def __init__(self, name):
self.name = name
def factory(self):
if self == "sport":
return Sportcar()
elif self == "mini":
return Minicar()
assert 0, "Not found car type: " + self
# else:
# raise Exception("Not found car type")
def __str__(self):
return "It is %s" % self.name
class Sportcar(Car):
"""Sport car"""
def __init__(self) -> None:
super().__init__("Sportcar")
class Minicar(Car):
"""Mini car"""
def __init__(self) -> None:
super().__init__("Minicar")
car = Car.factory("sport")
print(car)
car = Car.factory("mini")
print(car)
# car = Car.factory("asd")
|
7e70a63ce78f04b076cc8f9cd27a39639d7b2e1c | vladislavbasyk/Lessons | /Python/excepts/raising.py | 769 | 3.71875 | 4 | #!/usr/bin/env python3
class ShotInputException(Exception):
# пользовательский класс исключения
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
text = input('Введите что-нибудь:')
if len(text) < 3:
raise ShotInputException(len(text), 3)
# Здесь может происходить обычная работа
except EOFError:
print('Зачем вы сделали EOF?')
except ShotInputException as ex:
print('ShotInputException: Длина введенной\
строки', ex.length, 'ожидалось минимум', ex.atleast)
else:
print('Не было исключений') |
44c5ff52ff6ff7e653a8b50aa598dc231f5cb90b | pothedarsuhas/Data-Structures-Algorithms | /lineardatastructures/postfixtoinfix.py | 431 | 3.53125 | 4 | from stack import *
e = "*+ABC"
st = "" #to convert prefix to infix, reverse the expression, use this same program
for i in e:
st = i + st
print(st)
s = stack()
operators = "+-*/"
for i in st:
if i not in operators:
s.push(i)
elif i in operators:
a = s.pop()
b = s.pop()
c = str(a)+str(i)+str(b)
print(c)
s.push(c)
print(s.pop())
|
be104d93262456e9937aa38c986350afa35726ee | mecozma/100DaysOfCode-challenge | /ctci/2/delete-middle-node.py | 2,007 | 3.96875 | 4 | """
Implement an algorithm to delete a node in the middle (i.e., any node but the
first and the last node, not necesarily the exact middle) of a singly linked
list, given access to that node.
Example:
Input: the node c from the linked list a->b->c->d->e->f
Output: nothing is returned, but the new linked list looks like:
a->b->d->e->f->
"""
import math
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.next = None
class SLinkedList:
def __init__(self):
self.head = None
self.tailval = None
self.length = 0
def add_node(self, value):
newNode = Node(value)
if(self.head):
current = self.head
while(current.next):
current = current.next
current.next = newNode
else:
self.head = newNode
self.length += 1
def traverseLL(self):
current = self.head
ll_length = 0
while current:
ll_length += 1
print(current.dataval)
current = current.next
return ll_length
def find_nth_to_last(self, index):
current = self.head
if index < 0 > self.length:
return False
for i in range(self.length - index - 1):
current = current.next
print(current.dataval)
def remove_middle(self):
middle = math.floor(self.length / 2)
current = self.head
previous = None
if self.length < 3:
return False
for i in range(self.length):
if i == middle:
previous.next = current.next
self.length -= 1
break
else:
previous = current
current = previous.next
sll = SLinkedList()
sll.add_node(0)
sll.add_node(1)
sll.add_node(2)
sll.add_node(3)
sll.add_node(4)
sll.add_node(5)
sll.add_node(6)
sll.add_node(7)
sll.remove_middle()
sll.remove_middle()
sll.traverseLL()
|
5d5dbba221c152d37977315e2fc7f745995dc962 | acalio/gnn-diffusion | /cascade-generator/cascade_generator/generator.py | 5,277 | 3.578125 | 4 | import numpy.random as rn
from networkit.centrality import DegreeCentrality
import tqdm
class CascadeGenerator:
"""Cascade Generator.
This class is in charge of running a diffusion
process and to collect the output of the propagation.
Parameters
----------
influence_graph: networkit Graph object
influence graph
diffusion_model: DiffusionModel
diffusion model to generate the cascades
"""
def __init__(self, influence_graph, diffusion_model):
self.influence_graph = influence_graph
self.diffusion_model = diffusion_model
def __call__(self, k, num_of_runs=1, seed_selection_strategy='degree',
beta=1.0):
""" Method to generate the cascades
Parameters
----------
k: int or list-like of int of shape (num_of_runs,)
number of initial seeds of the propagation.
If k is a single integer than each simulation has
the same number of initial seeds
num_of_runs: int, default=1
number of propagation process to run.
seed_selection: {'degree', 'uniform', 'random-walk' }, default='degree'
strategy to randomly select the seeds of the propagation
- 'degree' nodes are selected according to their out degree.
Nodes with high out-degree are more likely to be selected
- 'uniform' nodes are selected according to a uniform distribution.
Each node has the same probability 1/N to be selected, where N
is the number of nodes in the graph
- 'random-walk' nodes are selected according to a random walk
strategy. This strategy requires the selection probability
\beta which denotes the probability
of a node to be inserted into the seed
set once it has been reached by the random walker.
More specifically, the process starts from a node v,
selected uniformly at random, which is added to
the seed set. Given v, the random walker jumps on
one of v's out-neighbors (each neighbor is equally likely to
be selected), call it u. u will be inserted into the
seed set with probability \beta.
The random walker proceeds until the seed set reaches the
desired size
beta: float, optional
random walk selection probability
Return
------
cascades: list of cascades
a list containing every cascade generated
"""
if isinstance(k, tuple) or isinstance(k, list):
runs = k
else:
runs = [k] * num_of_runs
# determine the seed selection strategy
if seed_selection_strategy in ('uniform', 'degree'):
if seed_selection_strategy == 'uniform':
probs = None
else:
probs = DegreeCentrality(self.influence_graph).run().scores()
# normalize the probability so they sum up to 1
probs = [d/sum(probs) for d in probs]
def choice(nodes, k): return rn.choice(nodes, k, replace=False, p=probs)
elif seed_selection_strategy == 'random-walk':
def choice(nodes, k): return self.random_walk(nodes, k, beta)
else:
raise ValueError("Unknown selection strategy: %s" %
seed_selection_strategy)
# initialize the list of cascades
cascades = []
# get the list of node ids
nodes = []
self.influence_graph.forNodes(lambda v: nodes.append(v))
# get the seeds of the propagation
for k in tqdm.tqdm(runs):
seeds = choice(nodes, k)
_, cascade = self.diffusion_model(self.influence_graph, seeds)
cascades.append(cascade)
return cascades
def random_walk(self, nodes, k, beta):
"""Random walk selection strategy
Parameters
----------
nodes: list of nodes
nodes of the graph
k: int
size of the seed set
beta: float
selection probability
Returns
-------
list of int
seed set
"""
def start():
# start the random walker
start_node = rn.choice(nodes)
return start_node, set([start_node])
current_node, seeds = start()
while len(seeds) < k:
try:
# get v's neigbors
neigh = [u for u in self.influence_graph.iterNeighbors(current_node)]
# select one of the neigbors
next_node = rn.choice(neigh)
current_node = next_node
if rn.rand() <= beta:
if next_node in seeds:
if next_node in seeds:
# might be in a loop - start all over
raise ValueError
seeds.add(next_node)
except ValueError:
# some of the nodes has no out-neighbors
# discard the entire selection and start from
# the beginning
current_node, seeds = start()
return seeds
|
0a480c07b73c11000e89cae21aeaea27a7ad3d0d | Matheus-616/Stepik | /lista8: recursão/L8Q2.py | 703 | 3.9375 | 4 | '''
[1 ponto] Escreva uma função matriz_2x2_inversa: recebe uma matriz 2×2 e calcula a sua inversa. Retorne None caso a matriz seja singular.
Cabeçalho da função:
def matriz_2x2_inversa(M):
Não se preocupe com a chamada das funções, ou impressão dos resultados, isso será feito automaticamente.
Escreva apenas as funções solicitadas.
'''
def matriz_2x2_inversa(M):
det_M = M[0][0]*M[1][1]-M[0][1]*M[1][0]
if det_M != 0:
M1 = [[0,0],[0,0]]
M1[0][0] = M[1][1]
M1[0][1] = -M[0][1]
M1[1][0] = -M[1][0]
M1[1][1] = M[0][0]
for i in range(2):
for j in range(2):
M1[i][j] *= 1/det_M
return M1
|
00fb551a6cf58e40e2530264669a049ff560d3cf | sjaney/PDX-Code-Guild---Python-Fullstack-Solution | /python/lab15.py | 1,508 | 4.1875 | 4 | # Lab 15 Count Words
import requests
import string
# Make everything lowercase, strip punctuation, split into a list of words.
def use_requests():
response = requests.get('https://www.gutenberg.org/files/64214/64214-0.txt')
book = response.text.lower() # make everything lowercase
return book
book = use_requests()
'''
str.maketrans creates a translation table containing the mapping
between two characters. To remove all punctuations str.maketrans('', '', string.punctuation)
creates mapping from empty string to empty string, and punctuations to None.
'''
no_punctuation = book.translate(str.maketrans('', '',string.punctuation))
words = no_punctuation.split() # split into a list of words
''' Your dictionary will have words as keys and counts as values. If a word isn't in your dictionary yet, add it with a count of 1.
If it is, increment its count.'''
word_list = {} # create empty dict
for word in words:
if word not in word_list:
word_list[word] = 0
word_list[word] += 1
# Print the most frequent top 10 out with their counts. You can do that with the code below.
# word_dict is a dictionary where the key is the word and the value is the count
most_frequent = list(word_list.items()) # .items() returns a list of tuples
most_frequent.sort(key=lambda tup: tup[1], reverse=True) # sort largest to smallest, based on count
for i in range(min(10, len(most_frequent))): # print the top 10 word, or all of them, whichever is smaller
print(most_frequent[i]) |
44e6269a1dec3ef2a13a9449d7d9ff1c4e501369 | Sebstar2000/semiprime | /index.py | 965 | 3.875 | 4 | minVal = int(input("Minimum Value:"))
maxVal = int(input("Maximum Value:"))
primeNumbers = []
semiprime = []
def checkNumber(num):
isPrime = True
for i in range(2, num):
if num % i == 0:
isPrime = False
if isPrime == True:
global primeNumbers
primeNumbers.append(str(num))
def timesNumbers():
for i in primeNumbers:
for x in primeNumbers:
outNum = int(i)*int(x)
# print("For1:",i,"For2",x,"OutNum:",outNum)
if outNum <= maxVal and outNum >= minVal:
semiprime.append(outNum)
def removeDup(inputArray):
outputArray = []
for element in inputArray:
if element not in outputArray:
outputArray.append(element)
return outputArray
for i in range(1,maxVal):
checkNumber(i)
# print(primeNumbers)
primeNumbers.pop(0)
timesNumbers()
output = removeDup(semiprime)
print(sorted(output)) |
984469c33fd33b7cfe3d770163580c075506b408 | zolcsika71/JBA_Python | /Rock-Paper-Scissors/Problems/Decimal places/main.py | 132 | 3.5625 | 4 | number = float(input())
decimal_places = int(input())
print(f'{number:.{decimal_places}f}')
# print(round(number, decimal_places))
|
3604fe72a2a5c65fcc784b401581321e4c29665f | teja-rostan/DeepExpressionLearner | /data_target.py | 3,691 | 3.6875 | 4 | """
A program for data and target retrieving in right format used by class_learning.py and reg_learning.py
"""
import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder
def get_datatarget(scores_file, delimiter, target_size, problem_type, class_, nn_type):
"""
Reads a complete file with pandas, splits to data and target and makes wished preprocessing of the target variables.
:param scores_file: The file with data and targets for neural network learning.
:param delimiter: The delimiter for the scores_file.
:param target_size: Number of columns at the end of scores_file that represent target variables.
:param nn_type: The type of learning problem for neural networks {class, reg, ord}.
:param class_: Number of classes (supported in classification problem).
:return: data that represent the input of neural network, target that represent the output of neural network,
raw target expressions and classified target.
"""
""" get data """
df = pd.read_csv(scores_file, sep=delimiter)
input_matrix = df.select_dtypes(include=['float64', 'int']).as_matrix()
""" split data and target """
data = input_matrix[:, :-target_size]
if nn_type == "cnn":
data = data.reshape((-1, 1, 1, data.shape[1]))
target = input_matrix[:, -target_size:]
target_class = 0
target_names = list(df)[-target_size:]
if problem_type == "class":
""" Classify raw expression with percentil thresholds or raw value thresholds"""
# TODO: make without manual fix
target_class = classification(target, 0.2, 0.8) # raw value thresshold
# target_class = classification(target, 0.1, 0.9) # percentile threshold
print(target_class.shape)
target = one_hot_encoder_target(target_class, class_)
ids = df['ID'].as_matrix()
return data, target, target_class, ids, target_names
def classification(target, down_per, up_per):
"""
Changes to a classification problem up to three classes.
:param target: Raw target values that we want to classify.
:param down_per: lower threshold as percentile.
:param up_per: upper threshold as percentile.
:return: new target with classes.
"""
new_target = np.zeros(target.shape)
for i, expression in enumerate(target.T):
new_expression = np.ones(expression.shape)
# IF USING PERCENTIL THRESHOLD FOR CLASSIFICATION # TODO: make without manual fix
# down_10 = np.percentile(expression, down_per * 100)
# up_10 = np.percentile(expression, up_per * 100)
# new_expression -= (expression <= down_10)
# new_expression += (expression >= up_10)
# IF USING RAW VALUE THRESHOLD [0, 1] FOR CLASSIFICATION # TODO: make without manual fix
new_expression -= (expression < down_per)
new_expression += (expression > up_per)
new_target[:, i] = new_expression
return new_target
def one_hot_encoder_target(y, k):
"""
One hot encoding of all target variables (can handle multiple targets with k classes).
:param y: target variables.
:param k: number of classes per target.
:return: one hot per target.
"""
new_y = np.zeros((y.shape[0], y.shape[1] * k))
# for i in range(y.shape[1]):
# col = y[:, i]
# enc = OneHotEncoder(sparse=False)
# one_hot = enc.fit_transform(col.reshape(-1, 1))
# new_y[:, i * k:i * k + k] = one_hot
for i, s in enumerate(y):
new_row = np.array(list(s)).astype(np.int)
b = np.zeros((new_row.size, 3))
b[np.arange(new_row.size), new_row] = 1
new_y[i] = b.flatten()
return new_y
|
11bf6cda5e9a65bacdd69af2632640ebb35c7f3a | rishabh1994/DSA | /show_me_the_data_structure/pythonFiles/problem_3.py | 4,876 | 3.5625 | 4 | from queue import PriorityQueue
import sys
class Node:
def __init__(self, character, count):
self.character = character
self.count = count
self.left = None
self.right = None
self.binaryCode = None
def __lt__(self, other):
return self.count <= other.count
def updateCharacterToBinaryCodeMap(node, characterToBinaryCodeMap):
if node:
if not node.character == 'nonLeafNode':
characterToBinaryCodeMap[node.character] = node.binaryCode
updateCharacterToBinaryCodeMap(node.left, characterToBinaryCodeMap)
updateCharacterToBinaryCodeMap(node.right, characterToBinaryCodeMap)
def addNodes(node1, node2):
if node1 and node2:
updatedCount = node1.count + node2.count
elif node1:
updatedCount = node1.count
elif node2:
updatedCount = node2.count
else:
return None
node3 = Node('nonLeafNode', updatedCount)
node3.left = node1
node3.right = node2
return node3
def constructTree(priorityQueue):
while priorityQueue.qsize():
firstNode = priorityQueue.get()
if firstNode.character == 'nonLeafNode' and priorityQueue.qsize() == 0:
return firstNode
if priorityQueue.qsize() == 0:
secondNode = None
else:
secondNode = priorityQueue.get()
combinedNode = addNodes(firstNode, secondNode)
priorityQueue.put(combinedNode)
def constuctPriorityQueue(inputString):
characterToCount = dict()
for char in inputString:
if char in characterToCount.keys():
characterToCount[char] += 1
else:
characterToCount[char] = 1
priorityQueue = PriorityQueue()
for character in characterToCount.keys():
count = characterToCount[character]
priorityQueue.put(Node(character, count))
return priorityQueue
def updateBinaryCode(rootNode):
if rootNode:
if rootNode.left:
updateBinaryCodeHelper(rootNode.left, "0")
if rootNode.right:
updateBinaryCodeHelper(rootNode.right, "1")
def updateBinaryCodeHelper(node, parentCode):
tempNode = node
if tempNode:
tempNode.binaryCode = parentCode
if tempNode.left:
updateBinaryCodeHelper(tempNode.left, parentCode + "0")
if tempNode.right:
updateBinaryCodeHelper(tempNode.right, parentCode + "1")
def huffman_encoding(data):
queue = constuctPriorityQueue(data)
rootNode = constructTree(queue)
updateBinaryCode(rootNode)
characterToBinaryCodeMap = dict()
updateCharacterToBinaryCodeMap(rootNode, characterToBinaryCodeMap)
huffmanEncodedData = ""
for charcter in data:
huffmanEncodedData += characterToBinaryCodeMap[charcter]
return huffmanEncodedData, rootNode
def huffman_decoding(data, rootNode):
updateBinaryCode(rootNode)
characterToBinaryCodeMap = dict()
updateCharacterToBinaryCodeMap(rootNode, characterToBinaryCodeMap)
newLookupMap = dict()
for character in characterToBinaryCodeMap:
binaryCode = characterToBinaryCodeMap[character]
newLookupMap[binaryCode] = character
newLookupMap[character] = binaryCode
decodedString = ''
combinedCharacter = ''
for character in data:
combinedCharacter += character
if combinedCharacter in newLookupMap.keys():
decodedString += newLookupMap[combinedCharacter]
combinedCharacter = ''
return decodedString
def test_case(a_great_sentence):
print("The size of the data is: {}\n".format(sys.getsizeof(a_great_sentence)))
print("The content of the data is: {}\n".format(a_great_sentence))
encoded_data, tree = huffman_encoding(a_great_sentence)
print("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2))))
print("The content of the encoded data is: {}\n".format(encoded_data))
decoded_data = huffman_decoding(encoded_data, tree)
print("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data)))
print("The content of the encoded data is: {}\n".format(decoded_data))
def empty_string_test_case():
input = ""
encoded_data, tree = huffman_encoding(input)
print(encoded_data)
# Since our input string is "" that is empty string. Our ouput string is also "". And we compare both below and True is printed.
decoded_data = huffman_decoding(encoded_data, tree)
print(decoded_data == input)
if __name__ == "__main__":
test_case("The bird is the word")
# Test with same character. Here since just 1 character is there. We will just assign it 0 bit and the answer
# would be the number of times this character occurs in the string which is 15 here. So answer will be 15 0's.
test_case("AAAAAAAAAAAAAAA")
test_case("AAAABBBBCCCCDDDD")
|
0499226de56c60c225eccac6bfa3bf39dc64fb0a | gerrylwk/Efficient-Matrix-Algorithms | /augGaussLabel.py | 1,087 | 3.609375 | 4 | import numpy as np
def augGaussLabel(A): #Gaussian with row labels, to prevent
n = len(A) #unnecessary changes in entries with zero pivot elements
r = np.arange(n)
for i in range(0,n-1):
j = i
while j <= n-1 and A[r[j]][i] == 0:
j += 1
if j == n:
print("Error. Matrix is singular.")
elif j != i:
r[i],r[j] = r[j],r[i]
for j in range(i+1,n):
m = A[r[j]][i]/A[r[i]][i]
for k in range(i+1,n+1):
A[r[j]][k] -= m*A[r[i]][k]
x = np.zeros(n) # General backward substitution
x[n - 1] = A[r[n - 1]][n] / A[r[n - 1]][n - 1]
for i in range(n - 1, -1, -1):
x[i] = A[r[i]][n]
for j in range(i + 1, n):
x[i] -= A[r[i]][j] * x[j]
x[i] = x[i] / A[r[i]][i]
x[i] = round(x[i],7)
print(x)
return(x)
A = np.array([[1,2,3,0],[3,4,7,2],[6,5,9,11]],dtype=float) #example input
augGaussLabel(A) #4,1,-2
|
516d8356436ab73ef180e2d4319cf2ba2ca2ce84 | s-surineni/atice | /leet_code/find_words_chars.py | 396 | 3.96875 | 4 | from collections import Counter
def find_words_chars(words, chars):
char_count = Counter(chars)
len_sum = 0
for a_word in words:
a_word_counter = Counter(a_word)
len_sum += len(
a_word) if a_word_counter & char_count == a_word_counter else 0
return len_sum
words = ["cat", "bt", "hat", "tree"]
chars = "atach"
print(find_words_chars(words, chars))
|
3b52d3c9e4da651e79cf5d9f0dec641d83af7762 | annazof/LCbasic2021 | /Baisc Track/how_to_think/Chapter 3/exercise3.4.4.15.py | 378 | 3.9375 | 4 | #An equilateral triangle
import turtle
canvas = turtle.Screen()
leo = turtle.Turtle()
#triangle
for i in range(3):
leo.forward(50)
leo.left(120)
#square
for i in range(4):
leo. forward(100)
leo.left(90)
#hexagon
for i in range(6):
leo.forward(80)
leo.right(60)
#octagon
for i in range(8):
leo.forward(150)
leo.left(45)
canvas.exitonclick()
|
f4ebe77a4a3dfbeaca07ca2cc356079cb68a9d51 | ashish-ucsb/xor_back_propagation | /xor_back_prop.py | 2,896 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[17]:
import numpy as np
import matplotlib.pyplot as plt
import random
# In[18]:
# Visualization of XOR in 2-D Space
plt.plot([1,0], [1,0], 'ro', marker="+", markersize=20, color = 'blue')
plt.plot([1,0], [0,1], 'ro', marker="_", markersize=20, color = 'red')
plt.axis([-0.1, 1.1, -0.1, 1.1])
plt.xlabel('First input of x',size=10)
plt.ylabel('Second input of x',size=10)
plt.show()
# In[19]:
# Sigmoid Function
def sigm(x):
return 1/(1+ np.exp(-x))
# Derivative of Sigmoid Function
def der(x): # takes sigmoid of x
return x*(1-x)
# Propogation
def prop(lr, epochs, noise):
# Variables Initialization
x = np.array([[1,1],[0,0],[1,0],[0,1]]) # Input matrix
x = np.random.normal(loc=x, scale=noise) # adding gaussian noise
y = np.array([[1],[1],[-1],[-1]]) # Target Output
w_hidden = np.random.rand(2,2) # 2x2 random Hidden weights
w_out = np.random.rand(2,1) # 2x1 random output weights
in_h = np.zeros((4,2)) # Input at Hidden Layer
out_h = np.zeros((4,2)) # Output from Hidden Layer
out_y = np.zeros((4,1)) # Estimated Output
for i in range(epochs):
# Forward Propogation
in_h = np.matmul(x,w_hidden)
out_h = sigm(in_h)
out_y = np.matmul(out_h, w_out)
# Backward Propogation
error = y - out_y
del_2 = error * lr
w_out = w_out + np.matmul(out_h.T, del_2)
del_1 = np.matmul(del_2, w_out.T) * der(out_h)
w_hidden = w_hidden + np.matmul(x.T, del_1)
return(w_hidden, w_out)
# Predict function uses weights to predict outputs on new inputs
def predict(x, W_hidden, W_out):
in_h = np.matmul(x,W_hidden)
out_h = sigm(in_h)
out_y = np.matmul(out_h,W_out)
return out_y
# In[20]:
lr = 0.01 # Learning Rate
epochs = 100000 # Epochs
noise = 0 # Gaussian Noise
W_hidden, W_out = prop(lr, epochs, noise)
# In[21]:
print("Hidden Weights (w1, w2, w3, w4) : {}, {}, {}, {}".format(W_hidden[0][0], W_hidden[0][1], W_hidden[1][0], W_hidden[1][1]))
print("Output Weights (w5, w6) : {}, {}".format(W_out[0][0], W_out[1][0]))
# In[22]:
# Classification Region in 2-D (Without Gaussian Noise)
random_inputs = np.random.uniform(low=-2, high=2, size=(1000,2))
k = predict(random_inputs, W_hidden, W_out)
plus = 0
minus = 0
for i in range (1000):
if k[i][0] >= 0:
plus = plus + 1
plt.plot(random_inputs[i,0], random_inputs[i,1], 'ro', marker="+", color = 'blue')
else:
minus = minus +1
plt.plot(random_inputs[i,0], random_inputs[i,1], 'ro', marker="_", color = 'red')
plt.axis([-2.1, 2.1, -2.1, 2.1])
plt.xlabel('First input of x',size=10)
plt.ylabel('Second input of x',size=10)
plt.show()
print(plus, minus)
|
0b62f93f32e16bf81cf30f28b3aa61caa33e16c7 | RodolfoContreras/AprendaPython | /Tablas.py | 312 | 3.609375 | 4 | # Tablas.py
# Autor: Contreras Galvan Rodolfo Alejandro
# Fecha de creación: 02/09/2019
for tabla in range(1,11):
encabezado="Tabla del {}"
print(encabezado.format(tabla))
print()
for tablas in range(1,11):
R="{} x {} = {}"
print(R.format(tabla,tablas,tabla*tablas))
else:
print() |
1b415550094fb8f04a520f03052fd2df80e51451 | msaei/coding | /LeetCode/Top Interview Questions/Dynamic Programming/Unique Paths.py | 427 | 3.65625 | 4 | #Unique Paths
#https://leetcode.com/explore/interview/card/top-interview-questions-medium/111/dynamic-programming/808
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
mem = [[1] * n for _ in range(m)]
print(mem)
for i in range(1, m):
for j in range(1, n):
mem[i][j] = mem[i-1][j]+mem[i][j-1]
print(mem)
return mem[m-1][n-1]
|
968b94ab4baa01221a6b14384dd26a0376ac44ef | lobsangmerc/caldoe | /pythongit.py | 2,868 | 3.9375 | 4 | import os
dolar = float(58.5)
euro = float(66.8)
def operaciones_dolar():
print('1.DOLAR A PESO11111 2.PESO A DOLAR')
dolar_op = int(input("Ingrese la operacion que desea realizar: "))
if dolar_op == 1:
print('Esta convirtiendo de dolar a peso dominicano')
cantidad = int(input('Ingrese la cantidad que desea convertir: '))
total = float(cantidad*dolar)
print('sus dolares son: {} pesos dominicanos '.format(total) )
print('Desea volver al inicio?')
print ('1.SI 2.NO')
opcion2= int(input('Ingrese la opcion deseada: '))
if opcion2 == 1:
os.system("cls")
run()
elif opcion2 ==2:
exit()
elif dolar_op ==2:
print('Esta convirtiendo de peso dominicano a dolar')
cantidad = int(input('Ingrese la cantidad que desea convertir en guevos sin guevos mmg: '))
total = float(cantidad/dolar)
print('sus pesos son: {} dolares '.format(total) )
print('Desea volver al inicio?')
print ('1.SI 2.NO')
opcion2= int(input('Ingrese la opcion deseada: '))
if opcion2 == 1:
os.system("cls")
run()
elif opcion2 ==2:
exit()
def operaciones_euro():
print('1.EURO A PESO 2.PESO A EURO')
dolar_op = int(input("Ingrese la operacion que desea realizar: "))
if dolar_op == 1:
print('Esta convirtiendo de euro a peso dominicano')
cantidad = int(input('Ingrese la cantidad que desea convertir: '))
total = float(cantidad*euro)
print('sus euros son: {} pesos dominicanos '.format(total) )
print('Desea volver al inicio?')
print ('1.SI 2.NO')
opcion2= int(input('Ingrese la opcion deseada: '))
if opcion2 == 1:
os.system("cls")
run()
elif opcion2 ==2:
exit()
elif dolar_op ==2:
print('Esta convirtiendo de peso dominicano a euros')
cantidad = int(input('Ingrese la cantidad que desea convertir: '))
total = float(cantidad/euro)
print('sus pesos son: {} euros '.format(total) )
print('Desea volver al inicio?')
print ('1.SI 2.NO')
opcion2= int(input('Ingrese la opcion deseada: '))
if opcion2 == 1:
os.system("cls")
run()
elif opcion2 ==2:
exit()
def run():
print("Esta es una calculadora para divisas Hoola linux")
print("1.Operaciones con dolares")
print("2.Operaciones con Euros")
opcion = int(input("Ingresa la opcion: "))
if opcion == 1:
operaciones_dolar()
elif opcion == 2:
operaciones_euro()
elif opcion == 3:
os.system("cls")
run()
if __name__ == "__main__":
run()
|
057d2f1336f7cc460dfdf3ca63e070de0d052e0c | harsh22chauhan/Python-Projects | /basic codes/forloop.py | 383 | 3.90625 | 4 | for i in range(1, 5 ):
for j in range(i):
print(i, end=' ')
print()
print(20*"*")
for letter in 'Python class':
if letter == 'h' or letter == 's':
continue
print ('Current Letter :', letter)
var = 10
print(20*"*")
for d in 'Pythonclass':
if d == 't' or d == 's':
break
print ('Current Letter :', d)
|
6f06c24cc9eecc85ed6ef6c386520cfcab0eed49 | EOppenrieder/HW070172 | /Homework3/Exercise11.py | 272 | 4.1875 | 4 |
def main():
print("This program converts meter per second (ms)")
print ("into kilometers per hour (kmh).")
ms = eval(input("Enter your velocity in meter per second: "))
kmh = 3.6 * ms
print("Your velocity is",kmh,"kilometers per hour.")
main ()
|
c38d281706e1d4169c01d310c9f782edd87a4393 | sambapython/batch46 | /log/app.py | 1,130 | 3.890625 | 4 | import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s-->>%(levelname)s==>%(message)s",
filename="log.txt")
logging.info("program started")
a=raw_input("Enter a value:")
logging.info("Got the a value from the user")
b=raw_input("Enter b value:")
logging.info("Got the b value from the user")
logging.debug("before conversion a=%s,b=%s"%(a,b))
try:
a=float(a)
logging.info("safely converted a")
b=float(b)
logging.info("safely converted b")
logging.debug("after conversion a=%s,b=%s"%(a,b))
res=a/b
logging.info("Result calculation completed")
print "result=%s"%res
logging.debug("result=%s"%res)
except ZeroDivisionError as err:
print "ERROR:%s"%err.message
logging.error("ERROR:%s"%err.message)
print "Enter b value not equal to zero"
logging.error("Enter b value not equal to zero")
except Exception as err:
logging.error("ERROR:%s"%err.message)
print "ERROR:%s"%err.message
logging.error("some error")
print "some error"
print "other statements in program"
print "program ended"
print "main block"
logging.info("COMPLETED!!!") |
b25165259fc4cee754afa12aaa13df9f928f6829 | fernandamarr/python-course | /Section 6: Functions/Function-Practice/paper-doll.py | 323 | 4.1875 | 4 | # PAPER DOLL: Given a string, return a string where for every character in the original there are three characters
# paper_doll('Hello') --> 'HHHeeellllllooo'
# paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'
def paper_doll(text):
result = ''
for elem in text:
result += elem * 3
return result |
3a9004b2924ba8b97882d44d0c4cef3635e49ee6 | acgoularthub/Curso-em-Video-Python | /desafio020.py | 311 | 3.65625 | 4 | from random import shuffle
nome1 = str(input('Insira o nome do primeiro aluno: '))
nome2 = str(input('Insira o nome do segundo aluno: '))
nome3 = str(input('Insira o nome do terceiro aluno: '))
nome4 = str(input('Insira o nome do quarto aluno: '))
lista = [nome1,nome2,nome3,nome4]
shuffle(lista)
print(lista) |
26381263286908defa03dd4c230b25dfc8a68ed3 | Sqvall/codewars | /python/kyu_4/sudoku_solutions_validator.py | 1,046 | 3.515625 | 4 | """ https://www.codewars.com/kata/529bf0e9bdf7657179000008 """
correct = [i for i in range(1, 10)]
def validSolution(board):
swap = [[] for _ in range(9)]
three = [[] for _ in range(9)]
for i in board:
for val in range(9):
swap[val].append(i[val])
for i in range(0, 9, 3):
for j in range(3):
for q in range(3):
three[0 + i].append(board[q + i][j + i])
three[1 + i].append(board[q + i][j + i])
three[2 + i].append(board[q + i][j + i])
for i in range(9):
if set(board[i]) != set(correct) or set(swap[i]) != set(correct) or set(three[i]) != set(correct):
return False
return True
assert validSolution([
[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]
]) == True
|
778b3ed9d06b10c99158889b7079e21e52315dbb | RosanaR2017/PYTHON | /posnegzero.py | 923 | 3.578125 | 4 | import sys
import math
def number(x):
if x==0:
return "Cero"
return "Positivo" if x > 0 else "Negativo"
def main():
try:
list=["4","0","-12","0.0","0","-1"] #input("Please, enter only a list of number separated by a comma.If you enter another key the program will end.\n").split(",")
list2=[]
j=0
for i in range(len(list)):
list2.append(list[i])
j+=1
list2.append(number(float(list[i])))
j+=1
a=1
print("INPUT"+" "+"OUTPUT")
while a <len(list2):
print("{} ".format(list2[a-1]),end="\t")
print("{}".format(list2[a]),end="\n")
a+=2
except ValueError:
sys.exit("Invalid input. Program ends.")
if __name__== "__main__" :
main() |
55ec61458b3eccecd10d90349b9227721b055559 | Senpaistorm/gpasim | /course.py | 434 | 3.71875 | 4 | import Student.py
'''
A class that represents a course specified with a course code.
'''
class Course():
def __init__(self, code):
''' Initialize a new course specified by the course code.
code -> str
'''
self.code = code
def __str__(self):
''' Returns the course code of a course.
return -> str
'''
return self.code |
2b47ebcaee897541babcb17b45b13245bc4cd3fe | marcushvega/pythonLearning | /marcus_scripts/ex18_MV_args.py | 720 | 4.1875 | 4 | #---This import allows us to use module argv from package sys
import sys
#---This script exists to demonstrate use of '*args'
def unknown_vars(args):
print("This script exists to demonstrate use of '*args' as shown below.\n")
print(f"This args list contains {len(sys.argv)} variables.\n-------------------------------------")
#---I need a counter
counter = 0
#---List out all the variables
for arg in args:
print(f"Argument at index {counter} contains value {arg}")
#---Apparently the ++ operator is not an operator in python
counter+=1
#---If I define a function, it might behoove me to actually use it
unknown_vars(sys.argv)
#---I want another line for easier reading
print("\n")
|
829351b0060d1388c1c21a63d7b847e595e21764 | halfak/wikidata_usage_tracking | /multi_wiki_wikidata_usage.py | 4,589 | 3.765625 | 4 | """
For each wiki, calculates Wikidata usage and returns a csv containing its usage
information. Also returns csv with aggregated results across wikis.
Usage:
multi_wiki_wikidata_usage (-h|--help)
multi_wiki_wikidata_usage --results-directory=<directory_path> --naming-scheme=<scheme> --dump-date=<yyyymmdd>
Options:
-h, --help Returns this help message
--results-directory=<directory_path> Directory where results will be
written
--naming-scheme=<scheme> Naming scheme for files in results
directory. Describes objects whose
usage is being calculated E.g.
"item" or "statement".
--dump-date=<yyyymmdd> Date of wbc_entity_usage dump in
yyyymmdd format. E.g. 20170420
"""
import docopt
import wiki_list
import wikidata_object_usage
import csv
# Used to write out which wikis had Wikidata usages
def writeToFileWhichWikisHadUsages(directory, wiki_list, name_of_file_to_create,
description, date):
wikis_file = open(directory + "/" + name_of_file_to_create + "_" + date +
".txt", "w")
wikis_file.write(description + ":\n")
for wiki in wiki_list:
wikis_file.write(wiki + "\n")
wikis_file.close()
# Calculates list of all wikis from MediaWiki API
def calculateListOfWikis():
print("Getting list of wikis from MediaWiki API...", end="")
list_of_wikis = wiki_list.getWikiNamesList()
print("found " + str(len(list_of_wikis)) + " wikis")
return list_of_wikis
# Iterate through list of all wikis and calculate individual and aggregate
# Wikidata usage.
# Writes both individual and aggregate wiki usage to file
def calculateWikidataUsages(list_of_wikis):
wikis_completed_count = 0
wikis_not_processed = []
wikis_successfully_processed = []
wikidata_object_usage.resetWikidataUsageAggregation()
for wiki in list_of_wikis:
print("Getting object usages for " + wiki + "...", end="",flush=True)
wikidata_usages = wikidata_object_usage.getSortedObjectUsagesFromDump(
wiki, dump_date)
if len(wikidata_usages) == 0:
print("\n\tNot Found...", end="", flush=True)
wikis_not_processed.append(wiki)
else:
wikis_successfully_processed.append(wiki)
wikidata_object_usage.addToWikidataUsageAggregation(wikidata_usages)
wikidata_object_usage.writeWikidataUsagesToFile(results_directory,
naming_scheme,
wiki,
wikidata_usages,
dump_date)
wikis_completed_count += 1
print(str(wikis_completed_count) + " wikis completed", flush=True)
# Write aggregated Wikidata usages to file
wikidata_object_usage.writeWikidataUsagesToFile(results_directory,
naming_scheme,
"all_wikis",
wikidata_object_usage.returnWikidataUsageAggregation(),
dump_date)
# Finish by writing to file which wikis successfully processed or not
writeToFileWhichWikisHadUsages(results_directory,
wikis_not_processed,
"wikis_not_processed",
"Wikis not processed",
dump_date)
writeToFileWhichWikisHadUsages(results_directory,
wikis_successfully_processed,
"wikis_successfully_processed",
"Wikis successfully processed",
dump_date)
def main():
args = docopt.docopt(__doc__)
global results_directory
results_directory = args['--results-directory']
global naming_scheme
naming_scheme = args['--naming-scheme']
global dump_date
dump_date = args['--dump-date']
list_of_wikis = calculateListOfWikis()
calculateWikidataUsages(list_of_wikis)
main()
|
558d337a28fe9da7fcae216a6bec02f4ab0770c9 | duxiaobu/data_structure | /20_05_22/判断子序列.py | 512 | 3.546875 | 4 | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
s_point = t_point = 0
s_length = len(s)
t_length = len(t)
while s_point < s_length and t_point < t_length:
if s[s_point] == t[t_point]:
s_point += 1
t_point += 1
else:
t_point += 1
return s_point == s_length
if __name__ == '__main__':
str1 = "ab"
str2 = "adfbdc"
s = Solution()
print(s.isSubsequence(str1, str2))
|
ab135fe8a5e767ede05351d4c9b2c5ec5b28513b | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_200/1457.py | 501 | 3.71875 | 4 | def tidy(num):
num = list(num)
for i in range(len(num) - 1, 0, -1):
if int(num[i]) < int(num[i - 1]):
for j in range(i, len(num)):
num[j] = '9'
num[i] = '9'
num[i - 1] = str(int(num[i - 1]) - 1)
return str(int(''.join(num)))
def main():
nb_test = int(input())
for _ in range(nb_test):
arg = input()
print('Case #' + str(_ + 1) + ': ' + tidy(arg))
if __name__ == '__main__':
main() |
655b236877a07283d99e5adc9bb055e06dc6f149 | velenk/Python | /Python语言程序设计基础/科赫曲线绘制.py | 837 | 3.671875 | 4 | import turtle as t
def main():
num = input_msg()
start()
for i in range(3):
draw(num, 600)
t.right(120)
def input_msg():
while True:
msg = input('The Koch Number:')
if msg:
try:
num = int(msg)
if num > 5:
num = 5
if num < 1:
num = 1
return num
except:
print('Error')
else:
break
def start():
t.setup(1200, 1200, 0, 0)
t.pensize(3)
t.pencolor('blue')
t.speed(100)
t.up()
t.left(90)
t.fd(200)
t.right(90)
t.fd(-500)
t.down()
def draw(a, s):
if a == 0:
t.fd(s)
else:
for angle in [0, 60, -120, 60]:
t.left(angle)
draw(a-1, s/3)
main()
|
e60860cb26fedeb65ece5f631e55c8cf5d5d1240 | JonathanCrt/SIO_Algorithmic_applied | /nb-notes.py | 224 | 3.96875 | 4 |
compte=int(input("Combien de notes ?:"))
lnotes=[]
for i in range (compte):
x=float(input("Note :"))
lnotes.append (x)
print(lnotes)
print ("la moyenne des notes est :" , (lnotes.append(x))/compte)
|
4a8edcefa9e3c44657077f017f35108f13a135ee | Leetcode-101/Leetcode-python | /leetcode/102.二叉树的层序遍历.py | 1,386 | 3.828125 | 4 | #
# @lc app=leetcode.cn id=102 lang=python3
#
# [102] 二叉树的层序遍历
#
# https://leetcode-cn.com/problems/binary-tree-level-order-traversal/description/
#
# algorithms
# Medium (64.15%)
# Likes: 876
# Dislikes: 0
# Total Accepted: 312.6K
# Total Submissions: 487.4K
# Testcase Example: '[3,9,20,null,null,15,7]'
#
# 给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
#
#
#
# 示例:
# 二叉树:[3,9,20,null,null,15,7],
#
#
# 3
# / \
# 9 20
# / \
# 15 7
#
#
# 返回其层序遍历结果:
#
#
# [
# [3],
# [9,20],
# [15,7]
# ]
#
#
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
# 递归法
i = 0
def get_dfs(node, i, res):
if node:
if len(res) <= i:
res.append([node.val])
else:
res[i].append(node.val)
get_dfs(node.left, i+1, res)
get_dfs(node.right, i+1, res)
get_dfs(root, i, res)
return res
# @lc code=end
|
bea135ceb282843867a40760a68748ff581de622 | euzin4/gex003_algprog | /material/respostas_exercicios/lista10/exe2.py | 1,065 | 4 | 4 | N_linha = 5 #VARIÁVEL GLOBAL - Tamanho das linhas da matriz
N_coluna = 4 #VARIÁVEL GLOBAL - Tamanho das colunas da matriz
def soma_matriz(matA, matB):
#Cálculo da matriz matC (matA + matB)
matC = []
for i in range(N_linha):
linha = []
for j in range(N_coluna):
linha.append(matA[i][j] + matB[i][j])
matC.append(linha)
return matC
#Leitura matriz A
A = []
print("----Matriz A----")
for i in range(N_linha):
linha = []
print("Linha", i+1)
for j in range(N_coluna):
n = int(input("Informe um número para a coluna {}: ".format(j+1)))
linha.append(n)
A.append(linha)
#Leitura matriz B
B = []
print("\n----Matriz B----")
for i in range(N_linha):
linha = []
print("Linha", i+1)
for j in range(N_coluna):
n = int(input("Informe um número para a coluna {}: ".format(j+1)))
linha.append(n)
B.append(linha)
#Chama a função para fazer o cálculo da matriz C
C = soma_matriz(A, B)
#Impressão da matriz C
print("\nMatriz C (A + B):")
for i in range(N_linha):
for j in range(N_coluna):
print("{:3}".format(C[i][j]), end=" ")
print()
|
0f69801461bba0583ccf39a81731d2eaa3aef29d | serikisaev/serikisaev | /pytz_task.py | 1,196 | 3.6875 | 4 | import pytz
import datetime
def return_timezones_list():
quantity_timezones = int(input('Сколько нужно временных зон вывести?: '))
count = 0
time_zones_list = []
for country in pytz.country_names:
if count == quantity_timezones:
break
else:
time_zones_list.append((country, (pytz.country_names[country], pytz.country_timezones.get(country))))
count += 1
for i in time_zones_list:
print(i[0], i[1])
return time_zones_list
t = return_timezones_list()
def main():
while True:
code_country = input('\nДля выхода введите "q"\nВведите двухбуквенный код страны: ')
if code_country == 'q':
break
else:
for i in t:
if code_country == i[0]:
time_zone = pytz.timezone(i[1][1][0])
print(f'\nСейчас время в {i[1][0]}: {datetime.datetime.now(tz=time_zone)}')
print(f'Сейчас время в UTC:{datetime.datetime.utcnow()}')
if __name__ == '__main__':
main()
|
33447cab3ae475f55e421e8483c4c1ea9c4a5214 | dirceileen/An-lisis-de-Algoritmos | /BubbleSort.py | 268 | 3.875 | 4 | def BubbleSort(Lista):
for numPasada in range(len(Lista)-1,0,-1):
for i in range(numPasada):
if Lista[i]>Lista[i+1]:
temp = Lista[i]
Lista[i] = Lista[i+1]
Lista[i+1] = temp
return Lista |
273c64f69aebb0b394fd044453b5dbe2c10fa128 | WrathTitan/DLNeuralNetwork | /StructuredModel/relu_backward.py | 477 | 4.15625 | 4 | def relu_backward(dA, cache):
"""
The backward propagation for a single RELU unit.
Arguments:
dA - post-activation gradient, of any shape
cache - 'Z' where we store for computing backward propagation efficiently
Returns:
dZ - Gradient of the cost with respect to Z
"""
Z = cache
# just converting dz to a correct object.
dZ = np.array(dA, copy=True)
# When z <= 0, we should set dz to 0 as well.
dZ[Z <= 0] = 0
return dZ |
8739024db133b3a3bb68d2f99f1ee00c4907f089 | thonrocha/fiap-r | /teste.py | 283 | 3.53125 | 4 | #!/usr/bin/python
import csv
tipos = ['red', 'white', 'vinho']
with open('BaseWine_Red_e_White.csv', 'rw') as f:
data = csv.reader(f, delimiter=';')
for l in data:
if l[13].lower() in tipos:
pass
else:
print('ERROR ######### FUUUU')
|
0e0c9e1567eee7a17b65bba2867063d0252575ab | WBReiner/coding_notebooks_python | /CS/paired_prog_CS.py | 1,204 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 17 17:07:43 2018
@author: whitneyreiner
"""
#make a linked list from scratch
# =============================================================================
# Q1 Implement an algorithm to determine if a string has all unique characters.
# What if you cannot use additional built-in data structures other than
# strings?
#
# =============================================================================
# is everything good in code, read next line in code
#continue means skip code
x = 'insight is lit'
z = []
for i in x:
if x is not :
x= x.strip() #unnecessary
x = 'insight is lit'
z = []
for i in x:
if i not in z:
z.append(i)
else:
continue
if len(x) == len(z):
print('yep')
uni = [i for i in x if i not in x]
#go through one array no need for range or len
# range(len())
if access more than one array and are mushed together and need to maintain index order :
(if you forget str are iterable or you care about the explicit length of the string)
#Doesn't know what the index is if iterating through the string, so if it matters then you need to do range(len())
#permutation- case and space sensitive |
55199b8b1bead4f2e72839012f6254941a01ece1 | szhmery/leetcode | /SortingAndSearching/74-Search2DMatrix.py | 3,002 | 3.765625 | 4 | from typing import List
import bisect
class Solution:
# https://www.bilibili.com/video/BV1aK4y1h7Bb
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
R = len(matrix)
if R == 0:
return False
C = len(matrix[0])
if C == 0:
return False
if matrix[0][0] > target or matrix[R - 1][C - 1] < target:
return False
tmp = []
for i in range(R):
tmp.append(matrix[i][0])
ind = bisect.bisect_left(tmp, target)
if ind == R:
ind = ind - 1
if target < matrix[ind][0]:
ind = ind - 1
ind2 = bisect.bisect_left(matrix[ind], target)
if ind2 == C:
return False
return matrix[ind][ind2] == target
def searchMatrix2(self, matrix: List[List[int]], target: int) -> bool:
R = len(matrix)
if R == 0:
return False
C = len(matrix[0])
if C == 0:
return False
if matrix[0][0] > target or matrix[R - 1][C - 1] < target:
return False
tmp = []
for i in range(R):
tmp.append(matrix[i][0])
left = 0
right = R - 1
while left <= right:
row = (left + right) // 2
if tmp[row] == target:
return True
elif tmp[row] > target:
right = row - 1
else:
left = row + 1
if row == len(tmp):
row = row - 1
if target < matrix[row][0]:
row = row - 1
left = 0
right = C - 1
while left <= right:
mid = (left + right) // 2
if matrix[row][mid] == target:
return True
elif matrix[row][mid] > target:
right = mid - 1
else:
left = mid + 1
return False
def searchMatrix3(self, matrix: List[List[int]], target: int) -> bool:
R = len(matrix)
if R == 0:
return False
C = len(matrix[0])
if C == 0:
return False
if matrix[0][0] > target or matrix[R - 1][C - 1] < target:
return False
l = 0
r = R * C - 1
while l <= r:
mid = l + (r - l) // 2
element = matrix[mid // C][mid % C]
if element == target:
return True
elif element < target:
l = mid + 1
else:
r = mid - 1
return False
if __name__ == "__main__":
solution = Solution()
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
target = 3
result = solution.searchMatrix(matrix, target)
print(result)
result = solution.searchMatrix2(matrix, target)
print(result)
matrix = [[1, 3]]
target = 1
result = solution.searchMatrix3(matrix, target)
print(result)
result = solution.searchMatrix2(matrix, target)
print(result)
|
420d29d9484572fda7353ed7be6eb156bd2d7b96 | darshanjoshi16/GTU-Python-PDS | /lab2_2.py | 798 | 4.15625 | 4 | #Lab Assignment 2.2
#Write a Python program to print the series of prime numbers until the number entered by the user.
#take the input from user
number=int(input("Enter the number: "))
print("-----------------------------------------------------------")
print("The Prime Numbers come before "+str(number)+" are: ")
# here j is running from numbers which are less than the number entered by user
for j in range(2,number):
k=0
# here i is running from 2 to j to see j is divisible by i or not divisible.
for i in range (2,j):
if(j % i == 0):
k=1
# k is determining the status of reminder if it is 1, it is not prime.
if(k != 1):
print(j,end=" ")
print("\n ----------------------------------------------------------")
|
9247b6521b3996b9e53e438ba513f77a16720d0c | tanviredu/python_database_oop_coursera | /Class_and_inheritance/second.py | 553 | 3.953125 | 4 | class Employee:
''' this is the class Description'''
name = "Ben"
designation = "Sales Executive"
salesMadeThisWeek = 6
def hasAchivedTarget(self):
if self.salesMadeThisWeek >=5:
print("Target has been achived")
else:
print("Target is not achived")
#help(Employee) ### this helps to see the description with doc string
employee = Employee() ## creating the object
print(employee.name)
employee.hasAchivedTarget()
employee2 = Employee()
print(employee2.name)
employee2.hasAchivedTarget() |
1081071038cd4ba56e298fdbf21ccab09643c38a | hakver29/project_euler | /python/problem62.py | 465 | 3.671875 | 4 | def main():
cubes = [''.join(sorted(str(i**3))) for i in range(1,10000)]
cubes = sorted(cubes)
yolo = []
for i in range(len(cubes)-3):
if cubes[i] == cubes[i+1] and cubes[i+1] == cubes[i+2] and cubes[i+2] == cubes[i+3] and cubes[i+3] == cubes[i+4]:
yolo.append(cubes[i])
for i in range(1,10000):
x = ''.join(sorted(str(i**3)))
for j in yolo:
if x == j:
return i**3
print(main()) |
e3a45b1403aa4f940753b52790b8aeea8ca8b3e0 | clovery410/mycode | /interview_qa/snapchat/task_sequence.py | 1,511 | 3.59375 | 4 | import collections
class Task(object):
def __init__(self, _id):
self._id = _id
self.deps = set()
class Solution(object):
def taskSequence(self, tasks):
in_degree = collections.defaultdict(list)
out_degree = collections.defaultdict(int)
# build graph
for task in tasks:
for parent_task in task.deps:
in_degree[parent_task].append(task)
out_degree[task] += 1
# do topological sort
order = []
sinks = []
for task in tasks:
if task not in out_degree:
sinks.append(task)
while sinks:
cur_task = sinks.pop()
order.append(cur_task._id)
for parent_task in in_degree[cur_task]:
out_degree[parent_task] -= 1
if out_degree[parent_task] == 0:
sinks.append(parent_task)
# detect cycle
if len(order) < len(tasks):
print "There is Cycle"
return None
return order
if __name__ == "__main__":
task1 = Task(1)
task2 = Task(2)
task3 = Task(3)
task4 = Task(4)
task5 = Task(5)
task2.deps.add(task1)
task2.deps.add(task3)
task3.deps.add(task5)
task4.deps.add(task1)
task4.deps.add(task2)
# task4.deps.add(task5)
task5.deps.add(task4)
tasks = [task1, task2, task3, task4, task5]
sol = Solution()
print sol.taskSequence(tasks)
|
0b68b088eaaf44518d6f0d0c149276997027118b | wentingsu/Su_Wenting_spring2017 | /Final/codePY/Analysis4.py | 3,718 | 3.65625 | 4 |
# coding: utf-8
# # Analysis 4
#
# * analyse the variable
# * from previous analyses we can find out that the happiness scores difference between Western Europe and Central and Eastern Europe is large. In this analysis, let's find out each how variables influence the outcomes.
# In[3]:
import pandas as pd
# from pythainlp.segment import segment
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import math
get_ipython().magic('matplotlib inline')
# In[4]:
# define the function to calculate and create the total score of happiness.
def getTotalScore(str):
# load the data
data = pd.read_csv(str)
# get all the columns that to be added together
colums = data.ix[:,2:]
# add the new column named 'total score'
# data['total score'] = colums.sum(axis = 1).head()
data['total score'] = np.sum(colums,axis = 1)
# return the data frame
return data
# In[5]:
data2015=getTotalScore('data/2015.csv')
data2016=getTotalScore('data/2016.csv')
# In[6]:
#define the function to sort based on total score and add a new column named rank
def getRank(data):
newData = data.sort_values(by='total score',ascending=False)
newData['Rank'] = range(1,len(data) + 1)
newData.index = range(0,len(data))
return newData
# In[7]:
data1 = getRank(data2015)
data2 = getRank(data2016)
# In[9]:
data1.columns
# In[ ]:
# apply the PCA
# In[13]:
from sklearn.preprocessing import StandardScaler
# In[12]:
df = data2015.ix[:,2:-1]
# In[33]:
df.head()
# In[17]:
# standardize the data prior to a PCA,to make sure it was measured on the same scales.
X_std = StandardScaler().fit_transform(df)
# In[29]:
pd.DataFrame(X_std).head()
# In[30]:
mean_vec = np.mean(X_std, axis=0)
cov_mat = (X_std - mean_vec).T.dot((X_std - mean_vec)) / (X_std.shape[0]-1)
# In[25]:
cov_mat = np.cov(X_std.T)
eig_vals, eig_vecs = np.linalg.eig(cov_mat)
# In[34]:
#correlation matrix
f, ax = plt.subplots(figsize=(12, 9))
sns.heatmap(cov_mat, vmax=.8, square=True,linewidths=.5);
plt.savefig('4-2.png')
# In[100]:
# eig_pairs1
# In[40]:
tot = sum(eig_vals)
var_exp = [(i / tot)*100 for i in sorted(eig_vals, reverse=True)]
cum_var_exp = np.cumsum(var_exp)
# In[46]:
with plt.style.context('seaborn-whitegrid'):
plt.figure(figsize=(6, 3))
plt.bar(range(7), var_exp, alpha=0.5, align='center',
label='individual explained variance')
plt.step(range(7), cum_var_exp, where='mid',
label='cumulative explained variance')
plt.ylabel('Explained variance ratio')
plt.xlabel('Principal components')
plt.legend(loc='best')
plt.tight_layout()
# plt.show()
plt.savefig('4-3.png')
# In[48]:
tot = sum(eig_vals)
var_exp = [(i / tot)*100 for i in eig_vals]
cum_var_exp = np.cumsum(var_exp)
# In[49]:
with plt.style.context('seaborn-whitegrid'):
plt.figure(figsize=(6, 3))
plt.bar(range(7), var_exp, alpha=0.5, align='center',
label='individual explained variance')
plt.step(range(7), cum_var_exp, where='mid',
label='cumulative explained variance')
plt.ylabel('Explained variance ratio')
plt.xlabel('Principal components')
plt.legend(loc='best')
plt.tight_layout()
# plt.show()
plt.savefig('4-4.png')
# In[50]:
from sklearn.decomposition import PCA
# In[51]:
X = np.array(X_std)
# In[52]:
pca=PCA(n_components=6)
# In[53]:
pca.fit(X)
# In[54]:
Y = pd.DataFrame(pca.transform(X))
# In[59]:
Y.columns = ['Economy (GDP per Capita)','Family','Health (Life Expectancy)','Trust (Government Corruption)','Generosity','Dystopia Residual']
# In[60]:
Y.head()
# In[89]:
pca.explained_variance_ratio_
# In[ ]:
|
7947634bf956c047137997d2c9cb2c83e2f646a9 | sez07/hangman | /hangman/hangman.py | 2,918 | 4 | 4 | import random
def hangman():
list_of_words=['newyork','chicago','houston','philadelphia','dallas','atlanta','fresno','columbus','indianapolis','portland','miami','orlando','greensboro']
word=random.choice(list_of_words)
turns=10
guessmade=''
valid_entry=set('abcdefghijklmnopqrstuvwxyz')
while len(word)>0:
main_word=""
for letter in word:
if letter in guessmade:
main_word=main_word +letter
else:
main_word=main_word+"*"
if main_word==word:
print(main_word)
print('you wonn!!!')
break
print("guess the words",main_word)
guess=input()
if guess in valid_entry:
guessmade=guessmade+guess
else:
print("enter valid character")
guess=input()
if guess not in word:
turns=turns-1
if turns==9:
print("9 turns left!")
print("----------")
if turns==8:
print("8 turns left")
print("-----------")
if turns==7:
print("7 turns left")
print("-----------")
print(" () ")
print(" ")
if turns==6:
print("6 turns left")
print("------------")
print(" () ")
print(" || ")
if turns==5:
print("5 turns left")
print("------------")
print(" () ")
print(" || ")
if turns==4:
print("4 turns left")
print("------------")
print(" () ")
print(" || ")
print(" /\ ")
if turns==3:
print("3 turns left")
print("------------")
print(" () ")
print(" /||\ ")
print(" /\ ")
if turns==2:
print("2 turns left")
print("------------")
print(" ()_ ")
print(" /||\ ")
print(" /\ ")
if turns==1:
print("1 turn left")
print("------------")
print(" ()_| ")
print(" /||\ ")
print(" /\ ")
if turns==0:
print("u loose the game and man is dead")
print("------------")
print(" ()_|| ")
print(" /||\ ")
print(" /\ ")
break
name=input("ENTER YOUR NAME")
print("Welcome",name,"!")
print("----------")
print("try to guess the american city name in less than 10 attempts")
hangman() |
40110fe47181f8c5c296f5f1b7e4aef1e13e075f | igorbeduin/reinforcement-maze | /mazegen.py | 1,517 | 3.84375 | 4 | # From http://code.activestate.com/recipes/578356-random-maze-generator/
# Modified to use numpy and return maze instead of saving it as an image.
# Random Maze Generator using Depth-first Search
# http://en.wikipedia.org/wiki/Maze_generation_algorithm
# FB - 20121214
import random
import numpy as np
def make_maze(mx, my):
maze = np.zeros((my, mx))
dx = [0, 1, 0, -1]; dy = [-1, 0, 1, 0] # 4 directions to move in the maze
# start the maze from (0, 0)
stack = [(0, 0)]#[(random.randint(0, mx - 1), random.randint(0, my - 1))]
while len(stack) > 0:
(cx, cy) = stack[-1]
maze[cy][cx] = 1
# find a new cell to add
nlst = [] # list of available neighbors
for i in range(4):
nx = cx + dx[i]; ny = cy + dy[i]
if nx >= 0 and nx < mx and ny >= 0 and ny < my:
if maze[ny][nx] == 0:
# of occupied neighbors must be 1
ctr = 0
for j in range(4):
ex = nx + dx[j]; ey = ny + dy[j]
if ex >= 0 and ex < mx and ey >= 0 and ey < my:
if maze[ey][ex] == 1: ctr += 1
if ctr == 1: nlst.append(i)
# if 1 or more neighbors available then randomly select one and move
if len(nlst) > 0:
ir = np.random.choice(nlst)
cx += dx[ir]; cy += dy[ir]
stack.append((cx, cy))
else: stack.pop()
return np.abs(maze.T - 1) # transpose and invert 0s and 1s
if __name__ == '__main__':
print make_maze(10, 10)
|
ec5327bcb6376e6ef5250dd1c531c05f893b926e | zdurczok/hard_way | /ex16_1/test_sorting1.py | 942 | 3.921875 | 4 | import sorting
from random import randint
max_numbers = 30
def random_list(count):
numbers = []
for i in range(count, 0, -1):
numbers.append(randint(0, 10000))
return numbers
def test_bubble_sort():
numbers = random_list(max_numbers)
lista1 = sorted(numbers)
lista2 = sorting.bubble_sort(numbers)
assert lista1 == lista2
def test_merge_sort():
numbers = random_list(max_numbers)
lista1 = sorted(numbers)
lista2 = sorting.merge_sort(numbers)
assert lista1 == lista2
def test_quick_sort():
numbers = random_list(max_numbers)
lista1 = sorted(numbers)
lista2 = sorting.quick_sort(numbers)
assert lista1 == lista2
def test_quickSort_inplace():
numbers = random_list(max_numbers)
lista1 = sorted(numbers)
lista2 = sorting.quickSort_inplace(numbers)
assert lista1 == lista2
test_bubble_sort()
test_merge_sort()
test_quick_sort()
test_quickSort_inplace()
|
eb1da6b45d2a27d5f91c8da43d383d51113dd3f3 | mdLearning/mnist | /src/networkMnist.py | 5,731 | 3.8125 | 4 | '''
Created on Dec 1, 2017
@author: lyf
'''
#-*- coding:utf-8 -*-
class Network(object):
def __init__(self,sizes):
"""
the list '''sizes'''contains the number of neurons in the respective
layers of the network. for example,if the list was [2,3,1] the it would
be a three-layer network,with the first layer containing 2 neurons,the second
layer 3 neurons,and the third layer 1 neuron.the biases and weights for the
network are initialized randomly,using a Gaussian distribution with mean 0,and variance 1.
note that the first layer is assumed to be an input layer,and by convention we won't set any
biases for those neurons,since biases are only ever used in computing the outputs
from later layers.
"""
self.num_layers = len(sizes)
self.sizes = sizes
self.biases = [np.random.randn(y,1) for y in sizes[1:]]
self.weights = [np.random.randn(y,x)
for x,y in zip(sizes[:-1],sizes[1:])]
def feedforwards(self,a):
"""
Return the output of the network if '''a'''is input
"""
for b,w in zip(self.biases,self.weights):
a = sigmoid(np.dot(w,a)+b)
return a
def SGD(self,training_data,epochs,mini_batch_size,eta,test_data=None):
"""
Train the neural network using mini-batch stochastic gradient descent. the
'''training data''' is a list of tuples (x,y) representing the training inputs
and the desired outputs . the other non-optional parameters are self-explanatory
if test data is provided the the network will be evaluated against the test data
after each epoch,and partial progress printed out.this is useful for
tracking progress,but slows things down substantially
"""
if test_data:n_test = len(test_data)
n = len(training_data)
for j in xrange(epochs):
random.shuffle(training_data)
mini_batchs = [
training_data[k:k+mini_batch_size]
for k in xrange(0,n,mini_batch_size)]
for mini_batch in mini_batchs:
self.update_mini_batch(mini_batch,eta)
if test_data:
print "Epoch{0}:{1}/{2}".format(j,self.evaluate(test_data),n_test)
else:
print "Epoch {0} complete".format(j)
def update_mini_batch(self,mini_batch,eta):
"""
Update the network's weight and biases by applying gradient descent using backpropagation
to a single mini batch.the mini_batch is a list of tuples(x,y) and eta is the learning rate
"""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
for x,y in mini_batch:
delta_nabla_b,delta_nabla_w = self.backprop(x,y)
nabla_b = [nb+dnb for nb dnb in zip(nabla_b,delta_nabla_b)]
nabla_w = [nw+dnw for nw dnw in zip(nabla_w,dleta_nabla_w)]
self.weights = [w-(eta/len(mini_batch))*nw
for w,nw in zip(self.weights,nabla_w)]
self.biases = [b-(eta/len(mini_batch))*nb
for b,nb in zip(self.biases,nabla_b)]
def backprop(self,x,y):
"""
Return a tuple(nabla_b,nabla_w) representing the gradient for the cost function
c_x nabla_b and nabla_w are the layer_by_layer lists of numpy arrays,similar to
self.biases and self.weights
"""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
#feedforward
activation = x
activations = [x]
zs = []
for b,w in zip(self.biases,self.weights):
z = np.dot(w,activation)+b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
#backward pass
delta = self.cost_derivative(activation[-1],y)* sigmoid_prime(zs[-1])
nabla_b[-1] = delta
nabla_w[-1] = np.dot(delta,activations[-2].transpose)
"""
Note that the variable l in the loop below is used a little different to the
notation in the Chapter 2 of the book. here l=1 means the last layer of neurons
,l=2 is the second-last layer,and so on.it's a renumbering of the scheme in the book,
used here to take advantage of the fact that Python can use negative indices in lists
"""
for l in xrange(2,self.num_layers):
z = zs[-l]
sp = sigmoid_prime(z)
delta = np.dot(self.weights[-l+1].transpose(),delta)*sp
nabla_b[-l] = delta
nabla_w[-l] = np.dot(delta,activations[-l-1].transpose)
return (nabla_b,nabla_w)
def evaluate(self,test_data):
"""
Return the number of the test inputs for which the neural network
outputs the correct result. NOte that the neural network's output
is assumed to be the index of whichever neuron in the final layer
has the highest activation
"""
test_results = [(np.argmax(self.feedforward(x)),y)
for (x,y) in test_data]
return sum(int(x==y) for (x,y) in test_results)
def cost_derivative(self,output_activations,y):
"""
Return the vector of partial derivative \partial C_x /
\partial a for the output activations
"""
return (output_activations-y)
def sigmoid(z):
"""
The sigmoid function
"""
return 1.0/(1.0+np.exp(-z))
def sigmoid_prime(z):
"""
Derivative of the sigmoid function
"""
return sigmoid(z)*(1-sigmoid(z)) |
b8bc2e13c8c949bb807e1c9b784da2a7aebac1d4 | Thirumurugan-12/Python-programs-11th | /Find the row sum and column sum of all the elements list stored as a nested list..py | 307 | 3.65625 | 4 | l=eval(input("Enter the nested list"))
m=len(l) # no of rows
n=len(l[0]) #no of coloums
for i in range(m):
rs=0
for j in range(n):
rs+=l[i][j]
print("Sum of",i,"row",rs)
for j in range(n):
cs=0
for i in range(m):
cs+=l[i][j]
print("Sum of",j,"col",cs)
|
cc374058fd353742bc0579f26b272f60704350d0 | henrylin2008/Coding_Problems | /DS and Algorithms/recursion.py | 271 | 3.9375 | 4 | # recursion: it needs the base case, and recursive calls on same function of last 2 positions
# Fibonacci Sequence
def get_fib(position):
if position == 0 or position == 1: # base case
return position
return get_fib(position - 1) + get_fib(position - 2)
|
e93df79a583a7808b595f2914693255fd65d66fc | negative0101/Python-OOP | /9.Testing/Lab/2.py | 1,544 | 3.625 | 4 | class Cat:
def __init__(self, name):
self.name = name
self.fed = False
self.sleepy = False
self.size = 0
def eat(self):
if self.fed:
raise Exception("Already fed.")
self.fed = True
self.sleepy = True
self.size += 1
def sleep(self):
if not self.fed:
raise Exception("Cannot sleep while hungry")
self.sleepy = False
import unittest
class TestCase(unittest.TestCase):
def test_cat_if_size_increase_after_eating(self):
cat = Cat('Akira')
cat.eat()
self.assertEqual(1, cat.size)
def test_cat_if_fed_after_eating(self):
cat = Cat('Akira')
cat.eat()
self.assertTrue(cat.fed)
def test_cat_already_fet(self):
cat = Cat('Akira')
self.assertFalse(cat.fed)
cat.eat()
self.assertTrue(cat.fed)
with self.assertRaises(Exception) as ex:
cat.eat()
self.assertEqual("Already fed.", str(ex.exception))
def test_cat_sleep_if_not_fed(self):
cat = Cat('Akira')
self.assertFalse(cat.fed)
with self.assertRaises(Exception) as ex:
cat.sleep()
self.assertEqual("Cannot sleep while hungry", str(ex.exception))
def test_cat_is_not_sleepy_after_sleeping(self):
cat = Cat('Akira')
cat.eat()
cat.sleep()
self.assertFalse(cat.sleepy)
if __name__ == '__main__':
unittest.main()
|
e6e1fa653cc44f8ee78b0707577ba3942b1bdedd | arfu2016/DuReader | /wiki-word2vec/pca.py | 4,294 | 3.6875 | 4 | """
@Project : DuReader
@Module : pca.py
@Author : Deco [deco@cubee.com]
@Created : 5/24/18 1:16 PM
@Desc :
In Depth: Principal Component Analysis
https://jakevdp.github.io/PythonDataScienceHandbook/05.09-principal-component-analysis.html
PCA and proportion of variance explained:
https://stats.stackexchange.com/questions/22569/pca-and-proportion-of-variance-explained
Making sense of principal component analysis, eigenvectors & eigenvalues
https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues
"""
'''
因为用了numpy包,算法的实现非常简单,如果纯粹用C写的话要复杂的多。
首先对向量X进行去中心化
接下来计算向量X的协方差矩阵,自由度可以选择0或者1
然后计算协方差矩阵的特征值和特征向量
选取最大的k个特征值及其特征向量
用X与特征向量相乘
'''
"""
Created on Mon Sep 4 19:58:18 2017
@author: zimuliu
http://blog.jobbole.com/109015/
"""
from sklearn.datasets import load_iris
import numpy as np
from numpy.linalg import eig
import matplotlib.pyplot as plt
from sklearn import decomposition
def pca(X, k):
print('mean used in pca:', X.mean(axis=0))
# Standardize by remove average
X = X - X.mean(axis=0)
# Calculate covariance matrix:
X_cov = np.cov(X.T, ddof=0)
print('Covariance of the data matrix:')
print(X_cov)
# Calculate eigenvalues and eigenvectors of covariance matrix
eigenvalues, eigenvectors = eig(X_cov)
# top k large eigenvectors
klarge_index = eigenvalues.argsort()[-k:][::-1]
k_eigenvectors = eigenvectors[klarge_index]
print('Coordinates of mean after eigenvector transform:',
np.dot(X.mean(axis=0), k_eigenvectors.T))
print('eigenvectors:')
print(k_eigenvectors)
print('Coordinates of eigenvectors after transform:')
print(np.dot(k_eigenvectors, k_eigenvectors.T))
print('Explained variance:', eigenvalues/sum(eigenvalues))
return np.dot(X, k_eigenvectors.T)
def sk_pca(X, k):
"""
PCA can be implemented either by finding the eigenvectors of the covariance
matrix or by applying SVD to the centered data matrix. You don't do both
covariance and SVD. In practice, the SVD approach is preferable because
the computation of covariance matrix amplifies numerical issues associated
with poorly conditioned matrices.
sklearn uses the SVD method, and applies data centering (remove mean) in the
program
https://stackoverflow.com/questions/47476209/why-does-sklearn-decomposition-pca-fit-transformx-no-multiplication-by-x
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/decomposition/pca.py#L432
:param X:
:param k:
:return:
"""
pca2 = decomposition.PCA(n_components=k, svd_solver='full')
# X = X - X.mean(axis=0)
pca2.fit(X)
print('mean used in pca process:', pca2.mean_)
print('Coordinates of mean after transform:',
pca2.transform(np.array([pca2.mean_.tolist()])))
print('components after mean shift:')
print(pca2.components_)
adjust_components = pca2.components_ + pca2.mean_
print('Coordinates of adjusted components after transform:')
print(pca2.transform(adjust_components))
print('Coordinates of eigenvector-like components after transform:')
print(np.dot(pca2.components_, pca2.components_.T))
print('Explained variance:', pca2.explained_variance_ratio_)
X_reduced = pca2.transform(X)
return X_reduced
def cal_scatter(func, X, k):
X_pca = func(X, k)
X_pca = X_pca.tolist()
xy = zip(*X_pca)
return xy
if __name__ == '__main__':
XX = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
print('mean:', XX.mean(axis=0))
print('std:', XX.std(axis=0))
iris = load_iris()
X0 = iris.data
print('Shape of X0:', X0.shape)
k0 = 2
x1y1 = cal_scatter(pca, X0, k0)
x2y2 = cal_scatter(sk_pca, X0, k0)
x1, y1 = x1y1
x2, y2 = x2y2
print('x1y1:', list(zip(x1, y1)))
print('x2y2:', list(zip(x2, y2)))
fig = plt.figure(1)
ax = fig.add_subplot(1, 2, 1)
ax.scatter(x1, y1, color='blue')
ax2 = fig.add_subplot(1, 2, 2)
ax2.scatter(x2, y2, color='red')
plt.show()
|
689775ad2e7d622e93db95c88f9585512aeb1f45 | WeijieH/ProjectEuler | /PythonScripts/Smallest_multiple.py | 747 | 4.125 | 4 | '''
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
'''
from math import log
def smallest_multiple(num):
result = 1
for i in range(2, num + 1):
if not isprime(i):
continue
result *= i ** int(log(num, i))
return result
def isprime(n):
"""Returns True if n is prime."""
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return False
i += w
w = 6 - w
return True
print(smallest_multiple(20))
|
a41697c6cededbf1cfc611cc715b66d922df5739 | nithish-kumar-t/Algorithms-Assignment | /knapsack.py | 810 | 3.734375 | 4 | # Uses python3
import sys
import numpy
def optimal_weight(W, w):
# write your code here
#w.sort()
#w = w[::-1]
result = 0
c1 = W
r1 = len(w)
# the above function initializes a 2D Array of size mXn with Zeroes using Numpy
value = numpy.zeros((r1+1 , c1+1))
for i in range(r1+1):
value[i][0]= 0
for i in range(c1+1):
value[0][i]= 0
for i in range(1,r1+1):
for x in range(1,c1+1):
value[i][x] = value[i-1][x]
if w[i-1]<=x:
val = value[i-1][x-w[i-1]] + w[i-1]
if val > value[i][x]:
value[i][x] = val
return int(value[i][x])
if __name__ == '__main__':
input = sys.stdin.read()
W, n, *w = list(map(int, input.split()))
print(optimal_weight(W, w))
|
4eb5121d7bab76272f0337ae75f8d9c5f00bc99d | mingyue33/python_base | /04-python基础-if、while、for等/3-我和媳妇去银行办业务.py | 278 | 3.6875 | 4 | #1. 询问媳妇是否去银行
a = input("亲爱的,您去银行么? 1:去 2:不去")
#2. 询问自己是否去银行
b = input("自己有时间去银行么? 1:去 2:不去")
#3. 判断是否去银行办事
if a=="1" and b=="1":
print("可以办理业务")
|
038271316634aa2e4b624557a394064f136739bb | Moukthika-sai-satya-karinki/python-programs | /min_3_nums.py | 304 | 4.125 | 4 | #python program for min of three numbers
a=int(input("enter the first number"))
b=int(input("enter the second number"))
c=int(input("enter the third number"))
if(a<b and a<c):
print(a,'a is smallest')
if(b<a and b<c):
print(b,'b is smallest')
else:
print(c,'c is smallest')
|
855eecdd6723c29c3d64a60c33f1847342292e3d | giuper/teaching | /OldClasses/ALGO20/04-Back/Codice/maze.py | 3,188 | 3.71875 | 4 | from back import BackTrack
class Maze(BackTrack):
#does not handle cycles in the maze
MOVES=[[0,0],[-1,0],[0,1],[1,0],[0,-1]]
#moves
#0 --> Dummy move
#1 --> North
#2 --> East
#3 --> South
#4 --> West
## EXIT/FINISH -1
## LIBERO 0
## BLOCCATO 1
## VISITATO 2
## ESAURITO 3
#nr -- numero di righe
#nc -- numero di colonne
def __init__(self,nr,nc,rs,cs):
super().__init__()
self.nr=nr #number of rows
self.nc=nc #number of columns
self.rs=rs #starting row
self.cs=cs #starting col
#intialize grid with all free
self.m=[[0]*nc for x in range(nr)]
self.sol=None
#required by BackTrack
#for this problem a state consists of
#current row --> starting row at the start
#current col --> starting col at the start
#current grid -> the initial grid
def initState(self):
mm=[]
for x in self.m:
mm.append(x.copy())
return [self.rs,self.cs,mm]
#required by BackTrack
def nextAdmMove(self,state,lmove):
[r,c,m]=state
if lmove is None:
lmove=0
for mossa in range(lmove+1,5):
newr=r+self.MOVES[mossa][0]
newc=c+self.MOVES[mossa][1]
if self._isAdmissible(m,newr,newc):
return mossa
return None
#required by BackTrack
def makeMove(self,state,move):
[r,c,m]=state
newr=r+self.MOVES[move][0]
newc=c+self.MOVES[move][1]
return [newr,newc,m]
#required by BackTrack
def setVisited(self,state):
[r,c,m]=state
m[r][c]=2
#required by BackTrack
def isFinal(self,state):
[r,c,m]=state
return m[r][c]==-1
#used by nextAdmMove
def _isAdmissible(self,m,newr,newc,verbose=False):
if (newr<0) or (newr>=self.nr):
return False
if (newc<0) or (newc>=self.nc):
return False
if m[newr][newc]>0:
return False
return True
#used by application
def setFinish(self,rf,cf):
self.m[rf][cf]=-1
def setBlock(self,r,c):
self.m[r][c]=1
def __str__(self):
#if there is no solution yet
#print the instance
#otherwise print the soloution
if self.sol is None:
return(self.stampa(self.m))
else:
#reminder:
#a state consists of current row, current col, grid
#the actual solution is thus found at index 2
return(self.stampa(self.sol[2]))
def stampa(self,mm):
if(self.nc<10):
res=" "
for r in range(self.nc):
res=res+str(r)
res=res+"\n"
else:
res=""
res=res+" +"+"-"*(self.nc)+"+\n"
for r in range(self.nr):
res=res+str(r)+"|"
for c in range(self.nc):
if mm[r][c]==1:
res=res+"#"
if mm[r][c]==0:
res=res+"."
if mm[r][c]==-1:
res=res+"*"
if mm[r][c]==2:
res=res+"*"
res=res+"|\n"
res=res+" +"+"-"*(self.nc)+"+\n"
return res
|
5ce80c6d41c76c48aa0c37267096eb7864a8f746 | SasView/sasmodels | /sasmodels/models/power_law.py | 1,768 | 3.546875 | 4 | #power_law model
#conversion of PowerLawAbsModel.py
#converted by Steve King, Dec 2015
r"""
This model calculates a simple power law with a flat background.
Definition
----------
.. math::
I(q) = \text{scale} \cdot q^{-\text{power}} + \text{background}
Note the minus sign in front of the exponent. The exponent *power*
should therefore be entered as a **positive** number for fitting.
Also note that unlike many other models, *scale* in this model
is NOT explicitly related to a volume fraction. Be careful if
combining this model with other models.
References
----------
None.
Authorship and Verification
----------------------------
* **Author:**
* **Last Modified by:**
* **Last Reviewed by:**
"""
import numpy as np
from numpy import inf, errstate
name = "power_law"
title = "Simple power law with a flat background"
description = """
Evaluates the function
I(q) = scale * q^(-power) + background
NB: enter power as a positive number!
"""
category = "shape-independent"
# ["name", "units", default, [lower, upper], "type", "description"],
parameters = [["power", "", 4.0, [-inf, inf], "", "Power law exponent"]]
# NB: Scale and Background are implicit parameters on every model
def Iq(q, power):
# pylint: disable=missing-docstring
with errstate(divide='ignore'):
result = q**-power
return result
Iq.vectorized = True # Iq accepts an array of q values
def random():
"""Return a random parameter set for the model."""
power = np.random.uniform(1, 6)
pars = dict(
scale=0.1**power*10**np.random.uniform(-4, 2),
power=power,
)
return pars
tests = [
[{'scale': 1.0, 'power': 4.0, 'background' : 0.0},
[0.0106939, 0.469418], [7.64644e+07, 20.5949]],
]
|
731412e1f46d5adc5cc3d2dcc735808f24639757 | piksa13/ChallengingTasks4beginners | /ChallengingTask_level_3/22freq_keys.py | 494 | 4.125 | 4 | freq = {} # frequency of words in text
line = input("Enter you text here: ")
for word in line.split():
word = word.lower()
freq[word] = freq.get(word, 0) + 1 # It checks whether the value for word is already there if not it defaults to 0, only for dicts
words = freq.keys()
numb = freq.values()
# freq.items()
#print(words, numb)
#for i in words:
# print(words[i], numb[i])
#print(freq)
for word in sorted(words):
print(f'The frequency of the word "{word}" is {freq[word]}')
|
98127d8d6a62cf5c9d7bb62cfb5b884679fd5287 | elliotpalmer/plotly-mapping-alpha | /python-plotly-v1/utils/json_helpers.py | 431 | 3.765625 | 4 | def write_json_to_file(json_data, filename, separators=(',',':')):
"""
Write JSON data to a .json file
"""
import json
file = open(filename, 'w')
file.write(json.dumps(json_data,separators=separators))
def read_json_from_file(json_file):
"""
Read to a Python dictionary from a .json file
"""
import json
with open(json_file) as f:
json_data = json.load(f)
return(json_data)
|
9eff0c12da107274c6a9577a2a0c9ad61d7cf58b | Mansurjon1112/FOR-for-sikl-operatoriga-oid-masalalar-40-ta-masala | /For16.py | 462 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
For16. n butun soni va a haqiqiy soni berilgan (n > 0). Bir sikldan foydalanib a ning 1 dan n gacha
bo’lgan barcha darajalarini chiqaruvchi programma tuzilsin.
Created on Thu Jun 24 19:37:20 2021
@author: Mansurjon Kamolov
"""
a = float(input('a = '))
n = int(input('n = '))
kup = 1
if n>0 :
for i in range(1,n+1):
kup*=a
print(a,'ning',i,'- darajasi',kup)
else:
print('n>0 bo\'lishi kerak') |
433db01b27fcdbbe46a3e1a2fb0253e220d414a7 | shasha9/python-scripts | /prime.py | 945 | 4.125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
def isPrime(n):
if n<1 or n>2*(10**9):
return 0
if n == 1:
return 0
if n == 2:
return 1
for i in range(2,n):
if n%i == 0:
return 0
return 1
def isPrime2(n):
if n<1 or n>2*(10**9):
return 0
if n == 1:
return 0
if n%2 == 0:
return n==2
if n%3 == 0:
return n==3
if n%5 == 0:
return n==5
for i in range(7,int(math.sqrt(n))+1):
if n%i == 0:
return 0
return 1
T = input().strip()
if int(T)<1 or int(T)>30:
print("T<1 or T>30")
else:
for i in range(int(T)):
n = input().strip()
flag = isPrime2(int(n))
if flag:
print("Prime")
else:
print("Not prime")
|
2869980770d9406d202f564ea80002612a1928e9 | Ducbx/algorithm-training | /Blue/Session 05 - String/Codeforces_499B.py | 2,824 | 3.71875 | 4 | # Problem from Codeforces
# http://codeforces.com/problemset/problem/499/B
# You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
#
# You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.
#
# You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.
#
# You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
#
# Input
# The first line contains two integers, n and m (1 ≤ n ≤ 3000, 1 ≤ m ≤ 3000) — the number of words in the professor's lecture and the number of words in each of these languages.
#
# The following m lines contain the words. The i-th line contains two strings ai, bi meaning that the word ai belongs to the first language, the word bi belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once.
#
# The next line contains n space-separated strings c1, c2, ..., cn — the text of the lecture. It is guaranteed that each of the strings ci belongs to the set of strings {a1, a2, ... am}.
#
# All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.
#
# Output
# Output exactly n words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input.
#
# Examples
# input
# 4 3
# codeforces codesecrof
# contest round
# letter message
# codeforces contest letter contest
# output
# codeforces round letter round
# input
# 5 3
# joll wuqrd
# euzf un
# hbnyiyc rsoqqveh
# hbnyiyc joll joll euzf joll
# output
# hbnyiyc joll joll un joll
def get_shorter(ci, _a, _b):
_i = 0
while ci != _a[_i]:
_i += 1
return _a[_i] if len(_a[_i]) <= len(_b[_i]) else _b[_i]
n, m = map(int, input().split())
a = []
b = []
for i in range(m):
ai, bi = input().split()
a.append(ai)
b.append(bi)
c = input().split()
result = []
for i in range(n):
result.append(get_shorter(c[i], a, b))
print(*result, sep=' ')
|
605b81f7461216c5b301fddb2c7b535aed7279f3 | saradaprasad/py | /py_basics_problems/list_min_max_number.py | 178 | 3.625 | 4 | def find_min_num():
print("min")
def find_max_num():
print("max")
if __name__ == "__main__":
lst=[10,20,30,40,50,60,70,80,90]
find_min_num()
find_max_num()
|
739ce04a04600eb695086898c0de5c5a376b389c | amitsaha/notes | /articles/data_python_c/listings_py/mut.py | 553 | 3.71875 | 4 | #!/usr/bin/env python
# mutable data types: dictionary, list.
from __future__ import print_function
dict()
print('dict: {0}'.format(id(dict())))
list()
print('list: {0}'.format(id(list())))
def func():
d = dict()
print('dict: {0}'.format(id(d)))
l = list()
print('list: {0}'.format(id(l)))
class A:
def __init__(self):
self.d = dict()
self.l = list()
print('dict: {0}'.format(id(self.d)))
print('list: {0}'.format(id(self.l)))
if __name__=='__main__':
func()
a = A()
b = A()
|
d78b16caaaf6a9da56b4d0a4c7c79662bf894037 | yzl232/code_training_leet_code | /Decode Ways.py | 1,464 | 3.796875 | 4 | '''
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
'''
class Solution:
# @param s, a string
# @return an integer
def numDecodings(self, s):
if not s or s[0] == '0' : return 0
ppre = pre= 1
for i in range(1, len(s)):
ppre, pre = pre, (pre if s[i]!="0" else 0) + (ppre if '10' <= s[i-1]+s[i] <= '26' else 0)
return pre
'''
class Solution:
# @param s, a string
# @return an integer
def numDecodings(self, s):
if not s or s[0]=='0': return 0
self.d={"":1}
return self.dfs(s)
def dfs(self, s):
if s not in self.d:
self.d[s] = (0 if s[0]=="0" else self.dfs(s[1:])) + (0 if not (len(s)>=2 and '10'<=s[:2]<='26') else self.dfs(s[2:]))
return self.d[s]
class Solution:
# @param s, a string
# @return an integer
def numDecodings(self, s):
n = len(s)
if n==0 or s[0] == '0' : return 0
dp = [0 for i in range(n+1)]
dp[0] = 1; dp[1] = 1
for i in range(2, n+1):
if s[i-1] != '0': dp[i]+=dp[i-1]
if '10' <= s[i-2:i] <= '26': dp[i]+=dp[i-2]
return dp[-1]
''' |
a9007ae3bd8000654120a7fadcbfa766d4259a2f | Kriti231999/Looping.py | /Positive .py | 835 | 3.984375 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> Org_list = input("Enter list:"):
SyntaxError: invalid syntax
>>> Org_list = int (input("enter list:"))
enter list:-3,2,1,4,-5
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
Org_list = int (input("enter list:"))
ValueError: invalid literal for int() with base 10: '-3,2,1,4,-5'
>>> List = [12,-7,,5,64,,-14]
SyntaxError: invalid syntax
>>> List = [12,-7,5,64,-14]
>>> for num in List:
if num >= 0:
print(num, end = "")
12564
>>>
>>> List = [12,-7,5,,64,-14]
SyntaxError: invalid syntax
>>> List = [12,-7,5,64,-14]
>>> for num in List:
if num >= 0:
print(num, end = " ")
12 5 64
>>> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.