blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b84d184b232740477a96d3de4f77794f529befcf | deckardmehdy/coursera | /Course3/Week2/directedGraph2.py | 3,140 | 3.734375 | 4 | # Runs using Python 3
def edgeVisited(vertex,neighbor,dict):
return dict[str(vertex) + "-" + str(neighbor)]
def visitEdge(vertex,neighbor,dict):
dict[str(vertex) + "-" + str(neighbor)] = True
return dict
def computeTopology(dict,n,verticesToVisit):
# Do a depth first search of all of the vertices
... |
2f82f165eef9093ca851c1fb4a92da220ed4ba70 | BoboTiG/ebook-reader-dict | /wikidict/user_functions.py | 17,405 | 3.546875 | 4 | """
Functions that can be used in *templates_multi* of any locale.
"""
import re
from collections import defaultdict
from typing import Dict, List
def capitalize(text: str) -> str:
"""
Capitalize the first letter only.
>>> capitalize("")
''
>>> capitalize("alice")
'Alice'
... |
5dda8669c369a096aa6dc61a1840b22003b6079c | Nelicax/Python | /ArraysPractice.py | 1,156 | 4.125 | 4 | # Creating Array List (arrayList1)
arrayList1 = [8,"I am a Double Quotation String",True,["one",2,3,"four","Five"],3.16,'I am a Single Quotation String']
# Printing arrayList1
print("arrayList1: " + str(arrayList1))
# Changing Index 3 into a number 10
arrayList1[3] = 10
# Reprinting the array with the new d... |
40f6f71df5f4d2ee5eef823e1800f6994788c76f | emilycheera/coding-challenges | /reverse_words_2.py | 235 | 4.1875 | 4 | """Given a string, reverse the order of characters in each word within a
sentence while still preserving whitespace and initial word order."""
def reverse_words(s):
return " ".join(word[::-1] for word in s.split()) |
3a53a1cde3c077f43d61e72a36603a089b46bb55 | prasantib/docsaiprassu | /chapter10.py | 5,765 | 3.921875 | 4 | #opening and reading the file
with open("pi_digits.txt") as file:
contents = file.read()
print(contents.rstrip())
#printing each item in the text as a line
filepath = "pi_digits.txt"
with open(filepath) as file:
for line in file:
print(line)
#printing each line as a string in a list... |
6011079f16d4165a3b23acd0eda80f8c9c9066df | maomao905/algo | /lowest-common-ancestor-of-a-binary-tree-4.py | 1,377 | 3.71875 | 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 lowestCommonAncestor(self, root: 'TreeNode', nodes: 'List[TreeNode]') -> 'TreeNode':
def dfs(node):
if node is No... |
46412d8eb647be0d2477eba11667ed87839c6e82 | ajaybhatia/python-practical-2020 | /05-practical.py | 249 | 3.96875 | 4 | '''
Practical 5
Print numbers up to N which are not divisible by 3, 6, 9,, e.g., 1, 2, 4, 5, 7,....
'''
n = int(input("Enter limit: "))
for num in range(1, n+1):
if num % 3 != 0 and num % 6 != 0 and num % 9 != 0:
print(num, end=", ")
|
b5c089c1bf0099dc42557bf90b3749b6b19c213d | aa2276016/Learning_Python | /AByteOfPython/C04_Calculation4_identity.py | 672 | 4.125 | 4 | # 此内容是额外的,不包括在A byte of python这本书里,源自http://www.jianshu.com/p/dc5675b4317c
# 用函数id()来获取存储单元的编号
fruits_1 = ['apple', 'banana', 'grape', 'orange', 'pear']
fruits_2 = ['apple', 'banana', 'grape', 'orange', 'pear']
print(id(fruits_1))
print(id(fruits_2))
# 由于fruits_1和fruits_2的内容,使得他们占用了不同的储存单元,所以这两者是不相同的,结果为False
# 只有两者id... |
41c3fe1dcfc3636c115a04084274503ee5327a9f | Tabish596/Data-Structure-Algo | /Searching Techniques/Searching.py | 1,402 | 3.9375 | 4 | class searching:
def __init__(self, arr):
self.arr = arr
def linearsearch(self, a):
for i in range(len(self.arr)):
if self.arr[i] == a:
print('Element found')
return
print('Element not fount')
def mergesort(self, p):
if len(p) < 2... |
17b27c65c2fa56db1715c098827009ef27da943b | Altaris33/python_save | /OOP/tales_of_vesperia.py | 1,525 | 3.859375 | 4 | # TALES OF VESPERIA OOP PYTHON PROGRAM
class Character():
def __init__(self,name,attack,defense,agility,hp,pm):
self.name = name
self.attack = attack
self.defense = defense
self.agility = agility
self.hp = hp
self.pm = pm
def __str__(self):
return f"{se... |
997f2804e884f636395f03ca8b9754c5beaa636e | HiddenFox29/Python | /oop.py | 2,501 | 3.734375 | 4 | class User: #создаем класс с именем User обязательно с большой буквы
# описываем класс с помощью переменных строки цифры словарь
name = ''
city = ''
work = ''
money = 0
posts = []
userCount = 0
# self ссылка на сам объект например darkhan
# Конструктор класса
def __init__(self, n, с, w, m): #Так как объект... |
151bf302bb4ed6d5462b0f25534f53ae621bdefd | JoshJovanW/starbucks | /main.py | 3,376 | 3.703125 | 4 | from price import price_Menu
from soylatte import SoyLatte
from frappucino import Frappucino
from icecoffee import IceCoffee
from macchiato import Macchiato
from menu import Menu
from orders import Order
def main():
Menu()
price_Menu()
exit = False
Orders = Order()
while exit == False:
... |
a624e5f3105b47c01cd4dd124365e834f6748ce5 | brdayauon/interviewPreparation | /lowestCommonAncestor.py | 1,115 | 3.546875 | 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 lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
status = collections.namedtuple('st... |
0bba8ce533383a4a0ab0b24580564c44108d039f | IuliiaKot/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /Quiz/myLog.py | 334 | 4.03125 | 4 | def myLog(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.
'''
# Your Code Here
a = b
i = 1
if x < b:
return 0
while a*b <= x:
if b == 0:
return 0
i+=1
a*= b... |
376e0531ea3f150cfa7f6dab1190918527ac9d9c | fan-weiwei/algo-prep | /xin-era/codility/sorting/triangle.py | 1,414 | 3.671875 | 4 | """
given an array A consisting of N integers, returns 1 if there exists a triangular triplet for this array and returns 0 otherwise
A[P] + A[Q] > A[R],
A[Q] + A[R] > A[P],
A[R] + A[P] > A[Q].
(solution [10, 2, 5, 1, 8, 20]) == 1
(solution [10, 50, 5, 1]) = 0
N is an integer within the range [0..100,000];
each elem... |
116ceb95855bc65eb21bb53b33eacdab7d3723f4 | kapilmathe/algorithms | /pp01/pp01/Paytm/sort_0_1_2.py | 505 | 3.90625 | 4 | # https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0
from collections import Counter
def sort_012(arr):
elem_cnt = dict(Counter(arr))
j = 0
for i in range(3):
m = elem_cnt.get(i, 0)
for _ in range(m):
arr[j] = i
j += 1
return True
t = ... |
c7d2170bae53fcb520128f73b5865fdb37c51ba8 | parthkandpal/Sorting-Algorithms-using-Python | /MergeSort.py | 2,544 | 4.125 | 4 |
Arr=[54,26,93,17,77,31,44,55,20]
def Merge(L,R,A): #Merge function takes 3 parameters L as left sorted Array, Right Sorted Array and A as Array to be sorted
nL=len(L) #nL stores length of left sorted array
nR=len(R) #nR stores length of Right sorted a... |
ea4a5dcfc3fe8a85b5b903573398abc0513537a6 | jinal360/Project-111 | /z_score.py | 3,544 | 3.8125 | 4 | import statistics
import csv
import random
import pandas as pd
import plotly.figure_factory as ff
import plotly.graph_objects as go
df = pd.read_csv("medium_data.csv")
data = df["temp"].tolist()
population_mean = statistics.mean(data)
def random_set_of_mean(counter):
dataset = []
for i in range(0... |
19882d4f8692d11063670711552a52526d5f7446 | JLtheking/cpy5python | /hbl/f.py | 468 | 3.5625 | 4 | import random
class Player():
def __init__(self, username, score):
self.username = username
self.score = score
def randomName():
nameLength = random.choice(range(3,8))
name = chr(64 + random.choice(range(1,27)))
for i in range(1,nameLength):
name += chr(96 + random.choice(range(1,27)))
re... |
d11c4fbdc6a42bcefc039f726ab6997ea47adb70 | gslmota/Programs-PYTHON | /Exercícios/Mundo 3/ex099.py | 320 | 3.609375 | 4 | # Programa que verifica se o site esta acessivel
import urllib
import urllib.request
# Programa principal
try:
site = urllib.request.urlopen('http://www.pudim.com.br')
except urllib.error.URLError:
print('Ocorreu um erro! O site não esta acessível!')
else:
print('Deu tudo certo! O site está acessível!') |
c88cfe54f48c76ff860b5d9e01b7d5cc8e3af42d | romanokhrimchuk/testRoman | /write documentation/manipulate_csv.py | 3,990 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
from datetime import datetime
def create_dummy_csv(outname_csv='the_csv', output_path=None,
random_seed=None, columns=["test1", "test2"... |
b2a8a028bc2abebeeb01f1f5bc3466b3b70caa61 | GuuMee/ExercisesTasksPython | /6 Dictionaries/_134_unique_characters.py | 711 | 4.53125 | 5 | """
Create a program that determines and displays the number of unique characters in a
string entered by the user. For example, Hello, World! has 10 unique characters
whilezzzhas only one unique character. Use a dictionary or set to solve this problem.
"""
# Compute the number of unique characters in a string using a ... |
f0d51b14a01e67f3774c1999c69255f074be3049 | Bulgakoff/Exceptions07 | /lesson01_TerOp/ter_op.py | 214 | 3.84375 | 4 |
is_has_name = True
name = 'Max' if is_has_name else 'Bob'
print(name)
one = True
number = 1 if one else 56
print(number)
is_russian = False
print('Здорово братан ' if is_russian else 'How do you do')
|
193c434d75fecaecc4502dfa302e13c11d079056 | theoctober19th/tn-python-django-bootcamp-5 | /day1/assignments/1.py | 139 | 3.84375 | 4 | nums = [int(x) for x in input("Enter a list of numbers").split()]
for num in nums:
if num%2==1 and num<14:
print(num, end=' ') |
09d464f79dbe9cc140f4b459df54e3ed10bd8d8e | meenakshi-madan/dailyprogrammer | /call_forwarding.py | 1,409 | 3.546875 | 4 | """
Developer: Meenakshi Madan
Solution to http://www.reddit.com/r/dailyprogrammer/comments/1g09qy/060913_challenge_127_intermediate_call_forwarding/
"""
from collections import defaultdict
from operator import itemgetter
#Dictionary describing whose calls to forward to whom
forward_dict = {}
#List that will conta... |
33f3c37a71cb688b74e67259666b7f80b0f50bc3 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2232/60716/313059.py | 488 | 3.546875 | 4 | num = int(input())
arr = list()
for i in range(num):
strs=input().split()
tl = [int(j) for j in strs]
arr.append(tl)
if num==5:
print(1)
print(2)
elif num==33:
print(1)
print(1)
elif num==13:
print(13)
print(13)
elif num==10:
if arr[0]==[2, 3, 4, 5, 6, 7, 8, 9, 10, 0]:
pr... |
df331ad7b6c2e3f400fb2ba58fbb12dc2836efe4 | TheMikeste1/Advent-of-Code-2020 | /Day13/crt_solver.py | 1,988 | 3.6875 | 4 | def egcd(a: int, b: int) -> tuple:
"""
Calculates the Greatest Common Denominator for the
given a and b using Bézout's identity:
ax + by = gcd(a, b)
When a and b are coprime (gcd = 1), x will be a (mod b)'s inverse
and y will be b (mod a)'s inverse.
"""
# if 0 is the b, the answer w... |
404323ae4f7fa6954adb84cd2c7772fd1061705d | Priyansh-Kedia/MLMastery | /27_ordinal_onehot_encoding.py | 2,604 | 4.375 | 4 | # A numerical variable can be converted to an ordinal variable by dividing
# the range of the numerical variable into bins and assigning values to each
# bin. For example, a numerical variable between 1 and 10 can be divided into
# an ordinal variable with 5 labels with an ordinal relationship: 1-2, 3-4,
# 5-6, 7-8... |
ce55a4028314d514e4b202f28408ce99dfeabd44 | GyutaeSon/hello-world | /noc_06.py | 758 | 3.96875 | 4 | """
“paraparaparadise”と”paragraph”に含まれる文字bi-gramの集合を,
それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.
さらに,’se’というbi-gramがXおよびYに含まれるかどうかを調べよ.
"""
a = "paraparaparadise"
b = "paragraph"
def ngram(n, bun) :
res = []
for it in range(len(bun)) :
if it + n > len(bun) :
return res
res.append(bun[it :... |
5743bce19c63688e4396e9caf11939662bbaa1c4 | Medusa31/Traffic-Simulation | /TrafficSimulation.py | 9,063 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 12 18:00:26 2016
@author: Carl
"""
#keyboard shortcuts:
#indent/unindent: tab/shift+tab
#comment/uncomment: ctrl+1
#file created to store code that works
import numpy as np
import numpy.random as rnd
import matplotlib.pyplot as plt
import random
... |
39920d0607606c0373215c3bba5c292e9df83e74 | haringd/EGR680_FPGA_Labs | /test1tktu.py | 3,383 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 31 12:37:36 2018
@author: schwa
"""
# This is a Python program that uses two modules, the turtle and tkinter modules.
# When a module is used in Python you need to import it into your program.
import turtle
import tkinter
# Next, the main function is defined. Defining a... |
508c82c18ba44995c1098a8918574571c9bab85b | hnkien/DailyCoding | /DailyCoding114.py | 823 | 4.4375 | 4 | # This problem was asked by Facebook.
#
# Given a string and a set of delimiters, reverse the words in the string while maintaining the relative order of the delimiters. For example, given "hello/world:here", return "here/world:hello"
#
# Follow-up: Does your solution work for the following cases: "hello/world:here/", ... |
ea3ce1c59ddac982b3536057a1125462385b5cf8 | RohanDeySarkar/DSA | /strings/longestBalancedSubstring/longestBalancedSubstring.py | 870 | 3.546875 | 4 | def longestBalancedSubstring(string):
maxLength = 0
for i in range(len(string)):
for j in range(i, len(string) + 1):
if isBalanced(string[i : j]):
currLength = j - i
maxLength = max(maxLength, currLength)
return maxLength
def isBalanced(string):
stack = []
for char in string:
if char == "(":
s... |
c2668d1177646bd13e1c48f9e7cfcfe88c6ababb | raghuboreda/examplecode | /python/careercup/sumsquares.py | 831 | 3.78125 | 4 | from math import sqrt, ceil
def sumSquares( c ):
"""
10 = 3^2 + 1^2
find number of ways which c
can be written as combination of two squares
"""
x = int(ceil(sqrt(c)))
i = 0
while( i <= x ):
sqsum = i**2 + x**2
if sqsum == c:
print i, x
i = i + 1
... |
2f61da9535cb163afc6d83283ef3d7cc2d163369 | nenusoulgithub/LearnPython | /求知学堂/day4_02-初识函数.py | 314 | 3.875 | 4 | # 函数定义
def printInfo(name, height, weight, hobby, pro):
print("%s的身高是:%d" % (name, height))
print("%s的体重是:%d" % (name, weight))
print("%s的爱好是:%s" % (name, hobby))
print("%s的专业是:%s" % (name, pro))
printInfo("小明", 173, 70, "游戏", "计算机")
|
8178d11a09f8a4bef4c63f7f8af227a34fa4865f | naray89k/Python | /DeepDive_1/5_Function_Parameters/star-args.py | 2,477 | 4.59375 | 5 | #!/usr/bin/env python
# coding: utf-8
# ### \*args
# Recall from iterable unpacking:
a, b, *c = 10, 20, 'a', 'b'
print(a, b)
print(c)
# We can use a similar concept in function definitions to allow for arbitrary numbers of **positional** parameters/arguments:
def func1(a, b, *args):
print(a)
print(b)
... |
3c93563cfbad10c594c1067e24337205cb624d24 | walshbr/git-debugging-practice | /pirates.py | 409 | 4.09375 | 4 | # prompt the user to find out if they are a pirate. If they are, respond accordingly.
# what is the code supposed to do? work line by line to troubleshoot.
# each time you think you've made a correction and gotten it closer, push those changes up.
greeting = input("Hello, possible pirate! What's the password?)
if gre... |
e7e6689a8adbb310974790f4dfe73f74d2da9e8e | thanos73k/CoTe | /2884.py | 174 | 3.71875 | 4 | hour, minute = map(int,input().split())
if minute>=45:
print(hour,minute-45)
else:
if hour==0:
print(23,minute+15)
else:
print(hour-1,minute+15) |
4ad373010f0b929fecc8aae0068c4bad59280754 | sagarnikam123/learnNPractice | /tutsPlus/gettingStartedwithPython/2_stringsSlicing.py | 634 | 3.6875 | 4 | #! /usr/bin/env python
var1 = "this is a string"
print var1
var2 = "and another"
print var2
print var1+var2
var3 = var1+var2
# multiline strings
multiline = "This is a \n\
multiline string "
print multiline
multilie = """this is also
a
multiline string"""
print multiline
# comments
#fsdfsdf
# indexing
pri... |
93671e640537a1ea1ce85fcbfdb1e0368ee71f1f | riteshsingh1/learn-python | /functions.py | 173 | 3.96875 | 4 | # Functions are defined by `def` keyword
# Function should be all lowercases
def say_hi(name):
return "Hi "+name+" !"
data = input("Enter Name ")
print(say_hi(data)) |
263e3c58d14fff13bcd8856c581d68919cb118e2 | agrammatin/solution_lab | /lab_6/task_6_1.py | 5,262 | 3.9375 | 4 | """
Game "Catch the ball"
"""
import pygame
import math
import sys
from pygame.draw import *
from random import randint
# It is library initialization after import
pygame.init()
B_GROUND = (200, 200, 200)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
MAGENTA = (255, 0, 255)
CYA... |
cedf31a8231b645ade18b6aa9d81afd3d03bfee3 | omeinsotelo/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 250 | 3.609375 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
new_mtx = [i[:] for i in matrix]
index = 0
for row in new_mtx:
for col in row:
row[index] = col * col
index += 1
index = 0
return new_mtx
|
f352871cf9d473ec1a9094f701adf3601b50b31c | yangyang0126/PythonLearning | /GUI/tkinter/4_Button.py | 499 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 8 09:02:59 2020
@author: Yenny
"""
from tkinter import *
from tkinter.messagebox import showinfo
import datetime
def clicked():
day = datetime.datetime.now().strftime('%d %b %Y')
time = datetime.datetime.now().strftime('%H:%M:%S %p')
text = 'Day:'+day+'\n'+'... |
1206e6c9ef822e0cc79c3d89e49bb37e00135195 | bettyariyani/Python-Beginner | /문자열 포맷팅 연습.py | 343 | 3.609375 | 4 | wage = 5
exchange_rate = 1142.16
rate = wage * exchange_rate
print("%d시간에 %d%s 벌었습니다." %(1, wage * 1, "달러"))
print("%d시간에 %d%s 벌었습니다." %(5, wage * 5, "달러") )
print("%d시간에 %d%s 벌었습니다." %(1, rate, "달러"))
print("%d시간에 %d%s 벌었습니다." %(5, 5 * rate, "달러")) |
1a92269833a928fa76492271ccc7700b00ea4db8 | Neoplatonist/cam-test | /005.py | 367 | 4.28125 | 4 | # 1. Define an empty variable named "my_list".
# 2. Define an empty list with the variable name "your_list".
# 3. Convert "my_list" from NoneType to a list.
# Then using a loop fill "my_list" with numbers 0 - 9.
# 4. In the simplest way possible, sort "my_list" from least to greatest.
# 5. Using "my_list"... |
9d5c5b165cb48853763c47504c2765ef9dc8d3f6 | wchengsir/Python | /15_List.py | 546 | 3.984375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
t = ['a','b','c','d','e']
print t[1:3]
print t[:4]
print t[3:]
print t[:]
print
list = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # 输出完整列表
print list[0] # 输出列表的第一个元素
print list[1:3] # 输出第二个至第三个元素
print... |
2a57b96bddd1bd11c8fa24461b53b741324c1833 | sagarkukreja/Python-and-Data-Structures | /Lab9/holicow.py | 4,653 | 3.625 | 4 | __author__ = 'jrl'
__author__ = 'sk'
"""
CSCI 603, Lab 9
File: holicow.py
Language: python3
Author: Justin Lad jrl8632@g.rit.edu
Author: Sagar Kukreja sk3126@rit.edu
"""
from graph import Graph
from sys import argv
class holicow:
"""
drives the exploding paint balls simulation
:slot: field (Graph): graph... |
12557eef3465e2d4111fea4dd8a5b887eb5bc3ea | laurieroy/python-codeAlongs_books | /guessNo.py | 555 | 4.03125 | 4 | #!/usr/local/bin/python3
"""Guess number between 1-10."""
def main():
from random import randint
secret = randint(1,10)
print("Welcome!")
guess = 0
while guess !=secret:
g = input("Guess the number: ")
guess = int(g)
if guess == secret:
print ("You win!... |
671732c91adc77e66493abb1733485e357481fd9 | pranavkakkad/CTCI-practice | /Arrays And String/1.6_StringCompression.py | 697 | 3.546875 | 4 | class StringCompress:
def __init__(self, str1):
self.str1 = str1
def compression(self):
compr_str = []
count = 0
for i, j in enumerate(self.str1):
if i != 0 and self.str1[i] != self.str1[i - 1]:
compr_str.append(self.str1[i - 1] + str(count))
... |
5061984f7f6da35469158c064e09dcd56ee14d17 | acmbo/MarketSimulation | /market/Sample.py | 3,340 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 3 14:09:52 2019
@author: Stephan
"""
from market import Marketactor, Marketplace as Market, visualization as mv
if __name__ == '__main__':
'''This is a sample, how to set up a market and add actor to the market, which interact with each other.+
After Simul... |
ee8626b2d0f3cb93d7c13d215993768dfe2574b5 | CodedQuen/The-Python-3-Standard-Library | /Ch01/01_04/01_04_Start.py | 185 | 3.71875 | 4 | # Range -> range instance that holds all nums counting by one between 0 and first input
# List -> lists numbers from the inputted tuple
numbered = range(30)
print(list(numbered))
|
0fe1eee27af21593e411e46f1d10a698cec29d43 | kirtivr/leetcode | /Leetcode/22.py | 975 | 3.65625 | 4 | class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
n = n * 2
if n == 0:
return []
parens = []
def isValid(current):
stk = []
for ch in current:
if ch ... |
c6235380d7af20e146ed50d223e0c3a7cbf57b9e | hilings/leetcode | /python/025.py | 1,472 | 3.640625 | 4 | # 025
# Reverse Nodes in k-Group
# 2015-05-02
#####################################################
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} head
# @param {integer} k
# @return {Li... |
729943175be7c0dd980de171a0ba1556b1b16db7 | alexandre146/avaliar | /media/codigos/21/21sol394.py | 82 | 3.609375 | 4 | n=int(input())
m=int(input())
while n<=m:
if n%2!=0:
print(n)
n+=1 |
9ecaf8ccd6871f40f40d3d406e03984e6d6cd646 | LORDBABUINO/FGAme-1 | /src/FGAme/mathutils/matrix.py | 10,915 | 4.3125 | 4 | # -*- coding: utf8 -*-
from FGAme.mathutils import Vector, dot
from math import sqrt, sin, cos
SQRT_2 = sqrt(2)
number = (float, int)
__all__ = ['Matrix', 'RotMatrix', 'asmatrix']
class Matrix(object):
'''Implementa uma matriz bidimensional e operações básicas de álgebra
linear
Example
-------
... |
690ebf06a44f0737ca7996a9132e2d0364597af8 | rajo999/web2-sql-data-base | /main.py | 681 | 3.828125 | 4 | from smartninja_sql.sqlite import SQLiteDatabase
db = SQLiteDatabase("hiking.sqlite")
db.execute("DROP TABLE;")
db.execute("CREATE TABLE User(id integer primary key autoincrement, name text, age integer);")
db.print_tables(verbose=True) #ta verbose v oklepaju je, da izpiše datile tabele
#db.execute("INSERT INTO User... |
ad6f888acb5f61750d75fa67c55f39f2ba5de57a | vincently916/python | /input.py | 386 | 3.890625 | 4 | import datetime
name = str(raw_input("What is your name "))
age = int(raw_input("What is your age "))
repetition = int(raw_input("Enter the number of time to print the messages: "))
noOfYears = 100 - age
today = datetime.date.today()
currentYear = today.year
futureYear = currentYear + noOfYears
print repeti... |
e71f091e29d6c3be66e5714f2f424299779cb401 | kazma89/Taller_RPi | /reto1.py | 343 | 4.09375 | 4 | for num in range(0,3,1): #hacer un conteo de 2 en 2 hasta 10
a = [1,2,3,4,5,6,7,6,5,4,3,2,1] #Esto es un arreglo
#Aqui tenemos un ciclo FOR con una sentencia IF dentro!
for elemento in a:
if elemento == max(a): #Mira por el número más alto en a
print(elemento*'=')
print('Secuencia numero {}' .format(num+1))
... |
c86d318d5430623988dee62e25343568f422b9af | Arosebine/PythonJobs | /day1/chapter2/input.py | 104 | 4.03125 | 4 | num1 = int(input('Enter number 1: '))
num2 = int(input('Enter number 2: '))
add = num1 + num2
print(add) |
65c47be4309b06446759123b2dcb1028061d608f | vPastor/FASTA_READER_1 | /main.py | 187 | 3.640625 | 4 | import sys
if (len(sys.argv)>2 or len(sys.argv)<2):
print ('Numero de argumentos invalidos')
else:
for linea in open(sys.argv[1]):
if (('>') == (linea[0])):
print (len(linea))
|
b6e3cc2d139ae347eefb72b322076bdbfd2e43a9 | rachaelheiss/mintor | /Plot.py | 6,111 | 3.765625 | 4 | '''
MINTOR
Plot.py
J. Card, R. Heiss, M. Mora Sanchez, B. Tou
Northeastern University MIE Capstone Spring 2018
This script reads .csv data files for the MINTOR project. The given epoch
timestamps are translated into elapsed time. Four plots are generated to
visualize the accelerometer and gyroscope for each hand.
'''
... |
8361b32facb2165a07c5c49951b90cf98132bcb0 | luckkyzhou/leetcode | /1_3.py | 323 | 3.5625 | 4 | # -*- coding: utf-8 -*-
def twoSum(nums:list,target:int):
hashmap = {}
for index,num in enumerate(nums):
hashmap[num] = index
for i,num in enumerate(nums):
j = hashmap.get(target - num)
if j != None:
return [i,j]
if __name__ == '__main__':
print(twoSum([2,7,11,15],... |
a551e0fec90cfe5037f5337b30fb00af336fc4e3 | simonwrafter/FMN050 | /ex5/garden_1.py | 708 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 8 10:28:12 2015
@author: claus
"""
def read_acc_data(file='garden.txt'):
r"""
reads coordinates from a file (default: garden.txt)
and returns three lists:
t time (sec)
x acceleration in x-direction $(m/sec^2)$
y acceleration in y-... |
1e61fbc08528e95568fdaa05316533b9119f6769 | walkershashi/myCoders | /leetCode/remove duplicates from sorted list 2.py | 934 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
cntr =... |
db356bb838e93ea83a1445ca303a6829fb8a2f71 | JerryHu1994/LeetCode-Practice | /Solutions/57-Insert-Interval/python.py | 1,067 | 3.6875 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[... |
0a08a6603feae178f43dc7aa09932955261663b8 | charlieb954/code_snippets | /python/decorator_timer_syntax.py | 416 | 3.625 | 4 | # DECORATOR
# function must be called in the decorator else it won't execute
from time import time
def timer_decorator(func):
def inner(*args):
start = time()
func(*args)
end = time()
return f"Function took {end-start} seconds to execute"
return inner # inner must be returned el... |
d5f98512062c043ae8b393e682ee92fc38f632fc | ArrayZoneYour/LeetCode | /031/Next Permutation.py | 1,086 | 3.625 | 4 | # /usr/bin/python
# coding: utf-8
class Solution:
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if len(nums) > 1:
swap_index_left = -2
while abs(swap_index_left) <= l... |
dc8b419f5bfbbbb8ec5d4b2ea5d081f5f96de8a6 | Ang3l1t0/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 297 | 3.796875 | 4 | #!/usr/bin/python3
""" My list
"""
class MyList(list):
"""print_sorted
Arguments:
list {list} -- [create a new sorted list]
"""
def print_sorted(self):
new_list = []
new_list = self.copy()
new_list.sort()
print(new_list)
|
94bda2d48be84b70ad2088e050aef50dc8b78a43 | ekane3/pandas | /mod1.py | 840 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
@author: EKANE3
Module 1 : Scrapping
"""
import pandas as pd
#Import the csv into a DataFrame
#url:https://cadastre.data.gouv.fr/data/etalab-dvf/latest/csv/2020/full.csv.gz
data = pd.read_csv("D:/full.csv")
df = pd.DataFrame(data)
#Add a column myName using your name.
df['myName'] = 'EKAN... |
dfd38a4370b146cf90969222dcdc0b53c8137899 | vibhor-vibhav-au6/APJKalam | /week10/day03.py | 590 | 4.09375 | 4 | '''Binary to decimal'''
def binaryToDecimal(num):
res = 0
base = 1
while(num):
lastDigit = num % 10
num = int(num / 10)
res += lastDigit * base;
base = base * 2
return res
'''Write a function to perform XOR between two positive integers:do not use the xor operator.
'''
def ... |
79fc5b4168b020e2441eabab6b5dbd90a81a31b4 | afaalevao/RestaurantSelector | /RestaurantSelector.py | 3,508 | 4.03125 | 4 | '''
Andrew Faalevao
Random Restaurant Selector
Python Program to select random restaurant given a location
'''
import bs4
import urllib.request as request
import random
import secrets
import tkinter
# class to store Restaurant information
class Restaurant:
def __init__(self, name, rating, price):
self.n... |
324f004133962327c125e7bc99b50a659036e9f3 | pilihaotian/pythonlearning | /leehao/learn67.py | 146 | 3.765625 | 4 | # 异常 exception
a = 2
b = 0
try:
print(a / b)
except ZeroDivisionError:
print("除数不能为0")
else:
print(a / b)
print("END")
|
2f77a491faa86d2e13f4e78f9c24371ac04004a9 | minuso/leetcode | /0985/sumEvenAfterQueries.py | 639 | 3.625 | 4 | def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:
is_even = [1 - (n&1) for n in A]
even_sum = 0
for i, n in enumerate(A): even_sum += n*is_even[i]
res = []
for [val, i] in queries:
A[i] += val
from_even = is_even[i]
to_even = is_even... |
5f02b07d1a1cc3fdc68086c189d971cad4f9433e | AlSavva/Python-basics-homework | /homework5-5.py | 2,320 | 4.125 | 4 | # Создать (программно) текстовый файл, записать в него программно набор чисел,
# разделенных пробелами. Программа должна подсчитывать сумму чисел в файле и
# выводить ее на экран.
# Вариант №1 ввод данных пользователем
try:
with open('text_result_5.txt', 'w', encoding='utf-8') as out_file:
chek =... |
00f0a49b26b0367ab28c26bff4ec6a466395cb68 | jercas/PythonModuleLearning | /argparseTest/test.py | 882 | 4.34375 | 4 | # coding=utf-8
# By JerCas
# 测试argparse,选择参数
import argparse
descStr = "This program is a test example of how to use argparse to analyze command"
usageStr = "Test usage"
parser = argparse.ArgumentParser(usage=usageStr,description=descStr)
parser.add_argument('-e', "--echo", required=False, help="echo the string you ... |
3ce6883e6f1192a9f685ead0c89de696fceeee73 | magikitty/GetPythonBookPractice | /07.Strings/7.StringIntro.py | 1,806 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 22 22:52:14 2019
@author: elina
These are Chapter 7 Qs
"""
new_line = "\n"
# Quick Check 7.3
print("Quick Check 7.3")
print("hey there"[1])
print("TV guide"[2])
code = "L33t hax0r5"
print(code[0])
print(code[-4])
print("bananaboo"[3])
print("bananaboo"[-3])
# Quick Ch... |
0bb1cc957d138eb1052ed4d647b654e1d52a3316 | semuel1/whiteboard-wednesday-array-helpers | /solution.py | 536 | 4.3125 | 4 | #sum of negatives
#write a function that takes in a list of numbers that gives you back a tuple or list with two items
#the sum of all the negative numbers in the list
# the count of all the positive numbers
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]
def count_positives_sum_negatives(arr):
nu... |
2875db2603c0ffda098201df9545dd22d83c5968 | gao634209276/myPython | /modules/base/control_flow/if.py | 1,361 | 4.3125 | 4 | # coding=utf-8
# if语句
# if语句的格式用法:
"""
if 是这样:
执行该部分语句
执行该部分语句
执行该部分语句
执行该部分语句
执行该部分语句
elif 或者是这样:
执行elif部分语句
执行elif部分语句
执行elif部分语句
执行elif部分语句
执行elif部分语句
else 或者以上情况都不是:
执行该部分语句
执行该部分语句
"""
# 一种情况的if用法
a = 8
if a == 8: # 这里的等号注意是==
print "hello"
if a != 8:
print "heh... |
d31e8eb36af9af0139b05d23b6c556ddc2b6eba5 | Omkarkale0002/Developer | /php/01_Opr.py | 666 | 3.890625 | 4 | a,b,c=2,3,30
c=a+b
print"line 1 - value of c is",c
#Arithmetic
c=a-b
print"line 2 - value of c is",c
c=a*b
print"line 3 - value of c is",c
c=a/b
print"line 4 - value of c is",c
c=a%b
print"line 5 - value of c is",c
c=a**b
print"line 6 - value of c is",c
... |
acb6b2bbfb437816ef8120e043bb14700e6d2e88 | wsilva32/poly_decomp.py | /poly_decomp/poly_decomp.py | 18,709 | 3.78125 | 4 | #!/usr/bin/env python
from __future__ import division
import math
def lineInt(l1, l2, precision=0):
"""Compute the intersection between two lines.
Keyword arguments:
l1 -- first line
l2 -- second line
precision -- precision to check if lines are parallel (default 0)
Returns:
The intersec... |
64b00f39c05a1817a65803be03e8ec215955154a | feiyanshiren/myAcm | /leetcode/t000088_2.py | 497 | 3.9375 | 4 | from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
nums1[m:m+n] = nums2 # 将nums2合并到nums1中
nums1.sort() # 直接使用内置排序方法sort
... |
946c4ee37d95421415c09ec78c1e86b3b1feb32b | shay2501/ThinkPython | /ch_6.py | 971 | 3.96875 | 4 | #As an exercise, write a compare function takes two values, x and y, and
#returns 1 if x > y, 0 if x == y, and -1 if x < y.
def value_compare(x, y):
if(x > y):
return 1
elif(x == y):
return 0
elif(x < y):
return -1
def is_between(x, y, z):
return x <= y <= z
#exercise 2
def ac... |
7165cc785dbc6f90c379f3e3a9b0cfe58318ef73 | Mayuri0612/Data_Structures-Python | /Trie/TrieImplement.py | 1,075 | 3.890625 | 4 | class TrieNode:
def __init__(self):
self.child = {}
self.end= False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self,word):
current = self.root
for w in word:
if w not in current.child:
current.child[w] = TrieNode()
... |
9ae1f06f8b72fe4efd63ccabdde2c30791faf21f | UnaStankovic/ProteinNucleotideSequenceAlignment | /second.py | 2,783 | 3.671875 | 4 | #This file contains alignment of protein and nucleotide sequences.
#Firstly, we recognize if sequence is a nucleotide or a protein.
#Secondly, from nucleotide sequences we extract potential coding subsequence (from START to STOP codon).
#Thirdly, codons are translated into aminoacids.
#Finally, protein sequences are... |
1fe9a1c2e87c6529745d18ba4169cbe822903623 | austrafin/mat-02660-pc-harjoitus | /pc_harjoitus.py | 5,373 | 3.640625 | 4 | from copy import deepcopy
from itertools import product
def xro2Matrix(omega, alpha):
'''
This function takes omega sets and the alpha
values and produces an augmented binary matrix
'''
# Collect all of the variables in omega
allVariables = {
var for key, variables in omega.items() for... |
5e132fc89bfee2d04932013b677ebaa2aa676637 | BoyceLee/Pottery_Templates | /draw_a_polygon.py | 865 | 3.765625 | 4 | from save_to_svg import saveImg
import turtle
window = turtle.Screen()
window.bgcolor("white")
turtle.screensize(canvwidth=5000, canvheight=5000, bg=None)
def draw_a_shape(new_turtle, number_of_sides, angle, length):
new_turtle.pendown()
new_turtle.left(angle)
for item in range(0,number_of_sides):
new_turtle.for... |
d7f0314bb781d49dc0caa5cbcd2d55b401048650 | AntB95/ML | /Project 1/Polo/functions.py | 6,756 | 3.671875 | 4 | import numpy as np
import matplotlib.pyplot as plt
from implementations import *
""" GENERAL FUNCTION """
# Sigmoid function that bring back x in the interval [0, 1]
def sigmoid(x):
s = 0.5 * (1 + np.tanh(0.5*x))
return s
# Given a matrix 'x' and the degree, return the polynomial expansion of
# the matrix.
... |
19e57aab6bb05cc1ad3879a29780f4b4bdd5eaea | CJHdreamore/Udacity_learning | /Algorithm_DataStructure/BST.py | 2,665 | 4.21875 | 4 | # Binary Search Tree
# This shows us we can achieve our goal either by an iteration ( while function)
# or by a recursive function.
class Node(object):
def __init__(self,value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self,root):
sel... |
64307594a1183945c02edf6c7b8ca65c52e9c010 | rsazizov/mit-ocw-6.0002 | /lecture4/dice.py | 346 | 3.5625 | 4 | import random
random.seed(42)
def roll_die():
return random.choice(range(1, 6 + 1))
def run_sim(goal, n):
total = 0
for _ in range(n):
result = ''
for _ in range(len(goal)):
result += str(roll_die())
if result == goal:
total += 1
return total / n
print('Estimated prob: ', r... |
f4257d0069846d1aba6af2ae21daeb8f69e2ca87 | iggy-pigy/Algorithms-in-Python | /palindrome/_init_.py | 447 | 3.546875 | 4 | import re
def isPalindrome(s):
def toChar(s):
s = re.split("[^a-zA-Z\\d]+", s)
s = ''.join([i for i in s if len(i) > 0]).lower()
ans = ""
for c in s:
if c in "abcdefghijklmnoprstuvwxyz":
ans = ans + c
return ans
def isPal(s):
if len(... |
e21c656f30cae2bcdaaca7f8f790cb3085cf6ec6 | ghilbing/Ejemplos | /searchMatrix.py | 896 | 3.59375 | 4 | def searchMatrix(A, B):
y = len(A)
x = len(A[0])
start = 0
end = x * y - 1
while start <= end:
mid = start + (end - start) // 2
if A[mid // x][mid % x] == B:
return 1
elif A[mid // x][mid % x] < B:
start = mid + 1
else:
end = mid - ... |
2c78376e77fda93027304ca10a232d2e8defdd1d | msaei/coding | /LeetCode/Top Interview Questions/Strings/Longest Common Prefix.py | 576 | 3.609375 | 4 | #Longest Common Prefix
#https://leetcode.com/explore/featured/card/top-interview-questions-easy/127/strings/887/
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
res = ""
if len(strs) == 0:
return ""
i = 0
while True:
if i >= len(strs[0]... |
0ceeee11261696f7eaa00d0de832267211b3a171 | ed-learner/Python | /objects and class/inheritance_multiple_04.py | 772 | 4.28125 | 4 | class Parent:
def __init__(self):
self.parentname = "Parent"
print("Parent properties")
class Child:
def __init__(self):
self.childname = "son"
print("Child properties")
# We specify all parent classes as
# comma separated list in bracket.
class grandchild(Pare... |
b9d8ddf9add486801234cd48a516370b1be20c10 | steadydoer/problem-solving | /programmers/level3/12938/solution.py | 507 | 3.75 | 4 | # Programmers Coding Test Practice
# Level 3
#
# https://programmers.co.kr/learn/courses/30/lessons/12938
#
# ==============================================================================
def solution(n, s):
if n > s:
return [-1]
default = s // n
answer = [default for x in range(n)]
for i... |
886fc4a531c5ac84277199f149a7ca76ccf776c2 | DemianAvila/Demian_Avila_1358 | /DoubleQueue.py | 1,281 | 4.34375 | 4 | #implementar cola de prioridad acotada y no acotada, ademas de la cola doble
"""class Queue:
def __init__(self):
self.__data=[]"""
class DoubleQueue:
def __init__(self):
self.__data=[]
def add_last(self, value):
self.__data.append(value)
def add_first(self, va... |
0cbdf1639a53b853d56a4c9eca4c8d7e1569cc7c | jinurajan/Datastructures | /LeetCode/bloomberg/smallest_range_I.py | 1,030 | 3.828125 | 4 | """
Smallest Range I
You are given an integer array nums and an integer k.
In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i.
The score of nums is the diffe... |
fa2c7462b3677f958d5864d577dd190ab9f71599 | ShellCase/Python_Practice | /gessgame.py | 606 | 3.765625 | 4 | #! usr/bin/python3.5
import random
def inputa():
print("******WELCOME******")
print("How many times do you wish to play?")
num=int(input())
return num
def process():
num=inputa()
sec_no=2
#sec_no.random()
total=0
z=0
while True:
if z<=num:
break
z=z+1
print(str(num))
print("Enter your lucky numb... |
7148c25a08df2398c4ac1190cf002dde11b0dd2a | Ricefrog/adventOfCode2020 | /day20/day20.py | 14,281 | 3.625 | 4 | #! /usr/bin/python
import itertools
from copy import deepcopy
def printTile(rows):
for row in rows:
for ch in row:
print(ch, end='')
print()
def flip(rows):
#print('before flip:', rows)
flipped = []
for row in rows:
flipped.append(row[::-1])
#print('after flip:', flipped)
return flipped
def rotateRig... |
e97afe58a103d030a45380acf46f5216fb6f422e | imranasq/DataStructPy | /Factorial.py | 172 | 4.09375 | 4 |
def factorial(a):
if a == 0:
return 1
else:
return a * factorial(a-1)
tg = int(input("Enter target number: "))
fact = factorial(tg)
print(fact)
|
f5a2ec6a0e5594a4bef0b5faffe67f977a3141e5 | psbarros/Variaveis3 | /2019-1/230/users/4044/codes/1763_2102.py | 156 | 3.59375 | 4 | from numpy import*
vec = array(eval(input("Digite numeros inteiros: ")))
i = 0
while (i < size(vec)):
if (vec[i]%2 != 0):
vec[i] = 0
i += 1
print(vec) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.