blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
54ed4f477b5f52468ea5cdd1a9c4b8c6e7251981 | Broozer29/Utrecht_HBO_ICT | /Lists & numbers.py | 468 | 3.578125 | 4 | def main():
invoer = "5-9-7-1-7-8-3-2-4-8-7-9"
list = invoer.split("-")
list.sort()
nieuweList = []
totaal = 0
for i in list:
totaal += int(i)
nieuweList.append(int(i))
print("Gesoorteerde list: ", nieuweList)
print("Het minimum getal is: ", min(list), "Het maximum getal ... |
4fac8eda3ce50f8b41beb9be5508de400b2589ac | pfkevinma/stanCode_Projects | /stanCode_Projects/my_drawing/draw_line.py | 1,622 | 3.765625 | 4 | """
File: draw_line.py
Name: Pei-Feng (Kevin) Ma
-------------------------
This program creates lines on an instance of GWindow class.
There is a circle indicating the user’s first click. A line appears
at the condition where the circle disappears as the user clicks
on the canvas for the second time.
"""
fro... |
ade97e11cd2b8ce2321384c78a24128fd2961278 | mamemilk/acrc | /プログラミングコンテストチャレンジブック_秋葉,他/src/2-1-2_03_arc037_b.py | 1,846 | 3.578125 | 4 | # https://atcoder.jp/contests/arc037/tasks/arc037_b
# 閉路判定
# - DFS
# 訪問済みの頂点を再度訪問したときに閉路存在.
#
# - UnionFind
# a,bの辺を張るときに,すでに同じグループなら閉路が存在.
#
N, M = map(int, input().split())
UV = []
for m in range(M):
u, v = map(int, input().split())
UV.append((u,v))
class UnionFind:
def __init__(self, n):
... |
70037e2a99bcff22dd6337e7a06323500da5e216 | mpyrev/checkio | /open-labyrinth.py | 6,827 | 3.65625 | 4 | from heapq import heappush, heappop
START = (1, 1)
FINISH = (10, 10)
def get_manhattan_score(coords):
return (FINISH[0]-coords[0]) + (FINISH[1]-coords[1])
def make_move(coords, move):
return coords[0]+move[0], coords[1]+move[1]
class SearchNode:
coords = None
move_number = None
previous = No... |
05f5a123e3b47cffb018e67c748c9f2d31a2c440 | spymobilfon/PythonHomeWork | /Lessons_1/questions_and_answers.py | 2,004 | 4.03125 | 4 | # Clear the value of variables
correct_answer = 0
not_correct_answer = 0
# Set the value options for YES and NO
value_yes = ["yes", "true", "да", "верно", "правда"]
value_no = ["no", "false", "нет", "не верно", "ложь"]
# Block of the questions and answers
answer_1 = input("Какой это язык программирования?\nОтвет: ")... |
3c0cc7b30c511a3b4e1f52bc7c70cdf58d30d10a | grigart97/Basics_of_Python | /.idea/Task-2.py | 1,225 | 3.734375 | 4 | from abc import ABC, abstractmethod
class Clothes (ABC):
def __init__(self, size):
self.size = size
@abstractmethod
def tissue_consumption(self):
pass
class Coat(Clothes):
max_size = 66
min_size = 40
@property
def tissue_consumption(self):
if self.size < self.min_... |
677d705bf43bb091474e86891c15601c4fcf6e85 | esigei/Lab_4 | /Image.py | 2,045 | 3.515625 | 4 | # Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
import numpy as np
from keras.preprocessing import image
from keras.preprocessing.image import Im... |
d66ee814bba5b7b79a6be36fa6bf1e08e48d6e39 | qamine-test/codewars | /kyu_5/fibonacci_streaming/test_all_fibonacci_numbers.py | 2,350 | 3.515625 | 4 | # Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
# ALGORITHMS
import allure
import itertools
import unittest
from utils.log_func import print_log
from kyu_5.fibonacci_streaming.all_fibonacci_numbers import all_fibonacci_numbers
@allure.epic('5 ky... |
37eb040eee324df5bc657743c7b12143fa168263 | manishdwibedy/Natural-Language-Processing | /Homework 4/ngrams.py | 1,895 | 3.75 | 4 | import codecs
class NGrams(object):
def __init__(self, n, filename):
self.filename = filename
self.n = n
def readFile(self):
'''
Reading the file
:return: Sets the value in the line parameter
'''
lines = []
with codecs.open(self.filename,'r',enc... |
9ed6b78ac508fbdebde06d506e9df517a32953ed | EmjayAhn/DailyAlgorithm | /18_programmers/programmers_35.py | 448 | 3.921875 | 4 | # https://school.programmers.co.kr/learn/courses/30/lessons/120893
# programmmers, 코딩테스트 입문
import string
def solution(my_string):
answer = ''
for s in my_string:
if s in string.ascii_lowercase:
answer += s.upper()
else:
answer += s.lower()
return answer
if __name... |
e1f6237109ddeee306208634fc3c565efdad4450 | cwahbong/roller | /roller/dice/_immutable_die.py | 1,438 | 3.640625 | 4 | """ class ImmutableDie.
"""
from roller.dice._die import Die
class ImmutableDie(Die):
""" A die that has immutable attributes.
"""
def __init__(self, distribution, expected_hint=None):
def _normalized_dist_dict(dist_dict):
""" Make the sum of probability be 1 in a distribution by
... |
eb82b1cc4dcd2bea324a73553f17ba395038c353 | quanewang/public | /window.py | 4,163 | 4.4375 | 4 |
"""
Given an integer array of size n, find the maximum of the minimums
of every window size in the array. Note that window size varies from 1 to n.
Example:
Input:
10 20 30 50 10 70 30
10 20 30
Output:
70 30 20 10 10 10 10
30 20 10
Explaination:
Input: arr[] = {10, 20, 30, 50, 10, 70, 30}
Output: 70, 3... |
de2bbc4359a0d0c13c231820f40bab9253bb45d0 | mrejonas/MRC_Flagship | /ExceltoREDCapInstrument.py | 1,856 | 3.859375 | 4 | #!/usr/bin/python
import sys
import re
# Description:
# Take a CSV file generated by Excel with fields in columns
# and transpose column fields to rows. Used these fields to
# then create a basic REDCap instrument to be imported
# PseudoCode/ Steps
# -Add REDCap header
# -Remove trailing or extra spaces from field
#... |
c0e6396c167ad80f53a54fe322c053aba6b6e5e3 | poojaKarande13/ProgramingPractice | /python/intToRoman.py | 1,962 | 3.921875 | 4 | '''
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is... |
11061a915910abeaf0c05cbf77c6aae51d90bf12 | GenyGit/python-simple-code | /venv/NOK.py | 330 | 3.828125 | 4 | #нахождение наименьшего общего кратного через нахождение наибольшего общего делителя
a = int(input())
b = int(input())
if a > b :
n = a
m = b
else:
n = b
m = a
while n % m != 0 :
ost = n % m
n = m
m = ost
print(a * b // m) |
4ca60261e1129dbce2004a9204f3eac33aa7f10b | philwade/Euler | /euler4.py | 636 | 4.09375 | 4 | #A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
def isPalindrome(n):
n = str(n)
if len(n) == 1 or n == '':
return True
if n[0] == n[-1]... |
780aa0ff92d671b61119f7100c2d4223cf5f7222 | Jane11111/Leetcode2021 | /106_2.py | 827 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021-05-12 15:15
# @Author : zxl
# @FileName: 106_2.py
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def buildTree(self, in... |
b9d8614f035490050b52a5b75944ac4083c0484e | codacy-badger/pythonApps | /countNumberEachVowel.py | 234 | 3.53125 | 4 |
vowel = 'aiueo'
setString = 'Hello, get back to the future'
setString = setString.casefold()
count = {}.fromkeys(vowel, 0)
for charCount in setString:
if charCount in count:
count[charCount] += 1
print(count)
|
0b033ea21feebbd60d853f003d6a8db1eee80769 | 666syh/python_cookbook | /python_cookbook/1_data_structure_and_algorithm/1.8_字典的运算.py | 615 | 3.953125 | 4 | """
问题
怎样在数据字典中执行一些计算操作(比如求最小值、最大值、排序等等)?
"""
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
# 使用 zip() 函数先将键和值反转过来
min_price = min(zip(prices.values(), prices.keys()))
print(min_price)
# (10.75, 'FB')
max_price = max(zip(prices.values(), prices.keys()))
pri... |
dd254a29df8181d5808fb35ec54c52a727941b30 | tommytobi/DataStructures | /Binary Tree/test_binaryTree.py | 2,064 | 3.734375 | 4 | from binaryTree import BinaryTree
tr = BinaryTree([5,9,7,4,6,1,2,8])
print(tr)
print('find 2', tr.search(2))
print('find 22', tr.search(22))
print('testing deletion')
print('delete 2')
tr.delete(2)
print(tr)
tr = BinaryTree([5,9,7,4,6,1,2,8])
print('delete 1')
tr.delete(1)
print(tr)
tr = BinaryTree([5,9,7,4,6,1,2,8])
... |
56593a6968819041901b793928689098be6549ea | suriyakamal007/python | /leap.py | 98 | 3.71875 | 4 | num=int(input())
if ((num%400==0)or(num%4==0 and num%100!=0)):
print('yes')
else:
print('no')
|
b575310940f81b968bd1662c9d9936579f93f701 | dallasmcgroarty/python | /General_Programming/OOP/grumpy_dict.py | 665 | 4.40625 | 4 | # overriding dictionary object in python
# using magic methods we can override how a dictionary functions
# this can also be applied to other objects as well
class grumpyDict(dict):
def __repr__(self):
print("None of Your Business")
return super().__repr__()
def __missing__(self, key):
... |
c5ab9e9bcd5b4f4996035e8468fa4a9509ee42b9 | RuRey0310/Competitive_Programming | /ABC151~200/ABC153/d.py | 103 | 3.53125 | 4 | h = int(input())
ans = 0
cnt = 1
while h >= 1:
ans += cnt
h = h // 2
cnt *= 2
print(ans)
|
d7a79c2a81f29c89f14c98b81614fc923adf8caf | almighty-superstar/Python-Projects | /Guessing Game.py | 741 | 3.984375 | 4 | tries=0
secret_word="giraffe"
guess=0
while guess!=secret_word:
guess=input("Choose and animal in all lowercase letters:")
tries=tries+1
if tries==1:
print("The animal is yellow")
if tries==2:
print("The animal is yellow and has spots")
if tries==3:
print("The ani... |
ccbe4c9f93a977aad4e7222034444b2a92087dd8 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_06/f6_q02_separar_frase.py | 327 | 3.921875 | 4 | def main():
frase = input('Digite a frase:\n>> ')
print_palavras(frase)
def print_palavras(string):
palavra = ''
for c in string:
if c == ' ':
print(palavra)
palavra = ''
else:
palavra += c
print(palavra)
... |
0b5482df0b5459c427589c6c35dbb4a195a529a0 | Abdel-IBM-IA/Formation | /Pycharm/LesFonctions/Echange de variables.py | 1,666 | 4.1875 | 4 | from copy import copy
def swap(var1, var2):
""" Permet d'échanger les valeurs de 2 variables passées en arguments
Les deux variables doivent être de même type"""
print("type(var1) : " + str(type(var1)))
if type(var1) == type(var2):
if type(var1) == int or type(var1) == float or type(var1) == ... |
e4e56de38507cc4a4029977d568997f66ea120f6 | guei061528/Leetcode_Training | /FindandReplacePattern.py | 1,206 | 4 | 4 | # You have a list of words and a pattern, and you want to know which words in words matches the pattern.
#
# A word matches the pattern if there exists a permutation of letters p so that after replacing
# every letter x in the pattern with p(x), we get the desired word.
#
# (Recall that a permutation of letters is a bi... |
e5f47aa24187cf025022dde11581770a7074b0e2 | AlexandraSenkova/pyth_senkova-github | /Урок4_7.py | 1,144 | 3.671875 | 4 | """7. Реализовать генератор с помощью функции с ключевым словом
yield, создающим очередное значение.
При вызове функции должен создаваться объект-генератор.
Функция должна вызываться следующим образом:
for el in fact(n).
Функция отвечает за получение факториала числа,
а в цикле необходимо выводить только первые n чисел... |
011bd8b6efff03b48da666814972a1f087f5ea3c | HenriFeinaj/Simple_Python_Programs | /Even_or_Odd_Finder.py | 238 | 4.5 | 4 | #EVEN/ODD FINDER
#Input of an interger by the user.
number = int(input("Enter only an integer: "))
#Find if the number is even or odd.
if number % 2 == 1:
print(number, " ===> odd")
else:
print(number, " ===> even")
|
b56d81745e80ce1fad8c5042f4152ed390d2d402 | codebankss/CorePython | /count.py | 128 | 3.6875 | 4 | n = input()
l = len(n)
count = 0
for x in range(l):
if (n[x] == 'a'):
count +=1
print('a is repeated', count, 'times')
|
3601212637672430d86ffd83e4055307c0ff1beb | AdrianWR/MachineLearningBootcamp | /day00/ex01/matrix.py | 3,535 | 3.5 | 4 | #!/usr/bin/python3
from vector import Vector
class InputError(Exception):
def __init__(self, message="User input error."):
self.message = message
class Matrix:
def __init__(self, data, shape=None):
if isinstance(data, list):
if len(set([len(i) for i in data])) > 1:
... |
a3cf509db22682ccf52e1e102af94bc85cd98c05 | lyicecream1012/leetcode | /7_ReverseInteger/Solution_1.py | 554 | 3.6875 | 4 | # Solution 1
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x < 0:
y = 0-x
string = str(y)
str_new = '-'
else:
string = str(x)
str_new = ''
list_x = list(string)
... |
76576ae0e4a26843ff9f9e33700c1ec0d218fe32 | zhongtan/automl-scripts | /merge_csv.py | 663 | 3.65625 | 4 | # This script combines all the given input csv files and merges them into one single csv file.
import os
def merge_csv(merge_dir, filenames, outfile):
files = [os.path.join(merge_dir, file) for file in filenames]
fout = open(os.path.join(merge_dir, outfile), "a")
for file in files:
for line in open(file):
... |
07921e72ef11d5f0c5b529fba01d6a69200d87cd | dwqq/algorithm_python | /动态规划/最大子序和.py | 540 | 3.625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# -------------------------------
# @Author: dwqq
# @Date : 2021/1/26 10:21
# @File : 最大子序和.py
# @IDE : PyCharm
# -------------------------------
def maxSubArray(nums):
"""最大子序和"""
n = len(nums)
dp = [float('-inf') for _ in range(n)]
if n == 0:
r... |
4e696a222736c71de3beca4471134e58ad781793 | nacros/My-files | /snakenladder.py | 1,188 | 3.90625 | 4 | #!/usr/bin/python3
import random
count=0
r=0
while count<=100:
roll=input("press r to roll the dice")
if roll=="r":
r=random.randint(1,6)
count=count+r
print("your random num is",r)
if count==8:
count=37
print("wow u climbed to ladder",count)
elif count==13:
count=34
print("wow u cli... |
96cdf9bfceabf52c4005bda0dfba33919c1b59c4 | alextar/drone_trips | /test.py | 2,038 | 3.96875 | 4 | from copy import deepcopy
from typing import List
from typing import Dict
def shipment(items: List[Dict], drone: Dict, trip: int = 1, initial: bool = True) -> None:
if initial:
# sort items by weight from heavier to lighter
# do this only for the first function call (initial=True)
items.s... |
8e6689e8250315bb45d04748665cbb4be1fa965f | saloni27301/SIG-python | /module4/even.py | 185 | 3.796875 | 4 | print("SALONI\n 1803010120")
start=int(input("enter start digit:"))
end=int(input("Enter end digit:"))
for i in range(start,end+1):
if(i%2==0):
continue
print(i,end=" ") |
f58b39741f93ad26df4cdfcdd6a97fc866585f39 | mamorukudo0927/pracPython | /src/basicCode/classAndMethod.py | 1,604 | 4.09375 | 4 | # コメント。 #から初めて1行が認識される。
# 変数宣言。型はない。初期化するなら任意の値も
a = 'Hello world'
print(a) # Hello world
a = 1
print(a) # 1
# 関数宣言。 def 関数名 (引数) :で定義。
def addNumber(num1, num2) :
return num1 + num2
# 呼び出しは名称と引数を合わせるだけ
print(addNumber(1 ,2)) # 3
# class宣言もできる。
"""
DocString。ダブルクォートで囲った範囲に適応される。
このクラスは共通処理を提供しています。
"""
class B... |
a66b6364543e1003838416479979b19ace203f54 | python20180319howmework/homework | /yaojikai/20180328/h5.py | 427 | 3.640625 | 4 |
'''
5,定义一个函数,判断用户输入的成绩所属于的等级
1) 90~100:A
2) 80~89 :B
3) 70~79:C
4) 60~69:D
5) 0~59:E
'''
def yjkpd(num):
if 90 < num <= 100:
print("A")
elif 80 < num <= 90:
print("B")
elif 70 < num <= 80:
print("C")
elif 59 < num <= 70:
print("D")
elif 0 <= num <= 59:
print("E")
else:
print("请输入正确的成绩!")
n = int(... |
fca5ede91a5e89b51a670b1b0b7aef97bce69469 | oknowles/euler | /problem_12.py | 931 | 3.96875 | 4 | def prime_factors(n):
prime_factors = []
while (n % 2 == 0):
prime_factors.append(2)
n //= 2
p = 3
while (n > 1):
if (n % p == 0):
prime_factors.append(p)
n //= p
else:
p += 2
return prime_factors
# makes use of a trick to count... |
e88f137e28b516d6fa0036bfb1b9dedb90f064ef | zy15662UNUK/Homework | /Remove Duplicates from Sorted Array.py | 1,388 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 8 23:04:46 2017
@author: James
"""
"""
:type nums: List[int]
:rtype: int
nums is a sorted array
"""
def removeDuplicates(self, nums):
temp = nums[:]
if len(nums)<2:
return len(nums)
else:
... |
a3e558a98833af4495e60663240a3971089a93cd | abuyinn/practice-python | /16/e16.py | 750 | 4.09375 | 4 | #!/usr/bin/env python3
import string
import random
easy_chars = string.digits + string.ascii_letters
all_chars = string.digits + string.ascii_letters + string.punctuation
def generate_passwd(_strong):
length = _strong*_strong*2
if strong<2:
passwd = [random.choice(string.ascii_lowercase) for _ in ra... |
b38b8756d6197d194e035c8212e548498cd60f59 | balajisomasale/Chatbot-using-Python | /05 Python Data Stuctures/04 Dictionaries: Challenges/02 Even Keys.py | 591 | 4.375 | 4 | '''
Create a function called sum_even_keys that takes a dictionary named my_dictionary, with all integer keys and values, as a parameter. This function should return the sum of the values of all even keys.
'''
# Write your sum_even_keys function here:
def sum_even_keys(my_dictionary):
total=0
for key in my_... |
3bb16089ace35132e54f762250e75ada4732d974 | piupom/Python | /sortedrate.py | 797 | 3.828125 | 4 | # python sortedrate.py sortedrate.txt
from sys import argv
rates = {"FIM":6.0}
with open (argv[1]) as infile:
for line in infile:
ps = line.split("\t")
code, name, rate, inrate = ps[0], ps[1], float(ps[2]), float(ps[3])
rates[code] = rate
print(rates.keys())
print(rates.values())
#sanakirjan (set) läpikäynti
... |
b756c89a12a774eca670e510d672a499ce0156fc | vtopgh/python-tour | /functions/tasks/task9.py | 271 | 3.515625 | 4 | def show_jets(jets):
for jet in jets:
print(jet)
def make_great(jets):
for jet in range(len(jets)):
jets[jet] += ' is great!'
return jets
jets = ['f-18', 'f-86', 'me-163']
show_jets(jets)
new_jets = make_great(jets[:])
show_jets(new_jets)
|
6a0384119909e00113b1de2561a0f96ad5f07da1 | kchase9/ai50-projects-2020-x-tictactoe | /tictactoe.py | 3,890 | 4.03125 | 4 | """
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who ha... |
d6557e983a95b5c417138e9bf4a3d11a3683fc8b | hmc-koala-f17/CTCI-Edition-6-Solutions-in-Python | /graph_trees/bst_sequence.py | 1,200 | 3.890625 | 4 | # BST Sequences: A binary search tree was created by traversing through an array from left to right
# and inserting each element. Given a binary search tree with distinct elements, print all possible
# arrays that could have led to this tree.
from tree import Tree
def permute (prefix, lst_l, lst_r):
if lst_l == None... |
774b5f4bc32721880d557d4d0f7468c9f2232a9c | laureanopiotti/algoritmosI | /ejercicios/fwdalgoritmosparcialito4/10 30 17 Practica - Recursion.py | 1,884 | 4.0625 | 4 | """
TP 3
* --> desencola, imprime y encola
'\\' --> caracter barra
Fibo(0)=1
Fibo(1)=1
Fibo(n)=Figo(n-1)+Figo(n-2)
"""
def suma(l):
if not l:
return 0
print (l)
return l[0]+suma(l[1:])
# Otra manera
def suma(l):
if len(l)==0:
return 0
return l[0]+suma(l[1:])
def fibonacci(n):
... |
58c212a99a48f944b714c6b9406e81716172a1c4 | stevied9366/Simple-Work-Calculator | /Work_Calculator.py | 840 | 3.90625 | 4 | # Calculator that calculates total based on QUANTITY of coins/bills etc.
pennies = input("Number of Pennies: ")
num1 = int(pennies) * float(.01)
print(num1)
nickels = input("Number of Nickels: ")
num2 = int(nickels) * float(.05)
print(num2)
dimes = input("Number of Dimes: ")
num3 = int(dimes) * float(.1)
pri... |
a6afd7599b3dc4cee005b05511230ddd470c40a3 | JanaRasras/2D-Game-using-arcade-library | /P03.py | 3,394 | 3.875 | 4 | '''
Build Your Own 2D Platformer Game using Arcade Library
P03: Add keyboard control
Jana Rasras
Nov.2019
'''
## libraries
import arcade
## constants
WIDTH = 1000
HEIGHT = 650
TITLE = 'A game'
BLUE =[100,149,237]
CHARACTER_SCALING = 1
TILE_SCALING = 0.5
COIN_SCALING = 0.5
PLAYER_MOVEMENT_SPEED... |
209485aa5487dbbf42f31825944f502bd7b71cbf | rwaidaAlmehanni/python_course | /get_started/dictionary/problem37.py | 206 | 4.28125 | 4 | # Write a function valuesort to sort values of a dictionary based on the key.
def valuesort(f):
arr=[]
x=f.keys()
x.sort()
for i in x:
arr.append(f[i])
print arr
valuesort({'x': 1, 'y': 2, 'a': 3}) |
cc395661950473f79a34f7967c11b5770fe8b13a | MonaTem/algorithms-practice | /SubArray_Cum_Sum.py | 462 | 3.921875 | 4 | # Python program to find the start and end index of a subarray
# that equals a sum passed in
# function to check for subArray that equals the sum
def subArray(a, X):
# Create empty hash set
s = set()
sum = 0
for i in range(0,len(a)):
sum = sum + a[i]
if sum == X:
print (0, i)
if s... |
5ec24cea48ce106fe50599a29a723bae548d9b5b | atu-ce/Error-Management | /handling.py | 1,417 | 4.1875 | 4 | # error handling => hata yönetimi
# Yöntem 1 -> Detaylı gösterim, belirtilen hatalar için özel mesaj.
try:
x = int(input("x: "))
y = int(input("y: "))
print(x / y)
except ZeroDivisionError:
print("y değeri için 0 girilemez.")
except ValueError:
print("x ve y değerleri için sayısal değer... |
2dbb7b7e371c0e19a52fb5089169d4ce392d9315 | appan-roy/Seleniun-Python | /LearnPython/Pattern/Pattern23.py | 416 | 3.6875 | 4 | """
1
2 2 2
3 3 3 3 3
4 4 4 4
5 5 5
6 6
7
"""
for i in range(1, 4, 1):
for j in range(i, 3, 1):
print("\t\t", end="")
for k in range(1, 2*i, 1):
print(str(i)+"\t\t", end="")
print()
for x in range(4, 8, 1):
for y in range(x, 3, -1):
pri... |
983905009d611aa5df69e476320e5405728cf778 | casterbn/my_program | /python_/list_test.py | 203 | 3.59375 | 4 | #!/usr/bin/python
list = ["dai",123,10.02]
list_1 = ["chenghe"]
list[2] = "hehe"
print list[0]
print list
print list[0:1]
print list * 2
print list + list_1
print "********************"
print list[1:2]
|
965dd0529742981315d7def9188da23bad1374e4 | houziershi/PythonStudy | /demo/my_demo.py | 791 | 3.859375 | 4 | #! usr/bin/env python3
# -*- coding:utf-8 -*-
def variable_arg(a, b, *l):
"""可变参数"""
return a + b + sum(l)
def key_word_arg(name, age, **key):
"""关键字参数"""
print(name, age, 'other ===', key)
def named_keyword_arg_1(name, age, *, city, job):
"""命名关键字参数形式1"""
print(name, age, city, job)
def... |
afe16866cf0836690c40be6ef1fe947bd1288eea | salterb/ktane | /simple_wires.py | 3,312 | 3.953125 | 4 | """Simple Wires
The Simple Wires module consists of 3-6 horizontal wires with various
possible colours.
"""
from utils import get_input
from colours import bold
def _is_valid_simple_wires(wires):
"""Helper function to determine if the wire arrangement specified
is valid.
"""
if len(wires) < 3 or len(... |
ac7509aa1b31a80ba8720b1ea168b686c65f705f | agandhasiri/Python-OOP | /program 2 DNA/dna.py | 1,375 | 4.25 | 4 | DNA=input("Enter a DNA sequence: ")
pattern=input("Enter the pattern: ")
reversed_pattern=pattern[::-1]
a=DNA.find(pattern) # Finding start index of pattern
c=len(pattern) # Finding length of pattern
b=DNA.... |
9b2dc2edb737fda6c72adfd3d39a3442296b2aca | prabhat997/demo | /hackerrank/practise here.py | 489 | 3.875 | 4 | import random
n=(random.randint(1,10))
guess_count = 0
guess_limit=4
print('you have 5 chances:')
while (guess_limit<=4):
guess_number=int(input('guess the number:\n'))
guess_limit -= 1
if guess_number > n:
print('insert lower number')
elif guess_number < n:
print('inser... |
8b0487dc802ab14c39ec86426adb85b34abd0772 | Goooaaal/ali_freshman_compatiton | /model_lr_and_gdbt_and_xgboost/data_preanalysis/dict_csv.py | 1,549 | 3.859375 | 4 | import csv
####
# convert csv file to dict
####
# convert csv file to dict(key-value pairs each column)
def csv2dict(csv_file, key, value):
new_dict = {}
with open(csv_file, 'r')as f:
reader = csv.reader(f, delimiter=',')
# fieldnames = next(reader)
# read... |
692585667a88981a77b87e1d35507d353342579a | JQ-WCoding/Python_base | /Base/Solution/Q.py | 483 | 3.640625 | 4 | class Calculator:
def __init__(self):
self.value = 0
def add(self, val):
self.value += val
class UpgradeCalculator(Calculator):
def minus(self, val):
self.value -= val
class MaxLimitCalculator(Calculator):
def maxLimit(self):
if self.value > 100:
self.val... |
9ce46135324bb104ef8f201945dd2fec1922b977 | souza10v/Exercicios-em-Python | /activities1/codes/37.py | 638 | 4 | 4 | // -------------------------------------------------------------------------
// github.com/souza10v
// souza10vv@gmail.com
// -------------------------------------------------------------------------
s1=int(input("Primeiro segmento: "))
s2=int(input("Segundo segmento: "))
s3=int(input("Terceiro segmento:"))
... |
3ed77cb0475c6ba1258af189beb950698ecb1e51 | amrfekryy/course-CS50W | /lecture2 - Flask/24notes/application.py | 1,429 | 3.734375 | 4 | # import "session" to store user-specific data
from flask import Flask, render_template, request, session
# imoprt "Session" to control "session"
from flask_session import Session
app = Flask(__name__)
# store the sessions server-side
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
... |
05bf09066c39e7a7e808c78b4b79790b141c4356 | Mchighjohnny/Microsoft-DAT208x-Introduction-to-Python-for-Data-Science | /Manipulating Data.py | 1,874 | 3.59375 | 4 | ##Creating Columns I
# Add sharemen column
recent_grads['sharemen'] = recent_grads['men'] / recent_grads['total']
print(recent_grads)
##Select Row with Highest Value
# Find the maximum percentage value of men
max_men = np.max(recent_grads['sharemen'])
# Output the row with the highest percentage of men
print(rece... |
8c0a7ee4bc3f8bff16ea3ff3002a27e58de95f3c | arielramirez/people-sorter | /sort_people.py | 3,737 | 4.28125 | 4 | # Task:
# In the language of your choice, please write a function that takes in a list of unique people and returns a list of the people sorted.
# People have a name, age, and social security number. Their social security number is guaranteed to be unique.
# The people should be sorted by name (alphabetically) and age... |
659c1b1a43d2f1005a8a63eb25983383cdf911d9 | JenZhen/LC | /lc_ladder/Basic_Algo/binary-tree/Binary_Tree_Path_Sum_III.py | 1,944 | 4.1875 | 4 | #!/usr/bin/python
import BinaryTree
# https://leetcode.com/problems/path-sum-iii/
# Example
# You are given a binary tree in which each node contains an integer value.
#
# Find the number of paths that sum to a given value.
#
# The path does not need to start or end at the root or a leaf, but it must go downwards (trav... |
25cfee827f5c7cd472c7aabdedd6314365d4b662 | AddisonG/codewars | /python/stop-gninnips-my-sdrow/stop-gninnips-my-sdrow.py | 383 | 4 | 4 | def spin_words(sentence):
result = ''
words = sentence.split(' ')
for word in words:
if (len(word) >= 5):
result += " " + reverse(word)
else:
result += " " + word
return result[1::]
def reverse(word):
reversedWord = ''
for letter in word:
... |
196ce00a26dd8405a219154329d188679fc60fbd | JaydipMagan/codingpractice | /leetcode/May-31-day/week5/edit_distance.py | 2,060 | 4.0625 | 4 | """
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse... |
30d00c14122802366b74d82c095875dc261946c5 | mrusinowski/pp1 | /01-TypesAndVariables/z20.py | 171 | 3.75 | 4 | r = 6
pi = 3.141592
pole = pi*r**2
obwod = 2*pi*r
print("Pole koła o promieniu {} wynosi {}".format(r,pole))
print("Obwód koła o promieniu {} wynoi {}".format(r,obwod)) |
a48c65586d74342cd8611930e1b458e8c6ef3da7 | carlosDevPinheiro/Python | /src/Unisa/Exemplos de programas em Python/árvore2.py | 1,811 | 3.84375 | 4 | # -*- coding: cp1252 -*-
class Tree:
def __init__(self, cargo, left=None, right=None):
self.cargo = cargo
self.left = left
self.right = right
def printTreeIndented(tree, level=0):
if tree == None: return
printTreeIndented(tree.right, level+1)
print ' '*level + str(tree.cargo)... |
6045b17e552e3b9315ba06a3a9029d29fe99c2b1 | NikolayVaklinov10/Interview_Preparation_Kit | /Recursion_and_Backtracking/Recursive_Digit_Sum.py | 326 | 3.5625 | 4 | def superDigit(n, k):
def add_digits(string):
if len(string) == 1:
return string
result = sum(int(s) for s in string)
return add_digits(str(result))
start = sum(int(s) for s in n) * k
return add_digits(str(start))
# OR
n, k = map(int, input().split())
print( n * k % 9 ... |
428049684621761f24ac8e7e1a935b3fafcb5eed | vishnuvardhan1807/Datastructure-algorithms | /Triplets.py | 1,014 | 4.03125 | 4 | def triplets(array, targetsum):
array.sort()
for i in range(len(array)-2):
for j in range(i + 1, len(array) - 1):
for k in range(j + 1, len(array)):
if array[i] + array[j] + array[k] <= targetsum:
print((array[i], array[j], array[k]))
# Finding triple... |
e94debeb80bb50eb8562eacd6746ec929ae8d965 | Platforuma/Beginner-s_Python_Codes | /9_Loops/26_Conditional_Statement--each-even-digit-in-range.py | 355 | 4.0625 | 4 | '''
Write a program, which will find all such numbers between 1000 and 3000
(both included) such that each digit of the number is an even number
'''
values = []
for num in range(1000,3001):
num = str(num)
if int(num[0])%2==0 and int(num[1])%2==0 and int(num[2])%2==0 and int(num[3])%2==0:
values.append... |
a452489e25331014e4ea0e54ad03487fa0c41230 | Chadzero/Python_Tuturials | /Project_Euler/003-Largest_prime_factor.py | 1,121 | 4 | 4 | #!/usr/bin/env python
# Name: 003-Largest_prime_factor.py
# Auther: cRamey
# Problem
####################################################
# The prime factors of 13195 are 5, 7, 13 and 29.
#
# What is the largest prime factor of the number 600851475143 ?.
####################################################
... |
32e71b73e59d3885cfbc2cdd58c2f234da4a0c78 | JeanBilheux/python_101 | /exercises/Modern python tips and tricks/decorators.py | 474 | 3.765625 | 4 | """Decorator exercises"""
from functools import wraps
def catch_all(func):
"""Trap non-exiting errors and ask user if we should ignore."""
@wraps(func)
def new_func(*args):
try:
return func(*args)
except Exception as error:
print("Exception occurred: {}".format(erro... |
5659477a9eb3ad38e51c4337e027a7c1b6a6e871 | zzZ5/StudyNote | /Python/strategy.py | 1,301 | 3.9375 | 4 | #!usr/bin/python3
# -*- coding: utf-8 -*-
# author zzZ5
class Order:
# 建立订单时必须设定价格, 可以选择折扣方式, 若不选择则为原价
def __init__(self, price, discount_strategy=None):
self.price = price
self.discount_strategy = discount_strategy
# 可以临时更改折扣方式
def set_strategy(self, discount_strategy: function):
... |
445f0f524e1813dea78a79603ef97b0b647cbda6 | andesviktor/Python_adv_lessons | /homeworks/homework_library/book.py | 628 | 3.6875 | 4 | class Book:
""" Класс книги и действий с ней """
def __init__(self, book_id: int, book_name: str, book_author: str, book_year: int, book_available: bool):
"""
:param book_id: ID книги
:param book_name: Имя книги
:param book_author: Автор книги
:param book_year: Год выпус... |
1413a4380f2a3f56cdce48040bf95094729e6c68 | BStrope/Intro-to-algorithms | /hot_potato_queues.py | 496 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 10 13:41:38 2021
@author: - Benjamin Strope
"""
from datatypes import Queue
def hot_potato(players,passes):
q = Queue()
for player in players:
q.enqueue(player)
while q.size() > 1:
for i in range(passes):
ha... |
55bece2d8d5589962a6835f3fde0661446220d70 | orangedidlo/SOFTUNISHITZz | /24.07.py | 2,571 | 3.71875 | 4 | # for i in range(1, 101):
# print(i)
#
#
#
#
#
# num = int(input())
#
# for i in range(1, num + 1, 3):
# print(i)
#
#
#
#
# num = int(input())
#
# for i in range(0, num + 1, 2):
# print(2 ** i)
#
#
#
#
#
#
#
# num = int(input())
#
# for i in range(num, 0, -1):
# print(i)
#
#
#
#
# symbols = input()
... |
c56c124bf4c34d0d7f50bc10a072480078f33ce3 | TayKristian/Python | /Estrutura_Decisão/Questão 01.py | 227 | 3.984375 | 4 | n1 = int(input('Informe o 1° numero: '))
n2 = int(input('Informe o 2 ºnumero: '))
if (n1 > n2):
print (n1, 'é maior que', n2)
elif (n1 < n2):
print (n2, 'é maior que', n1)
else:
print ('Os numeros sao iguais')
|
acca8016fdb8bcdc2d1446c610c1fdebcb8bf54d | zc2214/Introduction-to-Computer-Programming | /ICP exercise and assignment/A03/A03_exercise2.py | 552 | 4.3125 | 4 | # PROGRAMMING ASSIGNMENT 03
# Filename: 'exercise2.py'
#
# Write a program that does the following:
# 1. asks the user to input a password length N (type: int, positive)
# 2. then, generates and prints a random password of N characters*
#
# *see the list of valid characters in the pdf file
#
# NOTE: you MUST u... |
4125f9e1ff9732988c3df2b03bbce9d4adc8c67b | k4k7u3/betroot-test | /lesson11/task3json.py | 9,449 | 3.546875 | 4 | import json
json_info = None
class Product:
my_type = ""
name = ""
price = 0
def __init__(self, my_type, name, price):
if type(my_type) != str:
raise ValueError("Type should be a string")
if type(name) != str:
raise ValueError("Type should be a string")
... |
7dc1a7671c25503669480605988a3d14441ffc64 | weipanchang/FUHSD | /turtle-house.py | 779 | 3.609375 | 4 | #!/usr/bin/env python
import time
from turtle import *
def square(length):
for i in range(4):
fd(length)
rt(90)
def retangle(x,y):
fd(x)
rt(90)
fd(y)
rt(90)
fd(x)
rt(90)
fd(y)
rt(90)
def door(lx, ly, turn, x, y):
penup()
goto(lx,ly)
pendown()
rt(turn... |
106440bf8dbc8a5956d1344da2763040a16e8f84 | TylerBromley/fullstack_python_codeguild | /lab9-unit-converter_v4.py | 1,711 | 4.0625 | 4 | # lab9-unit-converter_v4.py
# get the user's distance, sans unit of measure
distance = float(input("What is the distance? "))
# ask for in an out units, but restrict the way they can be entered to numbers
in_unit = int(input("What is the input unit? Please enter\n\t[1] for feet\n\t" +
"[2] for miles\n\... |
d46de45f5e5fa539a88e3ea411a0a2c0037ff9b1 | gabriellaec/desoft-analise-exercicios | /backup/user_148/ch19_2020_04_01_04_46_50_488834.py | 213 | 3.671875 | 4 | def classifica_triangulo(x, y, z):
if x==y==z:
print('equilátero')
elif x!=y!=z:
print('escaleno')
elif x==y and y!=z or x==z and z!=y or y==z and x!=z:
print('isósceles') |
063a6884b107d50c14715779425e5d3f2d053b58 | shakfu/polylab | /py/genetic/basic/basic35.py | 5,646 | 4.25 | 4 | """
helloevolve.py implements a genetic algorithm that starts with a base
population of randomly generated strings, iterates over a certain number of
generations while implementing 'natural selection', and prints out the most fit
string.
The parameters of the simulation can be changed by modifying one of the many
glob... |
9339060107bef177c65e11f8f90005a64e3ff59f | L200170153/coding | /da best/uas/uas3.py | 203 | 3.578125 | 4 | def putar(l):
k = []
a = l[-2:]
b = l[0:len(l)-2]
for i in a:
k.append(i)
for l in b:
k.append(l)
print(k)
l = [x for x in input().split(',')]
putar(l)
|
11f5f26f7d43db15614a8fb2e5a4a003b878307b | madhavibadekolu/python | /assignment programs/exception handling/ex1.py | 368 | 3.796875 | 4 | try:
n1=int(input('enter 1st number:'))
n2=int(input('enter 2nd number:'))
print('sum=',n1+n2)
try:
print('div=',n1/n2)
print('mul=',n1*n2)
print('sub=',n1-n2)
except ZeroDivisionError as ze:
print(ze)
print('mul=', n1 * n2)
print('sub=', n1 - n2)
exc... |
3eccc969ae4865e8cb27c56b4862248777089d2c | kbr1218/project_comcode | /파이썬_자료/TupleTest.py | 1,232 | 3.84375 | 4 | #Tuple 튜플
print("-" * 10, "tuple 생성/type 확인", "-" * 10)
t1 = (1, 2, 3) #괄호를 이용해서 만든 튜플
t2 = 5, 6, 7 #괄호 없이 만든 튜플
print(type(t1), type(t2)) #튜플의 type 확인
#요솟값 삭제 불가 del t[x]
# del t1[0] ---> 튜플의 값은 삭제할 수 없으므로 오류 발생
#요솟값 변경 불가 t[x] = x
# t1[0] = 3 ---> 튜플의 값은 수정할 수... |
48250c93ca983b875d11dbda7652038d1fd7ca00 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2510/60705/297143.py | 64 | 3.65625 | 4 | l = input()
if l == "5 2 2 24":
print(19)
else:
print(l) |
0bd281dc799aa8c5b0e696125581a7acf5ce61d0 | wrossmorrow/cattree | /cattree.py | 16,844 | 3.765625 | 4 | import numpy as np
# utility function; return True if the argument is a positive integer
def is_pos_int( n ) :
import numbers
if not isinstance( n , numbers.Integral ) : return False
elif n <= 0 : return False
else : return True
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #... |
e2fd0421db552cd047b2ec0351b7b002475f8fe8 | jeonggoun/python3 | /data_type.py | 1,338 | 3.84375 | 4 | # 데이터 자료형(data type)
# 숫자형
# 변수
# 문자, _으로 시작
# 공백x (한글x)
# 예약어 x - Camel Case / Snake Case
# 변수 : 데이터를 담는 그릇, 공간, 컨테이너, 변한다
# 리터럴 : 5; '한'
num1 = 13
num1 = 5
# num1의 공간에 숫자 3이 저장되어 있는 것
num2 = 3.5
# num2의 공간에 숫자 5가 저장되어 있는 것
print(num1+num2)
# 변수의 데이터 타입 확인 -type()
print(num1+num2)
print(type(num1))
print(type("hello w... |
8a1b42d50065636aa2b86cc44e976cfda99b2b7d | xuzhendongfire/python | /日期_数码管.py | 2,095 | 3.578125 | 4 | import turtle
#设置回执日期长度和间隔
le = 50
itv = 20
#定义数字,传入(x,y)和number
def drowDate(x,y,n):
d = turtle.Turtle()
d.speed(5)
d.pensize(10)
d.color("red")
d.hideturtle()
d.penup()
d.goto(x,y)#画笔移动到起点
d.pendown()
#绘制 从上到下,从左到右
#第一横
if n==0 or n==2 or n==3 or n==5 or n==6 or n==7... |
0764dec5163d43f1d34f36fdd25c1ee52df26e86 | junjongwook/programmers | /Skill Check/Level4/s12942.py | 916 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
최적의 행렬 곱셈 : https://programmers.co.kr/learn/courses/30/lessons/12942?language=python3
"""
M = dict()
def solution(matrix_sizes):
def MIN(i1, i2):
if i1 == i2:
return 0
if (i1, i2) in M:
return M[(i1, i2)]
if i1 + 1 == i2:
M[(i... |
46dc24f0bb63753f5eab5114c0e10f9b2510f33b | Kiris-Wu/recipeProj | /EECS337/recipeNT.py | 512 | 3.671875 | 4 | import recipegenerator as recipe
import SL as sl
url = input("Please input URL(type a space in the end then enter): ")
print("You want to transform recipe url is :"+ url)
url=url.strip()
if(url==""):
print("You did not enter anything, using the default link...")
url="https://www.allrecipes.com/recipe/220125/slo... |
3bfad7917439fefa88f74c1ceab0626ad744813e | EuricoDNJR/beecrowd-URI | /Em Python/1173.py | 133 | 3.546875 | 4 | first = int(input())
n = [first]
for i in range(0, 9):
n.append(n[i] * 2)
for i in range(10):
print("N[%d] = %d" % (i, n[i])) |
0a40bfd5e6e93bf7327296a4736e489dce891010 | deeplymore/erp | /get_summary.py | 2,573 | 3.84375 | 4 | # -*- coding: utf-8 -*-
def math_test():
a_contents = int(input("请输入第一种类型可以乘坐或拥有的个数:"))
a_price = int(input("请输入第一个类型的价格:"))
b_contents = int(input("请输入第二种类型可以乘坐或拥有的个数:"))
b_price = int(input("请输入第二个类型的价格:"))
print("--------------------------------------------------------------------------")
... |
1f38ee947a36fc3e1ea2d2bd3a6347f5faf4832a | zhangchizju2012/LeetCode | /747.py | 914 | 3.578125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 23 19:28:32 2017
@author: zhangchi
"""
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = []
for item in nums:
if len(result) == ... |
ab44f100361e007e42be6013ef3fe9747d7a0ab9 | nielschristiank/DojoAssignments | /Python/pOOP/animal/animal.py | 1,479 | 3.84375 | 4 | class animal(object):
def __init__(self, name):
self.name = name
self.health = 100
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def displayHealth(self):
print "Animal:", self.name
print "Health:",... |
614fcc668465fee9bbc3af57696e3f535594a43e | arbalest339/myLeetCodeRecords | /main876middleNode.py | 942 | 3.6875 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
@staticmethod
def build(lst):
if not lst:
return
res = ListNode(lst[0])
last = res
for i in range(1, len(lst)):
cur = ListNode(lst[i])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.