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 |
|---|---|---|---|---|---|---|
6d595915c78424f87e1b1587dcc1d00472fa200f | Mansi1096/testrepo | /strings.py | 364 | 3.765625 | 4 | <<<<<<< HEAD
for i in range (0,6):
n=input("enter the strings")
m=input("enter the character")
if m is n[0]:
print(n)
else:
print("wrong!!!")
=======
for i in range (0,6):
n=input("enter the strings")
m=input("enter the character")
if m is n[0]:
print(n)
else:
print("wrong!!!")
>>>>>... |
5ab04ddcf6089a09688aad722abdca9aa214acbc | Cxov80415/Eric_PsychoPy2018 | /ex18.py | 460 | 3.796875 | 4 | def print_three(*args):
arg1, arg2, arg3 = args
print ("arg1: %r, arg2: %r, arg3: %r" % (arg1, arg2, arg3))
def print_three_again(arg1, arg2, arg3):
print ("arg1: %r, arg2: %r, arg3: %r" % (arg1, arg2, arg3))
def print_one(arg1):
print ("arg1: %r" % arg1)
def print_OK(arg3):
prin... |
0afcdd1b460d404300305ada8fbcd91fc78611db | threexc/SYSC5001 | /assignment_3/test_uniformity.py | 739 | 3.53125 | 4 | #!/usr/bin/python3
# test_uniformity calculates the max D value for evaluating data sets with the
# Kolmogorov-Smirnov test
def test_uniformity(filename):
data = []
D_plus_values = []
D_minus_values = []
count = 0
with open(filename) as f:
for line in f:
data.append(float(line.strip('\n').replace('"',''))... |
d078ba46d8fe58b23aaf3265655069a50d016e02 | orez-/Orez-Summer-2012 | /Tactics/skills.py | 7,367 | 3.625 | 4 | import pygame
import random
import sys
from string import lowercase as alphabet
from math import cos, sin, pi
from constants import SCREEN_SIZE
try:
seed = int(sys.argv[1])
except:
seed = random.randint(0, 2 ** 32 - 1)
random.seed(seed)
print seed
vowel = "aeiou"
consonant = ''.join(filter(lambda x: x not in... |
dc15be912cf9927fb8882770b25a2dba9a680fe3 | bhornung/python-utilities | /source/io_utils.py | 1,455 | 3.953125 | 4 | def load_from_json(path_to_db):
"""
Loads the contents of a json file.
Parameters:
path_to_db (str) : full path to a json file.
Returns:
data_ (object) : the loaded object.
"""
with open(path_to_db, 'r') as fproc:
data_ = json.load(fproc)
... |
35617eb0f37c0dbe7c5c79740d7d1a97c3818f9c | jchamish/python3-algorithms | /Daily_code_problems/anytwo_numbers_add_up_k.py | 898 | 3.890625 | 4 | # Problem Number 1
# Good morning! Here's your coding interview problem for today.
#
# This problem was recently asked by Google.
#
# Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
#
# For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
#
# ... |
2b1a783d4c28b82fd0d0aa2b57f00d2427163544 | maskani-moh/algorithms | /island_size.py | 3,003 | 4 | 4 | """
Two solutions presented for the Exercise 695 of Leetcode.
The aim is to find the maximum area of an island given a binary grid.
The idea is to find the maximum size of the connected component (4 directions)
in the grid.
Method: Depth-first Search
"""
def maxAreaOfIsland(grid):
"""
Function returning the... |
4a3edaf4fd696b7a6ab15bbf2031299c04c1ddf8 | hautbli/algorithm | /programmers_codingtest/level1/codingtest1_ex16.py | 472 | 3.75 | 4 | # 행렬의 덧셈
def solution(arr1, arr2):
answer = []
for ar1, ar2 in zip(arr1, arr2):
line = []
for a1, a2 in zip(ar1, ar2):
line.append(a1 + a2)
answer.append(line)
return answer
print(solution([[1, 2], [2, 3]], [[3, 4], [5, 6]]))
import numpy as np
def sumMatrix(A, B)... |
8295833dcb16487914fb9e42e15439091cc442fe | sanskarjain2507/full-stack-development | /Django/Automobile shop/class_practice/class1.py | 411 | 3.8125 | 4 | class Student:
'''this is class'''
clg_name='bit'
def __init__(self):
self.__name="sanskar jain"
self.age=20
def input(self):
self.__name="sanskar"
self.age=20
def show(self):
print(f"name: {self._Student__name}")
print(f"age: {self.age}")
pri... |
8053045835240b92902ae0ad6ca65defcadf73a3 | NikitaKirin/Linear-equation-solver-calculator | /main.py | 1,212 | 3.78125 | 4 | import core.method_of_Cramer as calc
matrix_of_variables = []
matrix_of_free = []
count_line = 0
count_free_line = 0
while True:
line = input(
'Вводите коэффициенты при неизвестных построчно через пробел! - для остановки ввода введите Stop' + '\n')
if line == "Stop":
break
else:
lin... |
17b7b272d6760d87db456fea41ca171e99ed9cce | manoj0806/progate-python | /python_study_2/page4/script.py | 192 | 4.125 | 4 | fruits = ['apple', 'banana', 'orange']
# Get the elements of fruits using a for loop, and print 'I like ___s'
i=0
for fruit in fruits :
print("I like " +fruits[i],"s")
i+=1
|
23565631a8aa3b716b7d974a8d5f9b359c91b9d2 | paulettemaina/password_locker | /password_locker.py | 7,145 | 3.625 | 4 | #!/usr/bin/env python3.6
import pyperclip
import string
import random
from user_credentials import User, Credentials
def create_user(login, pword):
'''
Function to create a new user
'''
new_user = User(login,pword)
return new_user
def save_users(user):
'''
Function to save user
'''
... |
a8c3af298eb233d532edbf4186168d230c30cbb4 | asfinahamza/python_basics | /palindrome.py | 655 | 3.828125 | 4 | # str=input('enter a word : ')
# status=0
# l=len(str)
# for i in range(0,int(len(str)/2)):
# if(str[i] != str[l-i-1]):
# status=1
# if(status==1):
# print('no')
# else:
# print('yss')
# string=input('enter the string: ')
# rev_str=string[::-1]
# print(rev_str)
# if(string==rev_str):
# print(... |
60b1548ca27bdb9be62743c75f1409683a9e5e19 | vishwanath79/PythonMisc | /Py201/29Lock.py | 534 | 3.53125 | 4 | from multiprocessing import Process, Lock
def printer(item,lock):
""" Prints out the item that was passed in """
lock.acquire()
print('process')
try:
print(item)
finally:
lock.release()
if __name__ == '__main__':
lock = Lock()
items = ['tango', 'foxtrot', 10]
# Loop o... |
125dba0146620cdff4e0353f63e7123411cf6be6 | ThisIsRoy/leetcode | /easy/rotated-digits.py | 806 | 3.703125 | 4 | # Runtime can be improved
class Solution(object):
def rotatedDigits(self, N):
"""
:type N: int
:rtype: int
"""
count = 0
for num in range(N + 1):
if self.valid_rotate(num):
count += 1
return count
... |
18be706141e79076e3c674dcb8dec85a1d50048d | Wolverinepb007/Python_Assignments | /Python/greater.py | 174 | 4 | 4 | a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
if(a>b):
print(a," is greatest the number.")
else:
print(b," is greatest the number.")
|
9054372d90ef79898c94434adcf32331c389b29a | YiHerngOng/ME599 | /ME599_HW3/optimizer.py | 1,610 | 3.65625 | 4 | #!/usr/bin/env python
#Written by Yi Herng Ong
#ME 599 Homework 3
#Note: This code takes about 2 seconds to compute the lowest cost
import numpy as np
def optimize(simulator, record_waypoints, done):
baseline_cost = simulator.evaluate([(-10, -10), (10, 10)])
waypoints = [(-10, -10), (0, 0), (10, 10)]
re... |
8c1da0f90add339328ae60f632520d7be392e1fb | rapidcode-technologies-private-limited/Python | /medhavi/assignment1/7.py | 149 | 4.09375 | 4 | #python program to swap two elements in a list
array=[1,2,35,4]
t=array[0]
array[0]=array[1]
array[1]=t
print('after'+' '+ 'swaping'+' '+'=',array)
|
69f032b2c01996a8cc55e4793adb573e076f4f8d | panditdandgule/Pythonpractice | /Fibonacci.py | 431 | 4.34375 | 4 | # Program to display the Fibonacci sequence up to n-th term where n is provided by the user
n=int(input())
n1=0
n2=1
count=0
if n<=0:
print("Please enter a positive number")
elif n==1:
print('Fibonacci sequance upto:',n)
print(n1)
else:
print('Fibonacci sequance upto:',n)
while cou... |
5f4d2fa34d042b71e861815b3b9a645fb55b9a04 | J4VJ4R/pythonCourse | /conditionals/if.py | 152 | 3.890625 | 4 | #!/usr/bin/python3
uno = 15
dos = 15
if uno < dos:
print ("is menor")
elif uno == dos:
print ("Vamos al mar")
else:
print ("es more big")
|
6ae2a5d02c4da06fb0a46b721b807cc34759ef2e | d1sd41n/holbertonschool-machine_learning | /math/0x03-probability/binomial.py | 1,581 | 3.75 | 4 | #!/usr/bin/env python3
"""docs"""
class Binomial():
"""docs"""
def __init__(self, data=None, n=1, p=0.5):
"""docs"""
if data is None:
if n <= 0:
raise ValueError("n must be a positive value")
elif p <= 0 or p >= 1:
raise ValueError("p mu... |
13d336c2bccc88b11793702bbbff85138d8d090d | Oking123/CFG_Generator | /recursion.py | 370 | 3.796875 | 4 | x = 0
y = 0
signal = [True]
if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]):
print(1)
if grid[x][y] == 1:
print(1)
else:
if x == 0 or x == len(grid) - 1 or y == 0 or y == len(grid[0]) - 1:
signal[0]= False
grid[x][y] = 1
travel(x - 1, y, signal)
travel(x + 1, y, signal)
trav... |
f60c00c8e7adf14ff95416c9f518d8a4672e3750 | Iararibeiro/coding-challenges | /easy/arrays/MaximumSubArray.py | 629 | 3.5 | 4 | def solution(nums):
result = float('-inf')
for i in range(0, len(nums)):
current_sum = 0
for j in range(i, len(nums)):
current_sum += nums[j]
result = max(result, current_sum)
return result
def solutionDP(nums):
currentSubArray = nums[0]
maxSubArray = nums[... |
4f1ebb0f1b25ea6a4cd9622a46ee0d3cade33f60 | suifengqjn/python_study | /7迭代器与生成器/1什么是迭代协议.py | 435 | 4.0625 | 4 |
# 迭代器是什么
# 迭代器是访问集合内元素的一种方式,一般用来遍历数据
# 迭代器和用下标访问的方式不一样,迭代器是不能返回的
# 只要实现 __iter__ 就是可迭代的 成为迭代器还需要实现 __next__
from collections.abc import Iterable,Iterator
list = [1, 2, 3, 4]
# 创建迭代器对象
it = iter(list)
print(isinstance(it, Iterable))
print(isinstance(it, Iterator))
|
4f5a0579f48fe6b2d4395730c69fe4a5281a35e0 | Sean-Moon/algo | /goorm5.py | 1,074 | 3.5625 | 4 | #-*- coding: utf-8 -*-
#알파벳 빈도
from collections import Counter
texts = input().split()
lower_caracters = []
while(texts):
lower_caracters += list(texts.pop().lower())
counter = Counter(lower_caracters)
print("a : %s" % counter['a'])
print("b : %s" % counter['b'])
print("c : %s" % counter['c'])
print("d : %s" % c... |
4f4e50bf42368947439e225128fa9a5803bc57f3 | cairoas99/Projetos | /PythonGuanabara/exers/listaEx/Mundo2/ex063.py | 163 | 4.09375 | 4 | n = int(input('Insira um numero: '))
c = 0
def fib(x):
if x == 1 or x == 2:
return 1
elif x > 0:
return (fib(x-1)+fib(x-2))
print(fib(n)) |
674095b45964b534f92ebe09f600ef0ec686dae6 | nikita-chudnovskiy/ProjectPyton | /00 Базовый курс/Zadachi/011 Строки методы/07 Сколько раз встречается буква h 1 или больше.py | 601 | 4 | 4 | # Если она встречается более 2 раз выведите индекс 1 и посл числа
a = 'hello world'
print(a.count('l'),'вхождения') # ищем сколько вхождений
if a.count('l')==1: # если 1 то пишем
print(a.find('l')) # под каким индексом
elif a.count('l')>=2: # если находим больше 2
print('... |
10d802bbb014cb3bc871fdd00551c20cfaa5ddf9 | Renwoxin/leetcode | /array/hg_832_Flipping_an_Image.py | 3,024 | 4.40625 | 4 | """
Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the
resulting image.To flip an image horizontally means that each row of the image is reversed.
For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].To invert an image means that
each 0 is replaced by 1, and... |
30ccd0ae2a813d68d6d31c42be7d3771d575b7d1 | syurskyi/Python_Topics | /060_context_managers/_exercises/104. Generators and Context Managers - Coding.py | 3,835 | 3.703125 | 4 | # # Generators and Context Managers
# # Let's see how we might write something that almost behaves like a context manager, using a generator function:
#
# print('#' * 52 + ' ### Generators and Context Managers')
#
#
# ___ my_gen
# t__
# print('creating context and yielding object')
# lst _ 1 2 3 4 ... |
3c71007ba3f92f9f1ace1c84bf59de88b14da17a | AlphaCoderX/MyPythonRepo | /Assignment 8/Weather.py | 1,060 | 3.734375 | 4 | #Programmer Raphael Heinen
#Date 4/18/17
#Version 1.0
import json
import urllib2
import functions
def readJson():
city = functions.userString("Please enter a zip code or city name:")
print " "
url = 'https://api.apixu.com/v1/current.json?key=dcb629e49c894492b66150648172303&q=' + city
jsonTxt ... |
490a2df88ffd95d3dfb014c40e1dc118ea6490dc | divyansh-gupta-0210/BinarySearch.io | /LongDistance.py | 1,018 | 3.5 | 4 | # Long Distance
# Given a list of integers nums, return a new list where each element in the new list is the number of smaller elements to the right of that element in the original input list.
# Constraints
# n ≤ 100,000 where n is the length of nums
# Example 1
# Input
# lst = [3, 4, 9, 6, 1]
# Output
# [1, 1, 2, 1,... |
5233789df7e1c181a6b01480fdd40b563808d51f | sarabudlasoumyasri/20176080_Competitive-Programming | /Competitive-Programming/week-3/day5/url.py | 1,103 | 3.875 | 4 | def Base(string):
dict1={}
for i in range(len(string)):
dict1[i]=string[i]
return dict1
short = 7
shorturl={}
Long={}
count=0
base=Base("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
def shortmethod(url):
if (url in Long):
print("ShortURL Exists"+Long[url])
return
global count
s=""
k... |
96e66221ceebd0b1653fce8eb8931d29ab48d9a5 | zspatter/network-simulation | /network_simulator/ConnectivityChecker.py | 4,071 | 3.84375 | 4 | from typing import Set, Optional
from network_simulator.Network import Network
class ConnectivityChecker:
"""
This class determines whether a given network is connected or not.
In a connected network, there exists a path between any given node
and all other nodes (no nodes exist that cannot be reach... |
6793c72a499bae6029fc4a0736cbc51e48c76563 | EPAlmighty/cti110 | /M6T2_Pinnell.py | 308 | 3.875 | 4 | #CTI 110
#M6T2- Bug Collector
#Evan Pinnell
#11/29/17
def main():
total = 0
for day in range(1, 8):
print('Enter the bugs collected on day', day)
bugs = int(input())
total += bugs
print('You collected a total of', total, 'bugs')
main()
|
2cc01678177ec762442fd1b71258e799cf53659f | asherLZR/algorithms | /graphs/kruskals_mst.py | 1,107 | 3.5 | 4 | from abstract_data_types.union_find import UnionFind
# initialisation of input values
vertex_count, edge_count = map(int, input().split())
U, V, W = [0] * edge_count, [0] * edge_count, [0] * edge_count
for i in range(edge_count):
U[i], V[i], W[i] = map(int, input().split())
edge_list = sorted(zip(U, V, W), key=lam... |
c1d62dcc63b0a8205ac14ae5d9d80f88e1f23f52 | tsjabie-o/Advent-of-Code-2020 | /Day 6/main.py | 998 | 3.609375 | 4 |
from typing import MutableMapping
def ParseInput():
with open("./Day 6/data.txt") as data:
rawdata = data.read()
groups = rawdata.split("\n\n")
groups = [group.replace("\n", " ") for group in groups]
return groups
def CountQuestions1(group):
questions = list()
for char in group:
... |
81ce842c498e71e2fffcf79700f8eb187735f79b | BotOreo/Python-Files | /ngram_test_zaim.py | 3,785 | 3.59375 | 4 | import re
di_unigram={}
di_bigram={}
di_trigram={}
di_unigram_count = {}
di_bigram_count = {}
di_trigram_count = {}
di_probability = {}
def ngram():
#using "with" will close the file immediately after last call
with open("text-ngram.dat","r") as rfile:
infile = rfile.readlines()
... |
f1040f6df9cdffcbf08c2b6db00a610b31cf5558 | BMariscal/study-notebook | /coding_interview_patterns/sliding_window/max_sum_arr_size_k.py | 557 | 3.515625 | 4 | # Given an array, find the average of all contiguous subarrays of size ‘K’ in it.
# Array: [1, 3, 2, 6, -1, 4, 1, 8, 2], K=5
# Output: [2.2, 2.8, 2.4, 3.6, 2.8]
def max_sum_arr_size_k(arr, k):
ans = []
windowStart, windowSum = 0, 0
for windowEnd in range(len(arr)):
windowSum += arr[windowEnd]
... |
666050ba17111078e5fe3e3636e4e4766a424a05 | lsom11/coding-challenges | /leetcode/September LeetCoding Challenge/Largest Number.py | 231 | 3.5 | 4 | class Solution:
def largestNumber(self, nums):
compare = lambda a, b: -1 if a+b > b+a else 1 if a+b < b+a else 0
print(compare)
return str(int("".join(sorted(map(str, nums), key = cmp_to_key(compare))))) |
50ab1993cd58c396a6d4e51cb9d0d3aff66f4bc1 | ivo-douglas/OlaMundo | /CalcularNota.py | 2,493 | 4.125 | 4 | """ Nome: Douglas Ivo Martins de Moraes
1. a) Sabe Programar: Não, ja experimentei algumas coisas de scripting structure nas minhas horas de lazer / hobbie, mas formalmente nunca programei ou aprendi uma linguagem de programação
b) Ja trabalha na aréa de computação? : Não
c) Ja estudou ou fez algum outro curso na área ... |
6c3a4c023b51f31c3baf0cad6d26f9ac17cf2d32 | Dacode45/gh5server | /court_locator.py | 9,649 | 3.65625 | 4 | import sys
import json
### COURT LOCATOR SCRIPT (court_locator.py)
###
### Author: Elliott Battle (09-13-2015)
### Event: GlobalHack V
### Team: Rush Hour 3
###
### Purpose: Process queries from a JSON database by taking geographic points (represented as a lattitude and a longitude)
### and identifying which ... |
5626722b6c9ad0cf2318b7a8aaf655f6f6f274b7 | rgayatri23/Python_prac | /allSort.py | 5,850 | 3.890625 | 4 | import random
#######################################################Quick Sort #########################################################################
def quickSort(arr) :
# print("Quick sort")
if len(arr) <= 1 :
return arr
pivot = arr[len(arr)/2]
left = [x for x in arr if x < pivot]
... |
06735541954a85c263fd2b0e1a3abc0e2f209459 | kashyap92/python-training | /MyMath.py | 289 | 3.578125 | 4 | #!/usr/bin/python
def add(a,b):
return a+b
def mul(a,b):
return a*b
def sub(a,b):
return a-b
def div(a,b):
return a/b
if __name__ == "__main__":
print add(10,20)
print mul(10,20)
print sub(4,2)
print div(10,2)
print __name__
|
22df68a087f09a8337ecf5774eec62c6fbab3ce0 | nwthomas/code-challenges | /src/interview-cake/product-of-every-integer-but/product_of_every_integer_but.py | 1,124 | 4.0625 | 4 | """
Write a function get_products_of_all_ints_except_at_index() that takes a list of integers and returns a list of the products.
For example, given:
[1, 7, 3, 4]
your function would return:
[84, 12, 28, 21]
by calculating:
[7 * 3 * 4, 1 * 3 * 4, 1 * 7 * 4, 1 * 7 * 3]
Python 3.6
Here's the catch: You can't use d... |
7b79eb125ee7453c86a991a8003dcf61974e35fc | r002/interview_prep | /strings/q201.py | 1,494 | 3.890625 | 4 | from base.question import *
class Str201(Question):
description = "201) Given a string, s, find the longest palindromic substring in s."
i = 0 # Number of iterations my solution takes
def __init__(self):
# s = 'racecar'
# s = 'tracecars'
# s = 'ab'
# s = 'abcbgh'
... |
330f9c4fab16ed56a8f42bda8175d6fa33641d73 | alhulaymi/cse491-numberz | /sieve_iter/test.py | 825 | 3.734375 | 4 | #The first prime number is 2 but im following the outcome of sieve-fn.py and starting by 3
import sieve
def test1():
print "--<<test 1>>--"
print "should get to one value above 29 and stop"
x = 0
for i in sieve.adder():
x = i
if i > 29:
break
assert x == 31
print "=>... |
f37d04970030ab66bc49713e178dac54b4c29f64 | yistar-traitor/LeetCode | /LinkedList/ReverseLinkedList.py | 1,570 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/9/15 15:41
# @Author : tc
# @File : ReverseLinkedList.py
"""
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
参考:https://leetcode-cn.com/problems/reverse-linked-list/solution/fan-zhuan-lian-biao-by-leetcod... |
705010c88fdc1e0c4a5cda6963a2eb4981ea629e | VinayakaSridharKVV/Spice_in_python | /ee19b058_file1.py | 1,901 | 4.09375 | 4 | """ EE2703 ASSIGNMENT 1
NAME: VINAYAKA SRIDHAR K V V
ROLL NO.: EE19B058
"""
# PYTHON PROGRAM FOR READING A NETLIST AND PRINTING IN THE REVERSE ORDER
from sys import argv, exit #importing module sys
pycode = argv[0]
CIRCUIT = '.circuit' # defining the constants
END = '.end'
""" Sanity Check whether there is a input f... |
6370c81e41d004a2c089097976d406350346664b | mfcrespo/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 324 | 3.84375 | 4 | #!/usr/bin/python3
""" Module that manipulates lists
"""
class MyList(list):
""" Class that inherits from list
"""
def print_sorted(self):
""" Prints self sortedly, without modifying the
original list
"""
new_list = self[:]
new_list.sort()
print(new_li... |
aed24f58dc924174df5c95c5e3839251a4190d28 | jgsneves/algoritmo-python | /poo/encapsulamento/exercicio8.py | 624 | 3.5 | 4 | class Funcionario:
def __init__(self, nome, salario, matricula, funcao):
self.nome = nome
self.__salario = salario
self.__matricula = matricula
self.funcao = funcao
@property
def matricula(self):
return self.__matricula
@property
def salario(self):
r... |
c827732bd723bd387ddeccc1a4b4ed48135831a4 | jamalamar/Python-function-challenges | /challenges.py | 1,182 | 4.28125 | 4 |
#Function that takes a number "n" and returns the sum of the numbers from 1 to "n".
# def sum_to(n):
# x = list(range(n))
# y = sum(x) + n
# print(y)
def sum_to(num):
sum = 0
for i in range(num + 1):
sum += i
print("The sum from 1 to "+ str(num) + ": " + str(sum))
sum_to(10)
#Function that takes a... |
23cb91e6de15c782f3eb396edbf495a783e7f967 | ermteri/PythonTraining | /Exercises.py | 12,929 | 3.90625 | 4 | # Exercises taken from http://www.practicepython.org/
def ex1():
import datetime
now = datetime.date.today().year
name=input("Enter your name:")
age = int(input("Enter your age:"))
num = int(input("Enter how many times:"))
for i in reversed(range(1,99)):
print(i)
print('Dear {} y... |
b4553f670eefb5c12ae6261b3b8aa57bfb890f05 | ksoftlabs/labsheets1001 | /Tutorial 7 (Aditional) 06-05-2016/queue_using_dequeue.py | 167 | 3.640625 | 4 | from collections import deque
queue=deque([])
print(queue)
queue=deque(["a","b","c","d","e"])
print(queue)
queue.append("f")
print(queue)
queue.popleft()
print(queue)
|
cd097fcb70e992d098a162539705130d5a937e41 | LiuAllan/Seng265 | /lab5/word_counter.py | 275 | 3.640625 | 4 | import sys
words = sys.stdin.read().split()
#word = lines.split(" ") ; word
print("Number of words:{}".format(len(words)))
count = [0] * 256
for word in words: count[len(word)] += 1
for i, c in enumerate(count):
if c > 0: print("Word length: {:02} = {}".format(i, c))
|
a73e5abefed6a9feec5c8db434c50fa6bdeb22cd | 8563a236e65cede7b14220e65c70ad5718144a3/python3-standard-library-solutions | /Chapter01/0039_re_groups_alternative.py | 436 | 3.5625 | 4 | """
Listing 1.39
Groups are also useful for specifying alternative patterns. Use the
pipe symbol (|) to indicate that either pattern should match.
"""
from re_test_patterns_groups import test_patterns
def main():
test_patterns(
"abbaabbba",
[
(r"a((a+)|(b+))", "a then seq. of a or seq... |
979a26178f187c901e74383d293c848d2f02fae9 | Riopradheep007/Leetcode-problem-solving | /Easy/longest_common_prefix_in_list.py | 264 | 3.71875 | 4 | def longestCommonPrefix(strs):
if len(strs) == 0:
return ''
res = ''
strs = sorted(strs)
for i in strs[0]:
print(strs[-1])
if strs[-1].startswith(res+i):
res += i
else:
break
return res
n=input.split()
print(longestCommonPrefix(n))
|
3444f08fdf55b410a0dd91619f2a35f5d51b346e | Dombrauskas/Apart_-_Stuff | /Matemática/MDC/mdc.py | 1,628 | 4.125 | 4 | """
"
" Autor Maurício Freire
" Cálculo do Máximo Divisor Comum consiste em encontrar o maior termo comum a
" dois (ou mais) números capaz de dividir ambos.
" Calcule of the Greatest Common Divisor consists in finding the greatest value
" common to two (or more) number that is able to divide both.
"""
def mdc(x,... |
8bf6ea9bdc046346c27b066bab593cf24d179745 | andrea9888/domaci2 | /zad1.py | 236 | 3.546875 | 4 | lista=list(range(1,11))
lista1=[]
lista2=[]
k=0
import random
while k!=5:
lista2.append(random.choice(lista))
k=k+1
for i in lista:
if lista2.count(i)==0:
lista1.append(i)
print (list(zip(lista1, lista2))) |
54260f6335ff9e44f259bd691ab8f9e85995d021 | MarynaHaiduk/pthn | /HackerRank/on_sale.py | 306 | 3.65625 | 4 | #!/usr/bin/python
if __name__ == "__main__":
fruits = ["banana", "apple", "pineapple", "oranges"]
on_sale = ["banana", "apple", "tomatoes"]
print("All: ", set(on_sale) | set(fruits))
print("On Sale: ", set(on_sale) & set(fruits))
print("Others on Sale: ", set(on_sale) - set(fruits))
|
dd2ec105719515708ac9dd1c18175fa919403981 | bmcgahee/Math | /compositefunctions.py | 506 | 3.609375 | 4 | def f(x):
y = x*x + 5
return y
def g(x):
y = x - 2
return y
def fog(x):
t = g(x)
y = f(t)
return y
def gof(x):
t = f(x)
y = g(t)
return y
#Test 1
fy = f(3) #f(3) = 3^2 + 5 = 14
gy = g(3) #g(3) = 3 - 2 = 1
print "f(3) = " + str(fy)
print "g(3) = " + str... |
9c4686b06584a5bc515094a34f05c15422b17b2f | pulakanamnikitha/nikki | /552.py | 100 | 3.5 | 4 | p,o= map(int,raw_input().split())
s=p*o
if (p % 2) == 0:
print ("even")
else:
print ("odd")
|
8fd59853e3650e070730289521f54e30de20f0da | ucsb-cs8-m17/Lecture3_0810 | /turtle_demo_01.py | 206 | 3.734375 | 4 | import turtle
t = turtle.Turtle()
# Invoke the shape method,
# passing the string "turtle"
# as a parameter
t.shape("turtle")
# A simple T
t.forward (50)
t.goto (25, 0)
t.right (90)
t.forward (100)
|
4cced7ff49070e5bf42dfc6dcbc9c8cee03fb945 | flowxcode/pySnips | /elgamal/appro1/likelyPrime.py | 1,997 | 3.609375 | 4 | #! /usr/bin/python
'''Implementation of the Miller-Rabin primality test. '''
from random import randint
# import gcd
from math import log
# from math import pow
from math import gcd
from mrabingfg import *
def isMillerRabinPsuedoPrime(n,a):
if n % 2 == 0:
return False #even numbers aren't prime
m = n-1; k ... |
3e9958c4ab2b639055165ad73ad7e1eb1d20635c | apollomat/TechInterview | /problems/math/hammingDistance.py | 527 | 4.21875 | 4 | '''
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
'''
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int... |
df57c1e40ca51c77bc1d6d8b088132f9ea23688b | jandrovins/cp | /CP/10106-Product/sol.py | 275 | 3.59375 | 4 | from sys import stdin
cont =0;
for line in stdin:
if(cont+1 == 2):
cont = 0
b = line
print(int(a) * int(b))
continue
elif cont == 0:
a = line
cont += 1
#while (a = int(input())) && b = int(input()):
# print(a*b)
|
9fb78d6f57282958c4c3d28463b2ae175552704e | vish9767/python | /programes/mix.p/def.while.for.py | 249 | 4.03125 | 4 | def star():
name=('vishal','akshay','rohan','somnath')
for e in name:
print("\n")
print(e)
a=int(input("enter the value for star how star you want"))
i=0
while(i<a):
print("*",end="")
i=i+1
star()
|
dbf4d77a4a43b63e608a0e1d9a48fd2f668b9d29 | ramanaidu07/python | /Assignment1_area_of_triangle.py | 134 | 3.859375 | 4 | i1=input('enter base length:')
i2=input('enter height:')
b=float(i1)
h=float(i2)
area=1/2*(b*h)
print('area of triangle=',area)
|
109d597939aaea63c16562a4a64bcc7243fbb570 | macdit3/PasswordGeneratorApp | /PasswordGeneratorApp.py | 1,558 | 4.59375 | 5 | # This program will generate password by
# substring first 2 characters and display
# combined character.
import random
#1. Crreate a greeting for your program
print('Welcome Strong password generator app')
# Create an array to store the user's inputs
inputs = []
new_password = []
random_pass = []
#2. Ask the us... |
e5b16b157d098e0c7220232e7c37ccc58cd3eb83 | h-j-13/Algorithms-Soulution | /剑指offer/丑数.py | 1,438 | 3.53125 | 4 | # -*- coding:utf-8 -*-
class Solution:
"""
题目描述
把只包含因子2、3和5的数称作丑数(Ugly Number)。
例如6、8都是丑数,但14不是,因为它包含因子7。
习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
"""
def GetUglyNumber_Solution(self, index):
# 丑数的定义是1或者因子只有2 3 5,可推出丑数=丑数*丑数,假定丑数有序序列为:a1,a2,a3.......an
# 所以可以将以上序列(a1除外)可以分成3类,必定满足:... |
b408ca04a4a29b1830a8a589a5c3cd6e003afb76 | kouma1990/AtCoder-code-collection | /contests/ABC1-100/ABC54/a.py | 188 | 3.796875 | 4 | a, b = (int(i) for i in input().split())
if a==b:
print("Draw")
elif a==1:
print("Alice")
elif b==1:
print("Bob")
elif max(a,b) == a:
print("Alice")
else:
print("Bob") |
7229619a5ab3e53b5fd8a54139cd77ed84d78d0e | mand2/python-study | /day05/create_decorator2.py | 544 | 4.15625 | 4 | """
ref: https://www.datacamp.com/community/tutorials/decorators-python
application of create_decorator1.py
succeed to decorator_test.py
advantages of using these type:
- don't have to assign decorator_function
- just put @decorator to what-you-want-to-use function
- and just call the what-you-want-to-use ... |
d60ee8a6c5b0ba4bb4a2a2fc0f909e75a87c632e | shreezan123/Python-Interview-Practice-Problems | /sumpairs.py | 461 | 3.5625 | 4 | def sumnums(arr,sum):
anslist = []
dict = {}
for each in arr:
if each not in dict:
dict[each] = 1
else:
dict[each] += 1
print(dict)
for each in dict:
if dict[each] == 0:
break
target = sum - each
if target in dict:
... |
643aa2b85d8ff2ede6411a374582d7683857a896 | zhouyinfan/socket | /class49/4.16.py | 7,362 | 3.765625 | 4 | # lis1=[1,2,34,56,7,2,4,2]
# print(id(lis1))
# lis2=[3,4,[5,6]]
# lis3=lis1+lis2
# print(lis3)
# lis4=lis3[1:3:1]
# print(lis4)
# for i in lis3:
# print(i)
#内置函数
##增
#append 整体加进去
# lis1.append([1,2,3,4])
# print(lis1)
# print(id(lis1))
#extend将元素拆分开加进去,可迭代对象
# lis1.extend([1,2,3])
#中间加元素
# lis1.insert(2,"hello")
#... |
5840c22e07786544e10d9fef99467fd87a02a051 | prabhuyellina/Assignments_Python | /assignments/panagram.py | 361 | 4.0625 | 4 | import string
def panagram(x):
x=x.lower()
if len(x)<26:
return False
else:
x.replace(' ','')
count=0
for i in string.ascii_lowercase:
if i in x:
count+=1
if count==26:
return True
return False
print panagram(raw_input('Ent... |
fab57b68ddc6edc25d7a8718ac6a62ba48428cff | ThibautBernard/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/1-search_replace.py | 248 | 3.90625 | 4 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
counter = 0
new = []
for i in my_list:
if i == search:
new.append(replace)
else:
new.append(i)
counter += 1
return new
|
5b8c8344c07956fc8291710ce56dac080ac4b77e | vaclav0411/algorithms | /Задания 14-го спринта/Простые задачи/A. Генератор скобок.py | 592 | 3.625 | 4 | def generate_brackets(n: int, k: int, prefix='', lead=0, trailing=0):
if n == 0:
print(prefix)
else:
if lead < k and trailing > 0:
generate_brackets(n-1, k, prefix+'(', lead+1, trailing+1)
generate_brackets(n-1, k, prefix+')', lead, trailing-1)
elif trailing > 0:
... |
8f568416ca19c096f136ee7e8ec54c6f5c76fd72 | idimitrov07/blockchain-tutorials | /simple_blockchain_python/blockchain.py | 2,013 | 3.625 | 4 | from block import Block
class Blockchain:
def __init__(self):
self.chain = []
self.all_transactions = []
self.genesis_block()
def genesis_block(self):
transactions = {}
gen_block = Block(transactions, '0')
self.chain.append(gen_block)
return self.chain
# print blockchain
def p... |
741baa24e19cdaaff28c899211a30edf91b315fd | ltjhappy/PythonCode | /Base/TestVar.py | 592 | 3.90625 | 4 | # python 推荐使用 纯小写加下划线的方式做变量名
alex_of_age = 19
name = "ucs"
print(name)
x = 100
wu = x
xf = x
del (x)
# print(x)
print(wu)
国家 = "Korea"
print(国家)
# id 反映的是变量值的内存地址,内存地址不同id则不同
print(id(alex_of_age))
# type 不同类型的值用来表示记录不同的状态
print(type(alex_of_age))
x1 = "-9"
y1 = "-9"
print(id(x1))
print(id(y1))
x2 = 'algorithm,898989:... |
60916981adb969986be808b4350a30569851577f | floydawong/LeetCode | /python/003.py | 975 | 3.625 | 4 | # https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
'''
3. 无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
... |
8570f00103807439cd9777031db3efa33ae4a929 | matsub/sandbox | /python/pythonchallenge/prob_01.py | 509 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
'''http://www.pythonchallenge.com/pc/def/map.html'''
import string
def decode(code):
l = string.ascii_lowercase
tbl = str.maketrans(l, l[2:]+l[:2])
return code.translate(tbl)
if __name__ == '__main__':
code = '''\
g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq uf... |
b6fd47c4ccbe6b0a205d2dbd487389fe401d5c1a | nilavann/HackerRank | /Regex/Applications Challenges/Split the Phone Numbers.py | 247 | 3.8125 | 4 | #!/bin/python3
import re
Regex = r"^(\d+)( |-)(\d+)\2(\d+)$"
for _ in range( int( input())):
result = re.match( Regex, input())
print( "CountryCode={},LocalAreaCode={},Number={}".format(result.group(1), result.group(3), result.group(4))) |
52e2ef102aa34ac7d6f9170d1118937f058ef997 | mofei952/algorithm_exercise | /leetcode/141 Linked List Cycle.py | 1,221 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : mofei
# @Time : 2018/9/23 14:35
# @File : test141.py
# @Software: PyCharm
"""
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
"""
from utils import ListNode
class Solution(object):
de... |
5b13d0c96abd99078b76a222a25046b63384589a | AstroOhnuma/Unit3 | /gauss.py | 358 | 4.1875 | 4 | #Astro Ohnuma
#9/29/17
#gauss.py - using a loop to add up all the numbers from 1 to 100
num1 = int(input('Enter a number: '))
num2 = int(input('Enter another number: '))
num3 = int(input('Enter the difference you want between each term: '))
total = 0
for i in range(num1,num2+1,num3):
total += i
print('The sum of t... |
8389c2391d5ea11090be1a8e397cc81851b6c7ad | Cold-Front-520/valgundriy | /domashka3-zd1.py | 710 | 3.765625 | 4 | x = []
razm = int(input("введите количество элементов и сами значения "))
for i in range(razm):
x.append(int(input()))
print("это твой массив короче: ", x, "теперь введи циферку - скажу где она")
f = int(input())
for i in range(razm):
if f == x[i]:
slot = i + 1
print("эта циферка стоит на ", s... |
77fd82069aa2648fea685fec4567123642a507cf | subhashiniperni-test/python | /Tested programs code/writingtoexcel.py | 360 | 3.625 | 4 | import xlwt
from xlwt import Workbook
wk: Workbook=xlwt.Workbook()
ws=wk.add_sheet("testing")
r=input("enter how many rows")
c=input("enter how many columns")
#for i in range(0,(r>i),1):
# for j in range(0,(c>j),1):
# ws.write(i,j,"Testing world")
# ws.write(i,j,"www.testing world.com")
# wk.sa... |
d40b5706c173dbc03b7c1289239abddcec3313cd | ofenbach/GuitarSongGenerator | /code/song_generator.py | 960 | 3.5 | 4 | import sys
import random
# Chords
d_chords = ['D', 'Dm']
e_chord = ['E', 'Em']
a_chords = ['A', 'Am']
f_chords = ['F', 'Fm']
g_chords = ['G', 'Gm']
chords = [d_chords, e_chord, a_chords, f_chords, g_chords]
def generate_chords(amount):
""" Generates basic chords.
param: amount of chords (int) """
final_chords ... |
1eed20de1c866e6da25008911752fd187ae10a07 | Murilo-ZC/FATEC-MECATRONICA-MURILO | /LTP2-2020-2/Pratica08/prog03.py | 544 | 3.875 | 4 | personagens = {"dps": [] , "healer": [], "support": [], "tank": []}
quantidade_de_personagens = int(input("Quantidade de personagens:"))
contador = 0
while contador < quantidade_de_personagens:
nome = input("Qual o nome do personagem:")
classe = input("Qual a classe do personagem:").lower()
#Verifica se a class... |
52abfcdb90597de144d573de45daca10a81a9092 | dvbridges/regularExpressions | /alternations.py | 643 | 4.40625 | 4 | import re
# Optional items are declared using '?'
# However, you can also search for one of several regex patterns
# This is achieved using the '|' Or logical operator
# This example checks for multiple destinations in a string
pattern = r"Destination.*(Paris | Rome | London)"
msg = "Destination is London"
match = re... |
9e49dd6f783c051fac38e0c429f707e32083f8c6 | kaci65/Nichola_Lacey_Python_By_Example_BOOK | /Strings/rhyme_and_slice.py | 282 | 4.125 | 4 | #!/usr/bin/python3
"""Get input string from user, slice it using indexing then display it"""
string = input("Enter line of a nursery rhyme: ")
print(len(string))
begin = int(input("Enter a starting number: "))
end = int(input("Enter an ending number: "))
print(string[begin:end])
|
dbb8991e2684ef54c23be4dff6b5bbec3172de75 | islanrodrigues/learn-python | /src/08_manipulacao_de_arquivos.py | 1,980 | 4.09375 | 4 | # A manipulação de arquivos se torna bastante fácil com Python.
# A função open() permite que um arquivo seja aberto e;ou criado informando o caminho, o nome do arquivo e o modo de manipulação. Caso o caminho não seja especificado, será considerado o diretório corrente.
'''
Algumas opções dos modos de manipulação:
... |
5db32ff562b9f83b755c099098f2fa32bea33722 | raviranjan145/python-programs | /Tuple_5.py | 4,461 | 4.46875 | 4 | #1. Write a Python program to create a tuple.
# x =()
# print(x)
# fruits = ("apple", "banana", "cherry")
# print(fruits[1])
#2. Write a Python program to create a tuple with different data types.
# diffdatatype = (1,'ram', 50.5,True)
# print(diffdatatype)
#3. Write a Python program to create a tuple with... |
8e25f9638d1b6d128c26f19027afe04a02bf8d78 | asswecanfat/git_place | /杂项/新水仙花.py | 823 | 3.625 | 4 | def sure(x,y):
b = []
while True:
if y > 1000 and x >=100:
y = int(input('请重新输入上限:'))
elif x < 100 and y < 1000:
x = int(input('请重新输入下限:'))
elif y > 1000 and x < 100:
x = int(input('请重新输入下限:'))
y = int(input('请重新输入上限:'))
elif y <= 1... |
c6bbbe21f5ced8eb7b395ef1418e318291a34382 | WillMc93/AS.605.620 | /Project2/code/hashing.py | 11,119 | 4.03125 | 4 | """
hash_table takes care of storing, maintaining, and interacting with
the hash table.
@authour Will McElhenney
@date 11/6/2019
"""
class hash_table:
"""
Constructor for hash table
@param size: integer for the size of the table
@param mod: integer for the class modulo hash function
@param bucket_size: integer f... |
ab863b68668454567fdc65f0da0aca8a15474b8e | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/gigasecond/181bd8c14d8e426db4b98959af77ed93.py | 2,991 | 3.65625 | 4 | #!/usr/bin/env python
from datetime import date
from math import *
def add_gigasecond(birthday):
bday = updateDate(birthday)
bday.setToNewYear()
return bday.incrementSecs(1000000000)
class updateDate:
def __init__(self, basedate):
self.basedate = basedate
self.year = basedate.year
... |
b0693ca2020f4e30e9f0388739b8363374a492ea | Linjiayu6/LeetCode | /Algorithms/tree/EASY/590_N-ary Tree Postorder Traversal.py | 868 | 3.859375 | 4 | # https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
# For BST or BT, left -> right -> root
# For N-ary, children -> root
"""
# Definition for a Node.
class ... |
4513ff87de71790ef509b716ab2457c32241ac06 | nan0445/Leetcode-Python | /Power of Three.py | 250 | 3.8125 | 4 | class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n<=0: return False
while n>1:
n, m = divmod(n, 3)
if m!=0: return False
return True
|
bce1abeae3549d5bf953d24b826f2151b9996b9d | Eldwitch/CSE | /Everett Garrison - Guess Game.py | 323 | 3.953125 | 4 | import random
random = (random.randint(1, 10))
for i in range(5):
guess = int(input("Guess a number, any number: "))
if guess < random:
print("Guess is too low.")
elif guess > random:
print("Guess is too high.")
elif guess == random:
print()
print("You win!")
bre... |
a2d721cf8baa3f28ecd055ef4f515ba3bbbd445a | ggrecco/python | /basico/coursera/converte_segundos_em_horas_minutos_e_segundos.py | 289 | 3.84375 | 4 | segundos = int(input("Por favor, entre com o número de segundos que deseja converter: "))
horas = segundos // 3600
segundosRestantes = segundos % 3600
minutos = segundosRestantes // 60
resto = segundosRestantes % 60
print("{} horas, {} minutos, {} segundos.".format(horas,minutos,resto))
|
aa3fa4560cf8e7e57d1b2643cfcc68b04a22b9ab | Youga810/ProgrammingContest | /202/B.py | 181 | 3.8125 | 4 | s = input()
s2 = []
for elem in reversed(s):
if(elem == '6'):
print('9', end="")
elif(elem == '9'):
print('6', end="")
else:
print(elem, end="")
|
d6a02c55ff4ab382b723aeb2b3330909a282a7b1 | Sindhumeenakshi/guvi | /codekatta/letter or num.py | 221 | 3.75 | 4 | si=input()
letter_flag = False
number_flag = False
for b in si:
if b.isalpha():
letter_flag = True
if b.isdigit():
number_flag = True
if letter_flag and number_flag:
print('Yes')
else:
print('No')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.