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 |
|---|---|---|---|---|---|---|
7d5cdec139b3d5f058fc453ea02cca88c3776334 | salman98ansari/Practical | /OSTL/stringlen.py | 188 | 4.03125 | 4 | def stringl(x,y):
if(len(x)<=len(y)):
return(x)
else:
return(y)
a=str(input("entr string\n"))
b=str(input("enter string\n"))
print("the shortest strinf is",stringl(a,b))
|
df6b9a2cbad6361c3ab657f2023f0da27e7a7e29 | SaloniGandhi/leetcode | /48. Rotate Image.py | 1,094 | 3.875 | 4 | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
#for nxn matrix we would have n/2 cycles to complete
#we go from outer boundry to the inner one
# #x=boundry
'''
N=len(ma... |
9170e8bad7a2641598cc800e1a414f18c21122de | mszsorondo/Pr-cticas-y-programas-viejos | /herencia.py | 1,729 | 3.640625 | 4 | class movil():
def __init__(self, marca, modelo):
self.marca=marca
self.modelo=modelo
self.marcha=False
self.acelera=False
self.frena=False
def enmarcha(self):
self.marcha=True
def acelerar(self):
self.acelera=True
def frenar(self):
self.frena=True
def estado(self):
print("Ma... |
e4af72846506e7d5749bf8e35f2cb1c31cf5df86 | DiegoSantosWS/estudos-python | /estudo-10/lambda7.py | 537 | 3.953125 | 4 | tabuada = [
lambda x: f"{x} * 1 = " + str(x * 1),
lambda x: f"{x} * 2 = " + str(x * 2),
lambda x: f"{x} * 3 = " + str(x * 3),
lambda x: f"{x} * 4 = " + str(x * 4),
lambda x: f"{x} * 5 = " + str(x * 5),
lambda x: f"{x} * 6 = " + str(x * 6),
lambda x: f"{x} * 7 = " + str(x * 7),
lambda x: ... |
9ba6c41d20b1a67ba1660c2b060853792bfbc6af | Lewisw3/Tutorials | /assets/person.py | 357 | 3.8125 | 4 | class Person:
num_of_people = 0
all_names = []
def __init__(self, name, age, sex, height):
# initialise instance attributes
self.name = name
self.age = age
self.sex = sex
self.height = height
# update class attributes
Person.num_of_people += 1
... |
9ec6cef75aa74ae1f212435ff4844784dd22d68a | icicchen/PythonGameProgramming | /Monkeys.py | 778 | 4.1875 | 4 | '''
We have two monkeys, a and b, the parameters a_smile and b_smile indicate if each is smiling.
This program prints "We are in trouble" if they are both smiling or if neither of them is smiling, while in other conditions, we are fine.
'''
import sys
#reading arguments from the terminal
a_smile = sys.argv[1]
b_smile ... |
d1b687cce5af6e5a68a86326935da251761e65e4 | Ashwinbicholiya/cpp-Practice | /xplore11.py | 1,533 | 3.8125 | 4 | class Product:
def __init__(self,productName,productType,unitPrice,qtyinHand):
self.productName = productName
self.productType = productType
self.unitPrice = unitPrice
self.qtyinHand =qtyinHand
class Store:
def __init__(self,productList):
self.productList = productList
... |
7710e90593d889284c80a1e87704871e042ecc70 | yinty/python100day | /day5.py | 1,320 | 3.828125 | 4 | """
求解《百钱百鸡》问题
1只公鸡5元 1只母鸡3元 3只小鸡1元 用100元买100只鸡
问公鸡 母鸡 小鸡各有多少只
Version: 0.1
Author: 骆昊
Date: 2018-03-02
"""
for x in range(0, 20):
for y in range(0, 33):
z = 100 - x - y
if 5 * x + 3 * y + z / 3 == 100:
print('公鸡: %d只, 母鸡: %d只, 小鸡: %d只' % (x, y, z))
from random import randint
money... |
8856bd76f4542c419bc2906b7a66c615b0314041 | lakshay-saini-au8/PY_playground | /hackerrank/algorithm/warmup/timeConversion.py | 239 | 3.625 | 4 | def timeConversion(s):
hh, mm, ss = s[0:len(s)-2].split(":")
s_type = s[-2:]
if s_type == "PM" and int(hh) != 12:
hh = int(hh)+12
if int(hh) == 12 and s_type == "AM":
hh = '00'
return f"{hh}:{mm}:{ss}"
|
08005368c4a53e7aad98f7d7c8019635a52bda49 | MormonJesus69420/Knowledge-Based-Systems-Theory | /ass8/knn.py | 5,804 | 4.09375 | 4 | from typing import List, Tuple, Dict
from entry import Entry
import operator
class KNN:
"""Uses KNN algorithm to classify Entry elements.
Using KNN algorithm and other entries provided to the init methods finds
which class a specific entry belongs to.
"""
def __init__(self, entries: List[Entry],... |
d0db0ba8c0392ef5df3c2f93f88eeb4df6a7ec97 | ongsuwannoo/Pre-Pro-Onsite | /MRT Blue Line2.py | 631 | 3.703125 | 4 | """ MRT Blue Line 2 """
def main():
""" input station and card """
station = input()
card = input()
if "Adult" in card:
card = 1
elif "Student" in card:
card = 0.9
elif "Elder" in card:
card = 0.5
if "Chatuchak Park" in station:
price = 21 * card
... |
3681ccd885542897c170212411e73b4311fb7cff | sourabhjain19/aps-2020 | /Code Library/29_fibonacci.py | 96 | 3.53125 | 4 | n=int(input())
arr=[0]*n
arr[1]=1
for i in range(2,n):
arr[i]=arr[i-1]+arr[i-2]
print(*arr)
|
524a71473eb17df59eb61364ff786111ef9de536 | SethKwashie/PythonLabs | /DataTypes/lab7.py | 107 | 3.71875 | 4 | # Fibonacci sequence
x,y=0,1
count = 0
while count < 21 :
count +=1
print(y)
x,y = y,x+y
|
8e88860e8c8bb9242c4b5973e29d24e187b74869 | timeisen/Helpers | /revcomp_by_line.py | 331 | 3.5625 | 4 | import fileinput
import sys
def reverse_complement(seq):
"""Get reverse complement of sequence"""
nt_dict = {'A':'T', 'T': 'A', 'C': 'G', 'G':'C', 'N': 'N'}
return ''.join([nt_dict[nt] for nt in seq][::-1])
for line in fileinput.input():
newline = reverse_complement(line.strip()) + "\n"
sys.stdout.writ... |
3ce0c6eb3c670695c9b00beabe8a3a8615700d42 | ShawnBatson/Sprint-Challenge--Data-Structures-Python | /names/binary_search_tree.py | 5,799 | 4.28125 | 4 | """
Binary search trees are a data structure that enforce an ordering over
the data they store. That ordering in turn makes it a lot more efficient
at searching for a particular piece of data in the tree.
This part of the project comprises two days:
1. Implement the methods `insert`, `contains`, `get_max`, and `for_ea... |
fddd94248a3b9c9ce314e4672cadbfc5857ba0e5 | canoc62/trees | /median_maintenance/heap_runner.py | 1,712 | 3.625 | 4 | import sys
import time
from heaps.heaps import Heap, MinHeap
HEAP_LENGTH_DIFF_THRESH = 2
def main():
try:
f = open("text/" + sys.argv[1])
except OSError as e:
print("OS error({0}): {1}".format(e.errno, e.strerror))
sys.exit()
except:
print("Usage: 'python heap_runner.py [na... |
c0a39fec6b9bb26084ed42982a61883b65734964 | Abhrajyoti00/Tic-Tac-Toe | /main.py | 4,871 | 3.625 | 4 | class Node:
def __init__(self, val=None):
self.val = val
self.next = {}
class Board:
def __init__(self):
self.table = [[' ']*3 for i in range(3)]
self.available = {(col, row): True for col in range(3) for row in range(3)}
self.winner = ''
def put(self, col, row, ... |
247062347298a57522ac144ed0ed5683529d24c3 | haxzie/stackby | /scripts/get_files.py | 312 | 3.59375 | 4 | from os.path import isfile, isdir, join
from os import listdir
""" Method to return all files in the given directory """
def getFiles(dir):
#get all the contents of the dir
#add valid file to the array
files = [filename for filename in listdir(dir) if isfile(join(dir, filename))]
return files |
71c4f87d3e5973ab59f8a75a677c239567c47644 | TheRareFox/Socket-programming | /ws_battleship_client.py | 591 | 3.640625 | 4 | import socket
##MISSING CODE
#Code to create client socket
#Code to connected client socket to server socket
print("Welcome to Battleship! Try to guess where the ship is!\n")
while True:
##MISSING CODE
#Code to store data received into a variable named 'datareceived'
datareceived =
print(datareceive... |
25ac4296b96af23a0b7563aafe94b9c2c807f24a | nlakritz/video-poker | /maingame.py | 7,666 | 3.828125 | 4 | # Nathan Lakritz
# Fall 2016
# natejl123@gmail.com
import random
import VideoPoker
def create_deck():
'''Creates a deck of cards by storing character pairs into a list.
The elements are then randomized with a random shuffle function.'''
suits = "CDHS" # String of suits.
ranks = "23456789TJ... |
fb55f4c31f7fb341ca848a72ec35d3dac86642db | zmjstime/mlLearn | /doubanBook/test.py | 589 | 3.5 | 4 | import urllib2
# import urllib
# import json
import socks
import socket
socks.set_default_proxy(socks.SOCKS5, "localhost", 9150)
socket.socket = socks.socksocket
# url = 'https://api.douban.com/v2/book/1220562'
# a = urllib2.urlopen(url).read()
# a = json.loads(a)
# for x in a:
# print a[x]
url = 'http://www.doub... |
72d34a617fc5d2cbfd307c0dba3ed95de6df952a | nunenuh/raqm | /raqm/digital.py | 250 | 3.84375 | 4 | import math
def root(n, base=9):
return n % base or n and base
def root_with_factor(n, base=9):
base_factor = math.floor((n/base))
root = n % base or n and base
if get_factor:
return root, base_factor
return root
|
1263855dc788fb12e35b4067b892c02ad59b23dc | songzy12/LeetCode | /python/234.palindrome-linked-list.py | 1,310 | 3.640625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} head
# @return {boolean}
def isPalindrome(self, head):
# use fast and slow, slow = slow.next, fast = fast.next.next
# when fast m... |
9dd05be7c3fcb978ee91932393c343cb9a876114 | heniu75/python-milanovich | /HelloWorld.py | 745 | 4.1875 | 4 | # HelloWorld.py
csvValues = "some, csv, values"
splitValues = csvValues.split(",")
# simple looping
for item in splitValues:
print(item.strip())
# indexed for looping
for x in range(0, len(splitValues)):
print(x, splitValues[x].strip())
# boolean
a = True
b = False
aliens_found = None
# if then else
numbe... |
bcb572cf074b99adc54e35218b83ea05c83ebca7 | sprithiv/Algorithm-Design | /find_cyclic_graph.py | 2,462 | 3.6875 | 4 | def find_cyclic(matrix):
n = len(matrix)
#create adjacency list from given matrix
edges = {}
for i in range(0,n):
conn_node = []
for j in range(0,n):
if matrix[i][j] != 0:
conn_node.append(j+1)
edges[i+1] = conn_node
#Va... |
a764d2b7bd8871f45edd0fe15bd81ad1d70e9a16 | RadkaValkova/SoftUni-Web-Developer | /Programming Fundamentals Python/17 Lists Advanced Exercise/messaging.py | 416 | 3.6875 | 4 | numbers = input().split()
text = input()
text_string = [char for char in text]
get_chars = []
for num in numbers:
num = [int(n) for n in num]
index = sum(num)
for char in text_string:
if index > len(text_string):
index = index % (len(text_string))
get_chars.append(text_string[... |
7d64abe351a88d925596381935ae633c66d431e1 | lincolnjohnny/py4e | /2_Python_Data_Structures/Week_1/example_13.py | 173 | 3.875 | 4 | # String Library - Lowercase and Uppercase
greet = 'Hello Bob'
print(greet)
print(greet.lower())
print(greet.upper())
print('Hello Bob'.lower())
print('Hello Bob'.upper())
|
300673a2855a3dcdde860b27a3b28d9b283a93e8 | GuhanSGCIT/Trees-and-Graphs-problem | /Mex division.py | 2,484 | 3.515625 | 4 | """
Given an array A of n non-negative integers. Find the number of ways to partition/divide the array into subarrays, such that mex in each subarray is not more than k. For example, mex of the arrays [1, 2] will be 0, and that of [0, 2] will be 1, and that of [0, 1, 2] will be 3. Due to the fact that the answer can t... |
1d72370f2537792428674aa66240685f0ff08f8c | jk-aneirin/Scripts-practice | /pythonScripts/super.py | 518 | 3.578125 | 4 | #coding:UTF-8
class Base(object):
def __init__(self):
pass
def super_method(self,name):
self.name=name
print self.name
class A(Base):
def __init__(self):
Base.__init__(self)#因为调用类方法,所以要传self
class B(Base):
def __init__(self):
super(B,self).__init__()
def ca... |
2cb0750a0b9ce1ec2e04ffeebd0c46efde64a5ad | hidiorienta/praxis-academy | /novice/01-03/kasus/kasuscrc.py | 1,586 | 3.59375 | 4 | class Gadget:
def __init__(self, gadgetlist, price):
self.gadgetlist = gadgetlist
self.price = price
print('(Gadget: {})'.format(self.gadgetlist))
def tell(self):
print('Gadget List:"{}", Price:"{}"'.format(self.gadgetlist, self.age), end=" ")
class Brand(Gadget):
def __ini... |
22f255d4e0a1f925435ad7c67ac80d9c92d4a72f | navill/advanced_python | /metaprogramming/type_example.py | 2,141 | 3.546875 | 4 | def method(self):
return 1
# 인자에 해당하는 클래스를 생성한다.
# 세번째 인자의 key: 생성될 method 이름, value: 기존의 method
MyClass = type('MyClass', (object,), {'method_': method, 'attr': None})
# 위 코드는 아래 클래스와 동일한 구문
# class MyClass(object):
# def method_(self):
# return 1
def func_test():
my = MyClass()
print(my.me... |
a17801cfbb07adc5a0a07ce3e9e7d7d24d3f47c8 | LourdesOshiroIgarashi/algorithms-and-programming-1-ufms | /Lists/Estrutura_de_Repetições_Aninhadas/Cauê/01.py | 82 | 3.765625 | 4 | num = 7
x = 1
while num >= 1:
print("*" * x)
x = x + 1
num = num - 1
|
3926481567ada0322036dc0a8c14f4adffd5feee | laharrell20XX/rental_store_loganharrell | /core.py | 4,912 | 3.921875 | 4 | def process_inventory(unprocessed_inventory):
'''(list of str) -> list of dict
Returns a list of inventory items as a list of item dictionaries
'''
inventory_list = []
for item in unprocessed_inventory:
if item:
item = item.strip().split(',')
item_dict = dict(
... |
9543951333b68aa2bafbf257a8bc86f148750d58 | Grisson/MyPractice | /82. Remove Duplicates from Sorted List II.py | 1,973 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head... |
20aabb4cfd76db3cb3c39bf72c1c5246852f29e5 | businessglitch/Data-Structures-in-Python | /linked_list/linked_list.py | 5,312 | 4.09375 | 4 | class LinkedList:
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
def toString(self):
return str(self.data)
def __init__(self):
self.__size = 0
self.__head = None
s... |
169a2836517c64057a68794f051f2f9f4abc1f00 | devzgabriel/python-calculator | /calc_defs/calc_part0.py | 6,151 | 3.75 | 4 | import math
def part(opcao):
str(opcao)
if opcao == '1':
soma = 0
algoritimos = int(input('Quantos Números Somar?'))
for q in range(0, algoritimos):
soma += int(input('Quais: '))
print('O resultado da soma é: ', soma)
elif opcao == '2':
mult = 1
... |
9c059ecfc3485560583e8345f8ccf80fb814f505 | simranmahindrakar/DAA-things | /mergerrr.py | 459 | 3.875 | 4 | def merge(a,b):
(c,m,n)=([],len(a),len(b))
(i,j,k)=(0,0,0)
while(k<m+n):
if(j==n or a[i][1]*b[j][0]>a[i][0]*b[j][1]):
c.append(a[i])
i=i+1
k=k+1
elif(i==m or a[i][1]*b[j][0]<a[i][0]*b[j][1]):
c.append(b[j])
j=j+1
... |
5d0c5768dc5d038bd6287e49146bb7d4f9bbe271 | ficherfisher/leetcode | /SortList_1.py | 570 | 3.953125 | 4 |
def sort(nums):
if len(nums) <= 1: return nums
mid = len(nums) // 2
left = sort(nums[:mid])
right = sort(nums[mid:])
return merge(left, right)
def merge(left, right):
result = []
while len(left) > 0 and len(right) > 0:
if left[0] > right[0]:
result.append(right.pop(0)... |
5d6ea491415c407dd6fd7bdc0f45ad354f3ce52c | Auralcat/poker-simulation-python | /poker.py | 632 | 4.09375 | 4 | #!usr/bin/python3
# -*- encoding: utf-8 -*-
"""Another shot at simulating a poker game"""
import random
import os
# Just the card values here
card_values = list(range(2, 11)) + ["J", "Q", "K", "A"]
# Now, the suits (clubs, diamonds, hearts, spades):
suits = ["C", "D", "S", "H"]
# Now we pack everything together WI... |
8a195e057b4e9e5f6591c137b1d1b12322e19147 | neequole/my-python-programming-exercises | /unsorted_solutions/question55.py | 244 | 3.96875 | 4 | """ Question 55:
Write a function to compute 5/0 and use try/except to catch the exceptions.
Hints:
Use try/except to catch exceptions.
"""
def foo():
return 5/0
try:
foo()
except ZeroDivisionError:
print('Division by zero!')
|
5146a36e1917a4e0b73c2bfc4f925016bf97bea8 | elenamoglan/Instructiunea-IF | /Problema5_IF.py | 493 | 3.65625 | 4 | '''Cunoscând data curentă exprimată prin trei numere întregi reprezentând anul, luna, ziua precum şi data naşterii unei persoane,
exprimată la fel, să se facă un program care să calculeze vârsta persoanei respective în număr de ani împliniţi.'''
z, l, a = map(int, input("Data curenta este ").split('.'))
zn, ln, an... |
2eb6adcd81a2c08eec8b073ba82ce571ecb38ec2 | lixiang2017/leetcode | /leetcode-cn/0882.0_Reachable_Nodes_In_Subdivided_Graph.py | 1,202 | 3.6875 | 4 | '''
dijkstra + heap
执行用时:168 ms, 在所有 Python3 提交中击败了81.94% 的用户
内存消耗:20.3 MB, 在所有 Python3 提交中击败了93.06% 的用户
通过测试用例:49 / 49
'''
class Solution:
def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
g = [[] for _ in range(n)]
for u, v, w in edges:
g[u].ap... |
68ab9d165300f7945e75c098452a559151b45837 | Baidaly/datacamp-samples | /7 - introduction to data visualization with python/pyplot/pseudocolor plot from image data.py | 1,069 | 3.765625 | 4 | '''
Image data comes in many forms and it is not always appropriate to display the available channels in RGB space. In many situations, an image may be processed and analysed in some way before it is visualized in pseudocolor, also known as 'false' color.
In this exercise, you will perform a simple analysis using the ... |
45e78ad9c06827bed93446866762b088ba1796f4 | quento/encrypting-with-python | /client.py | 5,529 | 3.640625 | 4 | import socket
import helper
from helper import simpleCipher, randomString
class SimpleClient:
"Simple client that communicats with a socket server."
server_public_key = ""
# append a random string to client secret for each connection.
client_secret = "This is Client Secret - UniqueKey=" + randomString... |
3d7a9332c6348fbf3c93a2303fcfb4e8bfe1d0a0 | shuowenwei/LeetCodePython | /Easy/LC409LongestPalindrome.py | 485 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/longest-palindrome/
"""
class Solution:
def longestPalindrome(self, s: str) -> int:
res = 0
single_Letter = False
counterS = collections.Counter(s)
for k, v in counterS.items():
res += (v //... |
c5a7c303362f03ac003d40d5753346d152cc0966 | getstock/GETSTOCK | /getstock/accounts/friends.py | 11,308 | 3.75 | 4 | import csv
data = []
data2 = []
data1 = []
#accept, deny, write_to_somebody, print_friends, print_request_friends, print_conversation
#login = "", password = "", list_of_friends = [ [friend_login, [conversation]] ], list_of_requests = [login]
#[login, password] -> data
#[name1, name2, friend or requeste(1/0)] -> data1... |
62d248b0afbeda15b955a73ac29c652779a3ea14 | JakubKazimierski/PythonPortfolio | /Coderbyte_algorithms/Easy/SimpleAdding/SImpleAdding.py | 542 | 4.21875 | 4 | '''
SimpleAdding from Coderbyte
October 2020 Jakub Kazimierski
'''
def SimpleAdding(num):
'''
Have the function SimpleAdding(num)
add up all the numbers from 1 to num.
For example: if the input is 4 then
your program should return 10 because
1 + 2 + 3 + 4 = 10.
For the test cases, th... |
444960ab0c95947fa272a985b318c6c4f9d96e5a | TheQYD/think-complexity-examples | /graph.py | 1,146 | 3.765625 | 4 | #!/usr/bin/python
class graph(dict):
def __init__(self, verticies=[], edges=[]):
for vertex in verticies:
self.add_vertex(vertex)
for edge in edges:
self.add_edge(edge)
def add_vertex(self, vertex):
self[vertex] = {}
def add_edge(self, edge):
v,w = e
self[v][w] = e
self[w][v] ... |
6fc03b697de7f4c572d356ffd0f8c5a77b9d78b5 | dcontant/checkio | /restricted_sum.py | 493 | 4.0625 | 4 | def checkio(data):
'''
Given a list of numbers, you should find the sum of these numbers.
Your solution should not contain any of the banned words, even as a part of another word.
The list of banned words are as follows:
sum
import
for
while
reduce
Input: ... |
c091152030e77e96a66a9d8df2d0f32ddcc820cf | TechWriterLisa/My-Python | /Exercises/Beginner/Exercise4.py | 405 | 3.9375 | 4 | import math
# from math import pi
var=math.pi
'''
print('Enter Radius: ')
rad=input()
rad=float(rad)
'''
rad=float(input('Enter Radius: '))
area=var * (rad ** 2)
print('The area of a circle is ' + str(area) + ' with radius of ' + str(rad))
'''
#area=pir**2
import math
bigNum=math.pi
myRad=(input('Enter the radius... |
00388e5974d1241887235db67674e5580b78ac6b | LeetCodeBreaker/LeetCode | /048.RotateImage/clywin123/rotate.py | 409 | 3.59375 | 4 | import copy
class Solution:
# @param {integer[][]} matrix
# @return {void} Do not return anything, modify matrix in-place instead.
def rotate(self, matrix):
n = len(matrix)
if(n<=1):
return
tmp = copy.deepcopy(matrix[::-1])
for i in range(n):
for j in... |
077f366ca5db11d3fb89f305848d9164999eaa5f | CyrillSchwyter/awd | /aufgabe4/taylorpoloynome.py | 3,374 | 3.546875 | 4 | import sympy as sym
import numpy as npy
import matplotlib.pyplot as plt
# Verwendetes Modul fuer die Erstellung von Lambda-Funktionen
# aus mathematischen Funktionen
module = 'numpy'
def taylor_1(f, x0, symbol: sym.Symbol):
"""
Berechnet T1 (Taylorpolynom ersten Grades)
Entspricht der Tangente durch Punk... |
e2cfdc09ccf7df1a6dc679ed65534862aa3efb24 | DongjunLim/algorithm_study | /프로그래머스/가장 큰 수.py | 1,160 | 3.703125 | 4 | def compare(x, y):
xy = str(x) + str(y)
yx = str(y) + str(x)
return x if xy > yx else y
def partition(start, mid, end, numbers):
temp = []
i, j, k = start, mid, end
while i < mid and j <= end:
if compare(numbers[i], numbers[j]) == numbers[i]:
temp.append(numbers[i])
... |
0507e9f102d404c6f3246752600be757133f2faa | MaxKrog/KTH | /PRGOMED/Springaren/chessboard.py | 1,789 | 3.578125 | 4 | from tkinter import *
import random
from chesssquare import ChessSquare
class ChessBoard:
def __init__(self, parent,root):
self.parent = parent
self.container = Frame(root)
self.score = 0
self.chessBoard = []
self.createBoard()
self.moveList = []
self.row = random.randrange(0,8)
self.col = random.... |
936df9b8f034ab62035494ca22a04102228987ca | Brian-McHugh/algoPrep | /Python/nth_Fib/nth_Fib.py | 593 | 4.40625 | 4 | """Implement a function recursively to get the desired
Fibonacci sequence value.
Your code should have the same input/output as the
iterative code in the instructions."""
# recursive solution
def nth_Fib(n):
if n == 0 or n == 1:
return n
else:
return nth_Fib(n - 1) + nth_Fib(n - 2)
"""
# solution using m... |
899642f2dd4465473cfff75b92df302b321e30af | mpencegithub/python | /pyds/8_4.py | 253 | 3.75 | 4 | fhandle=open('romeo.txt', 'r')
words=list()
for lines in fhandle :
line=lines.rstrip()
pieces=line.split()
for piece in pieces :
if piece not in words :
words.append(piece)
words.sort()
print(words)
|
f1684ae889b0f7399e7e4680f4ae8e4f69168400 | LennyBicknel/Python-Text-Adventure | /Application/main.py | 4,998 | 3.515625 | 4 | import txtadvlib, os
from iowrapper import *
# ---------main----------
# Xander Lewis - 21/07/14
# -----------------------
def cls():
"""Clears the screen."""
clearstr = ""
for i in range(100):
clearstr += "\n"
strOut(clearstr)
def intro(name):
"""Welcomes and introduces the player to the... |
95faf0a7685fbbd3f72c300b85b6dc87541c6aa0 | gulan/jiyi-tty | /chinese.py | 4,624 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import sqlite3
class SQL(object):
""" Operations on a flashcard deck """
@property
def question(self):
(chinese,pinyin,english,live) = self._topcard()
if live == 1:
return [chinese]
if live == 2: # ... |
dc4fa2e780a1f57ee289a68e7dbd24335cfbb9e5 | Saranya-sharvi/saranya-training-prgm | /test.py | 551 | 4.21875 | 4 | """print("Find biggest values amoung three values: ")
var1 = int(input("enter var1: "))
var2 = int(input("enter var2: "))
var3 = int(input("enter var3: "))
if((var1 >= var2 )and (var1 >= var3)):
print("The biggest is :", var1)
if(var2 >= var3):
print("The biggest is :", var2)
else:
print("The biggest is :", var... |
8dd6b0a0a6e167d0de2c4a82747fef48bac2f311 | steamedbunss/LEARN-PYTHON-THE-HARD-WAY | /03.py | 877 | 4.59375 | 5 | #+ plus
#- minus
#/ slash
#* asterisk
#% percent
#< less-than
#> greater-than
#<= less-than-equal
#>= greater-than-equal
print("I will now count my chickens:")
print("hens", 25 + 30 / 6)
print("Roosters", 100 - 25 * 3 % 4)
print("Now I will count the eggs:")
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print("Is it tr... |
46bdf58bd0e43ac69cd076d65fe538ea3a327aa5 | mshekhar/random-algs | /epi_solutions/arrays/shortest-unsorted-continuous-subarray.py | 1,545 | 3.578125 | 4 | class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
start = None
i = 0
while i < len(nums) - 1 and nums[i] <= nums[i + 1]:
i += 1
if i == len(nums) - 1:
return 0
star... |
ca3519355db8aa90c2c374fb7dd52aa45761bf64 | naveenv20/myseleniumpythonlearn | /packageandmethods/variablescope.py | 651 | 4.1875 | 4 | """
variable scope
"""
a=10
ab=15
def test_method(a):
print("inside method local value is old ",a)
a=a+2
print("inside method local value is new", a)
print("before calling method",a)
test_method(a)
print("after calling method ", a)
print("&"*20)
def test_method2():
global ab
print("inside meth... |
c48d7e79335a4cc2b8d8a07b7a862a5edcfef089 | predavlad/projecteuler | /projecteuler.net/7.py | 514 | 3.59375 | 4 | import time
# 0.05 seconds
start_time = time.time()
def get_primes(n):
"""
Get all the primes smaller than n
"""
primes = [0] * n
for i in xrange(2, n):
if primes[i] == 0:
yield i
else:
continue
for j in xrange(1, n // i):
primes[j * i] ... |
58d1f619c262661d8556671a39c90733764fb949 | measephemeral/Python | /polite.py | 118 | 3.671875 | 4 | hi = '안녕하세요!'
print(hi)
for i in range(0,10):
# 0 ~ 9까지의 반복을 실행합니다.
print(hi) |
315bebc7906e8f22e26ff36ea3a1669176c93bc1 | club-Programacion-UAEM-Ecatepec/Fundamentos-de-Python | /Practicas/11-Diccionarios.py | 1,006 | 4.09375 | 4 | diccionario = {"valor1" : "hola mundo",
2 : 20};
print(diccionario);
print(diccionario[2]);
unaString = "valor1";
print(diccionario[unaString]);
diccionario = {"Tamal": "platillo mexicano hecho de masa de maiz, salsa verde y pollo",
"Botanear": "verbo de comer alguna golocina",
... |
184ce6a56ae2676bce969f4cce79e5afd1d000ac | jupiterhub/learn-python-the-hard-way | /lpthw-part3/ex24.py | 1,552 | 4.1875 | 4 | # return multiple variables, passing a list to .format() using *
print("Let's practice everthing.")
# not necessary to escape the single-quotes. just demo
print("You\'d need to know \'bout escapes with \\ that do:")
print("\n newlines addd \t tabs")
#printed with newlines as well
poem = """
\tThe lovely world
with l... |
0e6f1a91b5bab3543708d41266995547d49b1180 | Pythones/MITx_6.00.1x | /L6P2_m.py | 375 | 3.984375 | 4 | def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
#setting variables
tplNew = ()
Count = 0
#setting the body
for oddElements in aTup:
Count += 1
if Count % 2 == 0:
tplNew += (oddElements,)
return tplNew
#end ... |
8abf2e1e33e5f7b58a839f566d04afb0513aec26 | epsalt/aoc2017 | /day19/day19.py | 1,130 | 3.796875 | 4 | from string import ascii_uppercase
def walk_path(dat):
y = 0
x = dat[0].index("|")
letters = []
dy, dx = 1, 0
steps = 0
while(True):
val = dat[y][x]
if val in ascii_uppercase:
letters.append(val)
if val == " ":
break
elif val == "+":
... |
9113ff3610ad19eeb88abeb2dabb59273922c339 | debojyoti-majumder/CompCoding | /pyWorspace/masmom/uniquePath.py | 3,424 | 3.5625 | 4 | # Problem URL : https://leetcode.com/problems/unique-paths/
# This should again get a TLE Error
# Sumission log: Accepted Used DP
# I tkink we can just use a map instead of a matrix because we would not
# be needing older values. The values of top row only
# Related problems: https://leetcode.com/problems/minimum-path-... |
6ddec1127a71d8bdfe5bb45ad400955322f3445b | ptaylor2018/AoC2020 | /day13/day13.py | 2,281 | 3.59375 | 4 | def part1():
input_raw = []
with open("input_day13.txt", "r") as reader:
# Read and print the entire file line by line
for line in reader:
input_raw.append(line)
input_cleaned = []
for item in input_raw:
input_cleaned.append(item.rstrip())
print(input_cleaned)
... |
39d78a13a5f9ff1c7dd660c93dd9107a775ef49e | IamJenver/mytasksPython | /factorial.py | 251 | 3.953125 | 4 | # На вход программе подается натуральное число n.
# Напишите программу, которая вычисляет n!
n = int(input())
counter = 1
for i in range(1, n + 1):
counter *= i
print(counter) |
56dd8e3b2173f17d4195c6ba3b4f5f6a3776b555 | pymft/py-mft1 | /S11/with_context/main.py | 140 | 3.65625 | 4 | f = open('file.txt', mode='r')
text = f.read()
f.close()
print(text)
with open('file.txt', mode='r') as f:
text = f.read()
print(text) |
b5e79146302aeb281c1ecd52dea76b5fe4dbf379 | xiang525/leetcode_2018 | /python/house_robber_ii.py | 1,926 | 3.5625 | 4 | class Solution:
# @param {integer[]} nums
# @return {integer}
def rob(self, nums):
if len(nums) == 1:
return nums[0]
return max(self.robLinear(nums[1:]), self.robLinear(nums[:-1])) # rob the first room or rob the
# last room. If 1st room is chosen then cannot choose the ... |
4f5bcfff48f170260be1fedb7a169ded5b584f80 | pranavgurditta/data-structures-MCA-201 | /linked_list_pranav.py | 6,143 | 4.28125 | 4 | class Node:
'''
Objective: To represent a linked list node
'''
def __init__(self,value):
'''
Objective: To instantiate a class object
Input:
self: Implicit object of class Node
value: Value at the node
Return Value: None
... |
ea2c4560c8c9fb2d08b0a6360afaa33dbfc4ff8a | WesternUSC/USC_Timeline | /createuser.py | 1,557 | 3.625 | 4 | """Script for creating a new user account.
The script can be executed by typing in: `python createuser.py` (assuming your
current directory is `USC_Timeline`).
Upon executing the script, you will be prompted to enter a username, email and
password. Using this information a new User will be instantiated and stored in
... |
606320eb874a961d7e9a26540574ec2fd65dbf84 | Obdolbacca/PyDA | /hw/hw1.py | 1,935 | 3.609375 | 4 | # Copyright by Oleg Bobok (c) 2019. For educational purpose
from math import sin, pi
import re
from typing import Tuple
def check_long_is_longer(long_str: str, short_str: str) -> bool:
return len(long_str) > len(short_str)
def greatest_by_letter_inclusions_count(string: str) -> str:
string = re.sub(r'[^аи... |
39270412a42d1ef91f813bc34790d6e7e7c6fa06 | pcampolucci/SVV-Group-A13-TUDelft | /src/loads/distributed_load.py | 7,178 | 3.515625 | 4 | """
Title: Functions for aerodynamic distributed load discretization
"""
import numpy as np
from src.input.input import Input
# =================== Global inputs to generate arrays =========================
la = 2.661
stepsize = 0.1 # [m] set the distance between points in trapezoidal rule
load = Input('A').aero_... |
c4e6feafed6f1400210698344f97bd986a724ab9 | Matheusrma/problem-solving | /spoj/PRIME1/PRIME1.py | 1,733 | 3.75 | 4 | # SPOJ Classical Problems
# Url: http://www.spoj.com/problems/PRIME1/
# Author: matheusrma
# -*- coding: UTF-8 -*-
import sys
import unittest
# Adds problem-solving folder to module searching path
# to enable code modularization
sys.path.append('../../')
from util.python.printer import Printer
from util.python... |
28ccab0dea15d693093f57d7a12f5522d4395166 | riyadhswe/Python_Javatpoint | /10 Python break statement/Example 3.py | 115 | 3.796875 | 4 | i = 0;
while 1:
print(i," ",end=""),
i=i+1;
if i == 10:
break;
print("came out of while loop"); |
803acd7a405e60a8eff655e00065c14ea0e6e06c | nabilhassein/project-euler | /p6.py | 704 | 3.84375 | 4 | # Sum square difference
# Problem 6
# The sum of the squares of the first ten natural numbers is,
# 1^2 + 2^2 + ... + 10^2 = 385
# The square of the sum of the first ten natural numbers is,
# (1 + 2 + ... + 10)^2 = 55^2 = 3025
# Hence the difference between the sum of the squares of the first ten
# natural numbers a... |
f948d0da08acca53849c65fc04282f4f08672893 | RomaelP/Proyecto2s22017 | /Phyton/ListaDoble.py | 5,830 | 3.515625 | 4 | from NodoListaDoble import NodoListaDoble
class ListaDoble():
def __init__(self):
self.inicio = None
self.ultimo = None
self.grafica = "digraph G{\n"
def insertarListaDoble(self, usuario, contrasenia, direccion, telefono, edad):
if self.inicio != None:
temp... |
edca5c447590799c06a580aa64cc8e8358e1e4c2 | junghyun4425/myleetcode | /medium/Peeking_Iterator.py | 2,316 | 3.953125 | 4 | # Problem Link: https://leetcode.com/problems/peeking-iterator/
'''
문제 요약: iterator 객체를 이용해서 peek기능이 있는 iterator를 구현하는 문제. (peek는 다음 값만 보여주고 실제로 다음 포인터로 넘어가지 않는 기능)
ask:
["PeekingIterator", "next", "peek", "next", "next", "hasNext"]
[[[1, 2, 3]], [], [], [], [], []]
answer:
[null, 1, 2, 2, 3, false]
해석:
iterator를 그대로... |
b69a58ff28cf1f85a7438efd50d3f0c62100db97 | drahmuty/Algorithm-Design-Manual | /05_02_playing_with_wheels.py | 4,207 | 3.5625 | 4 | from collections import defaultdict, deque
# Adjacency list graph representation
class Graph:
def __init__(self, directed=False):
self.graph = defaultdict(list)
self.degree = defaultdict(int)
self.directed = directed
self.n = 0 # Number of vertices
... |
3c8c899c197e937f6f225d840e63377f4cdceb45 | Sanket-Mathur/CodeChef-Practice | /CHEFSTUD.py | 280 | 3.625 | 4 | try:
for _ in range(int(input())):
S = list(input())
for i in range(len(S)):
if S[i] == '<':
S[i] = '>'
elif S[i] == '>':
S[i] = '<'
c = (''.join(S)).count('><')
print(c)
except:
pass
|
03df11fbd88001b9476307c5e2b2b3a4bc728e2a | vadivisuvalingam/courseraPythonCode | /Assignment1/test_stock_price_summary.py | 2,663 | 3.734375 | 4 | import a1
import unittest
class TestStockPriceSummary(unittest.TestCase):
""" Test class for function a1.stock_price_summary. """
# Add your test methods for a1.stock_price_summary here.
def test_stock_price_summary_empty_list(self):
"""Test empty list."""
actual = a1.stock_price_summary(... |
f257501c614d70a285f85859af09b88d90b27b4d | skdonepudi/100DaysOfCode | /Day 82/WhatIsYourMobileNumber.py | 1,035 | 3.953125 | 4 | '''
These days Bechan Chacha is depressed because his crush gave him list of mobile number some of them are valid and some of them are invalid. Bechan Chacha has special power that he can pick his crush number only if he has valid set of mobile numbers. Help him to determine the valid numbers.
You are given a string "... |
a16d24ab7966787c8fe524e7ce7be2d28ababbc9 | unlimitediw/CheckCode | /0.算法/103_zigzag_BST_LOT.py | 835 | 3.671875 | 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 zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not ro... |
d60db74fcff9792e422f8d10b8d710958907f077 | dheeraj1010/Hackerrank_problem_solving | /Codechef/composite_sub.py | 860 | 3.796875 | 4 | def reverse_ascii(x):
x = x-65
return x
def ascii(x):
x = x+65
return x
cipher_text = list(input().strip())
k1 = int(input())
k2 = int(input())
cipher_text = list(map(ord, cipher_text))
cipher_text = list(map(reverse_ascii, cipher_text))
#print(cipher_text)
#print(k1)
#print(k2)
k2_inverse = 1
while... |
72a6f791738dec1c72a5cd59c9941adba8958111 | ShiJingChao/Python- | /PythonStart/0722Python/0731task/objori.py | 3,250 | 3.75 | 4 | # class Person(object):
# """保卫者"""
# def __init__(self,name):
# self.name = name
# def install_bullet(self,magazineclib,bullet):
# '''将子弹安装到弹夹中'''
# magazineclib.save_bullet(bullet)
# def install_clib_2_gun(self,gun,clib):
# '''6.1将弹夹安装到枪中'''
# gun.insall_clib(cl... |
26512ab5196720a3656e5bb735ec4bd229fa7a7c | shloang/RPCgame | /rps/game.py | 2,313 | 3.859375 | 4 | import random
class RPCGame:
def __init__(self):
self.rule_dict = {"rock": 0, "paper": 1, "scissors": 2}
self.rule_list = list(self.rule_dict.keys())
self.score = 0
def build_rule_dict(self, rule_string=""):
if rule_string != "":
rule_list = rule_string.split(",")
... |
ba66782ba04eec189ed1da859d05e016b05b6fdd | atomextranova/leetcode-python | /High_Frequency/two_pointers/同向双指针/Sliding Windows/Minimum Window Substring/Sliding Window Template.py | 1,417 | 3.875 | 4 | class Solution:
"""
@param source : A string
@param target: A string
@return: A string denote the minimum window, return "" if there is no such a string
"""
def minWindow(self, source , target):
# write your code here
if not source or not target:
return ""
ta... |
622abeceea1d71ed6769ec093d4e0c5121b794b0 | riunixnix/pytest-simple-examples | /test_2.py | 777 | 3.765625 | 4 | import pytest
""" Create Method to calculate formula below with input `number`
( number + 1) * ( number - 1)
"""
def plus_1(number):
""" number+1 """
return number+1
def minus_1(number):
""" number-1 """
return number-1
def multiply(number_1, number_2):
""" number_1 x number_2 """
return... |
0de38892813b619cb9a3507623be2a37c8274ba8 | RicardoATB/connect-dots | /connect-dots.py | 1,594 | 3.609375 | 4 | #!/usr/bin/python3.8
# Description: Program that connects dots from a list of coordinate points
# Author: Ricardo Augusto Teixeira Barbosa
import argparse
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
from matplotlib.backend_bases import MouseButton
show_dots = False
data = []
def plot_gra... |
8cfe53df58492712ae5dba169c01a19fa7abfa0f | VolodymyrKM/km_test2 | /restaurant.py | 1,500 | 3.765625 | 4 | class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(f'The name of the restaurant is {self.restaurant_name}.')
... |
7fb77f6cad1c60f14b2f05210e0dcc197c3a5de5 | srinidp/dplearn-python | /_modules/mycsv_file1.py | 14,902 | 3.84375 | 4 | #-------------------------------------------------------------------------------
# Name: mycsv_file1
# Purpose:
#
# Author: srini_000
#
# Created: 24/03/2018
# Copyright: (c) srini_000 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
i... |
39d82267f966ca106ee384e540c31a3e5e433318 | fershady19/Algorithmic-Design-and-Techniques | /2_3_greatest_common_divisor.py | 408 | 3.75 | 4 | """
Task. Given two integers a and b, find their greatest common divisor.
Input Format. The two integers a, b are given in the same line separated by space.
Constraints. 1<=a,b<=2·109.
Output Format. Output GCD(a, b).
"""
def EuclidGCD(a, b):
if b == 0:
return a
else:
a = a%b
return Euc... |
9cd5b925c3c170236a735000485d4f33ee2c7f1e | JohanEdenfjord/PythonSchoolProjects | /Lab2/racer2.py | 1,461 | 3.625 | 4 | from graphics import *
class racer:
def __init__(self, win, speedLimit):
self.circle = Circle(Point(0, 0), 10)
self.circle.setFill('red')
self.circle.draw(win)
self.letter = Text(Point(0, 0), 'R')
self.letter.setTextColor('white')
self.letter.draw(win)
sel... |
1f02810f111cda32bca48f2bc8d301f170617f05 | easyas123l1/Data-Structures | /lru_cache/lru_cache.py | 2,644 | 3.84375 | 4 | from doubly_linked_list import ListNode, DoublyLinkedList
class LRUCache:
"""
Our LRUCache class keeps track of the max number of nodes it
can hold, the current number of nodes it is holding, a doubly-
linked list that holds the key-value entries in the correct
order, as well as a storage dict that... |
abc1cac2448842153a6c635a4ba6ea29240ff5ea | dujodujo/lemur | /Programiranje/vaja3/skalarni_produkt.py | 147 | 3.578125 | 4 | b = (1, 2, 3)
a = (4, 5, 6)
prod = 0
for x,y in zip(a,b):
prod += x*y
print(prod)
print(' + '.join('%d * %d' % (x, y) for x, y in zip(a, b))) |
eb1e4b9d04d1f2a779a45f294fa67b36171c403d | rishabh-16/Machine_Learning | /Decision Tree/decision_tree.py | 6,164 | 3.71875 | 4 | import numpy as np
"""=====================================MODULE FOR IMPLEMENTING DECISION TREE CLASSIFICATION=========================================="""
class Decision_Tree:
def fit(self,X,y):
try:
self.X=X.tolist()
self.y=y.tolist() #THIS CONVERTS X AND y TO LIST IF IT IS ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.