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 |
|---|---|---|---|---|---|---|
36ee5e017679d04766ec379ba1c7d345968d1d90 | Arushi-V/PythonWithCM | /2021.05.26/set_ex.py | 1,169 | 4.375 | 4 | # Set
# its a collection of unique items
# A set is a collection which is both unordered and unindexed.
jwellerySet = {"earings", "necklace", "ring"}
print(type(jwellerySet))
print(jwellerySet)
# duplicates are not allowed in sets
print(len(jwellerySet))
# A set can contain different data types:
wallet = {100, "che... |
1f351a82046b76bc4b14897bc61f5eafde761bf3 | jacelecomte/Python | /first_occurrence.py | 1,027 | 3.671875 | 4 | # With runtime of O(log n) print array position of the first '1' found in the array
def location_of_first_one(array):
counter = 0
lowerbound = 0
upperbound = 0
length = len(array)
if length == 1:
return 0
while counter < length:
lowerbound = counter
counte... |
4d37e556f6f785cb9817e9a3068b2c9eea683e73 | karthikaManiJothi/PythonTraining | /Assignment/Day1Assignment/ReverseWordbyWord.py | 107 | 3.859375 | 4 | str =input("Enter string").split()
list1 =[]
for i in str:
list1.append(i[::-1])
print(" ".join(list1)) |
962c11de4dc82e0c0a722971dff82b517c9c149a | dedekinds/pyleetcode | /A_jzoffer/数组中只出现一次的数字.py | 1,283 | 3.703125 | 4 | 根据全部的^获得一个数,找到这个数的二进制数的右边第一个1的位置,根据这个1的位置可以将数组分类
成两组,这样就可以分别对每一组都来一波^即可
# -*- coding:utf-8 -*-
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def find_first_one(self,num):
if num == 0:return -1
cnt = 0
while num:
if num & 1:return cnt
else:
num = num >>... |
3f19379d6dff1963d40bf3cb302777041457e823 | EmineKala/Python-101 | /Python/Hafta2/alistirma6.py | 458 | 4 | 4 | #Bu egzersizde, size bir alışveriş listesi ve bir eşya verilecek.
#Eğer verilen eşya alışveriş listesinde ise True döndürün, alışveriş listesinde değilse False döndürün.
def shopping_list(list,item):
found = False
for i in list:
if i == item:
found = True
return found
list = ["süt","yumur... |
a607db685fa19842c302dd8899eaf441768eb785 | wkwkgg/atcoder | /arc/017/a.py | 161 | 3.703125 | 4 | from math import sqrt
N = int(input().rstrip())
ans = "YES"
for i in range(2, int(sqrt(N))+1):
if N % i == 0:
ans = "NO"
break
print(ans)
|
f215511e2cbab26a91e6580c0fe0a96881f3d9a2 | MSoup/Interval-Merge | /main.py | 934 | 4.1875 | 4 | """
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are ... |
aa16c20cf456820bf4ab9ee8f122b73f5b5365d3 | jidhu/code | /DataStruct/strings/anagram.py | 400 | 3.859375 | 4 | s1 = 'asdfg'
s2 = 'gadsdfa'
s1 = [char for char in s1]
s2 = [char for char in s2]
def anagram(s1, s2):
if len(s1) != len(s2):
return False
count = [0]*256
for i in range(0,len(s1)):
count[i]=count[i]+1
for i in range(0,len(s2)):
count[i]-=1
for i in range(256):
if... |
f7de84b4502f00f61a16d1835614c91ff52e01c2 | Beatriz021/Clases | /persona.py | 773 | 3.734375 | 4 | #crear una carpeta que se llame claases y dentro de los
#archivos dino.py persona.py
#crear una clases Persona() que tenga como atributos nombre, edad
#y profesión. Al instanciar la clases tiene que saludar igual que
#el dino diciendo sus atributos
class Persona:
def __init__(self, un_nombre="",una_edad=0,una_p... |
cbb9090a85a235ca747eb09e8300f060b74836f3 | charlie16-meet/MEET-YL1 | /oop/oop.py | 620 | 3.734375 | 4 | class Animal:
def __init__(self,name,color,age,size):
self.name=name
self.color=color
self.age=age
self.size=size
def print_all(self):
print(self.name)
print(self.color)
print(self.age)
print(self.size)
def sleep(self):
print(self.name,"is sleeping...zzzzz")
def eat(self,food):
print(self... |
68c925dd9cc70bb8f43854a410f10ac357d23eae | jonathanortizdam1993445/DI | /python/EJERCICIOS LISTAS/ejercicio1.py | 367 | 4.09375 | 4 | #!usr/bin/env python
print("Dime el número de palabras a introducir en la lista")
numero =int(input());
if int(numero)>0:
lista=[]
#VAMOS RELLENANDO LA LISTA TANTAS VECES COMO HEMOS INDICADO ARRIBA
for i in range(numero):
print ("Digame la palabra");
palabra=input();
lista+=[palabra]
print("La lista crea... |
ff23e4233995dee0237652908eb00b148afd25be | adamib4/learn_python | /digital_root.py | 590 | 4.15625 | 4 |
'''
In this kata, you must create a digital root function.A digital root is the recursive sum of all the digits in a
number.Given n, take the sum of the digits of n.If that value has more than one digit, continue reducing in this way
until a single-digit number is produced.This is only applicable to the natural numb... |
186992b34ee3b9316e17bc2d29153e15f67ae8f0 | shashank31mar/DSAlgo | /mergeKSorted.py | 932 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 8 22:42:24 2018
@author: shashankgupta
"""
from heap import Heap
import math
def mergeKSorted(arr,n,k):
temp = []
arr_index = []
next_arr_index = []
for i in range(k):
temp.append(arr[i][0])
arr_index.append(i)
... |
bce3d902b4336f47412ad3b2894db9b41dd991e5 | mansooni/algorithm | /codingame/TheRiver1.py | 242 | 3.5 | 4 | import sys
import math
r_1=int(input())
r_2=int(input())
while True:
r1 = list(str(r_1))
r2 = list(str(r_2))
if r_1<=r_2:
for i in r1:
r_1+=int(i)
elif r_1>r_2:
for j in r2:
r_2+=int(j)
if r_1==r_2 :
break
print(r_1)
|
daafa647ac4989a0e529a2da548f38e9079f4e62 | SESYNC-ci/online-data-with-R-lesson | /test_census_api_code.py | 649 | 3.59375 | 4 | from census import Census
# Not sure what this is doing
key = None
c = Census(key, year=2017)
c.acs5
# Define variables to extract (name and median household income) and get them for all counties and tracts in state 24
variables = ('NAME', 'B19013_001E')
response = c.acs5.state_county_tract(
variables,
state_fip... |
13f511e5d11ab75bc0fef923a8aae0a8e450dbb7 | terrancemount/terrance-python-training | /n-threading.py | 8,866 | 4.40625 | 4 | #!/usr/bin/env python3
'''
Topic Title: Threads
**John**
Concept: A thread, similar to Java, is a separate line of execution that runs
at the same time as the main thread and any other currently running threads.
In Python, threading is useful to run programs concurrently, especially when you need
to run IO tasks i... |
5d5ea3dd3464db1fa1348249ed120721140260d9 | NagiReddyPadala/python_programs | /Python_Scripting/Pycharm_projects/Practice/Generators.py | 182 | 3.796875 | 4 |
def topTen():
num = 1
while num <= 10:
yield num*num
num +=1
vals = topTen()
vals.__next__()
next(vals)
print(type(vals))
for val in vals:
print(val)
|
f5c4d2c171531cef22c98b019f010c61181cf8f5 | rsprenkels/kattis | /python/1_to_2/cups.py | 257 | 3.65625 | 4 | N = int(input())
cups = {}
for cup in range(N):
first, second = input().split()
if str.isdecimal(first):
cups[int(first) / 2] = second
else:
cups[int(second)] = first
for radius in sorted(cups.keys()):
print(cups[radius])
|
480cb828ea5fff46c8441a45871c567e0554b2cd | dmmfix/pyeuler | /p042.py | 377 | 3.734375 | 4 | #!/usr/bin/python
import euler
import math
def word_score(w):
return sum(map(ord, w.upper())) - (ord('A')-1)*len(w)
def is_trinum(n):
sn = int(math.floor(math.sqrt(n * 2)))
return n == (sn * (sn+1))//2
def is_triword(w):
return is_trinum(word_score(w))
triwords = filter(is_triword, euler... |
bf040073f3b3eb4323f0622d72895bc25877e72d | bilaleluneis/LearningPython | /conditional_and_loops.py | 3,239 | 3.921875 | 4 |
__author__ = "Bilal El Uneis and Jieshu Wang"
__since__ = "July 2018"
__email__ = "bilaleluneis@gmail.com"
from numpy import random as random_generator
def if_example(name):
if name == "Jieshu":
for x in name:
if x == "s":
continue
print(x)
else:
print... |
ab9d4a089ce39fa5cb90fe80235c2cc41d43d4fc | neilharvey/AdventOfCode | /2020/Day23/day23.py | 3,103 | 4.28125 | 4 | import sys
def crab_cups(cups, start, total_moves):
move = 1
min_cup = min(cups)
max_cup = max(cups)
current = start
while move <= total_moves:
# The crab picks up the three cups that are immediately clockwise of the current cup.
x = cups[current - 1]
y = cups[x - 1]
... |
de10be368792a24c4a7c5fcfcfee5a115543b196 | ilyas9797/university-stuff | /src/generators/mmlr.py | 6,413 | 3.71875 | 4 | """Реализация класса модифицированного многомерного линейного генератора и вспомогательных функций"""
import math
from typing import Callable, List
def bits_number(num):
"""Возвращает количество бит, необходимое для представления числа в двоичном виде"""
return math.floor(math.log2(num)) + 1
def nums_xor(n... |
5b56868c3ef6062d012d17ba2674960cdd4a56cc | EveryDayIsAPractice/Leetcode-python3 | /242_Valid_Anagram-0.py | 859 | 3.53125 | 4 | class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if s is None:
if t is None:
return True
else:
return False
elif t is None:
return False
memory... |
e07cbd509cd36e1d263c5d289277388adb4c9128 | carlos-sales/exercicios-python | /ex098.py | 511 | 3.546875 | 4 | from time import sleep
def contador(ini, f, p):
aux = 1
if p == 0:
p = 1
if ini > f and p > 0:
p *= -1
if p < 0:
aux *= -1
print(f'Contagem de {ini} até {f} de {p} em {p}')
for i in range(ini, f+aux, p):
print(i, end=' ')
sleep(0.5)
print('FIM')
co... |
a63c4ac84215d38df5a5db91f42ffc264e3b6a38 | yugin96/cpy5python | /practical01/q7_generate_payroll.py | 1,197 | 4.21875 | 4 | #filename: q7_generate_payroll.py
#author: YuGin, 5C23
#created: 21/01/13
#modified: 22/01/13
#objective: Obtain a user's number of hours worked weekly, hourly pay, and CPF contribution, and hence calculate his net pay
#main
#prompt user input of name
name = input('Enter name: ')
#prompt user input of hours worked w... |
605d5956e4692c98543975a5168dcac57d235151 | jj1of62003/inital | /DandC.py | 656 | 3.609375 | 4 | #!/bin/python
class node:
def __init__(self):
self.right = None
self.left = None
def msort1(numList):
msort(numList, 0, len(numList) - 1)
def msort(numList, first, last):
"""This is the initiator for the Merg sort algorithm"""
listLen = len(numList)
if first < last:
middle = listLen // 2
msort(numList,... |
c48b953f00f758701c26e38cbe8e251efa1b656b | Keshpatel/Python-Basics | /PythonBasicsExamples/PrintObjects.py | 544 | 4.09375 | 4 | # string representation of class object:
# Object printing concept:
class Test:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "x:%s y:%s" % (self.x, self.y)
def __str__(self):
return "value of a is %s and y is %s" %(self.x, self.y)
# Test Cod... |
7aa44710412f91a454617ede9a156b5a0962d177 | dcsm8/Udemy-Python-Course | /2. Functions and Loops in Python/class_25.py | 546 | 3.96875 | 4 |
cars = ['ok', 'ok', 'ok', 'ok', 'faulty', 'ok', 'ok']
for car_status in cars:
if car_status == 'faulty':
print('Stopping the production line!')
break
print(f'This car is {car_status}.')
for num in range(2, 10):
if num % 2 == 0:
print(f'Found an even number, {num}')
contin... |
6b7751d8862cee4aa89812aefeb60b58b76bb5c9 | vadim900/cool | /Індивідуальний проект/data_service.py | 2,414 | 3.828125 | 4 |
def get_goods():
""" повертає вміст файла 'dovidnuk.txt` у вигляді списка
Returns:
'from_file' - список рядків файла
"""
with open('./data/dovidnuk.txt', encoding="utf8") as goods_file:
from_file = goods_file.readlines()
# накопичувач товару
goods_list =[]
fo... |
e583efce261779ccd5f68c25370f629ca5af22cc | sanjitroy1992/PythonCodingTraining | /Mains/decorator.py | 545 | 4.15625 | 4 | #1. How about you create a function using which you could call another function.
def f1(func):
def wrapper():
print("Before")
func()
print("ended")
return wrapper
#let's write a small function to print a value
@f1
def f():
print("Hi")
# f()
#2. let's write a function to add two num... |
13263119c0b6283fe42fd719566701765ffb0af4 | anand14327sagar/Python_Learning | /IO.py | 115 | 3.84375 | 4 | # Python program showing simple I/O operation
name = raw_input("Enter your name : ")
print("Welcome "+name) |
219b3930cced2de9146cbd4c1d9c998beb672073 | purcellconsult/JNPR_Fundamentals | /day3-random.py | 1,052 | 3.96875 | 4 | from random import choice
import string
import random
first_name = ['Deen','John','Steve','Bruce','Sean']
last_name = ['Osaka','Marc','Mario','Dan','Anthony']
for x in range(2):
random_name = '{} {}'.format(choice(first_name),choice(last_name))
print(random_name)
## another way ....
email_service = ['gma... |
6a77431ed971a411d27497e50730a50174576601 | ml-resources/neuralnetwork-programming | /ch01/linear-equation.py | 1,415 | 3.578125 | 4 | import tensorflow as tf
# linear equation is represented by
# ax + b = y
# y - ax = b
# y/b - a/b(x) = 1
# x, y is known and can be represented as X matrix, goal is to find a and b
# therefore we can represent the above goal as AX = B where X is the input matrix, A is the unknown(a,b) and B is all ones
# example
# 3x... |
93bb6728d812b31f74d8b5d959da845e58e64b40 | basoares/coursera-ml-py-exercises | /ex1/computeCost.py | 785 | 4.1875 | 4 | '''
Stanford Machine Learning (Coursera) - Python
ComputeCost example function
ComputeCost(X, y, theta) is a function that computes cost of using theta as
the parameter for linear regression to fit the data points in X and y
Released under the MIT License <http://opensource.org/licenses/mit-license.php>
'''
__v... |
ebf96e7a2434f704fb37405c768a16f030a28a9e | ashrafulk/fire-detection | /mod1.py | 392 | 3.734375 | 4 | class cal:#modules
add =lambda a,b:a+b
def fact(n):
if n <=1:
return 1
else:
return n*cal.fact(n-1)
def prime(n):
for i in range(2,n):
if n%i==0:
print("its not prime")
break
else:
... |
8b2171e10476822318987e7acf71b77fe848a894 | Seemant-tiger/housing-price-prediction | /src/ta_lib/_vendor/tigerml/core/utils/reports.py | 269 | 3.5625 | 4 | import os
def get_extension_of_path(path):
_, ext = os.path.splitext(os.path.basename(path))
return ext
def append_file_to_path(path, file_name):
if get_extension_of_path(path):
return path
else:
return os.path.join(path, file_name)
|
4fe6706fbcd2a80e6d02d87e08b092dedfab28d5 | Hasib104/Learning-Python | /Day004/1.Randomisation.py | 529 | 3.9375 | 4 | """#Importing Module"""
# import my_module
# print(my_module.pi)
import random
"""#Random Generator"""
# random_int = random.randint(1, 100)
# print(random_int)
"""#Manipulating result of random generator using seed"""
# random.seed(8)
# random_int = random.randint(1, 10)
# print(random_int)
"""#Head... |
53461266ed2c6ebfa9e97d98ff8d491f0cec4364 | Ezi4Zy/leetcode | /24.两两交换链表中的节点.py | 818 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=24 lang=python
#
# [24] 两两交换链表中的节点
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:typ... |
c39bca24adf4edcdb001bf7ed7e7cf0b051f5fec | krokhalev/GeekBrains | /Lesson1/Number1.py | 979 | 4.09375 | 4 |
variableOne = 1 # Создал первую переменную.
variableTwo = 2 # Создал вторую переменную.
print (variableOne, variableTwo) # Вывел на экран.
numberOne = input("Введи первое число.\n") # Запросил первое число, сохранил в переменную.
numberTwo = input("Введи второе число.\n") # Запросил второе число, сохранил в перем... |
613f344965926d791953e9b9b212cdd7db6d797c | pengyang0106/python | /day24.py | 327 | 3.796875 | 4 | def calc_profit(n):
price = 24
cost = 8
profit = (price - cost) * n - 500
return profit
def calc_perf(profit):
if profit > 2000:
print('合格')
else:
print('不合格')
n = int(input('请输入今天咖啡店的销量'))
print(calc_profit(n))
profit = calc_profit(n)
calc_perf(profit) |
401f697ebeb6ee12edbbf226b9bbf89049b5733d | NutthanichN/grading-helper | /week_6/6210545530_lab6.py | 12,969 | 4.15625 | 4 |
# 1
def ll_sum(a, b, c):
"""Return sum of the all integers in the lists.
Args:
a (list): list one.
b (list): list two.
c (list): list three.
Returns:
int: the sum of all the number in the input lists.
Examples:
>>> ll_sum([1,2]... |
0413ee082f65e5ec041a182fd94d98903ab2e493 | LeonardoSaid/uri-py-solutions | /submissions/1051.py | 341 | 3.921875 | 4 | x = float(input(""))
if x <= 2000.0:
print("Isento")
elif x <= 3000.0:
salario = ( x - 2000.0 ) * 0.08
print("R$ %.2f" % salario)
elif x <= 4500:
salario = 0.08*1000 + ( x - 3000 ) * 0.18
print("R$ %.2f" % salario)
else:
salario = 0.08*1000 + 0.18*1500 + ( x - 4500 ) * 0.28
print... |
9daf9844007abb54e9b50610fdb8af500532087a | Rahul664/Pyhton_functional_code_snippets | /Python_Assignment_2/54.py | 472 | 3.625 | 4 | import time
try:
name = input("Enter your name:")
print("you entered: " + name)
except KeyboardInterrupt:
print( "Keyboard interrupt you hit ctrl-c")
i=1
try:
while(i<5):
time.sleep(1)
print (i)
i += 1
except KeyboardInterrupt:
print( "Keyboard interrupt")
try:
print ("Hi" +" "+ n)
except Nam... |
ff47b810fc153d3e49dbc62779b90fdfcf0d9dc0 | rjraiyani/Repository2 | /arrow.py | 80 | 3.671875 | 4 | N = int(input('Please enter your number ' ))
arrow = '-' * N + '>'
print(arrow)
|
f70553987465b9d012012209a1c11e65030c3477 | haell/AulasPythonGbara | /mundo_TRES/ex099.py | 1,047 | 3.8125 | 4 | # Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros.
# Seu programa tem que analisar todos os valores e dizer qual deles é o maior.
from time import sleep
from ex098 import linha
def gera_param(qtd_digitos):
from random import randint
numeros = list()
... |
421f472b5e756607786c7e8cd7d871c9b0cf9ab9 | leor/python-algo | /Lesson1/Task8/code.py | 539 | 3.8125 | 4 | year = int(input("Введите год (например 1970): "))
# вариант 1
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Год високосный")
else:
print("Год не високосный")
else:
print("Год високосный")
else:
print("Год не високосный")
# вариант 2
impor... |
9d0fe12e7136033934de45a10bc2b2ee53fcb1d2 | leofdss/busca-em-largura | /arvore.py | 771 | 3.78125 | 4 | class Node(object):
def __init__(self, key):
self.key = key
self.children = None
self.dad = ''
def BFS(self, key):
print('\n-----------Busca-----------')
return _BFS([self], key)
def _BFS(nodes, key):
filhos = []
if nodes:
for item in nodes:
... |
323a13f44e40e887ace111dc5a42ec5d17576cc6 | genuinenameerror/algorithm-week2 | /nonsequential.py | 322 | 3.953125 | 4 | finding_target = 9
finding_numbers = [0, 3, 5, 6, 1, 2, 4]
def is_exist_target_number_binary(target, numbers):
# 이 부분을 채워보세요!
for i in numbers:
if i==target:
return True
return False
result = is_exist_target_number_binary(finding_target, finding_numbers)
print(result)
|
5cd23f58faeab5288c8c97bef9721f7bc0349b0e | imvivek71/LearningPython | /Examples/PrintingIdentityMatrix.py | 171 | 3.796875 | 4 | n=input("Enter the size of matrix")
for i in range(0,n):
for j in range(0, n):
if i==j:
print "1 ",
else:
print "0 ",
print |
e4fc1728dfcc2f166d3eb3696d2f1fccaaf7469e | hi2gage/csci127 | /Programs/program6/test2.py | 415 | 3.59375 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
csv_data = pd.read_csv("airlines.csv")
data_frame_line = pd.DataFrame(data = csv_data, columns=['Diverted', 'Cancelled','Delayed', 'Year'])
df = data_frame_line.groupby('Year')['Delayed','Cancelled'].sum()
ax = df.plot(secondary_y='Delayed')
ax.s... |
82b674c58a027347ea3a53c66ea475cf55afe3c2 | alvinkgao/leetcode_solutions | /Python3/101.Symmetric_Tree.py | 1,279 | 3.9375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
return self.isSymmetricHelper(root, root)
def i... |
3dbe47c222f4cdad2bdf9ef0e822ae3015b37df2 | Aditya7256/Demo | /Recursion in Python.py | 245 | 4.0625 | 4 | # Recursion in python:
def my_function(k):
if k > 0:
result = k + my_function(k - 1)
print(result)
else:
result = 0
return result
print("\n\nrecursion Example Results")
my_function(10)
|
b6e2f222d980336a625af2b818094cf0b12294aa | gupta93/TemplatesForAlgorithm | /0-1knapsack.py | 808 | 3.65625 | 4 | def knapsack(weights,values,maximum_weight):
heightOfTable = len(values)
weightTable = [[0 for x in xrange(maximum_weight+1)] for y in xrange(heightOfTable)]
for column in xrange(weights[0],maximum_weight+1):
weightTable[0][column]=values[0]
for row in xrange(1,heightOfTable):
for column... |
57c39bbfa3088293863f3f8f27128a899d3ac24e | AhhhHmmm/MITx-6.00.1x | /Week 2/palinRecur.py | 342 | 3.921875 | 4 | word = 'oHahO'
def processWord(word):
tempWord = ''
for letter in word:
if letter.isalpha():
tempWord += letter
tempWord = tempWord.lower()
return tempWord
def palinRecur(word):
if len(word) == 0 or len(word) == 1:
return True
else:
return word[0] == word[-1] and palinRecur(word[1:-1])
print(palinRecu... |
56a1424436b02be4bb109f2a137438469c4d0963 | dooma/backtrack | /lib/backtrack.py | 5,423 | 4.03125 | 4 | __author__ = 'Călin Sălăgean'
class Backtrack():
'''
Class provides permutations of any list with a specified rule. Every rule should be implemented
Candidate list is a list with unique elements
'''
def __init__(self, array):
'''
Class constructor
:param array: The list th... |
c96f980d7d731f319947d295738fb787f8584428 | tskaro/unihero | /populate.py | 834 | 3.578125 | 4 | import sqlite3
items = [
{"id": 1, "name": "Jedi Starfighter", "speed": 1, "arm": 1, "capacity": 15, "quantity": 11},
{"id": 2, "name": "Starship Enterprise", "speed": 15, "arm": 9, "capacity": 3000, "quantity": 6},
{"id": 3, "name": "Millennium Falcon", "speed": 18, "arm": 10, "capacity": 10, "quantity": ... |
3d1a07c60461370a22729b4e6b0d0e9f4557c0d0 | nikileeyx/objectOrientedProgramming | /7002_theCar.py | 428 | 3.546875 | 4 | class Car:
def __init__(self, brand, colour, speed):
self.brand = brand
self.colour = colour
self.speed = speed
def whoAmI(self):
print("Hi I am a " + self.colour + " car")
def upgrade(self, speed):
speed += 10
print("Your speed has increased by " + str(self.speed))
return sp... |
da935e4b4081b151278414c7a574c9fba4343147 | yawzyag/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 133 | 3.828125 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
st = set(my_list)
num = 0
for i in st:
num = num + i
return num
|
5284a6a31f1ed1f74418c3817173533c91d42893 | s2motion/python-cookbook | /src/2/matching_and_searching_for_text_patterns_using_regular_expressions/example_practice.py | 905 | 4.53125 | 5 | # example.py
#
# Examples of simple regular expression matching
# Exact Match & Match at start or end & Search for the location of the first occurence
text = 'yeah, but no, but yeah, but no, but yeah'
# Exact Match
print(text == 'yeah')
# >>>False
# Match at start or end
print(text.startswith('yeah'))
# >>>True
print... |
d70372aa6b6f9fa5470caac68c83ac13fcc5716f | yetanotherbot/leetcode | /13. Roman to Integer/solution.py | 724 | 3.5625 | 4 | class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
romanceDict = {"M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100,
"XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5,
"IV": 4, "I": 1}
... |
2376141f6d5d132d938068860ceda18e75d67f5a | Aman08-forsk/FSDP_2019 | /Day05/regex1.py | 233 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 7 10:44:09 2019
@author: Hp
"""
import re
n=int(input("Enter the numbers:"))
for i in range(n):
s=input("Enter the input:")
print(bool(re.search(r'^[-+.]?[0-9]*\.[0-9]+$',s))) |
12a7909e1aa0dd5f0522c911e65ddbd3da74b8d5 | scaniasvolvos/python-basics | /3d-to-2d.py | 523 | 4.34375 | 4 |
Input = [[[3], [4]], [[5], [6]], [[7], [8]]]
result = []
for i in Input:
for j in i:
result.append(j)
print (result)
'''
# Python code to convert a 3D list into a 2D list
# Input list initialization
Input = [[[3], [4]], [[5], [6]], [[7], [8]]]
# Output list initialization
Output = []
# ... |
57bb81044cbd0e910552d249b3f6dfdf36efd043 | EricAlanPearson/python-challenge | /PyBank/main.py | 2,027 | 3.59375 | 4 | #PyBank
import os
import sys
import csv
#open file and write to file
budget_data = os.path.join(".", "budget_data.csv")
financial_analysis = os.path.join(".", "financial_analysis.txt")
with open (budget_data, "r", newline="") as filehandle:
next(filehandle)
csvreader = csv.reader(filehandle)
# loop
tota... |
0fa89cfbe93a7d26750f7d99371bf14bd4974dc0 | asparagus/chess | /client/fen.py | 3,440 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf8 -*-
"""This module contains functionality for the Forsyth-Edwards Notation."""
import re
class Fen:
"""Static class for dealing with the notation."""
# Initial state in Forsyth-Edwards Notation (FEN)
INITIAL_STATE = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w K... |
89b2535e32f30a1e27b4870138b97f72e367bf9a | zzag/codesamples | /elliptic_curve.py | 2,272 | 3.65625 | 4 | def extended_euclidean(a, b):
r_prev, r = a, b
s_prev, s = 1, 0
t_prev, t = 0, 1
while r:
q = r_prev // r
r_prev, r = r, r_prev - q*r
s_prev, s = s, s_prev - q*s
t_prev, t = t, t_prev - q*t
return s_prev, t_prev
def find_inverse(x, p):
inv, _ = extended_euclidea... |
e042690a66da0f9dd13774cd79b9e9b844ebeb81 | xiang12835/python-learning | /leetcode/linked_list/24. Swap Nodes in Pairs.py | 2,077 | 4.0625 | 4 | # coding=utf-8
"""
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
"""
# Definition for singly-linked list.
class ListNode(object):
... |
e4314e2952cbb1330f12ff89f8502ac9cf15b894 | VenetianDevil/Universality | /Python_Infosys/1/solution.py | 1,077 | 4.25 | 4 | #!/usr/bin/python
# -*- coding: iso-8859-2 -*-
##########################################
# Write a program that reads one line from the the standard input which contains two integers and a symbol of the operation. Depending on the symbol, the program should print the correct value of the operation. If the user gave... |
1faeaa13d3e991583613f24be7ecfc2a3f5b6211 | sadiquemohd/data_analytics | /python_math /hw5/task1.py | 273 | 3.671875 | 4 | import numpy as np
"""
Задание 1
Создайте numpy array с элементами от числа N до 0 (например, для N = 10 это будет array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])).
"""
def createNpArray(n):
return np.arange(0, n)[::-1]
|
4c4341f5395e02e99740a752093dbb848136ce8c | cathalgarvey/mdr | /mdr/utils.py | 1,687 | 3.6875 | 4 | # -*- coding: utf-8 -*-
import re
import itertools
def find_continous_subsequence(iterable, predicate):
"""
find the continuous subsequence with predicate function return true
>>> find_continous_subsequence([2, 1, 2, 4], lambda x: x % 2 == 0)
[[2], [2, 4]]
>>> find_continous_subsequence([2, 1, 2,... |
0482736893323b828ebd7b938808294a6165b2db | WinrichSy/Codewars_Solutions | /Python/7kyu/ReturnTheFirstMmultiplesOfN.py | 194 | 3.546875 | 4 | #Return the first M multiples of N
#https://www.codewars.com/kata/593c9175933500f33400003e
def multiples(m, n):
ans = []
for i in range(1, m+1):
ans.append(i*n)
return ans
|
ff09747fb8734328b4badb9f40a52aee36b706bd | sharmarishabh54/hospital | /update appointments.py | 4,911 | 3.578125 | 4 | from tkinter import *
import tkinter.messagebox
import sqlite3
conn = sqlite3.connect('database1.db')
c = conn.cursor()
class application:
def __init__(self,master):
self.master = master
# heading label
self.heading = Label(master, text="Update Appointments",fg='darkslategra... |
a5788b401b11810f033f8937e2f4d01791539e97 | simonfong6/ECE-143-Team-6 | /data_analysis/plotting.py | 6,412 | 3.796875 | 4 | #!/usr/bin/env python3
"""
Plotting functions
"""
import matplotlib.pyplot as plt
from math import pi # For radar graph.
def histogram(df, column_name, title, xlabel, ylabel, bins=10):
"""
Makes a histogram of the data.
Args:
df (pandas.DataFrame): All of the data.
column_name ... |
bb89d07d4de447e8e3d0670f6723471151afc10d | imckl/leetcode | /medium/79-word-search.py | 2,994 | 3.84375 | 4 | # Given a 2D board and a word, find if the word exists in the grid.
#
# The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells
# are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
#
# https://leetcode.com/problems/word-search/
... |
6fb560d71277e8cba3bbf1ef4d4e1226198c30fb | DeepakKumar-Mahadevan/repo01 | /Programs-01/dict-02.py | 232 | 3.796875 | 4 | num = {1:'A',2:'B',3:'C'}
print (num.items())
num[4] = 'D'
num[5] = 'E'
print (num.items())
num[6] = 'F'
num[7] = 'G'
num[8] = 'H'
num[9] = 'I'
num[10] = 'J'
print (num.items())
del num[6]
del num[8]
print (num.items()) |
4cada6c959eee83ade46002ca973890b89e2c226 | Jhancykrishna/luminarpythonprograms | /functions/even.py | 228 | 4.03125 | 4 | def even():
num=int(input('enter a number'))
if(num%2==0):
print('even number')
even()
print('**************')
def even(num):
if (num % 2 == 0):
print('even number')
even(4)
print('**************')
|
a13b42b6daf5f92a30bf2dfc1750653729046429 | VVSKushwanthReddy/100_days_of_DSA | /Data Structure with Python/List/Insert and Serach.py | 125 | 3.515625 | 4 | l = [10, 20, 30, 40, 50]
l.append(30)
print(l)
l.insert(1, 15)
print(l)
print(15 in l)
print(l.count(30))
print(l.index(30))
|
426a03f49e6099725e36d8ffd14c2f8caecad9b7 | jbremer/triegen | /triegen.py | 3,505 | 3.609375 | 4 | #!/usr/bin/env python
"""Triegen (C) Jurriaan Bremer 2013
Utility to generate a Trie from a set of strings.
"""
import RBTree
import sys
class Node:
"""Represents a single, light-weight, node of a tree."""
def __init__(self, left, value, right):
self.left = left
self.value = value
... |
0b36837149426177911c262a03dcb153f6b33716 | Jerry9757/pytw_a01 | /ex1_tk.py | 408 | 3.625 | 4 | # github Pytw_T01, Git 練習
from tkinter import *
from tkinter import ttk
my_window =Tk()
my_window.geometry("400x450") # window size
my_window.title("Hello tkinter") # window size
label_one= Label(my_window, text='Message ')
label_one.grid(row=0, column=0)
text_msg=Text(my_window,height=1, width=20)
text_msg.... |
322812b0925f094500374daeab3c4a4ef69fcdb8 | gmt710/leetcode_python | /primary/4_levelOrder.py | 1,400 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
f07453deb6191dea09f0971ef446ffd8da4e0c4d | Muhammadabubakar503/LearnOOPFall2020 | /lecture/lec_3_condition.py | 548 | 3.953125 | 4 | #if condition
a=4000
if a>3000:
print("a is greater")
print("________________________________________________________________")
#if else condition
a=10
b=20
if a>b:
print("a is greater")
else:
print("b is greater")
print("________________________________________________________________")
# if e... |
ef936f4821123c71a0975c5bc822123b526624da | vinoth-rz/xrange | /xrange.py | 5,220 | 3.828125 | 4 | from math import ceil
from collections import Sequence, Iterator
class xrange(Sequence):
"""Pure-Python implementation of an ``xrange`` (aka ``range``
in Python 3) object. See `the CPython documentation
<http://docs.python.org/py3k/library/functions.html#range>`_
for details.
"""
def __init__(... |
957ab29289184d27b72433111fde4d79893d98a2 | OliEyEy/Git_FOR | /FOR/Áfangi 1/Æfingarverkefni/09_AEfingarverkefni/Æfingarverkefni 9.py | 1,545 | 3.59375 | 4 | #Æfingarverkfefni 9 - Ólafur Eysteinn - 8. Nóvember 2016
on="on"
while on=="on":
print("1. Lengsta orðið - 2. Random tölur - 3. Að telja orð - 4. Afturábak - 5. Hætta")
valmynd=int(input("Veldu lið. 1, 2, 3, 4 eða 5. "))
if valmynd==1:
#Liður 1
print("Liður 1")
ordalisti=[]
... |
08db14431f04a39050c2fbf74745b016c7064b35 | Pennylele/Algorithms-fun-daily | /150.py | 726 | 3.671875 | 4 | class Solution:
def evalRPN(self, tokens):
stack = []
def math(num1, num2, operator):
if operator == "+":
return int(num1) + int(num2)
if operator == "-":
return int(num2) - int(num1)
if operator == "*":
return int(... |
411fb38ec9c257cfadf9598c92d5f0b336b0a3df | perglervitek/Python-B6B36ZAL | /08/otazky.py | 343 | 3.6875 | 4 | # lst = [10,20,30,40,50,60,70]
# for v in lst:
# print(v)
# print("---------------")
# for v in lst:
# print(v, lst.pop(0))
lst1 = [
{'name': 'Josef Novák', 'age': 27},
{'name': 'Jan Srp', 'age': 80}
]
# create a copy of lst1
lst2 = []
for v in lst1:
lst2.append(v)
lst2.pop()
lst2[0]['age'] = 15
print(... |
32b368b818680d617098076c60d5e8b16c3b699e | Raj1v/machine_learning_final_project | /mean_recommendations.py | 1,180 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 19 13:19:46 2019
@author: Rajiv
"""
import numpy as np
class RecommendMean(object):
def __init__(self):
return
def get_ratings(self, targetid, targetmovies):
"""Returns mean ratings for each target movie"""
... |
132552e3768837e33e6c7e7f31bf31bbbaa74759 | irfankhan309/DS-AL | /Py_Codes/my_practice/python_series/MRO.py | 1,019 | 3.984375 | 4 | #THIS IS METHOD RESOLUTION ORDER (MRO),using C3 algorithm , (Linearization)
#1.magine you were implementing a programming language that featured inheritance.
#2.When you first approach this topic you decide:
#a child class will have all of the functions and attributes that it’s parent classes should have!
#Now this ma... |
f2ca20e9c4d281194986d064c9b98e62e17fbaeb | alex2018hillel/Hillel2020Python | /Lesson_5/Task_3.py | 225 | 3.75 | 4 | text = "Help ELephant learn LOops. While's and fOrs. RLD!"
symbol = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
word_list = []
for l in list(text):
if l in list(symbol):
word_list.append(l)
word = ''.join(word_list)
print(word) |
5b89071c42810564c4556fa9030dbdff39e070f4 | rafaelperazzo/programacao-web | /moodledata/vpl_data/396/usersdata/302/81017/submittedfiles/av1_programa2.py | 689 | 3.8125 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
n = int(input('Primeira aposta: '))
a = int(input('segunda aposta: '))
b = int(input('Terceira aposta: '))
c = int(input('Quarta aposta: '))
d = int(input('Quinta aposta: '))
e = int(input('Sexta aposta: '))
f = int(input('Primeiro sorteado: '))
g = int(input('segu... |
4884ec9675f3094eacfb1bd904b40554f79d233f | MaartensInformatica/Afvink-4 | /bug collegcot.py | 389 | 3.71875 | 4 | #geef de variabele bugs een waarde om ermee te kunnen werken
bugs = 0
for dag in range(1,6):
bugs += int(input('Dag '+str(dag )+' aantal bugs: '))
print('totaal: ',bugs)
#Er zijn 5 dagen, dus een reeks van 1 tot 6 (1 t/m 5)
#In de reeks wordt voor elke dag de input gevraagd onder de naam bugs
#print het to... |
4156e51b2936e465a631fdbf12d113e7046db2ec | sunxianpeng123/python_common | /common_used_package/json_pickle_test.py | 1,522 | 3.546875 | 4 | # encoding: utf-8
"""
@author: sunxianpeng
@file: json_pickle_test.py
@time: 2019/12/1 20:04
"""
import json
def dumps():
# dumps可以格式化所有的基本数据类型为字符串
list_json = json.dumps([])
# 数字
num_json = json.dumps(1)
# 字符串
str_json = json.dumps('abc')
dict = {"name": "Tom", "age": 23}
dict_json = ... |
a7f0e0e07c270272362513180235e560526bc790 | ishaansaxena/ProjectEuler | /100-199/108.py | 351 | 3.546875 | 4 | #!/usr/bin/python
from time import *
from math import *
start = time()
def numOfFactors(x):
factors = 1
for i in range(2, int(sqrt(x))+1):
if x%i == 0:
factors += 1
if x % sqrt(x) == 0:
factors = 2*factors - 1
else:
factors = 2*factors
return factors
for x in range(1,100000):
print x, numOfFactors(x)
... |
612f8f95614e0047c339e942e4bcdfe515c76601 | Alcheemiist/42-AI-Bootcamp-python | /M00/ex01/exec.py | 159 | 3.578125 | 4 | def step_back(x):
return x[::-1]
import sys
sent_str = ""
for i in sys.argv[1:]:
sent_str += str(i).swapcase() + " "
print(step_back(sent_str.strip())) |
5e25539bf587bf615e6ebb4abb10c445c1977e3f | bonicim/technical_interviews_exposed | /tst/fifty_common_interview_questions_leetcode_book/test_implement_strStr.py | 1,582 | 3.65625 | 4 | import pytest
from src.algorithms.fifty_common_interview_questions_leetcode_book.str_str import (
str_str,
)
def test_should_return_2():
haystack = "hello"
needle = "ll"
assert str_str(haystack, needle) == 2
def test_should_return_negative_1():
haystack = "aaaaaaaaaaaaaa"
needle = "bba"
... |
44ba6645417c5a8c7ad509dd7f4cf4292a0be822 | krysnuvadga/learning_portfolio | /preps/listAverage.py | 116 | 3.78125 | 4 | def average(arr):
n = len(arr)
s = sum(arr)
a = s/n
return a
list1 = [1,2,3]
print(average(list1))
|
1330586aa13df5de529dc2ffa61924508fe84fc9 | mthezeng/euler-solutions | /p013.py | 1,916 | 4.4375 | 4 | def addition_algorithm(numb3rs):
"""the elementary school addition algorithm
numb3rs is a file object
returns a list of digits corresponding to the sum of all numbers in numb3rs
the list is in reverse order: the last digit appears first in the list
Indeed, since python no longer has a maximum i... |
bbbcccee1d34b533f48cb710c13ccda52b998d5c | ishaankulshrestha/pythonBaseProjects | /com/ishaan/python/Refresher/A_refresher.py | 3,284 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 14:55:24 2018
@author: ishaan
"""
a, b, c, d, e = 1, 2, 3, 4, "ishaan"
print(a, b, c, d, e)
list1 = [1, 2, 3, 4, 'a', 'b', 'c', 'd']
print(list1)
print(list1[0:5])
tuple1 = (1, 2, 3, 4)
print(tuple1)
print(tuple1[2:4])
dictn = {"name": "ishaa... |
5334395e7d49ca38d4d6a4f87ed68b8f7f800936 | ronin2448/kaggle | /Titantic/src/tutorial/tutorialAnalysis.py | 4,315 | 3.609375 | 4 | '''
Created on Jun 22, 2014
@author: Domingo
'''
import csv as csv
import numpy as np
if __name__ == '__main__':
csv_file_object = csv.reader( open('../data/train.csv', 'rb') )
print("File read")
header = csv_file_object.next() #next() skips the first line which is the header
... |
aa7f61472af49b92e5bf973f74ea017802b7a6d4 | Linus-MK/AtCoder | /AtCoder_unofficial/chokudai_speedrun_002_f_2.py | 510 | 3.640625 | 4 | # setに入れてしまってその長さとかで解けないかな?
# setやlistはsetに入れられない。
# 1つの数に置き換えれば良い 大*10**10 + 小 なら
# Python (3.8.2)で462ms
n = int(input())
ans = set()
for _ in range(n):
a, b = list(map(int, input().split()))
if a < b:
a, b = b, a
# どちらを使ってもほぼ同じ速度だった。ビットシフトのほうが速そうだけど。
ans.add(a*10**10 + b)
# ans.add((a<<3... |
d438aa349aa2976a8da5f83574a4473cca6b20a8 | vgsprasad/Python_codes | /prime1s.py | 336 | 3.734375 | 4 | def numones(num):
count = 0
while(num & (num-1)):
count = count +1
num = num & (num-1)
return count
def countPrimeSetBits(self, L, R):
count = 0
primelist = [2,3,5,7,11,13,17,19]
for X in range(L,R):
if numones(X) in primelist:
count = count+1
return coun... |
7716238a1a85eea8588ad5bb95cd755742e5f0cd | AaronLack/C200 | /Assignment5/magic.py | 224 | 3.828125 | 4 | def magic(x):
x= (((15+x)*3)-(9))/(3)-12
return x
if __name__=="__main__":
x = input("Pick any positive whole number: ")
x = int(x)
print("Your number was", magic(x))
if __name__=="main":
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.