blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0c504a5033fdbd41f85146e2e0c2dd0f304220fc | lisapearl/compatibility-metphon | /OT/preAnalysis.py | 2,958 | 3.609375 | 4 | #!/usr/bin/python
from __future__ import division
import collections
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("file", help="The name of the Brent data file used for either the OT\
or the parametric systems. Usually called brent.data")
args = parser.parse_args()
# allSyllables is a dict... |
fc9f2df4749ca75e462abfbe104545e0510e1362 | savva-kotov/coursera-python-basics | /Количество слов.py | 584 | 4.1875 | 4 | """
Дана строка, состоящая из слов, разделенных пробелами. Определите, сколько в ней слов.
Формат ввода
Вводится строка.
Формат вывода
Выведите ответ на задачу.
Тест 1
Входные данные:
Hello world
Вывод программы:
2
Тест 2
Входные данные:
Hello
Вывод программы:
1
Тест 3
Входные данные:
q w e
Вывод программы:
3
"""
... |
31fd7020f09ff3dd1a2459b005602a774a29869e | Alialmanea/Data-mining | /Apriori Algorithm.py | 436 | 3.5 | 4 | #To Read cvs file
import pandas as pd
# Read cvs file.
data = pd.read_csv('store.csv',header=None)#put the cvs file(Excel file) here
# data [['MILK','Bread'] , ['TEA','JAM'], ...]
t = []
for i in range(0,len(data)):
t.append(str(data.values[i][0]).split(","))#
from apyori import apriori
result = list(apr... |
2a7f4765d47dec15ce2f9fcdc5dcd72bb849bc4d | GivemeHam/CodingTest | /src/programmers/level2/짝지어제거하기.py | 330 | 3.546875 | 4 | from collections import deque
def solution(s):
que = deque(s)
stack = []
while que:
stack.append(que.popleft())
if len(stack) > 1:
if stack[-1] == stack[-2]:
stack.pop()
stack.pop()
if stack:
return 0
return 1
print(solution('... |
1158d8fe0cb8472b8fce1cf3b5439cb452a9221a | hjhjw1991/leetcode | /python/179_Largest_Number_improvement_needed.py | 2,909 | 3.515625 | 4 | # coding=utf-8
import unittest
class Solution:
def solve(self, nums):
return self.largestNumber(nums)
# @param {integer[]} nums
# @return {string}
def largestNumber(self, nums):
def lt(str1,str2):
l1=len(str1)
l2=len(str2)
if l1==l2:
... |
75456e3124a52502abcb6ee7a5c94fe9f1fee8a2 | alukinykh/python | /lesson3/6.py | 1,059 | 4.40625 | 4 | # 6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
# но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
# Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
# Каждое слово состоит из латинских бук... |
5893b008823533643ef7dc0aa3312cabd3594856 | fufd/Python | /Source Code/切片练习.py | 236 | 3.828125 | 4 | def trim(s):
if s[:1] != " " and s[-1:] != " ":
return s
elif s[:1] == " ":
s = s[1:]
return trim(s)
elif s[-1:] == " ":
s = s[:-1]
return trim(s)
a=" cc "
print(a)
d=trim(a)
print(d) |
a5d8d5f8e3c21c30ced954f46498a76cbf300c4e | thaisviana/python_p | /lista1/q3.py | 153 | 3.75 | 4 | t = [1, 2, 3,4, 5, 6,7, 8]
accumulador = 0
resultado = []
for i in t:
accumulador += i
resultado.append(accumulador)
print(t)
print(resultado)
|
fdfa3503c09db5294669a1dca9cd9d40fd8580a2 | CaptainPMP/BasicPythonGUI | /log_basic1.py | 975 | 3.765625 | 4 | Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> print ("Hello World")
Hello World
>>> name = 'Robert'
>>> print(name)
Robert
>>> type(name)
<class 'str'>
>>> name.upper()
'ROBERT'
>>> from tkinter... |
fb1609856fcfbe74e2cd0c4996afbff9e4fa47fa | fabriciogonzalez06/cursos-practicas-old | /Ejemplos python/verificarElementoEnArreglo.py | 680 | 4 | 4 | colores=["Rojo","Verde","Amarillo"]
#Verificar si el coloer Verde se encuentra en la lista con esta función IN si se encuentra devuelve true y sino false
print("Verde" in colores)#Devolvera un true porque sí se encuentra
print("Rosado" in colores)#Devolverá False porque no se encuentra
#Python acepta todo tipo de da... |
f0a3f335550ae691b2b3638f82975bb31cd5f90a | lafolle/Agastya | /MARBLES2.py | 357 | 3.546875 | 4 | #!/usr/bin/env python
def bcoff(n,r):
print "Computing..."
s=1
if n-r<r:
for i in range(1,n-r+1):
s*=(1+(r/i))
else:
for i in range(1,r+1):
s*=(1+(n-r)/i)
return s
if __name__=="__main__":
print bcoff(1000000,500000)
# approx 27sec for 1000000,20000... |
80eaa8d80e3c8a9430d1623898c5c3889889dd53 | UnsupervisedDotey/Leetcode | /数组/189_rotate-array.py | 810 | 3.6875 | 4 | class Solution:
def rotate(self, nums, k) -> None:
"""
Do not return anything, modify nums in-place instead.
替换list里面的原位置数据,用nums[:]
卧槽我是sb吧,你看人家这个多简单
k = k % len(nums)
nums[:]= nums[len(nums)-k:] + nums[0:len(nums)-k]
"""
k = k % len(nums)
... |
afebcb950445639d6cddf7fc81e1dbc523ce68b6 | Crepusculo/LeetCode | /LeetCode/035_Search_Insert_Position.py | 1,048 | 4.09375 | 4 | # -*- coding: UTF-8 -*-
"""
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it wou
ld be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
... |
0dea272ddf692c191d20fbb52aece3f4001c6a86 | schatzkara/2048Bot | /gridutils.py | 3,957 | 3.78125 | 4 | def num_monotonic(grid):
size = len(grid)
count = 0
for i in range(size):
# row
if monotonic(grid[i]):
count += 1
# col
if monotonic([grid[j][i] for j in range(size)]):
count += 1
return count
def monotonic(list):
return monotonic_increasing... |
ecfcc2d18053c9e393adc33f0ac88701fb49c659 | laviktor/python | /task_07/src/solution.py | 383 | 4.09375 | 4 | '''
Calculates lunar addition between the two inputs.
:param x: The first value
:param y: The second value
:returns: The lunar sum of the two values
'''
def lunar_add(x, y):
return 0
'''
Calculates lunar multiplication between the two inputs.
:param x: The first value
:param y: The second value
:returns: The lunar... |
ed2b73d506307d7df699bf8afbc06e869cae89ea | michaelaruiz/TruckProjectGUI | /distance.py | 3,683 | 3.5625 | 4 | # Michaela Ruiz #001323526
import csv
first_truck_delivery = []
first_truck_delivery_packages = []
second_truck_delivery = []
second_truck_delivery_packages = []
third_truck_delivery = []
third_truck_delivery_packages = []
class Distances:
# constructor
def __init__(self):
self.distanceData = self.i... |
77ce249775fc9a69f8e02df404d3a03c57173af6 | DashaChis/New_one | /hw14/hw14.py | 631 | 3.59375 | 4 | import re
def get_data(filename):
raw = ''
with open(filename, encoding='cp1251') as f:
raw = f.read()
print(raw[:50])
return raw
def preprocess(text):
tokens = re.split('[^\w-]+', text)
tokens = [word.lower() for word in tokens]
tokens = [re.sub(word, word+' ', word) for word in ... |
2e7b0f8a41a2356ff0e8edc71eb091d5bee34534 | mshahmirkhan/Muneeb | /MuneebAhmedch4.py | 848 | 3.71875 | 4 | #text and color
import cv2
import numpy as np
img = np.zeros((512,512,3))
print (img.shape)
# 255 means blue
img[:] = 255,0,0
cv2.imshow("image blue ",img)
#255,255,255 means white
img[:] = 255, 255, 255
#cv2.imshow("image", img)
# line on image
app =cv2.line(img,(0,0),(img.shape[1],img.shape[1]),(0,255,0),3)
#cv2.i... |
29be1cd10ec69a2c9a5cd1eb89bd9492a65d8b5d | 2017-1-LCC/Python | /media_abc.py | 423 | 3.984375 | 4 | nome=(input("Informe o nome do aluno: "))
n1=int(input("Informe a nota da prova: "))
n2=int(input("Informe a nota do trabalho: "))
n3=int(input("Informe a nota do seminário: "))
media = (n1 + n2 + n3) /3
if media >= 7:
print(nome," APROVADO!")
elif media >=3 :
nf = (50 - (media * 7))/3
print(n... |
dd50b16a064836281df25219862dc6d5c3c15d18 | sadiayousafzai036/CodalitySolutions | /Dominator.py | 663 | 3.609375 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
size=0
value=0
indice=0
count=0
for i in range(0,len(A)):
if size==0:
size+=1
value=A[i]
else:
if value!... |
a0df0e16bfb4b1947c9bd63edb28cb82f9839b89 | chickfilangel/U3L8. | /Lesson 8/problem1.py | 423 | 4 | 4 | print('-' * 17)
print('Morbid Predictions Program ')
print( )
#Description
print('This program asks you for your current age and tells you the year that you will die (on average) ')
age = input('What is your age today? ')
age = int(age)
print('...thinking... ')
print('...thinking... ')
print('...thinking... ')
b... |
c0bd6b13cf9cc0d3d1194645b621ce4630d63bcd | ilovepilav/LinkedLists_Python | /DoublyLinkedList.py | 4,557 | 3.8125 | 4 | from Node import Node
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def get(self, item):
n = self.head
while n is not None:
if(n.item == item):
return n
n = n.next
return No... |
3302a6c32ad347b90d25639033a053eda0708491 | ducphanduyagentp/CSCI-141 | /Homework3/text_count.py | 1,525 | 4.1875 | 4 | """
file: text_count.py
language: python 3
author: Duc Phan - ddp3945@rit.edu
description: Homework 3 - CSCI-141
"""
import pdb
def count_text_string(search_for, search_in):
"""Counts and return the number of occurences of the string search_for in the string search_in"""
if len(search_for) > len(search_in):
... |
58e69c701ec0490a66394f41338da9421b022b0b | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_158/711.py | 980 | 3.59375 | 4 | T = int(input())
def get_largest(x):
if x == 1:
return 1, 1
elif x == 2:
return 2, 1
elif x == 3:
return 2, 2
elif x == 4:
return 2, 3
for i in range(1, T+1):
x, r, c = map(int, input().split(" "))
total = r * c
if total % x != 0:
winner = "RICHA... |
de97ad0573bc322e75ae2bbfddf7ad96d3d3b76f | thuyvyng/CS325 | /hw9/dijkstra.py | 1,055 | 3.53125 | 4 | from collections import defaultdict
from heapdict import heapdict
def shortest(n, edges):
if edges == []: return None
def solution(v):
if v not in back:
return [v]
return solution(back[v]) + [v]
adjlist = defaultdict(list)
for u, v, c in edges:
adjlist[u... |
53570fb1bf0ba28eeec27f13b5c6d45c6c5881e4 | FernandoReyesV2/EDS2 | /Cargo.py | 475 | 3.53125 | 4 | class Cargo:
secuencia=0
def __init__(self,des="Sin cargo"):
Cargo.secuencia=Cargo.secuencia+1
self.codigo=Cargo.secuencia
self.descripcion = des
if __name__=="__main__":
cargo1= Cargo()
print("cargo1 ",cargo1.codigo, cargo1.descripcion)
cargo2=Cargo("Docente")
... |
8e571059fe1d90d2f2c71ea487bac81562cfb857 | rgliever/anagrams | /anagrams.py | 2,325 | 4.25 | 4 | # Ryan Gliever, 2015
from string import punctuation
import re
# finds if two strings (which are the concatenation of each pair) are
# anagrams by sorting them and comparing.
# also performs the check for the same word being in both pairs
def check_pair(pairA, pairB):
if not ((pairA[0] or pairA[1]) == (pairB[0] or... |
7dc98cbdef3d1f54a0274394cbe2a5c7aad5968c | thocoutelou/IA-Puissance4 | /Game.py | 238 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import IAPuissance4
# Game implements the rules of the game.
class Game():
def __init__(player1, player2, board):
self.player1 = player1
self.player2 = player2
self.board = board
|
ba5b3d5c896c9f16affc9a8a9c614fd2fabb542e | jhlax/sndalgo | /sndalgo/spline.py | 9,495 | 3.609375 | 4 | from collections import namedtuple
from random import randint
import numpy as np
from matplotlib.pyplot import plot, show
from numba import njit
def create_spline(x, y):
"""
creates a spline ready for use in interpolation.
:param x:
:param y:
:return:
"""
x = np.asfarray(x)
y = np.a... |
1e1a0869ea291405b26b19be42e2cfb5437e18b9 | Alireza-Gerami/UBPythonWorkshop | /Session-4/meet-code/2.py | 151 | 3.78125 | 4 | # Question url https://quera.ir/problemset/university/616
n = int(input())
i = 0
while True:
if 2 ** i > n:
break
i += 1
print(2 ** i)
|
5c14ef8a151d574e7240dcb4a4b1f365bf91f2e2 | shyun34/ezAlgorithm | /OYJ/WEEK1/회사에 있는 사람.py | 299 | 3.53125 | 4 | import sys
num = int(sys.stdin.readline())
employee = {}
for _ in range(num):
name, action = sys.stdin.readline().split()
if action == 'enter':
employee[name] = 'enter'
elif action == 'leave':
if employee[name]: del employee[name]
for e in sorted(employee, reverse=True):
print(e) |
e690c725a449f0a4f23b4420621fd5a2456d4abb | ajay946/python-codes | /SingleStringlst.py | 174 | 3.640625 | 4 | lst = ['Ajay ' , 'Santosh ' , 'Gaonkar' ]
print(lst)
#using inbuilt join function
print("".join(lst))
# using for loop
for i in range(len(lst)):
print(lst[i],end="") |
c37f0abb578be9c9685db9f8df309b3c412367ee | Zihanur/PyCalculator | /pyCalculator.py | 2,536 | 3.796875 | 4 | from tkinter import *
a = Tk()
a.title("Calculator")
text_input = StringVar()
operator = ""
e = Entry(a,font=('arial',20,'bold'),bd=30,borderwidth=8,insertwidth=4,justify='right',textvariable=text_input).grid(row=0,column=0,columnspan=4)
def clickbtn(numbers):
global operator
operator=operator+str... |
c33c59aa04150fd9becfabcad77e3f4b67ead3b4 | johathom/johathom.github.io | /exampleClass1.py | 161 | 3.671875 | 4 | C:\Users\johathom>python
#!/usr/bin/env python
def average(my_list):
sum = 0
for i in my_list:
sum = sum + i
average = sum/len(my_list)
print "average"
|
d7b8b07f50dc61f1f282fda76afa95834fc5fab6 | IvanProtsenko/BioInf | /задачки/доп.задания/пятая.py | 214 | 3.578125 | 4 | def fun(p, p1):
s = []
p = list(set(p))
p1 = list(set(p1))
for i in range(len(p1)):
if p1[i] in p:
s.append(p1[i])
return s
print(fun([1, 2, 3, 4, 5],[3, 4, 5, 6, 7, 8, 4]))
|
9e34e558e12b6af4af749b23915c7f0a2583199f | AtaeKurri/DiscordDBPlus | /discordDBPlus/db.py | 4,245 | 3.578125 | 4 | import discord
from .models import Data
class DiscordDB(object):
"""The Discord database client.
Parameters
----------
bot : discord.ext.commands.Bot
An instance of discord.py Client or Bot representing your discord application.
db_channel_id : int
An integer representing ID of D... |
2380ce6b1e7a92a72e38cdf3d06263dde552442f | ai-kmu/etc | /algorithm/2020/0909/hyejin.py | 1,138 | 3.515625 | 4 | class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals_len = len(intervals)
# intervals length check
if intervals_len == 0 or intervals_len == 1:
return intervals
# element[0]번째 오름차순 정렬
intervals = sorted(interv... |
3e31227cf24f04a05f9ff1fdb37b5141525b2ff7 | elirex/gogo_design_pattern | /patterns/template_method.py | 2,041 | 4.09375 | 4 | """
Template Method Pattern
只有兩種套餐的簡餐店
點餐 -> 收錢 -> 找零 -> 準備主餐 -> 準備附湯 -> 送餐
"""
class Meal:
def __init__(self, name, price):
self.name = name
self.price = price
def start_order(self):
print(f'客人點餐:{self.name}')
def charge(self):
print('收錢')
def return_money(self, mo... |
4e841521e03d9b05ab438f2c50bfd20aaf72c99d | vt-dataengineer/leetcode | /leetcode_problems/file4/pivot index.py | 670 | 3.6875 | 4 | # Input:
# nums = [1, 7, 3, 6, 5, 6]
# Output: 3
# Explanation:
# The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
# Also, 3 is the first index where this occurs.
# def one(a):
# nums = [1, 7, 3, 6, 5, 6]
# i = 1
# s = 0
# s1 = 0
# ... |
dc97d275793e893a2a2a404abdcf8c391110e659 | kopgittowin/testpro | /objectdemo/animal.py | 3,509 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''比如创建一个类(Animal)【动物类】,类里有属性(名称,颜色,年龄,性别),类方法(会叫,会跑)'''
import yaml
import data
class Animal:
name: str = 'Animal Name'
color: str = 'default Color'
age: float = 0
gender: str = 'null'
def __init__(self, name, color, age, gender):
self.name =... |
11330642b97f1c12a36371f185523a414ff9cec1 | nicolemadison/Odd1Out | /interface.py | 5,284 | 3.578125 | 4 | """ Interface Elements
This module contains the elements which are necessary to create the interface
of the game: text labels, images, colors, and button objects. This module requires
the 'elements' module, as well as 'pyglet' to be installed.
This module can be imported and contains the following:
* Tuples defining ... |
d0fa5e290dbd1e948363cabb1803b424ac650258 | masudurHimel/Problematic_Adventure | /Leetcode/Pascal's Triangle II.py | 347 | 3.625 | 4 | class Solution:
def getRow(self, rowIndex):
rowIndex = rowIndex + 1
res = [[1]]
for i in range(1, rowIndex):
list1 = res[i - 1] + [0]
list2 = [0] + res[i - 1]
_ = [a + b for a, b in zip(list1, list2)]
res += [_]
return res[-1]
s = Sol... |
69f9cdc3448abd62e68b354f9ebcee601fbd2074 | ktapsyman/Nccucs_work | /Algorithm/HW1/Gen.py | 70 | 3.828125 | 4 | Str = ""
for num in range(1, 2001):
Str += (str(num)+" ")
print(Str)
|
4ad109723554ace506f6953de13c53b45b36e839 | vlgandara/programas-.py | /medias.py | 344 | 3.765625 | 4 | nota1 = input("Digite a primeira nota: ")
nota2 = input("Digite a segunda nota: ")
nota3 = input("Digite a terceira nota: ")
nota4 = input("Digite a quarta nota: ")
_nota1 = int(nota1)
_nota2 = int(nota2)
_nota3 = int(nota3)
_nota4 = int(nota4)
media = (_nota1 + _nota2 + _nota3 + _nota4) / 4
print("A média a... |
9ad6b89e75b5dc341312be28e8fed7a69ca5b309 | yonedahayato/stock_MultiLayerNet | /get_predict/holiday/holiday.py | 8,778 | 3.5625 | 4 | #!/usr/bin/env python3
# 内閣府/「国民の祝日」について
# http://www8.cao.go.jp/chosei/shukujitsu/gaiyou.html
# 国立天文台/暦要項
# http://eco.mtk.nao.ac.jp/koyomi/yoko/
# 国民の祝日 - Wikipedia
# http://ja.wikipedia.org/wiki/%E5%9B%BD%E6%B0%91%E3%81%AE%E7%A5%9D%E6%97%A5
import sys
import argparse
import datetime
MONDAY = 0
TUESDAY = 1
WEDNESD... |
d915cdcd101587b8b621c45c93c1bef0ca84fe60 | yura-seredyuk/ItStep | /ITS #5/0005/DZ #5.py | 675 | 3.78125 | 4 | max, count_max, num_cons, number, num_input, i = 0, 0, 0, 0, 0, 1
while True:
x = int(input("число: "))
if x == 0:
break
else:
if x > max:
max = x
count_max = 1
elif x == max:
count_max += 1
if num_input == x:
i += 1
e... |
a82e46df98b279d21719f59c7f7f62afb5cf7f13 | kotarot/sawatabi | /sample/utils/npp.py | 1,495 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 Kotaro Terada
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
562410d48ae063cfe41a7456653e2fe9452c1c96 | ane4katv/STUDY | /Basic Algorithms/Graphs/Dijkstra.py | 1,744 | 4.1875 | 4 | def dijkstra(graph, start, end):
shortest_distance = {}
predecessor = {}
unseen_nodes = list(graph.keys())
infinity = float("inf")
path = []
# set all vertices besides of start to "infinity"
# shortest_distance = {'a': 0, 'b': inf, 'c': inf, 'd': inf, 'e': inf}
for node in unseen_nodes:... |
5a58943b36007ec06ff2288a8238dfe68785dd33 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_3_neat/16_0_3_Taehun_c.py | 975 | 3.59375 | 4 | from math import sqrt; from itertools import count, islice
def isPrime(n):
return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))
def dec_to_base(dec, base):
return int(dec, base)
def largest_prime_factor(n):
i = 2
while i * i <= n:
if n % i:
i += 1
else:
... |
959d21824398c7186dd99df5d84594cdfa7d648a | Fellylove/Lambdata-Burris1 | /New folder/testing.py | 599 | 4.09375 | 4 | class dataframe:
"""" Function to split dates of format "MM/DD/YYYY" into multiple columns
(df['month'], df['day'], df['year'])
and then return the same dataframe with
those additional columns. dataframe must have
column called date_series"""
def __init__(self, df):
self.df = df
de... |
503d65a2042c978d966e064d8d775a57fd9b5ca1 | pratiksachaniya/Python-Program | /Syllbus/Unit3/4.py | 554 | 3.828125 | 4 | class Area:
def __init__(self,height=0,width=0):
self.height = height
self.width = width
def getWidth(self):
return self.width
def getHeight(self):
return self.height
def setHeight(self,height):
self.height = height
def setWidth(self,width):
... |
1350ca72dda5e5d396d3a2b9f87eea49c8964c2f | KUEE1080/DataStructureAndAlgorithm | /maze.py | 3,734 | 3.625 | 4 |
'''defining constant'''
CORRIDOR = 0
WALL = 1
DESTINATION = 2
VISITED = 3
BLOCKED = 4
def findpath(_maze, y, x):
path_stack = [] # pushing the starting point to the path stack
path_stack.append([y, x])
_maze[y][x] = VISITED
while True:
coor = path_stack.pop()
if _m... |
cf21b4516576c1d6cddd3679f517bf5daaee6498 | eishkumar/dumypro | /dic.py | 136 | 3.65625 | 4 | a={1:'he','nu':'hehe'}
print(a[1],a['nu'])
print(a.values())
print(a.keys())
a=['key1','key2','key3']
dic=dict.fromkeys(a,10)
print(dic) |
e90bdf9790c6a2e8840e0c73a937281651375d7c | vc2309/interview_prep | /tree/minimum_tree.py | 419 | 3.71875 | 4 | from bst import Tree,Node
def minimum_tree(my_arr,my_tree,l,r):
if l<r:
mid = int((l+r)/2)
my_tree.insert(my_arr[mid])
minimum_tree(my_arr,my_tree,l,mid-1)
minimum_tree(my_arr,my_tree,mid+1,r)
if l==r:
my_tree.insert(my_arr[l])
def main():
my_arr = [int(i) for i in input("enter nums").split(' ') if i!=''... |
a4098ef9949268436dabcbdbf61603eefa479953 | hopegiometti/LearningPython | /basics/textpro.py | 671 | 3.8125 | 4 | # print("Say Something:")
# def say_something(s):
# all = []
# if s == "\end":
# print(all)
# else:
# print("Say Something:")
# all.append(s)
# say_something()
def sentence_maker(phrase):
q_words = ("how", "what", "when", "where", "who")
capitalized = phrase.capitalize()
... |
49302369e7b5de14ae33be0b0d73daa8e3e08ab7 | BrettRegnier/CPSC5310 | /asn2/asn2q3.py | 4,054 | 3.78125 | 4 | import random
import nltk
from nltk import probability
from nltk.corpus import brown
#remove punctuation
def main():
shannonWords = None
shannonSentences = None
bigrams = None
trigrams = None
cfd_bigram = None
cfd_trigram = None
choice = ""
while choice != "exit":
c... |
e7aca278a471c0f9a4769b494ed6026ba50dfdc0 | alfayemil/backup | /hints.py | 362 | 4.3125 | 4 | #how to turn a string into a list
myString = "arizona"
myList = list(myString)
print(myList)
# how to create a list with _ where the letters go
guessList = []
for a in myList:
guessList.append("_")
print(guessList)
#How to replace a specific item in a list
# So say the user types r for guess you would... |
d9fcef3beb91d5d634fc5460552d8ff539375857 | tangjikuo/studentsmanage | /student/students.py | 372 | 3.65625 | 4 | class Student:
"""
this class defined a student info
"""
def __init__(self, stu_no, tea_no, score, name='', sex=''):
self.name = name
self.sex = sex
self.stu_no = stu_no
self.tea_no = tea_no
self.score = score
def query_info(self):
sql = "select score... |
275bc1bcd992db77025744e0f6dfbdd2b8510c3b | lcfsluiz/520 | /Aula3/erro1.py | 334 | 4 | 4 | ling = input("qual a melhor linguagem de programação ?")
ling = ling.strip().lower()
if ling == 'python':
print('Você está no caminho certo')
elif ling == 'html' or ling == 'css':
raise ValueError('isso não é linguagem de programação')
else:
print('Mude para python!')
except ValueError as e:
print(e)... |
c71d6f2224945e0fb75da0f96c753bafabf35c9d | mathewtitus/hiton_ezk | /src/hiton_ezk/data_structures.py | 7,659 | 3.578125 | 4 | # data_structures.py
# Mathew Titus, November 2020
#
# Data classes holding the variables of the simulated
# system.
#
# CpnVar contains the variable's value, topology
# distribution when randomly sampled, and notion of
# distance.
#
# CpnSub collects a number of CpnVar objects into an
# array to allow list oper... |
a2543a31d0b5b73a1b7bd4bfcd4e8ad0248de0bf | PK-29/Focus | /webblocker/src/WBgui.py | 1,550 | 3.84375 | 4 | from Tkinter import *
def clear_entry(event, entry):
entry.delete(0, END)
#setting up application window
window = Tk()
window.title("FOCUS")
window.geometry("500x400")
window.wm_iconbitmap('fc.ico')
background_image=PhotoImage(file="dj.gif")
background_label =Label(window, image=background_image)
background_labe... |
74eea05f4bbe49d3cadf9302e8e6fece0448ac9e | akimasa-l/aidemy | /learned/supervised-learning/B1Z9h8oIxz.py | 834 | 3.6875 | 4 | from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Lasso
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
# データを生成
X, y = make_regression(n_samples=100, n_features=100, n_informative=60, n_targets=1, random_state=42)
train_X, test_X, trai... |
255b2d30302bf345446c0e56da9009ef5e5972c5 | DanielFadlon/simple_store- | /shopping_cart.py | 2,355 | 3.875 | 4 | from errors import ItemAlreadyExistsError, ItemNotExistError
from item import Item
class ShoppingCart:
"""
A class used to represent a shopping cart
Attributes
-----------
items : list
all the items that in the shopping cart
Methods
-------
add_item(item : Item)
add t... |
cda35e04b9ede8fe4be6d5335e33c54cefc88e59 | mmkekic/IC-crash-course | /coding/pytest_tutorial.py | 2,487 | 3.828125 | 4 | import pytest
def custom_sum(a, b):
return a+b
###### EXERCISE 1 ######
"""
Rename the file such that the tests are run with pytest command.
Write a test that will check that the results of custom_sum function
does not depend on arguments order (use a=1, and b=2)
Write a test to check that for a=1 and b=2 the re... |
d2aa7c8d0ad76a5ea4fdc9aa8667efd335ed9efc | invicta117/singlespottedtable | /table-one-spot.py | 827 | 3.765625 | 4 | import itertools
size = 5
def show(table):
print()
print("%" * 8)
for n, val in enumerate(table):
if n % size == 0:
print("\n", val, end="")
else:
print(val, end="")
print()
def count_spots(table):
spots = 0
for i in range(len(table)):
if tabl... |
f88b8dcce482f4746a6030bfdb4d1445c07e9842 | jinjungle/Python-Crash-Course | /chapter09/admin.py | 621 | 3.578125 | 4 | from only_user import User
class Admin(User):
"""管理员"""
def __init__(self, first_name, last_name, privileges, *profile):
"""初始化"""
super().__init__(first_name, last_name, profile)
self.privileges = Privileges(privileges)
def show_privileges(self):
"""显示管理员权限"""
sel... |
af26bc931521f9d5d55e54b3fbc6da31d37f401f | rochakgupta/dtu-minor-1 | /Recommender System/1.py | 2,823 | 3.5625 | 4 | #!/usr/bin/python
#
# Created by Albert Au Yeung (2010)
#
# An implementation of matrix factorization
#
import numpy
'''import pip
print(pip.pep425tags.get_supported())'''
try:
import numpy
except:
print "This implementation requires the numpy module."
exit(0)
a=numpy.zeros((5,5))
a[1][1]=5
print a
######... |
a8bdf0c4d3abbd4582c4149436a2abed7d48369b | Jessicammelo/cursoPython | /default.py | 951 | 4.15625 | 4 | """
Modulos colection - Default Dict
https://docs.python.org/3/library/collections.html#collections.defaultdict
# Recap Dicionarios
dicionario = {'curso': 'Programação em Python: essencial'
print(dicionario)
print(dicionario['curso'])
print(dicionario['outro']) #???KeyError
Default Dict -> Ao criar um dicionario uti... |
d2b862622a2896614bc3967e8cfa6f58fb911aec | alexgula/django_sites | /sites/ilitna/sprite_bundler/box.py | 4,479 | 3.953125 | 4 | # coding=utf-8
"""A simple 2D packing algorithm for making sprites."""
from .conf.bundler_settings import SPRITE_SPACING
class Box(object):
def __init__(self, width, height, x=0, y=0):
self.width = width
self.height = height
self.x = x
self.y = y
def same_size(self, other):
... |
22d31897e15d7082de9f2b304d55c496c4faa41b | dewetbaumann/python | /problem 4/problem4.py | 551 | 3.921875 | 4 | from os import system as console
console('color 0b && cls')
mes = input('ingrese el mes: ').lower()
if mes == 'abril' or mes == 'junio' or mes == 'septiembre'or mes == 'noviembre':
print ('El mes trae 30 dias')
elif mes == 'enero' or mes == 'marzo' or mes == 'mayo' or mes == 'julio' or mes == 'agosto' or mes == ... |
3f3e5261f271c4bf79805a31310f19975659f3b1 | hitigon/leetcode-template | /python/implement_strstr.py | 344 | 3.53125 | 4 | # coding=utf-8
# AC Rate: 22.0%
# https://oj.leetcode.com/problems/implement-strstr/
# Implement strStr().
# Returns a pointer to the first occurrence of needle in haystack, or null if
class Solution:
# @param haystack, a string
# @param needle, a string
# @return a string or None
def strStr(self, hay... |
0109f121e1e2c917938b08829867dee6150e28b4 | ryanpinnock10/Dijkstra-s-Algorithm | /unitTests.py | 3,001 | 4.21875 | 4 | #!usr/bin/env python3
# Ryan Pinnock
# Date: 12/12/2019
# Class: CSC- 321A
# Professor: Salvador
# Assignment: Implement a working version of Dijkstra's Algorithm following the implementation
# guidelines shown in the Textbook and in the slides, subject to the following conditions:
# The program should take a direc... |
def85ca7efbf7147eb11250af67354c85f2b4de1 | teinhonglo/leetcode | /problem/Binary-Tree-Level-Order-Traversal.py | 1,104 | 3.734375 | 4 | tion for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
# check ... |
93e813da7fc3b7c6e2fadfd49c248df1552db16f | zibrata/python-blackjack | /blackjack.py | 11,402 | 3.53125 | 4 | #!/usr/bin/env python3
#######################################
# Auteur : Alexandre LEVRET #
# Parcours : ESILV 5A IBO spé FinTech #
# Module : Python pour la finance #
#######################################
from random import randint
Cartes = { # dictionnaire afin de ranger les cartes avec en key les... |
8f34002cb87c9b28093a0a00c76c5fec88e3c175 | alejarojas19/programacion1 | /talleres/TallerFunciones/repasoQuiz2.py | 2,497 | 3.96875 | 4 | temperaturaCorporal = [36, 37, 38, 35, 36, 38, 37.5, 38.2, 41,37.4, 38.6,39.1, 40.3, 33]
#---funciones---#
def unidad (lista):
Preguntatemperatura2 = input(preguntaTemperatura)
for temperatura in lista:
if (Preguntatemperatura2 == "F"):
temperatura = (temperatura * 1.8) + 32
tem... |
d963e873de4bc3d58b192ef4c7b4704d0fddf0bc | JagadeeshVarri/learnPython | /collections.py | 570 | 3.859375 | 4 | list1 = [1,2,3,"hello",True]
print(list1)
print(type(list1))
print(list1[1:5])
list.append("python")
list.insert(1,"python")
print(list1[-4:-1])
#tuples
tuple1 = ("apple", "banana", "cherry")
print(tuple1)
print(len(tuple1))
x = tuple1.count(5)
print(x)
#sets:
set1 = {"Language", "python", "program"}
print(set1)
pr... |
ae4171cc853d141ac5eb8868653ef0940b8e1ed5 | lerematics/QuadraticFormula | /quadratic_eqn.py | 900 | 4.125 | 4 | import math
class Quadratic:
def __init__(self, a = 0, b = 0, c = 0):
self.a = a
self.b = b
self.c = c
def formula(self):
root_1 = (-self.b + math.sqrt(self.b**2 - 4 * self.a * self.c)) / (2 * self.a)
root_2 = (-self.b - math.sqrt(self.b**2 - 4 * self.a * self.c)) / (2 * self.a)
return '\n==> Qua... |
94c7cfe9c84b0eb83fe830178b189898c8c8772e | VaibhavD143/Coding | /leet_cousins_in_binarytree.py | 1,988 | 3.59375 | 4 | class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
return 'TreeNode({})'.format(self.val)
def deserialize(string):
if string == '{}':
return None
nodes = [None if val == 'null... |
898d42d8137a06b7875eadfd2e92f31c3cef029f | levyrachel/Intro-to-Computer-Science | /Semester Project Final Draft-3.py | 10,446 | 3.625 | 4 | #This is a simulation. Please press play!
import random
import Draw
def backdrop():
#Create the Backround
#Clear the canvas (it will clear each time through the loop)
Draw.clear()
#Set the Backround Color of Green
green = Draw.color(0, 100, 50)
Draw.setBackground(green)
#Draw the Sky
blue... |
fa4b9b30bf80a552aef854242e41922e0d7d5843 | c-yan/atcoder | /agc/agc046/agc046a.py | 112 | 3.8125 | 4 | from math import gcd
X = int(input())
def lcm(x, y):
return x // gcd(x, y) * y
print(lcm(X, 360) // X)
|
3781cdfcffafdc81c127188a0bd4a1df8f6147a2 | califafa/tf_learn | /wbm/002.py | 771 | 3.625 | 4 | import tensorflow as tf
import numpy as np
import random
#确定答案
var1=8
var2=42
#先生成学习数据
x_data=np.float64(np.random.rand(1,100))
# y_data=np.dot([23],x_data)
y_data=var1*x_data+var2
#构造一个线性模型
b=tf.Variable(tf.zeros([1]))
w=tf.Variable(tf.random_uniform([1],-1.0,1.0))
#w和b都能用,如下:
y=tf.multiply(w,x_data)+b
#y=tf.multi... |
81ef982b09b6d31089f990bf079f6e175aaf85d3 | Farzana0627/Python-Practice | /Sorting Algorithms/insertion.py | 242 | 3.984375 | 4 | def insertionSort(list):
for i in range(1, len(list)):
j=i
while(j>0 and list[j-1]>list[j]):
temp= list[j]
list[j]= list[j-1]
list[j-1]= temp
j=j-1
i+=1
return list
list = [19,2,2,45,6,11,121,0]
print(insertionSort(list)) |
e0a2e4b2ac1d77ca4742b2bbcb6fd6f5d52fd8c0 | higor-gomes93/curso_programacao_python_udemy | /Sessão 6 - Exercícios/ex3.py | 242 | 3.96875 | 4 | '''
Faça um algorítmo utilizando o comando while que mostra uma contagem regressiva na tela, iniciando em 10 e
terminando em 0. Mostrar uma mensagem "FIM!" após a contagem.
'''
n = 10
while n > -1:
print(n)
n = n - 1
print("FIM!") |
3745da63d1e78ba972e92364b4f4713642915f2f | cicihou/LearningProject | /leetcode-py/leetcode24.py | 1,258 | 3.859375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
'''
method 1 递归,请参考这个视频:https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/dong-h... |
31d431e833452ac49634e8cad60f9fa25e33eb71 | luozhiping/leetcode | /middle/sort_characters_by_frequency.py | 826 | 3.65625 | 4 | # 451. 根据字符出现频率排序
# https://leetcode-cn.com/problems/sort-characters-by-frequency
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
maxItem = 0
if not s:
return s
dict = {}
for c in s:
dict[c]... |
004d9fc8c4067c35d8fea46b15be4d99b5e4a400 | hicarrie/holberton-system_engineering-devops | /0x18-api_advanced/0-subs.py | 578 | 3.5625 | 4 | #!/usr/bin/python3
"""
Queries the Reddit API and returns number of subscribers to a given subreddit
"""
import requests
import sys
def number_of_subscribers(subreddit):
""" returns number of subscribers to a given subreddit """
headers = {'User-Agent': '113'}
subreddit = sys.argv[1]
url = "https://w... |
349e07f86fb1167e7776ba912c6c656ddab0d4fe | Pavithralakshmi/corekata | /mmin.py | 111 | 3.53125 | 4 | k=[]
n=int(input("enter the number:"))
for i in range(1,n+1):
b=int(input())
k.append(b)
print(min(k))
|
f401c3f25a38dcfe15840ce8bea335fc9dcd1415 | dezhili/My_learnings | /numpy_note/day4.py | 430 | 3.90625 | 4 | #索引
import numpy as np
A = np.arange(8)
# print(A)
# print(A[3])
B = np.arange(12).reshape((3,4))
#print(B)
print(B[1])
print(B[2][1])
print(B[1:])
print(B[1][:2]) #[4 5]
print(B[1,:2]) #[4 5]
print(B[1:,:2])
for row in B:
print(row)
for column in B.T:
print(column)
C = np.arange(3,15).reshape((3,4))
prin... |
239ddc5394ec49f7736008fbde2bf4c5b8603376 | usama78941/Danial-Liang-Books-Exercies | /chapterFive/exer_10.py | 574 | 4.25 | 4 | # (Find numbers divisible by 5 and 6) Write a program that displays all the num-
# bers from 100 to 1,000, ten per line, that are divisible by 5 and 6. Numbers are
# separated by exactly one space.
def numbers_divisible_by_five_and_six():
start_value = 100
count = 1
while start_value <= 1000:
if (... |
8c9833f4a2de3e361c7764a068f3d4b5f4414779 | EngrDevDom/Everyday-Coding-in-Python | /Ch# 133-138.py | 5,957 | 3.671875 | 4 | """ More Tkinter """
# Ch 133
from tkinter import *
def click():
name = textbox1.get()
message = str("Hello " + name)
textbox2["text"] = message
window = Tk()
window.title("Names")
window.geometry("450x350")
window.wm_iconbitmap("stripes.ico")
window.configure(background = "black")
logo = PhotoImage(f... |
bb09a20f71a6087803e1839bd0d16c2fead8994b | Ruchika2696/Competitive_Coding | /Minimum_Height_Trees.py | 2,702 | 4.40625 | 4 | # For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root la... |
04045ef73ea819f0cf1903bb4f4bcc6bd872058f | Da1-net12/Abramyan | /begin 7.py | 93 | 3.78125 | 4 | r = int(input("Enter r: "))
l = 3.14 * 2 * r
s = (r*r) * 3.14
print("L = ",l)
print("S = ",s) |
ed1071645c7ba0171bf86c5dc2bf456764ca891d | DavidRSeWell/LeetCode | /python/medium/climbing_stairs.py | 800 | 3.921875 | 4 |
def paths(m ,n):
if n == m : return 0
if (n - m) <= 2: return (n - m)
else: return paths(m + 1 ,n) + paths(m + 2 ,n)
def dp(m ,n,mem):
if mem.get(m): return mem[m]
result = None
if n == m :
result = 0
if (n - m) <= 2:
result = (n - m)
else:
result = dp(m + 1 ,n... |
a373a43a1a9d2c4a361b65f4a538602e507e3aef | ThomAaShelby/Temp | /Program3.py | 248 | 3.5625 | 4 | a = int(input("Entr Integer"))
ini = 1
for x in range(1, a):
if x == 1:
print(ini, " ", end='')
elif x/2 != 0:
ini = ini + 2
print(ini, " ", end='')
elif x/2 == 0:
print(ini, " ", end='') |
5ba274d5c2ceb7324c7dd2bc10f3ea9a72dba5ad | johnny3young/codingame | /puzzles/python3/mayan_calc.py | 2,057 | 3.515625 | 4 | import sys
import math
BASE = 20
def read_num(numeralDict, height):
numeral = ""
num_list = []
nb_lines = int(input())
for i in range(nb_lines):
num_line = input()
numeral += num_line
numeral += '\n'
if (i % height == height - 1):
# last column
... |
2f127355d4c40854acdc00e5475b232cefadceae | Ebs3010/Adivinha | /Server_Main.py | 1,353 | 3.5 | 4 |
import socket
import random
from thread import *
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = socket.gethostname()
PORT = 6015
tcp.bind((HOST, PORT))
print ("Socket criado com sucesso!!\n")
#Numeros de conexoes permitidas
tcp.listen(2)
#
def clientthread(con):
while True:... |
0b273c966ac2aaee26d1c4d168844e4fcb297b6e | komalupatil/Leetcode_Solutions | /Medium/Total Hamming Distance.py | 356 | 3.53125 | 4 | #Leetcode 477. Total Hamming Distance
class Solution:
def totalHammingDistance(self, nums: List[int]) -> int:
total_hamming_dist = 0
for i in range(32):
ones = 0
for num in nums:
ones += (num >> i) & 1
total_hamming_dist += ones * (len(nums) - one... |
022cc4331b98b6ee2afcfca5c6511c28d2a69dec | GiseleViedenhelfen/ExerciciosPython | /pacote download/lista-exercicios/ex043.py | 549 | 3.796875 | 4 | peso = float(input('Quantos kg vc pesa? kg:'))
alt = float(input('Qual a sua altura? em metros. ex:1.60'))
imc = peso / (alt **2)
if imc < 18.5:
print('Seu IMC é {:.1f} e corresponde à magra'.format(imc))
elif 18.5 <= imc < 25:
print('Seu IMC é {:.1f} e corresponde a normal'.format(imc))
elif 25 <= imc < 30:
... |
eef3e9eb92b31a55e8f3e512ef7c954fbc0c0efe | Andrew-Finn/Daily-Coding-Problems | /2019/08 Aug/6th.py | 743 | 4.28125 | 4 | # Good morning! Here's your coding interview problem for today.
#
# This question was asked by ContextLogic.
#
# Implement division of two positive integers without using the division, multiplication, or modulus operators.
# Return the quotient as an integer, ignoring the remainder.
import random
def useless_divide(x... |
987e27911b5da1ca323605cb6e837d90cff5bb45 | rkporwal/PythonPrograms | /Factorial.py | 166 | 4.15625 | 4 | def factorial (number):
fact=1
for i in range(2,number+1):
fact=fact*i
return fact
print("Factorial is ",factorial(int(input("Enter Number ")))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.