blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0a59e34aebbfa91a9234994b98f3b9674b1ab7b5 | TedYav/CodingChallenges | /leetcode/word_break_2.py | 7,887 | 3.859375 | 4 | """
Word Break II:
Given non-empty string s and non-empty non-empty word containing dictionary d, return all possible sentences formable from s.
Solutions:
Brute Force: try all possible combinations of spaces. O(2^n) to try all possible combinations. Could take O(n) to verify each, so this... |
b71c6a4a8425bcb64d0ccad9825f1b98091ed62a | brittainhard/py | /cookbook/data_structures/chainmaps.py | 824 | 4.0625 | 4 | from collections import ChainMap
"""
If you delete an item from a dictionary, it always deletes it from the latest
dictionary.
This will make those dictionaries incongruent.
"""
a = {"x": 1, "z": 3}
b = {"y": 2, "z": 4}
c = ChainMap(a, b)
del c["z"]
print(c)
"""
Scoped variables?
Lets you keep a dict that has a c... |
3227ad6dac7ba4551b9a3180cfb3e7c03be1f58f | AmigaTi/Python3Learning | /interface/ui-tkinter-widgets/tkinter-spinbox.py | 943 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from tkinter import *
# Spinbox
root = Tk() # 初始化TK()
root.title('Tkinter - Spinbox') # 设置窗口标题
root.geometry('300x200') # 设置窗口大小
root.resizable(width=False, height=True) # 设置窗口的长宽是否可变
Spinbox(root,
from_=0, ... |
3fa4549d4fd5b3c29823d6cbf510fa8a95df79a9 | CateGitau/Python_programming | /LeetCode/top_interview_questions/MaximumDepthBinaryTree.py | 942 | 4.1875 | 4 | '''
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path
from the root node down to the farthest leaf node.
'''
#Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
se... |
837f52385ba68a21474c0e30f72c6f3a135834df | MrHamdulay/csc3-capstone | /examples/data/Assignment_4/mphkam003/boxes.py | 756 | 4 | 4 | def print_square():
print("*****")
print("* *")
print("* *")
print("* *")
print("*****")
def print_rectangle(width, height):
print("*"*width)
for i in range(height-2):
print("*"+" "*(width-2)+"*")
print("*"*width)
k=0
def get_rectangle(width, height)... |
d28c340712b09038f390803949c8cb4474238263 | GrigoriyPL/10.04.21 | /13.03.2021(3).py | 218 | 3.921875 | 4 | x = int(input('x = '))
y = int(input('y = '))
def xyz():
z=0
if y>0:
if x > 0: z = "I"
else: z = "II"
else:
if x < 0: z = "III"
else: z = "IV"
print(z)
xyz()
|
245318b875d16486271e0449582613926afd021d | kemar1997/Python_Tutorials | /Challenge1.py | 241 | 3.9375 | 4 | """
Creating a for loop that loops through zero to one hundred and only prints a multiple of 4
until it reaches to 100.
"""
for x in range(4, 101, 4):
print(x)
if 100 < x:
print("Whoa you have exceeded your normal capacity.") |
4b020de7ef67b58b38868881e7b0285e206c5151 | Syuanbo/code_collection | /code/FindStrinFile | 1,759 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
import os
import chardet
ftype =['.txt', '.html', '.php'] #要查找包含字符的文件后缀
def findstr(dirname, fstr):
for filenames in os.listdir(dirname):
filenames = os.path.join(dirname, filenames)
if os.path.splitext(filenames)[1] in ftype: #找到要处理后缀的文件
wi... |
e332d5c39195ae966ade0c65b72de501ff088625 | jpmcb/interview-problems | /ctci/2_4.py | 848 | 4.03125 | 4 | # Partition
from LinkedList import LinkedList
def make_partition(llist, val):
# generate two linked lists around the partition
llist_a = LinkedList()
llist_b = LinkedList()
node = llist.head
while(node != None):
if node.data < val:
llist_a.add(node.data)
else:
... |
a2bfc0fd5dec69dcc25815040039bb8aedd70093 | DenizenB/advent-of-code | /2019/2a.py | 1,108 | 3.828125 | 4 | class Computer:
def __init__(self, memory):
self.pc = 0
self.memory = memory
def execute(self):
while self.pc >= 0 and self.pc < len(self.memory):
self.step()
return self.memory[0]
def step(self):
op = self.memory[self.pc]
if op is 99:
... |
016e2bc6e020899bb307877c28d95a74eff5bfff | omgimanerd/trump-clinton-analyzer | /analyze.py | 1,303 | 3.53125 | 4 | #!/usr/bin/python
from collections import defaultdict
import json
import re
def aggregate(filename):
with open(filename) as f:
return " ".join(json.load(f))
def get_stopwords():
with open('data/stopwords.txt') as f:
return f.read().strip().split('\n')
def word_frequency(string):
string ... |
5525e6f9f6d733d70fdc2da8f0083c0987258bd2 | bexshinderman/DSMI_Code | /Code/hello.py | 6,974 | 4 | 4 | import random #libraries
import time
print("Hello World!")
print("*****************************************")
print("****************user input********************")
userName = input("What is your name?") #Python 3.X or later
print("hello " + userName)
counter = 3 # An integer assignment
weight = 80.5 ... |
dd12416e62cdb9ec1748f796b29b62e02925413a | yycang/Bucciarat | /剑指offer/two.py | 906 | 3.75 | 4 | # 实现单例
"""使用new方法, 将类的实例绑定在类变量上,判断是否为none,
如果没有的话,new一个该类的实例并返回,没有的话直接返回类变量"""
class Singleton:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
singer = super(Singleton, cls)
cls._instance = singer.__new__(cls, *args, **kwargs)
return cls._instance
... |
fa3ee4f4b9232e11841c85f9abebf93ff0c1b974 | stasvorosh/pythonintask | /PINp/2014/KOROTKOVA_D_S/task_2_39.py | 608 | 3.78125 | 4 | # Задача 2 Вариант 39
# Текст задачи Напишите программу, которая будет выводить на экран наиболее понравившееся вам высказывание, автором которого является Гомер. Не забудьте о том, что автор должен быть упомянут на отдельной строке.
# Короткова Д.С.
# 05.03.2016
print("Женщину украшает молчание.")
print("\t\t\t\t\t\... |
dd9b6f7df0fe7d3cb735525739cb2ef64531b80a | GuiGolfeto/curso-em-video | /mundo 1/Usando módulos do Python/exercicios/ex017.py | 204 | 3.6875 | 4 | from math import hypot
op = float(input('Digite o valor do Cateto oposto: '))
ad = float(input('Digite o valor do Cateto adjacente: '))
hip = hypot(op, ad)
print(f'O valor da hipotenusa é {hip :.2f}')
|
77ab262c7e603d3196a61f8d691b2a6896e6a46c | Littlemansmg/pyClass | /Week 5 Assn/Project 14/14-1.py | 1,506 | 4 | 4 | # created by Scott "LittlemanSMG" Goes on DD/MM/YYYY
class Rectangle:
def __init__(self, height, width):
self.height = height
self.width = width
def area(self):
return self.height * self.width
def perimeter(self):
return (self.height + self.width) * 2
def show_rect(s... |
bd1e62da5fb9f1e9f5e630677171339e56bef3e9 | dianvaltodorov/learning-code | /learning-dsa/cracking_the_coding_interview/chapter_2/2.4.py | 574 | 3.625 | 4 | class Node:
def __init__(self, data, next=None):
self.next = next
self.data = data
n1 = Node(3)
n1.next = Node(1)
n1.next.next = Node(5)
n2 = Node(5)
n2.next = Node(9)
n2.next.next = Node(2)
def calculate_sum(n1, n2):
sentinel = Node(0)
head = sentinel
carry = 0
while n1 and n2... |
28af10f7274e2dafff250be4721ced2dafd28f2f | DIPEA/Newer-s-Python-program | /guess.py | 479 | 3.921875 | 4 | import random
secret = random.randint(1,99)
guess = 0
tries = 0
print("game start")
while guess != secret and tries < 6:
guess = input("what is your guess?")
if int(guess) < secret:
print("too low")
elif int(guess) > secret:
print("too high")
tries = tries + 1
if int(gues... |
a9e3874be94922475f6d585a804fd6dd91134270 | MaxZN/Leetcode | /111.二叉树的最小深度.py | 691 | 3.609375 | 4 | #
# @lc app=leetcode.cn id=111 lang=python3
#
# [111] 二叉树的最小深度
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: ... |
7284f8d2221b932023475398c7e7b48c3975f1db | huangruihaocst/leetcode-python | /700. Search in a Binary Search Tree/solution.py | 957 | 3.828125 | 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 searchBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
de... |
3ac619ba22899ebc44b65599470c719007aa6519 | xinyang12/python_practice | /5/14.py | 430 | 3.96875 | 4 | def main():
file_name = input("输入文件名: ")
infile = open(file_name, "r")
line_count = 0
word_count = 0
char_count = 0
for line in infile:
line_count += 1
word = line.split()
word_count += len(word)
for ch in line:
char_count += 1
print("行数是:", line_... |
eb4f5389153723596890858b0f7fd3c101930651 | alvarovdt/100-Days-Of-Code-Udemy | /100 Days of Code/2. Intermediate [15-31]/Day 15 Coffee Machine/main.py | 2,219 | 4.03125 | 4 | from data import MENU
from data import resources
my_money = 0.0
machine_money = 0.0
machine_on = True
def ask_and_insert_coins():
local_money = 0.0
print("Please insert coins")
quarters = int(input("How many quarters? (25cents)"))*0.25
dimes = int(input("How many dimes? (10cents)"))*0.10
nickels = int(i... |
76c0a75284a69f412ede04aced2a1f0cbaa849bc | justinta89/Work | /PythonProgramming/Chapter 5/Exercises/quizzes.py | 449 | 4.1875 | 4 | # quizzes.py
# This program will take a user input quiz score 1 - 5, then output the appropriate grade.
def main():
# Get grade from user
grade = int(input("Enter grade (0 - 5): "))
# check to see what letter the number matches.
letters = ['F', 'F', 'D', 'C', 'B', 'A']
letterGrade = letters[gra... |
fd027fdd603eeff950dffc8c237cd3408e7f6e37 | Aislingpurdy01/CA277 | /cities-in-state-1.py | 278 | 3.515625 | 4 | #!/usr/bin/env python
import sys
header = sys.stdin.readline()
x = header.split(",")
cities = sys.stdin.readlines()
field = sys.argv[1]
i = 0
while i < len(cities):
tokens = cities[i].strip().split(",")
if tokens[9] == field:
print cities[i].strip()
i = i + 1
|
48036e56ad6c2006c36ed2fc0a5097e16075a0ce | alechaka/algorithms-python | /mergesort.py | 1,346 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
def merge_sort(a, first = 0, last = None):
"""
Args:
a: A list of unsorted items.
first: The index of the first item.
last: The index of the last item.
Returns:
A list of sorted items.
Note:
time: const * n * log_2(n)
"""
def merge_v_1(a, first, mid, last):
l... |
c9623e2723d6e86dcf06a83d6df2a5cff6d8d942 | limar63/study_folder | /PythonPrograms/OtherPythonGarbo/exam.py | 1,852 | 3.65625 | 4 | #'abc' ->
['bac','cab','acb','cba','bca','abc']
# n!=1*2*...*n
# 3!=1*2*3=6
# 'a','bc'
# ['bc','cb']
# ['bc','cb']
# ['abc','acb']
# 'b','ac'
# ['bac','bca']
# 'c','ab'
# ['cab','cba']
#permutations
a=[1,2]
b=[3,4]
c=[5,6]
[1,2,3,4,5,6]
a.append(b)
def permutations(s):
if s == '':
return [s] # since '... |
1eaf6dbb00e0b654a1c35c435bf0313c2de0ca5d | anil0775/Python | /sumOfNumbers.py | 159 | 4.15625 | 4 | """Program for calculating sum of two number"""
num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")
sum = num1 + num2
print(sum) |
c9fb86add088dd70cfa867189a7209f4468e455e | QT-HH/Algorithm | /Programmers/Lv2/전화번호 목록.py | 356 | 3.765625 | 4 | def solution(phone_book):
answer = True
check_list = set()
for i in phone_book:
if len(i) == 2:
check_list.add(i[0])
continue
for j in range(1, len(i)):
check_list.add(i[:j])
for i in phone_book:
if i in check_list:
answer = False
... |
f3b4984a53a1b6625f79e50f9757689a6c03bc39 | RanChenSignIn/Numpy_Pandas_Seaborn | /Numpy/numpy_Netease_could/numpy_copy_deepcopy.py | 250 | 3.640625 | 4 | import numpy as np
#浅度复制
a=np.arange(4)
print(a)
b=a
c=a
d=b
a[0]=6
print(a)
print(b)
print(c)
print(b is a)#判断a是否是与b完全相同,成立返回true,否则返回FALSE
#deep copy
b=a.copy()
#或者 b=a[:]
print(b)
a[3]=33
print(a) |
237302a60c0cf49ad7c2edc0c6b61f52172ea703 | YeongEunLee/Algorithm | /백준/1_그리디/2839.py | 92 | 3.796875 | 4 | n = input()
if n % 5 == 0:
res = n // 5
elif n % 3 == 0:
res = n // 3
else:
m = n // 5 |
c42cc7e32ac446d66c46280fbc24250607e80c33 | pushon07/Project_Euler | /006_sum_square.py | 275 | 3.515625 | 4 | max_num = 100
sum_squares = 0
for i in xrange(1, max_num + 1):
sum_squares += i ** 2
square_sums = (max_num * (max_num + 1) / 2.0) ** 2
print ("Sum_of_squares=%d; Square_of_sums=%d" % (sum_squares, square_sums))
print ("The difference = %d" % (square_sums - sum_squares)) |
06025bde02deddbb05e070c302d54f2cc7e0d425 | vishalkumar95/ECE-4802-Cryptography-and-Communication-Security | /Vigenere_Cipher_Autokey_Plaintext.py | 1,331 | 3.859375 | 4 | # This function is an implementation of the autokey Vigenere cipher algorithm.
def decryptVigenere(ciphertext, key):
ciphertextbreak = []
ciphertextbreakextra = []
Letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
smallLetters = 'abcdefghijklmnopqrstuvwxyz'
keylength = len(key)
ciphertextlength = len(cip... |
b0e61d2d734e96f385135bccada46d9163e937f2 | johnathanachen/cs1 | /Grade_Book/Assignments.py | 428 | 3.671875 | 4 | class assignments(object):
def __init__(self, name):
self.name = name
with open('./db/students.txt', 'r') as student_db:
student_names = [line.strip() for line in student_db]
if self.name in student_names:
pass
else:
print(self.nam... |
02489f84921f37f83902ccc272888414167273d8 | Cxiaojie91/python_basis | /python_basis/python_procedure/01_python_basis/07_condition.py | 731 | 4.1875 | 4 | # a = 17
# if a >=18:
# print('你的年龄是:', a)
# print('你已成年')
# else:
# print('你的年龄是:', a)
# print('你未成年')
#
# b = 2
# if b >= 18:
# print('adult')
# elif b >= 6:
# print('teenager')
# elif b >= 3:
# print('kid')
# else:
# print('baby')
#
# s = input('birth:')
# birth = int(s)
# if birth < ... |
f3c02d6d08392f3b50233404a69ecfd0fc0f49d5 | gabriellaec/desoft-analise-exercicios | /backup/user_166/ch59_2019_06_07_00_02_59_313348.py | 188 | 3.5625 | 4 | def conta_a (string):
contador = 0
vezes_a=0
while contador < len(string):
if string[contador] == "a":
vezes_a += 1
contador += 1
return vezes_a |
76a45f3bae0da04a548684faab4e11751513caa0 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4000/codes/1828_1657.py | 341 | 3.671875 | 4 | from numpy import*
n = input("maior quantidade: ").split(',')
a=0
b=0
c=0
d=0
e=0
for i in range(size(n)):
if(n[i] == "AZ"):
a=a+1
elif(n[i]=="CA"):
b=b+1
elif(n[i]=="FL"):
c=c+1
elif(n[i]=="PA"):
d=d+1
elif(n[i]=="WI"):
e=e+1
v = zeros(5,dtype=int)
v[0]=a
v[1]=b
v[2]=c
v[3]=d
v[4]=e
j=max(v)
print(j)
p... |
bbcd09a379145b066823ab81d0302c2d70418c1b | Noah-Schoonover/class | /lab6/lab6p12.py | 650 | 4.21875 | 4 | #lab6p12
#Prime Number Generation
#Noah Schoonover
def isPrime(num):
for x in range(2, int(num**.5)+1):
if num % x == 0:
return False
return True
def getPrimes(r):
print("The prime numbers between from 2 to {} are:".format(r))
nums = range(2,r+1)
for x in nums:
if is... |
f5ab498a6e801d219758be3ea6e8255966dc34a5 | rzc96/python-course | /sesion-8/game.py | 1,140 | 3.71875 | 4 | import pygame
ancho = 240
altura = 180
def main():
x = 50
y = 50
velocidad = 1
pygame.init()
pygame.display.set_caption("test")
pantalla = pygame.display.set_mode((ancho, altura))
corriendo = True
while corriendo:
pygame.time.delay(100) # delay siempre presente en lo que se ... |
2e1992fd0c518f8836df742358c8099969ceae85 | nagarajuiitm/PythonCorseJohn | /FlexibleNumberOfArguments.py | 274 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 28 13:15:44 2019
@author: SNR
"""
def add_numbers(a,b,c):
total = a +b+c
print(total)
def MultiplyNumber(a,b,c):
result= a * b* c
print (result)
MultiplyNumber(2,3,4)
add_numbers(2,3,4)
|
b32db9b2d86d49d93a4e79687d4d0ea483cad1fb | artpods56/Matura-Informatyka-Python | /2018 Maj - Rozszerzenie/zad4_2.py | 660 | 3.59375 | 4 | plik = open("sygnaly.txt","r")
strings = []
for linia in plik:
linia = linia.strip()
strings.append(linia)
naj_dl = 0
naj_string = ""
def ile_roznych(string):
litery = []
for letter in string:
if letter not in litery:
litery.append(letter)
len_litery = len(litery)... |
a2cb30cfd7ca6e131c6eca8255ea072b824041b8 | vipul-royal/A7 | /rev.py | 189 | 4.34375 | 4 | def reverse(s):
str=" "
for i in s:
str=i+str
return str
s=str(input("Enter the string:"))
print("The original string is:",s)
print("The reversed string is:",reverse(s)) |
8234b4c9291420671eac2c6f1257e893abd1efe4 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_135/2436.py | 806 | 3.5625 | 4 | n_cases = int(raw_input())
def read_int():
return int(raw_input())
def read_arrangement():
return [eval("[ " + raw_input().replace(" ", ",") + " ]") for i in range(4)]
def transpose_arrangement(arr):
return [[ x[i] for x in arr] for i in range(4)]
for case in range(1, n_cases+1):
answer1 = read_int() - 1
arran... |
1b6a81c583ab37a02fb2f2529fdbc19a50a1ccd8 | yangjiahao106/LeetCode | /Python3/09_Palindrome_Number.py | 1,407 | 3.84375 | 4 | #! python3
# __author__ = "YangJiaHao"
# date: 2018/2/3
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
tmp = x
rev = 0 # 反转后的数字, 其他语言需要考虑反转后溢出的问题
while tmp:
rev = rev * 10 + ... |
9a67a68d4f8b680ca491c98ce2a47d434b083154 | sapanp007/python_scripts | /min_chars_to_palindrome.py | 607 | 3.75 | 4 | from math import ceil
def find_min_chars_to_make_palindrome(s):
str_len = len(s)
st_pt = ceil(str_len/2) - 1
left = st_pt - 1
right = st_pt + 1
while right < str_len and left >= 0:
if s[left] == s[right]:
left = left - 1
right = right + 1
elif s[left] != s[... |
3243c9b93aae4fb93e8591d16626126e299ba4e3 | Nidhintsajee/Test-answers | /image-puzzle/puzzle.py | 1,383 | 3.796875 | 4 | #!/usr/bin/python
import requests
def print_urls(file):
#Each line is of the form: GET /foo/bar/a.jpg
#remove the GET and print only /foo/bar/a.jpg
#use a for-loop to iterate through each line of `file'
#split the line and print second part
for line in f:
print line.split()[1]
f = open('... |
1865d73948fd61456461bc10d4079d36ef1efea8 | Arjun-Pinpoint/InfyTQ | /Programming Fundamentals using Python/Day 2/Assignment 19.py | 2,002 | 4.03125 | 4 | '''
FoodCorner home delivers vegetarian and non-vegetarian combos to its customer based on order.
A vegetarian combo costs Rs.120 per plate and a non-vegetarian combo costs Rs.150 per plate. Their non-veg combo is really famous that they get more orders for their non-vegetarian combo than the vegetarian combo.Apart fro... |
c30fddbe359dfcf52c69ac0aa96edc866853391c | herrmannjob/DevTraining | /Languages/Python/Exercises/Meu Python Minha Vida.py | 915 | 3.9375 | 4 | print('=' * 35)
print('Programa Meu Python, Minha vida')
print('=' * 35)
casa = float(input('Qua o valor da casa? R$: '))
salario = float(input('Qual o seu salario? R$: '))
pres = int(input('Em quantos anos quer pagar? '))
pres1 = float(casa / (pres * 12))
sal = salario * 30 / 100
if pres1 > sal:
print('Com o salar... |
727930e9c0a74bfc78c32e50bcacdece77fb0149 | neu-velocity/code-camp-debut | /codes/Aiamjay/Week3-Day4/126. Word Ladder II.py | 2,891 | 3.609375 | 4 | # encoding = utf-8
from collections import (
defaultdict, deque
)
from math import inf
class Solution1:
def ladderLength(self, beginWord: str, endWord: str, wordList: list):
if endWord not in wordList or not wordList:
return 0
# # wjcnote 创建图
word_dict = defaultdict(list)
... |
6f59d5224c5625c671a29e2b9c92108975094221 | qq854051086/46-Simple-Python-Exercises-Solutions | /problem_11.py | 560 | 4.4375 | 4 | '''
Define a function generate_n_chars()that takes
an integer n and a character c and returns a string,
n characters long, consisting only of c:s. For
example, generate_n_chars(5,"x")should return
the string "xxxxx". (Python is unusual
in that you can actually write an expression
5 * "x"that will evaluate to
"x... |
d57fac16be388f429ee361680056bb39ef541698 | tanvir07-ops/python_oop | /another_app.py | 1,068 | 3.8125 | 4 | '''
p = {}
p['name'] = 'Tanvir Rifat'
p['email'] = 'tanvir@example.com'
print(p)
'''
class Person:
def __init__(self,name,email):
self.__name = name
self.__email = email
def log(self):
print(self.__dict__)
@property
def name(self):
print(self.__name)
@property
... |
f1aaa838a3e26ea33701272008b7441d779d5975 | Formation-CDA-Grenoble/S01-Algo-E05-POO | /Person.py | 2,579 | 3.640625 | 4 | import datetime
# Simulation de données que l'on pourrait récupérer d'une base de données
data = [
["Josette", "Martin", 25, False],
["Robert", "Durand", 45, True],
["Lucien", "Pinard", 33, True],
]
# Modèle permettant de créer des objets (instances) représentant des personnes
class Person:
# Propriét... |
6204dee29982170180d6d6efe80645ad2c6fb00c | garigari-kun/til | /src/codewars/python/6kyu/order.py | 1,080 | 4 | 4 | """
Your task is to sort a given string.
Each word in the String will contain a single number.
This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input String is empty, return an empty String. The words in the input St... |
ac7ebe4762df32bd7a685a5f3d0e886b4cab2f7f | eduardoh27/IP-JAVERIANA202120 | /prueba.py | 530 | 3.671875 | 4 | """
Parcial 1 Barrera
"""
def main ():
total = int(input("Ingrese el # de casilleros: "))
abiertos = 0
cerrados = 0
i=1
while i <= total:
divs = divisores(i)
if divs%2 != 0:
print(i, " queda abierto")
abiertos += 1
i+=1
cerrados = tota... |
2dd5923a98201c18c936866b72aafa5b555c18d6 | allgoliot/Projet-python | /module/mathematiques.py | 638 | 3.96875 | 4 | #Fonction addition
def addition(a,b):
print("Somme =", a+b)
#Fonction soustraction
def soustraction(a,b):
print("Soustraction =", a-b)
#Fonction multiplication
def multiplication(a,b):
print("Multiplication =", a*b)
#Fonction division
def division(a=1,b=1):
resultat = 0
try:
resultat = a/... |
2432643ba6caef66100251966201aac767d82db1 | lonmiss/2020WinterHoliday | /数据结构与算法/20200125Class/par/十进制转换成任意进制.py | 374 | 3.53125 | 4 | from Stack import *
def divibeByany(decNumber,numCnt):
arr=Stack()
n=decNumber
while decNumber > 0:
n=decNumber % numCnt
arr.push(n)
decNumber//=2
binString= ""
while not arr.isEmpty():
binString+=str(arr.pop())
print("十进制的数{}转换成{}进制的数为:{}".format(n,numCnt,binS... |
f49c7866f8d47b4174b206e9d24aef35c1d79937 | varungove/CS242 | /CSAir2.1/Assignment2.1/src/graph.py | 785 | 3.59375 | 4 | """
Graph class and functionality
"""
import parse
class Graph:
city_dict = {}
convert = {}
def __init__(self, control):
"""
Constructor for the Graph
"""
if(control == '1' or control == '2'):
self.city_dict, self.convert = parse.parse_graph(self.city_... |
400fe488e5caa65d30b256f1f73ba20960eaec21 | MgArreaza13/CifrarDescifrar | /package/menu.py | 476 | 3.8125 | 4 | #metodo que muestra el menu, y recoge la opcion valida que necesita ejecutar el usuario
import os
def menu(): #menu
opc = 0
while True:
os.system("cls")
print("Selecione una opcion que decea relizar \n"
+"\n1)Encriptar Texto Plano \n"
+"2)Desencriptar Texto Plano\n"
+"3)Encriptar Archivo .TXT \n"
... |
03959660d9e9e0a2fefc8920a2360594764f432f | SilvesterKnuut/Python | /Section_21_Interacting_with_Databases/SQLite_Connecting_Inserting_Data.py | 921 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 14 13:00:54 2019
@author: Silvester
Standart proces to interact with a db:
1. Connect to a database
2. Create a cursor object (Its a pointer to access rows from the table of a db)
3. Apply an SQL query
4. Commit the changes to the database
5. Clos... |
6f796c1b957c510905192ddb4afcc1f9be6ad5b6 | serebrov/so-questions | /python-abc/abc_test.py | 887 | 4.15625 | 4 | from abc import ABCMeta, abstractmethod
class ClassA:
def do(self):
print('A-do')
class ClassB:
def do(self):
print('B-do')
class ClassC:
pass
class Doable(metaclass=ABCMeta):
@abstractmethod
def do(self):
pass
# We can register existing classes as "Doable" without m... |
24e66f84ec444fa169869163e067280670d5f9c9 | aselivan0v/home-work-beetroot | /lesson5/l5task2.py | 792 | 4.0625 | 4 | # Task 2
# Exclusive common numbers.
# Generate 2 lists with the length of 10 with random integers from 1 to 10,
# and make a third list containing the common integers between the 2 initial lists without any duplicates.
# Constraints: use only while loop and random module to generate numbers
import random
x = 0
list_o... |
f1882189924a62864cc7b3b35e9a0975d8d848f1 | iftekharchowdhury/Problem-Solving-100-Days | /py_collections_namedtuple.py | 402 | 3.734375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import namedtuple
n = int(input())
fields = input().split()
total = 0
for i in range(n):
students = namedtuple('student', fields)
ID, NAME, MARKS, CLASS = input().split()
student = students(ID, NAME, MARKS, CLASS)
... |
f54effd5e5a3380936e0fa635e830c2f4c0ee80d | Hema113/python_puzzles | /fact.py | 206 | 4.1875 | 4 | def fact(n):
fact = 1
for i in range(1,n+1):
fact *= i
return fact
if __name__ == "__main__":
n=int(input("Enter number>>>"))
print("The Factorial of given number is", fact(n))
|
417e178ab859ef40492c6846f6e64f7116a96b04 | aflens/Learning-python | /Electron_configuration.py | 752 | 3.890625 | 4 | import math
# Calculates the electron configuration of atoms
Atomic_number =____ # number of electrons
o_name = ['s', 'p', 'd', 'f', 'g']
o_value = [2, 6, 10, 14, 18]
output_string = ""
end_period = 1
while Atomic_number > 0:
for i in range(math.floor((end_period-1)/2), -1, -1):
if(Atomic_number > o... |
d49be0373c5c49c937143c224dbb37aa78ea7263 | yuxiaous/adventofcode | /2020/day21.py | 2,655 | 3.5 | 4 | #!/usr/bin/env python3
import re
class Food:
def __init__(self, info):
m = re.match(r'(.+) \(contains (.+)\)', info)
self.ingredients = m.group(1).split(' ')
self.allergens = m.group(2).split(', ')
class Day21:
def __init__(self, inputs):
self.foods = [Food(x) for x in input... |
6f7a2bc9e63a1f52dd996eeb0005921d170f980d | yaswanthkoravi/Apsproject | /tests/insertion1.py | 492 | 3.546875 | 4 | import matplotlib.pyplot as plt
#inserting elements in rb tree in ascending order
y=[0.38,0.659,0.93,1.27,6.604,48.468]
x=[500,1000,1500,2000,10000,100000]
#inserting elements into splay tree in ascending order
y1=[0.14,0.278,0.362,0.44,2.022,13.32]
x1=[500,1000,1500,2000,10000,100000]
plt.ylabel("Time(ms)")
plt.xlabel... |
9883b10a554507fbd879684074cbd55739adaebc | gbuchdahl/term_blackjack | /printing.py | 796 | 3.859375 | 4 | import typing
from typing import List
from card import Card
def print_piles(cards: List[Card]) -> None:
""" prints a 1D array of cards as they would be a hand"""
for i in range(len(cards)):
print("+----+", end=" ")
print()
for i in range(len(cards)):
print("| |", end=" ")
print... |
8a7b5e8e544f9df45c5c762cbc7c5d73dc057aa3 | icejoywoo/toys | /algorithm/leetcode/70_climbing_stairs.py | 577 | 3.84375 | 4 | #!/usr/bin/env python2.7
# encoding: utf-8
"""
@brief: https://leetcode.com/problems/climbing-stairs/
和斐波那契数列一样
@author: icejoywoo
@date: 2019-10-11
"""
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0] * (n+1)
... |
b27aa79330db66571923d6529b9e59ad801424e8 | andrei-tarnauceanu/uhomeuponor | /custom_components/uhomeuponor/uponor_api/utilities.py | 333 | 3.6875 | 4 | def flatten(*args):
output = []
for arg in args:
if hasattr(arg, '__iter__'):
output.extend(flatten(*arg))
else:
output.append(arg)
return output
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield... |
25d8caf0f8af7e61453c84c6b2a3f2c68ea056b7 | jiaquan1/cracking-the-coding-interview-189-python | /Chapter5-bits/54next_number.py | 3,134 | 3.859375 | 4 | <<<<<<< HEAD
def next_numbers(number):
if number <=0:
return None,None
if number%2:
a = 1
c1=0
#large
while number&a and number>=a:
c1+=1
a<<=1
if number<a:
large = a+(1<<(c1-1))-1
else:
large = ((nu... |
aefee984b8984c8187842127d050fed037d079ad | winterfellding/mit-cs-ocw | /6.006/clrs/chap8.py | 472 | 3.71875 | 4 | def count_sort(array, count_array):
for i in array:
count_array[i] += 1
for i in range(1, len(count_array)):
count_array[i] += count_array[i-1]
result = [0] * len(array)
for i in range(len(array)-1, -1, -1):
print(count_array)
print(i)
result[count_array[array[i]]... |
6036dede25545c9a8723fc6b3f4b31e350cb4955 | giuliocorradini/CryptoWorkshop | /cryptow/maths/maths.py | 903 | 3.796875 | 4 | import logging
def gcd(a, b):
'''
Computes the greatest common divisor using Euclid's extended
algorithm.
:param a: positive integer
:param b: positive integer <= a
:return: positive integer
'''
if b == 0:
return a
if b > a:
return gcd(b, a)
seq = [a, b, a%b]
... |
451d7ab52a0fdf06d20495f3217c41d3702c8d97 | ash/amazing_python3 | /344-concat-string-list.py | 151 | 3.75 | 4 | # How to concatenate a few strings
# from a list to a single string
data = [
"This", "is",
"my", "message"
]
str = " ".join(data)
print(str)
|
590e9129b65336da3bf98020faaa05f12066b8dd | skreynolds/uta_cse_1309x | /mid_semester_exam/Test1.py | 84 | 3.5 | 4 | x = ["dog", 2, "cat", 34, 5.8]
m = 0
for i in range(len(x)):
m = m + i
print(m)
|
0644016412c650a8d59c67a61d0b63bfb2273b76 | shwetabhsharan/leetcode | /linkedin/sll.py | 1,597 | 3.828125 | 4 |
class Node(object):
def __init__(self, data):
self.data = data
class SLL(object):
def __init__(self):
self.head = None
def add(self, value):
node = Node(value)
node.next = self.head
self.head = node
def remove(self, value):
curr = self.head
wh... |
a4c38e64654a47e661bc0334a1bc3196f7510868 | balanikaran/College-Practicals-GLAU | /PythonClasses/primeComplexityKBvsHS.py | 985 | 4.03125 | 4 | import time
import math
def checkPrimeKB(number):
#true = prime false = not prime
if(number%2 == 0 and number != 2):
return False
else:
for i in range (3, int(math.sqrt(number)) + 1):
if(number%i == 0):
return False
return True
def checkPrimeHS(n):
#tru... |
156fda4ef1a2f9bd2c8a2fcbbab2a89e84206723 | mhill142/swc_newstuff | /stats.py | 410 | 4.15625 | 4 | def mean(vals):
"""Calculate the arithmetic mean of a list of numbers in vals"""
assert type(vals) is list, 'wrong input format'
total = sum(vals)
length = len(vals)
if length == 0:
return 0.0
else:
return total/length
def test_mean():
assert mean([2,4]) == 3.0
test_mean()
de... |
dea43d809227b6e100192d80bea0a341e27e8f8c | erdembozdg/coding | /python/python-interview/intermediate/recursive.py | 991 | 3.640625 | 4 | from itertools import permutations
perm = permutations([1, 2, 3])
print(list(perm))
def permute(s):
out = []
if len(s) == 1:
out = [s]
else:
for i, v in enumerate(s):
for perm in permute(s[:i] + s[i+1:]):
out += [v + perm]
return out
def word... |
cdb7c45a88a9840ce6e770308ee8732ccbe4aa4c | afsana1210/python-learning | /spy_game.py | 349 | 3.96875 | 4 | #SPY GAME-Write a function that takes in a list of integers and returns True if it contains 007 in order
def spy_game(nums):
code=[0,0,7,'x']
#check [0,7,'x'] x is some string
# [7,'x']
# ['x'] len is 1.
for num in nums:
if num == code[0]:
code.pop(0)
return len(code) == 1
res=spy_game(... |
0b5fdc968a6c98b11f55428af3ca115a04bc6641 | wesleysilva2/Introdu-oPythomUSP | /Programas parte 2/Programas semana 1/LeMatrizes.py | 1,211 | 4.0625 | 4 | def cria_matriz(num_linhas, num_colunas):
"(int,int) -> matriz (lista de listas)"
"Cria e retorna uma matriz com nun_linhas linhas e num_colunas"
"colunas em que cada elemento é digitado pelo usuario"
matriz = [] # lista vazia, guarda as linhas da matriz
for i in range(num_linhas): # nume... |
314c3dd78b38e3394f2e4ecbaae4be42facb8b88 | Bravelemming/PushingAWSIotButton | /email_button.py | 2,201 | 3.59375 | 4 | # Generate Email from Raspberry Pi GPIO button press
# HSU LumberHacks Hackathon
# Team: Pressing Dave's button
# Contributors: Jack Kinne, Sam Alston, Max Lemos, Nathan Ortolan
# Last Modified: 3/24/18
# Standard time library
import time
# GPIO Control
import RPi.GPIO as GPIO
# Email
import smtplib
# To e... |
55bfa0513194ff7d907e806792ae52b9281eb06c | admud/pythonforbeginners | /app.py | 1,780 | 4.09375 | 4 | # print("hello lul")
# use py -3 for python 3
# use py -2 for python 2
# or use special comment at the top of script
# print(" /|")
# print(" / |")
# print(" / |")
# print("/ |")
# character_name = "Kapp"
# print("my name is " + character_name)
# phrase = "omegalul"
# print(phrase.upper())
# print(phrase[2... |
93a2a10d61b6b53e6f11f0fe4c2d2bc54dc8e123 | MulengaKangwa/PythonCoreAdvanced_CS-ControlStatements | /53HandleZero.py | 206 | 4.34375 | 4 |
x = int(input("Enter a number:"))
if x==0:print(x, "is zero")
elif x%2 == 0:print(x,"is even")
else:print(x, "is odd")
# This simple demonstrates how to use the ELSE IF ladder, using the elif condition.
|
f07cbd7c7c1d4e8f037908b5a2baba27fd1ee8e4 | green-fox-academy/FKinga92 | /week-02/day-01/draw_square.py | 366 | 4.1875 | 4 | # Write a program that reads a number from the standard input, then draws a
# square like this:
#
#
# %%%%%
# % %
# % %
# % %
# % %
# %%%%%
#
# The square should have as many lines as the number was
n = int(input("Please enter a number: "))
for i in range(n):
if i==0 or i==(n-1):
print("%"*(n-1))
... |
392a2a1e3da4b5807a0ed426c394cbe0f0307469 | CarolinaFCerqueira/Learning_Python2018 | /Exercise04_check_internet.py | 473 | 3.71875 | 4 | #Exercise 4
#Carolina
#Time spent: 10 minutes
# -*- coding: Latin-1 -*
""" Write a program to check a computer is connected to the internet. """
import requests
def check_internet():
url='http://www.google.com/'
timeout=5
try:
_ = requests.get(url, timeout=timeout)
retu... |
e368c7a813fe1c088b5a2af53301bfb6a294be75 | hoang-ng/LeetCode | /Array/628.py | 1,182 | 4.03125 | 4 | # 628. Maximum Product of Three Numbers
# Given an integer array, find three numbers whose product is maximum and output the maximum product.
# Example 1:
# Input: [1,2,3]
# Output: 6
# Example 2:
# Input: [1,2,3,4]
# Output: 24
# Note:
# The length of the given array will be in range [3,104] and all elements a... |
d90d6f814fc89f9d9145fc1e9fa8fd9e63c46562 | sbrew/cohort4 | /python/code.py | 205 | 3.671875 | 4 | f_name = input("Please give me your first name:")
l_name = input("Please give me your last name:")
address = "evolveu.ca"
print(f"Thank you for creating your new e-mail it is {f_name}.{l_name}@{address}") |
9c3dabc0cb7878af42f2d4a36a3ede6c6d9bbb74 | G0rocks/Honnunarverkefni-ortolvu-og-maelitaekni-2020 | /demo code/input_test.py | 658 | 3.890625 | 4 | def castAsInt(a):
"""
Function takes in value a and attempts to cast it as int, returns "null" if it fails
"""
try:
return int(a)
except:
return "null"
print("Ath 1 lota er 5 sek þ.e. 12 lotur mæla í 60 sek")
c = input("Hversu margar lotur viltu profa?: ")
c = castAsInt(c)
while (True): # Safety me... |
9638690853557bdce179d4f8817cf348274674b3 | ecollins2307/HPM573S18_COLLINS_HW1 | /HW1_problem1.py | 405 | 4.03125 | 4 | #HW 1, Problem 1
#Part 1
#creating y1 as integer
y1 = int(17)
#creating y2 as float
y2 = float(17)
#creating y3 as string
y3 = "17"
#creating y4 as Boolean
y4 = (17==17)
#printing the above variable with their type
print(y1)
print(type(y1))
print(y2)
print(type(y2))
print(y3)
print(type(y3))
print(y4)
print(type(y4))... |
b052b571aa430f6f1d1ba8ac8c232dfa6db83fff | raoashish10/NoCode-ML | /ML_Codes/Clustering.py | 2,015 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 13 05:22:49 2020
@author: nishantn
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
def KMeans(X, n=6):
kmeans = KMeans(n_clusters = n, init = 'k-means++')
y_kmeans = kmeans.fit... |
937468dee6e73695f417b29876ee8c9b65935a77 | 72Roman/Data-Manipulation-at-Scale-Coursera | /assigment3/asymmetric_friendships.py | 1,038 | 3.53125 | 4 | import sys
import MapReduce
mr = MapReduce.MapReduce()
def mapper(record):
person, friend = record
mr.emit_intermediate(person, ("has_as_friend", friend))
mr.emit_intermediate(friend, ("is_friend_of", person))
def reducer(key, list_of_values):
person, friendships = key, list_of_values
frien... |
764bfe6778573aaa9564593ded691601a93d9271 | Indhuu/git-github | /python/Name_prog.py | 316 | 3.953125 | 4 | # Name prog
Name = raw_input("Enter the Name:")
Age = raw_input ("Enter the Age:")
print ('Name of the person: ' + Name)
print ('Age of the person: ' + Age)
A = Name * 5
print A
B = float(Age)
print ('Age after converting to float:'+ str(B))
C = len(Name)
print ('length of the name:'+ str(C))
|
5f8469c69c8355675f74939ce0e80416f117ef1c | baloooo/coding_practice | /detect_html_tags.py | 426 | 3.65625 | 4 | """
https://www.hackerrank.com/challenges/detect-html-tags
"""
import re
regex = r"<\s*[a-zA-Z]{1,3}\s*>*"
n = int(raw_input().strip())
tags = set()
final_tags = []
for i in xrange(n):
inp = raw_input().strip()
tag_matches = re.finditer(regex, inp)
for match in tag_matches:
tags.add(re.sub(r'[<|>|\... |
64faf607b140cb576ccace9da660013802c20d7b | DaveFelce/shopping-cart | /main.py | 1,124 | 3.65625 | 4 | from cart import Cart
from item import Item
from user import User
def main():
item_shorts = Item(name='shorts', price=10, description='Some nice shorts')
item_tshirt = Item(name='tshirt', price=20, description='A nice t-shirt')
item_pants = Item(name='pants', price=30, description='Lovely pants')
# c... |
7c15ac86290c9b2a4aa0164a3e6535fb078b0b76 | abimarticio/learning-python | /exercises/exercise_01.py | 746 | 4.0625 | 4 | #Ask for the following information,
#and display the:
#country
#gender
#mobile number
#major
#birthday
#instagram username
country = input("What is the name of your country? ")
print("{}".format(country))
gender = input("What is your gender? ")
print("{}".format(gender))
mobileNumber = input("What is your mobile numb... |
079d1c937ecee89c4b6a9f391fbb940cd29fc563 | Ghostpupper/adventofcode | /day12/day12.py | 1,683 | 3.734375 | 4 | from input_getter import get_input
class Boat:
def __init__(self):
self._dir_pointer = 0
self._dir_list = ['E', 'S', 'W', 'N']
self._facing = self._dir_list[self._dir_pointer]
self._dir_dist = {
'N': 0,
'S': 0,
'E': 0,
'W': 0
}... |
038bf7be20d7ee9d1fc51cac0f64d80903956614 | Vcolvr/KenziePython | /Short_Long_Short.py | 158 | 3.53125 | 4 | def solution(a, b):
lengthA = len(a)
lengthB = len(b)
if lengthA > lengthB:
return b + a + b
else:
return a + b + a
|
32f2b29ec590f32ffb09a240ee8f8525fb32ca2e | Little-frog/python | /leecode/最长公共前缀.py | 476 | 3.53125 | 4 | def longestCommonPrefix(s):
'Written by myself'
if not s:
return ""
str0 = min(s)
str1 = max(s)
for i in range(len(str0)):
if str0[i] != str1[i]:
return str0[:i]
return str0
'Answer'
ans = ''
for i in zip(*s):
if len(set(i)) == 1:
ans... |
0b912d49bbb2a83d04ce1e59a7f92d8be2b1064b | shinobu0831/python | /src/if.py | 713 | 3.890625 | 4 | #age = int(input('input age:'))
# if age < 18:
# print('no vote1')
# elif age < 20:
# print('no vote2')
# else:
# print('no vote3')
# 三項演算子
#print('A' if age < 10 else 'B')
# 内包表記
#data = [10**n for n in range(1, 11)]
# print(data)
# リスト[]:重複可、順序保持、変更可
listA = ['1', 2, 3, 4, 5, 6, 7, 7]
listA.append(8)
pri... |
9286688297bdf10c2c62c4c18a51d3c47fa4b8bc | daniel-reich/ubiquitous-fiesta | /WQjynmyMXcR83Dd8K_12.py | 1,209 | 3.78125 | 4 |
def swapPositions(list, pos1, pos2):
list[pos1],list[pos2] = list[pos2],list[pos1]
return list
def number_of_swaps(listOfNumbers):
currentNumber = 0
nextNumber = 0
count = 1
organizedListOfNumbers = []
numberOfSwaps = 0
for i in listOfNumbers:
organizedListOfNumbers.append(i... |
0823df27de4215859751e960f2df4acd7a296b87 | mishrakeshav/Competitive-Programming | /SPOJ/BUGLIFE.py | 848 | 3.53125 | 4 | def dfs(node,c):
visited[node] = 1
color[node] = c
for nbr in graph[node]:
if visited[nbr]==0:
if not dfs(nbr,c^1):
return False
elif color[nbr] == color[node]:
return False
return True
for tt in range(int(input())):
n,m = map(int,input()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.