blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
238722d288633262934c91dd279c4a31b7a99e44 | EmmaNunoMares/Practice_Python_withAlgorithms | /SmallestDifference.py | 2,033 | 3.515625 | 4 | """
Sample input: [-1,5,10,20,28,3],[26,134,135,15,17]
Sample output: [28,26]
tiemp: O(nlog(n) + mlog(m))
space: O(1)
"""
import sys
""" my version
def smallestDifference(arrayOne, arrayTwo):
out =[]
arrayOne.sort()
arrayTwo.sort()
holdValue = sys.maxsize
leftOnePointer = 0
leftTwoPointer = 0
... |
117e7902f17adb03cc9505e6845fecda4dd239ff | code-runner-2017/python-snippets | /multiprocessing-example.py | 457 | 3.578125 | 4 | import multiprocessing
# Here we create separate processes, with different heaps
# You can also create threads, that share the same heap.
# See 'multithreading.py'
# More examples here: https://pymotw.com/3/multiprocessing/basics.html
def worker():
"""worker function"""
print('Worker')
if __name__ == '__... |
404debd7472e6215d748b8932f7a0f75766e0e31 | TouchySarun/comarchProject62 | /Assembler/my_utils.py | 945 | 3.625 | 4 | import string
avaiable_character = string.ascii_letters + "1234567890"
def check_allowed_label(label):
illegal_character = []
for character in label:
if character not in avaiable_character:
illegal_character.append(character)
return illegal_character
def to_binary_str(number, mask):... |
933b7ff7774c70de17422265ad8d6cc2a56bb7dc | BeaLove/RLlab | /PycharmProjects/minimax/player2.py | 5,493 | 3.5 | 4 | import random
from fishing_game_core.game_tree import Node
from fishing_game_core.player_utils import PlayerController
from fishing_game_core.shared import ACTION_TO_STR
class PlayerControllerHuman(PlayerController):
def player_loop(self):
"""
Function that generates the loop of the game. In each... |
756fa601346f2d53c6a88a560bb94b2bbc4366d1 | AlexaAndreas99/Faculty | /ArtificialIntelligence/HillClimb.py | 4,439 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 8 14:21:16 2020
@author: Andreas-PC
"""
import copy as cp
import qtpy as qt
class State:
def __init__(self,n):
self.__board=[]
self.__N=n
self.__currentn=0
for i in range(n):
self.__board.append(0)
def __str__(sel... |
43bac6c967c915f8841151ed13853272875621e0 | IsmaTerluk/Progamacion_Orientada_Objetos | /ProbandoListaPorProgramador/Principal.py | 785 | 3.578125 | 4 | from ClasePersona import Persona
from ClaseLista import Lista
if __name__ == '__main__':
lista=Lista()
persona1=Persona('Ismael',21)
persona2=Persona('Juan',28)
persona3=Persona('Cluadio',22)
persona4=Persona('Joaquin',30)
lista.insertarVehiculoPorCola(persona1)
lista.insertarVehicu... |
458216d4dbb5e10cf96d54e84402bcd888f4bbc1 | Billshimmer/blogs | /algorithm_problem/merge_intervals.py | 948 | 3.84375 | 4 | #!/usr/bin/python
# -*- coding: latin-1 -*-
# leetcode 56
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
def to_list(self):
print(self.start, self.end)
class Solution(object):
def merge(self, Intervals):
Inte... |
da86f2c7c4083a0cb7be29898368781dcb3df1a8 | FabriceSalvaire/mamba-image | /test/basics/testLabelb.py | 6,356 | 3.53125 | 4 | """
Test cases for the image labelling function.
The function only works with binary image as input and 32-bit image as output.
For every set of pixels in the input image (pixels set to True that are
connected), the output image is computed to give the entire pixels set a value
(its label) that is unique inside the ... |
de6b8049ebd59c50d04f20bd946af1828245ebf3 | JoaoPauloAntunes/learning | /SQLite/basic_cmd/crud/update.py | 1,419 | 3.734375 | 4 | import sqlite3
from read_one import retrieve_single_product
def update_produto():
code = input("Codigo: ")
product = retrieve_single_product(code)
user_want_to_update = False
if product:
description = product[1]
price = product[2]
description_buffer = input(
"Desc... |
0aee6e1417fc356dade15917ae958a329414ede4 | targueriano/neuroIFC | /neuro-ifc_1.0.16_amd64/usr/local/lib/python2.7/dist-packages/neurolab/__init__.py | 1,764 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Neurolab is a simple and powerful Neural Network Library for Python.
Contains based neural networks, train algorithms and flexible framework
to create and explore other neural network types.
:Features:
- Pure python + numpy
- API like Neural Network Toolbox (NNT) from MATLAB
... |
687ad0cc29a78af39d58209855b0b68bbf665f17 | juhideshpande/LeetCode | /AsteroidCollision.py | 621 | 3.546875 | 4 | class Solution(object):
def asteroidCollision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
"""
result=[]
for i in range(len(asteroids)):
while result and asteroids[i]<0<result[-1]:
if result[-1]<-aster... |
b1f2fb75fae04236bb24e6219848da0caf633111 | daviddwlee84/LeetCode | /Python3/BinaryTree/BalancedBinaryTree/Naive110.py | 978 | 3.765625 | 4 | from ..TreeNodeModule import TreeNode
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
if not root.left and not root.right:
return True
return self._checkBalanced(root) and self.isBalanced(root.left) and self.isBalanced(root.r... |
57085c65eaa49c7e26da412032736836deeda718 | EH2007/veritas_fal2018 | /Veritas/Hackerrank/scratch.py | 177 | 3.5625 | 4 | score_list = []
for i in range(int(input())):
name = input()
score = float(input())
in_list = [name, score]
score_list.append(score_list)
print(score_list) |
f5c84557b9c10395148713394cb9b04bd2464290 | 0xRUDRA/Simplified-Advanced-Encryption-Standard | /src/rsa.py | 6,409 | 3.75 | 4 | """
author: RUDRA
@description: --RSA Class module --
module(created) -
func
rsa class for encryption, decryptiona and key generation
parameters: Key Generation Paramters (p,q,r)
variables: p,q,e ... |
522ce42319ab526d430d7f099f20e6d5ddbc3640 | fedeMorlan/semin_python_2021 | /practico2/eje6.py | 1,185 | 3.9375 | 4 | """ 6. Dada una frase donde las palabras pueden estar repetidas e indistintamente
en mayúsculas y minúsculas, imprimir una lista con todas las palabras sin repetir
y en letra minúscula.
"""
frase = """
Si trabajás mucho CON computadoras, eventualmente encontrarás que te gustaría
automatizar alguna tarea. Por ejemplo, p... |
26c11ebd8994ef897d10a21e5adaafed80f7a3e1 | DhruviV/LeetCode | /string_to_int.py | 73 | 3.578125 | 4 | s="dhruvi"
ans=""
for char in s:
ans=ans + str(ord(char))
print(ans)
|
91a84bbe9d6b4fc403544e004b7bfb81fb80c483 | hvijaycse/Data-Structures-and-Algorithms-Coursera | /Algorithmic Toolbox/week2/8_fibonacci_sum_squares.py | 827 | 3.90625 | 4 | # Uses python3
def get_fibonacci_huge_naive():
m = 10
previous = 0
current = 1
sequense = [0, 1]
while True:
previous, current = current, previous + current
s = current % m
if s == 0:
previous, current = current, previous + current
s2 = current % m
... |
f1f488fdc2967c7f2c1a3497e5170976b94a120f | ARSimmons/IntroToPython | /Students/michel/session02/fizzBuzz.py | 411 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 07 20:33:17 2014
@author: Michel
"""
for number in range(100):
if not number % 3 == 0 and not number % 5 == 0:
print number
elif number % 3 == 0 and not number % 5 == 0:
print 'Fizz'
elif not number % 3 == 0 and number %... |
37da1de5cb511b8f0930dde207d551fb777220ef | mortiz96/Learning-Scripts | /Primeros cursos/palindromo.py | 415 | 3.90625 | 4 | def palindromo(palabra):
palabra=palabra.replace(' ','')
palabra=palabra.lower()
palabra_inv=palabra[::-1]
if palabra==palabra_inv:
return True
else:
return False
def run():
palabra=input('Escribe una palabra: ')
es_palindromo=palindromo(palabra)
if es_palindromo==True:
pri... |
04bdf3627f8329aca025c7effdc22adba7f1606b | aldst/redes_neuronales | /adaline.py | 3,985 | 3.578125 | 4 | import random
import math
import numpy as np
import matplotlib.pyplot as plt
class ConjuntoEntrenamiento:
def __init__(self, x1, x2,x3, esperado):
self.x1 = x1
self.x2 = x2
self.x3 = x3
self.esperado = esperado
class Etapa:
def __init__(self, conjunto):
self.w1 = 0
... |
f0406ea2b5c70a340116a6d891edf08e61ea6463 | fernandadreis/Duel-52 | /duel52.py | 2,137 | 3.546875 | 4 | from time import sleep
from lanes import game_board
from deck import make_deck, pick_a_card, show_cards
from actions import draw_card
deck = make_deck() # the deck of this game
# preparing to the start of the game
# flag to alert the end-game
end_game = False
# dealing cards
face_down = deck[0:6] # 1 face_do... |
59c52a46f2fed91aa5c0e80e6b9578fe917fd9b1 | mhernandez2/Python | /sumatorianp.py | 201 | 3.75 | 4 | n = int(raw_input("ingrese n numeros "))
i = int(raw_input("ingrese limite de suma "))
suma=0
if n>i :
print "no se efectuara suma n debe ser < que i"
else :
while n<=i :
suma+=n
n+=1
print suma
|
f5d14dd96ef3dbebfec3873666e46ee707af1189 | monty123456789/coding_one_submission | /Week3_PigLatin.py | 860 | 4.03125 | 4 | vowels = ('a', 'e', 'i', 'o', 'u', 'y')
consonants = ('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z')
word1 = input('enter a word: ')
def pig_latin(word):
if word[0] in vowels:
print(word + 'yay')
elif word[0] in consonants and word[1] in vowels:
... |
4a21fc0672c7c34b0f5ca996efac54cd60a7082c | mmiah00/Sudoku | /clique.py | 307 | 3.5 | 4 | class clique:
def __init__(self):
self.group = [] #one clique is 9 numbers in either a row, column, or square
def check_group (list):
uniqueNums = set (group)
i = 1
while (i < 10):
if !(i in uniqueNums):
return False
return True
|
d082272f859ab1fbfc7c0620769e889692aea563 | Damon0626/Leetcode- | /069-Sqrt(x).py | 737 | 3.578125 | 4 | # -*-coding:utf-8-*-
# @Author: Damon0626
# @Time : 18-11-4 下午10:53
# @Email : wwymsn@163.com
# @Software: PyCharm
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
"""
if x < 0:
return 0
else:
return int(x**0.5)
... |
6c4381f77a400d43ab1a9228e73dbbed19c7ad83 | sakshimadan20/Python-Projects | /fundamentals/chapter4/4_example_string_reverse.py | 167 | 4.28125 | 4 | #to print the string in reverse order
myString = "Programming"
#print(len(myString))
for count in range(1, len(myString)+1):
print(myString[-count], end="")
|
a2da8463d7327887b8220fec6ffbf4e295cead39 | ktel1218/skills2 | /skillstest2.py | 1,525 | 4.09375 | 4 | # Write a function that takes an iterable (something you can loop through, ie: string, list, or tuple) and produces a dictionary with all distinct elements as the keys, and the number of each element as the value
def count_unique(some_iterable):
d = {}
while some_iterable != []:
key = some_iterable.pop... |
0a89014452834708e697c9da1c38a4f1107e217c | ankurgokhale05/LeetCode | /Amazon/Trees/124-Binary_Tree_Max_Path_Sum.py | 845 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
See Most Voted 2nd solution
'''
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
max_path_sum = float('-inf')
def get_max... |
fef474436fa23697a0539df0fe47ed146f3b3b78 | jsinoimeri/Gr12-Python | /Task 2/hash_table.py | 6,278 | 3.875 | 4 | from linked_list import *
from hashing import *
from contacts import *
class HashTable(object):
def __init__(self, size):
'''H(size) creates a hash table with the desired size'''
self.__buckets = []
for num in range(size):
self.__list = SortedList()
self.__... |
1c9d085c55bdf5a2f7898cf97e55c4ddc364b7f0 | Huchengxi/Programming-Exericises | /python_event/thread_test.py | 1,057 | 3.8125 | 4 | # -*- coding:utf-8 -*-
import time
from collections import deque
from random import Random
import threading
class Example():
def __init__(self):
self.r = Random(time.time())
def worker_run(self, name, q):
while True:
if q:
print("%s pop number: %s, %s numbers left... |
a7778c0bce559da27d608c7c3b37cda51845eba3 | ranxx/map-house | /unique.py | 504 | 3.625 | 4 | import csv
def unqiue(filename):
# 读取csv数据
w = open(filename,"r")
# w.readline()
ret = w.readlines()
# print(ret[:3])
# return
print(len(ret))
# 去重
ret = set(ret)
print(len(ret))
# 重写
uw = open("unique"+filename, "a+")
uw.writelines(ret)
# csv_writer = csv.writer... |
645ba6eea58f471748c3f7f66f5b42140e4a4ce9 | Hhn202/APweofingwoi | /AP1/util/generate_expressions.py | 1,677 | 3.890625 | 4 | #!/usr/bin/python
# This is just the very beginning of a script that can be used to process
# arithmetic expressions. At the moment it just defines a few classes
# and prints a couple example expressions.
# Possible additions include methods to evaluate expressions and generate
# some random expressions.
# Stolen fro... |
4dca4cf87bc9e595af6fd407939eefe9812ee401 | anitrajpurohit28/PythonPractice | /python_practice/List_programs/9_count_occurance_of_element.py | 991 | 4.1875 | 4 | # 9 Python | Count occurrences of an element in a list
input_list = [15, 6, 7, 10, 12, 20, 10, 28, 10]
key = 10
print("------- for loop-------")
count = 0
for element in input_list:
if element == key:
count += 1
print(f"Element {key} occurred {count} times")
print("-------builtin count()-------")
count... |
c1905ab495050522d54f2d5391d3c19f9d98f108 | kryman0/school | /python/analyzer/analyzer.py | 3,500 | 4.03125 | 4 | """
Module for text analyzing.
"""
import re, string
filename = None
def check_file_exists(filename):
"""
Check if file exists.
"""
file_not_found = True
try:
open(filename, "r")
return not file_not_found
except:
print("Kunde ej hitta filen.\n")
return file_not_... |
a5db68ddd93fb42c9a675324ac1a4a934dae090a | PhamNguyen18/PHY403 | /hw/hw2/dart_class.py | 7,518 | 4.125 | 4 | """
Author: Pham Nguyen
Last Updated: 02-05-20
"""
import argparse
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
class DartGame:
"""
Class to play dart game.
Rules:
1. A dart is throw randomly at a board. One
point is given even if the first throw is
... |
99363bf5ae7e7128171b4b66cc43138f6fd05c6f | rockyboyyang/python_practices | /variables.py | 329 | 3.953125 | 4 | # a = 9
# b = 'marbles'
# print(a, b)
# print(float('nan'))
# print('run'[-1:2])
# print('run'[-2])
def remove_last_vowel(word):
vowels = "AEIOUaeiou"
i = len(word)
s = ''
for x in reversed(range(i)):
if word[x] not in vowels:
s += word[x]
return s
print(remove_last_vowel('... |
2ac6674a5236c833a19ff1498fe7ba41c44970e7 | ariellewaller/Python-Crash-Course | /Chapter 5/stages_of_life.py | 1,710 | 4.46875 | 4 | # Exercise 5-6. Stages of Life: Write an if-elif-else chain that determines a
# person’s stage of life. Set a value for the variable age, and then:
# If the person is less than 2 years old, print a message that the person is a
# baby.
# If the person is at least 2 years old but less than 4, print a messag... |
d1da1670df51c984007ec3c4b65c76bd812b76af | asis-parajuli/Python-Basics | /queues.py | 360 | 3.796875 | 4 | # FIFO = First IN - First Out
# if we use queues in a list of thousand item and when we remove the first item other 999 items should be shifted in the memory
# for that we need to use deque
from collections import deque
queue = deque([])
queue.append(1)
queue.append(2)
queue.append(3)
queue.popleft()
print(que... |
3e0dc7bea0802a1cbe67e615fc969738cf1a91a4 | HeywoodKing/mytest | /MyPractice/tuple (2).py | 657 | 3.84375 | 4 |
print('不可变的Tuple')
tuple1 = (1, 2, 'aa', 'flack')
print(tuple1[2])
print(tuple1[0:])
dic = {12, 32, 'chook'}
print(dic.pop())
for x in tuple1:
print('tuple:', x)
age = 25
# if age >= 18:
# print('您已经成年了')
# else:
# print('您还未成年')
if age >= 18:
print('您已经成年了')
elif age >= 12:
pri... |
99fd14e433ce72ec855a699c8327fc057f812260 | fossabot/IdeaBag2-Solutions | /Files/Zip File Maker/zip_file_maker.pyw | 4,820 | 3.828125 | 4 | #!/usr/bin/env python3
"""A simple zip archive creator.
Title:
Create Zip File Maker
Description:
The user enters various files from different directories
and maybe even another computer on the network
and the program transfers them
and zips them up into a zip file.
For added complexity,
apply actual compression to t... |
04206f059a06def1872a099c0695961b1cb72470 | rogerwoods99/UCDLessons | /UCDLessons/DataCampPandasSquareBrackets.py | 1,771 | 4.1875 | 4 | # This looks at the use of square brackets for import data and print out a subset
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
# Print out country column as Pandas Series
print(cars['country'])
# Print out country column as Pandas DataFrame
print(cars[['country']])
# Print out... |
f2ea252cdde340f41b36215ab05543c36aa9845a | SR-Sunny-Raj/Hacktoberfest2021-DSA | /33. Python Programs/Square of n numbers.py | 354 | 4.3125 | 4 | ''' Problem Statement : To find square of given N numbers using Recursion and iterative approach'''
n=int(input("Enter Number : "))
def squareIterative(n):
for i in range(n,0,-1):
print(i**2,end=" ")
squareIterative(n)
print()
def squareRecursive(n):
if n>0:
print(n**2,end=" ")
squareR... |
1d341b59a694200af566f94b19790d8467173ddb | amritat123/dictionary-questions | /sum_of_keys_values.py | 145 | 3.875 | 4 | dict1={1:2,2:3,3:4,4:5}
sum=0
for i in dict1.keys():
total=0
for j in dict1.values():
total+=j
sum+=i
print(total)
print(sum) |
ae2bda34b39fef2e79e0168de179e5c800557f0f | mochapup/Python-Programming-2nd-edition-John-Zelle | /Ch4/4.10.10.py | 1,090 | 3.953125 | 4 | # 4.10.10.py
# This program displays information about a rectangle drawn by the user.
# import libraries
from graphics import *
from math import sqrt
def main():
win = GraphWin("Triangle Information",400, 400)
for i in range(1):
p1 = win.getMouse()
p2 = win.getMouse()
p3 = win.getMouse... |
3f1f893fb4921810d20aa8c96b808a35fe8debb2 | Exabyte-io/express | /express/parsers/__init__.py | 547 | 3.625 | 4 | import os
class BaseParser(object):
"""
Base Parser class.
"""
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def _get_file_content(self, file_path):
"""
Returns the content of a given file.
Args:
file_path (str): f... |
db814fc496d13c17a7e9c48d33436bbba58d7fe7 | TumsaUmata/the_last_lap | /Google Assessment/New Grad/watering_flowers.py | 2,005 | 3.75 | 4 | # class Solution:
# def waterPlants(self, plants, capacity1, capacity2):
#
# if len(plants) == 0:
# return 0
#
# pointer1 = 0
# pointer2 = len(plants) - 1
#
# can1 = capacity1
# can2 = capacity2
# count = 2
#
# while pointer1 != pointer2:
# ... |
4b0961633e7be09f8a62f17ae79763eba6c86157 | paulangton/lowest-case | /lowest.py | 1,055 | 3.71875 | 4 | # lowest.py
# A non-serious attempt at creating a lowestcase implementation for python
# strings
# Author: Paul Langton
import sys
lowest_rules = {
' ': ' ',
'a': 'o',
'b': 'o',
'c': '_',
'd': 'o',
'e': 'o',
'f': 'l',
'g': 'o',
'h': 'l',
'... |
2cb43824cec5ef9529ee50e3e74fc20daba4ee62 | adrenalin/helpers | /helpers/get_recursive_filelist.py | 1,053 | 3.53125 | 4 | """
Get recursive filelist
@author Arttu Manninen <arttu@kaktus.cc>
"""
import os
import re
def get_recursive_filelist(
target_folder: str,
filename_filter: str = None,
filename_regex: re = None
) -> list:
""" Get recursive filelist in the target folder with optional filename filter """
... |
bc5fd00494409469cb17195c704443dcfcf285a6 | MMAGANADEBIA/Programming_Courses | /Python_course/numbers.py | 628 | 3.84375 | 4 | #podemos tener numeros enteros como:
10 #conocidos como int de integers
#tambien numeros flotantes o float como:
14.4
#recuerda que podemos ver el tipo de dato asi:
print(type(9))
print(type(10.1))
print(1 + 1 ) #simple suma de numeros
print(3 - 1) #restas
print(1 * 3) #multiplicaciones
print(3 / 2) #diviciones
print... |
0dffb623150b70ee2b9f915a9541c78e8ddc735c | fhmurakami/Python-CursoemVideo | /Exercicios/Mundo 02 - Estruturas de Controle/Aula 15 - Interrompendo repetições while/ex071.py | 1,202 | 4.125 | 4 | # Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a
# ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues.
# OBS: Considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1.
cd50 = cd20 = cd10 =... |
03c5a22caef38221ee3885c6ecc8551ad1c5aa22 | JBailey87/advent | /day1.py | 774 | 3.6875 | 4 | import collections
#filepath = 'input/day1/day1-test.txt'
strFilepath = 'input/day1/day1-puzzle1.txt'
intTotalFrequency = 0
intFrequencySet = set()
def duplicate(intFrequency):
if intFrequency in intFrequencySet:
raise ValueError("Duplicate frequency found {}".format(intFrequency))
with open(strFilepath) as oFile:... |
5c7697f763ef3b439f4269c708585180bd5a4bb3 | gschen/where2go-python-test | /1300-蓝桥杯/year-2016/JAVA-C/test01.py | 125 | 3.515625 | 4 | result='vxvxvxvxvxvxvvx'
money=777
for i in result:
if i=='v':
money*=2
else:
money-=555
print(money) |
fe44437cbdea47b6ff3c0d1935d9dd60810bc2dc | guigui64/advent-of-code | /2020/21.py | 2,103 | 3.9375 | 4 | #!/usr/bin/env python
import re
from collections import Counter
pattern = re.compile(r"(.*) \(contains (.*)\)")
def solve(fname):
# allergens is a dict of sets of ingredients per allergen
allergens = {}
# ingredients is a Counter of the ingredients
ingredients = Counter()
with open(fname) as f:
... |
3e49718f247f2b9eb2956cd76ba636388c2dc822 | marythought/sea-c34-python | /students/RichardGreen/weekthree/safe_input.py | 589 | 3.921875 | 4 |
'''The raw_input() function can generate two exceptions: - EOFError or
end-of-file (EOF) - KeyboardInterrupt or canceled input. - Create a wrapper
function, perhaps safe_input() that returns None rather than raising these
exceptions.'''
def safe_input():
print "Enter a number:"
input = raw_input()
prin... |
c6209e798d69c2d3e89f3dd9db75e060a177ce7d | osnipezzini/PythonExercicios | /ex054.py | 516 | 3.921875 | 4 | '''
Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.
'''
from datetime import date
ano = date.today().year
maior = 0
menor = 0
for c in range(1, 8):
num = int(input('Digite o ano de nascimento da {}ª pessoa: '.... |
68a1177ea707d3eb596431db87984b559f05e899 | shreayan98c/CompetitiveProgramming | /Arrays/BaruaRankReversal.py | 1,453 | 3.78125 | 4 | # Barua and his Rank Reversal
# You've been given a permutation of containing N distinct elements between 1 and N, both included. (1<=N<=10^3)
# The rank of an element in this array is the number of elements to it's left which are strictly lesser than it.
# You have been given array,formulate it's rank array.
# Seems ... |
22be8e84368378228588fe8324e04e0f54727a0d | Shubham-iiitk/Codes | /linklist_insert.py | 1,074 | 4.09375 | 4 | class Node:
def __init__(self,data):
self.value= data
self.next= None
class Linklist:
def __init__(self):
self.head =None
# for printing the linklist
def printlist(self):
temp = self.head
while temp:
print(temp.value)
temp= temp... |
ce1b9b8e5c2793617536c7b33244469d7a865bcd | MarcelinaWojnarowska/Comment-on-a-random-book | /app/car.py | 386 | 3.640625 | 4 | class Car:
def __init__(self, number_of_door, number_of_wheel):
self.number_of_door = number_of_door
self.number_of_wheel = number_of_wheel
def get_number_of_doors(self):
return self.number_of_door
def get_number_of_wheels(self):
return self.number_of_wheel
my_car = Car(4... |
1781ae7bc99693a6c7ffb4365f9676f5d542246a | flyingaura/PythonLearning | /LearnOOP/learning0417002.py | 6,981 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from LearnModule import StringSplit
# 定义一个过滤的行政区划名表
#
filter_province = ('省', '市', '自治区')
filter_city = ('区', '县')
filter_towns = ('街道', '镇', '乡', '回民乡')
filter_street = ('社区','村')
class wordlist(object): #定义一个词表内词输出的类
def __init__(self,word_name,word_nominal,word_freq,word_note):
... |
0c36beccf0133044a5aa9cf8349d50a01a2d7e4e | rafi80/UdacityIntroToComputerScience | /varia/interacjaPoListach.py | 372 | 3.734375 | 4 | '''
Created on 5 paz 2013
@author: Stefan
'''
def iteracja(lista):
i = 0
j = 0
for i in range(len(lista)):
for j in range(len(lista)):
print lista[i][j]
def is_integer(a):
t = int(a)
return t
correct = [[1,2,3],
[2,3,1],
... |
041bb1e2361e02f52db640028b3a914baa8ccbca | Elvis-Lopes/Curso-em-video-Python | /exercicios/ex069.py | 609 | 3.75 | 4 | idade = maiorIdade = qtdHomens = qtdMulheres =0
sexo = str()
opcao = str
while True:
idade = int(input('Digite a idade: '))
sexo = str(input('Qual o sexo da pessoa? F/M')).strip().upper()[0]
if sexo in 'M':
qtdHomens += 1
if sexo in 'F':
if idade < 20:
qtdMulheres += 1
if... |
32fd30b03098605fbcebc5be1a83523a4b9eee38 | jeevananthanr/Python | /File_handle.py | 1,003 | 3.515625 | 4 | #File handling
#fname="Sample.txt"
#fname="C:\\Users\\A603367\\Desktop\\Py\\File\\Sample.txt"
fname="C:/Users/A603367/Desktop/Py/File/Sample.txt"
#open
fhandle=open(fname,"w") #'''create if its not exist otherwise overwrite'''
#lst=['hello','hai']
#write content
fhandle.write("Welcome to File handling\n")... |
c9f0852cb6ec754994217def77db1347040b96e3 | chris-geelhoed/project-euler | /p17/main.py | 1,364 | 3.953125 | 4 | '''
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (t... |
e5c7e20a05f016ca1e4697f3aa15f27c25e910cc | AdamZhouSE/pythonHomework | /Code/CodeRecords/2325/59018/275895.py | 255 | 3.546875 | 4 | info=input().split(',')
a=[int(y) for y in info]
b=set(a)
if len(a)==1:
print(False)
elif len(a)==2:
if len(b)==1:
print(True)
else:
print(False)
else:
if len(a)/len(b)>=2:
print(True)
else:
print(False) |
f06efa85b3ebf443d488197fd9acbcb759531be9 | thecodice/practice_python | /1/richter_scale.py | 1,120 | 4.125 | 4 | #largest ever measured is in chile 9.5 in 1960
#prompt a user to enter a Rc measuremenet,accept floating point value and do some calculations and display the equivalent amount of energy in joules and in tons of exploded TNT for that user-selected value.
#The Richter scale is a way to quantify the magnitude of an earth... |
0ec3619cec0dc520dabfe5fe4317acc9f95312fb | bugxiaoc/spider-Demo | /spider_Demo/tools/stringu.py | 808 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
"""
String Util
"""
def checkURI(str):
if re.search('',str,re.S):
return 1
else:
return 0
def delete_space(obj):
while '' in obj:
obj.remove('')
return obj
def fromat_list(obj):
temp = []
for x in obj:
temp.... |
a54a67b3f2cbc93b59c9b9e0d9bb1b9918ddae4b | Geoff-Lucas/Challenge_Problems | /shortest_substring.py | 1,535 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 21 20:04:12 2021
@author: Geoff
This problem was asked by Square.
Given a string and a set of characters, return the shortest substring
containing all the characters in the set.
For example, given the string "figehaeci" and the set of characters
{a, e, i}, you should... |
fa6990ad3c1c6aa0a56d494a0ccaa4a590ff6674 | cheol-95/Algorithm | /Python/085. 영어 끝말잇기/English.py | 357 | 3.75 | 4 | def solution(n, words):
stack = []
for i in range(len(words)):
if stack and stack[-1][-1] != words[i][0] or words[i] in stack:
return [i%n+1,i//n+1]
stack.append(words[i])
else:
return [0,0]
n, words = 3, ["tank", "kick", "know", "wheel", "land", "dream", "mother", "robo... |
c99e0594d839ec5e7b42d4857c75cab4898cff27 | OrangeCodelover/LeetCode-Solution | /1. Two Sum.py | 284 | 3.65625 | 4 | nums = [2,7,11,15]
target = 9
# look through the entire array
for i in range(len(nums)-1):
for j in range(len(nums)-1):
if i != j and nums[i]+ nums[j] == target:
print([i,j])
break
# break the nested loop
else:
continue
break
|
c3f852b35705f28fba94e3603d320e96e4341a99 | ddrifter/drifting1 | /player.py | 9,447 | 3.875 | 4 | """Class Player with it's properties and functions."""
import pygame
from pygame.sprite import Sprite
class Player(Sprite):
"""Defines the class Player with the player's properties."""
def __init__(self, screen, settings):
"""Initializes the player's properties."""
super(Player, self).__in... |
1438a398a4c9c99d56734b214b9c9e1a6356447f | alu-rwa-dsa/week-3---dynamic-array-josephine_samwel_modester_cohort2 | /Question 2.py | 868 | 3.984375 | 4 | #Authors:Modester, Samwel, Josephine
#Question:Create a dynamic array subclass which also has the following basic methods:
# importing modules
from numpy import random
array1 = []
i = 0
while i < 5:
i += 1
x = random.randint(10) + 1
array1.append(x)
class Array:
def check_val(self, val):
print(... |
838f97bcad6c015f344328ca08ffd189a7368cce | liuouya/MIT_6.00_assignments | /ps3b.py | 496 | 3.59375 | 4 | #! /usr/bin/python2.5 -tt
# Problem Set 3
# Name: Anna Liu
# Collaborators: N/A
# Time: 00:05:00
# Date: 10/04/2014
# search and return a tuple of starting points of 'key' in 'target'.
def subStringMatchExact(target,key):
if key == '':
match = range(0, len(target))
return match
match = ()
location = 0
... |
60bc545c91ddf384c7c3f60378c9375182238673 | tooyoungtoosimplesometimesnaive/probable-octo-potato | /p_y/520_detect_capital.py | 446 | 3.65625 | 4 | class Solution:
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
first_capital = self.is_capital(word[0])
count = 0
for c in word:
if self.is_capital(c):
count += 1
return count == 0 or count =... |
3d34eafd7b2354f6578575b9c3ba3bd29ae0eb62 | xiaoweigege/Python_senior | /chapter01/type_object_class.py | 577 | 4.09375 | 4 | a = 1
b = 'str'
print(type(a))
print(type(int))
print(type(b))
print(type(str))
# 关系为 type 对象生成 int , int对象生成 1
# type -> class -> object
# object 是顶层基类
# type 也是一个类 同时type 也是一个
class Student(object):
pass
stu = Student()
print(type(stu))
print(type(Student))
print(Student.__bases__)
# type object
print('---... |
362b8bdd815de739832be89e28003b4ee7214d54 | martica/aoc2019 | /day7/day7.py | 1,282 | 3.5625 | 4 | import itertools
from intcode.computer import Computer
def main():
program_text = next(open("day7.txt"))
largest_output = 0
best_combination = None
for a, b, c, d, e in itertools.permutations(range(5, 10)):
print(a, b, c, d, e, end=' ')
amp1 = Computer(program_text, [a])
amp2 =... |
97795611e94f77cb5d43b57333bf61c74038a718 | shivdazed/Python-Projects- | /ListFunctions.py | 2,468 | 4 | 4 | a = []
n = int(input("Enter the number of elements in the List:"))
for i in range(n):
l = input("Enter an element")
a.append(l)
print("\nList is:",a)
def ListOps():
o = input("\nEnter the operation you would like to perform on list:\n1.Append\n2.Extend\n3.Count\n4.Index\n5.Clear\n6.Remove\n... |
d7db83626a0c1049497292cc82efb6fc4dabdbf5 | Walrusbane524/Basic-python-projects | /Project_3.py | 431 | 4.15625 | 4 | # Recebe o nome e dia do mês do usuário e imprime um olá, o dia anterior e posterior ao dado.
# Receives the user name and day of month and prints a hello, the day before and the day after the given one.
nome = str(input('Insira o seu nome: '))
dia = int(input('Insira o dia do mês de hoje: '))
print('Olá, ' + nome)
p... |
7ed7fa1cfd7ec2b92aca1205339cbf4c7fabefe7 | yyyuaaaan/python7th | /crk/8.1stairsNcoinchange.py | 1,577 | 3.890625 | 4 | """__author__ = 'anyu'
9.1 A child is running up a staircase with n steps, and can hop either 1step, 2 steps, or 3 steps at a time.
Implement a method to count how many possible ways the child can run up the stairs.
not permutation and not combination
"""
def npermu(n):
if n<=0: return 0
elif n ==1:
re... |
c8b2e28af43e614b072b02ac8fdd6614441dd615 | anayatrabbi/Python_Basic_Data_Structure | /4_Looping_Over_List.py | 375 | 4.53125 | 5 | letters = ["a", "b", "c", "d", "e"]
for letter in letters:
print(letter)
# if we want index we should use enumerate which will return iterable object
# which is tuple and we can insert any item in tuple
for letter in enumerate(letters):
print(letter)
# we can unpack tuple as we did for our list
for index, ... |
1fa5c17ecdad06ce8e46c5a3f700340c4ffab8b0 | kbalasub78/Python-CS1 | /checkpoint1/jacket.py | 739 | 4.3125 | 4 | ## jacket.py
## Write a program to accept the temperature value and
## to tell a person to bring heavy jacket if temperature is < 20,
## if temperature is between 20 and 30, bring light jacket.
## if temperature > 30, do not bring any jacket.
##
## import sys module for graceful error handling
import sys
#### Get use... |
644d999a3834c116b55e3bcb8aeed4b7aba0499c | estherGomezCantarero/practica | /sample/tdd.py | 4,796 | 3.859375 | 4 | import unittest
from sample.strings_example import StringsExamples
class TestStringsExamples(unittest.TestCase):
def test_concat_strings(self):
string1 = "hola"
string2 = "adios"
result = StringsExamples.concat_strings(string1, string2)
assert result=="holaadios"
de... |
eb7d5fd2d03c64f653154cc27012f990a0b70439 | wtokarz80/Python | /fibonacci/fibonacci.py | 884 | 3.96875 | 4 | def fibonacci():
i = 0
j = 1
k = 0
fib = 0
fib_list = []
while i < int(number):
fib_list.append(fib)
fib = j + k
j = k
k = fib
i += 1
max_n = max(fib_list)
for z, e in enumerate(fib_list):
z += 1
print(f"{z}. " + str(e).rjust(len(st... |
4acbbf6fe06f43883a425c9ffdf8378924060874 | dylanplayer/ACS-1100 | /lesson-2/example-6.py | 2,795 | 4.59375 | 5 |
# Convert the lyrics into string:
# When I find myself in times of trouble, Mother Mary comes to me
# Speaking words of wisdom, let it be
# And in my hour of darkness she is standing right in front of me
# Speaking words of wisdom, let it be
# Let it be, let it be, let it be, let it be
# Whisper words of wisdom, let ... |
5284ab9e157bc94da6a6ca56ae737aadcdfcc577 | Apro123/projectEuler | /problem 2.py | 289 | 3.71875 | 4 | #!/usr/bin/env python3
def main():
sum = 0
num1 = 1
num2 = 2
while(num2 <= 4000000):
if(num1 % 2 == 0):
sum += num1
if(num2 % 2 == 0):
sum += num2
num1 += num2
num2 += num1
print(sum)
main()
|
c7efb42dc967a153a2c710ec161faa478b0eb2a4 | codebind-luna/exercism_python | /scrabble-score/scrabble_score.py | 429 | 3.640625 | 4 | dict = {}
dict[1] = ['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T']
dict[2] = ['D', 'G']
dict[3] = ['B', 'C', 'M', 'P']
dict[4] = ['F', 'H', 'V', 'W', 'Y']
dict[5] = ['K']
dict[8] = ['J', 'X']
dict[10] = ['Q', 'Z']
def score(word):
return sum([get_score(dict, x.upper()) for x in list(word)])
def get_... |
25bf001a28be5c4ce991a62cb5392af79c3fb191 | shourya192007/A-dance-of-python | /Basics/14. CSV to JSON.py | 3,645 | 3.71875 | 4 | import csv
import json
# ------------------------------------------------------------
# TODO: FIND A EFFICIENT WAY TO INCLUDE HEADERS IN EACH ROW
# ------------------------------------------------------------
# Function to convert a CSV to JSON
# Takes the file paths as arguments
def make_json(csvFilePath, jsonFilePa... |
6e31824b3c3ccf8d4adfd26150aa3efb9e10f9d5 | anovacap/daily_coding_problem | /imp_autocomplete.py | 1,211 | 3.890625 | 4 | #!/usr/bin/python
# Daily Coding Problem - Tries: 8.1 Implement autocomplete system
class Trie:
def __init__(self):
self.ends_here = '#'
self.trie = {}
def __repr__(self): # allows print
return repr(self.trie)
def _insert(self, *words):
trie = {}
for word in words:
temp_dict = trie
for char in wo... |
6bdcc955245a8cb7b26f2c5b212b632f2097fd77 | IdeaventionsAcademy7/chapter-1-part-1-beginnings-Ninja858 | /asknumb.py | 181 | 3.9375 | 4 | import math
numb_str = input("Ennter a number: ")
numb_int = int(numb_str)
n = numb_int
n = n + 2
n = n * 3
n = n - 6
n = n / 3
print("And your number is...",n)
|
c6bf95d666d67b33e384afeb22c2ec313609dbe4 | Yoo-an/Algorithm | /Brute-Force/15650 - N과 M (2).py | 991 | 3.5 | 4 | # 문제
# 자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.
#
# 1부터 N까지 자연수 중에서 중복 없이 M개를 고른 수열
# 고른 수열은 오름차순이어야 한다.
# 입력
# 첫째 줄에 자연수 N과 M이 주어진다. (1 ≤ M ≤ N ≤ 8)
#
# 출력
# 한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다.
#
# 수열은 사전 순으로 증가하는 순서로 출력해야 한다.
answer=[0]
def findAnswer(... |
0a0394e926b61899bdd952ab401cb57b498aeb35 | albertusdev/competitive-programming | /AtCoder/ABC094/A.py | 146 | 3.609375 | 4 | A, B, C = [int(x) for x in input().split(" ")]
if A > C:
print("NO")
elif A == C:
print("YES")
elif A + B >= C:
print("YES")
else:
print("NO") |
665db8b550c90dcf3e1fffac90064aa4a6987642 | mnauman-tamu/ENGR-102 | /interactingWithTheUser.py | 676 | 3.765625 | 4 | # interactingWithTheUser.py
#
# Work together to format a list of projects and dates
#
# Muhammad Nauman
# UIN: 927008027
# September 10, 2018
# ENGR 102-213
#
# Patrick Zhong
#
# Lab 3A - 2
projects = []
dates = []
for i in range(1, 5):
projects.append(input("\nEnter the name of project %d: " % ... |
860d48a74ac4f57a0fad6bdba30e0b5418b5f403 | palcu/algo | /Contests/MindCoding-2015/runda2/pr1.py | 370 | 3.796875 | 4 | def solve(line):
x, y, z = line.strip().split()
if x == "0" and y == "0" and z == "0":
return False
x = x.replace(y, z)
x = list(x)
while len(x) and x[0] == "0":
x.pop(0)
if not len(x):
x = 0
else:
x = "".join(x)
print x
return True
while True:
value = raw_input()
c = solve(value)... |
5872d6e790035c643e70f910437f175794e66840 | Arko98/Alogirthms | /Competitive_Coding/Search_2D_Matrix_Binary_Search.py | 885 | 3.890625 | 4 | # Problem URL: https://leetcode.com/problems/search-a-2d-matrix
class Solution:
def binarySearch(self, array, begin, end, target):
mid = (begin + end)//2
while begin<=end:
if array[mid] == target:
return True
elif array[mid] < target:
... |
fc8b059aeabf699dd8816a9d3d521ad4eedd983b | zk97/lab-code-simplicity-efficiency | /your-code/challenge-1.py | 2,186 | 4.34375 | 4 | """
This is a dumb calculator that can add and subtract whole numbers from zero to five.
When you run the code, you are prompted to enter two numbers (in the form of English
word instead of number) and the operator sign (also in the form of English word).
The code will perform the calculation and give the result if you... |
7439623479d31fa7128ffaf7c48cd9be2d115883 | javedmomin99/Spam-Identifier | /main.py | 780 | 4.21875 | 4 | # Identify the spam comments from the given list below and write a code to show the user whether the comment is a spam comment or not?
options_text = ["hello","make a lot of money","buy now","how are you","subscribe this", "click this","Have a nice day"]
print(options_text)
text = input("\nplease select any 1 comment ... |
92cb3210e2c254324fe7f3ae1e0f123e99ecd7b1 | dtwin/shiyanlou_code | /squares2.py | 193 | 3.828125 | 4 | squares=[]
for x in range(10):
squares.append(x**2)
print(squares)
squares=[x**2 for x in range(10)]
print(squares)
matrix=[(z,y) for z in [1,2,3] for y in [3,2,1] if z!=y]
print(matrix)
|
2f8c8033e21ea0e7383ee2eab86181d3d2efb047 | scorp6969/Python-Tutorial | /loop/nested_loops.py | 347 | 4.375 | 4 | # nested loops = The inner loops will finish all of its iterations before finishing one iteration
# of the outer loop
rows = int(input('How many rows?: '))
columns = int(input('How many columns?: '))
symbol = input('Enter a symbol: ')
for i in range(rows):
for j in range(columns):
print(sy... |
10f8db69373d0a6515ceaddb65c66de9d49620d0 | junkwd/AizuOnlineJudge | /ALDS1_2_A.py | 512 | 4.03125 | 4 | def bubbleSort(array):
sw = 0
flag = True
i = 0
while (flag):
flag = False
for j in range(len(array) - 1, i, -1): # for (int j = array.length - 1; j > i; j--) {...}
if (array[j] < array[j - 1]):
array[j - 1], array[j] = array[j], array[j - 1] # 配列の置換
flag = True
sw += 1
... |
5b55f223e006bc75f233dfb213515810e0c4a0bd | YutingYao/leetcode-3 | /leetcode/string/14.py | 624 | 3.734375 | 4 | from typing import List
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
'''最长公共前缀
@Note:
纵向比较
'''
if len(strs)==0:
return ''
for j in range(len(strs[0])):
for i in range(1,len(strs)):
if len(... |
bf4064961fb45c50ab1dc1779e3eab843919d4e6 | bluedynamics/bda.calendar.base | /src/bda/calendar/base/inspector.py | 1,243 | 3.71875 | 4 | from datetime import datetime
from timezone import timezoneAdjuster
def dtYear(dt, context=None):
"""Return the year of dt."""
if pyDt(dt):
dt = timezoneAdjuster(context, dt)
return dt.year
return dt.year()
def dtMonth(dt, context=None):
"""Return the month of dt."""
if pyDt(dt):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.