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 |
|---|---|---|---|---|---|---|
d3f03f00a5287051a9523c3e8b770475f355606f | igorkoury/cev-phyton-exercicios-parte-2 | /Aula20 – Funções (Parte 1)/ex096 – Função que calcula área.py | 470 | 4.28125 | 4 | '''Exercício Python 096: Faça um programa que tenha uma função chamada área(),
que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno.'''
def area(larg, comp):
a = larg * comp
print(f'A área de um terreno de {l} x {c} = {a}m²')
# Progrma principal
print('... |
90a24dc01a2530eac818646aa3b8c36eebcd27b6 | Patrrickk/aprendendo_python | /ex044.py | 1,043 | 3.984375 | 4 | valor = float(input('Volor a ser pago: '))
print("""
[1] À vista dinheiro/cheque: 10% de desconto
[2] À vista no cartão: 5% de desconto
[3] Em até 2x no cartão sem juros
[4] 3x ou mais no cartão: 20% de juros""")
opcao = int(input('Escolha uma opção para pagamento: '))
if opcao == 1:
desconto = valor - (valor * 10 ... |
1381c6f94e6e88edcc43430eb8b09e1825925a3e | vandanagarg/practice_python | /learning_python/hacker_rank/problem14.py | 1,966 | 4.0625 | 4 | ''' Min cost to get the projects completed?
** Note: If any project has no bids, return -1
Example:
numProjects = 3 projects.
projectId = [2, 0, 1, 2]
bid - [8, 7, 6, 9]
• projectId[i] is aligned with bid[i]
• The first web developer bid 8 currency units for project 2
• The second web developer bid 7 currency units fo... |
5ef97f9079314a7989719f322648b139d3b30561 | PaulinaGuerrero/Mision_02 | /clase.py | 439 | 3.84375 | 4 | # Autor: paulina guerrero Ruiz A01024519
# Calcular porcentajes
print("Cantidad de mujeres inscritas")
m = int(input("Teclea el numero de mujeres inscritas: "))
print("Cantidad de hombres inscritos")
h = int(input("Teclea el numero de hombres inscritos: "))
t = (m+h)
m1 = (m/t)*100
h1 = (h/t)*100
pri... |
7fc0078db10739781956851dbcfb69edfc2fdf0a | RevansChen/online-judge | /Codewars/7kyu/find-the-next-perfect-square/Python/solution1.py | 123 | 3.5625 | 4 | # Python - 2.7.6
def find_next_square(sq):
num = int(sq ** 0.5)
return (num + 1) ** 2 if (num ** 2) == sq else -1
|
d5b965430705876843d63c823c812fcb97c486e5 | postiffm/usfmtools | /charmap.py | 1,132 | 3.53125 | 4 | #!/usr/bin/python3
import os
import re
import sys
import io
# Matt Postiff, 2020
# Take one or more text files and build a character map from it
# Usage: python3 charmap.py learn.txt
script = sys.argv.pop(0)
if len(sys.argv) < 1:
print(f"Usage: {script} file [file ...]\n")
exit(1)
charDict = {}
def charma... |
82ec9291da70de221fd92620027ab54aa2891e2a | telecode-paris/concours-plateforme | /subjects/Mediane/solve.py | 360 | 3.625 | 4 |
# simplement un tri baquet pour trouver la médiane
def mediane():
N = int(input())
numbers = [0 for _ in range(10001)]
for _ in range(N):
numbers[int(input())] += 1
acc = 0
for i, e in enumerate(numbers):
acc += e
if acc > N / 2:
print(i)
return
if... |
d7c74b39b292878b4b4bf1afe030b8f406cc5872 | KCCTdensan/ProCon2017-Solver | /Search/Figure.py | 656 | 3.5 | 4 | class Figure:
_vertexes: list # 頂点を格納したリスト :: [(int, int)]
_angles: list # 角度を格納したリスト :: [float]
def __init__(self, vertexes: list):
if len(vertexes) < 3:
raise FigureError("二次元図形には頂点が最低3つあるはずなんだよなぁ...")
self._vertexes = vertexes
def new(vertexes: list):
return Figure(vertexes)
def getVertexes(self) -... |
d8c6a762f5b45f4703f58ae8be41390378b1447e | PedroCapa/SDLE | /Trabalho/RandomGraph.py | 2,834 | 3.578125 | 4 | import networkx as nx
import Node
from random import randrange
from enum import Enum
class Types(Enum):
"""
Type of aggregation functions
"""
SUM = 0
AVERAGE = 1
COUNT = 2
class RandomGraph:
"""
Class used to generate a graph with random connections
between the nodes until it's a... |
0b413fb9194572435f51b8b3ae5fa90f8c529668 | tanyavasilkova/lesson3 | /old_dz/dz4.vasilkova.py | 10,052 | 3.59375 | 4 | data_users = {}
log_pass = {}
def main():
print('Выберите действие:\n\
1. Зарегистрироваться\n\
2. Войти')
deistvie = str(input('Введите 1 либо 2: '))
if deistvie == '1': loginpassword();
elif deistvie == '2': autint()
elif deistvie != '1' or deistvie != '2':
print('В... |
547d496f47e4e975ce5fd82d5f23443b534a936b | MikeCalabro/euler-everywhere | /Py-Solutions/Problem-27-2.py | 826 | 3.8125 | 4 | # Looked at the forum for the template for this answer
# Modified it to my typical format
def isPrime(num):
if num < 2:
return False
elif num ==2:
return True
else:
return sum([i for i in range(1, int(num**0.5) + 1) if num % i == 0]) == 1
def prime_counter(a, b):
n = 0
while True:
if... |
771ac8e31a9fead113a89e987980f08a4b3ffd4c | tb0700372/special-Python | /Demo/test_0001.py | 964 | 4.0625 | 4 | # 小易喜欢的单词具有以下特性:
#
# 1.单词每个字母都是大写字母
# 2.单词没有连续相等的字母
# 3.单词没有形如“xyxy”(这里的x,y指的都是字母,并且可以相同)这样的子序列,子序列可能不连续。
#
# 例如:
# 小易不喜欢"ABBA",因为这里有两个连续的'B'
# 小易不喜欢"THETXH",因为这里包含子序列"THTH"
# 小易不喜欢"ABACADA",因为这里包含子序列"AAAA"
# 小易喜欢"A","ABA"和"ABCBA"这些单词
#
# 给你一个单词,你要回答小易是否会喜欢这个单词
import re
if __name__ == "__main__":
# 正则
re... |
fec082441c46ff7d67cc0dd4df8c35bb45447e5f | jeyendhran/pythonLTT | /src/assessment_3.py | 681 | 3.8125 | 4 |
INVALID_NEXT_IP = '255.255.255.255'
def nextip(ipaddr):
'''To find next possible IP address available'''
# if the input IP is max IP then no addr other that it
if ipaddr == INVALID_NEXT_IP:
return "No more IP address available"
ip = ipaddr.split(".")
# convert the string list to int list
... |
1e2953ae5ca9a1fb08f637baca6e2164ac99d09f | jasonaibrahim/AcademicWorks | /Hog/hog.py | 19,014 | 3.921875 | 4 | """The Game of Hog"""
from math import *
from dice import four_sided_dice, six_sided_dice, make_test_dice
from ucb import main, trace, log_current_line, interact
goal = 100 # The goal of Hog is to score 100 points.
commentary = False # Whether to display commentary for every roll.
# Taking turns
def roll_d... |
e88eabdc52b8e1ead5e42fa45cd47afa049bf6b7 | AnenaVictoriaSims/DataMiningLab1 | /kmean.py | 1,345 | 3.515625 | 4 | #Anena Sims 1001138287
#Lab 1
import numpy as np
import matplotlib.pyplot as plt
import random
import math
#Randomly generate 2 sets of Gaussian data containing 500 samples using given parameters
def genGauss2D(mean, cov, numSamples):
x, y = np.random.multivariate_normal(me... |
b4461b175e2bdd16c2f620ff1c69f5a71fc4d439 | aminelfc96/Anagram-Finder | /anagram_finder.py | 881 | 3.890625 | 4 | mon_dict = input("entrer l'emplacement du fichier : ")
if len(mon_dict) == 0:
mon_dict = './dico-fr.txt' # Juste pour cet exercice
else:
pass
mot_pour_chercher_anagramme = input("entrer le mot pour chercher l'anagramme : ")
__mot_pour_chercher_anagramme__ = list(mot_pour_chercher_anagramme.lower())
__mot_pour_c... |
225353f8a44e9ee41926c52b3e2280d0359266bf | tobyzhu/genesis-backend | /learnpython.py | 139 | 3.53125 | 4 | import math
testlist=[1,2,3,4,5,6,7,'abd','hadsa']
for i in testlist:
print(i)
testlist[2] = 'asdfa'
for i in testlist:
print(i) |
3cb05e8256254b55415a6ac8df7228797fd5998b | varshakabadi/GitDemo | /slicebackwards.py | 117 | 3.65625 | 4 | Letters= "abcdefghijklmnopqrstuvwxyz"
backward=Letters[25::-1]
print(backward)
backward=Letters[::-1]
print(backward) |
65b5e38ccd05c00f0ec700ad986342db417880d6 | vpalat/1073iOSExample | /Hardway/GameExample/21BlackJack.py | 1,328 | 3.515625 | 4 | import Deck
import Hand
cards = Deck.Deck()
def showHands():
print "Dealer's Hand:"
dealer.showHand()
print "\nPlayer's Hand:"
player.showHand()
def findWinner(player, dealer):
ptotal = player.total()
dtotal = dealer.total()
print "Player: ", ptotal
print "Dealer: ", dtotal
if pto... |
4e1c103337326d20a162044c028ede8f3f9fbae5 | Esty-Hirshman/pokemon-project | /ex_2.py | 409 | 3.6875 | 4 | from config import connection
def find_by_type(type):
"""
returns all of the pokemon names with given type
"""
with connection.cursor() as cursor:
query = "SELECT name FROM pokemon WHERE type = %s"
cursor.execute(query,type)
result = cursor.fetchall()
return [pokemon["na... |
b95f3d00dba68e1113e6697bdbe5286c228510e7 | ngthnam/Python | /Python Basics/19_Reading_CSV.py | 332 | 3.984375 | 4 | import csv
with open('.\samplefiles\example.csv') as csvfile: # 'With' is used to take care of two simultaneous process, Open() and Close()
readcsv = csv.reader(csvfile,delimiter=',')
fruit = input('Enter a fruit to get its color: ')
for row in readcsv:
if row[0]==fruit:
print(row[... |
c8c3415de3c38ebc2281996afa28313faa6055ee | subsid/sandbox | /algos/sliding_window/non_repeat_substring.py | 872 | 4.15625 | 4 | # Given a string, find the length of the longest substring, which has no repeating characters.
def non_repeat_substring(input_str):
curr_chars = set()
window_start = 0
longest = 0
curr_len = 0
for j in range(len(input_str)):
c = input_str[j]
if c not in curr_chars:
curr... |
6cdb3949f6efdef6ef6da2df022f5e39284abe7d | za3k/short-programs | /quiz | 754 | 3.796875 | 4 | #!/bin/python3
"""
Usage: quiz FILE.csv
Interactively prompt the user to fill out a questionnaire. Reads the questions and writes the results to a CSV.
Intended use is for daily, weekly, etc logging of something.
"""
import csv, io, readline, subprocess, sys
if __name__ == '__main__':
if len(sys.argv) != 2:
... |
072414f6608077fd6c5c0aa6bcda1b90357bfdb6 | florlema222/python-random-quote | /listatp.py | 2,421 | 4.15625 | 4 | '''
Cree una lista con los siguientes elementos:
conex=[ "127.0.0.1","root","123456","nomina"]
a) Escriba un programa que imprima todos los elementos de la lista y la longitud total de la lista
conex
b) Escriba un programa que imprima los elementos ordenados de la lista. (presentación
c) cree otra lista con los elem... |
c276065914aef65b69a3dd699a3c68433c997d61 | novarac23/learn-python-the-hard-way | /ex32.py | 415 | 3.921875 | 4 | the_count = [1, 2, 3, 4, 5]
fruits = ["apples", "oranges", "pears", "appricots"]
change = [1, "pennies", 2, "dimes", 3, "quarters"]
for number in the_count:
print(f"this is for {number}")
for fruit in fruits:
print(f"this is for {fruit}")
for i in change:
print(f"tjis is a {i}")
elements = []
for i in ... |
2ff5489304b31f1c74eebf12bb4d38d879789174 | dkbarcla/variance | /final/models.py | 8,030 | 3.828125 | 4 | import random as rd
from constants import *
class Card:
def __init__ (self, rank, suit):
'''Implement a card with a rank and suit.'''
self.rank = rank
self.suit = suit
self.ranking = list(RANKS.keys())[list(RANKS.values()).index(self.rank)]
# checks if card is a valid card,... |
34169b70be4b480ac31189611626955ef75d9bc8 | codemossaka/searchAlgorithms | /methods.py | 7,190 | 3.78125 | 4 | import collections
class search:
def __init__(self):
pass
def dfs(self, graph, start, target, visited=None):
if visited is None: # проверяем пустоту посешенный ход
visited = set() # инициализируем неповторяемый массив посещаемых ходов
if self.isTarget(start, target):
... |
ca275404cf4e0baa902b0873bbc1e2fa76346465 | eternalseptember/CtCI | /05_bit_manipulation/03_flip_bit_to_win/flip_bit_to_win_sol_2.py | 831 | 3.640625 | 4 | # Optimal solution
# Integer.BYTES = 32?
# O(b) time, where b is the length of the sequence.
# O(1) memory.
def longest_sequence_of_ones(num):
if num == -1:
# -1 in binary is a string of all ones.
# This is already the longest sequence.
return "No bits are flipped."
current_length = 0
previous_length = 0
m... |
18df1fb940b039e388e483c79658765ccfd1c085 | chao-ji/LeetCode | /python/linked_list/lc82.py | 2,617 | 3.765625 | 4 | """82. Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
"""
# Definition for singly-linked list.
# c... |
b2768b46bf055058df4a5576e005a78e37bae140 | Shelby86/Python_Work | /review1_with_answers.py | 4,981 | 4.4375 | 4 | """
Questions
What is a list?
What is the difference between insert and append?
What is the difference between remove and pop?
What is join on a string?
What is split on a string?
Can you add a remove a value from a tuple?
What is the difference between remove, del and pop?
What is the difference be... |
8c06ede63297bebdd7cf4fee84b3697c4664cb9c | libowei1213/LeetCode | /816. Ambiguous Coordinates.py | 1,265 | 3.578125 | 4 | class Solution:
def judge(self, str):
if "." in str:
a, b = str.split(".")
else:
a = str
b = '1'
if ((len(a) == 1 and a == '0') or not a.startswith('0')) and not b.endswith('0'):
return True
else:
return False
def amb... |
cbef406f02070da12f4906aae73affe062769688 | C-N-G/j-m-c | /hello world.py | 2,075 | 3.96875 | 4 | import random
def my_function(input):
if input > 200:
print("hello world")
elif input < 200:
print("goodbye world")
else:
print("you suck")
def MYadd():
first_numberadsasdasdasd = input("enter a number ")
second_numberasdasdasdasd = input("enter another number ")
print(int(first_numberadsasdas... |
3dee80d0d43dfeedc7697a9f844a111bd304380e | guveni/RandomExerciseQuestions | /mirror_trees.py | 1,526 | 4.03125 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
__author__ = 'guven'
class TreeNode(object):
def __init__(self, value):
self.value = str(value)
self.left = None
self.right = None
def traverse_tree(root):
if not root:
return ''
left = traverse_tree(root.left)
... |
8e5821aac93e69f3eac0a177a1b86babf40a15f7 | Sasikumar-s/Python-files | /List/6-sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.py | 419 | 4.21875 | 4 | ''' Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples. Go to the editor
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]'''
a=[]
t=[]
l=int(input("How many pairs"))
fo... |
276f96b3b2f786503db722c6c4a78c43c372b041 | 14Praveen08/Python | /no_of_char.py | 84 | 3.890625 | 4 | word = input()
char = 0
for i in word:
if i != " ":
char = char + 1
print(char)
|
fd24278816be2b651cda110d45262145b59d09ef | JunyaZ/algorithm- | /QuickSort.py | 2,120 | 3.546875 | 4 | #!/usr/bin/env python3
"""
Created on Wed Oct 3 11:22:45 2018
@author: Junya Zhao
"""
import numpy as np
import random
Comparison=[]
def readfile (filenemae):
file = np.loadtxt(filename,delimiter='\n')
data = list(file)[1:]
inputData = list(map(lambda x:int(x),data))
return inputData
def pa... |
176163f0ee72cf2f4ccadecd570df105fc982b95 | KATO-Hiro/AtCoder | /ABC/abc101-abc150/abc146/b.py | 405 | 3.65625 | 4 | # -*- coding: utf-8 -*-
def main():
from string import ascii_uppercase
n = int(input())
s = input()
alpha = ascii_uppercase
ans = ''
for si in s:
for index, a in enumerate(alpha):
if si == a:
next_index = (index + n) % 26
ans... |
c2805cfdbae3f8fd4ab3280d08d9afa734d54c3c | alei-num1/Git-hub | /Practice-program/Program3.py | 1,569 | 4.125 | 4 | # 这是一个猜字游戏
import random
guess_number = random.randint(1, 20)
print("I'm thinking of a number between 1 and 20.")
# 向游戏者询问数字4次
for guess_counts in range(1, 5):
print("Please take a guess.\n")
try:
number = int(input("Please tell me a number: "))
if number < guess_number:
print("Yo... |
c05c3431ccbfc6778fc8bcb263d0bb942313b969 | wwwhaleee/ZeNan | /hanoi.py | 327 | 3.953125 | 4 | def hanoi(n, A, B, C):
if n > 0:
hanoi(n-1, A, C, B)
print("{} --> {}".format(A,C))
hanoi(n-1, B, A, C)
m = int(input())
hanoi(m, 'A', 'B', 'C')
print("just modify the code")
print("just modify the code")
print("just modify the code")
print("just modify the code")
print("just modify the... |
09b074479332026a8ce5cc6ebc2113aedf71737b | dwi859/tugas_pyton | /tugas_pyton.py | 785 | 4 | 4 | nilai1 = int(input("Masukan nilai diameter : "))
nilai2 = int(input("Masukan nilai tinggi : "))
volume = ((nilai1/2) * (nilai1/2)) * 3.14*nilai2
print("Maka Hasil Volume tabung adalah = " + str(volume))
print("\n")
sisi = int(input("Masukan panjang Sisi segitiga : "))
keliling = sisi*3
print("Keliling dari segitiga... |
515199decd6f4a4ccd5911f4b074db4ad8c03e61 | Raghu-vamsi-pav/dataanalytics_practice | /datastructure.py | 3,540 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 30 20:09:38 2020
@author: Raghu
"""
print("hello world")
#Numbers
a=3
b=5 #a and b are number objects
#String
str1 = 'hello javatpoint' #string str1
str2 = ' how are you' #string str2
print (str1[0:5]) #printing first five character using slice operator
print (st... |
b72c8a7eac290a1bb11d2aee3db6b639b8a51bdd | chuxing/wechat | /datamigration/Trie.py | 1,980 | 3.578125 | 4 | # -*- coding:utf8 -*-
class Trie(object):
def __init__(self):
self.root = dict()
self.END = '\0'
def insert(self, string):
if string == '\0':return
index, node,return_index, return_flag = self.findLastNode(string)
# print index,node
for char in string[index:]:... |
678eff5daeb7c8d35b0275791985d7d51f91c679 | andrelsf/python | /scripts_python/livro_curso_intensivo_de_python/strings/name_cases.py | 455 | 4.125 | 4 | #
#
# 2.3 Mensagem Pessoal: Armazene o nome de uma pessoa em uma variável e apresente uma mensagem a esta pessoa.
# Sua mensagem deve ser simples, como "Aló Eric, voce gostaria de aprender um pouco de python hoje?".
#
name = "Andre"
print("Ola "+ name + " voce gostaria de trabalhar na SOLUTI.")
resposta = input("Entre... |
4d8b4125ba0a95fb6448762db11c74bb41eeb994 | osbetel/LeetCode | /problems/lc70 - Climbing Stairs.py | 2,192 | 4.3125 | 4 | # See lc746 for a similar problem
# Given a staircase with n steps, if you can step up one step
# or two steps at a time, how many distinct ways can you climb to the top?
#
# So if we have a staircase of 2 steps, we can do 1 step + 1 step, or 2 steps, making
# 2 distinct ways we can get to the top.
#
# With 3 steps, th... |
2fbe2c4739dd410c36eee4aed489a16f2ebf5781 | helbertsandoval/trabajo10_sandoval-sanchez-helbert_cesar_maira_paz | /menu.py | 1,216 | 3.546875 | 4 | import libreria
def agregarBytes():
# 1. Pedir 2 bytes
# 2. Guardar los datos en el archivo bytes.txt
byte1=libreria.pedir_byte("Ingrese Byte 1:")
byte2=libreria.pedir_byte("Ingrese Byte 2:")
contenido=byte1 + "-" + byte2 + "\n"
libreria.guardar_datos("bytes.txt", contenido, "a")
... |
9a6a377c4ad27e41292ae8be64b76946cc867dbc | FRadford/sage | /src/Timer.py | 509 | 3.859375 | 4 | import time
class Timer:
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, error_type, value, traceback):
self.end = time.time()
self.elapsed = self.end - self.start
if self.elapsed > 3600:
self.elapsed = str(self.elapsed / 3600)... |
565359fb4969e9d0c3c34a21f62abfee03c34a66 | Pranith1785/Algorithms | /Strings/Reverse_words_in_String.py | 1,149 | 4.125 | 4 | ### Problem Statement
'''
Function that takes the string of words separated by one or more spaces and
returns the string with words in reverse order.
Example : string = "Space b/w words is 4"
Ans = "4 is words b/w Space"
'''
### Solution - 1
## Time - O(n) | Space - O(n) n- length of the string
... |
c382e12590d56eac3942833eeb89e5a281bffad9 | Rockfish/PythonCourse | /04_SqlLite/movie_database.py | 3,107 | 3.984375 | 4 | import sqlite3
from movie_client import get_movie_data
class MovieDatabase(object):
def __init__(self):
"Connects to the database or creates a new if needed."
self.connection = sqlite3.connect("test.sqlite")
def create_movie_table(self):
"Creates the movie table in the database."
... |
e6398d8c1dd9ec3af700db33b9a1852587b3bb60 | 3l-d1abl0/DS-Algo | /py/oops/class-static-method-decorator.py | 1,286 | 3.5 | 4 | class NewClass(object):
classy = 'class value!'
def __init__(self):
print('Initalized')
count = 100
class InstanceCounter(object):
count = 0
def __init__(self,val):
self.val = self.filterint(val)
InstanceCounter.count +=1
@staticmethod #any utility function that doesn't ac... |
0a088923728208c5b0bec6d40ee12508ebd0199c | chinmaey/CSSPythonPractice | /Exersise10_7.py | 279 | 4.03125 | 4 | def is_anagram(s1,s2):
if s1==s2:
return False
elif len(s1)!=len(s2):
return False
else:
cs1=sorted(s1)
cs2=sorted(s2)
if cs1!=cs2: return False
else: return True
import sys
print(is_anagram(sys.argv[1], sys.argv[2]))
|
99e0a127384f68b42d905700d170e0468945f25a | dmaryanbarnes/Machine-Learning-2018 | /playgound/calcComplete.py | 664 | 3.71875 | 4 | import sys
import math
def pythagoras(a, b):
a_squared = math.pow(a, 2)
b_squared = math.pow(b, 2)
return math.sqrt(a_squared + b_squared)
def main():
command = sys.argv[1]
if command == "add":
x = int(sys.argv[2])
y = int(sys.argv[3])
print(x + y)
if command == "sub"... |
fc7327b5d110a8e3bc4279532eb2b78fb8392829 | BlueVelvetSackOfGoldPotatoes/medicalMRIcnn | /goncalo/thesis_project/files_for_thesis/scripts/distance_measure_control/distance_measure.py | 1,310 | 4.03125 | 4 | ''' Methods that calculate the distance measure between two images
'''
import numpy as np
def calc_average_vector(li_images):
''' Calculate the average vector over all vectorized images '''
final_vector = []
total = len(li_img)
# val_i should be a list - the vectorized image
for i, val_i in enumer... |
db8fff37137829aaf2a7ba4cbd92386fcc7b12e3 | kirtish16/My-Articles | /Que3.py | 1,226 | 4.125 | 4 | # Python3 implementation of the approach
# Function to multiply two square matrices
def multiplyMatrices(arr1, arr2):
order = len(arr1)
ans = [[0 for i in range(order)] for j in range(order)]
for i in range(order):
for j in range(order):
for k in range(order):
ans[i][j] += arr1[i][k] * arr2[k][j]
retur... |
686d0d880fc1ac25f7ce4a726037b929c522fd89 | Klooskie/mownit2 | /lab4/lagrange_interpolation.py | 4,806 | 3.59375 | 4 | import numpy as np
import matplotlib.pyplot as plt
from math import sin, cos, pi, exp
def maximum_norm(vector):
m = 0
for x in vector:
if abs(x) > m:
m = abs(x)
return m
def newton_polynomial(x, n, factors, points):
result = 0
for i in range(n):
result += factors[i]
... |
0bc2a7a07ac3c230bc328b3c91fc8c6a7ddb5c9a | pgadds/Program-Design-and-Abstraction | /Problem Set 2.py | 1,850 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 12 23:18:30 2019
@author: navboi
"""
#Problem 1
month = 0
totalPay = 0
monthlyInterestRate = annualInterestRate / 12.0
while month <12:
minPay = monthlyPaymentRate * balance
unpayBal = balance - minPay
totalPay += minPay
balance = ... |
29ccadcb5a463d4cec162adbde567a75cbe63529 | wilsonfr4nco/cursopython | /Modulo_Intermediario/Dicionarios/dicionários_04.py | 386 | 3.859375 | 4 | # fazendo cast com dicionário
lista = [
['c1', 1],
['c2', 2],
['c3', 3],
]
# como tenho um par eu posso converter para dicionário.
# posso também converter tuplas para dicionário, o que importa é ter chaves e valores.
d1 = dict(lista)
print(d1)
d1.pop('c3') #removeu um ítem
print(d1)
d2 = {
1:2,
... |
32165c27cff89b19ec7f09fbdfdafdf3cb79eacd | nazaninsbr/Turtle-Drawings | /more-complex/two.py | 391 | 3.703125 | 4 | import turtle
from random import randint
NUMBER_OF_CIRCLES = 50
NUMBER_OF_GROUPS = 3
SPEED = 0
loadWindow = turtle.Screen()
turtle.speed(SPEED)
turtle.colormode(255)
for i in range(NUMBER_OF_GROUPS):
r = randint(0,255)
g = randint(0,255)
b = randint(0,255)
for i in range(NUMBER_OF_CIRCLES):
turtle.circle(i... |
5e8cf56b8cdbadc25fe2e70074e2278e744da075 | jayendra-patil33/python_lab_programming | /Angstrom_4.py | 320 | 3.921875 | 4 | # Jayendra Patil
# roll no: 19, gr no: 11810706
# To test for angstrom number
# question: 4
num=int(input("Enter a number:"))
sum = 0
temp = num
while temp > 0:
digit =temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Angstrom number")
else:
print(num,"is not an Angstrom num... |
ac03ecf5d6aefdf5b9c0de63c55e16c04aca96b2 | rahulvshinde/Python_Playground | /Top_Leetcode/majority_elementII.py | 556 | 3.984375 | 4 | """
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Follow-up: Could you solve the problem in linear time and in O(1) space?
Example 1:
Input: nums = [3,2,3]
Output: [3]
Example 2:
Input: nums = [1]
Output: [1]
Example 3:
Input: nums = [1,2]
Output: [1,2]
"""
nums = [3,... |
ca81410dd8ce2b51f5fe803f7e8b8417d4681135 | kukukuni/Python_ex | /3day/Quiz01_2.py | 520 | 3.71875 | 4 | # Quiz01_2.py
items = {"콜라":1000,"사이다":900,"씨그램":500,"우유":700,"활명수":800}
print("=== 음료 자판기 입니다 ====")
print("[콜라][사이다][씨그램][우유][활명수] 중 선택")
print("복수 선택 시 --> 예) 사이다,우유 ")
# 선택목록 item, 가격 price
item = input() # 사이다,우유
items2 = item.strip().split(',')
prices = [p for i,p in items.items() if i in items2]
price =... |
189f44ba0ef319b1188838898fefcf9f83394128 | arnabs542/DataStructures_Algorithms | /bitwise/Single_Number_III.py | 944 | 3.640625 | 4 | '''
Single Number III
Given an array of numbers A , in which exactly two elements appear only once and all the other elements appear exactly twice.
Find the two elements that appear only once.
Note: Output array must be sorted.
Input 1:
A = [1, 2, 3, 1, 2, 4]
Input 2:
A = [1, 2]
Output 1:
[3, 4]
Output 2:
[1, 2]
... |
33fe6c1accd0e8d238e54aeb8de6cf1bbfecbb2f | Naazyon/RNG-Battle-Royale | /socket_client.py | 1,672 | 3.8125 | 4 | """
This is a simple example of a client program written in Python.
Again, this is a very basic example to complement the 'basic_server.c' example.
When testing, start by initiating a connection with the server by sending the "init" message outlined in
the specification document. Then, wait for the server to send yo... |
440f0ed85eaf27f40c105df434437bd86d0b6e27 | patrick-bedkowski/Sorting-Algorithms-Visualized | /selection_sort.py | 761 | 3.859375 | 4 |
def selection_sort(data):
if not data:
return []
# by default minimum value of the list is set to be the first one
indecies_length = len(data) - 1 # number of indecies to iterate through is smaller by one
# iterate through the rest of the values
# and compare them with minimum
for ind... |
da984afae696a07340a05719ae411e62c1aa9e65 | MengdiWang124/thinkcspy | /Chap_2/12_fahren_to_celsius.py | 90 | 3.828125 | 4 | fahrenheit=float(input("Degrees fahrenheit:"))
Celsius=(fahrenheit-32)/1.8
print(Celsius)
|
a10f6e6c0a36c55aa7529a7cc4167228f749cb82 | curlyae/DGSim | /function/write_into_database.py | 13,590 | 3.984375 | 4 | """
.. note::
This module provides methods to transfer data from JSON/TXT file into database
"""
import sqlite3
import json
from data.connect_database import *
from function.get_datainfo import *
def icd10cm_info_json_into_database(database_name, table_name, json_file_path):
"""
Transfer icd10cm dat... |
6c9930479e1e3bd827cb72477f9039943e905650 | here0009/LeetCode | /Python/1617_CountSubtreesWithMaxDistanceBetweenCities.py | 5,574 | 3.71875 | 4 | """
There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree.
A subtree is a subset of cities where every city is ... |
0bdc57412c51eac8fc9459c4e16abd93489f8d81 | LXZbackend/python | /数据结构/排序/sort.py | 1,481 | 3.953125 | 4 | # coding=utf-8
# 冒泡排序
def bobbleSort(list):
# 首先设置外层循环
# 逐渐递减 最后也循环长度减1次 但是为内存循环提供了方便
for i in range(len(list) - 1, 0, -1):
# 注意这里面循环只要到最后num 在下面的判断中 因为是上一个和下个匹配 当你到达前一个的时候其实 就可以对比到最后一个了。但那是选择排序不一样 所以得 加1
for j in range(i):
if list[j + 1] < list[j]:
temp = list[j + ... |
99defb0a781227421b12b4a315bba50f843d6929 | Mosiv/Python-lissons | /game.py | 596 | 3.875 | 4 | '''Game: Guess the number'''
import random
random_number = random.randint(1,50)
attempt_counter = 0
print('Игра, угадай число от 1 до 50')
while attempt_counter < 6:
number = int(input('Введите число: '))
attempt_counter+=1
if number == random_number:
print('Угадал')
break
if number > r... |
655fe68b0b65ad8cf28428f9d1e81f0f48b1616e | paritabrahmbhatt/Python-for-Everybody | /Extra Problems/Easy/P006.py | 226 | 4 | 4 | #Python Program for simple interest
p = int(input("Enter the amount of principle: "))
n = int(input("enter the number of years: "))
r = float(input("Enter the rate: "))
sr = (p*n*r)/100
print("Simple interest: ",sr)
|
ce84e3ceff75bc38bf506e1204e814bd019c6058 | paulsobers23/steph-smith-school | /Jan-24-2020/coding-challenge.py | 273 | 3.8125 | 4 | def find_uniq(lst):
dic = {};
for char in lst:
if char not in dic:
dic[char] = 1
else:
dic[char] += 1
for char in dic:
if dic[char] == 1:
return char
print(find_uniq([1, 1, 1, 2, 1, 1])) |
df5b2fa97e00dc4e4c3d60b8218a23966a2d4dd3 | romeorizzi/temi_prog_public | /2018.12.05.provetta/all-CMS-submissions-2018-12-05/2018-12-05.12:59:53.727460.VR429684.rank_unrank_ABstrings.py | 715 | 3.734375 | 4 | """
* user: VR429684
* fname: ERIKA
* lname: ZOCCATELLI
* task: rank_unrank_ABstrings
* score: 0.0
* date: 2018-12-05 12:59:53.727460
"""
#!/usr/bin/env python3
# -*- coding: latin-1 -*-
# Template di soluzione per il problema rank_unrank_ABstrings
def ABstring2rank(s):
p=0
for i in range(len(s)):
... |
7d12fe31261e15910b7778846f396695bc25ef57 | rebeccajohnson88/qss20 | /mini_book/_build/jupyter_execute/docs/getting_started.py | 9,332 | 4.6875 | 5 | (getting_started)=
# Setting up Your Python Environment
## Overview
In this lecture, you will learn how to
1. get a Python environment up and running
2. execute simple Python commands
3. run a sample program
4. install the code libraries that underpin these lectures
## Anaconda
The [core Python package](https... |
b4e783deded3d274de02a07f2ec147afb1fa4907 | anoopkumarcv/PythonScripts | /Fibonnici.py | 597 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number.
"""
def Fibonacci (num):
num1=0
num2=1
for num in range(0,num):
yield num1
num1,num2=num2,num2+num1
while(True):
try:
num... |
0db0c89c0f86e9691b4d3c649cb50cd03760ccd2 | cosmos-nefeli/practice_python | /maps.py | 545 | 4.21875 | 4 | """
Python Maps also called ChainMap is a type of data structure to manage multiple dictionaries together as one unit.
"""
import collections
dict1 = {'day1': 'Mon', 'day2': 'Tue'}
dict2 = {'day3': 'Wed', 'day1': 'Thu'}
res = collections.ChainMap(dict1, dict2)
# Creating a single dictionary
print(res.maps,'\n'... |
27fd7457caf11e26144eb02c78e9ce54ec5603ce | kanekyo1234/AtCoder_solve | /A other/三井住友信託銀行プログラミングコンテスト2019/B.py | 195 | 3.59375 | 4 |
import math
a=int(input())
if (a/1.08)%1==0:
print (math.ceil(a/1.08))
else:
m=math.ceil(a/1.08)
if a==math.floor(m*1.08):
print(math.floor(m))
else:
print(":(")
|
d02141db3953a942302f600f60b8384d6b85c855 | LucasHuls/OpdrachtenGroep5 | /Bram van Nek/python/opdracht 3.py | 216 | 3.6875 | 4 | numbers=[1,2,3,5,7,10,44,2,5,11,2]
print("grootste waarde is: ", max (numbers))
print("kleinste waarde is: ", min (numbers))
tellen = list.count (numbers, 2)
print ("numbers twee komt", tellen, "keer voor.")
input() |
a22f2f389b26228790b0f9beb49614d1168faaf5 | geodimitrov/Softuniada | /2017/04. snake.py | 2,181 | 3.703125 | 4 | def create_cube(size):
result = []
for x in range(size):
line = input().split(" | ")
result.append([list(el) for el in line])
return result
def read_commands():
result = []
while True:
command = input()
if command.startswith("end"):
result.append(co... |
ebfe55dff4ade40fcf6c44b5a5264f013a4492d0 | huazai007/python | /day02/07.py | 212 | 3.71875 | 4 | arr = []
while True:
input = raw_input('input: ')
if input == 'add':
detail = raw_input('detail.......:')
arr.append(detail)
print arr
elif input == 'do':
if len(arr) ==0:
break
print arr.pop(0)
|
64c937cb355dd0c7072bbf4225d54f4ee45f26ed | cybernuki/holbertonschool-higher_level_programming | /0x0A-python-inheritance/100-my_int.py | 523 | 4.0625 | 4 | #!/usr/bin/python3
# 100-my_int.py
# Jhonatan Arenas <1164@holbertonschool.com>
"""
Defines a MyInt class that inherits by Int
But has == and != operators inverted
"""
class MyInt(int):
"""Class that has == and != operators inverted
Also, it inheritance by int
"""
def __eq__(self, other):
... |
bda567dd1fa7c49f2557b470bc7faf1108410969 | Sumit-daniel/Roll-the-dice-game | /Roll the dice.py | 819 | 4.03125 | 4 |
___________ROLL The Dice___________
#Modules
import tkinter as tk
from PIL import Image, ImageTk
import random
#adding images
dice=["dice1.png","dice2.png","dice3.png","dice4.png","dice5.png","dice6.png"]
root=tk.Tk()
root.title("Dice simulator")
root.geometry("500x400")
#label
l1=tk.Labe... |
52f18bfa1870212b5422ade88f59a5deab0cea33 | kiilkim/book_duck | /pythonPractice/pnuPY/0708book.py | 769 | 3.875 | 4 | #자료형 변수와입력
pi=3.14159265
r = 10
print("원주율 = ",pi)
print("반지름 =",r)
print("원의둘레 =",2*pi*r)
# 변수형을 설정안해줘서 좋긴 하지만, 팀프로젝트 할 떄 서로 충돌할 가능성
#복합 대입연산자
r +=10
print(r)
#빼기, 곱하기, 나누기, 몫 등 에 제곱도 가능 '연산 후 대입!'
#문자열도 가능하다.
string = input("입력 >")
print("자료 :",string)
#090 문제 5
str_input = input("원의반지름입력>")
num... |
5126ea5df3a6089c7d10d1393e93adbd87a062f5 | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | /answers/MridulMohanta/Day22/question2.py | 714 | 3.6875 | 4 | from queue import Queue
def revque(k , Queue):
if Queue.empty() == True or k > Queue.qsize():
return
if k <= 0:
return
stack = []
for i in range(0 , k):
stack.append(Queue.queue[0])
Queue.get()
while (len(stack) != 0):
Queue.put(stack[-1])
stack.pop()
... |
f2207b6224c2f45c7f3132433383c757087ec872 | royashams/Restaurant-Simulator | /customer.py | 4,406 | 4.15625 | 4 | class Customer:
"""A Customer.
This class represents a customer in the simulation. Each customer will
enter the simulation at _entry_time, will wait at most _patience turns.
The restaurant need _prepare_time turns to prepare this customer order,
and will receive _profit if can serve this customer o... |
d22208def77d5cba9de07162f1a9d7f84049455f | WilsonTandya/DedBot | /src/regex.py | 2,937 | 3.515625 | 4 | import re
def regex_tanggal(tanggal):
# Tanggal dengan format XX NAMA_BULAN YYYY
tanggal = tanggal.lower()
bulan = 'januari|februari|maret|april|mei|juni|juli|agustus|september|oktober|november|desember'
pattern = r'[0-9]{1,2}\s(' + bulan + ')' + r'\s[0-9]{4,4}'
x = re.search(pattern, tanggal)
... |
8fba49bdde14ee42105b1fb166423d7dc713b028 | ricardovergarat/1-programacion | /Python/Utilidad/Paquetes/Paquetes mios/paquetes de python/Modulos Paquetes y Namespaces/funciones/paquete1/matematica.py | 156 | 3.5 | 4 | def suma(numero1, numero2):
resultado = numero1 + numero2
return resultado
def resta(numero1, numero2):
resultado = numero1 - numero2
return resultado
|
343ee055ff68588d94dfb2622fa088550a9828a4 | dipalira/LeetCode | /String/345.py | 513 | 3.6875 | 4 | s = "leetcode"
def reverseString(s):
"""
:type s: str
:rtype: str
"""
start = 0
end = len(s) - 1
s = list(s)
vowels = set(list("aeiou"))
while (start < end):
if (s[start] in "aeiou") and (s[end] in "aeiou" ):
s[start], s[end] = s[end] ,s[start]
start +... |
fc78249cea41af1185722f0ad3dd2683d66d39a9 | ahmadzaidan99/Codewars | /Persistent_Bugger.py | 236 | 3.5 | 4 | def persistence(n):
arr = [int(x) for x in str(n)]
count = 0
while(len(arr)!=1):
result=1
count += 1
for x in arr:
result *= x
arr = [int(x) for x in str(result)]
return count
|
b8f3ccadb2536ca6e34d1159d23e0424541f7654 | oolsson/oo_eclipse | /Practise_stuff/object/object2.py | 761 | 3.984375 | 4 | '''
Created on Jan 29, 2012
@author: oo
'''
class className:
def createName(self,name):
self.name=name
def displayName(self):
return self.name
def saying(self):
print 'hello %s' % self.name
#creates the object
first=className()
#sets the name i to eq... |
c7a17c2445d3a9f32926e40293010f6041f242ca | lucatray/PythonPractice | /zillion.py | 2,913 | 3.703125 | 4 | class Zillion:
def __init__(self, string):
self.digits = []
if len(string) == 0:
raise RuntimeError
else:
length = 0
while length < len(string):
if string[length] >= '0' and string[length] <= '9':
self.digits.append(str... |
7b623f77c74d4a6149653d5e0a45c4788a640e0d | correl/euler | /python/e040.py | 985 | 4.1875 | 4 | """Finding the nth digit of the fractional part of the irrational number.
An irrational decimal fraction is created by concatenating the positive integers:
0.12345678910[1]112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional par... |
6be45a8a35fd10aca4db88e0984926485d4c68fb | CoderTag/Python | /Pract/find_prime.py | 389 | 3.921875 | 4 | # Find the number is prime or not
import math
import sys
num = 100
sqrt_num = math.sqrt(num)
int_num = int(sqrt_num)
ceil_num = math.ceil(sqrt_num)
if ceil_num == int_num:
print("Not a Prime number. Perfect Square")
else:
for r in range(2, ceil_num + 1):
if num % r == 0:
print("Not a Prim... |
1ed79b6842e40c19e3a00d67f282804a66012384 | eldojk/Workspace | /WS/DSTests/algos/math/factorial_tests.py | 648 | 3.515625 | 4 | from unittest import TestCase
from DS.algos.math.factorial import iterative_factorial, recursive_factorial
class FactorialTestCase(TestCase):
def test_iterative_factorial(self):
self.assertEqual(120, iterative_factorial(5))
self.assertEqual(1, iterative_factorial(0))
self.assertEqual(24,... |
8ee44b798ebb81abe979b4283ba421a306f0a6bd | snsokolov/contests | /codeforces/556A_zeroes.py | 2,674 | 3.515625 | 4 | #!/usr/bin/env python3
# 556A_zeroes.py - Codeforces.com/problemset/problem/556/A Zeroes quiz by Sergey 2015
# Standard modules
import unittest
import sys
import re
# Additional modules
###############################################################################
# Zeroes Class
###################################... |
9996dac51bbe4a6faf3937ab2f6498b96c4274d6 | Duome/data_structure | /queue01.py | 1,174 | 4.03125 | 4 | # -*- coding: utf-8 -*-
#从头出,从尾进
class Squeue(object):
def __init__(self):
self.queue = []
def is_empty(self):
return not self.queue
def dnqueue(self):
assert not self.is_empty()
return self.queue.pop(0)
def enqueue(self, item):
self.queue.append(item)
class ... |
88460421daf3cdc0cded2d8744b38eb0621cd00b | ssarup/covid19 | /data/LocationDoNotUse.py | 1,091 | 3.71875 | 4 | class LocationDoNotUse(object):
"""
This class should not be used.
It is unsafe. It does not support equality.
"""
def __init__(self):
self._country = None
self._state = None
self._county = None
self._city = None
def country(self, country_):
self._countr... |
4a788e1887175fe2f3a36028732348e6b9d665cc | teslamyesla/leetcode | /python/0494-target-sum.py | 920 | 3.859375 | 4 | """
DFS + memo
Time complexity: O(l⋅n). The memo array of size l*n has been filled just once. Here, l refers to the range of sum and n refers to the size of nums array.
Space complexity: O(l⋅n). The depth of recursion tree can go upto n. The memo array contains l⋅n elements.
"""
class Solution:
def findTargetSu... |
07bf558a32ef3fa977bc67860c7ed9c9159bf3f0 | sroopsai/file-management-system | /commandhandler.py | 12,688 | 3.59375 | 4 | """
This program handles the commands
passed by the client to server.
"""
import os
import time
import pandas
class CommandHandler:
"""
Handles all the commands received from the client.
Acts as helper program to the server.
Attributes
----------
self.user_id :
Username of register... |
4b19e47edf8a22cd98366ca2068d6345e3a839de | derick-droid/pythonbasics | /flags.py | 253 | 3.78125 | 4 | prompt = "\nenter your message here please:"
prompt += "\n enter message:"
# using flags in while loops
active = True
while active:
message = input(prompt)
if message.lower() == "quit":
active = False
else:
print(message)
|
641711607a138ce1df44f996bca329d0810f65b8 | syedareehaquasar/python | /encrypting string.py | 1,356 | 3.859375 | 4 | # def generate_encrypted_string (string):
# new = ""
# for x in string:
# if ord(x)>=65 and ord(x)<=90 or ord(x)>=97 and ord(x)<=122:
# if (ord(x)>=65 and ord(x)<=77) or (ord(x)>=97 and ord(x)<=110):
# new += chr(ord(x)+13)
# else:
# new += chr(ord... |
8981d1e20e26a2def75105b34768a289ba6de3f1 | Splashbeats/EnglishGrammarBattle | /py/testScript.py | 1,197 | 3.640625 | 4 |
# I'm expecting 2 breaks
sentenceToTest = "Jack went to bed late last night because he studied _____ 1:00 a.m."
print("---------------------------------------------------")
print("------------------Test Script----------------------")
print("---------------------------------------------------")
print("Testing: " + se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.