blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8ac0d6a9297e2186fcc7034b86e85e1b0ed7ac30 | HJ23/Algorithms-for-interview- | /SetMatrixZeroes/setzero.py | 452 | 3.953125 | 4 | def set(matrix):
r,c=len(matrix),len(matrix[0])
row=[False for _ in range(r)]
column=[False for _ in range(c)]
for x in range(r):
for y in range(c):
if(matrix[x][y]==0):
row[x]=True
column[y]=True
for x in range(r):
for y in range(c):
if(row[x] or c... |
e9d965bb4e52dbc3f21dd7d2bcfb5c234d77a19a | shankar7791/MI-10-DevOps | /Personel/Rajkumar/Practice/march2/fun_fibo.py | 524 | 4.15625 | 4 | #Ceate a Function
def fibo():
# Ask for enter the number from the use
number = int(input("Enter the integer number: "))
# Initiate value
first_number=0
second_number=1
print(first_number,second_number)
count=2
# fibonacci series the integer number using the while loop
while(count<... |
14cac801c53874ca446cc03a1629023c5d679d52 | anajikadam17/myPackageAna | /myPackageAna/__init__.py | 237 | 3.921875 | 4 | def add_numbers(num1, num2):
return num1 + num2
def subtract_numbers(num1, num2):
return num1 - num2
def multiply_numbers(num1, num2):
return num1 * num2
def divide_numbers(num1, num2):
return num1 / num2
|
52218057dedc2eba7eac0f4733d2c8e1982bda51 | charlewn/python-learning | /algo-1/regExpRev.py | 1,115 | 3.796875 | 4 |
def search(pattern, text):
"""Return True if pattern appears anywhere in text"""
if pattern.startswith('^'):
return match( pattern[1:], text)
else:
return match( ".*" + pattern, text)
def match(pattern, text):
if pattern == '':
return True
elif pattern == '$':
return (text == '')
elif len(pattern) > 1 ... |
4e573b89cbdf8dd71b8378937966a300150ff0fe | victordalet/nsi | /python/TP Chevalier.py | 2,723 | 3.640625 | 4 | import random
import time
#Initialisation des points de vie
pv_chevalier=100;
pv_dragon=100;
nb_tour=1
def displayASCII():#Affichage d'un ASCII ART
"""
affiche le chevalier
"""
print(r"""
__ _
/__\__ //
//_____\///
_| /-_-\)|/_
(___\ _ //___\
( |\\_/// * \\
\_| \_((* *))
... |
eebe649c826fae690a206f7b247d02c3d1957088 | here0009/LeetCode | /Python/422_ValidWordSquare.py | 2,762 | 4.03125 | 4 | """
Given a sequence of words, check whether it forms a valid word square.
A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).
Note:
The number of words given is at least 1 and does not exceed 500.
Word length will be at least 1 a... |
76f788908fc21b1a9c8729e3bcfbfd3af4bb37ca | marcinBN/python-kindergarden | /rsa.py | 1,732 | 3.71875 | 4 | #!/usr/bin/python3
#-*- coding: utf-8 -*-
import random
def is_prime_number(n):
i = 2
while i <= (n**(0.5) + 1):
if n%i == 0:
return False
i+=1
return True
def generate_prime_number(start, stop):
while start <= stop:
if is_prime_number(start):
return start
start+=1
def gcd(a, b):
if a == b:
ret... |
24435bf75707dbd67127797861ee6773f3733ec9 | amber1710/Converter | /Operators/practice.py | 264 | 3.703125 | 4 | age={'bob':28,'sarah':29,'sally':23,'hank':22}
def isBobPresent(d):
is_present = False
for k in d.keys():
if k =='bob':
is_present = True
if is_present:
return 'The key "bob" is present! The value is ' + str(d[])
|
6d5fca0f42e625c894666d39fc35a7d188a19ae5 | Code-Law/Ex | /python/Function_ Power.py | 94 | 3.71875 | 4 | a=int(input("input a:"))
b=int(input("input b:"))
m=1
while b>0:
b=b-1
m=m*a
print(m)
|
24e6906397951bcb14274889c4ed919480a04945 | Jclayton-cell/CP1404 | /Practicals/Prac_01/loops.py | 423 | 4.0625 | 4 | for i in range(1, 21, 2):
print(i, end=' ')
print()
for x in range(0, 101, 10):
print(x, end=' ')
print()
for y in range(20, 0, -1):
print(y, end=' ')
print()
stars = "*"
num_stars = int(input("How many stars would you like?: "))
print(stars * num_stars)
print()
rows = int(input("How many rows of stars:... |
1404bde25d19df281efd417611fc2c3377d4750c | highballl/elice_study | /JeongGod/programmers/stack&queue/bridge.py | 731 | 3.515625 | 4 | from collections import deque
def solution(bridge_length, weight, truck_weights):
answer = 0
# bridge_length만큼 견딘다.
# weight만큼 무게를 견딘다.
bridge = deque([])
cur_weight = 0
i = 0
while i < len(truck_weights):
answer += 1
if len(bridge) > 0 and bridge[0][0] == an... |
006cd7165a9b71e7878929d6fcc6eb9bd6d97cbd | Salty-Potato/python-exercises-flex-02 | /python-exercises-flex-1/tip_calc.py | 454 | 3.921875 | 4 | total = input("Total bill amount? ")
total = float(total)
service = input("Level of service: (Good, Fair or Bad)? ")
split = input("Split how many ways? ")
split = int(split)
if service == "Good":
tip = total * .20
elif service == "Fair":
tip = total * .15
else:
tip = total * .10
print("Tip: ${... |
e37c4b9be58b059f3e850ffe80c1dd862197413a | dubeamit/Daily_Coding | /str_permutation.py | 468 | 3.71875 | 4 | def toString(lst):
return ''.join(lst)
def str_permute(lst, left_index, right_index):
if left_index == right_index:
print(toString(lst))
else:
for i in range(left_index,right_index+1):
lst[left_index], lst[i] = lst[i], lst[left_index]
str_permute(lst,left_index+1, ri... |
5ea386e50b6b15daaa4a5b4ac73e5366ebec7383 | mc4117/Introduction-to-Python-programming-for-MPECDT | /src/tides.py | 1,718 | 3.65625 | 4 | import pylab
import numpy as np
tide_file = open("../data/2012AVO.txt", "r")
# We know from inspecting the file that the first 11 lines are just
# header information so lets just skip those lines.
for i in range(11):
line = tide_file.readline()
# Initialise an empty list to store the elevation
elevation = []
day... |
bdc8129280f3a2100e416bebedde541b678a8b79 | rafaelgustavofurlan/basicprogramming | /Programas em Python/02 - If Else/Script2.py | 325 | 4.09375 | 4 | # Elabore um algoritmo que leia um numero. Se positivo
# armazene-o em 'a', se for negativo, em 'b'. No Final
# mostre o resultado.
#entradas
numero = int(input("Informe um número: "))
#processamento
if numero > 0:
a = numero
print("Valor positivo")
else:
b = numero
print("Valor negativo")
print(num... |
7ae252d1d39ffc50824850b64b30423703e794d0 | jennyChing/leetCode | /60_PermutationSequence.py | 956 | 4.0625 | 4 | '''
60. Permutation Sequence
The set [1,2,3,…,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between ... |
a2516f25f604377d02725f3230cd149a6404ed57 | Jamie-Cheon/Python | /section06.py | 3,429 | 3.90625 | 4 | # Section06
# 파이썬 함수식 및 람다(lambda)
# 함수 정의 방법
# def function_name(parameter):
# code
# 함수 호출
# function_name()
# 함수 선언 위치 중요
# practice 1
def hello(world):
print("Hello,", world)
param1 = "Niceman"
hello(param1)
# practice 2
def hello_return(world):
value = "Hello, " + str(world)
return value
str1 = ... |
5d229ae416ce76a724ef8a77d2644d6c8c3226fe | jcampillay8/Python-test-basicos-TDD | /monedas.py | 1,125 | 3.609375 | 4 | # monedas : escribe una función que determine cuántas monedas de 25 centavos, de 10 centavos, de 5 centavos y de 1 centavo le dará a un cliente para un cambio en el que minimice la cantidad de monedas que entrega.
# Ejemplo: dado 87 centavos, el resultado debe ser 3 cuartos, 1 centavo, 0 níquel y 2 centavos
# Prueba de... |
d865a23342821a341cdca3752c6fe40d74f53230 | ClubDosDevs/URI_Solutions | /1024/1024.py | 3,943 | 4.0625 | 4 | #função que recebe os segredos do usuario
def recebe_segredo(valor):
segredos=[]
for i in range(valor):
palavras = input('Digite seu {}° segredo\n'.format(i+1))
segredos.append(palavras)
return segredos
#primeira parte - modifica letras maiusculas e minusculas
def mod_letras(list_test):
aux_modifica = []
list... |
f17d84e38684cb5101c1aa3b6ddb2227298d5521 | diegobaron2612/copa_transparente | /exemplos/03_09_error.py | 199 | 3.546875 | 4 | import math
math = 10
print(math.sqrt(9))
Traceback (most recent call last):
File "03_09_error.py", line 3, in <module>
print(math.sqrt(9))
AttributeError: 'int' object has no attribute 'sqrt'
|
6d052e142e2e87208475192fad8e85e15d662bde | ketul-1997/assignment-1 | /odd_even.py | 234 | 3.984375 | 4 | num = [1,2,3,4,5,6,7,8,9,10]
odd= "-"
even= "-"
for i in num:
if (i % 2 ==0):
even = even.join(i)
else:
odd = odd.join(i)
print "even numbers are \n",even
print "odd numbers are\n",odd
|
5ac4aed89c62b684cdb512f1495760cb19174cd7 | bryoncodes/325-project2 | /changegreedy.py | 625 | 4.03125 | 4 | #!/usr/bin/python
'''
getchange: takes params v and c where:
v = list of coin values available for making change. Ex: [1, 5, 10, 50]
c = the value for which we will make change
Returns array A and number min, where:
A = list of numbers correlating to coins in v. Ex: [0, 0, 1, 2] means zero
pennies and nick... |
8fd944d2fdcb0e2ce250cf4525bd5c37d87f7f01 | neizod/problems | /acm/livearchive/6512-assignments.py | 342 | 3.765625 | 4 | #!/usr/bin/env python3
def main():
for _ in range(int(input())):
n, dist = [int(i) for i in input().split()]
count = 0
for _ in range(n):
speed, fuel, rate = [int(i) for i in input().split()]
count += (fuel >= rate*dist/speed)
print(count)
if __name__ == '... |
7169e04ee3ba6cc974a2ac0e2873c42cc1dfb81a | dipesh-lab/python_lang | /src/main/for_loop.py | 222 | 4.0625 | 4 | data = "star ship"
for l in data:
print("Char", l)
elements = ["nasa", "esa", "isro"];
for item in elements:
print("Element>", item)
for index in range(0, len(elements)):
print("Item>", elements[index]) |
69a6b9678d92ccf2561021cd6ea479c4cefeee25 | ptkuo0322/SI506_Fall2019 | /LAB_Exercise/Oirginal/lab_exercise_05/lab_exercise_05.py | 2,328 | 3.84375 | 4 | # START LAB EXERCISE 05
print('Lab Exercise 05 \n')
# [IMPORTANT NOTE]
# The autograder in Gradescope will directly test functions and files instead of variables
# So even though the variables printed seems right, it's possible your code didn't pass all the test cases.
# In this lab, we use txt files. Be very careful... |
d1b9a765daf875d01cf36c32bbd4d93e551701a7 | Neal0408/LeetCode | /Data_Structures/Stack/#155.py | 704 | 3.90625 | 4 | # 155.最小栈
# 设计一个支持 push,pop,top操作,并能在常熟时间内检索到最小元素的栈。
# 解题思路
# 1.比较经典的设计题,用一个辅助栈来保存现在的最小值。但是写的还是没有题解简约。还是值得学习。
import math
class MinStack:
def __init__(self):
self.stack = []
self.min = [math.inf]
def push(self, val: int) -> None:
self.stack.append(val)
self.min.append(min(val... |
ea8fe5b78f51786aac45c1c1f80fc472817018cd | shilpa5g/Python-Program- | /python_coding_practice/fibonacci.py | 314 | 4.0625 | 4 | def fib(n):
if n <= 1:
return n
else:
return(fib (n - 1) + fib(n - 2))
terms = int(input("enter the number of terms of the series: "))
if terms <= 0:
print("please enter postive number........")
else:
print("fibonacci sequence : ")
for i in range(terms):
print(fib(i))
|
bb9acc9f44602efbbd231b0c25dba3af018272b9 | zconn/PythonCert220Assign | /students/DiannaTingg/lessons/lesson01/activity/calculator/multiplier.py | 383 | 3.96875 | 4 | """
This module provides a multiplication operator
"""
class Multiplier:
"""
Returns the product of two numbers.
"""
@staticmethod
def calc(operand_1, operand_2):
"""
Multiplies two numbers.
:param operand_1: number
:param operand_2: number
:return: Product... |
ea8a3465a82ae9aa849b94a93419c0518ffa09f1 | Bieneath/LeetCode_training | /Week-1024/34.py | 1,254 | 3.53125 | 4 | # # 使用bisect
# import bisect
# class Solution:
# def searchRange(self, nums: List[int], target: int) -> List[int]:
# left = bisect.bisect_left(nums, target)
# right = bisect.bisect_right(nums, target)
# return [-1, -1] if left == right else [left, right - 1]
class Solution:
def searchRa... |
da1467b2b590e6231150cdb6ddb0e90733496848 | iconjone/Engineering-102 | /Lab4/Lab 4b/Program 1.py | 544 | 3.96875 | 4 | # By submitting this assignment, I agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
#
# Name: Jonathan Samuel
# Section: 510
# Assignment: Lab 4b Program 1
# Date: 9 25 2018
numbers = input("Pleas... |
16da508f62ddb353409ef723a4e6a6a3360ae592 | Shayennn/ComPro-HW | /2-First LAB/L01M1.py | 262 | 3.546875 | 4 | # -*- coding: utf-8 -*-
#std25: Phitchawat Lukkanathiti 6110503371
#date: 09AUG2018
#program: L01M1.py
#description: hello name and lastname
name = input("What is your name? ")
lastname = input("What is your lastname? ")
print("Hello",name,lastname)
print("Welcome to Python!")
|
3e338c244cb1a6be614b44caf7d909ffeb08ca80 | rshiv1029/Search_And_Sorts | /main.py | 911 | 3.921875 | 4 | import Search
import Sort
from constants import SEARCH, SORT
from Search.main import search_main
from Sort.main import sort_main
def main():
# Take user input for preferred searching algorithm; check if valid
while True:
option = input("Enter preferred algorithm (type 'help' for list of options): ")
... |
92585b230ef3a52bb2a7d06bd43a9d3c096d3453 | sharonk70/Book-my-movie | /Book My Movie/Price.py | 300 | 3.5 | 4 | def Ticekt_Price(a,j,c,d):
if c<=60:
Price=10
else:
if d%2==0:
if a<=d//2:
Price=10
else:
Price=8
else:
if a<=d//2:
Price=10
else:
Price=8
return Price
|
da353c0d886478acb768ff3b73d682500bc95dae | newking9088/Data-Science-Materials-from-Coursera | /Python-Classes-and-Inheritance/overridingMethod1.py | 1,584 | 4.59375 | 5 | """ Here we have a Superclass or Parentclass Book and two subclass as Ebook and
PaperBook that inherits from Book. In addition, we can use Book constructor
method to add some instance variable in each subclass. Finally, we have a
different class called Library which does not inherit anything from Book."""
class Boo... |
c11f2de9973445954e94eae9b3bc367f146fc651 | adsigua/ProjectEulerCodes | /Python/Problem 001-050/problem_026.py | 3,962 | 3.78125 | 4 | """
A unit fraction contains 1 in the numerator. The decimal
representation of the unit fractions with denominators 2 to
10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666..., and has a 1-digit
recurring cycle. ... |
2003ef209f4c6e586230e6a9d7df4459e459f635 | sunshinewxz/leetcode | /239-maxSlidingWindow.py | 763 | 3.53125 | 4 | from collections import deque
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if len(nums) == 0:
return []
sliding_win = deque()
result = []
for i in range(le... |
e238d604c1cac18637ecffa14d0229dcf288dd39 | gabriellaec/desoft-analise-exercicios | /backup/user_195/ch34_2019_03_22_13_24_02_683060.py | 285 | 3.671875 | 4 | deposito=float(input("Qual o depósito inicial?"))
juros=float(input("Qual a taxa de juros"))
tempo=24
meses=1
total=0
while meses<=tempo:
mensal=deposito*(1+juros)**i
total=total+mensal
meses+=1
print("{0:.2f}".format(mensal))
print("{0:.2f}".format(mensal-deposito))
|
d06683659c0598327742b91966bb42abf1b49d5b | gulshan-mittal/bomberman-game | /bomb.py | 4,175 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from bomberman import obj
import gameConfig
import time
import brick
class Bomb:
# This class is making bomb & give time remaining in exploding bomb.
def __init__(self, x, y):
self.x = x
self.y = y
''' set cordinates of bomb'''
def set_coordi... |
c52f9d2f70412a3a4bc26afac1b27c1319a2cc99 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/gvnlea002/question1.py | 848 | 4.21875 | 4 | """program with a recursive function to calculate whether or not a string is a palindrome (reads the same if reversed).
leandra govender
05 May 2014"""
#function to reverse the string
def reverse(word):
if len(word) == 0 or len(word) == 1: # if the string is one letter or the string is zero retur... |
cf7ce4040fdf9fdb428fa07253605c981f8e1707 | EJChavez/challenges | /Exercises/Functions.py | 594 | 3.9375 | 4 | def highest_even(*args):
mylist.sort()
mylist.reverse()
total = 0
while total < len(mylist):
if mylist[total] % 2 == 0:
print(f'{mylist[total]} is the highest even')
break
else:
total = total + 1
mylist = [10,2,3,4,8,11,100,192034821,28194657... |
cfc2415cfbe7c2095c3d8cc865cbeff60f481d1e | andresguevara99/GalaxyConflictGame | /simulation.py | 10,094 | 3.65625 | 4 | import curses
import random
from time import sleep
from bpriorityq import BPriorityQueue as PriorityQueue #--> you will need this for the pqueue!
from ships import Battleship, Cruiser, Destroyer, Fighter
from weapons import Torpedo, Railgun, Laser
from computers.random import target_ship
class Simulation:
def __init... |
a1c1248449fc07ddce4ef66ab33cdc9f42dd8653 | mcttn1/python | /parameter.py | 10,310 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 16 16:52:31 2018
@author: huashuo
"""
#Python的函数定义,除了正常定义的必选参数外,还可以使用默认参数、
#可变参数和关键字参数,使得函数定义出来的接口,不但能处理复杂的参数,还可以简化调用者的代码。
# #位置参数
# =============================================================================
# #我们先写一个计算x2的函数
# def power(x):
# return... |
a41eba028edd1affa8390edc1bf1363fc53ecb28 | naikvikrant92/Edabit | /EdaBit/Python/Convert Minutes into Seconds.py | 121 | 3.796875 | 4 | def convert(minutes):
print('Minutes to seconds',minutes*60)
return minutes*60
convert(5)
convert(3)
convert(2) |
fbf338f1131cd24f694ecd133384a323f6f73c98 | nandadao/Python_note | /note/download_note/first_month/day16/demo04.py | 1,226 | 3.859375 | 4 | """
迭代器
"""
class SkillManagerIterator:
"""
迭代器
"""
def __init__(self, data):
self.__data = data
self.__index = 0
def __next__(self):
# try:
# item = self.__data[self.__index]
# self.__index += 1
# return item
# except:
... |
9ddf58078faba411c16b3d6fb16794fe8fb4ebe0 | singh1114/ImplementingAlgorithms | /ArtificaialIntelligencelab/calendar/program.py | 191 | 3.609375 | 4 | # first import the library that handles the calendar functon
import calendar
print('Enter the year whose calendar you want to see\n')
year = raw_input()
print(calendar.calendar(int(year)))
|
22ec108c174a0ca37b1f699ed1cff07d59fe8e7b | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/70b7eccd79924c0b802d0a30f59552cf.py | 380 | 3.890625 | 4 |
def hey(message):
text = message.strip()
is_upper = text.upper() == text
is_alpha = not (text.upper() == text.lower())
if not text:
result = 'Fine. Be that way!'
elif is_upper and is_alpha:
result = 'Whoa, chill out!'
elif text.endswith('?'):
result = 'Sure.'
... |
d2adf7dd83a5d4f1fddad6d4be4b8afd7fac6b98 | SebastianAthul/pythonprog | /files/ques/objcreation.py | 368 | 3.609375 | 4 | class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def print(self):
print("name=",self.name)
print("age=",self.age)
def __str__(self):
return self.name
f1=open('athul','r')
for i in f1:
line=i.split(",")
name=line[0]
age=line[1]
obj... |
6eade07d85e25a51d4f1091ee0a80e7a83527caa | RamySaleh/Algorithms | /General/move_zeros.py | 805 | 3.609375 | 4 | #https://leetcode.com/problems/move-zeroes/
from Helpers import helper as hlp
from Helpers import test_class
import re
class Solution(test_class.test_class):
def setUp(self):
super().setUp()
def moveZeroes(self, nums):
zero = 0 # records the position of "0"
for i in range(len(nums))... |
d9506be72e8e9abed29533c9e031f0cf8214b6b8 | datAnir/GeekForGeeks-Problems | /Stack And Queue/decode_string.py | 1,953 | 4.21875 | 4 | '''
https://practice.geeksforgeeks.org/problems/decode-the-string/0
An encoded string (s) is given, the task is to decode it. The pattern in which the strings were encoded were as follows
original string: abbbababbbababbbab
encoded string : "3[a3[b]1[ab]]".
Input:
4
1[b]
3[b2[ca]]
1[a4[bccd]2[c]]
10[geeks]
Output:
b
... |
f6627841a0bfa1865ab03f9aa838868617d1bf49 | LEGEND18325/PROJECT107 | /Data.py | 389 | 3.578125 | 4 | import pandas as p
import csv
from pandas.core import groupby
import plotly_express as px
fileName = p.read_csv('StudentData.csv')
grouping=fileName.groupby(["student_id",'level'],as_index=False)['attempt'].mean()
graph=px.scatter(
grouping,
x='student_id',
y='level',
size='attempt... |
9038c1c89bffdf6eba96f13852f00597ea1f765f | bluepioupiou/advent-code | /2020/1_b.py | 320 | 3.53125 | 4 | file1 = open('1.txt', 'r')
Lines = file1.readlines()
# Strips the newline character
for x in Lines:
for y in Lines:
for z in Lines:
if int(x) + int(y) + int(z) == 2020:
print("{}".format(int(x) * int(y) * int(z)))
break
else:
continue
break
else:
continue
break |
f4299105b03cd0e3374aabe55ce86e473d1b02c8 | mansal3/Regular-Expression | /RegularExpressionFile.py | 2,095 | 4.1875 | 4 | #re is the package for regular expression
import re
sentence="Hllo everyone!i m regular epression 123"
#\d is for knowing any integer /number in the sentence
x=re.findall('\d',sentence)
print(x)
#[a-z] is for matching the set of charaters for the given range
y=re.findall('[a-z][A-Z]*',sentence)
print(y)
... |
404fff00e4c670f927ef65a788ab369ec6a485af | anillava1999/Innomatics-Intership-Task | /Task5/Task7.py | 456 | 3.890625 | 4 |
# Validating Roman Numerals in Python - Hacker Rank Solution
# Python 3
# Validating Roman Numerals in Python - Hacker Rank Solution START
thousand = 'M{0,3}'
hundred = '(C[MD]|D?C{0,3})'
ten = '(X[CL]|L?X{0,3})'
digit = '(I[VX]|V?I{0,3})'
regex_pattern = r"%s%s%s%s$" % (thousand, hundred, ten, digit)
# Do not del... |
5b9e1160c6615ac845bbbceeee6f5e892f31481f | ayoubabounakif/edX-Python | /quizz_3_part5.py | 763 | 4.28125 | 4 | # Function that accepts a positive integer n as function parameter and returns 'True'
# if n is a prime number, 'False' otherwise. Note that zero and one are not prime numbers
# and two is the only prime number that is even.
def prime_num(n):
n = abs(int(n)) # Check that n is a positive integer.
if n < 2... |
d0af2a044ff90f97fc55f002fb58a1b4e2ce1622 | msbelal/Project-Euler | /euler-045.py | 295 | 3.765625 | 4 |
def pentagonal(n) :
return (n * (3 * n - 1)) >> 1
def hexagonal(n) :
return (n * (2 * n - 1))
p = 144; pc = pentagonal(p)
h = 144; hc = hexagonal(h)
while pc != hc :
if pc > hc :
h += 1
hc = hexagonal(h)
else :
p += 1
pc = pentagonal(p)
print "Hex: ", h, hc
print "Pent: ", p, pc
|
6351bfe6fa73d1e6b96f04e775899797b35fc18b | OctaveC/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/1-search_replace.py | 131 | 3.828125 | 4 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
return [replace if ite == search else ite for ite in my_list]
|
0c00c4728ccc65303f65ae61d576c8976a02c78e | githubdacer/python_learning | /practice/get_news_recursion.py | 1,619 | 3.5 | 4 | #!/usr/bin/python3
"""
Just a routine practice: Get all the articles from 18 consecutive pages from https://enterprisersproject.com/,
and put them in a list, this to practice recursion and Web Scraping.
"""
import requests
from bs4 import BeautifulSoup
import json
pages = []
all_articl... |
8d74bb36b81e6cce1e4b734866e91552f1d4feb0 | ssebass7/PythonWorkSpace | /Inicio/Pruebas.py | 7,994 | 4 | 4 |
# -*- coding: utf-8 -*-
print('hola mundo python!!!!')
print("hola mundo python!!!!")
print(5 + 9, 5 * 6, 2 ** 3, 5 / 2)
print('hola', 'adios')
print('hola' + 'adios')
print('pruebas', 5)
print('pruebas ' * 5)
print(4 * 'HO' + 2 * 'LA')
var1 = 5
var2 = 8.4
var3 = var1 + var2
print(var3)
print(5 == 5)
print(5 == 6)... |
9e9d078884d6a46081eb8bdc6d44924aac9cf878 | imksav/gca_python | /Seriously/oop/basic_class.py | 894 | 4.03125 | 4 | class Vehicle:
def __init__(self, name, color, door, window, seats): # called as initalizer
self.name = name
self.color = color
self.window = window
self.door = door
self.seats = seats
def seat(self):
return self.seats
def description(self):
return ... |
9389c0b43144eb22209749a40112407a4518b38d | pz325/ProjectEuler | /app/solutions/problem112.py | 926 | 3.5 | 4 | '''
Bouncy numbers
1587000
'''
from util import digits
def isBouncyNumber(n):
numDigits, digitList = digits(n)
if numDigits < 2:
return False
index = 0
trend = 0
while trend == 0 and index < numDigits-1:
trend = digitList[index] - digitList[index+1]
index += 1
# print(... |
c3d817e8c61dd6bfc82c6ec011746191116f2142 | LucasMaiale/Libro1-python | /Cap4/Ejemplo 4_5.py | 793 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
@author: guardati
Ejemplo 4_5
Variante de solución del problema 4.20.
Calcula e imprime la suma de los números contenidos en
una cadena, los cuales deben estar separados por coma.
"""
cadena = input('Ingrese la cadena de caracteres: ') + ','
suma_numeros = 0
for caracter in cade... |
6265421d9485bc5d21d6399f1e5e8d858565a579 | shridharkute/sk_learn_practice | /tasks/runnnerup.py | 841 | 3.578125 | 4 | #!/usr/bin/python3
'''
This script is created to find 2st runner up from the list of the results
2 9 5 3 8 9 7
'''
# solution1
if __name__ == '__main__':
#n = int(input())
n = 5
arr = map(int, input().split())
sk = list(arr)
kk = max(sk)
NEW = []
for i in range(len(sk)):
if sk[i] !... |
c1f42e80d82754001bff50bf29f942faeced40a1 | WindAsMe/Algorithm | /venv/include/Python_Daily_5/firstUniqChar.py | 695 | 3.640625 | 4 | # !/usr/bin/python3
# -- coding: UTF-8 --
# Author :WindAsMe
# Date :18-6-13 下午2:11
# File :firstUniqChar.py
# Location:/Home/PycharmProjects/..
# LeeCode No.387
class Solution:
@staticmethod
def firstUniqChar(s):
"""
:type s: str
:rtype: int
"""
for i in ran... |
b897cb65549686d7cef309e4e2754745bea5241d | chendante/search-homework-backend | /project/models/indexlist.py | 1,262 | 3.53125 | 4 | #每个词项的结构
class Node:
def __init__(self, word, id):
self.word = word
self.id = [id]
self.df = 1
#在该词项中添加一个歌曲ID
def addID(self, Sid):
if self.id.count(Sid) == 0:
self.id.append(Sid)
self.df += 1
def getJson(self):
return {
'term... |
c70727628d640571bf9cae4f89f161488358f0a4 | ufo9631/pythonStudy | /list1.py | 1,226 | 3.796875 | 4 | weekday=['Monday','Tuesday','Wednesday','Thursday','Friday']
print(weekday[0])
all_in_list=[
1, #整数
1.0, #浮点数
'a word', #字符串
print(1),#函数
True,#布尔值
[1,2],#列表中套列表
(1,2),#元组
{'key':'value'} #字典
]
fruit=['pineapple','pear']
fruit.insert(1,'grape') #列表增加,insert方法必须指定在列表中要插入心得元素位置,插入元素的实际位... |
58df166f43b9fe8bebe0bc8bcefcb68976e0e2f7 | jasonadu/quant-python | /code/chapter3-1.py | 289 | 3.734375 | 4 | # -*- coding: UTF-8 -*-
# tuple
t = type((1, 3, 5, 7))
print(t)
# str
t = type('pi')
print(t)
# bool
t = type(5 > 6)
print(t)
# dict
t = type({"Heigh": 7.45, "Low": 7.30})
print(t)
# list
t = type(["Hello World", 3, 4, ("a", "b"), True])
print(t)
# set
t = type({"3", "5"})
print(t)
|
d7266d50453484aaa1aa7157474b9ed47ef962ff | ace034/PDX_Labs_and_Other_Assignments | /RPSv2.py | 1,576 | 3.609375 | 4 | import random
import os
os.system('cls' if os.name == '**' else 'clear')
#trying to allow for any input :\n is the new line command preoper use is within the print section
user_respose = input('Do you wanna play rock paper scissors "Y" or "N "?:\n')
no = ['N' , 'n' , 'no' , 'NO' , 'No']
yes = ['Y' , 'y' , 'yes' , 'YES'... |
c54d2044711f38389bee59c5569272e087462f13 | gdaniel4/CIS-2348-14911 | /HW3/11.27 CIS 2348.py | 3,146 | 3.96875 | 4 | # Gabriel Daniels
# PSID 1856516
# establishes roster dictionary
roster_dict = {}
# initializes i
i = 1
#loops until there have been 5 loops
for i in range(1, 6):
jersey_number = int(input("Enter player {}\'s jersey number:\n" .format(i)))
rating = int(input("Enter player {}\'s rating:\n" . format(i)... |
c5046a8ae2578c077d188311cbfa86b994b0de87 | ftlka/problems | /leetcode/decode-string/solution.py | 898 | 3.59375 | 4 | def decodeString(s):
if not s:
return
ar = []
i = 0
while i < len(s):
if s[i].isdigit():
if i > 0 and s[i-1].isalpha():
ar.append('\'')
ar.append('+')
num = s[i]
while s[i+1].isdigit():
i += 1
... |
7e8c9b9f6ce090ea2780a1f00eda5ba1904e7467 | spandanasalian/Python | /map.py | 587 | 3.96875 | 4 | lis=[1,2,3,4,5,6,7]
square_str=[]
def square(lis):
for item in lis:
square_str.append(item**2)
return square_str
print(square(lis))
#indentation take into
listt=[1,2,3,4,5,6,7,8]
def square(num):
return num**2
print(list(map(square,listt)))
#list function to get the result in the form o... |
b199e8c3016f76371abc9af9842cdc361987ca16 | timManas/Practice | /Python/project/src/LinkedList/ConvertBinaryNodeToInt/ConvertBinaryNodeToInt.py | 1,016 | 3.890625 | 4 | class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def getDecimalValue(self, head):
# Step1 - Create output variable
stringBinary = ""
# Step2 - Traverse head Node
while head != None:
# Ste... |
a7c23a549ef84507dcde14d4624d0bfc5d6e3227 | dmacdonald83/ICTPRG-Python | /Files/Quiz Question 2.py | 231 | 3.65625 | 4 |
names = []
name = input("Enter name: ")
while len(name) > 0:
names.append(name)
name = input("Enter name: ")
out_file = open('people.txt', 'w')
for n in names:
out_file.write(n + "\n")
out_file.close()
|
721a99278681b326d097dc2bbb6976e6e3906887 | GuSilva20/Primeiros-Codigos | /Ex027AlistamentoExercito.py | 561 | 4.1875 | 4 | from datetime import date
nome = str(input("Qual seu nome? ")).strip()
print("O Nome inserido é valido? {}".format(nome.isalpha()))
idade = int(input("Ano de Nascimento? "))
ano = int((date.today().year))
if (idade - ano) == 18:
print("Você esta no periodo do excercito!!")
elif (ano - idade) >= 18:
print("voc... |
d14f41732068d9148e4c4c706f2115fab5c3c215 | essenceD/GB | /Lesson_1/HW#5.py | 564 | 4.03125 | 4 | procs, costs = int(input('Enter a proceeds of your company: ')), int(input('Enter a costs of your company: '))
if procs > costs:
print('\nGood news! Your company is profitable!\n\nYour company\'s profit is: {}\nYour company\'s profitability is {}'
.format(procs - costs, (procs - costs) / procs))
emplo... |
88160f9db5def6ec6e78c60c46dfe06057a96fee | AdnanSalah84/Getting-Started-With-Python | /Sequences/slicing-and-for-loops.py | 244 | 3.859375 | 4 | colors = ['red', 'blue', 'green', 'yellow']
# print(colors[1])
# print(colors[1:])
# print(colors[:1])
# print(colors[1:3])
# for color in colors:
# print(color)
for index, color in enumerate(colors, start=1):
print(index, color)
|
3a282a6e5daad8846ba825fa4c5fb2cfd32ec05e | GitEtec/PassagemDeArgumentos | /Aula8Passagem_Argumentos.py | 294 | 3.59375 | 4 | import sys
args = sys.argv #arg1 = metodo // arg2 = n1 // arg = n2
def soma(n1,n2):
return n1 + n2
def sub(n1,n2):
return n1 - n2
if args[1] == "soma":
resp = soma(float(args[2]), float(args[3]))
elif args[1] == "sub":
resp = sub(float(args[2]), float(args[3]))
print(resp) |
01c3e0e902c4c6136ca9850f5fe07d18cebc20c1 | darr/offer_algri | /offer_algri/整数中1出现的次数/p.py | 1,400 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#####################################
# File name : p.py
# Create date : 2018-07-23 08:49
# Modified date : 2018-07-23 13:04
# Author : DARREN
# Describe : not set
# Email : lzygzh@126.com
#####################################
class Solution:
#run:30ms memory:5... |
4acaf052a1bf2a5cf423a5053ebe0f26b38b26f2 | ljm9104/advanced_python_study | /chapter04/try_except_finally_test.py | 670 | 4 | 4 | """
with语句上下文管理协议实现__enter__和__exit__魔法函数
try except else finally
return语句执行,若finaly里有return执行finally里面的,若没有就执行之前,try,except,else
"""
def exe_try():
try:
print ("code started")
raise KeyError
return 1
except KeyError as e:
print ("key error")
return 2
else:
... |
30642c722526002be86dff110d79a52678d41777 | ejhusom/FYS-STK4155 | /exercises/exercise-2-4.py | 3,816 | 3.6875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Exercise 2
# In[1]:
# Exercise 2.1: Own code for making polynomial fit
import numpy as np
import matplotlib.pyplot as plt
import sklearn.linear_model as skl
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
try:
from jupyterthemes import jtp... |
133243229e2c81b48bb7e5bcd0b8484c39abe9ba | Hyo-gyeong/likelion-python-exercise | /first.py | 311 | 3.875 | 4 | number2 = int(input("첫번째 숫자를 입력하세요 : "))
number3 = int(input("두번째 숫자를 입력하세요 : "))
print("숫자의 합은",number2 + number3)
banjang = "신효경"
print("우리반 반장 이름은", banjang)
print(1+2)
print("멋쟁이 사자처럼")
number = 3
print(number+3)
|
d1d8720b3f965c936ef64e53b70f2a8164b7a7f8 | adamaguilar/LeetCode | /2AddTwoNumbers.py | 1,204 | 3.84375 | 4 | '''
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itsel... |
0b1479be09ea5a244b763f2d94c7e61f87c68273 | KarolJanik-IS/pp1 | /04-Subroutines/zadanie27.py | 454 | 3.578125 | 4 | #27
import re
s = "Nam strzelać nie kazano. Wstąpiłem na działo. I spojrzałem na pole, dwieście armat grzmiało. Artyleryji ruskiej ciągną się szeregi, Prosto, długo, daleko, jako morza brzegi."
samogloski = ['a','e','y','i','o','ą','ę','u','ó']
#cyfry = re.findall('\d',line)
for x in samogloski:
samogloska = re.fin... |
afe1a2a347694631a815a2d15faa3c39ea2b5356 | AyubQuadri/Python---Sessions | /Day 7 Lists/Code/Comprehensions.py | 434 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 22 08:48:41 2017
@author: Acer
"""
# normal way of writing for loop to print odd numbers
for x in (range(10)):
if x%2 != 0:
print x
# using Comprehensions print odd numbers
odd = [i for i in range(10) if i%2 != 0]
odd
# Even numbers using for loop
for x in (r... |
01c0587b485f8e50cddcf3c935e789e11369b1ba | Deepak-Deepu/Edx-mit-6.00.1x | /Week 6 Problem set/1Build the ShiftDictionary and ApplyShift.py | 3,319 | 3.8125 | 4 | class Message(object):
### DO NOT MODIFY THIS METHOD ###
def __init__(self, text):
'''
Initializes a Message object
text (string): the message's text
a Message object has two attributes:
self.message_text (string, determined by input text)
... |
5ae5d0fc72ed5b058836f7058c43ebcc5ef6d22f | tcltsh/leetcode | /leetcode/src/13.py | 700 | 3.5 | 4 | class Solution(object):
ROMA = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
ROMA_TO_INT = [1, 5, 10, 50, 100, 500, 1000]
def add(self, c, next):
if next == '0' or self.ROMA.index(c) >= self.ROMA.index(next):
ind = self.ROMA.index(c)
return self.ROMA_TO_INT[ind]
else:
... |
813a8dc9710639a1a057d97f03765705924bbbd4 | PhilippSchuette/projecteuler | /py_src/problem002.py | 2,226 | 3.984375 | 4 | # Project Euler Problem 2 Solution
#
# Problem statement:
# Each new term in the Fibonacci sequence is generated by adding
# the previous two terms. By starting with 1 and 2, the first 10
# terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values
# do not... |
f1c325ac6b788f5586ff815d3137b2fce0629cef | MrScabbyCreature/Chinese_phonetics | /chinese.py | 8,732 | 3.859375 | 4 | import pandas as pd
import numpy as np
from random import shuffle
from IPython.display import display as display_dataframe
print("Practice what?\n1) Left column(hanze->pinyin) \n2) Right column(meaning->hanze+pinyin)")
choice = input()
### left column
if choice == '1':
df = pd.read_excel("left_row.xlsx")
if '... |
c17bd0bd263a32b11c893fa1910a43bf94d4bf61 | vkvikaskmr/ud036_StarterCode | /media.py | 921 | 4.21875 | 4 |
class Movie():
"""This class is used to store and display Movie related informations"""
VALID_RATINGS = {
"General": "G",
"Parental_Guidance": "PG",
"Parents_Strongly_Cautioned": "PG-13",
"Restricted": "R"
}
def __init__(
self,
movie_title,
... |
3b5c7d30961c6f37af3297ab4d15c1c48e627c69 | sureshmelvinsigera/ssdcs-pcom7e-aug-seminar-3 | /calculating_factorial_3ways.py | 757 | 4.34375 | 4 | ####################################################################################
# Three ways to calculate factorial:
# a) Using a function from the math module;
# b) Using for loop;
# c) Using recursion.
####################################################################################
# a) Using a function fr... |
09199ad43ac386b6375fdc20bc811e26ae4bb0f2 | kinsey40/minesweeper | /src/buttons_script.py | 10,369 | 4.03125 | 4 | """
Author: Nicholas Kinsey (kinsey40)
Date: 10/12/2017
Description:
This file contains the Create_Button class, which is used to define how the
buttons in the grid behave when clicked.
Also contained within this file is the create array function, which decides
where the mines should be placed and calculates the rel... |
b727eb6e60aafcad6f26233c03bc5ab637bc363d | Progradius/DeltaV_Calc | /DvCalc.py | 1,021 | 3.5 | 4 | # This tool helps you calculate
# the Delta-v of your spacecraft
#
# |
# / \
# / _ \
# |.o '.|
# |'._.'|
# | |
# ,'| | |`.
# / | | | \
# |,-'--|--'-.|
from math import log
while True:
print("Entrez 'dv' pour calculer le Delta-v de votre engin spatial")
print("Entrez... |
44c650636d404884b3fbbae6011daa79aa3bf6a2 | nbthales/cev-python | /ex044.py | 1,377 | 3.703125 | 4 | #DESAFIO 044
#ELABORE UM PROGRAMA QUE CALCULE O VALOR A SER PAGO POR UM PRODUTO,
#CONSIDERANDO O SEU PREÇO NORMAL E CONDIÇÃO DE PAGAMENTO:
#À VISTA DINHEIRO/CHEQUE: 10% DE DESCONTO
#À VISTA NO CARTÃO: 5% DE DESCONTO
#EM ATÉ 2X NO CARTÃO: PREÇO NORMAL
#3x OU MAIS NO CARTÃO: 20% DE JUROS
print('='*11, 'LOJAS TERRA', '... |
5dc8e4496647d275688456571598cb0fec5a8272 | Xiristian/Linguagem-de-Programacao | /Exercícios aula4/Exercicio12.py | 109 | 3.625 | 4 | milhas = float(input("Digite a distancia em milhas: "))
km = milhas * 1.61
print("A distancia em km é:", km) |
454b9311a49a296fb547156efe0ef7f23778228a | odwanodada/Graph-and-Mean-Mode-etc-Python | /Data Distribution Exercise.py | 432 | 3.875 | 4 | import matplotlib.pyplot as plt
test_scores = [12,99,65,85,42]
test_names = ["Andy", "Martin", "Zahara", "Vuyo","Ziyaad" ]
test_graph = [x for x ,_ in enumerate(test_names)]
plt.bar(test_graph, test_scores, color="blue")#to display numbers on the Y or left side
plt.xticks(test_graph, test_names)
plt.title("Python Mar... |
4517eba39b4286e9609df736bf7136e1a95477ef | MMVonnSeek/Hacktoberfest2021_beginner | /Python3-Learn/some modules/calculator_avyayjain.py | 595 | 4 | 4 | // AUTHOR: Avyay Jain
// Python3 Concept: (calculator)
// GITHUB: https://github.com/avyayjain
import operator
my_string = input("input what you want to calculate = ")
print(my_string)
def get_operator_fn(op):
return{
'+':operator.add,
'-':operator.sub,
'*':operator.m... |
c0b10be067a08ebc25c39d8335c54f89a8355e64 | yfdoor/MyPython | /00_PythonStudy/Example3.py | 448 | 4.03125 | 4 | # Copyright (c) 2019. Daniel's python study project.
# 题目:输入三个整数x,y,z,请把这三个数由小到大输出。
# 程序分析:我们想办法把最小的数放到x上,先将x与y进行比较,如果x>y则将x与y的值进行交换,然后再用x与z进行比较,如果x>z则将x与z的值进行交换,这样能使x最小。
l = []
for i in range(3):
x = int(input('整数:\n'))
l.append(x)
l.sort()
print(l)
|
48e22ac0a2054ea0f4926b48976accd838d381db | dkumar95120/python | /pytest/test_math.py | 725 | 4.34375 | 4 | def add(x, y):
"""[summary]
Arguments:
x {int} -- first number
y {int} -- second number
Returns:
int -- sum of two numbers
"""
return x + y
def subtract(x, y):
"""subtract y from x
Arguments:
x {int} -- first number
y {int} -- second number
... |
9b385d2da982fc8702d9f8681a12fbd411a5a08f | ilyaveryasov/hexlet_tests | /bin_plus_bin/bin_conversion.py | 289 | 4.4375 | 4 | def bin_conversion(number):
"""Decimal to bin conversion function, only for number > 0"""
result = ''
while number >= 1:
if number % 2 > 0:
result = '1' + result
else:
result = '0' + result
number = number // 2
return result
|
31ae41943e133922683ecb946d06943c74223857 | jerryhanhuan/LearnPython | /datastruct/sort/shell_sort.py | 1,082 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
#File Name:shell_sort.py
#Created Time:2019-09-20 02:42:45
'''
将待排序数组按照步长 gap 进行分组,然后将每组的元素利用直接插入排序的方法进行排序,
每次将 gap 折半减小,循环上述操作,当 gap = 1时,利用直接插入方法,完成排序。
总体实现应该 由 三个循环完成
1. 第一层循环:将 gap 依次折半,对序列进行分组,直到 gap = 1
2. 第二,三层循环,则是直接插入排序的两层循环
'''
def shell_sort(L):
length ... |
cdfd11dc8da894131509639328b92b31d833409b | eliasssantana/logicaProgramacao | /Exercício 3 - verificação de aprendizagem.py | 1,557 | 4.15625 | 4 | print("=-" * 30)
e = 'Exercícios'
print(e.center(50))
print("=-" * 30)
# 03)
'''
- Utilizando estruturas de repetição com teste lógico, faça um programa que peça uma senha para iniciar seu processamento. Não deixe o usuário continuar se a senha estiver incorreta, após entrar d-vindas a seuê as boas usuário e apresente... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.