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 |
|---|---|---|---|---|---|---|
0f00b77ba1cfcbd85742f80e25f2bb758fd70294 | hrishitelang/Python-For-Everybody | /Programming for Everybody (Getting Started with Python)/Week 5/Assignment3.1.py | 177 | 3.90625 | 4 | #Enter inputs
hrs = input("Enter Hours:")
h = float(hrs)
rph = float(input("Enter rate per hour:"))
if h>40 :
print(40*rph + (h-40)*1.5*rph)
else :
print(h*rph)
|
3fb34220befbe4e36c0eb3c931fdd5fa7e7c3b09 | Aasthaengg/IBMdataset | /Python_codes/p02833/s397738111.py | 280 | 3.53125 | 4 | def resolve():
'''
code here
'''
N = input()
res = 0
if int(str(N)[-1]) % 2 == 0:
i = 0
N=int(N)
while int(N) >= 2*5**i:
i += 1
res += N//(2*5**i)
print(res)
if __name__ == "__main__":
resolve()
|
0fa265e981383d9c30344ec38c01bcdc74921a25 | upstarter/python_algorithms | /python_algorithms/control_flow.py | 684 | 4.0625 | 4 | # Ensure variable is defined
try:
x
except NameError:
x = None
# Test whether variable is defined to be None
if x is None:
print("some fallback operation")
else:
print("some operation with: ", x)
# Conditionals
## If
age = 18
if age >= 18:
print(("is an adult"))
elif age >= 12:
print("is a y... |
c06135e6937add9b8703252d5d93dc770a69e18a | brijrajsingh/auto-pricepredict-amlworkbench | /linear-regression.py | 1,843 | 3.71875 | 4 | import numpy as np
import pandas as pd
from sklearn import linear_model
from sklearn.cross_validation import train_test_split
import pickle
from matplotlib import pyplot as plt
# Use the Azure Machine Learning data preparation package
from azureml.dataprep import package
# This call will load the referenced package ... |
bff6d6335b618f5bd89fdf97b5e5159c910d6442 | jparker/therminator_client | /therminator/sensors/photoresistor.py | 4,646 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
import math
import signal
import time
from RPi import GPIO
logger = logging.getLogger(__name__)
def read(pins, capacitance, resistance, voltage=3.3, n=20, timeout=300):
"""Return the average resistance of the photoresistor.
Keyword arguments:
... |
fa76492a9a1d94d4aa794cb8c2563c25917dcae9 | leandrotune/Python | /pacote_download/PythonExercicios/ex029.py | 352 | 3.8125 | 4 | # Radar de multa:
carro = float(input('Em que velocidade seu carro estava rodado ? '))
multa = (carro - 80) * 7
if carro <= 80:
print('Bom dia! Dirija com segurança!')
else:
print('MULTADO! você excedeu o mimite de 80km/h')
print('Você deve pagar uma multa de: R${}'.format(multa))
print('Tenha um bom d... |
e0b1f2f1a7fc3bc1ceaa756f470ff35d9674e458 | danielbrandao/AprendendoPython | /Aula3/exAula3.3.py | 116 | 3.890625 | 4 | #Declarando a variável S
s = 'Minha String'
#Concatenando a variável em uma frase
print("O valor de s é: " + s)
|
c5d6f374c7e735ad2191fcab5e1c60238d59d7aa | cromox1/KodPerang_kata | /4kyu_twice_linear.py | 2,794 | 4 | 4 | '''
Consider a sequence u where u is defined as follows:
The number u(0) = 1 is the first one in u.
For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u too.
There are no other numbers in u.
Ex: u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]
1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13... |
2064aca7163b55914d1c4e9faf7a1382da6a20ed | rharyadi/cryptophrenia | /exteuclid.py | 1,059 | 3.546875 | 4 | #!/usr/bin/env python3
"""
Extended Euclidean Algorithm.
Given two integers a,b, solving au+bv=gcd(a,b)
then returning [u,v]
"""
from divide import divide
from errorhandler import zerodiv, inputerror
from sys import argv
def exteuclid(a,b):
try:
[q,r] = divide(a,b)
except ZeroDivisionError:
z... |
522c144fcb2c05df5409d51365ff3890225a679b | neaGaze/CodingPractice | /src/solutions/recursion/WordSquares.py | 2,062 | 4.03125 | 4 | """
Given a set of words (without duplicates), find all word squares you can build from them.
A sequence of words forms a valid word square if the kth row and column read the exact same string,
where 0 ≤ k < max(numRows, numColumns).
For example, the word sequence ["ball","area","lead","lady"] forms a word square be... |
bc8728ca84e11844610f6f826de8bc254dd9758d | willgood1986/myweb | /pydir/indexer.py | 1,613 | 3.515625 | 4 | # -*- coding: utf-8 -*-
class MyItems(object):
'''
We can simulate the obj[index] by __getitem__
slice type, start, stop
__init__: constructor
__iter__: IEnumerable
__next__: GetIteration
'''
def __init__(self, maxlen):
self._maxlen = maxlen
self._index = 0
def __it... |
864fd4bceea556eee8181191add92b9f516ceb53 | cjones6/cubic_reg | /src/cubic_reg.py | 21,614 | 3.53125 | 4 | """
This module implements cubic regularization of Newton's method, as described in Nesterov and Polyak (2006) and also
the adaptive cubic regularization algorithm described in Cartis et al. (2011). This code solves the cubic subproblem
according to slight modifications of Algorithm 7.3.6 of Conn et. al (2000). Cubi... |
4e7f0ab51df44fb6cf74790008160b6233521a2a | cecilioct/programa_u-dos | /prograu2.py | 20,334 | 3.75 | 4 | import re
def derizqui(str, princ):#Resive la incognita y la cadena ::::Esta funcion es cuando los operadores son iguales en casos donde las operaciones_
element=str #se van resolviendo de izquierda a derecha
print("Elementos del tripo :"+element)
print("") ... |
3180cfe2d50dcb8fefd0bc8c0fbfed595a063845 | fuxingbit/python | /day3/file.py | 1,338 | 3.859375 | 4 | #Author: Jenliver
# open file
# data = open("yesterday", encoding="utf-8").read()
# f = open("yesterday", 'rw', encoding="utf-8") # 文件句柄
# data = f.read()
# print(data)
#w = open("day2", 'w', encoding="utf-8")
# w.write("人生苦短,我用python\n")
# w.write("人生苦短,我用python")
#a = append追加
# w = open("day2", 'a', encoding="u... |
6a174a0760c03f385263d6b70a76369b37009b4d | jamesnatcher/Old-Python-Stuff | /CS 101/CS 101 Labs**/SHOPPING CART.py | 4,099 | 3.84375 | 4 | menu = 'MENU\na - Add item to cart\nr - Remove item from cart\nc - Change item quantity\ni - Output items\' descriptions\no - Output shopping cart\nq - Quit'
class ItemToPurchase:
def __init__(self, user_string = 'None', user_float = 0, user_int = 0, user_description = 'none'):
self.item_name = user_stri... |
0f84ae86d503c328393c110f922a3944d8d2d418 | wrillrysata/udacity-mini | /breaktime.py | 601 | 3.9375 | 4 | #first program. An alarm that pops up every 2hours and prompts you to take a break from ur pc
import webbrowser #webrowser and time is a module in the python standard library
import time
count=0 #set the count to 0
break_count =3 #we're taking 3 breaks
print ("Yoo, The program started on" +time.ctime()) #print out the ... |
68eaa38e4461dd33380da7833d200a72e2824aad | BharathTalloju/ProblemSolving | /largest_common_subsequence.py | 759 | 3.75 | 4 |
s1 = raw_input("Enter s1:").strip()
s2 = raw_input("Enter s2:").strip()
l1, l2 = len(s1)-1, len(s2)-1
def largest_common_subsequence(s1, l1, s2, l2, result):
if l1 < 0 or l2 < 0:
return 0
if s1[0] == s2[0]:
result.append(s1[0])
return 1+largest_common_subsequence(s1[1:], l1-1, s2[1:], l2-1, result)
else:
... |
ec2b2f25c325958ee54f1da3d4e57193c9a4dee7 | jason3189/Mr.zuo | /Mr.左/month01/代码/day13/code.py | 1,379 | 3.65625 | 4 | #1.
list01 = [
["00", "01", "02", "03"],
["10", "11", "12", "13"],
["20", "21", "22", "23"],]
#1.
import exercise01
n01=exercise01.DoubleListHelper.get_elements(list01, exercise01.Vector2(1, 0), exercise01.Vector2.right(), 3)
print(n01)
#2.
from exercise01 import DoubleListHelper as helper
from exercise01 i... |
351ce1d0f507413a4c67199b220e48c532fd3d14 | kotelyan/Lattice | /Lattice/Lattice.py | 864 | 3.765625 | 4 | from Particle import *
import random
class Lattice(object):
"""defines a square 2D Lattice of Particle's type A and B and H(holes)
Copyright M.Kotelyanskii
7/30/2017 - just set up a 2D rectangular PBC grid and flip particles at random, no interactions
"""
def __init__(self,x_size=2,y_size=2,x_... |
50c92d0ab111bd218714901f976dad57b30d0fd5 | todorovventsi/Software-Engineering | /Programming-Fundamentals-with-Python/functions-m.exercise/02.Center-point.py | 398 | 3.9375 | 4 | # d = sqrt(a**2 + b**2)
import math
def distance_to_origin(x, y):
return abs(math.sqrt(x**2 + y**2))
x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
d_first = distance_to_origin(x1, y1)
d_second = distance_to_origin(x2, y2)
if d_first <= d_second:
print(f"({math.floor(x1)},... |
c7ecdd9b9bc2f865b3d44a1b7d9708fba6a25cab | dantangfan/leetcode | /SortColors.py | 807 | 3.703125 | 4 | # coding:utf-8
# 经典问题
# 排序 0,1,2 三个数字
# 只需要三个指针分别指向头/尾/当前位置,将0向左移,2向右移
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
llen = len(nums)
if not llen:
retu... |
32593bf68b1c34f438e8577a78af1ba32297c892 | avneeshgupta/tathastu_week_of_code | /Day5/Program5.py | 582 | 3.9375 | 4 | def sort_list(list1,num1):
c=0
for x in range(num1):
if list1[x]%2==0:
for y in range(x+1,num1):
if list1[y]%2!=0:
list1[x],list1[y]=list1[y],list1[x]
c+=1
break
else:
continue
list1=sorted(li... |
bad4b9399df13af52023d27c7654d279ca65e1e8 | EdmundGoodman/go-fish | /app.py | 11,402 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from card_deck import Card, Faces, CardError
from os import system
class SafeInputs:
@staticmethod
def yes_no_input(prompt="Enter yes or no (y/n) "):
"""Repeatedly query for a yes or no input, until one is given, then
return the appropriate b... |
3227055aaecd6c05c9239c69f4074591124ba65d | qiangwennorge/AlgorithmInPython | /TurtleTree.py | 532 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on May 02 20:37 2017
@author: qiangwennorge
"""
import turtle
def tree(branch_len, t):
if branch_len > 5:
t.forward(branch_len)
t.right(20)
tree(branch_len - 15, t)
t.left(40)
tree(branch_len - 15, t)
t.right(20)
t.backwa... |
3e138b791141f1c3cfeb8a975c1a95c4a0d6ae0f | 19doughertyjoseph/josephdougherty-python | /TurtleProjectPt2/TurtleProjectPt2.py | 970 | 4.1875 | 4 | import turtle
def main():
turtle.setup(width=800 , height=800)
turtle.title("Turtle Graphics - turtleIntro")
turtle.bgcolor("#1de047")
turtle.hideturtle()
turtle.speed(0)
inputinfo ()
circle ()
turtle.exitonclick ()
def inputinfo () :
color = input ('Input a color to draw with - '... |
03bee6c04fd6031eb725cfd02a90348b6e063ddf | mohsenil85/wordgen-round-1 | /wordgen.py | 1,172 | 3.859375 | 4 | # vim: tabstop=9 expandtab shiftwidth=4 softtabstop=4
# python 3??
from collections import defaultdict
import random
dictionary = defaultdict(list)
wordlist = "/usr/share/dict/cracklib-small"
def get_words():
for line in open(wordlist):
line += '@@'
word_to_dict(dictionary, line)
def word_to_... |
90af7aa8b14876659d444325adc52527c87bbc50 | ANKITPODDER2000/LinkedList | /24_compare_string.py | 655 | 4.125 | 4 | from LinkedList import LinkedList
from LinkedListHelper import CreateLinkedList
def compare(head1 , head2):
while head1 and head2:
if head1.val == head2.val:
head1 = head1.next
head2 = head2.next
elif head1.val > head2.val:
return 1
else:
retu... |
ccc152b3efb85b380b4796cc8a33449432a86c34 | adityamangal1/GeeksfForGeeks | /Arrays/Rotate of an array.py | 329 | 3.640625 | 4 | '''
Input:
2
5 2
1 2 3 4 5
10 3
2 4 6 8 10 12 14 16 18 20
'''
def rotate():
size, num = input().split()
array = list(map(int, input().split()))
array = array[int(num):] + array[:int(num)]
return array
if __name__ == "__main__":
n = int(input())
while(n > 0):
print(*rotate())
... |
8a2d8d6849b8b573619bd5a18f688dd5ba1e1132 | pau1tuck/nlp-python | /src/replacing/replace_spelling.py | 864 | 4.0625 | 4 | import enchant
from replacers import SpellingReplacer
replacer = SpellingReplacer()
print(replacer.replace('cookbok'))
# The SpellingReplacer class starts by creating a reference to an Enchant dictionary. Then, in the replace() method, it first checks whether the given word is present in the dictionary. If it is, no ... |
02d183d12aa19312a3886920d361c2814032e96d | Aperocky/leetcode_python | /025-ReverseNodeKGroup.py | 3,147 | 3.9375 | 4 | """
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked li... |
7866aded4b0288b72e7718c3da9ff25d7f65da49 | sabinzero/various-py | /circle length/main.py | 183 | 4.21875 | 4 | PI=3.1415926
r=input("get radius: ")
while r<0:
print "radius cannot be negative"
r=input("get radius: ")
circle_len = 2 * PI * r
"circle_length = %f" % circle_len |
5edaec01cbc6665b4e71a05fe6887f7c49c1737e | dianaartiom/algorithms | /search/linear/linear.py | 142 | 3.703125 | 4 |
array = [1,2,11,4,5,6,7]
n = 4
for i in range(len(array)):
if (n == array[i]):
print "Element " + str(array[i]) + " was found."
|
024afff857c0160b02e01caf6ff61ab9987ca564 | narahkwak/CSE111course | /.py | 1,161 | 4.15625 | 4 | # Example 5
def main():
# Create a dictionary with student IDs as the keys
# and student data stored in a list as the values.
students = {
"42-039-4736": ["Clint", "Huish", "hui20001@byui.edu", 16],
"61-315-0160": ["Michelle", "Davis", "dav21012@byui.edu", 3],
"10-450-1203": ["Jorge... |
21ba62f479898f125f49c2079d43e42fe8df473a | 106FaceEater106/Pythonparazumbis | /Lista 1/ex01.py | 85 | 3.71875 | 4 | n1 = int(input("Numero: "))
n2 = int(input("Numero: "))
soma = n1 + n2
print(soma) |
e4627f5792bd6a2e8b9d86416ef9b3a0370db248 | fainaszar/pythonPrograms | /files.py | 885 | 4.09375 | 4 |
filename = raw_input("Enter the name of the file to open: ")
try:
file_content = open(filename)
except IOError:
print "File %r not found" % filename
exit()
print "The file %r has following content :\n" % filename
print file_content.read()
print "Keep the file or overwrite it ? Press Ctrl+C to keep the file"
tr... |
37defdc2116aa20c6314d20a91027698062e76c3 | stongeje/Great-Courses | /episode_9.py | 929 | 3.890625 | 4 | def getName():
first = input("Enter your first name:")
last = input ("Enter your last name:")
full_name = last + ", " + first
return full_name
#name = getName()
#print(name)
#def getGuess():
number = input("Enter a number: ")
return number
#guess = getGuess()
#print(guess)
... |
e58281d79a351df67eb54e0b4c567297a6495466 | cacciella/Curso-em-Video | /aula_desafio_003.py | 204 | 3.84375 | 4 | # mostre dois numeros e mostre a soma entre eles
n1 = int (input('digite um valor 01 '))
n2 = int (input('digite um valor 02 '))
s=n1+n2
print('A soma de {} + {} é igual a {}' .format(n1,n2,s))
# foi.. |
c06f894590c2cb0c708286defdadd7f4d3a91009 | neequole/my-python-programming-exercises | /shuffle/fisher_yates_shuffle.py | 291 | 3.5 | 4 | import random
def shuffle(seq):
for i in range(len(seq)-1, -1, -1):
k = random.randint(0, i)
temp = seq[i]
seq[i] = seq[k]
seq[k] = temp
text_twist = list("sunflower")
print(text_twist)
for x in range(11):
shuffle(text_twist)
print(text_twist)
|
2298b063a593ef744af8cc087b3e01b37d463267 | pauvrepetit/leetcode | /88/main.py | 877 | 3.640625 | 4 | # 88. 合并两个有序数组
#
# 20210716
# huao
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
nums = nums1[:]
i, j, loc = 0, 0, 0
while i < m and j < n:
if nums1[i] < nums2[j]:
nums[loc] = nums1[i]
... |
88e80647245203cb9a189b40699dfd297c1d55e9 | soy-sauce/cs1134 | /HW4/cz1529_hw4_q8.py | 400 | 3.75 | 4 | def flat_list(nested_lst, low, high):
if(low > high):
return []
out = []
if(isinstance(nested_lst[low], int)):
out.append(nested_lst[low])
else:
out += flat_list(nested_lst[low], 0, (len(nested_lst[low])-1))
out += flat_list(nested_lst, low+1, high)
return out
... |
9a07d5b36405cdfa55efe9000a35009e341389cb | zarkaltair/Data-Scientist | /Coursera_courses/Diving_in_python/03_week/Classes/07_classmethod.py | 918 | 3.578125 | 4 | class ToyClass:
def instancemethod(self):
return 'instance method called', self
@classmethod
def classmethod(cls):
return 'class method called', cls
@staticmethod
def staticmethod():
return 'static method called'
obj = ToyClass()
print(obj.instancemethod())
# ('instan... |
e2501aae6798871faae299fc5683679a0e96c444 | whereistanya/aoc | /2017/17.py | 862 | 3.625 | 4 | #!/usr/bin/env python
# Advent of code Day 17.
inputvalue = 348
#inputvalue = 3
circular_buffer = [0] # probably better as a linked list
position = 0
posone = set()
length = 1
i = 1
while i < 50000000:
# For part two, don't actually need to insert it, just act as if we did.
#position = ((position + inputval... |
be2c53b437d421f1b27c187e1277cfec3d3bc5a2 | ienax/code | /Fibonacci's_Numbers.py | 651 | 3.828125 | 4 | """
Условие
Дано натуральное число A.
Определите, каким по счету числом Фибоначчи оно является, то есть выведите такое число n, что φn = A.
Если А не является числом Фибоначчи, выведите число -1.
"""
def fib_digit(a):
i = 1
if a == 0 :
return 0
else:
x, y = 0, 1
while y < a:
x,... |
7cd9b65c368cc924f15e1ec12c18f749f43324ce | DPBefumo/snippet-directory | /snippet_collection/binary-search-types.py | 1,611 | 4.28125 | 4 | """
Notes:
"""
"""
Problem:
The height of a binary search tree is the number of edges between the tree's root and its furthest leaf. You are given a pointer, root, pointing to the root of a binary search tree. Complete the getHeight function provided in your editor so that it returns the height of the binary search tr... |
7279ea9e3790714850d0ed315b81e396c789bef3 | nancydyc/Code-Challenge | /nextNodeInBST.py | 1,889 | 3.875 | 4 | """
Write an algo to find the "next" node of a given node in a bst.
In order traversal. Assume each node has a link to its parent.
5
/ \
2 6
/ \
1 4
/ \
3 4.5
runtime: O(n)
space: O(n) n is the... |
8275202813e6ce955f3114d509d1342c084a07e0 | tgparton/NDTC | /PythonPractical/PythonScriptVersion/block notebooks/0_PythonIntro.py | 21,141 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Python Introduction
# 2018/10/18
# [tgp27@cam.ac.uk](mailto:tgp27@cam.ac.uk)
#
# ## Sources
# Content based on
# * [Python Standard Library](https://docs.python.org/3/library/)
# * [NumPy manual](https://docs.scipy.org/doc/numpy/)
# * [Pandas manual](http://pandas.pydata.or... |
ffd319452c5b38b402c9aabe26583388ae19ede0 | wanghan2789/CPP_learning | /algorithm/Practice/并查集基础实现 (2).py | 2,581 | 3.65625 | 4 | class BCSet:
def __init__(self, val):
self.val = val
self.parent = self
self.count = 1
def is_same_set(self, set2):
set1 = self
stack1 = []
stack2 = []
while set1 != set1.parent:
stack1.append(set1)
set1 = set1.parent
while... |
4e89281b164b04e21cecd99c8be0b0f1e6ff5e2f | mccullaghlab/Fixman-Theory-Coding-Day-1 | /hello_world/v4/hello_world.py | 106 | 3.59375 | 4 |
helloWorld = "Hello World"
maxIter = 10
for i in range(maxIter):
if i%2 == 1:
print i+1, helloWorld
|
773bfaecd14ea6f4835042c5de9993e6c8138381 | wadi19-meet/y2s18-python_review | /exercises/for_loops.py | 126 | 3.515625 | 4 | # Write your solution for 1.1 here!
a = 0
for i in range (100):
if i % 2 == 0:
a= a + i
print(a)
|
46705a5545c1f59452dd815cdac338dbb44059b2 | Jeta1me1PLUS/learnleetcode | /696/696CountBinarySubstrings.py | 1,005 | 3.625 | 4 | # Scroll to the bottom for the 3-liner
# An intuitive approach will be to group the binary string into chunks of 0s and 1s (sort of like compressing). The answer will be simply to sum the min of length of neighboring chunks together.
# Here are some examples:
# '00001111' => [4, 4] => min(4, 4) => 4
# '00110' => [2,... |
6ba67f950a737686f97dc10248cedfa41bc93854 | QIAOZHIBAO0104/My-Leetcode-Records | /6. ZigZag Conversion.py | 935 | 4.1875 | 4 | '''
https://leetcode.com/problems/zigzag-conversion/
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
(you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the ... |
ef36f4262c9ac76da8ecaeea2bc806e2990dac9d | Abhi551/starting | /permute.py | 510 | 3.625 | 4 | def permute(word):
if n==0:yield [];
else :
for i in range(n):
for a in permute(word[:i]+word[i+1:]):
yield [word[i]]+a;
def middle_permutation(word):
list_of_word,word,x,s=[],list(word),0,1;
for i in range(n):
s=s*i;
word.sort();
for p in permute(word... |
0111d0d5009a521f9db1b1ab6325a14a725f4656 | Yvonnexx/code | /word_search.py | 1,186 | 4.09375 | 4 | #!/usr/bin/python
"""
>>> exist(board, 'ABCCED')
True
>>> exist(board, 'SEE')
True
>>> exist(board, 'ABCB')
False
"""
def exist(board, word):
if not board or len(board) == 0:
return False
if len(word) == 0:
return True
for i in range(len(board)):
for j in range(len(board[0])):
... |
3a48afd4fc43f5926ca091842d01af47bd876e25 | catr1ne55/epam_training_python | /lec4/lec/task2.py | 402 | 3.921875 | 4 | import functools
def count_test(sentences):
""" Counts number of occurrence "test" in sentences.
:param sentences: A list f strings, where we count occurrences of "test".
:type sentences: list.
:returns Number of "test" in sentences.
:rtype int.
"""
return functools.reduce(lambda x, y: x ... |
96a203be0ec011c3f75d2776e0ead35e24ecb341 | ht-dep/Algorithms-by-Python | /Python Offer/06.The Sixth Chapter/65.Swap_Two_ele.py | 361 | 3.796875 | 4 | # coding:utf-8
'''
交换两个变量的值
不能使用新的变量
'''
def SwapTwoEle(x, y):
# 方法一:加减法
x = x + y
y = x - y
x = x - y
print x, y # 交换
# 方法二:异或法
x = x ^ y
y = x ^ y
x = x ^ y
print x, y # 交换
if __name__ == '__main__':
x = 15
y = 27
SwapTwoEle(x, y)
|
8fb9bd6572985c797884b6c5608c14495786bbf9 | jjb33/PyFoEv | /Chapter09/exercies9.3.py | 891 | 3.59375 | 4 | """
Write a program to read through a mail log, build a histogram
using a dictionary to count how many messages have come from
each email address, and print the dictionary.
"""
'''
Outline:
define dict
choose file (skip the user request for speed this time)
open file
find From or From:
if there,
count w dictionar... |
0364c9fbd0db255eeae35e29929a484e43427bc0 | animus203/59 | /16.py | 468 | 3.75 | 4 | def index_words(text):
result = []
if text:
result.append(0)
for index, letter in enumerate(text):
if letter == ' ':
result.append(index + 1)
return result
address = 'for you and for me i'
result = index_words(address)
print(result)
def index_words_iter(text):
for ind... |
c6bb4ef580560326008a6dca541e17aa97dc1368 | shubhamgupta16/Python_Programs | /73_chap5_exer4.py | 381 | 4.125 | 4 | # filter odd even
# define a function
# input
# list ---> [1,2,3,4,5,6,7]
# output ---> [[1,3,5,7],[2,4,6]]
def seprate_element(l):
even = []
odd = []
for i in l:
if i%2 == 0:
even.append(i)
else:
odd.append(i)
output = [odd,even]
return output... |
2ed780d8d09586e022dacc81825e527594ce50d7 | raulpeter/lpthw | /ex08.py | 342 | 4.0625 | 4 | #对格式化输出进一步练习强化
formatter = "{} {} {} {}"
print(formatter.format(1,2,3,4))
print(formatter.format("one","two","three","four"))
print(formatter.format(True,False,True,False))
print(formatter.format(formatter,formatter,formatter,formatter))
print(formatter.format("try your","own txt here","maybe a poem","or a song")) |
aeabc8e01e471a953b725b887b96e36f8f9b6426 | promacbhattacharyya/Programming-for-Everybody-Coursera | /PythonForEverybody-Assignments.py | 2,121 | 4.375 | 4 | ## Assignment 1: Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
hours = input('Enter the hours worked: ')
rate = input('Enter the rate: ')
h = float(hours)
r = float(rate)
pay = (h*r)
print('Your pay is: $',pay)
## Assignment 2: Write a program to prompt the... |
cd3ed236afc9e747c49ea4e4123575f9f1311718 | Dadinel/Alura_introducao-ao-python | /python/biblioteca.py | 835 | 3.75 | 4 | # -*- coding: UTF-8 -*-
def gera_nome_convite(convite):
posicao_final = len(convite)
posicao_inicial = posicao_final - 4
parte1 = convite[0:4]
parte2 = convite[posicao_inicial:posicao_final]
#print '%s %s' % (parte1, parte2)
return parte1 + " " + parte2
def envia_convite(nome_convidado):
p... |
fdbf2d99b09a3691cc9b219ba21adaf0081121ce | seena00/Worth-It | /priceComp.py | 2,212 | 3.828125 | 4 | import random
class car(object):
name = ""
mileage = 0.0
def __init__(self, name, mileage):
self.name = name
self.mileage = mileage
def calcMileage(self, distance): #calculates the gas lost driving to the gas station using the dist and mileage
return float(distance/self.mileag... |
1ff2b8a23fd6721ca8bae5217aa1a28907c0ef8a | hui55/primaryPython | /src/think.py | 3,770 | 3.5625 | 4 | if __name__ == '__main__':
print("--- think.py ---")
# 代码1
def print_lyrics():
for _ in range(5):
print("你好,我打印出来函数lyrics的内容")
print("Python非常有意思")
def repeat_lyrics():
print_lyrics()
repeat_lyrics()
# 代码2
# def sort_by(x, y):
# if x>y:
# return True
# else:
# ... |
40fd4e2de115d3e2be9cf1e47fb95fe7e4d3e378 | skyil7/DiscreteMathematics | /과제/154p 4-6.py | 227 | 3.765625 | 4 | """
A와 B의 관계 R은 b가 a로 나누어 떨어질 때, aRb이다. 이때 R을 구하라.
"""
A = [2,3,4,7]
B = [2,3,4,5,6]
R = []
for a in A:
for b in B:
if b % a == 0:
R.append((a,b))
print(R) |
baadc14eb82fe19791d4246498fc65c425906f35 | 59090939/ClassProjects | /CSCI210 - gamemaking/homework2/Tomogachi/Tamagochi.py | 2,281 | 3.609375 | 4 | ################################################################################
# Tamagochi.py version 1.0 Dana Hughes 18-February-2012
#
# Edited by David Schirduan 3/18/12
# changed sleep wait time to .1 seconds to speed up debugging and testing
#
# Create the behavior of a simple Tamagochi. The beha... |
0e57fa79a76a197773cde1613df3842579e9a3a8 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4350/codes/1596_1015.py | 142 | 3.546875 | 4 | a = int(input("valor"))
b = int(input("valor"))
c = int(input("valor"))
print(min(a,b,c))
print(a+b+c-min(a,b,c)-max(a,b,c))
print(max(a,b,c)) |
0d54841824cf66e4afa0fa041e9dc7c2fe03ed5a | mguaypaq/union-find | /solutions/python3/depth_first_search.py | 1,441 | 3.84375 | 4 | #!/usr/bin/python3
r"""
A solution using depth-first search.
"""
def main():
# Read vertices from stdin
num_vertices = int(input())
vertices = list(range(num_vertices))
# Read edges from stdin
num_edges = int(input())
edges = [int_pair(input()) for _ in range(num_edges)]
# Construct the g... |
590cab46ee48d2e7380fd4025683f4321d9a1a34 | dipak-pawar131199/pythonlabAssignment | /Introduction/SetA/Simple calculator.py | 642 | 4.1875 | 4 | # Program to make simple calculator
num1=int(input("Enter first number: "))
num2=int(input("Enter second number: "))
ch=input(" Enter for opration symbol addition (+),substraction (-),substraction (*),substraction (/), % (get remainder) and for exit enter '$' ")
if ch=='+':
print("Sum is : ",num1+num2)
... |
044ac2027b9dfc78372d3064475584aac4578cdf | dexterchan/DailyChallenge | /Jan2020/JumpToTheEnd.py | 2,608 | 3.90625 | 4 | #Skill: Path searching, backtracking
#Difficulty: Medium
#Starting at index 0, for an element n at index i, you are allowed to jump at most n indexes ahead. Given a list of numbers, find the minimum number of jumps to reach the end of the list.
#Example:
#Input: [3, 2, 5, 1, 1, 9, 3, 4]
#Output: 2
#Explanation:
#The ... |
cccfec60a53e859e3473ab00aa5b6e329aaf25da | bushuhui/python_turtle | /codes/4_cherryFlower3.py | 847 | 3.71875 | 4 | from turtle import *
from random import *
from math import *
"""
Ref:
https://blog.csdn.net/weixin_43943977/article/details/102691392
"""
def tree(n, l):
pd()
t = cos(radians(heading() + 45)) / 8 + 0.25
pencolor(t, t, t)
pensize(n / 4)
forward(l)
if n > 0:
b = random() * 15 + 10
... |
4312e8d077dbd202721f90732d97abc3786ce0a1 | ActiveAnalytics/littleR | /factor.py | 5,668 | 3.9375 | 4 | # -*- coding: utf-8 -*-
# Implementation of factor class based on lists
# The purpose of the level object is to create a class that allows selection
# on unique items that is able to handle when an item is selected and isn't in
# the list
class level(np.ndarray):
'''
Description
-----------\n
... |
95be5b2265800736878e7c2c0be6e79717a71965 | hamzayn/My_HackerRank_Solutions | /Second task.py | 184 | 3.640625 | 4 | if __name__ == '__main__':
a = int(input())
b = int(input())
if (a>=1 and a<=10**10) and (b>=1 and b<=10**10):
print(a+b)
print(a-b)
print(a*b) |
678665ce16a4988f2c898d1954ad909b39064f19 | Malfunction13/Rotten-Apples | /RA-v3_fixed.py | 2,888 | 4.15625 | 4 | import copy
#take user input for crate size
rowsXcolumns = [input("Please insert your crate size as ROWSxCOLUMNS:")]
#intialize list with crate size in rowsXcolumns format and add the measures as separate list entries by splitting based on "x"
crate_size = []
for measures in rowsXcolumns:
for measure in meas... |
ebeb8cd94ef4dd58384f3eee3e2b833b7a76694d | oustella/coding-exercises | /rotateMatrix.py | 2,586 | 3.859375 | 4 | # https://leetcode.com/problems/rotate-image/submissions/
# Given a 2D nxn matrix, rotate it by 90 degrees clockwise in place.
matrix = [
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
]
# rotated matrix should become
# [
# [15,13, 2, 5],
# [14, 3, 4, 1],
# [12, 6, 8, 9],
# [16, 7,10,11]
#... |
992801c296cb3d5f49e2b98b124180b31cc1bbf5 | ManojKrishnaAK/python-codes | /EXCEPTION HANDLING/div2.py | 416 | 3.5 | 4 | #div2.py------with functions
def div(a,b):
try:
x1=int(a)
x2=int(b)
x3=x1/x2
except ValueError:
print("don't enter ANV / Strings / Special symbols..")
except ZeroDivisionError:
print("don't enter zero for den..")
else:
print("div=",x3)
print("prog exec successfully")
finally:
print("i am from final... |
f87dc7ee61bd66a8feabb65c55278907c431a634 | ninaholm/Discourse-Machine | /Nina_beta/pickle_test.py | 1,646 | 3.5625 | 4 | import csv
import pickle
import time
import random
def load_data(filename):
with open(filename) as file:
data = pickle.load(file)
return data
def pickle_dump_data(data):
times = []
for i in range(1,100):
starttime = time.time()
with open("temp", "w") as file:
pickle.dump(data, file)
times.append(tim... |
f7a3f1b2507ffa94ea330173656a28bebe939afd | kishanrajasekhar/UFO-Ambush | /missile.py | 208 | 3.59375 | 4 | #A missile is a tiny projectile
from projectile import Projectile
import math
class Missile(Projectile):
def __init__(self, x,y, angle, color):
Projectile.__init__(self, x, y, angle, 2.5, color) |
71cdf88966fcfcac511bd6cf82fc7c7ebd37f11c | vtemian/interviews-prep | /leetcode/medium/validate-bst.py | 655 | 3.90625 | 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 isValidBST(self, root: TreeNode) -> bool:
def valid(node, lower=float('-inf'), upper=float('inf')):
if not node:
... |
92adb32ee798e5f439d6985f416f5367da8f7f5a | ameenhashir/DataStructuresPython | /youtube_codebasics/DataStructures/graph/graph_flightroutes.py | 2,008 | 3.84375 | 4 | class Graph:
def __init__(self,edges):
self.edges = edges
self.graph_dict = {}
for start,end in self.edges:
if start in self.graph_dict:
self.graph_dict[start].append(end)
else:
self.graph_dict[start] = [end]
def get_path(self,star... |
6eac4fc6f6615498263978e5525ed736f2f8371c | CodecoolGlobal/erp-mvc-test_adam | /model/crm/crm.py | 2,671 | 3.671875 | 4 | """ Customer Relationship Management (CRM) module """
# everything you'll need is imported:
import random
from model import data_manager
def generate_random(table):
"""
Generates random and unique string. Used for id/key generation:
- at least 2 special characters (except: ';'), 2 number, 2 lower and... |
63aff696077e5bae40b15c84de29563a38312ebd | Diana-rufasto/trabajo04 | /conversores.llontop.py | 1,955 | 3.8125 | 4 | # Conversion de datos con I/O (I=Input/O=Output)
ninio,examen1,examen2,examen3="",0,0,0
promedio=0.0
# INPUT
ninio=input("Ingrese nombre ninio:")
examen1=int(input("Ingrese examen 1:")) # input() devuelve un str
examen2=int(input("Ingrese examen 2:"))
examen3=int(input("Ingrese exmanen 3:"))
# PROCESSING
promedio=(ex... |
f1af6004b94fdf06f08079a55d6edff1f0af9ebe | jackinf/aoc2019 | /day19/experiment.py | 824 | 3.75 | 4 | import numpy as np
import math
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
def plot_point(ax, point, angle, length):
x, y = point
# find the end point
endy = length * math.sin(math.radians(angle))
endx = length * math.cos(math.radians(angle))
m = math.tan(ma... |
cbc222e1802adf90be0cdacc3dd39a9bcfc4982e | SRG08/DesignPatternsInPython | /StructuralPatternsInPython/Decorator.py | 1,384 | 4.90625 | 5 |
# The Decorator Pattern is used to add functionality to a class without changing the class itself
# analogy : Fruits and vegetables
from abc import ABC , abstractmethod
class FruitsAndVegetables(ABC): # Abstract class
@abstractmethod
def get_handle(self , c):
pass
class Fruits: ... |
da0d2f01d0dffbd0d6cc4e1454b203f384c6d924 | testpass1982/Python_lessons_basic | /lesson04/home_work/hw04_hard.py | 3,022 | 3.53125 | 4 | # Задание-1:
# Матрицы в питоне реализуются в виде вложенных списков:
# Пример. Дано:
matrix = [[1, 0, 8],
[3, 4, 1],
[0, 4, 2]]
# Выполнить поворот (транспонирование) матрицы
# Пример. Результат:
# matrix_rotate = [[1, 3, 0],
# [0, 4, 4],
# [8, 1, 2]]
#... |
017825948a3cd8a2d45875ede631aa0e799fe22d | KPouliasis/CrackingCodeInterview | /Chapter10/SortAnagrams.py | 337 | 4.03125 | 4 | def sort_anagrams(strarray):
def compare(str1,str2):
if sorted(str1)<sorted(str2):
return -1
elif sorted(str1)==sorted(str2):
return 0
else:
return 1
strarray.sort(cmp=lambda x,y: compare(x,y))
return strarray
print sort_anagrams(["abba","bbaa","c... |
39fd86c1ae7deecafb9c3c31d8ce38e13cb94b4d | tushar9604/HackerRankSkillChallenges | /python/hex-color-code.py | 244 | 3.59375 | 4 | import re
for _ in range(int(input())):
# hexcodes = re.findall(r'(?<!^)(#[0-9a-f]{6}|#[0-9a-f]{3})',input(),re.I)
hexcodes = re.findall(r'(?<!^)(#(?:[\da-f]{3}){1,2})',input(),re.I)
for hexcode in hexcodes:
print(hexcode) |
6c0aa2ab8b14555cbea875c925cdf9ef9537184e | shishir7654/Python_program-basic | /inheritance9.py | 550 | 3.8125 | 4 | #Multilevel Inheritance
class Grandfather:
grandfathername =""
def grandfather(self):
print(self.grandfathername)
# Intermediate class
class Father(Grandfather):
fathername = ""
def father(self):
print(self.fathername)
# Derived class
class Son(Father):
... |
cb668091ffca6796e41ebcb216b722ada7ccd047 | youngvoice/myLeetcode_python | /preorderTraversal.py | 1,028 | 3.875 | 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 preorderTraversal(self, root: TreeNode) -> List[int]:
def traversal(curr, ret):
if curr:
ret.... |
d8ed4869d11e44926b5267def110a00a155cf92c | Awranik/BezKonserwantow | /plik6.txt | 434 | 3.671875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# zakres poszukiwa
n = 150
# lista liczb od 2 do n (0 i 1 nie s liczbami pierwszymi)
numbers = list(range(2, n + 1))
# usuwanie wielokrotnoci liczb pierwszych
for prime in numbers:
for multiple in range(2 * prime, n + 1, prime):
if multiple in numbers:
... |
5efeb00e2b1b38f0d782c484ddc8eeb4ae79ea07 | Harry-Ramadhan/Basic-Phthon-5 | /Week 2/for_loop.py | 125 | 3.78125 | 4 | fruits = ["apple", "banana","cherry"]
for buah in fruits:
print("Ini buah " + buah)
buah = "banana"
print(len(fruits)) |
2497d13703bec600c7aee2f110c00b7deeb4454a | xtyghost/python_helloworld | /controller/basic/v2/tuple.py | 430 | 4.0625 | 4 | #!/usr/bin/python3
tuple =('abcd',123,2.123,'runoob',23.2)
tinytuple=(1231,'sfadf')
print (tuple) # 输出完整元组
print (tuple[0]) # 输出元组的第一个元素
print (tuple[1:3]) # 输出从第二个元素开始到第三个元素
print (tuple[2:]) # 输出从第三个元素开始的所有元素
print (tinytuple * 2) # 输出两次元组
print (tuple + tinytuple) # 连接元组 |
6c2df3a173c96e3ee347710f5cc389694c7d2b47 | UgochukwuPeter/holbertonschool-higher_level_programming | /0x03-python-data_structures/1-element_at.py | 243 | 3.890625 | 4 | #!/usr/bin/python3
"""
a function that retrieves an element from a list
my_list: a integers list
idx: a index
"""
def element_at(my_list, idx):
if idx < 0 or idx > len(my_list) - 1:
return
return (my_list[idx])
|
510b02960226e5afe4b919d0b81744922ff6e318 | ntexplorer/PythonPractice | /PythonCrashCoursePrac/Chapter10_Prac/10-4.py | 332 | 3.765625 | 4 | trigger = True
while trigger:
print("Enter 'q' to quit.")
name = input("Please enter your name: ")
if name != "q":
print("Hello, {}".format(name.title()))
with open("guest_book.txt", "a") as guest_book:
guest_book.write(name + "\n")
else:
print("Input terminated!")
... |
205a483b671ef76042672c0831b44cb29508b683 | FrozenLemonTee/Leetcode | /sortByBits_1356/sortByBits.py | 1,543 | 3.765625 | 4 | """
1356. 根据数字二进制下 1 的数目排序
给你一个整数数组 arr 。请你将数组中的元素按照其二进制表示中数字 1 的数目升序排序。
如果存在多个数字二进制中 1 的数目相同,则必须将它们按照数值大小升序排列。
请你返回排序后的数组。
示例 1:
输入:arr = [0,1,2,3,4,5,6,7,8]
输出:[0,1,2,4,8,3,5,6,7]
解释:[0] 是唯一一个有 0 个 1 的数。
[1,2,4,8] 都有 1 个 1 。
[3,5,6] 有 2 个 1 。
[7] 有 3 个 1 。
按照 1 的个数排序得到的结果数组为 [0,1,2,4,8,3,5,6,7]
示例 2:
输入:arr ... |
90c5e7f553374e86ae74139c7317956b03f2c1d1 | Po3mTo/Python_Hard_Way | /ex014.py | 671 | 4.125 | 4 | from sys import argv
script, user_name, car = argv
prompt = 'Your answer: '
user_name = input("What's your name?: ")
script = 'Piotr'
print(f"Hi {user_name},I'm the {script} script.")
print("I'd like to ask you a few questions.")
print(f"Do you like me {user_name}?")
likes = input(prompt)
print(f"Where do you live {... |
ddf190ac09665a07f67a34bcdc4b3d51781301de | jamesholbert/jamesholbert.github.io | /starstream/star.py | 3,523 | 3.578125 | 4 | from random import randint
import os
#for x in range(0,100):
#print (randint(0,9))
def strike(text):
return ''.join([u'\u0336{}'.format(c) for c in text])
class dice:
def __init__(self, name, first, second, third, fourth, fifth, sixth):
self.name = name
self.first = first
self.second = second
self.third = t... |
62a3c64922fc7356b214cd8319a1f847b97cc0e0 | gouravkmar/codeWith-hacktoberfest | /python/Checking-Prime-Number.py | 615 | 4.375 | 4 | # Program to check whether a number is prime number or not
# To take input from the user
number = int(input("Enter the number: "))
# prime numbers are greater than 1
if number > 1:
# check for factors
for i in range(2,number):
if (number % i) == 0:
print(f"The given number {number} ... |
f1750717c4ab4de71da28d8ddc670c1d6207005b | AP-MI-2021/lab-4-simona-sidau | /main.py | 4,397 | 3.65625 | 4 | from collections import Counter
def citire_lista():
"""
Citeste o lista de numere intregi cu n elemente
:param lst:
:return:
"""
lst=[]
n = int(input("Introduceti numarul de elemente: "))
for i in range(n):
lst.append(int(input("l[" + str(i) + "]=")))
return lst
def gaseste... |
14852b7bdd305ca89817befdbb615aea038f4120 | pjchavarria/algorithms | /interviewCake/product-of-other-numbers.py | 648 | 4.15625 | 4 | # https://www.interviewcake.com/question/product-of-other-numbers
# Greedy
# Time complexity O(n)
# Space complexity O(n)
def print_products(array):
products_of_all_ints = [1] * len(array)
product_so_far = 1
for i in xrange(len(array)):
products_of_all_ints[i] = product_so_far
product_so_f... |
1e4bb462743d8925eebd9baa80e061e11aca4acb | sohaibk321/algorithms-and-data-structures | /Algorithms/Recursion.py | 449 | 4.03125 | 4 | '''Implementing a function to get fibonacci numbers at a given index in the sequence '''
def get_fib(position):
ans = 0
if position == 0 or position == 1:
return position
else:
return get_fib(position-1) + get_fib(position-2)
'''
Fibonacci sequence: 0,1,1,2,3,5,8,13,21,34,...
Index starts at... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.