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 |
|---|---|---|---|---|---|---|
d7c8393176e4c9bb51dfec73e9c3097e39b7af8c | SuperTrampAI/Chapters | /Chapter4process.py | 1,615 | 3.671875 | 4 | # __author__ = 'lxh800109@gmail.com'
# __fileName__='Chapters Chapter4-process'
# __create_data__='2020/1/5 18:47'
# 各类语句
# if语句
x = 1#int(input("Please enter an integer:"))
if x<0:
x=0
print("Negative changed to zero")
elif x ==0:
print("Zero")
elif x == 1:
print("One")
else:
print("More")
y= 'y'... |
b811a7cd39743581b839c6331a965e641023d611 | Wuhuaxing2017/spider_notes | /day04/code/5-xpath-book.py | 1,157 | 3.53125 | 4 | from lxml import etree
books = '''
<?xml version="1.0" encoding="utf-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2008</year>
<price>30.00</price>
</book>
<book category="children" lang="zh"> ... |
39f80532a18709f22a7006949e08f5eb4c89d1ab | Tomoka64/interview_preparation | /array_interview_questions/array_pair_sum/pair_sum.py | 951 | 3.609375 | 4 | from nose.tools import assert_equal
# my answer
def my_pair_sum(list, target):
if len(list) < 2:
return
ret = set()
for i in range(len(list)):
j = i + 1
while j < len(list):
if (list[i]+ list[j] == target):
if not (list[i], list[j]) in ret:
... |
69c14bd40a360e9bdd8518ba1859776687ba84d9 | ryhanlon/legendary-invention | /labs_Fundaments/dice.py | 763 | 4.28125 | 4 | """
This is a file written by Rebecca Hanlon.
Asks for the number of die and the number of sides then prints the result.
"""
import random
def roll_dice(dice, sides):
"""
Uses uses random to roll the die
:param dice: interger
:param sides: interger
:return: print the results
"""
for i... |
6c8baaa84cad8a3c4b3f8620150182d535f43e69 | itsmonicalara/Coding | /HackerRank/30 Days of Coding/10Binary.py | 541 | 3.96875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def num_to_binary(num):
binary_list = []
current = 0
longest = 0
while int(num) > 0:
remainder = num % 2
num = num / 2
binary_list.insert(0, int(remainder))
for ele in binary_list:
if ele == 1... |
3d8b6325ffb0d38486b2402c14320c3f2c40c26b | cotncndy/leetcode-python | /learnpythonthehardway/jump-game-ii.py | 902 | 3.796875 | 4 | # Time: O(n)
# Space: O(1)
#
# Given an array of non-negative integers, you are initially positioned at the first index of the array.
#
# Each element in the array represents your maximum jump length at that position.
#
# Your goal is to reach the last index in the minimum number of jumps.
#
# For example:
# Given arr... |
961f6907971736dff5d90d037130ed85c5380eb4 | rabahbedirina/UdacityPython | /Which Prize.py | 405 | 3.609375 | 4 | import random as rd
points = rd.randrange(1, 200)
if points <= 50:
result = "Woden Rabbit"
elif points <= 150:
result = "No Prize"
elif points <= 180:
result = "Wafer thin mint"
else:
result = "Penguin"
if result == "No Prize":
print("Oh dear, no prize this time.")
else:
print("Co... |
350b6dbf7e3e993365efdaf28015ad88c70a10d8 | matthewsgerling/Python_Class_Work | /ParamAndReturn/moreFunctions/validateInputsFunctions.py | 227 | 3.609375 | 4 | def scoreInput(name, score=0, invalidmessage='Invalid test score, try again!'):
while 0 >= int(score) >= 100:
score = input(invalidmessage)
return print(name, ': ', score)
if __name__ == '__main__':
pass
|
0698c804e5c160b939aabdd3b314414da8a6878e | R-Billington/practice-projects | /games-of-chance/games.py | 3,912 | 3.796875 | 4 | import random
money = 100
#Write your game of chance functions here
#Flips coin and returns winnings or losses
def coin_flip(guess, bet):
print('Flipping a coin...\n')
one_or_two = random.randint(1, 2)
if one_or_two == 1:
coin = 'Heads'
elif one_or_two == 2:
coin = 'Tails'
... |
e41bfc8fc802efdad88cc126c592b611760c0b1e | DanielMGuedes/Exercicios_Python_Prof_Guanabara | /Aulas_Python/Python/Exercícios/Exe020-random-shuffle - Ordem aleatória.py | 630 | 3.921875 | 4 | '''import random
a1=str(input('Digite o nome numero 1: '))
a2=str(input('Digite o nome numero 2: '))
a3=str(input('Digite o nome numero 3: '))
a4=str(input('Digite o nome numero 4: '))
lista = [a1,a2,a3,a4]
random.shuffle (lista)
print('A ordem de apresentação será')
print(lista)'''
# importando apenas a função do paco... |
dcabc87d0d0bcbb43ad48e057e0b63bbb111ddb8 | sarma5233/pythonpract | /functions.py | 1,011 | 3.890625 | 4 | """def first(a):
def second(b):
return a+b
return second
adv = first(10)
print(adv(12))
"""
def Total_sum(nod,k):
s = 0
while(k > 0):
r = k % 10
s += (r**nod) # a**b is a raised to power b
k //= 10
return s # returns the calculate... |
a15d203fea9a36b76d64b0cf6fe0ff6c6c7f3b8b | ibardi/PythonCourse | /session01/helloex1.py | 1,616 | 4.5 | 4 | prnt ('Hello, Word')
# The error: "NameError: name 'prnt' is not defined" is returned, as prnt is an undefined in terms of Python, as such the program does not understand what I am asking of it.
#1a Lack of One Parenthesis
print ("Hello, World"
#ANSWER: Same as #1b, Python warns about the lack of the parentheses and ... |
e67aed685f33204e9807d983b9d886a4e5edd901 | satyagraha5/CodeJam_Python | /2015/Ominous_Omino/Ominous_Omino.py | 4,339 | 3.671875 | 4 |
'''
An N-omino is a two-dimensional shape formed by joining N unit cells fully along their edges in some way.
More formally, a 1-omino is a 1x1 unit square, and an N-omino is an (N-1)omino
with one or more of its edges joined to an adjacent 1x1 unit square. For the purpose of this problem,
we consider two N-ominoe... |
71e94121b2cca5746ad9b5caf281483c04b328a4 | Washira/HelloWorld | /PracticeOfString2.py | 470 | 3.8125 | 4 | '''
Input: รับสตริงหนึ่งบรรทัด
Process: ตรวจว่าสตริงนี้เป็น palindrome(ซึ่งคือสตริงที่กลับลำดับแล้วคือสตริงเดิม) หรือไม่
Output: ถ้าเป็น ก็แสดง Y ถ้าไม่เป็น ก็แสดง N /**
'''
a= input().strip()
if a == a[::-1]:
print("Y")
else:
print("N")
|
2fa9e5cc629eac2a0217e62bbd75277a02497ccc | zijing0926/Pythonds | /Trees and Tree Algorithms/ParseTree.py | 1,834 | 3.59375 | 4 | ##application of tree data structure
##use stack to track the parent and children of a tree
from pythonds.basic import Stack
from pythonds.trees import BinaryTree
def buildParseTree(fpexp):
####tokenize the expression to follow the rules:
fplist=fpexp.split()
pStack=Stack()
eTree=BinaryTree('')
pStack.... |
b47cf69ecc9ed790ff47fc100f8e57491e0da8e2 | chiragcj96/Algorithm-Implementation | /Delete N Nodes After M Nodes LL/solution.py | 832 | 3.8125 | 4 | # 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 deleteNodes(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype:... |
18d6c0a34fac60755612b6e9c8df072d331fbdc8 | thetonyluce/tony-python-core | /week_03/labs/11_inheritance/11_01_subclasses.py | 3,086 | 4.09375 | 4 | '''
Build on 10_03_freeform_classes from the section on Classes, Objects and
Methods.
Create subclasses of two of the existing classes. Create a subclass of
one of those so that the hierarchy is at least three levels.
Build these classes out like we did in 10_03_freeform_classes.
If you cannot think of a way to build... |
df4ebab80b84b79485dc5aa5e9f9eed9d7bcdd25 | ciastooo/ulamSpiral | /ulamSpiral.py | 1,908 | 4.25 | 4 | from PIL import Image
def is_prime(n):
if n == 2 or n == 3: return True
if n < 2 or n % 2 == 0: return False
if n < 9: return True
if n % 3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0: return False
if n%(f+2) == 0: return False
f +=6
return True
size = input("Ente... |
75df37601e8819adfd6f2ea1c8e6662ee5246007 | poiler22/brightCozmo | /qw.py | 562 | 3.921875 | 4 | import sys
import os
from tkinter import Tk, Label, Button
def restart_program():
"""Restarts the current program.
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function."""
python = sys.executable
root.destroy()
os.execl(p... |
55c56256d278bd592fbfed459e8d113c8b61fb25 | timkaing/interview-prep | /leetcode/804/unique-morse-code-words.py | 818 | 3.953125 | 4 | '''
given a list of words (list of strings)
find the # of transformations ()
convert the words into morse code
- array of strings, map them
- create full morse by iterating each char of the word (for loop)
- convert letter to matching morse value
-
[a, a, a, a, a, b, c, c, d, d]
a, b, c, ... |
155359354b2395e4c1b887ad8cb8c9312cb3f0fc | FisicaComputacionalPrimavera2018/ArraysAndVectorOperations | /vectoroperationsUpdated.py | 1,620 | 4.28125 | 4 | import math
#### FUNCTIONS
# The name of the function is "norm"
# Input: array x
# Output: the norm of x
def norm(x):
tmp = 0
for v in x:
tmp += v*v
norm_x = math.sqrt(tmp)
return norm_x
def vectorSum(x, y):
#z = x + y This doesn't work for arrays!
# First we check if the dimensions of x and y
# ... |
305c98278c1c886ba6b63d2a553e99db65c9cf39 | martin-martin/nlpython | /exercises/anagrams/anagrams.py | 1,071 | 4.5 | 4 | from itertools import permutations
def find_anagrams(word, word_list):
"""Finds all valid anagrams for a given word.
Args:
word (str): the word we want to find anagrams for
word_list (list): a list of valid words in the english language
Returns:
set: a set of valid anagrams of th... |
d1878a07d800312a3cfdc673ea03a59eea62efa4 | absoluteabutaj/Guvi | /KinderArrange.py | 304 | 3.625 | 4 | # Created on 03-Sep-2016
# @author: AbuTaj
n = int(input('Enter N'))
n2 = 2 * n
for i in range(1, n2):
print('Day', i)
for j in range(0, 1):
if(i != j):
if i + 1 > 9 or j + 1 > 9 or i > 9 or j > 9:
i = 0
j = 0
print(i, i + 1, j, j + 1)
|
4300f9feaa302bb003027151d0c92b712a182964 | vjstark/Python_Basics | /python_mini_projects/fileprogs/fileprog1.py | 1,656 | 3.890625 | 4 | import os
while True:
try:
op= int(input('1:Create File, 2:Delete File, 3:Read File, 4:Write File, 5:Exit : '))
#Create File
if op==1:
fn= input('Enter file name to be created: ')
if(not os.path.exists(fn)):
f = open(fn,'a')
print('File created.')
else:
print('File already exists.')
#Delet... |
0ad3ad3891dee0a91f99e381ac012ddda111d385 | jimleroux/enphaseai | /enphaseAI/problem1.py | 2,424 | 4.28125 | 4 | from typing import Tuple
def find_lines_from_points(
p0: Tuple[float, float],
p1: Tuple[float, float]
) -> Tuple[float, float]:
"""
Function calculating the line passing throught a pair of points.
Args:
p1 (Tuple[float, float]): First point.
p2 (Tuple[float, float]): S... |
07b711a53bbd3e12e98bb91f858393ee283f2751 | Sposigor/Caminho_do_Python | /exercicios_curso_em_video/Exercicio 40.py | 160 | 3.890625 | 4 | n1=float(input("nota 1"))
n2=float(input("nota 2"))
m=(n1+n2)/2
if m<5:
print("REPROVADO")
elif m>=7:
print("APROVADO")
else:
print("RECUPERAÇÃO") |
407837d46870d714b93e269d66beada90c5ad1b8 | jt-lai/python-100-day-practice | /Day 6/Day_6_Practice_1.py | 447 | 3.71875 | 4 | """
练习1:实现计算求最大公约数和最小公倍数的函数。
Ver: 0.1
Author: JT
Date: 02/08/2020
"""
def gcd(a, b):
# find the greatest common devisor (gcd)
for i in range(1, a + 1):
if a % i == 0 and b % i == 0:
gcd = i
return gcd
def lcm(a, b):
# find the least common multiple (lcm)
lcm = 0
while True... |
5ce2fdca9d108932784bef12cf85548447f424da | SadManFahIm/HackerRank-Preparation-Kit | /Minimum Time Required.py | 561 | 3.640625 | 4 | def minTime(machines, goal):
# make a modest guess of what the days may be, and use it as a starting point
efficiency = [1.0/x for x in machines]
lower_bound = int(goal / sum(efficiency)) - 1
upper_bound = lower_bound + max(machines) + 1
while lower_bound < upper_bound -1:
days ... |
77dc60a6a27ff9d341ec31633df651b2a914c0ff | vecchp/CrackingTheCodingInterview | /chapter2/question2_5.py | 428 | 3.859375 | 4 |
# Question 2.5
# Time O(n)
# Space O(1)
def sum_small_to_big(list_1: list, list_2: list):
order = 1
total = 0
for a, b in zip(list_1, list_2):
total += (a + b) * order
order *= 10
return total
# Time O(n)
# Spac O(1)
def sum_big_to_small(list_1: list, list_2: list):
total = 0
... |
9aca81a214b4e5c218c50db00cdea312755277fb | wcsBurneyCoder/lintCode-python | /A+B问题.py | 404 | 3.640625 | 4 | #coding:utf-8
'''
A + B 问题
给出两个整数 a 和 b, 求他们的和,不使用+号
'''
def aplusb(a, b):
# write your code here
INT_RANGE = 0xFFFFFFFF
while b != 0:
a, b = a ^ b, (a & b) << 1
a &= INT_RANGE
return a if a >> 31 <= 0 else a ^ ~INT_RANGE
if __name__ == '__main__':
print (aplusb(5, 6))
print (aplusb(... |
51b16ec6a02a7e0570448aeeb83ad30c49b1a6c1 | sushovan86/PythonProjects | /SplitJoinSpreadsheet/main.py | 1,197 | 3.8125 | 4 | import os
import sys
from pandas import read_excel
from process_split import *
def validate_column(df, column):
if column not in df.columns:
print("ERROR!!! Column {} is not available in the spreadsheet. "
"Please provide correct column name"
.format(column))
exit(-1)... |
b2c1bcd125b9e98751182981c8c0a421906deaff | jeff283/flask-login-app | /databs.py | 240 | 3.796875 | 4 | import sqlite3
def store():
global conn
global c
conn = sqlite3.connect("database.db")
c = conn.cursor()
#creating a table
c.execute("""CREATE TABLE IF NOT EXISTS login (
username TEXT,
password TEXT
)
""")
store() |
3c018a2cbc3498fc8942b889e37b265751975c89 | ArunPrasad017/python-play | /coding-exercise/Day76-SortArrayByParity.py | 695 | 3.953125 | 4 | """
905. Sort Array By Parity
Given an array A of non-negative integers, return an array consisting of all the even elements of A,
followed by all the odd elements of A.
You may return any answer array that satisfies this condition
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] wo... |
ff71cc7cf701c685073879cc644a51cea3fb0dff | doitfool/leetcode | /ReverseLinked List.py | 637 | 3.75 | 4 | # coding: utf-8
"""
Reverse a singly linked list.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
... |
91cfa0dd749027b89a99e73d72a70165af3f614b | PRKKILLER/Algorithm_Practice | /LeetCode/0067-Add binary/main.py | 1,255 | 3.953125 | 4 | """
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
"""
class Solution:
# bit-by-bit computation
# space complexity: O(max(M, N))
def addBinary(self, a: str, b: str) -> s... |
66170dfbe9761acc0424b763dcb6390d0ecf667f | mattvenn/python-workshop | /demos/turtle/fill.py | 264 | 3.5 | 4 | #import all from turtle library
from turtle import *
pencolor('red')
fillcolor( 'yellow')
speed(5)
#start a fill
begin_fill()
loops = 0
while loops < 20:
forward(200)
left(170)
loops = loops + 1
#end the fill
end_fill()
done()
|
299f10acfd68ad45221a2d1f84b996a42f96fc54 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/sum-of-matrices-reverse-rows.py | 1,600 | 4 | 4 | Sum of Matrices - Reverse Rows
The program must accept two integer matrices M1 and M2 are of equal size RxC as the input. In M1 and M2, The program must reverse the integers in the odd positions of the odd rows and the integers in the even positions of the even rows. Then the program must print the sum of M1 and M2 as... |
591862c704f531f9984e76d6c76c69ae631aeecb | rec/test | /python/calc.py | 1,010 | 4 | 4 | OPS = {
'add': (lambda x, y: x + y, '+'),
'sub': (lambda x, y: x - y, '-'),
'mul': (lambda x, y: x * y, '*'),
'div': (lambda x, y: x + y, '/'),
'quit': (None, 'quit'),
}
def main():
print('Welcome to attocalc')
while True:
op, symbol = _get_op()
if symbol == 'quit':
... |
13cdaddbaa0db76a4d31b9e2109948ac8654a791 | vckelly/Thinkful | /fizzbuzz.py | 322 | 3.828125 | 4 | #!/usr/bin/env python
fizz = range(1, 101)
buzz = ""
print "Fizz buzz counting up to 100"
for i in fizz:
if (i % 3) == 0:
buzz += "fizz"
if (i % 5) == 0:
buzz += "buzz"
elif not (i % 5) == 0 and not (i % 3) == 0:
buzz += str(i)
buzz += ", "
print buzz[:-2]... |
6057f2bbd745f706a82e5c1bd48a645497c8520c | Oyelowo/GEO-PYTHON-2017 | /ass3/untitled0.py | 1,496 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 22 08:54:32 2017
@author: oyeda
"""
word = 'lowo'
print word[0]
print word[1]
print word[2]
print word[3]
word2 = "mayor"
for char in word2: print (char)
length = 10
for letter in 'geomatics': length = length + 1
print length
for letter in 'dayom': print (letter)
pri... |
e5b8d8fb1bc6e4fadfc93ef81cd2ffa40790c83c | Amit32624/Python | /Python_codes/DemoSet.py | 537 | 4.03125 | 4 | '''
Created on 12-Jun-2017
@author: mohan.chinnaiah
'''
set1={1,2,3,4,5,6,7}
set2={4,5,6,7,8,9,10}
print(set1);
print(set2);
print(set1.union(set2));
print(set1.intersection(set2));
print(set1.difference(set2));
print(set2.difference(set1));
engineers = {'John', 'Jane', 'Jack', 'Janice'}
programmers = {'Jack'... |
45f3db7264fe2fef85daab923d7b506235df533f | fonyango/MayOfCode | /day_08.py | 793 | 4.3125 | 4 | # --- DAY EIGHT ---
'''
1. Write a Python program that can take a positive integer greater than 2 as
input and write out the number of times one must repeatedly divide this
number by 2 before getting a value less than 2.
'''
def divide_by_two(x):
'''
Determines the number of times one must repeatedly divide ... |
6edf0f3ae6369659f8671947753628107eb50428 | wxzoro1/MyPractise | /python/liaoscode/datetime.py | 1,317 | 3.53125 | 4 | from datetime import datetime,timedelta,timezone
now = datetime.now()
print(now)
print(type(now))
dt = datetime(2015,4,19,12,11,11)
print(dt)
#timestamp
dt = datetime(2018,2,21,23,11,22)
a = dt.timestamp()
print(a)
print(datetime.fromtimestamp(a))#本地时间
print(datetime.utcfromtimestamp(a))#UTC时间
#str转datetime
cday = dat... |
1f14a9d4a7c20a45a91538116da25c8823de0035 | daxm/duplicate_letter_word_counter | /main.py | 570 | 3.78125 | 4 | import nltk
def main():
with_duplicates = 0
without_duplicates = 0
for word in nltk.corpus.words.words():
if len(word) == len(set(word)):
without_duplicates += 1
else:
with_duplicates += 1
total = with_duplicates + without_duplicates
print(f"Total words: {t... |
4bad152502d49dd3375f14aa0913e02ebd1defac | pmana/breakout | /graphics.py | 1,263 | 3.59375 | 4 | import curses
from math import floor
class CursesGraphics:
def __init__(self, screen, max_x, max_y):
self.screen, self.max_x, self.max_y = screen, max_x, max_y
def begin_frame(self):
for row in range(0, self.max_y):
self.draw(0, row, ' ' * self.max_x)
def end_frame(self):
... |
6e11d8a5a05ad5cb94461ada917d27189e7f79d5 | ianzapolsky/practice | /misc/guess/game.py | 730 | 4.03125 | 4 | # game.py
# A simple number guessing game
# By Ian Zapolsky (12/08/13)
import random
def select_random_number():
random_integer = random.randint(1, 100);
return random_integer
def interpret_guess(random_integer):
print 'please enter a guess: '
guess = int(raw_input())
if random_integer > guess:
... |
5f575c64f51fe99f4ecb56c1e04ab72715284f2f | alansong95/leetcode | /169_majority_element.py | 948 | 3.53125 | 4 | # hash table
# time: O(n)
# space: O(n)
# class Solution(object):
# def majorityElement(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# ht = {}
# for num in nums:
# if num not in ht:
# ht[num] = 1
# else:
# ... |
1dff45d9904e92bc5396644f1ea960b29836ab0b | Omni-HuB/CO_M21_Assignment-main | /SimpleSimulator/registerFile.py | 959 | 3.65625 | 4 | #!/usr/bin/python
#Function to convert decimal to 8bit binary
def dto16b(decimal):
bnr = bin(decimal).replace('0b','')
x = bnr[::-1] #this reverses an array
while len(x) < 16:
x += '0'
return x[::-1]
class registerFile:
registers = [0, 0, 0, 0, 0, 0, 0, 0]
def dump(s... |
997ec859787340d6914a8d59efe0963ddc7d4dc9 | gabrieleliasdev/python-mentoring | /ex12.py | 920 | 4.09375 | 4 | def bot_cafe():
print("Welcome Cafeteria")
tipo = tipo_do_cafe()
print(tipo)
tamanho = tamanho_do_cafe()
print(f'Tudo bem, o {tipo} {tamanho}')
def tipo_do_cafe():
res = input("Qual o tipo do café que você deseja?\n[a] Expresso \n[b] Mocha \n[c] Capuccino\n")
if res == 'a':
return 'Ex... |
ca8ae7f452dd9709a247f13aea839f30d7465156 | bjherger/algorithms_and_data_structures | /algorithms/stack/reference_implementation.py | 3,978 | 4 | 4 | import logging
class Stack(object):
"""
A Stack implementation, with the following attributes
- Array implementation
- First in, last out
- New elements added to end of list
- Elements removed from end of list
API roughly based on https://docs.oracle.com/javase/7/docs/api/java/util/Que... |
aecfad6539042c2265409c156c5f82a06e6f3be8 | adstr123/ds-a-in-python-goodrich | /chapter-1/r2_is_even.py | 402 | 4.34375 | 4 | def is_even(k):
"""
Takes an integer and returns True if it is even
:param int k: the number to evaluate
:return boolean: based on condition evaluation
"""
# bitwise &
# if last bit is 1, number is odd
if k & 1:
return False
else:
return True
"""
Time: O(1)
- Always one calculation that take... |
052983dac6f8688c1f76b394dd8406adbdbd721f | BO3K404/Hash404 | /sha256.py | 409 | 3.53125 | 4 | #!/usr/bin/env python
#_*_ coding: utf8 _*_
import hashlib
def main():
hashpass = str(raw_input("HASH: "))
passfile = open("dictionary.txt",'r')
for p in passfile.readlines():
n = p.strip("\n")
n = hashlib.sha256(n).hexdigest()
if n == hashpass:
print("Password: {} ... |
3e0086aaf41e5edfe750235ed0ca5912a7aa20f8 | ZahraRoushan/MachineLearning1 | /Algorithm_Section/dynamic_programming/binomial_coefficient.py | 318 | 3.53125 | 4 | def binomial(n, k, dp={}):
assert (n >= 0 and k >= 0), "lotfan riazi yad begir"
if k == 0 or n == k:
return 1
if (n, k) not in dp:
result = binomial(n-1, k) + binomial(n-1, k-1)
dp[(n, k)] = result
return result
else:
return dp[(n, k)]
print(binomial(5, 4))
|
6d75efdbb0e4c38c323f47a3efb491ed64ce12ee | htrahddis-hub/DSA-Together-HacktoberFest | /strings/Easy/hash_table.py | 828 | 4.09375 | 4 | # Used Hashing concept in Finding Duplicates in an array
# Hastables are basically Dictionaries in Python
# Below is the implementation of HashTables (Referred Code Basics YT channel)
class HashTable:
def __init__(self):
self.MAX = 100
self.arr = [None for i in range(self.MAX)]
def... |
7f4dd5696527e529307d5d69d57459075827e43d | wjdgh7587/programmingstudy | /Python_Ruby/Container_Loop/3.py | 227 | 3.796875 | 4 | input_id = input("Puy your id\n")
members = ['naver', 'google', 'daum']
for member in members:
if member == input_id:
print('Hello!, '+member)
import sys #system out
sys.exit()
print('Who are you?')
|
29464973876d22a5cf2a8c717055744651c1deda | hugo-paiva/curso_Python_em_Video | /Exercícios Resolvidos/aula16.py | 247 | 3.921875 | 4 | '''lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim')
for contador in range(0, len(lanche)):
print(f'Eu vou comer {lanche[contador]}!')
print('Nossa comi pra caramba!')'''
a = (2, 5, 4)
b = (5, 8, 1, 2)
c = b + a
print(c)
print(c.index(5, 1)) |
f9cf8c5cc0eed8209b5a13b051b1760e2de04196 | smnbnt/MIT6.00.1x | /Quiz/Problem4.py | 409 | 3.890625 | 4 | def myLogIter(x, b):
'''
x: a positive integer
b: a positive integer; b >= 2
returns: log_b(x), or, the logarithm of x relative to a base b.
'''
power = 0
log_b = 0
while 1:
log_b = b**power
if log_b == x:
break
elif log_b > x:
po... |
2d55ff969783be59ba474d5e2a28b4756ff14201 | mayankgb2/Python-Programs | /fortunecookiegame.py | 816 | 3.625 | 4 | #https://www.facebook.com/100028679802914/posts/449717249327598/
# Subscribed by Nikita Desale
import random
print("Your Good Name Please:)__")
n=input()
print(n+" Your fortune cookie says")
fortune = random.randint(1,8)
if fortune == 1:
print("Good things happen just wait and have Patience")
elif fortune == 2:
... |
38d9ebd1469ba9106d4907c5002bac12d358ca7f | AchimGoral/DI_Bootcamp | /DI_Bootcamp/Week_5/Day_2/exercise_3_from_1_dogs.py | 1,056 | 3.546875 | 4 | import exercise_1_dogs as ex
import random as rd
class PetDog(ex.Dog):
def __init__(self, name, age, weight):
super().__init__(name, age, weight)
self.trained = False
def train(self):
self.bark()
return self.trained = True
def play(self, *dog_names):
dogs = ', '... |
0ff5a476c7d1249e26904debb90dc92126988936 | waltercardona/taller_Carlos_Python | /Taller_1.py | 4,394 | 4.21875 | 4 |
#TALLER UNO
# PUNTO/1
# Dados los valores ingresados por el usuario
# (base, altura) mostar en pantalla el area de un triangula
"""base=int(input("ingrese el base del triangulo\n"))
altura=int(input("ingrese la altura del triangulo\n"))
area = base * ... |
75d0c24092b9a9ea8d3d5355026a5210186a7da5 | nasa/bingo | /bingo/variation/add_random_individuals.py | 2,465 | 3.90625 | 4 | """variation that adds random individual(s)
This module wraps a variation in order to supply random individual(s) to the
offspring after the variation is carried out.
"""
import numpy as np
from .variation import Variation
class AddRandomIndividuals(Variation):
"""A variation object that takes in an implementat... |
8b7086f5616dd49627e8b548740fdf0ac6d909f4 | kdheejb7/baekjoon-Algorithm | /백준/4344_평균은넘겠지.py | 231 | 3.671875 | 4 | for _ in range(int(input())):
scoreList = list(map(int,input().split()))
average = sum(scoreList[1:])/scoreList[0]
print("%0.3f"%round(len([i for i in scoreList[1:] if i > average])/scoreList[0]*100, 3),'%',sep='')
|
a11062d58ce22784e3bf291f30eb2a575cb9e5a7 | apollopower/interview-prep | /python/python_questions/reverse_string_in_place.py | 278 | 3.9375 | 4 | def reverse_string_in_place(str_list):
left = 0
right = len(str_list) - 1
while left < right:
str_list[left], str_list[right] = str_list[right], str_list[left]
left += 1
right -= 1
return str_list
print(reverse_string_in_place(['j','o','n','a','s'])) |
142e95c36e206295330edb8c3e321394ce59f8cf | balupabbi/Practice | /Apple/DataStuff/NestedToFlatten.py | 1,476 | 4.03125 | 4 | """
https://www.geeksforgeeks.org/python-convert-nested-dictionary-into-flattened-dictionary/
Given a nested dictionary, the task is to convert this dictionary into a flattened
dictionary where the key is separated by ‘_’ in case of the nested key to be started.
"""
def helper(nd,out):
for k,v in nd.items():
... |
26d3e8f6cc5171b6ba04955243cdaedb82477d20 | guotian001/DataStructure-python- | /chapt4_tree_second/BinarySearchTree.py | 3,328 | 4.15625 | 4 | # encoding:utf-8
'''
二叉搜索树,BST
左子树都小于结点的值,右子树都大于结点的值
'''
class BinTreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
# 递归查找
def find_recursion(tree, X):
if tree==None:
return None
if X > tree.data:
return... |
541a528536eb20c8b2d638a4196643c6a65094d2 | ShathyaPeriaswamy/Python-Programming | /Beginner Level/set1g.py | 121 | 3.71875 | 4 | i=raw_input()
t=int(i)
if(t>0):
for n in range (t):
print 'Hello'
elif(t==0):
print " "
else:
print "invalid input"
|
5889c678834bd2f7465fda691d1c1d27739e4c9e | girscr/Pygame_Scene | /functions_practice.py | 697 | 4.40625 | 4 | import math
def distance (x1, y1, x2, y2):
'''calculates the distance between the
two points given'''
dist = math.sqrt((x1-x2)**2 + (y1-y2)**2)
return dist
def in_circle(center_x, center_y, radius, other_x, other_y):
'''determines whether a given point lies
within the circle'''
#get th... |
79aa61b5c6701d3d07db2f38837f10bf493dded2 | giuliasteck/MC102 | /lab05/lab05.py | 1,060 | 3.796875 | 4 | """
Nome: Giulia Steck
RA: 173458
"""
lista =[]
N = int(input())
for i in range(N):
entrada = input()
lista.append(entrada)
hashtag = 0
emoticon = 0
for i in (lista):
a = i.isdigit()
b = i.isalpha()
#printar números positivos e palavras
if a == True:
print(i)
elif b == True:
... |
20a132c2d9f613633de5b081c29985446b507bd2 | JamieCass/pynotes | /card_test.py | 4,266 | 4.28125 | 4 | import unittest
from cards_final import Card, Deck
class CardTests(unittest.TestCase):
def setUp(self):
self.card = Card('A', 'Spades')
def test_init(self):
"""Each card should have a suit and a value"""
self.assertEqual(self.card.suit, 'Spades')
self.assertEqual(self.card.va... |
c16da698b0c305d54136236a706b6211c699bf5c | Krishnaanurag01/PythonPRACTICE | /bubbleSORT.py | 529 | 3.71875 | 4 | l=[int(x) for x in input().split()]
# for i in range(len(data)):
# for j in range(len(data)-1):
# if data[j+1]<data[j]:
# data[j+1],data[j]=data[j],data[j+1]
# print(data)
def swap(a,b):
a,b=b,a
return a,b
# ans=[[swap(data[j+1],data[j]) for j in range(len(data)-1) if data[j+1]<data[... |
c4c4cc5bea0b7687d2388b77dcb160aeaa98426f | rksaxena/leetcode_solutions | /longest_univalue_path.py | 1,361 | 4.125 | 4 |
__author__ = Rohit Kamal Saxena
__email__ = rohit_kamal2003@yahoo.com
"""
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
Note: The length of path between two nodes is represented by the number of edges between ... |
399c075fac99fdd022b771679d55b633ddb8feb2 | abisha22/S1-A-Abisha-Accamma-vinod | /Programming Lab/27-01-21/prgm7abc.py | 982 | 3.96875 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> list1=[12,3,4,56,7,8,9,19,34,87]
>>> list2=[10,4,67,89,4,77,29,5,7,8]
>>> len1=len(list1)
>>> len2=len(list2)
>>> if len1==len2:
print('Both... |
63ad1db21c2012e1a76ea8470a50a4ed10ab1f96 | Mud-Phud/my-python-scripts | /DataCamp tutorial on matplotlib/datacamp-subplot matplotlib.py | 567 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 23:59:03 2020
@author: robert
DataCamp using subplot()
"""
import numpy as np
import matplotlib.pyplot as plt
# generate some data...
t = np.array(range(14))
temperature = t*6/14+27+np.random.normal(0,1,14) # linear growth in time plus random
... |
b3092e6bc3f609eaf90f19a2023dd6975a5f9346 | Robostorm/Aquabot-Bluetooth-Receiver | /pygameController.py | 3,956 | 3.515625 | 4 | import pygame
import config
pygame.init()
# Initialize the joysticks.
pygame.joystick.init()
class struct: pass
inputs = struct()
# -------- Main Program Loop -----------
def getInputs():
#
# EVENT PROCESSING STEP
#
# Possible joystick actions: JOYAXISMOTION, JOYBALLMOTION, JOYBUTTONDOWN,
# JOYB... |
96d69cfa49ac04e275a53d72bf651bc305f34dba | SergeyKodochigov/Python | /1 lab/12.py | 107 | 3.609375 | 4 | a = (input('Введите слово'))
g = a[::-1]
if a == g:
print("yes")
else:
print("no")
|
c34ea3d52e81320078ddd0b6874600533cc1837b | loucerac/pybel | /src/pybel/struct/filters/node_filters.py | 3,266 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""Filter functions for nodes in BEL graphs.
A node predicate is a function that takes two arguments: a :class:`BELGraph` and a node. It returns a boolean
representing whether the node passed the given test.
This module contains a set of default functions for filtering lists of nodes and buil... |
e6ae882498cfc5094d964d1ee2a06cf270d49012 | rakitaj/daily-programmer | /hackerrank/problemsolving.py | 2,790 | 3.734375 | 4 | from typing import Sequence, List, Tuple
import re
import itertools
import sys
import time
def simple_sum_array(count: int, numbers: Sequence[int]) -> int:
return sum(numbers)
def compare_the_triplets(alice: Tuple[int, int, int], bob: Tuple[int, int, int]) -> Tuple[int, int]:
alice_score = 0
bob_score = 0... |
77cbca8a0a18712a896957221d605529d386909a | rmgard/py_deep_dive_2 | /2.6_sequence_types.py | 1,842 | 4.34375 | 4 | l = [1, 2, 3]
t = (1, 2, 3)
s = 'python'
""" the above are all sequence types which are indexable and iterable.
We can reference elements inside the sequence by their indeces
l[0] = 1
t[1] = 2
s[2] = 't'
"""
""" We can also loop or iterate over them:
"""
for c in s:
print (c)
##############################... |
f023097fe36838da339a4272b1872808bdb41e07 | acep-uaf/MiGRIDS | /MiGRIDS/Model/Operational/getIntListIndex.py | 2,522 | 3.8125 | 4 | # Project: GBS Tool
# Author: Jeremy VanderMeer, jbvandermeer@alaska.edu
# Date: March 1, 2018
# License: MIT License (see LICENSE file of this package for more information)
# get the index of an interger value in a list of continuous sequential intergers
# using integer list indexing is much faster than np.searchsort... |
33e2592ffe14019a73116155e76b05db79ec9495 | Ferveloper/python-exercises | /KC_EJ25.py | 486 | 3.75 | 4 | #-*- coding: utf-8 -*
import random
random = random.randint(1, 100)
for i in range(1, 6):
guess = input('Escribe un número: ')
if (guess != random and i != 5):
print('Intenta con un número %s (te quedan %s oportunidad%s)' %('menor' if guess > random else 'mayor', 5 - i, 'es' if i != 4 else ''))
e... |
2be00c4384f631f71afd881d78e0478dd55c3609 | sheetaljantikar/python-codes | /hash_new.py | 1,512 | 3.546875 | 4 | class hashmap():
def __init__(self,size):
self.size=size
self.map=[None]*size
def get_hash(self,key):
hash=0
for char in str(key):
hash+=ord(char)
return hash%self.size
def add(self,key,value):
hash_value=self.get_hash(key)
l... |
7d388b1a977ea1a5681d6d3f6d520ae67eff55d8 | calciumhs/calciumAAA | /yufang/pythonnn/matrix.py | 544 | 3.578125 | 4 | a=[]
b=[]
c=[[0,0,0],[0,0,0],[0,0,0]]
for j in range(3):
a1=[eval(i) for i in input().split()]
a.append(a1)
for j in range(3):
b1=[eval(i) for i in input().split()]
b.append(b1)
def matrixMultiPly(a, b):
for i in range(3):
c[i][0]=a[i][0]*b[0][0]+a[i][1]*b[1][0]+a[i][2]*... |
debd2e4d31660576bf3b0ae62f9483f1d6367e11 | huangqiank/Algorithm | /leetcode/other/convertitle.py | 700 | 3.609375 | 4 | ##168. Excel表列名称
#给定一个正整数,返回它在 Excel 表中相对应的列名称。
#例如,
# 1 -> A
# 2 -> B
# 3 -> C
# ...
# 26 -> Z
# 27 -> AA
# 28 -> AB
# ...
#示例 1:
#输入: 1
#输出: "A"
##只需要注意1 - A而不是0 - A
##①让除数减一,那么余数自然就少一,原来余 1 的变成余 0,以此类推(详细见下表)。
#核心代码 `let remain = (n - 1) % 26;`
class Solution123411:
def convertToTitle(sel... |
495245b874d5927b7d98fb730bbe391d2fb0909f | Laurensvaldez/PythonCrashCourse | /CH4: working with lists/try_it_yourself_ch4.py | 509 | 3.953125 | 4 | print("4-1 Pizzas")
pizza_list = ["Pepperoni", "Margaritha", "BBQ"]
print (pizza_list)
print("______________________________")
for pizza in pizza_list:
print("I like " + pizza + " pizza!")
print("I really love pizza!")
print("______________________________")
print("4-2 Animals")
animal_list = ["dog", "cat",... |
6487c7c42e1fae422faa19598d7e6f06885832a5 | dangliu/TARI | /pythonscripts/vcf_overlap.py | 1,387 | 3.5 | 4 | #!/usr/bin/python3
usage = """
This script is for comparing the overlapping of two vcf.
It was written by Dang Liu. Last updated: May 29 2018.
usage:
python3 vcf_overlap.py vcf1 vcf2
"""
# modules here
import sys, re
# if input number is incorrect, print the usage
if len(sys.argv) < 3:
print(usage)
sys.exit()
... |
de2ddd34c578de105c909d6ddc66693a12737ca2 | wslxko/LeetCode | /tencentSelect/number18.py | 749 | 4.09375 | 4 | '''
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution:
def mergeTwoLists(self, l1, l2):
newl1 = l1.split('->')
newl2 = l2.sp... |
5da21450988eafbba0f7be2d7199973f70413b07 | AndrewErmakov/PythonTrainingBasics | /DataStructuresAndAlgorithms/SearchAndSort/Sort/Count&CountingSort&Digital(Bitwise)Sorting/anagrams.py | 1,094 | 3.8125 | 4 | first_word = input()
second_word = input()
def counting_sort(word: str):
count_list = [0] * 36
sorted_sequence = []
for symbol in word:
if 'a' <= symbol <= 'z':
count_list[ord(symbol) - 87] += 1
if symbol.isdigit():
count_list[int(symbol)] += 1
for i in range... |
3f1d83ed56275c24c3e0743f9ee73be8e2d1a0d0 | utabe/aoc | /2019/7/part2ampinput.py | 7,546 | 3.65625 | 4 | # --- Part Two ---
# It's no good - in this configuration, the amplifiers can't generate a large enough output signal to produce the thrust you'll need. The Elves quickly talk you through rewiring the amplifiers into a feedback loop:
#
# O-------O O-------O O-------O O-------O O-------O
# 0 -+->| Amp A |->| A... |
f34fdda4bc7db8a73bf636beaf0bac696ca7ecdc | scabbycoral/tactile_object_recognition | /code/test_functions.py | 5,663 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import math
"""
This file contains functions to be used as part of the robotic classifier project.
"""
def get_maximum_consecutive_changes(array):
"""
A function which identifies the maximum number of consecutive changes between frames from the tactile data
... |
98b39694fa9c92aaa50befbed18d8601e1dc86cf | codewithgauri/HacktoberFest | /python/plus.py | 138 | 3.875 | 4 | first = input("enter your first number :")
second = input("enter your second number :")
print("your answer is ", int(first) + int(second)) |
d30258e975f98b422c4afa9ad6aea0e6bbb461ba | monakhandat/Sentimental-Analysis-on-Presidential-Election-Twitter-Data | /src/Method3_SentimentAnalysis.py | 10,167 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### Reading the json file
# In[1]:
import json
tweets = []
for line in open('tweets.json', 'r'):
tweets.append(json.loads(line))
# ### Checking the data
# In[13]:
tweets[0]
# ### Creating Dataframe by extracting the features that we need
# In[3]:
import pandas a... |
b9767690d8dd129318dc37507a98261a3840ce74 | Naster20/t05_Ruiz.Sanchez | /Verificadores.Ruiz.Sanchez.py | 16,244 | 3.578125 | 4 | #EJERCICIO 1
producto="Leche"
type_producto=type(producto)
producto_es_str=isinstance(producto,str)
producto_es_int=isinstance(producto,int)
print("Variable Producto es :",type_producto)
print("Variable es str :",producto_es_str)
print("Variable es int :",producto_es_int)
#Fin if
#EJERCICIO 2
cliente="Naster"
type_cli... |
735b2f4409de2b85052d4d11846e22be0b2009d3 | hectorlopezmonroy/HackerRank | /Programming Languages/Python/Strings/Capitalize!/Solution.py | 956 | 4.3125 | 4 | # -*- coding: utf-8 -*-
# You are asked to ensure that the first and last names of people begin with a
# capital letter in their passports. For example, 'alison heck' should be
# capitalized correctly as 'Alison Heck'.
#
# alison heck -> Alison Heck
#
# Given a full name, your task is to capitalize the name appropri... |
9cb0ba028e64cbe14a213c4481cb6a09be2a9bef | AniruddhaSadhukhan/Dynamic-Programming | /C_Longest Common Subsequence/11_Min number of insertion to make the string palindrome.py | 1,216 | 3.6875 | 4 | # Given a string str, the task is to find the minimum number of characters
# to be inserted to convert it to palindrome.
# ab: Number of insertions required is 1 i.e. bab
# aa: Number of insertions required is 0 i.e. aa
# abcd: Number of insertions required is 3 i.e. dcbabcd
# abcda: Number of insertions required is 2... |
c408e0d09d777fe723d4c9c547c4db56022ac4a3 | SidPatra/ProgrammingPractice | /ttt_n_dimension_starter.py | 2,147 | 4.03125 | 4 | # YOUR NAME:
# YOUR PSU EMAIL ADDRESS:
# END OF HEADER INFORMATION
# -----------------------------------------------
# PLACE ANY NEEDED IMPORT STATEMENTS HERE:
# END OF IMPORT STATEMENTS
# -----------------------------------------------
# DEFINE YOUR FUNCTIONS (NOT INCLUDING MAIN) IN THIS SECTION
# YOU WILL NEED MOST O... |
3c455c61a1f25cf7238ca6346b7be1197014f68b | Harshupatil/PythonPrograms- | /CommonFactors.py | 439 | 3.71875 | 4 | #******************************************************************************
#Common factors of two numbers, this are the numbers which divide both input
#numbers.
#*******************************************************************************/
count=0
a = int(input("Enter first number: "))
b = int(input("Enter s... |
708147aba27d5e8e12d15384d291c60fd5ea33fe | retropleinad/TurfCutter | /map.py | 333 | 3.5625 | 4 | import numpy as np
"""
Adjacency matrix:
1.) VxV dimensions, where V is the number of vertices in a graph
2.) A 1 indicates that there is an edge between the indices represented by the dimensions
"""
adj_matrix = np.array([
[0, 1, 1, 0],
[1, 0, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 0]
])
prin... |
6e97734bac2816bed719f2be857d4fe9b8efcbb3 | yongxuUSTC/challenges | /heapq-library.py | 303 | 3.828125 | 4 | #Introduction to heapq library
import heapq
input = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print ("input >>>", input)
#Min Heap (DEFAULT)
heapq.heapify(input)
print ("input after min heap >>>", input)
#Max Heap
heapq._heapify_max(input)
print ("input after max heap >>>", input)
|
5fa5c9fdb51ce0b2933af50289b884c0e570f124 | pitzcritter/CodingDojo--Python | /6 Find Characters.py | 219 | 3.796875 | 4 | # input
word_list = ['hello','world','my','name','is','Anna']
char = 'o'
# output
# new_list = ['hello','world']
newArr = []
for item in word_list:
if item.find(char) != -1:
newArr.append(item)
print newArr |
0e8c10cccc7ada5c337db5155b2223e443604316 | abdullahalmamun0/Python_Full_Course | /09_list.py | 1,301 | 3.796875 | 4 | # =============================================================================
# List
# =============================================================================
a = ["Doreamon",'Shinchan',"Tom and Jerry",
1,3,4,'Shinchan',1.4]
b,c = ["Doreamon","dorejsdhfamon","Shinchan",
'shhdsvssinchan'],[1,6,3,8,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.