blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
23501bb1a4a17f52bb910242ab107c815c569b54 | lucifer612/ICT | /python/calendar.py | 180 | 4.15625 | 4 | # program to print calendar of given month and year
import calendar as cl
year=int(input("enter year: "))
month=int(input("enter month :"))
print(cl.month(year,month))
|
a4189a8fc068f397646bf6383d711a9939b2efd8 | Tomxp32/Python-proyects | /red.py | 3,089 | 3.625 | 4 | # This is red is named by berserk, it'll be the program that will make's me a better human
ruta = 'C:/Users/usuario/Desktop/Primer semestre/Introduccion a la programacion C/Proyectos/Materias a python/prueba_red.txt'
carl_sagan = 'C:/Users/usuario/Desktop/Primer semestre/Introduccion a la programacion C/Proyectos/Mate... |
dc9fd2bce543366b0a1f196397aeb8ba82c80bea | Tomxp32/Python-proyects | /math_main/clases/Clase1_logica.py | 1,502 | 4.5 | 4 | # CLase 1 Logica
logica = '''
La lógica es la ciencia formal y rama tanto de la filosofía como de las matemáticas que
estudia los principios de la demostración y la inferencia válida, las falacias, las
paradojas y la noción de verdad.
La lógica matemática es la rama más matemática de la lógica, que estudia ... |
2fa70d4d35deca77455806296d4b0504a6bb0aca | tsx3000/Screenshot-to-Code | /Data Structure and Algorithm/剑指offer代码/45. 扑克牌的顺子/IsContinuous.py | 961 | 3.65625 | 4 | class Solution:
def IsContinuous(self, numbers):
if numbers == None or len(numbers) < 5:
return False
numbers.sort()
zero_count = numbers.count(0)
if zero_count == 4:
return True
if zero_count > 0:
numbers = list(filter(lambda x: x != 0... |
5820ff745489b29b8d0b1d0c26ca47f52b6cffb4 | pavitrakumar78/Python-Custom-Digit-Recognition | /digit_recog.py | 6,172 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 21 14:38:53 2015
@author: Pavitrakumar
"""
import numpy as np
# from scipy.misc.pilutil import imresize
from needed import imresize
import cv2
from skimage.feature import hog
import sys
# sys arg 1
# TRAIN_DATA_IMG = 'digits.png'
# sys arg 2
# USER_IMG = 'test_image.p... |
42824782aa41b0775ab49cb23a40d23db147c5f1 | Jacob-Bankston/DigitalCrafts-Assignments | /Week1/Week1-Thursday-Assignments/list-exercises.py | 2,509 | 3.765625 | 4 | #Sum the Numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 87, 66, 3]
numbers2 = [22, 45, 13, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
total_sum_numbers = 0
for number in numbers:
total_sum_numbers += number
print(total_sum_numbers)
#Largest Number
largest_number = -100000000
for numbe... |
fe065712a5b6500d9b9a8dc88ce1b7910a3990a6 | Jacob-Bankston/DigitalCrafts-Assignments | /Week1/Week1-Tuesday-Assignments/add-two-numbers.py | 876 | 4.34375 | 4 | #Defining a function to add two numbers together from user input
def add_numbers(input_1, input_2):
total = input_1 + input_2
return print(f"Your two numbers added together are: {total}")
#Seeking user input for the add_numbers function
while 1:
try: #Checking for integer input on the first number's input
... |
b6f280ea94e85cc3d83e471ca74b5a841de7eeb0 | xuedong/google-contests | /Code Jam 2019/Qualification Round/Cryptopangrams/cryptopangrams.py | 4,061 | 3.640625 | 4 | import sys, string
def write_output(t, result):
print ('Case #%s: %s' % (t, result))
sys.stdout.flush()
def encrypt(sourceText, dictionary):
sourceList = list(sourceText)
encryptDictionary = {value: key for key, value in dictionary.items()}
primeList = [encryptDictionary[i] for i in sourceList]
... |
f6c95b85a709095b6294aa9f42ca52f781cdcf8b | MaksimDgn/test | /test.py | 485 | 3.703125 | 4 | #!/usr/bin/env python
from sys import argv
#print("test string\n")
list = [2, "smail", 5, 1, 3, 4, 2, 1, 55]
a=0
str = "test strng !"
def f(ar):
dub=[]
for i in list:
if (i == ar):
dub.append(list.index(i))
print(" {} - {} YES".format(i, dub[a]))
else:
... |
86234f3a44fde7732dec8aadb39d07155b09aaa0 | FelixSchool/jatin | /basics 3-2.py | 716 | 3.828125 | 4 | name = 'jatin'
vowel = 'aeiou'
for val in name:
if val == 'a':
print(val)
index = name.index(val)
print(index)
print('---------')
break
elif val == 'e':
print(val)
index = name.index(val)
print(index)
print('---------')
break
e... |
75602dd6eb5fc7a61bdbee545a31ed2c81ecf2eb | DevenderSarda/CS5590_Python-MachineLearning | /Lab 2/Source/task_2.py | 1,052 | 3.9375 | 4 | n = int(input("No. of contacts to be added to list: "))
contacts_list = []
contact_dictionary = {}
for i in range(n) :
contact_dictionary["name"] = input("Enter name ")
contact_dictionary["number"] = input("Enter number ")
contact_dictionary["email"] = input("Enter email ")
contacts_list.append(contact_... |
890613e529c33ecc0411ade2c6a67fbffe70cf55 | DanielleKoduru/Python-Brain-Teasers | /roman_numerals_CHI.py | 988 | 3.53125 | 4 |
class Solution(object):
def romanToInt(self,s):
dict = {
'I':1,
'V':5,
'X':10,
'L':50,
'C':100,
'D':500,
'M':1000,
'IV':4,
'IX':9,
'XL':40,
'XC':90,
'CD':400,
... |
6d8136d93fc16687e1899462d7b2481c20a8308a | Shahabgeravesh/Airbnb | /KMeans[1].py | 5,365 | 3.59375 | 4 | """
Husna Sayedi
Code for CS-235 Final Project
"""
# Full K-Means Algorithm
'''
This function will take in a 2-dim pandas DataFrame and run a K-Means Algorithm on it.
Inputs required are: DataFrame, number of iterations (after convergence KMeans will give same solution),
and the number of clusters (K). K often requi... |
bff9e6911ee84b2424d298daa4ded0fd29e417f7 | acrane1995/projects | /Module 1/absolute beginners.py | 2,855 | 4.15625 | 4 | #my_num = 123
#num_intro = "My number is " + str(my_num)
#print(num_intro)
#total_cost = 3 + 45
#print(total_cost)
#45 was represented as a string and therefore could not be executed
#school_num = 123
#print("the street number of Central School is " + str(school_num))
#school_num is an int and needed to be converted... |
3ad5a0f43f12fd7695e8687f9af527074625efe9 | amita-srivastava/ML-with-Python-Learning- | /StackList.py | 267 | 3.859375 | 4 | stack = []
for i in range(0,10):
stack.append(i)
print(f'Stack after adding {i+1} element: {stack}')
num = int(input('Enter number between 1 and 9 :'))
for j in range(0,num):
stack.pop()
print(f'Stack after removing {j+1} element: {stack}')
|
b36975217050a1e3a8af54e7e7a4d1d0e7ae3e1a | divyansh1235/Beta-Algo | /python/tree/PostorderTraversal.py | 2,087 | 4.375 | 4 | #POSTORDER BINARY TREE TRAVERSAL
# In this algorithm we print the value of the nodes present in the binary tree in postorder
# fashion.
# Here we first traverse the left subtree and then traverse the right subtree and finally we
# print the root
# The sequence is as follows -
# Left->Right->Root
class node (): ... |
e059107f0c4653e1c649eef428b943f1e2f9179c | MillerPr/MillerPr.github.io | /google2.py | 1,103 | 3.5625 | 4 | def getParentIndex(h, q):
## determine top node value
topNode = 2**h - 1
if topNode < q:
return -1
else:
nodeOffsetValue = 0
continueBoolean = True
totalNodesInSubtree = topNode
p = -1
while continueBoolean: #check for truthiness
if totalNode... |
deff5c75f34c59da73ca911301b3022eba1cfdcb | jasonluocesc/CS_E3190 | /P2/majority_element/majority_element.py | 1,006 | 4 | 4 | from element import Element
from solution import find_majority_element
import sys
def read_data_from_file(filename):
"""Read problem instance from file. No error handling!
Parameters
----------
filename : str
Returns
-------
elements : list of Elements in the order they exist in the ... |
41c9233b4165f4da13629a007e24dfbc248cff9d | jasonluocesc/CS_E3190 | /P4/shortest_cycle/solution.py | 1,791 | 4.34375 | 4 | # coding: utf-8
def get_length_of_shortest_cycle(g):
"""Find the length of the shortest cycle in the graph if a cycle exists.
To run doctests:
python -m doctest -v solution.py
>>> from networkx import Graph
>>> get_length_of_shortest_cycle(Graph({1: [2, 3], 2: [], 3: []}))
>>> get_length_o... |
8022b13d67965944c47908321fa2061722dbff14 | jasonluocesc/CS_E3190 | /P6/fuel_stations/fuel_stations.py | 1,310 | 3.796875 | 4 | # coding: utf-8
from solution import find_optimal_locations
import sys
def read_data_from_file(filename):
"""Read problem instance from file. No error handling!
Parameters
----------
filename : str
Returns
-------
num_locations : int
Number of locations
min_distance : int... |
59b7f10a36fdca9b68f1a52952a29fdf05dbae56 | mushari44/Hangman | /hangman.py | 5,053 | 3.9375 | 4 |
import random
from words import words
from hangman_visual import lives_visual_dict
import string
while True:
def get_valid_word(words):
word = random.choice(words) # randomly chooses something from the list
while '-' in word or ' ' in word:
word = random.choice(words)
... |
2f27f0933cb141d1bc26f2d24337b292f2d6595d | nishkachotai/tic-tac-toe | /main.py | 6,338 | 3.5 | 4 | import math
import time
class TreeNode:
def __init__(self, board_frame, player):
self.board_frame = board_frame
self.player = player
self.score = 0
self.children = []
self.best_child = None
def add_child(self, child):
self.children.append(child)
def print... |
84accc62c2408c4b1c5333d3cbc9792e10890909 | MiGray/School21 | /py/plot/plot4.py | 384 | 3.90625 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 50)
y1 = x
y2 = [i**2 for i in x]
plt.figure(figsize=(9, 9))
plt.subplot(2, 1, 1)
plt.plot(x, y1)
plt.title("Зависимости: y1=x, y=x^2")
plt.ylabel("y1", fontsize=14)
plt.grid()
plt.subplot(2, 1, 2)
plt.plot(x, y2)
plt.xlabel("x", fontsize=14)... |
f2b60b77dcbe4978be489d3cf56732eebe078f6a | bellcliff/leetcode | /binary-tree-level-order-traversal-ii.py | 738 | 3.890625 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def levelOrderBottom(self, root):
vals = {}
self... |
508888371639dadb65af209340a9c7aaf4be39b3 | anish29292/BigDataProgramming | /exercise1.py | 408 | 3.921875 | 4 | def lcs(str1, str2):
if not str1 or not str2:
return ""
a, s1, b, s2 = str1[0], str1[1:], str2[0], str2[1:]
if a == b:
return a + lcs(s1, s2)
else:
return max(lcs(str1, s2), lcs(s1, str2), key=len)
test_text1 = input ("Enter string 1: ")
test_text2 = input ("Enter stri... |
80c6d5f22f25b3eb24cde76774c2ab8d6298c923 | ahayworth/python_awair | /examples/remote.py | 1,001 | 3.6875 | 4 | """Remote sensors example."""
import os
import asyncio
import aiohttp
from python_awair import Awair
async def fetch_data():
"""Fetch remote data."""
async with aiohttp.ClientSession() as session:
# Instantiate a client with your access token, and an asyncio session:
token = os.environ.get("A... |
54465311c05ec6a408c465e2713d390b000cd308 | kingtub/PythonHello | /statement/while_break_else.py | 294 | 4.03125 | 4 |
while True:
c = input('A char:')
if c == 'o':
# 有一点需要尤其注意,如果你 中断 了一个 for 或 while 循环,任何相应循环中的 else
# 块都将不会被执行。
break
print('you enter ', c)
else:
print('The while loop is over.') |
c4d4e6ed57c64442bf4d8a7222d5d6bf22dc5a76 | emilylakic/hack-bu | /guiwithpython/demo.py | 1,744 | 3.5 | 4 | import tkinter as tk
class App(tk.Frame):
def __init__(self, parent = None):
super().__init__(parent)
parent.geometry('500x500')
self.pack()
self.add_label()
self.add_button()
self.add_slider()
def add_counter(self):
self.counter = tk.Label(self, text ='... |
aca7b1cf5d55a62b67f6156c9b633b7bc811e1ab | hansrajdeshpande18/geeksforgeeksorg-repo | /printreverse.py | 206 | 4.28125 | 4 | #Print first and last name in reverse order with a space between them
firstname = (input("Enter your first name:"))
lastname = (input("Enter your last name:"))
print("Hello " +lastname + " " +firstname) |
60cf83e30e3c0f969cb5577fa04d4cc799851ad5 | hansrajdeshpande18/geeksforgeeksorg-repo | /inputfunction-060321.py | 171 | 3.890625 | 4 |
#python program to illustrate
#getting input from user
name = input("Enter your name:")
#user enter the name ''
print("Hello",name , "You are looking beautiful")
|
f56a8011894ba37ab5f9799bca632c513cdecdea | shiki7/Atcoder | /ARC035/A.py | 152 | 3.828125 | 4 | S = input()
for i in range(len(S) // 2):
if not (S[i] == S[-1-i] or S[i] == "*" or S[-1-i] == "*"):
print('NO')
exit()
print('YES')
|
15a35248faa38de93290f409d188b45e244c6a74 | shiki7/Atcoder | /ABC216/A.py | 133 | 3.671875 | 4 | S = input()
x, y = S.split('.')
if 0 <= int(y) <= 2:
print(x + '-')
elif 3 <= int(y) <= 6:
print(x)
else:
print(x + '+')
|
074b817cba9795dc8cd6b032f3ce5ae3fc5de557 | shiki7/Atcoder | /cf17-final/A.py | 262 | 3.5625 | 4 | s = input()
t = 'AKIHABARA'
if len(s) > len(t):
print('NO')
exit()
s += (len(t) - len(s)) * '#'
j = 0
for i in range(len(t)):
if s[j] == t[i]:
j += 1
elif not (s[j] != 'A' and t[i] == 'A'):
print('NO')
exit()
print('YES')
|
e5a1dece964da1b6749166af86daba8cc134b831 | shiki7/Atcoder | /ABC111/B.py | 99 | 3.53125 | 4 | N = input()
x = N[0] * 3
if int(N) <= int(x):
print(x)
else:
print(str(int(N[0]) + 1) * 3)
|
eb38c5c29615ad953405651264e73026f8c6d235 | shiki7/Atcoder | /ABC101/B.py | 117 | 3.578125 | 4 | N = input()
total = 0
for w in N:
total += int(w)
if int(N) % total == 0:
print('Yes')
else:
print('No')
|
5eaedb69ef76d195af48000b1e9782d49c754cb4 | shiki7/Atcoder | /ABC157/D.py | 1,426 | 3.546875 | 4 | from collections import defaultdict
def find_root(x):
if parent[x] == x:
return x
else:
return find_root(parent[x])
def unite(x, y):
x = find_root(x)
y = find_root(y)
if x != y:
if rank[x] < rank[y]:
parent[x] = y
size[y] += size[x]
else:
... |
5192d6a76918b832769ede715fca3228de53b2b5 | shiki7/Atcoder | /ABC018/A.py | 215 | 3.609375 | 4 | a = int(input())
b = int(input())
c = int(input())
sorted_list = sorted([a, b, c], reverse=True)
for x in [a, b, c]:
for i in range(3):
if x == sorted_list[i]:
print(i + 1)
break
|
92cc3d1b5d115119c4109fbb7bde51df5851e7ea | shiki7/Atcoder | /ABC068/A.py | 129 | 3.5 | 4 | n = input()
len_n = len(n)
ans = "ABC" + n
if len_n == 1:
ans = "ABC00" + n
elif len_n == 2:
ans = "ABC0" + n
print(ans)
|
f76c6f070133f20e64f8e5e187a3a514711b0d66 | shiki7/Atcoder | /ABC216/C.py | 158 | 3.578125 | 4 | N = int(input())
ans = ""
while N > 0:
if N % 2 == 0:
ans = "B" + ans
N //= 2
else:
ans = "A" + ans
N -= 1
print(ans)
|
b182de3cc505003cf479c7d573e8f545de0facfd | shiki7/Atcoder | /ABC011/C.py | 420 | 3.734375 | 4 | n = int(input())
ng = [int(input()) for _ in range(3)]
### スタート時にngになっている場合を忘れがち
if n > 300 or n in ng:
print('NO')
exit()
for _ in range(100):
if n - 3 not in ng:
n -= 3
elif n - 2 not in ng:
n -= 2
elif n - 1 not in ng:
n -= 1
else:
print('NO')
exit()
... |
63da80f93496f9f06ca03c36ca38b215fd4ab8d9 | shiki7/Atcoder | /ABC106/B.py | 284 | 3.796875 | 4 | N = int(input())
def is_divisor_counter8(num):
count = 0
for i in range(1, num+1):
if num % i == 0:
count += 1
return True if count == 8 else False
count = 0
for i in range(1, N+1, 2):
if is_divisor_counter8(i):
count += 1
print(count)
|
715cd0ebee402b916dbd6390173a79fdbff45b77 | shiki7/Atcoder | /ABC150/B.py | 89 | 3.546875 | 4 | import re
n = int(input())
s = input()
result = re.findall('ABC', s)
print(len(result))
|
e67ff41a5f646101bc2ff185623787e374838cfe | shiki7/Atcoder | /pakencamp-2019-day3/B.py | 157 | 3.609375 | 4 | N = int(input())
cnt = 0
for _ in range(N):
s = input()
if s == 'white':
cnt += 1
if cnt > N//2:
print('white')
else:
print('black')
|
79ce7866d551a33b5f272be6766bfd9173966401 | Muthushunmugam/Tkinter | /Bill.py | 2,119 | 3.6875 | 4 | from tkinter import *
a = Tk()
Label(a, text="FRUITS SHOP").grid(row=0, column=1)
Label(a, text="PRICE:").grid(row=1, column=0)
Label(a, text="Apple - rs.35").grid(row=2, column=1)
Label(a, text="Orange - rs.20").grid(row=3, column=1)
Label(a, text="Pome - rs.50").grid(row=4, column=1)
Label(a, text="Lemon - rs.5")... |
839102579223d22c81a0f54a816f585f7c70262e | skrall3119/prg105 | /MyProject/Practice 9.1.py | 2,704 | 4.5625 | 5 | import pickle
def add(dic): # adds a new entry to the dictionary
name = input('Enter the name you wish to add: ')
email = input('Enter the email you wish to associate with this name: ')
dic[name] = email
print(dictionary)
def remove(dic): # removes the entry of the dictionary
na... |
19eb0c737e0807bf63622407c922d6fd20cf7a6d | eliasantoniorodrigues1/python_intermediario | /agrupando_elementos_com_dicionario_itertools.py | 1,310 | 4.03125 | 4 | """
Agrupando elementos em dicionário em Python
"""
from itertools import groupby
alunos = [
{'nome': 'Luiz', 'nota': 'A'},
{'nome': 'Elias', 'nota': 'A'},
{'nome': 'Camila', 'nota': 'B'},
{'nome': 'Ferreira', 'nota': 'C'},
{'nome': 'Lucas', 'nota': 'D'},
{'nome': 'Reginal', 'nota': 'B'},
{'... |
8efaf531e170a9ff4b1acec318d5ab14a57d3516 | eliasantoniorodrigues1/python_intermediario | /exercicio_resolucao.py | 1,352 | 4.0625 | 4 | """
01 - Crie uma função que encontra o primeiro duplicado considerando o segundo número como a duplicação.
Retorne a duplicação considerada.
Requisitos: A ordem do número duplicado é considerada a partir da segunda ocorrência do número,
ou seja, o número duplicado em si.
Exemplo:
[1, 2, 3, 3, 2, 1] -> 1, 2 e 3 são su... |
cb631a0f8690722a598cf4da210cbcdc1448beb1 | eliasantoniorodrigues1/python_intermediario | /funcoes.py | 312 | 3.828125 | 4 | """
Funções - def em Python
"""
# def saudacao(msg='Olá', nome='usuári'):
# print(msg, nome)
#
#
# saudacao('Olá mundo!')
# saudacao('Bom dia!')
# saudacao('E aí....')
def saudacao(msg='Olá', nome='usuári'):
print(msg, nome)
return f'{msg} {nome}'
variavel = saudacao()
print(variavel)
|
e316f1202a3bfa9a08d68273ed8373e2d0bef1b6 | slawektestowy/selenium | /python/lista.py | 686 | 4.0625 | 4 | lista = ["Bartek", "Tomek", "Basia", 1, 2, 3, 4 ]
print(lista[2])
for i in lista:
print(i)
print(lista[0:4])
print(lista.index("Tomek")) # miejsce na ktorym znajduje sie dany element listy
lista.append("Jedynka") # dodanie elementu na koncu listy
lista.insert(0, "nova") # dodanie elementu na konkretnym miejscu... |
4f9a88f561aa540cd61424d9640ee637e9091193 | xuwenping/doubleLinkList | /python/exe15.py | 351 | 4.0625 | 4 | #! /usr/bin/env python
# -*- coding: utf8 -*-
from sys import argv
script, filename = argv
print "the script is: ", script
txt = open(filename)
print "Here is your file %r:" % filename
print txt.read()
txt.close()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_... |
be935f6e973460fea6f2d71b6002f48df3434615 | DilyanYankow/Python-Excercises-2 | /quiz game.py | 1,953 | 3.921875 | 4 | questions = {
"Who created Python? ": "A",
"What year was Python created? ": "B",
"Python is tributed in which comedy group? ": "C",
"What is the best anime in the world rn?": "D"
}
options = [ ["A. Guido van Rossum", "B. Elon Musk", "C. Bill Gates", "D. Mark Zuckerburg"],
["A. 1989", "B. 1... |
a4b55e94244227ef003bdb3c40f9ab3d6f1218b4 | RahulRao23/tic-tac-toe | /program.py | 13,177 | 3.890625 | 4 | from tkinter import *
root = Tk()
root.geometry('900x900')
# frame for the game board
frame = LabelFrame(root, borderwidth=4, bg='#EA7773')
frame.grid(row=1, column=1,padx=20, pady=20, sticky=N)
# frame for the options
frame_options = LabelFrame(root, borderwidth=4, bg='#EA7773')
frame_options.grid(row=1, column=2,p... |
86be0c3c789110fe4f3164edfaeab4381a0bc6d1 | endercrest/qHacks-Hacks | /translatedToEnglish.py | 7,974 | 3.546875 | 4 | import re
from helpers.functions import functiontoenglish
def mapToEnglish(lom):
sentence = []
i = 0
while(i<len(lom)):
print(lom[i]['Type'],(i,lom[i]['Value'], len(lom)))
if lom[i]['Type'] == 'function':
sentence.append(functiontoenglish(lom[i]['Value']))
elif lom[i][... |
62be566195d032878f71c739425cfb3032985633 | Shahzeb98/Learning-algorithms | /Fork Python/Module 3/copy-the-end.py | 995 | 4.09375 | 4 | """
You are given a string str of length >=2. You need to extract the last 2 characters and print a new string that has the extracted characters 3 times concatenated.
Input Format:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains a string str.
Output Form... |
0d7f489bb18c6357e4e22fc88fa8d577fa70fdd2 | Shahzeb98/Learning-algorithms | /Fork Python/Module 5/unlucky-number.py | 1,379 | 3.859375 | 4 | """
You are given a list. Print the sum of the list numbers. If the list is empty then 0 gets printed. Also, the element 7 and the element next to it won't contribute to the sum.
Input Format:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains one line of in... |
882876f6a9788f15d0fbcc6d9dd83f5c70adfb3c | mikronixx/public | /my_linux_academy/my_python_class/exercise5.py | 195 | 3.703125 | 4 | #!/usr/bin/env python
import math
import os
digits = os.getenv("DIGITS") or "10"
my_float = math.pi
digits =int(digits)
print("%.*f" % (digits, my_float))
#else:
# print("%.*f" % (10, my_float))
|
e5edd00c88abfdbc1c6fd7b1d8664669be67c04b | farhat-jahan/storyGenerator | /buildstory.py | 770 | 3.640625 | 4 | import random
def create_story(books):
pass
books_title = ['Mother', ' Midnight Children', ' My experiments with truth']
where_places = [' greeen land', ' Neuschwanstein-Castle', ' Schwangau',' Cappadocia', ' Tunnel of Love']
when = [' A few years ago', 'Yesterday', ' Last night', ' A long time ago','on may 28t... |
6016471fe575c70b9aa69eaa0e5c801c254feacf | carpedm20/emoji | /tests/test_analyze.py | 4,997 | 3.5 | 4 | """Unittests for emoji.analyze()"""
import emoji
def test_analyze():
assert list(emoji.analyze('')) == []
assert list(emoji.analyze('', non_emoji=True)) == []
assert list(emoji.analyze('abc')) == []
assert list(emoji.analyze('abc', non_emoji=True)) == [('a', 'a'), ('b', 'b'), ('c', 'c')]
res... |
3fa9d55e95802a2bf82599646ee026b04d479535 | LaxmanMaharjan/Python | /venv/Codes/Magic_methods/__call__l.py | 183 | 3.5625 | 4 | """
The method named __call__ is called when the instance is called as function
"""
class nepa:
def __call__(self, *args, **kwargs):
print("hello world!")
N = nepa()
N() |
8611ef35c047b7362cb965eb1d07c713cf327d3e | LaxmanMaharjan/Python | /venv/Codes/Polymorphism/Operator_Overloading.py | 1,060 | 4.15625 | 4 | """
The purpose of these so-called “magic methods” is to overload Python operators or built-in
methods.
"""
class Polynomial:
def __init__(self,*args):
self.coeffs = args
def __add__(self, other): #overloading +
return Polynomial(*(x+y for x,y in zip(self.coeffs,other.coeffs)))
def __sub_... |
0b5158d64593672378993949ca7a4d308bb6091d | LaxmanMaharjan/Python | /venv/Codes/Exception Handling/2.multiple_except.py | 241 | 3.890625 | 4 | try:
x = int(input("Enter first Number:"))
y = int(input("Enter second number:"))
print(x/y)
except ZeroDivisionError as msg:
print("can't divide by zero")
except ValueError as msg:
print("Please provide integer value.")
|
b9cfc4cbcfe17fa307a7e2d63f109231cedd759b | LaxmanMaharjan/Python | /venv/Codes/object_serialization/pickle_module.py | 947 | 4 | 4 | """
Object serialization is done to convert python object to the form that could be saved in the file
or that could be used to send python object when requested by other app like javascript app,andriod app etc.
"""
import pickle
class Employee:
def __init__(self,id,name,salary):
self.id = id
self.na... |
698b19ae7303261114a85e8c8b84c4a996b175ec | LaxmanMaharjan/Python | /venv/Codes/Decorator.py | 1,186 | 4.0625 | 4 | """
Higher order Function
It takes a funtion as argument and returns function
"""
"""
Example 1
Closure property in python
"""
from time import time
user ={
'username':'laxman',
'password':123
}
def user_info(function):
def test(username):
if user['username'] == username:
return functi... |
129bdf93e67bd9a4f05ee037695c8b03ef770228 | LaxmanMaharjan/Python | /venv/Codes/Decorators/storing_args.py | 1,523 | 3.53125 | 4 | import functools
import pickle
# store ={}
#
# def add1(*args):
# if args in store:
# print("Returning from stored value.")
# return store[args]
# else:
# result = 0
# for i in args:
# result+=i
# store[args]= result
# print("Returning by calc... |
ce3a8502b50857b1768f7e4435d114b107602361 | todun/Dictionaryy | /archive/dictionaryy.py | 4,947 | 4.25 | 4 | """Dictionaryy: an app that makes a personal dictionary,
which you can study like flashcards
Dictionary's Data Structure:
{word1: {PartOfSpeech1: [def1, def2, ...], PartOfSpeech2: [def1, def2, ...]},
word2: {PartOfSpeech1: [def1, def2, ...], PartOfSpeech2: [def1, def2, ...]},
...}
"""
import pandas as pd
from rand... |
ce21b252f8f481309e06ddae439f47833b4b0f3c | norski824/pyapi | /sort01/sorted02.py | 341 | 3.984375 | 4 | new_list=[]
for data in open("sort.txt"):
new_list.append(data.strip())
print("This is our list", new_list)
print()
print("This is our list sorted with the sorted function:", sorted(new_list))
print()
print()
sortedlist=sorted(new_list)
print()
print("Another sorted list:" + str(sortedlist))
... |
76c13c36638d419c3079a5650f2c286d4e56a249 | dhananjayharel/mark_trego_python_beginners | /employee_object_attributes/employee.py | 484 | 3.578125 | 4 | class Employee:
'Base class for our Employees'
def __init__(self):
self.first_name = 'Jaddian'
self.last_name = 'Forte'
self.uid = '855'
def get_first_name(self):
return self.first_name
def get_last_name(self):
return self.last_name
def get_uid(self):
return self.uid
def main():
employee_01 =... |
cda52b77dbb776170b86622411d38ffb8d7bcf74 | kooi/prog-extended | /flyingturtle.py | 973 | 3.640625 | 4 | import turtle
class FlyingTurtle(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("turtle")
self.vy = 0
self.vx = 5
self.ay = -1
self.bottom = -200
self.right = 200
self.left = -200
self.move()
def move(self):
... |
d8ca1f9146fa6dad6de66701e10e45f054f37c39 | dgervais19/Eng74_Python | /dictionaries.py | 1,694 | 4.65625 | 5 | # What is a dictionary
# Dictionary (arrays) is another way managing data more Dynamically
# Key value pairs to store and manage data
# Syntax : {"name": "James"}
# a = {"key": "value"}
# what type of data can store/manage
# Let's create one
devops_student_data = {
"key": "value",
"name": "james",
"stream"... |
0ddda0b6e0daa457a0aec083114fad5ae0404d81 | ramani30/ab3.py | /ab3.py | 147 | 3.921875 | 4 | i =input("input the letter of the alphabet():")
if i is('a','e','i','o','u'):
print("%s is a Vowel" % i)
else:
print("%s is a Constant" % i)
|
86dd0843dff368fec2b7f361e5700ad0a7d88728 | bhawnabhatt2012/python_lab_exp | /operator_overloading.py | 390 | 3.53125 | 4 | class Complex:
def __init__(self):
self.real = 0
self.imag = 0
def setValue(self, real, imag):
self.real = real
self.imag = imag
def display(self):
print("(", self.real, " + ", self.imag, "i)")
C1 = Complex()
C1.setValue(1,2)
C2 = C... |
8d8a4983bc39fb8c6870cb7e7f275b43d160baea | bhawnabhatt2012/python_lab_exp | /2.b.py | 497 | 4.21875 | 4 | index = 0
string = input("Enter the string: ")
substring = input("Enter the substring: ")
if substring in string:
print(substring," is present in ",string)
while index < len(string):
index = string.find(substring, index)
if index == -1:
break
print(substring, ' found... |
9b7412472c6c515a8e0e3df2fdde185408c680fd | bhawnabhatt2012/python_lab_exp | /3.a.py | 1,391 | 4.09375 | 4 | class Time:
hour=0
minute=0
seconds=0
def input_values(self):
self.hour=int(input("ENTER HR"))
self.minute=int(input("ENTER MINU"))
self.seconds=int(input("ENTER SECONDS"))
return
def print_details(self,V1):
print("YOUR RESULT:%d:%d:%d" %(V1.hour,V1.... |
4e86a5e22554caaeb1d27ae7accd47d5f88b6358 | dipalpatel77/mypythonpractice | /odoo/que1.py | 348 | 3.78125 | 4 | '''Write a program which will find all such numbers which are divisible by 7 but
are not a multiple of 5, between 1000 and 2100 (both included). The numbers obtained
should be printed in a comma-separated sequence on a single line.'''
x = []
for i in range(1000,2101):
if i % 7 == 0 and i % 10 != 5:
x.append(i)
... |
3f1607ec740ef097b081d72c2d7a96fd8071889e | dipalpatel77/mypythonpractice | /classfull.py | 908 | 3.65625 | 4 | __author__ = 'DIPAL'
class demoforadditoin:
x = 388
_y = 3298
def __init__(self):
print
"called:", type(self)
pass
def addition(self, a, b):
print
"sum=", a + b
self.a = 10
self.b = 22
print
self.a + self.b
... |
33db590223d22b8d0ff0fa65d02609a09d7d8841 | dipalpatel77/mypythonpractice | /odoo/question2.py | 377 | 3.859375 | 4 | # a = []
# for i in range(1,input()+1):
# a[i:1]=[i,i*i]
# print a
# a = []
# for i in range(1,input()+1):
# a.append(i)
# a.append(i*i)
#for i in range(len(a)):
# print {a[i*2] : a [i*2+1] for i in range(0,len(a)/2) }
# print a
# d = {}
# for i in range(0,input()):
# d.insert(i,i**i)
d = {}
for i in range(1,input(... |
7d3e6b74bd3481348813d1bc1248e1c68e3715af | dipalpatel77/mypythonpractice | /challh3.py | 164 | 3.609375 | 4 | n = [0]
temp = 0
a = int(input("enter the value of a"))
for i in range(a):
n.append(int(input()))
temp += n[i]
##############
print(temp, sum(n))
|
64a464478af36b0152b498013587a2873fd0a4b0 | dipalpatel77/mypythonpractice | /odoo/function1.py | 216 | 3.578125 | 4 | import time
start_time = time.time()
n = input()
a = 0
for i in range(0, n):
a = a + float(i) / float(i + 1)
print(a)
if __name__ == '__main__':
print("--- %s seconds ---" % (time.time() - start_time))
|
3fa8b90e2411d4cad96b6a337f7643b59b256869 | dipalpatel77/mypythonpractice | /practical2.py | 861 | 3.546875 | 4 | def decrypt(msg,key,l):
print key
for i in(x):
if ord(i)>=97 and ord(i)<= 122:
if ord(i)-key <97:
p=chr(122-ord(i)+97-key)
l.append(p)
else:
#print 'its here'
p=chr(ord(i)-key)
... |
9c75600751a8e547b0929814569ec5aeaa1249f3 | chandan61308/RandomPasswordGenerator | /generator/random_password_creator.py | 1,533 | 3.78125 | 4 | import string
import random
class Password:
def __init__(self, charset, length):
# charset is string,length is string length
self.charset = charset
self.length = length
self.char_array = []
self.password = []
def set_the_charset(self):
# for cha... |
c82e47c2f9b9c8a326477d4dad34865a86397fdc | hipoudah/Transformers-for-NLP | /utils.py | 882 | 3.5 | 4 | import math
d_model = 512
def positional_encoding(pos, pe):
for i in range(0, 512, 2):
pe[0][i] = math.sin(pos / (1000 ** (2 * i / d_model)))
pe[0][i + 1] = math.cos(pos / (1000 ** (2 * i / d_model)))
return pe
def encode_word(pos, pe, y, pc):
"""
This function will add the pos... |
73ca3925410932bb18b86b3026b8def4ff65fb52 | Denis8967167/FirstProject | /309.py | 207 | 3.828125 | 4 | def election(x, y, z):
if a != b and a != c:
return b
if b != a and b != c:
return a
if c != a and c != b:
return a
a = 1
b = 0
c = 1
res = election(a, b, c)
print(res)
|
edc8eefa43d0a05859412b8ca21107af71e8237c | lanaelsanyoura/CommentedPythonIntermediateWorkshop | /Person.py | 1,226 | 4.25 | 4 | from datetime import date, datetime #for date
class Person:
"""
A person class
==== Attributes ====
firstname: str
lastname: str
birthdate: date YEAR, MONTH, DAY
address: str
"""
def __init__(self): #, firstname, lastname, birthdate, address):
#self.firstname = firstname
... |
e770484a845c2eec43d4c943f933bfa509633939 | Estevam2302/Calculadora-de-aluguel-de-carros | /Script.py | 1,136 | 3.71875 | 4 | print('Calculo de aluguel de veículo')
print('Categorias')
print('Cupê = 1')
print('Crossover = 2')
print('Esportivo = 3')
print('Hatch = 4')
print('Jipe = 5')
print('Picape = 6')
print('Sedan = 7')
print('SUV = 8')
categoria = int(input('Digite o número correspondente a categoria: '))
if categoria == 1:
valor = 1... |
a46b41591e6b604279d3bad60964c3dae3ccd61e | PSonline5/homework_beetroot | /hmw_10.py | 1,249 | 4 | 4 | # Write a class structure that implements a library. Classes:
# 1) Library - name, books = [], authors = []
# 2) Book - name, year, author (author must be an instance of Author class)
# 3) Author - name, country, birthday, books = []
# Library class
# Methods:
# - new_book(name: str, year: int, author: Author) - retur... |
0abd9e4b7b5e2874f2c14b1291c0c7ad6c8f9f2e | newnakashima/cardcase | /readTable.py | 1,361 | 3.65625 | 4 | import sys
import os.path
import random
class ReadTable:
"""
鍵を元にしてテーブルから文字を読み取る
"""
table_list = []
def read(self):
file = open(os.path.abspath('./stored/table'))
for line in file:
self.table_list.append(line)
def convert(self, key):
if len(key) % 2 != 0:
... |
a5350443f6562e1c91fa903a9552e645488cc20e | SB-BISS/RLACOSarsaLambda | /static_heuristics/EuclideanHeuristic.py | 843 | 3.96875 | 4 | import numpy as np
import sys
import scipy
'''
@author Stefano Bromuri
It selects the state that has the minimum distance from the goal.
Static Heuristic for Maze environments
'''
class EuclideanHeuristic(object):
def __init__(self,goal=None, model=None, actions_number=0):
self.goa... |
c731295f1450fe41271681af1cd3b58efceb0633 | nguyenvinhtriet/-CheckIO-0x02-HOME | /【02】Even the Last.py | 1,138 | 3.890625 | 4 | # =====================================
# --*-- coding: utf-8 --*--
# @Author : trietnv
# @Date : 2020-04-23
# @CSDN :
# @FileName: 【02】Even the Last.py
# =====================================
def checkio(array: list) -> int:
"""
sums even-indexes elements and multiply at the last
"""
i = 0
... |
463567be1f3109f02cf075f508e335fc11646637 | pinvolha/python | /hw3.py | 2,057 | 3.5625 | 4 | # variant 5
class Customer:
bill = 0
def __init__(self, id0, name0, surname0, partonim0, card0, count0):
self.__id = id0
self.name = name0
self.surname = surname0
self.patronim = partonim0
self.__card = card0
self.count = count0
print("Hello,... |
d7d2317e855d0bec1a74a0a2946f04392ef7e149 | lemonhu/lintcode | /binary_search/search_in_rotated_sorted_array.py | 943 | 3.890625 | 4 | """Search in Rotated Sorted Array
https://www.lintcode.com/problem/search-in-rotated-sorted-array/description
"""
class Solution:
"""
@param A: an integer rotated sorted array
@param target: an integer to be searched
@return: an integer
"""
def search(self, A, target):
# write your code... |
4bba6f39300ac74dcfa05bb57fd0d826f8f448a0 | lemonhu/lintcode | /array/longest_consecutive_sequence.py | 584 | 3.71875 | 4 | """Longest Consecutive Sequence
https://www.lintcode.com/problem/longest-consecutive-sequence/description
"""
class Solution:
"""
@param num: A list of integers
@return: An integer
"""
def longestConsecutive(self, num):
# write your code here
num.sort()
res = 1
cnt =... |
13c0b258a492922a560d61c522efd7d6217fc045 | michaelkemp2000/vader | /ex20.py | 1,186 | 4.375 | 4 | from sys import argv
# Pass in an argument from command line
script, input_file = argv
# Function to print the whole file
def print_all(f):
print f.read()
# Function to go the the begining of a file
def rewind(f):
f.seek(0)
#Function to print a line of the file that you pass in
def print_a_line(line_count, f):
p... |
d6edafab430c4d6585a2edc62ca1336901199f95 | michaelkemp2000/vader | /ex3.py | 1,104 | 4.375 | 4 | # Print the text
print "I will now count my chickens."
# Print test and the sum answer after the comma
print "Hens", 25.645 + 30.5943 / 6
# Print test and the sum answer after the comma
print "Roosters", 100 - 25 * 3 % 4
# Print the text
print "Now I will count the eggs."
# Prints the answer to the sum. Not sure w... |
01b9e6aefae36b15c25ddfa19a255b74da8ac3ed | michaelkemp2000/vader | /ex39.py | 1,861 | 4.0625 | 4 | #Create a mapping of states
states = {
'Oregan': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
#create a basic set of states an some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
#add some more cities
cities['NY'] = 'New York'
cities... |
c5574893325415132b53c9357b0f34f3d5f8cfb2 | michaelkemp2000/vader | /dict.py | 788 | 4.09375 | 4 | my_dict = {
"Name": "Michael",
"Age": 39,
"Height": 6.0
}
print my_dict.items()
print my_dict.keys()
print my_dict.values()
for key in my_dict:
print key, my_dict[key]
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print evens_to_50
even_squares = [x**2 for x in ... |
1c3323bfa80e567995cf755fd6b928fbe14dfed2 | robert-fekete/AdventOfCode2016 | /5/main.py | 943 | 3.5625 | 4 | from md5 import md5
def solve_first(input_string):
index = 0
result = ""
while len(result) < 8:
hasher = md5(input_string + str(index))
hash = hasher.hexdigest()
if hash[:5] == "00000":
result += hash[5]
index += 1
return result
d... |
210c5757a96f915bfdcba3d80cda9a7dddae74c1 | miguelgaspar24/BoardgamePrices | /utilities.py | 728 | 4.65625 | 5 | #!/usr/bin/env python
# coding: utf-8
def convert_chars(string):
'''
Converts problematic characters. Usually, tend to be accented vowels.
Takes the following parameters:
string (str): a string where one or more characters raise a UnicodeEncodeError.
Returns a modified string.
'''
... |
71eca0bfe16eb700afb7dc2b38bea1977e7ab911 | oliverxudd/pytorch-gist | /numpy_basics.py | 1,398 | 4.1875 | 4 | """basics of numpy"""
# 1. deep copy of numpy arrays
B = numpy.empty_like(A)
B[:] = A
# 2. rearrange axes for numpy array
np.transpose(A, axes=[2,0,1])
A.transpose(2,0,1)
# 3. set elements to 0 if element meet some condition
out = np.where(A<3, A, 0) # 将矩阵A中小于3的元素置为0
# 4. show nonzero elements of numpy array
A = np... |
e7ad385b81ce98f0c9e2d211d2a215354eb60381 | Shawn91/Algorithms | /图/Floyd_Warshall.py | 1,153 | 3.765625 | 4 | """输入:directed, weighted graph
字典 dist: 记录任意两个 vertices 之间的距离
字典 pred: 记录任意两个 vertices 之间的最短路径上,key 的上一个 vertex 是什么
"""
from math import inf
from graph import Vertex, Graph
def floyd_warshall(g):
# 初始化
dist = {v:{u:inf for u in g.getVertices()} for v in g.getVertices()}
pred = {v:None for v in g.getVertice... |
08bd821019e9f03fef6dc8789ed0c949826062aa | grumbledore96/RandomStuff | /Accountant.py | 448 | 3.921875 | 4 | originalMoney = 107.80
birthdayMoney = 390.00
userInput = " "
while (userInput) != "stop":
userInput = input("o for original, b for birthday")
while userInput == "o":
userInput = input("How much to take away from original money")
originalMoney-=float(userInput)
while userInput =="b":
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.