blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8801ec89583f5434792a224f4f10762fca1c0442 | MKAkin/Random-Number | /Final.py | 5,440 | 3.578125 | 4 | import random
def gen_digit():
digit = random.randint(0,9)
#print(digit)
return digit
#gen_digit()
def gen_numlist():
gen_num=[]
for i in range(4):
digit = gen_digit()
gen_num.append(digit)
return gen_num
#print(gen_numlist())
def TF(seq1):
check = Fal... |
9f92a1be81a1a0cc7a5b089059248d2a328cf781 | bchiud/cs61a | /tree.py | 1,024 | 3.703125 | 4 | class Tree:
def __init__(self, label, branches=[]):
for c in branches:
assert isinstance(c, Tree)
self.label = label
self.branches = list(branches)
def __repr__(self):
if self.branches:
branches_str = ', ' + repr(self.branches)
else:
... |
2e1c43c81ee231dba1876fc287bba2e4b555abcb | jichunwei/MyGitHub-1 | /PythonTest/Python_100/P27.py | 344 | 3.84375 | 4 | #coding:utf-8
'''
题目:利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来
'''
def output(N,l):
if l == 0:
return
else:
print N[l-1]
return output(N,l-1)
if __name__ == "__main__":
s = raw_input("Please enter a string: ")
lth = len(s)
output(s,lth) |
e2407f25e23d8562116d3deab8a009cd4bff21da | brianwoo/python-for-informatics | /exercise5/compute.py | 409 | 3.9375 | 4 | total = 0
count = 0
while True:
try:
input = raw_input("Enter a number:")
if input == "done":
print "Total: ", total
print "Count: ", count
# in case of div by 0
if count > 0:
print "Average: ", float(total) / float(count)
else:
print "Average: ", float(total)
break
number = float(... |
fd04b4581adc2c8f5d04369cb10aa696364a1066 | brlrb/Algorithm-Analysis | /Python/MoveZeros.py | 481 | 3.640625 | 4 | # Problem 283: Move Zeroes // LeetCode.com
class Solution:
nums = [1,0,3,3,0,9,0,6]
def moveZeroes(self, nums):
"""
Do not return anything, modify nums in-place instead.
"""
counter = 0
counter2 = 0
print(nums)
for counter in range(len... |
07cb320c1cb52034a1962797a863db67424e30d0 | Baidaly/datacamp-samples | /14 - Data manipulation with Pandas/chapter 2 - Aggregating Data/7 - What percent of sales occurred at each store type.py | 978 | 4.0625 | 4 | '''
While .groupby() is useful, you can calculate grouped summary statistics without it.
Walmart distinguishes three types of stores: "supercenters", "discount stores", and "neighborhood markets", encoded in this dataset as type "A", "B", and "C". In this exercise, you'll calculate the total sales made at each store t... |
faec819aae020d7523f90a6532c0d4e66084d169 | Icaro-G-Silva/AlmostNothingUseful | /Palindrome/Python/palindrome.py | 197 | 4.15625 | 4 | word = str(input('Please, write a word: '))
rWord = word[::-1]
if word == rWord: print(f'The word {word} is a palindrome!')
else: print(f'The word {word} is not a palindrome! Look -\n{rWord}')
|
7d50758534c3047b58269be0db0da9cdb08ce1a7 | michealbradymahoney/CP1404-2017-SP2 | /prac_02/passwordChecker2.py | 1,186 | 4.1875 | 4 | __author__ = 'Micheal Brady-Mahoney'
import random
import string
SPECIAL_CHARACTERS = "!@#$%^&*()_-=+`~,./'[]\<>?{}|"
def password_generator(size=8, chars=string.ascii_letters + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def main():
permittedChars=''
numberOfChars = input("... |
66e48300dcbde8f14e6aa9e9fb5ba33ac378ddac | emanueldicristofaro/Python-Project--1 | /Proyecto/main.py | 2,995 | 3.71875 | 4 | import pedidos
import banco
# Proyecto #1
# Integrantes:
# Emanuel Di Cristofaro Esposito
# Aaron Perez Pereira
# Boris Torrado Hernandez
# En este módulo presenta el menú principal del sistema
# Registro de nuevos clientes, mostrar los mismos, ver info de la tarjeta, iniciar sesión y cerrar el sistema.
clients = {}... |
d8ffa6107ffa7a6785e9b7ff370403325bf03cee | szqh97/test | /python/91advices/func_value.py | 970 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def inc(n):
print id(n)
n = n + 1
print id(n)
n = 3
print id(n)
inc(n)
print n
print '-----------'
def change_list(orginator_list):
print 'orgnator_list is:', orgnator_list
new_list = orgnator_list
new_list.append('I am new')
print 'new list i... |
794446202f6c8bf9f52b120aa4a1825ba0937084 | Uche-Clare/python-challenge-solutions | /Moses Egbo/Phase 1/Python Basic 1/Day 2 task/task_6.py | 246 | 4.1875 | 4 | ''' Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers. '''
num = (input("Input numbers separated by commas :"))
n = num.split(',')
print(n)
print(tuple((n)))
|
55e89092844450a6465d8841c92514b589921705 | AbdussamadYisau/30daysOfCodeWithECX | /Day6.py | 358 | 4.3125 | 4 | # This code returns the power set of a particular list, in the form of sublists.
def power_list(arr):
powerSet = [[]]
for num in arr:
#Iterate over the sub sets so far
for subSet in powerSet:
# Add a new subset consisting of the subset at hand
powerSet = powerSet + [list(subSet) + [num]]
return(po... |
e0b39e579f79334402fa601d7516a7f7ec39c428 | AnJian2020/Leetcode | /chapter5/二叉树层次遍历.py | 1,486 | 3.90625 | 4 | # -*- coding:utf-8 -*-
class TreeNode(object):
def __init__(self,data,left=None,right=None):
self.data=data
self.left=left
self.right=right
class Tree(object):
def __init__(self,root=None):
self.root=root
def add(self,item):
treeNode=TreeNode(item)
if not s... |
0a5ec273526a6b0ea291aad45a2cd0b63bbdd899 | zhang-ru/learn-Python | /codewars_Dec11 pin.py | 738 | 3.546875 | 4 | import itertools
def get_pins(observed):
l = {"1":"124", "2":"1235", "3":"236","4":"1457","5":"24568","6":"3569","7":"478","8":"57890","9":"689","0":"80"}
temp = []
result=l[observed[0]]
if len(observed) ==1:
return list(''.join(result))
else:
for i in range(1,len(observed)):
result = list(itertools.pro... |
7c6b2a90c060d5113dbc3d1ba16073f6bf753477 | PuneetDua/Python | /Tic_Tac_Toe_Game.py | 4,225 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Tic Tac Toe Game app
@author: Puneet Dua
"""
'''
Actions need to be taken care of
- board
- Displaying that board
- Alternate Turns, i.e, playing game
- Check for wins, tie
- check for rows, columns, diagonal
'''
# Reqd for computer ... |
aa25f13234b647191d3fdc1fad426e4e23cb90c8 | adityajaroli/python-training | /basic/oops/4PythonClassStaticVariablesAndMethods.py | 1,079 | 4.0625 | 4 |
class Employee:
COMPANY_NAME = "XYZ Pvt. Ltd."
def __init__(self, empid, name):
self.empid = empid
self.name = name
def print_emp_details(self):
print(f"empid: {self.empid} - name: {self.name}")
@staticmethod
def get_complete_address():
print(f"static method ... |
83a91fa21ccf9633daac394b2bad6f997273c790 | JessicaNgo/pyp-w1-gw-language-detector | /language_detector/main.py | 1,391 | 4.34375 | 4 | from .languages import LANGUAGES
def detect_language(text, languages=LANGUAGES):
'''Detects language name based on # of matches of common words to words in text'''
#lists that will hold counts for each language
lang_match_counts = []
#iterate sequentially through languages list
for langu... |
a4cedc0a8f1d9478d5d76aa2a313744804d8acfc | wccgoog/pass | /python/gcd.py | 188 | 3.875 | 4 | def gcd(a,b):
if b==0:
print('最大公约数为',a)
return
r=a%b
if r==1:
print('最大公约数为1')
return
return gcd(b,r)
a=int(input('a:'))
b=int(input('b:'))
gcd(a,b)
|
ab76bbcd036a156592f8eb4ad83a9cf30a329779 | Jorgro/TDT4110-Information-Technology | /Øving 7/Sortering.py | 771 | 3.96875 | 4 |
def bubble_sort(list):
exchanges = True
numb = len(list)-1
while numb > 0 and exchanges:
exchanges = False
for i in range(len(list)):
if list[i-1]>list[i]:
list[i-1], list[i] = list[i], list[i-1]
exchanges = True
numb -= 1
return list
... |
73556d419a55cde55f01bdc48bbae64ac1e34c18 | pavan-kc/Learnings | /Qspiders/Python/programs/atm.py | 723 | 4.0625 | 4 | withdrawal=int(input("enter the amount to be withdrawn "))
atm_balance=200
user_account_balance = 180
if withdrawal<100:
print("invalid amount entered please enter amount in multiple of 100")
elif withdrawal<atm_balance and withdrawal<user_account_balance:
atm_balance-=withdrawal
current_balance= user_accou... |
1d1ebc6cf2144b19935785e64d984ee98a6c12c9 | JustinWhalley-Carleton/snake | /auto_player.py | 2,526 | 3.578125 | 4 | from queue import PriorityQueue
import pygame
from node import Node
# get the next move by choosing the next move of the A* algorithm considering, head of snake as start, apple as end and snake body as walls
def getNextMove(grid,start,end):
#initialize variables
count = 0
open_set = PriorityQueue()... |
6d6e268e67eb2680fe432ca1e53501b375ed19c6 | hadoop73/sklearn | /predict_risk/feature/test.py | 571 | 3.515625 | 4 |
"""
import numpy as np
import pandas as pd
d = pd.DataFrame({'a':[2,'ad',6],'b':[3,'nan',2]})
b = pd.DataFrame({'a':[1,3,5],'b':[3,4,2]})
def kk(x):
try:
x = float(x)
return x
except:
return -9999
for c in d.columns:
d[c] = d[c].apply(lambda x:kk(x))
d.fillna(-9999,inplac... |
f2ffc91fccd29b356507835afeee81972434f5d1 | PravinSelva5/LeetCode_Grind | /Math/MissingNumber.py | 1,020 | 3.890625 | 4 | '''
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Time Complexity - O(N)
Space Complexity - O(1)
Runtime: 136 ms, faster than 37.28% of Python3 online submissions for Missing Number.
Memory Usage: 15.4 MB, less than 25.91% o... |
887358cfe0aba7e7d2b0701a3f20becdfe0c6c06 | senthil7780/honeybee-devops | /honeybee-challenge1/access_github_details.py | 1,754 | 3.5625 | 4 | import requests
import json
import sys
import urllib
import csv
from pprint import pprint
data = []
github_dic ={}
username=raw_input("Please enter your github id : ")
# from https://github.com/user/settings/tokens
token=raw_input("Please enter your OAuth Token : ")
print("please enter the repos in $orgname/$rep... |
4156fbad01b225c92b41b8137fd23f9f03396cff | julioadriazola/Sistemas-Operativos-y-Redes | /Tarea1/metodo_input.py | 818 | 3.53125 | 4 | def hacer(consola):
try :
variable = consola.split(";")
except :
pass
if(len>=5):
#Crear un proceso a partir de las componentes de la linea
print "Proceso por comando"
opciones = []
for x in range(4,len(variable)):
opciones.append(variable[x]... |
7e452b88f4518a768918ef77db15f4a438eb9911 | Mix701/Programiranje | /recnik.py | 1,446 | 4.25 | 4 | dictionary = {
"1": "Star Wars",
"2": "Avengers",
"3": "Joker",
}
def meny():
print("***************Meny***************")
print("1: Insert new element in dictionary")
print("2: Write all elements in dictionary.")
print("3: Edit existing element in dictionary.")
print("4: De... |
5538f709a22c7122a134bbe78a5826e3d9560e08 | kkredit/hs-projects | /python-gui/squres_gui.py | 579 | 3.984375 | 4 | # exercise1.py
# A program to make shapes
# Kevin Kredit
import graphics
from graphics import *
def main():
win = GraphWin()
shape = Rectangle(Point(25,25), Point(75,75))
shape.setOutline("red")
shape.setFill("red")
shape.draw(win)
for i in range (10):
x = shape.clone()
p = win.... |
33c01daea0e5279cc67d9ce4756da906eb832b43 | Oisin-Rooney/Python-Practical | /gpio_python_code/6_morsecode.py | 553 | 3.640625 | 4 | import os
from time import sleep
import RPi.GPIO as GPIO
loop_count = 0
def morsecode():
GPIO.setmode(GPIO.BCM)
GPIO.setup(22,GPIO.OUT)
GPIO.setwarnings(False)
GPIO.output(22,GPIO.HIGH)
sleep(.1)
GPIO.output(22,GPIO.LOW)
sleep(.1)
os.system('clear') # clear the screens text
print ... |
14ee260387cdfde73a97cc8e9a40fe07d0b09b78 | 845318843/20190323learnPython | /withKid/代码清单22.py | 1,888 | 3.703125 | 4 | # # my_file = open('my_filename.txt', 'r')
# #
# # # my_file = open('notes.txt', 'r')
# # #
# # #
# # # line = my_file.readline()
# # # lines = my_file.readlines()
# # #
# # # my_file.close()
# # # print(lines)
# # # print(line)
# #
# # # # 22-2
# # # my_file = open('notes.txt', 'r')
# # # first_line = my_file.readline... |
8b7b516c7aebe6f42b819bbd909ef15ac66e5819 | chriscent27/calculator | /test_calculator.py | 552 | 3.765625 | 4 | import unittest
from calculator import addition, subtraction, multiplication, division
class TestCalculator(unittest.TestCase):
def test_addition(self):
result = addition(50, 25)
self.assertEqual(result, 75)
def test_subtraction(self):
result = subtraction(50, 25)
self.assertE... |
48f982c3c67de8641ff55844d7eab6abe169c3c8 | darwinfv/Miscellaneous-Programs | /Learn Python/learn_python.py | 3,269 | 3.875 | 4 | # is checks if two variables refer to the same object, but == checks
# if the objects pointed to have the same values.
# Equivalent of C's '?:' ternary operator
"yahoo!" if 3 > 2 else 2 # yahoo!
li = []
li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
del li[2] # li is ... |
c4d61f81250f89805bd5d807962bac923fae8ef7 | GhimpuLucianEduard/CodingChallenges | /challenges/ctci/sorted_merge.py | 1,365 | 3.984375 | 4 | """
10.1 Sorted Merge
You are given two sorted arrays, A, B where A has a large enough buffer at the end
to hold B. Write a method to merge B into A in sorted order.
"""
import unittest
def sorted_merge(a, b):
# copy b in after a
end = len(a) - 1
end_of_b = len(b) - 1
end_of_a = len(a) - len(b) - 1
... |
03f11e3dcf32928ea9b2071c2fd4e3558f9eb54e | danielzuncke/minis | /foobar.py | 173 | 3.546875 | 4 | n = 100
for x in range(1, n):
y = ""
if x % 3 == 0:
y += "foo"
if x % 7 == 0:
y += "bar"
if len(y) == 0:
y += str(x)
print(y)
|
ca6c131960a61aa722a22f038350597d19acf4c4 | shaneweisz/CSC3002F-VirtualMemoryAlgorithms | /paging.py | 6,396 | 3.96875 | 4 | # Shane Weisz
# WSZSHA001
import sys
from random import randint
def FIFO(size, pages):
"""
Function that implements the FIFO page replacement algorithm and
returns the number of page faults that occur.
Parameters:
size (int): The number of available page frames - can vary from 1 to 7
... |
67aea2f801a91f9a9014f5ca9aaeefa0067f4ea6 | Aasthaengg/IBMdataset | /Python_codes/p03192/s380407726.py | 88 | 3.9375 | 4 | str_num = input()
count = 0
for c in str_num:
if c == "2":
count += 1
print(count) |
aac40d112d74096971e6d77388314422a52d07e5 | hk1997/Algorithms | /Cryptography Algorithms/Python/OneTimePad.py | 2,844 | 3.671875 | 4 | import string
import random
key = ''
encrypted_text = []
bin_key = []
def bin_to_str(binary):
binary = str(binary)
character = ''
char = ''
size = len(binary)
k = 1
for j in binary:
if j != ' ':
character += j
if k == size:
char += chr(int(charac... |
df024ed74db445bd2f31f91c3886d80afd358e3c | owlrana/cpp | /rahulrana/python/Leetcode/#051 Pascals Triangle/v51.0.py | 948 | 3.609375 | 4 | # https://leetcode.com/problems/pascals-triangle/
class Solution:
def generate(numRows):
# initiate 1st level
pascal = [[1]]
# assign level to 1
lvl = 1
# create list of sublevel and append it to pascal later on
while lvl < numRows:
... |
31d3cfc6313e09f69a1a826c938b228c2732eeef | Bowie666/what-you-want-to-be | /profeskills/backend/python/stdlib/1.Built-inFunctions.py | 5,314 | 3.546875 | 4 | """11 @classmethod
把一个方法封装成类方法。就是调用的时候不需要实例化了"""
"""10 chr(i) 就是返回当前整数对应的 ASCII 字符。
返回 Unicode 码位为整数 i 的字符的字符串格式。
例如,chr(97) 返回字符串 'a',chr(8364) 返回字符串 '€'。这是 ord() 的逆函数。
实参的合法范围是 0 到 1,114,111(16 进制表示是 0x10FFFF)。
如果 i 超过这个范围,会触发 ValueError 异常。"""
# print(chr(41)) # )
# print(chr(97)) # a
# print(chr(8364)) # €
""... |
7a45664ec8b90c7eb3666c01d95447fed4106da3 | yetimark/CSC415-Project | /grid.py | 4,242 | 3.875 | 4 | import random
# These are the data structures for holding information about a position on the display
# A cell is now a tuple in the format (x,y)
# In the end I really want the coordinates on the graph so this will be less cumbersome
# A Grid is basically a 2D array of cells. It also has some extra fancy bells and wh... |
b3eaf14dfc4d14a326352a2a3afa774181ee3ef5 | sunwang33/liaoxuefeng | /liaoxuefeng_python3/函数的参数.py | 5,007 | 4.3125 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
# @Time : 2018-11-14 13:42
# @Author : SunWang
# @File : 函数的参数.py
#可变参数
def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n*n
return sum
print(calc([1, 2, 3]))
print(calc((1, 3, 5, 7)))
#定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号。在函数内部,参数num... |
41b0b1aa0cb4ada4cb4058714a06f89f8f69700b | Da1anna/Data-Structed-and-Algorithm_python | /leetcode/其它题型/递归/斐波那契数列.py | 970 | 3.96875 | 4 | '''
写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下:
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2
输出:1
示例 2:
输入:n = 5
输出:5
提示:
0 <= n <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/prob... |
b16941eecd6da8f113283074f8669526cd4c2324 | pratik-iiitkalyani/Python | /file_system/read_text_file.py | 1,093 | 4.375 | 4 | # readfile
# open function - to open the file
# read method - read the file
# seek method - to the position of the cursor
# tell method - tell the cursor position
# readline method - read single line
# readlines method - read file line by line
# close method - to close the file
f = open('file1.txt') #... |
29e4b40ff26d59b31f204d4f518edd711376e244 | nouranHnouh/cartwheeling-kitten | /add_and_appandList.py | 245 | 4.125 | 4 | #create list1 and list2
list1 = [1,2,3,4]
list2 = [1,2,3,4]
#add 5 and 6 to list1
list1 = list1 + [5, 6]
list2.append([5, 6]) # add list [5,6] to list2
#check results of list1 and list2
print "showing list1 and list2:"
print list1
print list2
|
6cd0f2c155d4843880c74a3fb1b99cb63621d968 | Ben0623/IntroProgramming | /Guessing-Game.py | 369 | 4.09375 | 4 | def main():
print ("Hello, this is a guessing game guess an animal")
animal = str("Pig")
guess = input (str("The game is thinking of an animal take a guess:"))
guess = guess.capitalize()
while guess != "Pig":
print ("Wrong Guess again")
guess = input(str("Enter and animal:"))
if ... |
27a65b478ae1aacd072ae94ca6eb552453645937 | jieunjeon/daily-coding | /Programmers/12901_2016.py | 948 | 3.71875 | 4 | """
https://programmers.co.kr/learn/courses/30/lessons/12901
2016년
문제 설명
2016년 1월 1일은 금요일입니다. 2016년 a월 b일은 무슨 요일일까요? 두 수 a ,b를 입력받아 2016년 a월 b일이 무슨 요일인지 리턴하는 함수, solution을 완성하세요. 요일의 이름은 일요일부터 토요일까지 각각 SUN,MON,TUE,WED,THU,FRI,SAT
입니다. 예를 들어 a=5, b=24라면 5월 24일은 화요일이므로 문자열 "TUE"를 반환하세요.
제한 조건
2016년은 윤년입니다.
2016년 a월 b일... |
a67d07ea6464f8df440272ed01000ffcfdc3a5eb | daminisatya/Python | /PE40.py | 401 | 3.578125 | 4 | def digit_at(n):
digits = 1
n = n - 1
while True:
numbers = 9 * pow(10, digits-1) * digits
if n > numbers: n = n - numbers
else: break
digits = digits + 1
num = n / digits + pow(10, digits-1)
return int(str(num)[n % digits])
print digit_at(1) * digit_at(10) * digit_a... |
020b703aa68faafffd9cff67644b7de3ac6960ef | BayarevichAleh/FirstDay | /Day4/Function_4.py | 992 | 4 | 4 | from random import randrange
def create_matrix(n, m):
"""
Create new matrix
:param n: columns
:param m: rows
:type n,m: int
:return: created matrix
"""
new_matrix = list()
for i in range(m):
row = list()
for j in range(n):
row.append(randrange(-100, 100))... |
6e88e4a0eeb0da3ce5e77888753e8f24957036c9 | jc449767/syed | /practical 01/hello world.py | 599 | 3.96875 | 4 | firstname = 'syed'
lastname = 'ahemd'
age = int(input("enter your age:"))
fruits = ["orange", 'mango', 'banana', 'melon']
sequences = [1,2,3,4,5,6,7,8,9]
print ('today is the 1st day of programming')
print (firstname + " " + lastname)
print(25, firstname + " " + lastname)
print(fruits[0])
for value in fruits:
pr... |
b660355de92cb29666c2e4010d8b304b0fd37932 | holzschu/Carnets | /Library/lib/python3.7/site-packages/sympy/series/series.py | 1,918 | 3.546875 | 4 | from __future__ import print_function, division
from sympy.core.sympify import sympify
def series(expr, x=None, x0=0, n=6, dir="+"):
"""Series expansion of expr around point `x = x0`.
Parameters
==========
expr : Expression
The expression whose series is to be expanded.
x : Symbol
... |
e9c2c58ba9a7456dc7b1603fafdd480aa96fbf8a | sankari-chelliah/Python | /linked_list.py | 699 | 4.0625 | 4 | # A single node of a singly linked list
class Node:
def __init__(self, data = None, next=None):
self.data = data
self.next = next
# A Linked List class with a single head node
class LinkedList:
def __init__(self):
self.head = None
# insertion method for the linked list
def insert(self, data):
... |
4a8832b3fc12e8a2f999a5ba538bee8b2398b19d | taegyeongeo/python_algorithm_interview | /group_anagrams.py | 264 | 3.84375 | 4 | import collections
def group_anagrams(strs):
anagrams=collections.defaultdict(list)
for word in strs:
anagrams[''.join(sorted(word))].append(word)
return anagrams
token=['eat','tae','tan','ate','nat','bat']
res=group_anagrams(token)
print(res) |
0aec8906334cfe23edb7d7b49c3ea57ce540bd2b | linux-wang/leet-code | /bczf/2_2.py | 313 | 3.671875 | 4 | # -*- coding:utf-8 -*-
# 这个题最重要的是思路,感觉遍历一个数,然后使用hash去判断所需的另外一个数是否存在,机智的很啊
s = {1, 2, 3, 4}
sum = 5
s1 = set()
for i in s:
n = sum - i
if n in s:
if (i, n) not in s1 and (n, i) not in s1:
s1.add((i, n))
print s1
|
cafb9aeb9a9da703325dc2979a1e21a098e56bb7 | D-Code-Animal/CTI110 | /P2T1_SalesPrediction_EatonStanley.py | 311 | 3.53125 | 4 | # CTI-110
# P2TI-Sales Prediction
# Stanley J. Eaton Sr.
# June 15, 2018
# Get the projected total sales.
total_sales = float (input ('Enter the projected sales:'))
# Calculate the profit as 23 precent of total sales.
profit = total_sales * 0.23
# Display the profit.
print ('The profit is $', format (profit, ',.2f'... |
a9f484a5a5c9dac5a95de0667203e6ddc348c0e8 | saraparva/PROBLEMS_JUTGE | /Which graphics cards should I buy?.py | 270 | 3.71875 | 4 | gpu_frequency=int(input())
game_needed_frequency=int(input())
count_of_games=0
while( game_needed_frequency != 0):
if(game_needed_frequency<=gpu_frequency):
count_of_games = count_of_games+1
game_needed_frequency=int(input())
print(count_of_games)
|
9837bfc43e4e96a71b821e1621a7fda121b31a43 | AasaiAlangaram/OpenCV-Autonomous-Car | /Test - Arduino Raspberry pi Interactive control/Test1-Interactive Control.py | 2,926 | 3.921875 | 4 | #!/usr/bin/env python
"""Interactive control for the car"""
import pygame
import pygame.font
import serial
import configuration
UP = LEFT = DOWN = RIGHT = False
def get_keys():
"""Returns a tuple of (UP, DOWN, LEFT, RIGHT, change, stop) representing which keys are UP or DOWN and
whether or not t... |
bfbf9f91e966d755ab8b3e73a31a5fcf21f346a7 | ed100miles/StructuresAndAlgorithms | /LinkedLists/test_single_linked_stack.py | 1,385 | 3.546875 | 4 | import unittest
from single_linked_stack import LinkedStack
class TestCase(unittest.TestCase):
def setUp(self):
self.stack = LinkedStack()
for letter in 'abcd':
self.stack.push(letter)
def test_len(self):
self.assertEqual(len(self.stack), 4)
def test_is_empty(self):
... |
6e4f7bb9672e9681520e16d6d94b2990c0d11e18 | funktor/stokastik | /Cython/sieve/.ipynb_checkpoints/sieve_python-checkpoint.py | 327 | 3.546875 | 4 | import numpy as np
def sieve(n):
arr = np.empty(n+1, dtype=np.int32)
arr.fill(1)
arr[0], arr[1] = 0, 0
sqrt_n = int(np.sqrt(n))
for i in range(2, sqrt_n+1):
if arr[i] == 1:
j = i**2
while j <= n:
arr[j] = 0
j += i
return np.nonze... |
dcb7db80084d17b86c8c51611b46d6b530acea62 | Orbsa/CRUDbrary | /books_controller.py | 1,486 | 3.546875 | 4 | from db import *
def create_table(): # It may be more appropriate to use a schema sql file..
''' Create the database table if it's not already there
should have title, author, isbn
rented to be ISO8601 corresponding to time of last rental
availble is boolean integer '''
table = """CREATE TABLE IF ... |
91a5ae70d9483afad3a58968987fabbfcac8b38c | eljempek/informatika-python-if-zadaci | /zad2.py | 788 | 3.984375 | 4 | import math
# Unesemo vrednosti
a = float(input("Unesi vrednost a "))
b = float(input("Unesi vrednost b "))
c = float(input("Unesi vrednost c "))
# Proverujemo pravougaonost
a2 = math.sqrt(b**2 + c**2)
b2 = math.sqrt(a**2 + c**2)
c2 = math.sqrt(a**2 + b**2)
print((c2) or (a2) or (b2))
if ((c == c2) or (a == a2) or (b... |
4e43ef04517af1d8f297d811b1d14d368a232834 | woosanguk/solve-at-day | /Algorithms/Search/IceCreamParlor.py | 402 | 3.84375 | 4 | """
https://www.hackerrank.com/challenges/icecream-parlor/problem
"""
def ice_cream_parlor_solve(m, n, flavor):
for i in range(n):
for j in range(i + 1, n):
if flavor[i] + flavor[j] == m:
print(i + 1, j + 1)
return
if __name__ == "__main__":
ice_cream_... |
b88d7be86cc8d5939b7573b44c842749abdd4ef5 | tjvr/nefarious | /eval/b/fibiter2.py | 115 | 3.625 | 4 |
def fib(n):
return 1.0 if n < 2.0 else fib(n-1.0)+fib(n-2.0)
import sys
n = float(sys.argv[1])
print fib(n)
|
cfdef81f800ffc5e7725875d564736d02c7356d4 | mangei/adventofcode2016 | /21_2.py | 5,208 | 3.703125 | 4 | # Advent Of Code 2016 - http://adventofcode.com/2016
# python 21_2.py < input_21.txt
# correct answer: gdfcabeh
# --- Part Two ---
#
# You scrambled the password correctly, but you discover that you can't actually modify the password file on the system. You'll need to un-scramble one of the existing passwords by reve... |
6742dceff83f65ca2978fe3b81fc87818502ccea | liu839/python_stu | /程序记录/基础/列表遍历.py | 238 | 3.703125 | 4 | #方法1
count = 0
length = len(member)
while count < length:
print(member[count], member[count+1])
count += 2
#方法二:
for each in range(len(member)):
if each%2 == 0:
print(member[each], member[each+1]) |
4ddf9c302178860ed2dd9d3ab89e9ce4455b5dd0 | Yeansovanvathana/Python | /Python program/List program/List 8.py | 90 | 3.875 | 4 | lis = [1, 2, 3, 4]
if len(lis) == 0:
print("list is empty")
print("list is not empty") |
952d54a9477cdd934a17de135dbf0ac19164ad2d | fantasylsc/LeetCode | /Algorithm/Python/25/0009_Palindrome_Number.py | 1,310 | 4.25 | 4 | '''
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a pali... |
23ab75d81425ddc9de6dc2de7db19aa398b84bdc | rajathelix/Green-Data-Centers | /Data_Analyzer.py | 2,131 | 3.640625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import csv
# Reads data
def read_data():
x=[]
y=[]
z=[]
with open('data.csv') as csvfile:
readCSV=csv.reader(csvfile,delimiter=',')
for row in readCSV:
x.append(float(row[0]))
y.append(float(row[1]))
z... |
38cdc513e8a15b0d66ffbfdef469c725e4cb0d85 | helbertsandoval/trabajo10_sandoval-sanchez-helbert_cesar_maira_paz | /submenu6.py | 1,057 | 3.84375 | 4 | import libreria
#1. Implementacion de submenu
def agregarAreadelrectangulo():
#1 agregamos la base del rectangulo
#2 agregamos la altura del rectangulo
#3. calculamos el area del rectangulo
base=libreria.pedir_numero("ingrese la base",3,300)
altura=libreria.pedir_numero("ingrese la altura",2,... |
80004bc64883448534290b38d54a2b70e0dce9a8 | BenDosch/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/3-say_my_name.py | 543 | 4.59375 | 5 | #!/usr/bin/python3
""" Module containing a function that says your name
"""
def say_my_name(first_name, last_name=""):
""" function that prints, 'my name is' followed by a first and last name
Args:
first_name (str): Individual's name
last_name (str): Family's name
"""
if type(first_... |
1de36922d427cd066ae7b71a0136f8ebca302dea | Yucheng7713/CodingPracticeByYuch | /Medium/314_binaryTreeVerticalOrderTraversal.py | 732 | 3.78125 | 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 verticalOrder(self, root: 'TreeNode') -> 'List[List[int]]':
if not root:
return []
v_map = collections.de... |
4ccd28e76938385e39f8b4dc0d19698cde52d585 | srinisim/UMich-CIS-ECE | /CIS 350/Program 3/Program3.py | 3,411 | 3.921875 | 4 | # Srinivas Simhan
# CIS 350 - Elenbogen: Winter 2018
# Program 3
# Due: 3/27/18
class Germ:
def __init__(self):
self.children = []
self.ancestors = set()
self.index = None
"""
PRE:
- None
POST:
- returns the number of ancestors associated with the object
DESC... |
95ebdb366ce15b967916bfd2996cd1a6b707918f | Sangewang/PythonBasicLearn | /LeetCode/ImplementStrstr.py | 844 | 3.6875 | 4 | class Solution(object):
def strStr(self, haystack, needle):
haystack_lenth = len(haystack)
needle_lenth = len(needle)
if(haystack_lenth == 0 and needle_lenth == 0):
return 0
target_local = -1
print("The Length of haystack is %d" % haystack_lenth)
print("The Length of ne... |
4b4c2ea4817adc9c1310d92e38e393263010197a | TheSussex/SCAMP-Assesment | /mycode.py | 700 | 4.375 | 4 | # This program gives a fibonacci sequence based on the input of the user
# Author- Success Ologunsua
given_num = int(input("How many terms? ")) # accepting input from the user into the (given_num) variable
n1, n2 = 0, 1 # first two terms
count = 0
sequence = []
if given_num <= 0: # c... |
b1c53fbcc4d3fbfe9642ff4d05b945090b3749b8 | Caff1982/PyChess | /board.py | 2,997 | 3.890625 | 4 | import copy
class Board:
"""
Class to keep track of chess board and move pieces.
Castling rights are stored as class attributes and
updated in the move_piece function.
"""
def __init__(self, board=None):
if board is None:
self.board = ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r... |
71bc72183050d0206f1bf55d91ee2d83fdeb2509 | olgayordanova/PythonAdvanced | /AdvancedExamsPreparation/02.Snake.py | 1,645 | 3.921875 | 4 | def make_jump (r, c, mtr):
for i in range (len(mtr)):
for j in range (len(mtr)):
if mtr[i][j]=="B" and (i!=r and j!=c):
return i,j
def is_valid_position (row, col, n):
if 0 <= row < n and 0 <= col < n:
return True
return False
n = int(input())
matrix... |
17c3c38ba1756b19020f0e7b908a15ad6a95de6f | MeirNizri/KNN | /main.py | 2,409 | 3.53125 | 4 | import numpy as np
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
from KNearestNeighbor import KNearestNeighbor
# Create all points and labels from rectangle.txt
points = []
f = open("rectangle.txt", "r")
for line in f:
words = line.split()
points.append([float(words... |
20bde3099a6c5149755ea05b98b72d5fe9718395 | ssamea/team_note | /sort/H-index.py | 709 | 3.8125 | 4 | # 어떤 과학자가 발표한 논문 n편 중,
# h번 이상 인용된 논문이 h편 이상이고 나머지 논문이 h번 이하 인용되었다면 h의 최댓값이 이 과학자의 H-Index입니다
def solution(citations):
answer = 0
citations.sort(reverse=True) # 먼저 f 값을 가장 큰 값에서 가장 낮은 값으로 정렬
citations.insert(0,0)
# print(citations)
for i in range(1, len(citations)):
if i == citations[i]:
... |
7513f32b60ad82f59f3a0213891d3e6d58591963 | cmf2196/quadruped_robot | /PygameController.py | 5,401 | 3.734375 | 4 | """
Connor Finn
9/14/2020
# To run.
+ You need pygame 2 python3 -m pip install pygame==2.0.0.dev6
+ Connect your PS4 Controller to the computer over bluetooth (wired will work fine too)
# This is a modified Version of Josh's PygameController
"""
import time
import pygame
import platform
class PygameControl... |
ffb4cf91c39aca61c25dae01e284970bc0b3fe2c | prashantchanne12/Leetcode | /find the median of a number stream.py | 1,401 | 4 | 4 | from heapq import *
class MedianOfStream:
# cotains first half of numbers
maxHeap = []
# contains second half of numbers
minHeap = []
def insert_num(self, num):
if not self.maxHeap or -self.maxHeap[0] >= num:
heappush(self.maxHeap, -num)
else:
heappush(sel... |
91e81e45b330a1f1beba23190a0a352f7cda63bd | carlsfg/semestrei | /sums.py | 698 | 3.65625 | 4 | def sum2():
print x + y
def sum3():
print x + y + z
def sum4():
print x + y + z + a
def sum5():
print x + y + z + a + b
def sum6():
print x + y + z + a + b + c
def sum7():
print x + y + z + a + b + c + d
def sum8():
print x + y + z + a + b + c + d + e
def sum9():
print x + y + z + a + b ... |
088a7bf8ef1a0becea59e6930dea56e206361b3c | mathiasare/IdsSoccerPredictionsProject | /data_mining/data_extractor.py | 860 | 3.96875 | 4 | #From https://www.sqlitetutorial.net/sqlite-python/sqlite-python-select/
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
... |
55427007e8b5334d85f6ed4e0564e403c0edddd1 | Draqneel/Python | /python_hacks/script.py | 1,697 | 4 | 4 | from collections import Counter
def main():
string = "i need some sleep"
a = string[0:6]
b = string[7:11]
print("Main string: " + string)
print("1) String reverse: " + string_reverse(string))
print("2) To title: " + string.title())
print("3) Find unique: " + find_unique(string))
pr... |
0d6bb7fd51be8847bc0b317a987eaaad13329c43 | impiyush83/expert-python | /operator_overloading.py | 974 | 3.984375 | 4 | # operators cannot be used to do manipulations on objects
# operqtor overloading can be done in python with help of magic functions
class complex:
def __init__(self, a, b):
self.a = a
self.b = b
# adding two objects
def __add__(self, other):
return self.a + other.a, self.b ... |
e45bc5ee3c90702c9f67642fb4c0090f3169f3d6 | aduV24/python_tasks | /Task 4/example.py | 4,398 | 4.15625 | 4 | #************* HELP *****************
#REMEMBER THAT IF YOU NEED SUPPORT ON ANY ASPECT OF YOUR COURSE SIMPLY LOG IN TO www.hyperiondev.com/support TO:
#START A CHAT WITH YOUR MENTOR, SCHEDULE A CALL OR GET SUPPORT OVER EMAIL.
#*************************************
# PLEASE ENSURE YOU OPEN THIS FILE IN IDLE otherwi... |
ce573942dff69562fbc4a212be3e7d05bab4fd34 | SirGuiL/Python | /Mundo 3/Python_Exercicios/ex080.py | 546 | 3.921875 | 4 | lista = []
maior = 0
menor = 0
for c in range(0, 5):
num = int(input('Digite um número inteiro: '))
if c == 0 or num > lista[-1]:
print('Adicionado ao final da lista')
lista.append(num)
else:
posição = 0
while posição < len(lista):
if num <= lista[posição]:
... |
653fda668ee89fe97df9541ef9298d807ee1f3c9 | simba28/daily-codes | /sortArrayByParity.py | 604 | 3.625 | 4 | class Solution:
def sortArrayByParity(self, A):
# even = []
# odd = []
# for n in A:
# if n%2 == 0:
# even.append(n)
# else:
# odd.append(n)
# return even+odd
i, j = 0, len(A)-1
while i<j:
... |
e16cebcfc69bd09a5d356697fd1a04bca9cbd1f0 | lucken99/Qs | /poddu.py | 216 | 3.609375 | 4 | n = int(input())
if(n < 0):
print("Wrong Input")
else:
p=n*n*n*n
flag = False
while (n>0):
if(n%10==p%10):
n=n//10
p=p//10
else:
print("FALSE")
flag = True
break
if not flag:
print("TRUE")
|
119c5f6fd7547df7c143c16fe98883844e383b3c | hswang108/Algorithm_HW | /WEEK4/LeetCode/queue_array.py | 199 | 3.65625 | 4 |
def enqueue(myQueue, val):
for i in range(len(a)-1,0,-1):
a[i] = a[i-1]
a[0] = val
a = [5, 4, 3, 2, 1]
print(a)
# a = [5, 5, 4, 3, 2]
# a = [6, 5, 4, 3, 2]
enqueue(a, 6)
print(a) |
7394bdf13e37d6a6fbcbba7424c97f000931d3d4 | mewwts/pyudorandom | /pyudorandom/pyudorandom.py | 1,499 | 4 | 4 | import random
"""
Functions for generating the cyclic group [0,...n-1]. Use instead of
random.shuffle() or similar.
Functions:
pyudorandom(n) <- generate the numbers in 0,...n-1
bin_gcd(a, b) <- calculate the gcd of a and b fast
"""
def items(ls):
"""
Yields the elements of ls in a pseudorandom fashio... |
396a239fbff4cc252972862fc758ede2ebd6a8d1 | khanhbao128/HB-Code-Challenge-Problems | /Whiteboarding problems/Easier/max_of_three.py | 429 | 4.34375 | 4 |
# define a function that takes in 3 numbers and return the largest
def max_of_three(num1, num2, num3):
"""Return the largest number in three numbers given"""
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
elif num3 >= num1 and num3 >= ... |
c92ef065f86b9c7ff5cce0eecbf0da9fd03dc9f0 | GregorH97/HW070172 | /L07/Ch11/5.py | 2,540 | 4 | 4 | def getthings():
nums = []
xStr = input("Enter numbers you want to have in your listing (<Enter> to quit)")
while xStr != "":
x = int(xStr)
nums.append(x)
xStr = input("Enter numbers you want to have in your listing (<Enter> to quit)")
return nums
def count(listing):
... |
74cda4c510e302d09840506132078fd0784904c3 | syves/euler | /euler3.py | 711 | 4 | 4 | import math
def isprime(n):
ceil_sqrt_n = math.ceil(math.sqrt(n))
for x in range(2, int(ceil_sqrt_n)):
if n % x == 0:
return False
return True
def factorize(n):
"""
Returns a set of factors of n.
"""
ceil_sqrt_n = math.ceil(math.sqrt(n))
factors = []
for x in ra... |
2d6fff7ccf5fa6df15db70c88cb219a977ed95ed | michal0janczyk/udacity_data_structures_and_algorithms_nanodegree | /Data Structures/Arrays and Linked List/arrays/Add-One_solution.py | 4,009 | 4.25 | 4 | # Solution
"""
The Logic
1. The idea is to start checking the array from the right end, in a FOR loop.
2. Add 1 to the digit, and check if it lies in the range 0-9 OR becomes 10.
3. If the updated digit is between 0-9, quit the FOR loop. (Example, original array is [1,2,3])
4. Otherwise update the current position in t... |
62519d85e72563c9dae3095431b0ff71f1162166 | barackmaund1/Top-headlines | /tests/article_test.py | 1,318 | 3.640625 | 4 | import unittest
from app.models import Article
class ArticleTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Article class
'''
def setUp(self):
'''
Set up amethod that will run every test
'''
self.new_article=Article("Gizmodo.com","Catie Keck",
... |
51f94d2411c8fb418efb0b87c4af35e0fdb8ff57 | watsonjj/aoc2020 | /aoc2020/d02_password_philosophy/methods.py | 864 | 3.59375 | 4 | import re
class Password:
def __init__(self, line, old_policy=True):
self.old_policy = old_policy
pattern = r"(\d+)-(\d+) (\w): (.+)(?:\n?)"
reg_exp = re.search(pattern, line)
self.min = int(reg_exp.group(1))
self.max = int(reg_exp.group(2))
self.letter = reg_exp.gr... |
90854aca8e7a5e18c73af44432747a10f5e16f2e | baihaqi2193/daspro | /daspro.py | 10,217 | 3.65625 | 4 | ## LIST
## LIBRARY INI BERISI DATABASE CODE UNTUK LIST
## LIBRARY INI DIBUAT DAN DIKUMPULKAN OLEH :
## MUHAMAD NUR BAIHAQI (INFORMATIKA UNDIP 2020)
## INI ADALAH LIBRARY FUNGSI PRIMITIF
## Konstruktor:
def mklist():
return []
## Basic Predicate
# Mengecek List Kosong atau Bukan:
def IsEmpty(L):
i... |
0633310d08effec2ab8debb0b10bc9588e659f81 | gr4vytr0n/ml | /classification/applications/knn/dating_data/dating_data_test.py | 1,803 | 3.53125 | 4 | '''
test dating dataset with knn algorithm
'''
from numpy import array
from sys import path
from os import getcwd
path.insert(0, getcwd() + '/utils/')
path.insert(0, getcwd() + '/datasets/')
path.insert(0, getcwd() + '/classification/knn/')
from process_data import process_data
from knn import classify
def test... |
1da616f8036e98d90d9706bef6e8077be31f52a5 | Juldam/ejerciciosPython2DAM | /Clases/ejc8.py | 4,905 | 3.984375 | 4 | '''
En este ejercicio realizará un programa en Python que asigne e imprima en pantalla
las asignaturas, profesores y estudiantes de una pequeña "universidad".
Defina:
- Clase superior Miembro.
+Con atributos nombre, edad y dni.
- Dos clases que heredan de ella: Profesor y Estudiante.
+Profesor tiene, adicionalm... |
17905cb8ebffb6430c58338c8e833ca3b2876125 | Nickruti/HackerRank-Python-Problems- | /lists.py | 837 | 3.671875 | 4 | if __name__ == '__main__':
N = int(input())
inputlist = []
outputlist = []
for a in range(0, N):
inputlist.append(input().split())
if "insert" in inputlist[a][0]:
i = int(inputlist[a][1])
e = int(inputlist[a][2])
outputlist.insert(i,e)
... |
5a33d7e8ab0a013deaaabe0a7e4f100a068db94e | oneshan/Leetcode | /todo/636.exclusive-time-of-functions.py | 2,156 | 3.609375 | 4 | #
# [636] Exclusive Time of Functions
#
# https://leetcode.com/problems/exclusive-time-of-functions
#
# Medium (39.82%)
# Total Accepted:
# Total Submissions:
# Testcase Example: '2\n["0:start:0","1:start:2","1:end:5","0:end:6"]'
#
# Given the running logs of n functions that are executed in a nonpreemp... |
0caec53331d757772aac3f795373ef6d8930f458 | Run0812/Algorithm-Learning | /to_offer/60_DicesProbability.py | 830 | 3.859375 | 4 | """
问题60:n个骰子的点数
题目:把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。
输入n,打印出s的所有可能的值出现的概率。
"""
def dices_probability(n):
"""
:param n:number of dices
:return: dict of possible value
"""
times = {1:1, 2:1, 3:1, 4:1, 5:1, 6:1}
for i in range(2,n+1):
cache = {}
for val in range(1 * i, 6 * i + 1):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.