blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4405cd71e2b1676f601e75017539082489699a2b | onik282/Python | /L7/1.py | 839 | 3.609375 | 4 | class Matrix:
def __init__(self, list_1, list_2) -> object:
# self.matr = [list_1, list_2]
self.list_1 = list_1
self.list_2 = list_2
def __add__(self):
matr = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
for i in range(len(self.list_1)):
... |
cabb95644f96e6a792854cbcf0662c3107be442c | gcd0318/pe | /l3/pe57.py | 1,140 | 3.96875 | 4 | """
It is possible to show that the square root of two can be expressed as an infinite continued fraction.
2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...... |
7292131b90604ccc75633ad9c40f70804c067feb | leesohyeon/Python_ac | /1111/classex/ClassTest07.py | 1,347 | 3.53125 | 4 | '''
제품의 가격과 수량을 넘겨주면,
총 금액을 알려주는 프로그램을 만들어보세요
class Payment:
변수..
메서드..
'''
# 1. 06.py 파일을 외워서, 스스로 작성해보기!
# 2. 할인율을 추가해서, 할인가격도 출력해보기!
class Payment:
counter=0
discount = 0.5
def __init__(self,price,number):
self.price=price
self.number=number
Payment.counter+=1
def ... |
9639d87c50f00ef17b68b1fe44f01eabaaa06b99 | dryabokon/algo | /math_06_rotate_mat.py | 1,425 | 3.546875 | 4 | # leetcode.com/problems/rotate-image/
# ----------------------------------------------------------------------------------------------------------------------
import numpy
# ----------------------------------------------------------------------------------------------------------------------
# ------------------------... |
7b4b8d0c67b08fc70034165d47e1bfc707d198b7 | ersincebi/hackerrank | /30 Days of Code/Day 25 Running Time and Complexity.py | 994 | 3.890625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
def isPrime(param):
flag = True
if param == 2:
flag = True
elif param == 1 or param%2==0:
flag = False
else:
for i in range(2, int(math.sqrt(param)+1)):
if param % i == 0:
flag = False
break
return 'Prime' if flag e... |
e4c84c2d3d9c269d6d5f5798955d3c835d673f6e | woohyun212/Data_Science_and_AI_introductory_Coding_Solution | /chapter7/ex_7_1.py | 382 | 3.625 | 4 | fruit_list = ['banana', 'orange', 'kiwi', 'apple', 'melon']
largest_str = []
largest_str_len = len(max(fruit_list))
for i in fruit_list:
if len(i) == largest_str_len:
largest_str.append(i)
for i in largest_str:
fruit_list.remove(i)
print(f"가장 길이가 긴 문자열 : ", end='')
for i in largest_str:
print(i, end... |
e2fdb46f3b66c81de4bed7967b5d326af8939e1f | DrBugKiller/offer | /经典代码/0914-计数排序.py | 1,075 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/9/14 10:57
# @Author : DrMa
'''
计数排序:
空间复杂度:n+k,n对应着新数组res,k代表计数数组count_array
时间复杂度:O(n+k)或者O(n),n代表遍历a,k代表遍历count_array
'''
def count_sort(a):
min_num=min(a)
max_num=max(a)
#构造计数数组
count_array=[0]*(max_num-min_num+1)
for num in a:
count_array[num-m... |
2f3c745b5f381fe09922092bb48cdbf4fdcaced5 | SoliDeoGloria31/study | /AID12 day01-16/day03/exercise/rectangle2.py | 496 | 3.875 | 4 | # 练习:
# 写一个程序,打印一个高度为4行的矩形方框
# 要求输入一个整数,此整数代码矩形的宽度,打印
# 相应宽度的矩形
# 如:
# 请输入矩形宽度: 10
# 打印如下:
# ##########
# # #
# # #
# ##########
w = int(input("请输入矩形的宽度: "))
print('#' * w) # 打印第一行
print('#', ' ' * (w-2), '#', sep='') # 第二行
print('#', ' ' * (w-2), '#',... |
9576ab573518e6df91ec7a96e611a9d011dc9f31 | carodewig/advent-of-code | /advent-py/2015/day_03.py | 1,286 | 3.875 | 4 | """ day 3: perfectly spherical houses in a vacuum """
from collections import namedtuple
Location = namedtuple("Location", ["x", "y"])
def deliver_presents(directions):
location = Location(0, 0)
yield location
for step in directions:
if step == ">":
location = Location(location.x + ... |
8e0ebd063f434f77c799372935d190507d700c5d | raymondmar61/pythonwilliamfiset | /exceptionhandlingasserttryexceptfinallyraise.py | 1,543 | 3.96875 | 4 | #williamfiset 23 Assert Try Raise Except Finally
#ASSERT
age = 344
#check condition, if false then run whatever is on the right of comma as an AssertionError
assert age >= 0, "How is your age negative?\n"
print("Your age is", age) #print Your age is 344
#TRY EXCEPT
while True:
try: #try: the code below which may wo... |
0d440309c3c3872b72e9d2899bef958c319a5412 | maheshkrishnagopal/HackerRankSolutions | /Python-Basic Data Types-Lists.py | 571 | 3.8125 | 4 | if __name__ == '__main__':
N = int(input());
list=[];
for i in range (0,N):
inp=input();
ip=inp.split(" ");
if (ip[0]=='insert'):
list.insert(int(ip[1]),int(ip[2]));
elif(ip[0]=='print'):
print(list);
elif(ip[0]=='remove'):
list.rem... |
0cd91fa6cbfcda373178d8320c53c5f69e557a56 | oamam/algorithm | /sort/heap_sort.py | 924 | 3.59375 | 4 | # coding: utf-8
'''
node: n
parent node: (n + 1) / 2
left child node: 2n + 1
right child node: 2n + 2
'''
def make_heap(buff, end):
while True:
maked = True
for i in range(end):
n = buff[i]
c = 2*i + 1
if c >= end: break
lcn = buff[c]
... |
908f8c516e15b26b4a6edf1c0819d87e2d11e1b5 | lohitbadiger/python-basics-all | /43.py | 386 | 3.5625 | 4 | # functions with some input values
def spiceup(owners,staffs):
print('hello to the world of spiceup', owners, 'and welcome to ', staffs)
own=input('enter the name of the owner')
sft=input('enter the name of staffs')
spiceup(own,sft)
def home(rented):
print('hello im staying in ',rented ,'house'... |
7459347af32b0873c7ca9d86feb4decdd5abed72 | mrmattkennedy/CS5800 | /Prog_Assign_1/nfa_lambda_dfa.py | 26,044 | 3.828125 | 4 | #!/usr/bin/env python3
"""Purpose of this module is to convert NFA/NFA lambda to DFA
Course is CS 5800
Author is Matthew Kennedy
Example:
Option to run either the .py file, or .exe file
With each option, can either
1) Pass in a file to read input from
2) Pass in command line arguments, specif... |
24b14aaf50b23a74a37e5b6fd35f4e1a82958e0e | klondikemarlen/design_patterns | /interface/ducks.py | 1,352 | 4 | 4 | import abc
from interface.quack_behaviors import Quack
from interface.fly_behaviors import FlyWithWings, FlyNoWay
class Duck(abc.ABC):
"""Duck that implements arbitrary fly and quack behaviors.
NOTE on set/get in python:
In the simplest use case you don't need these methods in Python!
Using a method... |
7a4dab2d6938b09f2ee44e114bd9828baeb614c5 | berkaybaltas1/Python | /Create Turtle Color.py | 233 | 4.15625 | 4 | #Name: Berkay Baltas
#Date: 09/13/2018
#This program asks the user for the turtle color and stamps it
import turtle
myturtle = turtle.Turtle()
mess = input("Please enter the turtle color: ")
myturtle.shape("turtle")
myturtle.color(mess)
|
429abea983f85acb2bd7ea53032d5b2d4234394a | JustinMacaulay/Seng474Project | /tweetRetrieval.py | 2,413 | 3.78125 | 4 | '''
tweetRetrieval.py
Stephanie Goodale
SENG 474 Project
11/10/2017
Use Twitter API and tweepy functions to access a chosen user's most
recent tweets and write into a CSV file. CSV format includes the
tweet ID, the datetime that it was posted, and the text of the tweet.
Note: Twitter only allows access to ... |
b6ae132b4e5ec309b73c889087a2821074debd6b | Jason101616/LeetCode_Solution | /Tree/199. Binary Tree Right Side View.py | 1,116 | 4.15625 | 4 | # Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
# For example:
# Given the following binary tree,
# 1 <---
# / \
# 2 3 <---
# \ \
# 5 4 <---
# You should return [1, 3, 4].
# D... |
77ef787c5adcd766d2c3c6ef431fbf22f87733eb | datasciences/Bayesian_Inference-graphical_models | /scripts/pymc3/05_trimodal-distribution.py | 1,024 | 3.921875 | 4 | '''
Create a trimodal distribution with different number of
data points.
Input: n_cluster:number of datapoints
mean
std: standard deviation
'''
import numpy as np
import seaborn as sns
def main():
# Create a mixture distribution with 3 means and std
# There has to be 90, 50 and 75 draws from ea... |
ac65455af80de976b3eb10feef2cce0f312a2f97 | arpith-kp/interviewrelated | /leetcode_hard.py | 2,034 | 3.59375 | 4 | from collections import deque
from typing import List
def carrs():
def getCollisionTimes(A):
stack = []
n = len(A)
res = [-1] * n
for i in range(n - 1, -1, -1):
p, s = A[i]
while stack and (s <= A[stack[-1]][1] or (A[stack[-1]][0] - p) / (s - A[stack[-1]][1]... |
9bded1d02557e723f53863529fb1d23bdfa738b4 | AladinBS/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 546 | 3.703125 | 4 | #!/usr/bin/python3
""" Appends a line """
def append_after(filename="", search_string="", new_string=""):
""" appends a new line if a str is found
search_string: search str
new_string: appended str
filename: filename
"""
res_line = []
with open(filename, 'r', encoding="utf-8") as... |
6c6ae51b8bf89c4db17bda2ed53b5fdef08e9103 | langepass88/Python-Begins | /Lesson2/5.py | 499 | 3.84375 | 4 | my_list = [7, 5, 3, 3, 2]
print(f'У нас есть набор натуральных чисел: {my_list}')
while True:
try:
num = int(input('Введите число: '))
except ValueError:
print('Программа завершена')
break
for i in range(len(my_list)):
if num > my_list[i]:
my_list.insert(i, num)
... |
598232bf3efe5b37bfe6b35eb4fc2ba090699bcc | SobuleacCatalina/Introducere_Afisare_Calcule | /problema_4.py | 126 | 3.5 | 4 | nae=int(input("Introdu numarul de globulete albe:"))
nr=nae+3
nal=(nae+nr)-2
t=nae+nr+nal
print("Pe brad sunt",t,"globulete.") |
1490721df48e746827288e3121d5853fe75bff02 | daniel-reich/ubiquitous-fiesta | /q3JMk2yqXfNyHWE9c_10.py | 135 | 3.828125 | 4 |
def double_letters(word):
for i in range(len(word) - 1):
if word[i] == word[i + 1]:
return True
else:
return False
|
e043b87f17d384056534b49fe81cf526b0601172 | slm-bj/nlpia | /scripts/chapter2.py | 1,861 | 3.703125 | 4 | """ NLPIA Chapter 2 Section 2.1 Code Listings and Snippets """
import pandas as pd
sentence = "Thomas Jefferson began building Monticello at the age of "\
"twenty-six."
sentence.split()
# ['Thomas', 'Jefferson', 'began', 'building', 'Monticello', 'at', 'the',
# 'age', 'of', 'twenty-six.']
# As you can see, this s... |
5562a78a5668bef37d45084d49dddc78f3fc36e8 | Bruk3/ctci-solutions | /chapter_1/1_is_unique/is_unique.py | 398 | 4 | 4 | '''Two different implementations of how to check whether or not a string
is made up of all unique characters. '''
def is_unique_1(string):
'''
string: str
returns boolean
Time Complexity: O(n)
Space Complexity: O(n)
'''
seen_chars = set()
for char in string:
if char in seen_... |
7b03370a974869a9d47707741c939b68a6050c0b | AyaAshreey/Codeforces | /785A/anton_and_polyhedrons.py | 329 | 3.8125 | 4 | """ Created by Henrikh Kantuni on 3/15/17 """
if __name__ == "__main__":
n = int(input())
total = 0
faces = {
"Tetrahedron": 4,
"Cube": 6,
"Octahedron": 8,
"Dodecahedron": 12,
"Icosahedron": 20,
}
while n > 0:
total += faces[input()]
n -= 1
... |
a377f40924c9e2c51b9d98611db8bb2c5434f955 | tfidfwastaken/codefundo2k18 | /preprocessing.py | 1,867 | 3.734375 | 4 | from nltk.tokenize import TweetTokenizer
from nltk.corpus import stopwords
import re, string
import nltk
import pandas as pd
import geograpy as geo
#from nltk.tag import StanfordNERTagger
#import ner
"""
This part of the program takes our dataframe df containing
tweet data and extracts useful tokens, or meaningful key... |
d71b673ab50999918f3df497eb8ccf9bac93d5a7 | tigervanilla/Guvi | /player124.py | 229 | 3.578125 | 4 | def GCD(a,b):
if (a == 0) :
return b
return GCD(b % a, a)
def LCM(a,b):
return a*b//GCD(a,b)
n=int(input())
ar=list(map(int,input().split()))
for i in range(1,n):
ar[i]=LCM(ar[i],ar[i-1])
print(ar[-1])
|
9dbd66b0ea93a452d6b2b125de62175f4e87692c | jalletto/python_black_jack | /card.py | 277 | 3.515625 | 4 | class Card:
card_back = '| \\\\ | '
def __init__(self, suit, value, face=None):
self.suit = suit
self.face = face
self.value = value
def __str__(self):
return f'| { self.face if self.face else self.value }{ self.suit } | '
|
e036b03972a0506686af8cc0552eb1e08a06772a | myNameArnav/cheaper | /src/scraper.py | 1,888 | 3.796875 | 4 | """
The scraper module holds functions that actually scrape the e-commerce websites
"""
import requests
import formatter
from bs4 import BeautifulSoup
def httpsGet(URL):
"""
The httpsGet funciton makes HTTP called to the requested URL with custom headers
"""
headers = {"User-Agent": "Mozilla/5.0 (Wind... |
d0da99d02e647fd45849b36e75dac9f7478106d1 | daniel-leinad/progrepository | /hw5/hw5.py | 452 | 3.5625 | 4 | #5 вариан
#вводим список
i = []
#считываем слова
while True:
a = input()
if a == "":
break
#проверяем, оканчивается ли слово на tur, если да, то добавляем его в список
if a[-1]=="r" and a[-2]=="u" and a[-3]=="t":
i.append(a)
#записываем список в файл
f = open("output.txt","w")
f.write("\... |
c8afd3010906603dd02cc8d4629c0eb901c803df | Kavi1808/beginer-2 | /armstrong or not.py | 204 | 3.703125 | 4 | num=135
order=len(str(num))
sum=0
temp=num
while temp>0:
digit=temp%10
sum+=digit**order
temp//=10
if num==sum:
print(num,"armstrong")
else:
print(num,"not armstrong")
|
628dc941223a5aae5fc81402c66c523e136dd450 | hboonewilson/1CS | /Homework/home_work1.py | 6,625 | 3.765625 | 4 | #Presume that you can only drive 8 hours per day. So, if a trip requires 15.25
#hours, it will require a one-night hotel stay at an additional cost (beyond gas
#and food costs) equal to hotelCostPerNight.
def tripCostAndInfo(distanceKM, vehSpeedMPS, vehKPL, gasCostPerLiter, breakfastCostPerDay,
lu... |
e42364ed8430045d297604cade4e3f8048c40847 | peternortonuk/reference | /python/class/abc.py | 976 | 4.3125 | 4 | '''
https://www.python-course.eu/python3_abstract_classes.php
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared,
but contains no implementation.
Abstract classes may not be instantiated, and require subclasses to provide implementations for the abs... |
079047d57b63b3a7887423e3b8c60dbc2470b994 | Yihan-Dai/Leetcode-Python | /4Sum/solutionTLE.py | 1,409 | 3.84375 | 4 | '''
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate ... |
9639a1717b7a146d70c2671f91271a2fddf105aa | Andrespazmi/Ejercicios1-parcial | /s2 ejercicio 1.py | 225 | 3.53125 | 4 | # SEGUNDA SEMANA, PRIMER EJERCICIO
""" """ num=20
if type(num) ==int:
print("respuesta; ",num*2)
else:
print("No es numerico")
def mensaje("men")
print(men)
mensaje("Primera tarea")
mensaje("Segunda tarea ") """ |
caa3b319f92b4803b8d42057ecf2fe75eafb1aa7 | bhotw/Puzzle-Hunt | /coins3-yellow/PuzzleHunt.py | 277 | 3.875 | 4 | def reverse_caesar_shift(message, shift):
secret = ""
message = message.upper()
for letter in message:
if letter == ' ':
secret += letter
else:
secret += chr((ord(letter) - ord('A') - shift) % 26 + ord('A'))
print(secret) |
e3ffaff0b7d907b789a1b2583c36ebd76d3cc3f7 | vishipayyallore/LearningPython_2019 | /Session1/CustomModules/stringmodule.py | 410 | 3.71875 | 4 | def show_characters_v1(name):
for index in range(len(name)):
print(name[index], end=' ')
else:
print()
def show_characters_v2(name):
end_count = -1 * (len(name) + 1)
for index in range(-1, end_count, -1):
print(name[index], end=' ')
else:
print()
def show_reverse_... |
c68e9c8b534bb0b3447e1e0acec1077b915a65ba | mlitfin123/AmeritradeTradingApp | /env/Lib/site-packages/btalib/indicators/mfi.py | 1,732 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
# Copyright (C) 2020 Daniel Rodriguez
# Use of this source code is governed by the MIT License
###############################################################################... |
3f6b4352c9960a316745d25cc88dc3da11a05b34 | trippieiv/escaperoom | /map.py | 5,432 | 3.734375 | 4 | from items import *
room_cupboard = {
"name": "Cupboard",
"description":
"""You are currently stuck in a cupboard on the second floor of
a strange house. Your challenge is to overcome the obstacles and get
out of the house. The cupboard has an exit to the east and some wired
coat hangers in the corner of ... |
83ad02261c6d5f4a9624b87da203cae7764f48e8 | RazvanKokovics/Planes | /imports/queue.py | 638 | 3.84375 | 4 | class Queue:
def __init__(self):
#initializes a a queue data structure
self._data = []
def push(self, item):
#function that pushes an item in the queue
self._data.append(item)
def pop(self):
#function that pops an item from the queue
#it returns t... |
bd628ebfebd7c0455aca4a593c189c50a998e522 | MarehanRefaat/HackerRank_Solutions | /10 Days of Statistics/Day 7: Spearman's Rank Correlation Coefficient/solution.py | 350 | 3.515625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
x = [float(i) for i in input().strip().split(" ")]
y = [float(i) for i in input().strip().split(" ")]
x_s = sorted(list(x))
y_s = sorted(list(y))
d = ([(x_s.index(x[i])-y_s.index(y[i]))**2 for i in range(n)])
res = 1-6*sum(d)/(n*(n*... |
510466c5c4fa8c7efc5420cf51e83bb46d313682 | aynulislam/python_basic_covid_19 | /day6 part1.py | 1,976 | 3.96875 | 4 | #1 two dimensonal list
matrix = [
[10,20,30],
[12,16,18],
[15,25,35],
]
print(matrix[0][0])
print(matrix[1][2])
print(matrix[2][1])
for row in matrix:
for item in row:
print(item)
#practice
mat = [
[1,2,3,],
[2,3,4,],
[4,5,6],
]
for a in mat:
for b in a:
print(b)
#2
numbers =... |
49b6025ab39e528242d36336c8bebdc0f94cdd8c | andrecontisilva/Python-aprendizado | /diversos/PythonLogic.py | 1,128 | 4.25 | 4 | # Questão 1
# A lógica abaixo é um exemplo de sequência de Fibonacci.
# A questão queria saber qual seria o resultado de print(f(10)) [== 55]
# Mais detalhes em: http://www.devfuria.com.br/logica-de-programacao/recursividade-fibonacci/
"""
def f(i):
if i == 1 or i == 2:
return 1
return f(i-1) + f(i-2)
... |
92eb8575fde4b4525216c76823db8b4245ca0072 | manucirne/camadaFcomp | /4.HandShake2/enlaceTx.py | 4,419 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#####################################################
# Camada Física da Computação
#Carareto
#17/02/2018
# Camada de Enlace
####################################################
# Importa pacote de tempo
import time
# Threads
import threading
# Class
class TX(object):... |
5f7b5df87fad52417dd75b0582af9633bf5f3825 | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/101_15.py | 2,739 | 4.46875 | 4 | Python | Index Maximum among Tuples
Sometimes, while working with records, we might have a common problem of
maximizing contents of one tuple with corresponding index of other tuple. This
has application in almost all the domains in which we work with tuple records.
Let’s discuss certain ways in which this ta... |
ccc478a11489932987c21ab38cf3577104cac1b3 | wangrui0/python-base | /com/day07/demo03_local_global_variable_diff.py | 1,066 | 3.6875 | 4 | '''
局部变量
def get_wendu(): # 如果一个函数有返回值,但是没有在调用函数之前 用个变量保存的话,那么没有任何的意义
wendu = 33
return wendu
def print_wendu(wendu):
print("温度是:%d" % wendu)
result = get_wendu()
print_wendu(result)
'''
# 定义一个全局变量
temperature = 0
# def get_temperature():
# temperature = 33 # 注意这只是新定义了一个局部变量
def get_temperature()... |
de4a44dfc75940f4aa74634d41b7af393fad3f91 | PiJoules/Kalman-Filter | /kalman.py | 4,289 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy
class KalmanFilterLinear(object):
"""
Class modelling a linear Kalman Filter.
Linear because all the matrices used are constant and do not change
over time.
Equations
State prediciton:
Get our prediction of the next state giv... |
68b9be7ceec2689ea655889b2f44bbef01ce0b6e | TrevorMorrisey/Project-Euler | /Python/pe004.py | 806 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 12 21:27:46 2019
@author: TrevorMorrisey
"""
def isPalindrome(string):
if len(string) == 1 or len(string) == 0:
return True
elif len(string) == 2:
return string[0] == string[1]
else:
if string[0] != string[len(string) - 1]:
... |
4de755ac11e20074407d339475cc1fcb2c4d83fd | Alireza-IT/python-practice | /jadi/4.sheygaraei ersbari.py | 725 | 4.03125 | 4 | class Computer:
count = 0 # moshtarke va age taghiri az taraf ye objecti ru in beshe bara hame avaz mishe
def __init__(self, ram, hard, cpu):
Computer.count += 1
self.ram = ram
self.hard = hard
self.cpu = cpu
def value(self):
return self.ram + self.hard + self.cpu... |
8a0ff01a6eaceb990f41d03c4f11c79ccb315274 | j2woong1/algo-itzy | /SWEA/implementation/1974-스도쿠_검증/1974-스도쿠_검증-yeonju.py | 1,559 | 3.5 | 4 | def check_square(v):
x, y = v
box = [0] * 10
box[0] = 1
for i in range(3): # 3 x 3 박스 안에 1~9 모두 있나 확인
for j in range(3):
box[arr[x+i][y+j]] = 1
res = 1
for i in box:
if i != 1:
res = 0
break
return res
def check_vertical(v... |
962316774571f4d0c226d0d2a7f3396effd86bc2 | JEmbry2019/Tuesday_Python_Project | /jeopardy.py | 823 | 3.59375 | 4 | import csv
with open('jeop_question.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter='\t')
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count += 1
else:
for row in csv_reader... |
39e35e08489f33de16460f38649eb204bee63ce4 | vimleshtech/python-tutorial | /Sandbox/Python-Handson/GUI/8-Combo.py | 147 | 3.53125 | 4 | from tkinter import *
window = Tk()
combo = Combobox(window)
combo['values']= (1, 2, 3, 4, 5, "Text")
combo.current(3)
combo.grid(column=0, row=0)
|
4acdc3e8e4eb5729895781be3d52aeaca8f9cc9c | MD-AZMAL/python-programs-catalog | /questions/Trees/binary-trees/delete-tree.py | 251 | 3.6875 | 4 | """Author - Sidharth Satapathy"""
# Problem 9
# Assuming that the tree has getData(), setData(), getLeft(), getRight()
# Deleting a tree
def deleteTree(root):
if root is None:
return
deleteTree(root.left)
deleteTree(root.right)
del root |
47acb894929cd25c7a6fee22bacaa4a2a93935ad | dotchetter/RobBotTheRobot | /source/menu.py | 2,232 | 3.6875 | 4 | from datetime import datetime
from weekdays import Weekdays
"""
Details:
2019-11-24
Module details:
Lunch menu scraping feature
Synposis:
Provide a way for the chatbot to scrape
the lunch menu for the restaurant in school.
Return the menu scraped off the website.
"""
class Menu:
"""
Represent a menu in the... |
051bfcb3cfc4b31b506f9b0d26b7f0840745a01d | simnyatsanga/pandas-sklearn | /playing-with-pandas.py | 1,440 | 3.625 | 4 | import numpy as np
import pandas as pd
from pandas import DataFrame
import datetime
import pandas.io.data
import matplotlib.pyplot as plt
import sklearn
cars_df = pd.read_csv('ToyotaCorolla.csv')
print cars_df.shape
print cars_df.head()
cars_df['FuelType1'] = np.where(cars_df['FuelType'] == 'CNG', 1 , 0)
cars_df['Fue... |
2fb99cad816dc94df31676d9bd54c7dfecf101fa | juliencampus/python | /Denis/CalculTVA2/main.py | 1,546 | 3.890625 | 4 | # This is a sample Python script.
# Press Maj+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import math
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}')... |
2454bcd7025cdc5e16d91910c45e1532be959e89 | acondorba/Practicas---Python | /Problemas Python/Módulo 4/scripts/Problemas_Diversos.py | 3,316 | 3.859375 | 4 | print('Parte 1')
n = int(input('Introduce un número entero entre 1 y 10: '))
file_name = 'tabla-' + str(n) + '.txt'
f = open(file_name, 'w')
for i in range(1, 11):
f.write(str(n) + ' x ' + str(i) + ' = ' + str(n * i) + '\n')
f.close()
print('-------------------------------------------------------------------... |
446b1c03eed13eebab18936d42dec354eb3ccd38 | Nicortiz72/ICPC_AlgorithmsProblems | /uva/846.py | 522 | 3.546875 | 4 | from sys import *
Sumatory=[0,1]
Values=[0,1]
n=3
i=2
lim=1<<31
while n<=lim:
Sumatory.append(n)
Values.append((2*Sumatory[i//2])+(0 if i%2==0 else (i//2)+1))
i+=1;n+=i
def binarySearch(k):
low=0;high=len(Values)
while low+1!=high:
mid=(low+high)>>1
if(Values[mid]==k): return mid
elif(Valu... |
4a6d72ec79d83d3cd098a8c03b719c90c8bcddb5 | IgnacioLoria1995/cursoPythonTest | /ejercicioII-test.py | 956 | 3.953125 | 4 | #Ejercicio II-test
#personas = int(input('Cuantas personas desea registrar?: '))
#while personas <1 or clientes >120:
# personas = int(input('Cuantas personas desea registrar?: '))
# print('Perfecto, iniciando proceso')
#else:
# print('Numero no valido de personas')
clientes = int(input('Ingrese numero de cli... |
6a764fd49bb0b8173adf004d9b5177b6145c5653 | liukai234/python_course_record | /函数和lambda表达式/lambda表达式.py | 1,494 | 4.28125 | 4 | '''
lambda表达式:lambda [parameter_list] : 表达式
语法格式要点:1、必须要lambda关键字来定义
2、lambda之后、冒号左边是参数列表,可以没有参数或者多个参数,右边是表达式的返回值
3、只能是单行表达式,本质上是匿名的、单行函数体
'''
# lambda表达式代替局部函数
def get_math_func(type):
'''
def square(n): # 求平方
return n*n
def cube(n): # 求立方
return n * ... |
b083f970fb35d2aacb1c4f2d4cb6c312b96dd642 | greenfox-velox/danielliptak | /week3/day3/11.py | 470 | 3.875 | 4 | def create_triangle(hypotenuse):
if hypotenuse % 2 == 0:
print('Please give me odd number')
else:
for line in range(hypotenuse + 1):
star = line * '*'
space = int((hypotenuse - line) / 2) * ' '
if not line % 2 == 0:
print(space + star)
for line in range(hypotenuse-1, -1, -1):
... |
c881d368184de47b885903d7d3d9fad4c4d0fa65 | AnushkaTiwari/FSDP_2019 | /Day03/teen_cal.py | 421 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 12:21:57 2019
@author: ANISHKA
"""
# Code Challenge : Teen Calculator
sum1=0
Dict={}
for num in range(3):
user=input("Enter the user name: ")
values=int(input("Enter the integer values: "))
Dict[user]=values
print(Dict)
if (values>=13 and values<20... |
ef0ce6c54a9e1bc98804a3982255bb4a6ae0f6fd | jamiezeminzhang/Leetcode_Python | /ALL_SOLUTIONS/121_OO_Best_Time_to_Buy_and_Sell_Stock.py | 888 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 3 22:59:20 2016
121. Best Time to Buy and Sell Stock
Total Accepted: 84382 Total Submissions: 240817 Difficulty: Medium
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transacti... |
b36ea86ab103d2ff603e09e4bf77e2f088c3483d | uchenna-j-edeh/dailly_problems | /after_twittr/unique_char.py | 531 | 4.125 | 4 | """
Implement an algorithm to determine if a string has all unique characters What if you can not use additional data structures?
example: input: 'uchenna'
output: false
"""
def is_unique_char(text):
#assuming it's ascii char which is 256 characters
my_list = []
for i in range(256):
my_list.append(... |
b5fec61309f25d77ef0099be1348b674ad74a653 | icancode20/my-codes | /Teach/Day 2/python ++.py | 298 | 3.78125 | 4 | import turtle
A = turtle.Pen()
turtle.bgcolor("black")
A.speed(0)
colors = ["red", "blue", "white"]
for x in range (150):
A.pencolor(colors[x % 3])
A.forward(x)
A.left(120)
A.goto(10,10)
for N in range (200):
A.pencolor(colors[N % 2])
A.circle(N)
A.left(45)
turtle.done() |
f3e4a992c8d98c6c11003855af340a10dafcc1d4 | wfsfgedtwwwarfsge/python_programming | /default/default_simple_error.py | 547 | 3.984375 | 4 | def greet(name, msg="Good morning!"):
"""
This function greets to
the person with the
provided message.
If the message is not provided,
it defaults to "Good
morning!"
"""
print("Hello", name + ', ' + msg)
greet("Hrishikesh")
greet("Shalini", "How do you do?")
def greet(msg = "Go... |
f74b153c6af9dc791007fe2c2ab3311477792105 | metajinomics/dev | /fasta_tools/print_len_fasta.py | 647 | 3.609375 | 4 | #!/usr/bin/python
#usage: python print_len_fasta.py fastafile
import sys
flag = 0
length = 0
seq = []
name = ""
for line in open(sys.argv[1],'r'):
if (flag == 0 and line[:1]==">"):
name = line.strip()
flag = 1
continue
elif (flag == 1 and line[:1]==">"):
temp = ''.join(seq)
... |
111c8642273fdffe4899d0e35bb27e9cc213583e | nhlshstr/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 227 | 3.625 | 4 | #!/usr/bin/python3
"""Contains class that inherits list"""
class MyList(list):
"""My list class inherited from list"""
def print_sorted(self):
""" Function to print sorted list """
print(sorted(self))
|
3c85ee4b838f8f0d9228677697cea9bd175603f5 | rscai/python99 | /python99/mtree/p501.py | 272 | 3.5 | 4 | from functools import reduce
from operator import and_
def istree(t):
if type(t) is not tuple:
return False
if len(t) != 2:
return False
if type(t[1]) is not list:
return False
return reduce(and_, [istree(e) for e in t[1]], True)
|
78b004b389db7b5ebb14c305a296d97ba6441d2c | tanneo/Python_exercises | /ex34.py | 202 | 3.90625 | 4 | #accessing elements of lists
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
print(animals[0])
print(animals[1])
#skip this exercise as familar with Syntax and move onto next |
03ea6dd6b98ce96efc490807f9fcf16bae986ea3 | CityofToronto/tw-front-back | /django/djangoAPI/utils.py | 994 | 3.640625 | 4 | '''Some General Utils'''
def num_to_alpha(num):
'''
Converts a number to its alpha base(26) implimentation
Starts at 1 = a, 27 = aa
'''
lst = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
if num < 2... |
8846ac77857c01c0a4cf6cbe718f5dbd7b16189a | marcosrodriguesgh/PythonCertificate | /lab5_1_11_9The_Digit_of_Life.py | 248 | 3.796875 | 4 | def digit_of_live(dateofbirth):
output = 0
for x in dateofbirth:
output += int(x)
return digit_of_live(str(output)) if output >= 10 else output
date = input('Please, give you birthday (YYYYMMDD): ')
print(digit_of_live(date))
|
9d9f9c21cb7edd8c2bbdd3e1e318380a5255cc27 | SB1996/Python | /Function/Function.py | 219 | 3.5625 | 4 | # Functions in Python ...!
# Function declaration
def displayName(_name) :
# Function defination
print(f"Hiii i'm {_name}")
return _name
name = displayName("Santanu Banik") # Function call
print(f"Name : {name}") |
3435f3c40fb565a83dc18907408aad5fb2fae528 | AbishaStephen/Codekata | /palin.py | 597 | 3.65625 | 4 | string = input("Enter the string")
string_shortener = ""
a = 0
s = 3
p_temp=0
s_temp=0
long = ""
for i in range(len(string)-2):
string_shortener = string[a:s]
if(string_shortener==string_shortener[::-1]):
p_temp = a
s_temp = s
for u in range(1000):
p_temp-=1
s_temp +=1... |
8c4c143c73941a6a115cdee9cc84655b87be0794 | monishnarendra/Python_Programs | /Insertion_Sort.py | 472 | 3.953125 | 4 | import time
list1 = []
n = int(input("Enter the number of elements in the list"))
for i in range(0,n):
list1.append(int(input("Enter the list elements")))
start_time = time.clock()
for i in range(1, len(list1)):
j = i
while j > 0 and list1[j] < list1[j - 1]:
temp = list1[j]
list1... |
2e42d5a847c8a572eaefa9605ec6d7db59ae3750 | Rithik57/AI | /Informed and Uninformed/TSP brute force.py | 1,159 | 3.578125 | 4 | from itertools import permutations
from sys import maxsize
V = 4
def TSP(graph, S): #receives the graph and the starting vertex
# store all non active vertices in a list
vertex = []
for i in range(V): # V -> number of vertices
if i != S:
vertex.append(i)
minPath = maxsi... |
286a09b776c1c1335b6cda826f3b0e39676d514b | amaterasu1577/news | /main.py | 267 | 3.53125 | 4 | from client import News
def main():
news = News()
country = input("What country are you interested in?\n> ")
headlines = news.country_headlines(country)
for headline in headlines:
print(f"- {headline}")
if __name__ == '__main__':
main()
|
318b1fc380feaced13494796ba95fc26486ceb04 | AndreyNagorskiy/Geekbrains | /Python algorithms and data structures/2_Задание/les_2_task_3.py | 489 | 4.15625 | 4 | """ 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.
Например, если введено число 3486, надо вывести 6843."""
num = int(input('Введите целое число:'))
n2 = 0
while num > 0:
remainder = num % 10
num = num // 10
n2 = n2 * 10
n2 += remainder
print(f'Обра... |
f3aea1a8e16031b9f30e22c4e21decfb835e7023 | kalyan-ch/SltnsCrkdCpp | /Ch3StcksNQs/34QwStks.py | 411 | 3.828125 | 4 | #implement a queue with two stacks
from QueWStcks import NewQueue
from random import randint
qu = NewQueue()
qu.push(randint(1,100))
qu.push(randint(1,100))
qu.push(randint(1,100))
qu.push(randint(1,100))
print "before"
qu.printQ()
print "popping the q"
print qu.pop()
print qu.pop()
qu.push(randint(1,100))
print ... |
f09d716237ab693be041a6656664c88bc2b41c02 | guozanhua/xnn | /examples/mnist_loader.py | 2,346 | 3.515625 | 4 | import sys
import os
import numpy as np
from xnn.utils import numpy_one_hot
# ################## Download and prepare the MNIST dataset ##################
# This is just some way of getting the MNIST dataset from an online location
# and loading it into numpy arrays. It doesn't involve Lasagne or XNN at all.
def load_... |
8d59ac7347895230af851ab828fe075ceb0ae01e | ThaisMB/Curso-em-Video-Python-Exercicios | /ex058.py | 589 | 3.546875 | 4 | from random import randint
from time import sleep
palpite = 0
chute = 11
print('Pensei em um número entre 0 e 10. Você consegue adivinhar?')
computador = randint(0,10)
while chute!=computador:
chute = int(input('Em qual número eu pensei?'))
print('\033[33m PROCESSANDO... \033[m')
sleep(2)
... |
c1561fa35083edb3c4ac52f782a44d4961e8ddb3 | marklittle716/pythonfiles | /dictionary.py | 409 | 4 | 4 | # A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
# Create dict
person = {
'first_name': 'John',
'last_name': 'Doe',
'age': 30
}
# Use constructor
person2 = dict(first_name='Sara', last_name="Connors")
print(person['first_name'])
print(person.get('last_name... |
eebfeba72961a6ee91b77dd0444c71448424a9a0 | MantieReid/100-days-of-code-round-2 | /Day 6/Fizz Buzz.py | 837 | 4.1875 | 4 | from typing import List
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
alist = [] # create a empty list
for i in range(1, n + 1): #use range to generate the numbers to add to the list
if i % 3 == 0 and i % 5 == 0: # if the number is a a multiple of 3 and five. Then add the string FizzBuzz t... |
238127df834944d1b95b4be4d4456937e270ed3c | paymog/ProjectEuler | /Problems 70-79/71/bruteforce.py | 412 | 3.875 | 4 | # this is way too slow
from fractions import Fraction
fractions = set()
for denom in range(1, 1000001):
# print "testing %d" % denom
for num in range(denom * 3/7 -3, denom * 3 / 7 + 3):
fractions.add(Fraction(num, denom))
print "Converting to list"
fractions = list(fractions)
print "Sorting"
fractio... |
725780126984dc3b8f2a7f2a61f48593c800b328 | samisken/CSE-231 | /proj06[1].py | 35,096 | 4 | 4 | ##################################################################################
#
# CSE 231 Project #6
# Samuel Isken CSE 231 - 730
#
#
# Algorithm
# Display hand and community cards and winner of hand
# ask if player wants to play again
# deal new hand and check all possible combos to determine winning h... |
4003ef6d31645c8c0ce59ec34985805593f10072 | Stran1ck/python_mini | /qwerty.py | 131 | 3.9375 | 4 | n = input()
m = input()
if len(n) < 7 and len(m) < 7:
print('Short')
elif n == m:
print('OK')
else:
print('Difference') |
03d0fe33796fae3335931ef032527c6a135d0e0f | Wambuilucy/CompetitiveProgramming | /Project Euler/ProjectEuler2.py | 712 | 3.8125 | 4 | #! /usr/bin/env python
'''
Project Euler 2 (https://projecteuler.net/problem=2)
Even Fibonacci Numbers
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the ... |
3b6a0c4afe13b564e25c3f04a7563de076e5f451 | ryanmp/project_euler | /p003.py | 675 | 3.5625 | 4 | '''
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
import math
def factors(n):
return reduce(list.__add__,
([i, n//i] for i in range(1, int(math.sqrt(n)) + 1) if n % i == 0))
def is_prime(n):
for i in xrange(2,int(math.sqrt(n))+1):
if n... |
cffd704fff0b7f39ffcdd3ecde13a5b8f6f5aa27 | ipeterov/random-stuff | /Утилиты/remove_shit_from_filenames_recursive.py | 674 | 3.53125 | 4 | import os
from os.path import join, getsize
path = input('Path: ')
shit = input('Shit: ')
to_be_renamed = []
for root, dirs, files in os.walk(path):
for f in files:
if shit in f:
#print('AAAA!! FOUND SHIT!!!1')
new_f = f.replace(shit, '')
to_be_renamed.append(join(root,... |
7d528974dd8f7e3856fdd67fb10a1c4af970859d | rajkonkret/python-szkolenie | /pon_3_ex6.py | 160 | 3.96875 | 4 | def is_even(number):
return number%2==0
number = int(input('Podaj liczbe'))
print(is_even(number))
mask = (1 << 2) - 1
little = number & mask
print(mask)
|
a5f336bbd976af28f84c03bafff3c6133d03dba9 | PIvanov94/SoftUni-Software-Engineering | /Programming Fundamentals Python 2020 Part 1/Final Exam Problem 1.py | 1,479 | 4.0625 | 4 | text = input()
line = input()
while not line == "Finish":
data = line.split()
command = data[0]
if command == "Replace":
current_char = data[1]
new_char = data[2]
text = text.replace(current_char, new_char)
print(text)
elif command == "Cut":
start_ind... |
1509382beeb72538bc96a9d6e8ebb593d774e150 | silvadanilo/exercism | /python/word-count/word_count.py | 171 | 3.6875 | 4 | import re
from collections import Counter
def count_words(phrase):
splitted = re.findall(r"([a-z0-9]+(?:\'[a-z0-9]+)?)", phrase.lower())
return Counter(splitted)
|
7d0e1d4b42b9abee51a3f5fe9bf3257f79552b97 | weichuntsai0217/leetcode | /281-Zigzag_Iterator.py | 1,342 | 3.96875 | 4 | """
* Ref: https://discuss.leetcode.com/topic/24223/python-o-1-space-solutions
* Key points: No
* Explain your thought:
- Change v1 and v2 into iterator, and store them in a matrix
- When the "next" method is called, we alway return the top row of
the matrix, and append this row to the bottom of the matrix to k... |
a5d02ff50e1ad7708c08aa475200bdd695ecaa8e | ElizabethFoley/Text-Based-Game | /game.py | 15,871 | 3.59375 | 4 | # CMPT 120L 113
# Libby Foley
# 20 Sep 2018
###
##
# In my final commit, I added a class object for the player and the locales
# I added and "use item" feature for the candle
# I made the candle have "limited uses"
# I added the ability for the player to asce... |
2f9a8ff361746408c214205f910dd05d45c4f2cf | 02dirceu/jogo-forca | /forca.py | 5,162 | 3.796875 | 4 | import random
def jogar(): #Função responsável por executar o jogo abrindo todas as outras funções
abertura()
palavra_secreta = carrega_palavra_secreta()
lista_letras = letras_acertadas(palavra_secreta)
regras(palavra_secreta, lista_letras)
print("Fim do jogo")
def aber... |
c878db51505a2cd2b6aa05ba1cdbe1ce8e280419 | das888purnendu/number-to-word-convertor-python3 | /num_cal.py | 2,873 | 3.953125 | 4 | def ten(tn):
if(tn=="10"):
return "Ten"
elif(tn=="11"):
return "Eleven"
elif(tn=="12"):
return "Twelve"
elif(int(tn[1])>2):
return num(tn[1])+"teen"
def num(d):
if(d=="2"):
return "Twen"
elif(d=="3"):
return "Thir"
elif(d=... |
f4da6a5a3e69dd7f94e517523d3ae60b370f1dfa | agustinpodesta/Python-Course | /ejercicios_python/torre_de_control.py | 2,469 | 4.09375 | 4 | class Cola:
'''Representa a una cola, con operaciones de encolar y desencolar.
El primero en ser encolado es tambien el primero en ser desencolado.
'''
def __init__(self):
'''Crea una cola vacia.'''
self.items = []
def encolar(self, x):
'''Encola el elemento x.'''... |
f9906f84e4705ddaa794cc2c7ef5e0bb9f1a4433 | Mr0grog/ca-covid-vaccination-stats | /ca_covid_vaccination_stats.py | 13,188 | 3.515625 | 4 | from ca_counties import california_counties
from datetime import datetime
import dateutil.tz
import json
import requests
PACIFIC_TIME = dateutil.tz.gettz('America/Los_Angeles')
def parse_tableau_json_stream(raw):
"""
Tableau's data is a series of JSON blobs, each preceded by the number of
bytes or chara... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.