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 |
|---|---|---|---|---|---|---|
afab9d1f1ae6d6cefebe19ed9e39a8ed02a7366d | xyLynn/Python_HackerRank | /01_Introduction/05_Loops.py | 353 | 4.09375 | 4 | """
Task
Read an integer N. For all non-negative integers i < N, print i^2. See the sample for details.
Input Format
The first and only line contains the integer, N.
Constraints
1 <= N <= 20
Output Format
Print N lines, one corresponding to each i.
"""
if __name__ == '__main__':
n = int(input())
for i i... |
acb6493fc361dc45688d0163284925443e2c449f | Psp29/basic-python | /chapter 8/04_pract_01.py | 298 | 4.09375 | 4 | def max(num1, num2, num3):
if (num1 > num2):
if(num1 > num3):
return num1
else:
return num3
else:
if(num2 > num3):
return num2
else:
return num3
m = max(13, 69, 420)
print("The Maximum number is: " + str(m))
|
9c8713dc338b53c7730121db398f4309fbdcd826 | PacktPublishing/Text-Processing-using-NLTK-in-Python | /Section02/1.py | 445 | 4.0625 | 4 | namesList = ['Tuffy','Ali','Nysha','Tim' ]
sentence = 'My dog sleeps on sofa'
names = ';'.join(namesList)
print(type(names), ':', names)
wordList = sentence.split(' ')
print((type(wordList)), ':', wordList)
additionExample = 'ganehsa' + 'ganesha' + 'ganesha'
multiplicationExample = 'ganesha' * 2
print('Text Additions... |
9b42b3ea40ed98f478a47e1a21ca43c9d8ec003b | Veselin-Genadiev/NeedForCryptography | /crypto/tools/primes.py | 1,969 | 3.671875 | 4 | from tools.utilities import gcd
from math import sqrt
from random import SystemRandom
def is_prime(number):
return all(number % divisor for divisor in range(2, number))
def filter_divisors(number, numbers):
for divisor in numbers:
if divisor % number:
yield divisor
def primes():
fo... |
963fc4ff3c7e2e7ed1442bed190735a33e6531ab | rissuuuu/Algorithms | /01knapsacknorec.py | 825 | 3.59375 | 4 | def knapsack(w,wt,val,n):
k=[[0 for x in range(w+1)]for x in range(n+1)]
for i in range(n+1):
for j in range(w+1):
if i==0 or j==0:
print("if",i,j )
k[i][j]=0
print("__________")
elif wt[i-1]<=j:
print("elif")
... |
014551641de0edc81ce1fbab56bbc8ba59504850 | LucasLeone/tp1-algoritmos | /estructura_secuencial/es12.py | 631 | 4.0625 | 4 | '''
Teniendo como dato la hipotenusa y
el ángulo que forma ésta con la base
de un triángulo rectángulo. calcular
e imprimir los datos y ángulos restantes.
'''
import math
hipotenusa = float(input('El valor de la hipotenusa: '))
angulo = float(input('El valor del angulo: '))
if angulo > 90:
print... |
f9dc9680f1449908946cf611637d7e38e1d209ae | questonit/numerical-methods | /10.py | 2,095 | 3.75 | 4 | import math
def f(x, y):
return 1 + 0.6 * math.sin(x) - 1.25 * pow(y, 2)
def runge_kutta(f, a, b, x0, y0, h):
x = x0
y = y0
# создадим таблицу значений
points = []
# добавим нулевые значения
points.append((x, y))
while x + h <= b:
# вычисляем k1, k2, k3, k4 по формулам
... |
56adb16ed5c71672024040ca1e4e1462072da38b | LRScudeletti/app-algoritmos-ordenacao | /MergeSort.py | 878 | 3.8125 | 4 | import time
# MERGE SORT
def metricas_mergesort(vetor, ordem):
inicio = time.time()
mergesort(vetor)
fim = time.time()
print("Tempo (ms) vetor " + ordem + ": " + str(round(fim-inicio, 6)))
def mergesort(vetor):
if len(vetor)>1:
meio = len(vetor)//2
esquerda = vetor[:meio]
... |
98800e326fdea68fb4683313d55b92ecfd7e610f | zhengdazhi/py_scripts | /string_for.py | 246 | 4 | 4 | river = 'Mississippi'
target = raw_input('Input a character to find: \n')
for index in range(len(river)):
if river[index] == target:
print "letter found at index"
break
else:
print 'Letter',target,'not found in',river
|
2919b7c874dc487d6b7bb83f2808c2b601142b71 | liangyawang121109/python-study | /面向对象/属性方法.py | 721 | 3.859375 | 4 | class dog(object):
def __init__(self,name):
self.name = name
self.__food = None
@property #属性方法 将一个方法变成一个静态属性 当把它转换成一个属性后 默认是不可以在调用的时候给属性赋值的需要在写一个特殊处理 如下
def eat(self):
print('%s is eating %s'% (self.name,self.__food))
@eat.setter
def eat(self,food):
print('%s is e... |
301c6e24a6929b41c2913ba5cd727487d4d899fd | Aasthaengg/IBMdataset | /Python_codes/p02390/s090238523.py | 180 | 3.71875 | 4 | s=int(input())
sec=s%60
min=s//60 #may be more than 60
hr=min//60
min=min%60
# line 3-6 can be replace with 9-11
hr=s//3600
min=(s//60)%60
sec=s%60
print(hr, min, sec, sep=':')
|
743dde57e283ca6b2b71c219500932d004151c8f | rafi80/UdacityIntroToComputerScience | /varia/Lesson25ProblemSolvingDates.py | 4,073 | 3.625 | 4 | '''
Created on 18 wrz 2013
@author: Stefan
'''
def isLeapYear(year):
if year % 400 ==0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
else:
return False
print isLeapYear(2012)
def daysInMonth(month,year):
assert month < 13
if m... |
f286fe6424a794424c9f93717b8c2ea254f160d8 | kubas1129/WDI | /lab7.py | 1,682 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 08:41:57 2017
@author: palkjaku
"""
ceny = {1:1,2:3}
def primeEratostenes(n):
if (n < 2): return -1
primes = [i+1 for i in range(n)] #init tablicy liczb
primes.remove(1) #usuwamy 1
j = 0 #counter while
while j < len(primes):
numberToChe... |
e0d18df66312ea260a21a097e8eeddabccc3ad8d | kkiran13/Python | /Functions.py | 1,423 | 4.28125 | 4 | def add(a,b):
return a+b
def printthis():
print "Printing from function"
def printargs(name,age):
print "%s is %d years old"%(name,age)
print "Addition function result: %d"%add(1,2)
printthis()
printargs("John", 23)
print
'''
In this exercise you'll use an existing function, and while adding y... |
ae79cdc15f952087a9d06c4247a1cedc54f39282 | Sunil-Yaragoppa/codecademy_exercises | /divisible_by_ten.py | 227 | 3.796875 | 4 | #Write your function here
def divisible_by_ten(nums):
nums_new=[num for num in nums if num % 10 == 0]
return len(nums_new)
#Uncomment the line below when your function is done
print(divisible_by_ten([20, 25, 30, 35, 40]))
|
cf88e0ab147e12380ffdb687dfc78855bb2f48dc | SDrag/weekly-exercises | /exercise3.py | 728 | 4.3125 | 4 | # Dragutin Sreckovic 2018-02-07
# Collatz conjecture
# Asking user for an integer:
userInput = input("Please enter an integer greater then 0: ")
# Checking if it's an integer greater then 0. If not use a default value:
defaultVal = 27
try:
val = int(userInput)
if val == 0:
print("That's not what I've a... |
1141dcc5be6a48b9389931e40e19cdf5aee31057 | ashwinkumarm/CTCI | /linkedLists/partition.py | 630 | 3.515625 | 4 | from CTCI.concepts.Node import Node
def partition(node, x):
ll1 = Node(-1)
ll2 = Node(-1)
ll1_head = ll1
ll2_head = ll2
while node:
if node.value < x:
ll1.next = Node(node.value)
ll1 = ll1.next
else:
ll2.next = Node(node.value)
l... |
2f131a44b8fd5e5784ad7d4e73099228e4ee8729 | WestonMJones/Coursework | /RPI-CSCI-1100 Computer Science I/hw/HW7/test.py | 4,129 | 3.515625 | 4 | """
Description
"""
#Import Statements
import json
#Functions
def make_histogram(val_list):
"""
"""
if not len(val_list)-val_list.count(-9999)<2:
num = int(((sum(val_list)+(9999*val_list.count(-9999)))/(len(val_list)-val_list.count(-9999)))//1)
out_string = "*"*num
else:
o... |
debe336589f17a221b91a5850018a4bdbf75dc6d | thaReal/MasterChef | /tools/sequences/max_subarray.py | 2,070 | 4.21875 | 4 | #!/usr/bin/python3
'''
Functions for determining max contiguous subarray for a given array.
Also additional functions for derivative problems.
'''
def max_subarray(arr):
'''
Find the maximum sum of a contiguous subarray of a given array.
Solution implements Kadane's Algorithm.
'''
dp = [0 for i in range(len(arr)... |
ce705c625c6f495394d5d88ae0dc25d95685561a | osamamohamedsoliman/BFS-1 | /Problem-3.py | 822 | 3.671875 | 4 | # Time Complexity :O(n)
# Space Complexity :O(n)
# Did this code successfully run on Leetcode : yes
# Any problem you faced while coding this : no
# Your code here along with comments explaining your approach
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:... |
0659659779b325ba84154d77f68f744cba36fb57 | jhonatarios/curso-em-video-python | /desafios/ex064.py | 195 | 3.71875 | 4 | n = 0
c = -1
t = 0
while not n == 999:
n = int(input("Digite um numero inteiro: "))
t += n
c += 1
print(f"No total foram digitados {c} numeros, resulto no total de {t-999}.")
|
535713326b32ca15c88e7544de06b2ea92f7e89b | huiyi999/leetcode_python | /Minimum Domino Rotations For Equal Row.py | 4,529 | 3.828125 | 4 | '''
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the ith domino.
(A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the ith domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are the s... |
131cd3af34f3f7845dbae75e16904911c76cbf08 | kgopal1982/Analytics | /Python/AddKeyValue.py | 240 | 4.125 | 4 | #Python Program to Add a Key-Value Pair to the Dictionary
Age = {'Boy1': 30,
'Boy2': 20,
'Boy3': 40}
print("Orig Dictionary is :", Age)
Age['Boy4'] = 25
print("Age of Boy4 is :", Age['Boy4'])
print("new Dictionary is :", Age)
|
4dbd7bf17903bb0b4850a7985db2dd164c3f6cad | eapmartins/ds-algorithms | /src/linkedlist/linked_list.py | 2,758 | 3.859375 | 4 | from src.base.node import Node
class LinkedList:
def __init__(self):
self.head = None
def to_list(self):
out = []
node = self.head
while node:
out.append(node.value)
node = node.next
return out
def prepend(self, value):
if s... |
527a91169240bb5d7ba72a2dc4a4b0458f020a84 | nemodark/pythonCourseAnswers | /1st week/helloworld.py | 509 | 3.953125 | 4 | # this is a 1 line comment
"""This is
a multiple line
comment"""
print("Hello World")
name = "John Doe"
_age = "20 years old"
grade = 100
# _age = 30
location = "I'm from Philippines"
location2 = 'I\'m from Japan'
message = "My name is " + name
add = 100 + 200
print(add)
print(message)
print(name)
print(_age)
print(... |
948cca332988e0d5fef5846eac918ff034d9ab88 | shamilyli/python_work | /try2.py | 1,424 | 4.28125 | 4 | """ introduction for []"""
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles) #['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0]) #trek
print(bicycles[1].title()) #Cannondale
print(bicycles[-1]) #specialized
message = "My first bicycle wa a " + bicycles[0].title() +"."
pri... |
a6c7b8c0e3a0fba1efc7dc2031c43f95ba5689c6 | gaulghost/py4e | /Intro/ExpCalc.py | 1,539 | 4.21875 | 4 | print("which mathematical expression would you like to preform")
print("power / 1 / '**'")
print("division / 2 / '/'")
print("multipication / 3 / '*'")
print("substraction / 4 / '-'")
print("addition / 5 / '+'")
print("remainder / 6 / '%' \n")
x = None
y = None
operand = None
m = 0
while True:
try :
... |
71945b65b826b18262be1ef86260352b8bdb829f | kamojiro/atcoderall | /beginner/070/A.py | 76 | 3.578125 | 4 | N = input()
RN = N[::-1]
if N == RN:
print('Yes')
else:
print('No')
|
0e48f63e6576464578141c4f17e3760f78d2c75e | shirleychangyuanyuan/LeetcodeByPython | /88-合并两个有序数组.py | 679 | 4.09375 | 4 | # -*- coding:utf-8 -*-
# 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
# 说明:
# 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
# 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int... |
ec3740c9b189ad55ee44299ed6d9abfa08ce0df6 | megam5/Virtual-Desktop-Assistant-using-Python-from-Scratch | /main.py | 3,838 | 3.671875 | 4 | # import packages
import pyttsx3 # text to speech (https://github.com/nateshmbhat/pyttsx3)
import speech_recognition as sr # speech recognition (https://github.com/Uberi/speech_recognition)
import datetime # access date and time
import wikipedia ... |
de92a6cb1857d6961876a26a6a37f0bc5fa6079e | besson/my-lab | /algos/algos/redundant_braces.py | 328 | 3.890625 | 4 | # Check if an expression has redundant braces
def has_redundant_braces(expression):
ops = 0
stack = []
for w in expression:
if w is "(":
stack.insert(0, w)
elif w is ")":
if (ops == 0):
return True
else:
stack.pop(0)
ops = ops - 1
elif not w.isalpha():
ops = ops + 1
return len(st... |
756faa982017cb3ecdc0c5f11bd85d3d90d24c72 | gdpe404/formation_python | /08-exceptions/erreur.py | 972 | 3.859375 | 4 | # Par defaut, lorsque python rencontre une erreur, il quitte le programme
# Et il affiche une erreur dans le terminal
# On dit que python leve une exception
# 1 / 0
# print("On continue")
# On peut capturer une erreur en faisant
try:
# bloc d'instruction
1 / 0
except:
print("Erreur, division par 0 impossi... |
51f50ef9f1c25aaa74eca487a9ca47078321cceb | jinghanx/chea | /python/unique_paths.py | 358 | 3.515625 | 4 | #! /usr/bin/env python
def f(m, n):
shorter = min(m,n)
longer = max(m,n)
s = [0 for i in range(shorter+1)]
for i in range(longer-1, -1, -1):
for j in range(shorter-1, -1, -1):
if i == longer-1 and j == shorter-1:
s[j] = 1
else:
s[j] = s[j] ... |
a9f4104698114a35443545a4c187e9d42ed8c967 | ArthurG/Algorithms-Data-Structures-and-Design | /Algorithms/LeetCode Questions/String/49.groupAnagrams.py | 1,559 | 4 | 4 | # COMPLETED
'''
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
'''
class Solution:
def groupA... |
1e28b269ffa487027f68258d08d7686a4cb5bb4c | PyDrummer/data-structures-and-algorithms | /python/array_shift/array_shift.py | 336 | 3.875 | 4 | def insertShiftArray(list, num):
if len(list) % 2 == 0:
newList = []
midpoint = len(list)//2
newList = list[0:midpoint] + [num] + list[midpoint:]
return newList
else:
newList = []
midpoint = len(list)//2+1
newList = list[0:midpoint] + [num] + list[midpoint:]
return newList
# print(i... |
e4a143e16ac62366f7c93778c51ea7b9fda7a7ed | IvanAlexandrov/HackBulgaria-Tasks | /week_0/1-Python-simple-problem-set/sevens_in_a_row.py | 432 | 3.765625 | 4 | def sevens_in_a_row(arr, n):
sevens_count = 0
for number in arr:
if number == 7:
sevens_count += 1
if sevens_count == n:
return True
else:
sevens_count = 0
return False
def main():
print(sevens_in_a_row([10, 8, 7, 6, 7, 7, 7, 20, -7], 3))
print(sevens_in_a_row([1,7,1,7,7], 4))
print(sevens_i... |
07bd82946e1ce1970f4b748a72b881949ade6289 | jbtaylor1202/Python-Web-Scrapers | /test.py | 1,174 | 3.71875 | 4 | #!/usr/bin/env python3
#Script from Chapter 1 (Page 11) of Webscraping with Python
from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
def getTitle(url):
try:
html=urlopen(url)
except HTTPError as e:
return None
try:
bsObj = Beautifu... |
7f4a8f07ea2efdd757521724fac754ff3267b957 | zhoubaozhou/algorithm_study | /qsort.py | 750 | 3.78125 | 4 | #!/usr/bin/env python
#-!-coding:utf8-!-
def swap(array, x, y):
array[x],array[y] = array[y],array[x]
def partition(array, begin, end):
pivo = array[begin]
l = begin
for i in xrange(begin + 1, end):
if array[i] > pivo: continue
l += 1
swap(array, i, l)
swap(array, begin, l)... |
1cb15ec3410ec4394abd499583c42afb4e45a56d | vikbehal/Explore | /EfficientCoding/Assignment-12-MilitaryTime.py | 565 | 3.96875 | 4 | # with library
from datetime import datetime as dt
#print(dt.strptime(dt.strptime(input(), '%I%M%S%p'), '%H%M%S'))
tme = "11:21:30PM"
print(dt.strftime(dt.strptime(tme, '%I:%M:%S%p'), '%H:%M:%S'))
# without any library
tme = "11:21:30PM"
#hour, minutes, secondsplus = input().split(":")
hour, minutes, second... |
374104efe92e4bc505376343aec3518eecf341a2 | Lei9999/Python | /Learn/学习笔记/while中使用else语句.py | 255 | 4.0625 | 4 | """
while 表达式:
语句1
else:
语句2
逻辑:
在条件语句(表达式)为False时,执行else中“语句2”
"""
a = 1
while a <= 3:
print("循环!")
a += 1
else:
print("循环结束啦!")
print("退出循环!")
|
c8f50e6d711f8bded338fc550037858d2e715951 | Kareemali20/GoMyCode-Submissions | /QUESTION 6.py | 790 | 3.90625 | 4 | import pandas as pd
import numpy as np
# ASKING THE USER IF HE WANTS 1 OR 2 DIMENSIONAL ARRAY
Choice = int(input("Do you want 1 or 2 dimension array ?"))
Array1 = []
Array2 = []
if Choice == 1:
Elem = int(input('Enter the number of elements you want in the arrays : '))
Array1 = np.random.randint(1... |
f63893477f37269298305ac89d0f82c5520be592 | KKris13/PYTHON | /guess number.py | 543 | 3.78125 | 4 | #彩票小游戏
import random
#产生随机两位数数字
x=random.randint(10,99)
x1=x%10
x2=x//10
#用户输入数字
guess=int(input("Enter your lottery pick(two digits):"))
g1=guess%10
g2=guess//10
print("the lottery number is :",x)
#判断中多少钱
if guess== x:
print("match two digits in order ,win ¥10000")
elif x1==g2 and x2==g1:
print(... |
b72833e7db20ad5c980381763c6181898e5ddf44 | lengelberts/SimulaQron-QC | /redundant/hashing.py | 958 | 3.890625 | 4 | from numpy import matrix
def extended_sublist(x,I):
"""
Return the elements of x whose index is in I and pad with 0s to obtain same length as x.
Input argument:
x -- list of integers 0s and 1s (length n)
I -- list of non-decreasing integers i, where 0 <= i < n
Output:
list of length n
... |
47fb39a17949d674af237e2fd23c7fcbee6a4dbe | karchi/codewars_kata | /已完成/Find the odd int.py | 490 | 3.859375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
# 题目地址:
https://www.codewars.com/kata/54da5a58ea159efa38000836/train/python
'''
import unittest
class TestCases(unittest.TestCase):
def test1(self):self.assertEqual(find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]), 5)
def find_it(seq):
seq2 = list(set... |
aa10995f711b677195c51ec6c58836c07b8faac1 | LucianoSantosOliveira/AulaPythonHashtag | /Listas/Exercicio listar livro.py | 1,247 | 4.03125 | 4 |
from typing import cast
produtos = ['computador', 'livro', 'tablet', 'celular', 'tv', 'ar condicionado', 'alexa', 'máquina de café', 'kindle']
#cada item da lista dos produtos corresponde a quantidade de vendas no mês e preço, nessa ordem
produtos_ecommerce = [
[10000, 2500],
[50000, 40],
... |
2092fc667798be408b15067ad6d43ec8bf23e7a7 | w51w/python | /0928/함수6_turtle.py | 561 | 3.890625 | 4 | import turtle
def drawBarChar(t, value):
t.begin_fill()
t.left(90)
t.forward(value)
t.right(90)
t.forward(40)
t.right(90)
t.forward(value)
t.left(90)
t.end_fill()
def bubble(alist):
for p in range(6):
for i in range(6):
if alist[i] > alist[i+1]:
... |
69eef3ede193dcfa0555f765d9c298d23166882b | bomcon123456/DSA_Learning | /LeetCode/E_palindrome_linked_list.py | 984 | 3.625 | 4 | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head is None or head.next is None:
return True
mid_node = self.findMidNode(head)
reverse_list = self.reverse(mid_node)
runA = head
runB = reverse_list
while runB is not None:
if... |
7539c7e5bb4060a3872ec40b9c8320b8bdcd6693 | PaulLiang1/CC150 | /binary_tree/valid_BST/valid_BST.py | 1,057 | 3.921875 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
# http://www.lintcode.com/en/problem/validate-binary-search-tree/
class Solution:
"""
@param root: The root of binary tree.
@return: True if the binary tree is BST, ... |
6c3a5a87f06c4bd37b84bd3218ad0eb72a333bf3 | Luis4754/Mision_03 | /mision 3/Trapecio.py | 858 | 3.6875 | 4 | #Luis Fernando Duran Castillo
#Calcular el area y perimetro del trapecio
def calcularPerimetro(baseMayor, basemenor, altura):
perimetro= baseMayor + basemenor + (2*altura)
return perimetro
def calculararea(baseMayor, basemenor, altura):
area= ((baseMayor + basemenor)/2)* altura
return area
... |
4a653ba70b58c1016a91736b9995b98e29e83e8d | arnabs542/DS-AlgoPrac | /graphs/knightChess.py | 2,234 | 3.953125 | 4 | """Knight On Chess Board
Problem Description
Given any source point, (C, D) and destination point, (E, F) on a chess board of size A x B, we need to find whether Knight can move to the destination or not. The above figure details the movements for a knight ( 8 possibilities ). If yes, then what would be the minimum nu... |
36d5c69fce7737f22270c16175fba47aa38d71e5 | Squiercg/recologia | /project_rosalind/fibd.py | 585 | 3.734375 | 4 |
def reverse_complement(s):
complements = {'A':'T', 'T':'A', 'G':'C', 'C':'G'}
return "".join([complements[c] for c in reversed(s)])
def reverse_palindromes(s):
results = []
l = len(s)
for i in range(l):
for j in range(4, 12):
if i + j > l:
continue
... |
3f50654661d5ee19d78e03b4398ee3d17b25cc09 | 454400098/UI_snow_clean | /mysite/snow/snow_main/network.py | 3,949 | 3.53125 | 4 | class Graph(object):
def __init__(self):
self.adj_list = {}
self.nodes = []
self.node_val_map = {}
self.val_node_map = {}
self.locations = {}
self.edge_costs = {}
class CPGraph(object):
def __init__(self, graph):
self.orig_graph = graph
self.od... |
ce3ef25e41564ad5e9dc9d6bbe33a455ab5dbbe5 | shyammudaliar/QR-Code-Generator-Python | /qrcodegenerator.py | 462 | 3.875 | 4 |
#QR code generator
import pyqrcode
from pyqrcode import QRCode
# Enter url/link which is to be converted into the QR code
qr = input("Enter the link or url of which you want to generate the qrcode for: ")
# Generating QR code
url = pyqrcode.create(qr)
#Enter name of the file with which you wa... |
eccf6ba4a7a0f528e6b250ee6d509d3c67ae9d09 | VenkatalakshmiM/guvi | /my programs/pow2.py | 81 | 3.734375 | 4 | num=int(input())
res=(num&(num-1))
if res==0:
print("yes")
else:
print("no")
|
13cdf0242d9b65bf5874d9a6967ee1746f2d3530 | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_05/exception_1.py | 189 | 3.796875 | 4 | a = int(input("enter first num"))
b = int(input("enter second num"))
try:
c=a/b
print(c)
except ZeroDivisionError:
print("divison by zero is done please change the second num") |
643b0ab9efcb065518e02cbadc4a7ee02e18df8f | A01745969/Mision_04 | /Rectangulos.py | 1,239 | 3.90625 | 4 | # Paulina Mendoza Iglesias
# El programa calcúla áreas de rectángulos
def calcularArea(base, altura):
area = base * altura
return area
def calcularPerimetro(base, altura):
perimetro = (base*2) + (altura*2)
return perimetro
def main ():
base = int(input("Teclea la base del rectángulo 1: "))
... |
9e18ca0c910a39afcedd81193e4b16ecdffb726e | PatrykDagiel/Python_Dawson | /Chapter IV/dostep_swobodny.py | 225 | 3.75 | 4 | import random
word = "indeks"
high=len(word)
low=-len(word)
for i in range(10):
position = random.randrange(low, high)
print("word[", position, "]\t", word[position])
input("\nAby zakonczyc program nacisnij enter") |
329d2cdc7f7f0b745946f49bab03e56736818019 | JoshChubi/Academic | /Spring2019/Intro to Python/Test Practice/Two.py | 160 | 3.9375 | 4 | # Josh Ortiz cs 561
# Question 2
num = 1
sum = 0
while(num%5!=0):
num = int(input("Please enter number:"))
if num%2 == 0:
sum += num
print("Sum:",sum) |
fcb100db898cb236f64e6bc43db6fafbb50812f2 | shivekchhabra/ricebowl | /ricebowl/plotting.py | 2,911 | 3.765625 | 4 | import seaborn as sns
import matplotlib.pyplot as plt
from ricebowl.processing import data_preproc
def pairplot(df, hue=None, cols=['ALL']):
"""
General function to get a pair plot of the entire data. Hue can be modified.
:param df: Input data
:param hue: Particular column to refer
:param cols: Co... |
a122f8d4ff7929bba09e0b57abf40d545adfa3ea | Kezoe81/my-first-blog | /python_intro.py | 83 | 3.609375 | 4 | if 5>2: Print("5 is indeed greater than 2")
else: print("5 is not greater than 2")
|
f4243ac30a72dfa4e3d831d430c6370baacd5fe3 | printer83mph/adv-programming | /binarysearch.py | 528 | 3.828125 | 4 | from math import floor
def deepen(low,high,guesses):
if low + 1 == high: return high
inp = input("My guess is " + str(floor((high+low)/2)) + "! ")
if inp == "h":
return deepen(floor((high+low)/2),high,guesses+1)
elif inp == "l":
return deepen(low,floor((high+low)/2),guesses+1)
elif ... |
481416564bb8d3e14112177b3631cb513cf5897a | sakurasakura1996/Leetcode | /剑指offer/剑指offer33_二叉搜索树的后续遍历序列.py | 1,979 | 3.78125 | 4 | """
剑指 Offer 33. 二叉搜索树的后序遍历序列
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。
如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
提示:
数组长度 <= 1000
"""
# 检查是否是二叉搜索树的后序遍历结果,那么我们就根据其后序遍历结果还原二叉树。由于需要中序加后序才能恢复出这棵二叉树
# 那么中序遍历好搞啊,假设他就是二叉... |
25e929a8161beee970ae8776b152a76e2cf2e094 | rajeevdodda/Python-Practice | /FluentPython/Chapter 5/Example23.py | 816 | 4.3125 | 4 | # Example 5-23 shows a common use of itemgetter: sorting a list of tuples by the value
# of one field. In the example, the cities are printed sorted by country code (field 1).
# Essentially, itemgetter(1) does the same as lambda fields: fields[1]: create a
# function that, given a collection, returns the item at index ... |
1142e2aa7e238df925b4a8f30b90d4d2a10bd082 | Xrqian/LintCodeTraining | /code/A + B 问题.py | 798 | 3.859375 | 4 | class Solution:
"""
@param: : An integer
@param: : An integer
@return: The sum of a and b
"""
def aplusb(self, a, b):
# write your code here
# 递归
# return a if not b else aplusb(a ^ b, (a & b) << 1)
# 循环
import ctypes
while b:
tmp = ct... |
cb6987c9806c9f2281b7e1f5a689903b7fee620d | renatomarquesteles/estudos-python | /Maratona de programaçao/Aquecimento Primeira Fase 2015/problema_B.py | 413 | 3.5 | 4 | linha = input().split()
a = linha[0]
b = linha[1]
c = linha[2]
d = linha[3]
varetas = [a, b, c, d]
if a > b + c and a > b + d and a > c + d:
varetas.remove(a)
if b > a + c and b > a + d and b > c + d:
varetas.remove(b)
if c > a + b and c > a + d and c > b + d:
varetas.remove(c)
if d > a + b and d > a + c an... |
344138893e368b1a5d8af0de4379a882c0dd180f | amberleeshand/ExceptionHandling | /class1.py | 2,597 | 3.625 | 4 | import random
# print(random.randint(100, 999))
class InsufficientFundsError(Exception):
def init(self, msg):
super().__init__(msg)
class CannotDepositNegativeAmountError(Exception):
def init(self, msg):
super().__init__(msg)
class InvalidUserInputError(Exception):
def init(self, msg):
... |
7fcd047a1da1bd77096a39ac408292217d501daf | k43lgeorge666/Python_Scripting | /basic code/program5.py | 252 | 4.0625 | 4 | #!/usr/bin/python
number1 = input("Enter the first grade: ")
number2 = input("Enter the second grade: ")
number3 = input("Enter the third grade: ")
result = (number1 + number2 + number3) / 3
if result >=7:
print("Approved")
else:
print("failed")
|
f7ef0467404723df7e6be5c2fe725810245c7086 | 610yilingliu/leetcode | /Python3/637.average-of-levels-in-binary-tree.py | 900 | 3.53125 | 4 | #
# @lc app=leetcode id=637 lang=python3
#
# [637] Average of Levels in Binary Tree
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def averageOfLevels(self, root):
if... |
2c725a09e7574cc583725f9133576fec9a88e792 | huotong1212/mylearnpy | /code/day05/student.py | 703 | 3.625 | 4 |
## 演示封装
class Student(object):
def __init__(self,name,score):
self.__name = name
self.__score = score
self.grade = 6
def set_name(self,name):
self.__name = name
def set_score(self,score):
if score<0:
return 'score must more than 0'
elif score>... |
960779da20fa6d086c1316c1549c88083c71603a | aashirbad-11/Pattern-in_python | /py03.py | 131 | 3.625 | 4 | for i in range(1, 6):
for j in range (1, 6):
print(j, end='')
print()
# 12345
# 12345
# 12345
# 12345
# 12345 |
ec62e8e46f0b8d771e7abbac6c32aec18e40a863 | Alone-elvi/Simply_Python | /homework-2.py | 727 | 4.125 | 4 | years_list = [1974, 1975, 1976, 1977, 1978]
print(years_list[3])
print(years_list[-1])
things = ["mozzarella", "cinderella", "salmonella"]
things[1].capitalize()
print(things)
things[0].upper()
print(things)
del things[2]
print(things)
surprise = ['Groucho', 'Chico', 'Harpo']
surprise[-1].lower()
surprise[-1].capita... |
781b5644aedcab9f5e28ec9f7731f9b62a42c35f | ChannyHong/RNNInvestment | /dateTool.py | 2,923 | 3.8125 | 4 | # dateTool.py
# Channy Hong
#
# Toolkit for date calculations
import datetime
# Function that checks whether string is a floatStr or not
def isFloatStr(s):
try:
float(s)
return True
except ValueError:
return False
# Function for getting the number of days in the month, given a year
de... |
1d27b9f03356c1f881905c062900acad67bd928c | fukode/leetcode | /101-120/levelOrder.py | 899 | 3.765625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrder(self, root: TreeNode):
if not root: return []
res = []
def bk(s):
if not s:return
d... |
b14324e60a99c946f0e68de2f13f5d112024564f | tekkadon88/LeetCode | /0276_numWays.py | 529 | 3.6875 | 4 | """
276. Paint Fence
URL: https://leetcode.com/problems/paint-fence/
Level: Easy
"""
class Solution:
def numWays(self, n: int, k: int) -> int:
if n == 0:
return 0
if n == 1:
return k
dp = [0] * (n+1)
dp[1] = k
dp[2] = k*k
for i in ra... |
d49cdfb4e1ef68e0239ffff7d02d683d8c3657e1 | lbbruno/Python | /Exercicios_1/006_Formatando_Strings_2.py | 133 | 3.90625 | 4 | n = int(input('Digite um valor:'))
print('Valor Digitado:{} | Dobro:{} | Triplo:{} | Raiz quadrada:{} |'.format(n,n*2,n*3,n**(1/2)))
|
848713b63c062cc95a72b384671072ed99654d62 | yukilu/languages | /python/dict-instance.py | 908 | 3.703125 | 4 | # dict与类的实例不同,类的实例不是dict,所以dict访问键值与类实例访问属性的方式不同,且不能混用,这与js不同,js中相互是等价的
# 字符串索引与点操作符,dict([]),类实例(.)
# dict -> d["a"]/d['a'] 只能通过字符串索引访问值,单引号双引号都可,python中单引号双引号是等价的
# 类实例 -> s.a 只能通过点操作符访问属性
class Student(object):
def __init__(self, id):
self.id = id
d = { "a": 0 } # 可以写成单引号 { 'a': 0 },但键的引号不能省略,不能写成 {... |
b8ae6b247582f5d0de83b4218640b8c4b961f0ff | Keep-Going-Fight/pNSGA2_for_Btsp | /src/nsga_utils.py | 2,824 | 3.546875 | 4 |
def rank_assign_sort(pool):
"""
Be used to initialize the Children for Sort
Very fast Non-Dominant sort with binary insertion as per
NSGA-II, Jensen 2003.
Assign ranks to the members of the pool and sort it by rank,
e.g. member of the n'th non-dominated front (ascending; lower is better)
:p... |
022f4f8b43f2f0f0ca16fe8f77aaa5499033a774 | parhamgh2020/kattis | /Guess the Number.py | 271 | 3.65625 | 4 | def binary_search(lst):
m = len(lst) // 2
print(lst[m])
response = input()
if response == 'lower':
binary_search(lst[:m])
elif response == 'higher':
binary_search(lst[m:])
else:
return
binary_search(list(range(1, 1001)))
|
cfb2ed38aac18cdd31524f9c7eb013e667b9516d | mtj6/class_project | /favorite_language.py | 394 | 3.9375 | 4 | favorite_language = {
'jen' : 'python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'python',
}
list = ['jen', 'samantha', 'sarah', 'jeremy', 'heather', 'frank', 'phil']
for name in list:
if name in favorite_language.keys():
print('Thank you for taking the survey, ' + name.title() + '.'... |
b781f95699002cdfc89722537cf237b7a5fd2faa | therealiggs/oldpystuff | /test.py | 1,301 | 3.515625 | 4 | with open('smartguy.txt') as file:
text = [line for line in file]
def code(word,key):
ans = []
klst = list(key)
i = 0
for line in word:
k = ord(klst[i%len(klst)])
e=line.encode('cp1251')
s = bytes([(byte + k)%256 for byte in e])
ans+= s.decode('cp125... |
6ca1834d6686e129c3d24119ce5af571fbab2bbf | reiman2222/school-assigments | /IR/Program2/positional_index.py | 2,161 | 3.890625 | 4 | import re
#tokenizes a word
def tokenize(word):
regex = re.compile('[^a-zA-Z]+')
w = regex.sub('', word)
w = w.lower()
return w
#tokenizes a list of words
def tokenizeWordList(wordlist):
i = 0
while i < len(wordlist):
wordlist[i] = tokenize(wordlist[i])
i = i + 1
return wordlist
def ind... |
c98580dea9b75092bd301d0d348d29f41946c0da | diljasigurdar/dilja | /Heimaverkefni/int_seq.py | 526 | 4.1875 | 4 | largestInt = 0
countEven = 0
countOdd = 0
cumulativeSum = 0
num = 0
while num >= 0:
num = int(input("Enter an integer: "))
if num <= 0:
break
if num % 2 == 1:
countOdd += 1
elif num % 2 == 0:
countEven += 1
if num > largestInt:
largestInt = num
cumulativeSum += n... |
674e4d50d704a8da506f64a714b53742619eb106 | GrigoriyMikhalkin/testy_fbchatbot | /classifiers/preprocessors.py | 800 | 3.609375 | 4 | import re
import pymorphy2
morph = pymorphy2.MorphAnalyzer()
def normalizing_preprocessor(row_string):
"""
Clears string from everything, except letters
used in russian or english languages.
After that, transforms all words to normal form
"""
cleaned_string = re.sub('[^а-яА-Яa-zA-Z]', ' ', r... |
1840cf60d4946eaf53e4767cfb64d468f27f92fb | n0tch/my_uri_problems | /URI_1017.py | 211 | 3.515625 | 4 | # -*- coding: utf-8 -*-
'''
Escreva a sua solução aqui
Code your solution here
Escriba su solución aquí
'''
t = int(input())
v = int(input())
litros = (t*v)/12
print("{:.3f}".format(litros)) |
cd0a7eeecd3c5cc8d103944116613398ca5b58b2 | SarahZ22/web-scraping-challenge | /scrape_mars.py | 3,551 | 3.65625 | 4 | # Step 2 - MongoDB and Flask Application
# Use MongoDB with Flask templating to create a new HTML page that displays all of the information that was scraped from the URLs above. Convert your Jupyter notebook into a Python script called scrape_mars.py with a function called scrape that will execute all of your scraping ... |
ac467e5180ee550f65931b25e2a4555ba5107c4a | thehaseo/bot-binarias | /ContadorEstrategia.py | 1,823 | 3.6875 | 4 | """
Clase que se encarga de mantener un registro de cuantas veces se ha ejecutado una estrategia de forma seguida
y que tipo de operación ejecutó, sea esta compra o venta
return_estrategia: se encarga de revisar de que estrategia es la operación está a punto de ejecutarse
y revisar si es la misma estrategia que se eje... |
9a2ce3fed44392bd39075fc45362970790a6ec76 | toncysara17/luminarpythonprograms | /Advance_Python/Oops/personpgm2.py | 358 | 3.796875 | 4 | class Person: #create a class
def run(self): #method using function
print("person is running")
def walk(self):
print("person is walking")
def jump(self):
print("person is jumping")
obj=Person() #ref... |
19db672ea459e3a2d3c24fcbb596541e569c25c1 | Kulsumganihar/code | /calc.py | 400 | 3.5625 | 4 | import math as m
class calc:
def add(self,num1,num2):
return num1 + num2
def sub(self,num1,num2):
return num1 - num2
def mul(self,num1,num2):
return num1 * num2
def div(self,num1,num2):
if num2 == 0:
raise ZeroDivisionError
else:
retur... |
64d1e68fc5f67bdc6404aef5f80b44d9467511c8 | stanford-cnjc/cnjcx_project | /convertime/conversions.py | 703 | 4 | 4 | from convertime import constants
def hours_to_seconds(hours):
"""Computes the number of seconds in the number of hours provided"""
return hours * constants.MINUTES_IN_HOUR * constants.SECONDS_IN_MINUTE
def days_to_seconds(days):
"""Computes the number of seconds in the number of days provided"""
hou... |
b03c871a75bac0de33276ebdbba4de8ba2fd3429 | Nahla-shaban-salem/Disaster-Response-Pipelines | /data/process_data.py | 3,652 | 3.546875 | 4 | import pandas as pd
from sqlalchemy import create_engine
import sys
def load_data(messages_filepath, categories_filepath):
""""
INPUT
- messages csv file name and file path
-categories csv file name and file path
OUTPUT - pandas dataframe
1. read the message file into a pandas datafra... |
c0a452c952a6fd7f7ab1b069a4a54f84fa8d0a30 | Hangyeol-Jang/rasberrrypi_practice01-Python- | /ex9.py | 230 | 3.71875 | 4 | # -*- coding: utf-8 -*-
print("몇 번을 반복할까요? : ", end="")
limit = int(input())
count = limit if limit < 100 else 100
while count>0:
print("{0}회 반복".format(count))
count -= 1
print("프로그램 종료")
|
8a1d153c8ca9ea73f5e8fa6d3fec743b1b87fb28 | mamunm/data_science_algorithms | /coding_prep/practical_decorator/memoization.py | 796 | 3.71875 | 4 | #!/usr/bin/env python
# -*-coding: utf-8 -*-
#memoization.py
#Osman Mamun
#CREATED: 05-27-2019
from functools import wraps
def memoize(func):
cache = {}
@wraps(func)
def wrapper(*args, **kwargs):
if args not in cache:
print("Caching new function value for {}({})".format(
... |
4d883383c7f3a59b54524dd401b69112d03171cf | Xirtsit/learning-python | /15.03.2021/ex3.py | 636 | 4.09375 | 4 | import random
WORDS = ("carnotaurus", "velociraptor")
word = random.choice(WORDS)
len = len(word)
counter = 0
if_appears = False
print("\nTry to guess the word in 5 tries. The length of my chosen word is", len)
while counter != 5:
letter = input("Enter a letter: ")
if letter in word:
i... |
57a9e2859ac553482bac24ada65d6342fd8a90be | Olevova/SeaBattel | /sea_battel/player.py | 1,827 | 3.96875 | 4 | #создаем клас игрокаи дочернии от него классы игрок компютер и игрок Вы
from random import randint
from exseption import *
from point import Point
class Player():
def __init__(self, myboard, board):
self.board = myboard
self.other = board
def ask(self):
pass
def move(self):
... |
05e25de60e97541059c89f85a487704d038b4fea | degavathmamatha/LOOP_PY | /loop59.py | 142 | 3.859375 | 4 | c=0
while c<=4:
r=0
while r<=4:
if r==0 or c==2 or c==0 :
print("*",end=" ")
else:
print(" ",end=" ")
r=r+1
print()
c=c+1
#f |
f5d58452994b4cdc71dd734a4237701ba2acab5a | 8kasra8/PythonStudy | /First Attempt/Test01/test88.py | 640 | 4.125 | 4 | from math import sqrt
"""
Prime Number Detector
"""
def is_prime(x):
if x<2:
return False
for i in range(2, int(sqrt(x))+1):
if x % i == 0:
return False
return True
def main():
while True:
inp = input("Give me a number to see if it is Prime: ")
try:
... |
a6cf21231b81289c002f480dfbf7180c6eac1a85 | zhangruochi/leetcode | /007/Solution.py | 828 | 4.25 | 4 | """
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example ... |
31c948bf7b49c9f8a11e33a0985326942e17c8cb | amoddhopavkar2/LeetCode-November-Challenge | /01_11.py | 564 | 3.828125 | 4 | # Convert Binary Number in a Linked List to Integer
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
binary = []
while head != Non... |
450e9ab078777f3fcb43092a1bb41820f473035d | luyaosuperman/python3-playground | /homework/friends/friends.py | 6,454 | 4.09375 | 4 | class User():
'''
User information class
Node in the relationship graph
it stores the relationship/edge of the graph
'''
def __init__(self, username):
self.username = username
self.relationshipList = []
def addRelationship(self, relationship):
'''
store the ... |
0dca5d81190a7891385b4367d5aac2d0827942d7 | pnielab/PythonServer | /PythonServer/src/main/pythonserver/chat_client.py | 3,936 | 4.03125 | 4 | #!/usr/bin/env python3
"""Script for Tkinter GUI chat client."""
"""
https://medium.com/swlh/lets-write-a-chat-app-in-python-f6783a9ac170
"""
"""
This is more fun beause we’ll be writing a GUI! We use Tkinter, Python’s “batteries included” GUI building tool for our purpose. Let’s do some imports
"""
from socket impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.