blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8b930441ab1057de1610ee76174b260c46df0caa | Lornatang/TensorFlow2-tutorials | /guide/serialization/checkpoints.py | 10,663 | 3.5 | 4 | # Copyright 2019 ChangyuLiu Authors. All Rights Reserved.
# 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 required by applica... |
f8385516664bbf38e638d4f419501f77f9cb8f56 | Lornatang/TensorFlow2-tutorials | /Primary_tutorial/Basic/classifier_struct_data.py | 8,111 | 3.796875 | 4 | # Copyright 2019 ChangyuLiu Authors. All Rights Reserved.
# 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 required by applica... |
2626fa70d9b7c56c0a971e1bf3c47f1cb0300775 | Lornatang/TensorFlow2-tutorials | /Experts_tutorial/Text/text_generation.py | 16,126 | 3.65625 | 4 | # Copyright 2019 ChangyuLiu Authors. All Rights Reserved.
# 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 required by applica... |
f7c1316419a507503e79b1543bdf4e9a7d1c5cbd | pvmigdalov/self-taught-programmer-Althoff | /chapter_21.py | 1,662 | 3.84375 | 4 | import time
from random import randint
class Stack:
def __init__(self, *args):
self.items = list(args)
def push(self, x):
self.items.append(x)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.it... |
94f6c6915403e9e1569dcbbea5d4535732ca474f | YEL-59/Python_Mini_Project | /quiz_game.py | 1,515 | 4.3125 | 4 | print('Wellcome to my Computer game! ')
playing = input('Do u Want to play!')
if playing != 'yes':
quit()
print("Ok Let's play : ) ")
score = 0
print('''What Does CPU Stands for?
a)central processing unit.
b)graphics processing unit.
c)random access memory.
d)po... |
665c498bfb08bdd6e623c0a37eb703348dd07de6 | tejavarma-twl/python2 | /lists.py | 933 | 3.734375 | 4 | sample_list = [1,2,3,4,5]
sample_tuple = (1,2,3,4,5)
sample_set = {1,2,3,4,5}
sample_set2 = {1,2,4,6,7}
sample_dictionary = {'soups':'soup info','starters':'Starter info'}
# print(sample_set | sample_set2)
# print(sample_set & sample_set2)
# print(sample_set - sample_set2)
# print(sam... |
dd24af2ba8ca2ebc955a3ca7a22b3cf715e5a8fc | razak17/project-euler | /py/euler_031.py | 247 | 3.546875 | 4 | def coin_sums():
n = 200
ways = [1] + [0] * n
coins = [1, 2, 5, 10, 20, 50, 100, 200]
for coin in coins:
for i in range(len(ways) - coin):
ways[i + coin] += ways[i]
return str(ways[-1])
print(coin_sums())
|
a1e2140035be1adf9a5cc887f02eb1c9a501e268 | razak17/project-euler | /py/euler_036.py | 349 | 3.859375 | 4 | def is_decimal_binary_palindrome(n):
s = str(n)
if s != s[::-1]:
return False
t = bin(n)[2:]
return t == t[::-1]
def sum_double_base_palindrome():
ans = sum(i for i in range(1, 1000000) if is_decimal_binary_palindrome(i))
return str(ans)
print(is_decimal_binary_palindrome(585))
print(... |
6652dbc305cb37387a6a0480a5df5cbdfded4421 | razak17/project-euler | /py/euler_014.py | 454 | 3.53125 | 4 | from helpers import memoize
import sys
def longest_collatz_chain_sequence(n):
sys.setrecursionlimit(3000)
ans = max(range(1, n), key=collatz_chain_sequence)
return str(ans)
@memoize
def collatz_chain_sequence(x):
if x == 1:
return 1
if x % 2 == 0:
y = x // 2
else:
y = 3... |
58fbc5b819b2d293577197cf8ec70f339774bb40 | Aheri-Mondal/Python-Games | /Hangman.py | 4,368 | 3.59375 | 4 |
import random
import sys
class HangMan(object):
#Hanging Stand
hang = []
hang.append(' +---+')
hang.append(' | |')
hang.append(' |')
hang.append(' |')
hang.append(' |')
hang.append(' |')
hang.append('=======')
#The hanging man
man = {}
man[0] ... |
6be53a21d087d24f931638de0700365252ed936c | JQuinteroC/Ejercicios_PF | /p1.py | 249 | 3.703125 | 4 | """
Retornar un entero con los últimos dígitos de una lista de enteros
"""
def ultimo_dig(lista, valor):
if lista == []:
return valor
return ultimo_dig(lista[1:], (valor*10)+(lista[0] % 10))
print(ultimo_dig([123, 234, 678], 0)) |
7b9dcd8d3bc174d9e645d8d5a5f819a558db6628 | okola44/python1 | /bank.py | 4,861 | 4.15625 | 4 | from datetime import datetime
class BankAccount:
fixedAccount="fixed"
savingsAccount="save"
def __init__(self,name,phonenumber):
self.name=name
self.phonenumber=phonenumber
self.balance=0
self.loan=0
self.statement=[]#instasiating statement as an empty list so we can ... |
1254eb3c10e3732851dbddaccdbdfb864f58c511 | AnnaDluzhinskaya/Internship | /coding_tasks/ex2.py | 655 | 3.8125 | 4 | # Space complexity - O(2n)
# Time complexity - O(n*mˆ2)
# In this case we can assume that mˆ2 = const = 26ˆ2
def max_sub_str(s):
s = s.replace(" ", "")
s = s[3:(len(s)-1)]
arr = []
max_s = 0
"""
m - number of different chars in s
0 < m < 27
"""
for i in s: # O(n) Worst case
... |
78864c2a8597084fb711b43eaf59dfeb77b0974a | thiagoperess/python-plots | /double-bar.py | 301 | 3.515625 | 4 | import matplotlib.pyplot as plt
x1 = [1, 3, 5, 7, 9]
x2 = [2, 9, 7, 4, 7]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 5, 8, 4, 9]
plt.title('Meu primeiro gráfico em Python')
plt.xlabel('Eixo X')
plt.ylabel('Eixo Y')
plt.legend()
plt.bar(x1, y1, label = 'Grupo 1')
plt.bar(x2, y2, label = 'Grupo 2')
plt.show() |
09cf47cc214418b66ce69ec6189b34a1d4c66b4a | lizweer/2018_day2 | /maxima.py | 1,278 | 4.15625 | 4 | def find_maxima(x):
"""Find local maxima of x.
Example:
>>> x = [1, 2, 3, 2, 4, 3]
>>> find_maxima(x)
[2, 4]
Input arguments:
x -- 1D list numbers
Output:
idx -- list of indices of the local maxima in x
"""
idx = []
plateau = []
for i in range(len(x)):
... |
5a12f1ba70d9b1377141d793541a95e65d1690f6 | ranjit-kr-nair/HelloWorld | /TicTacToe.py | 3,255 | 3.71875 | 4 | from IPython.display import clear_output
def display_board(board):
clear_output()
print("{}|{}|{}".format(board[0],board[1],board[2]))
print("-----")
print("{}|{}|{}".format(board[3],board[4],board[5]))
print("-----")
print("{}|{}|{}".format(board[6],board[7],board[8]))
def status(bo... |
204908dd423079361f0c38f92529a4927b8a3913 | Aissen-Li/LeetCode | /112.hasPathSum.py | 716 | 3.671875 | 4 | from collections import deque
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
queue = deque([(root, root.val)])
wh... |
d38ccb262447ba1d6512eca18e70490f95a38eec | Aissen-Li/LeetCode | /671.findSecondMinimumValue.py | 613 | 3.5 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findSecondMinimumValue(self, root: TreeNode) -> int:
def preorder(root, val):
if not root:
return -1
if root.val > val:
... |
70c20bbb8f3bfd6ae23e69fbe187165977b222d1 | Aissen-Li/LeetCode | /329.longestIncreasingPath.py | 1,089 | 3.640625 | 4 | from typing import List
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
if not matrix or not matrix[0]:
return 0
m = len(matrix)
n = len(matrix[0])
self.res = 0
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
record = [[0] ... |
27cdad88ccd4297338a23d557bffe0564b0f6f85 | Aissen-Li/LeetCode | /173.BSTIterator.py | 766 | 3.8125 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class BSTIterator:
def __init__(self, root: TreeNode):
self.inorderSort = []
self.index = -1
self.inorder(root)
def inorder(self, root):
if not root:
... |
5dafaf017e38f44ffebb9023139eddbba54da9fd | KarthusLorin/python-learning | /python-basic-course/Chapter2/2-3.py | 678 | 3.6875 | 4 | #coding:utf-8
#以正确的宽度在居中的“盒子”内打印一个句子
#注意,整数除法运算符(//)只能用在Python 2.2以及后续版本,在之前的版本中,只使用普通除法(/)
sentence = raw_input("Sentence: ")
screen_width = 80
text_width = len(sentence)
box_width = text_width + 6
left_magin = (screen_width - box_width) // 2
print
print ' ' * left_magin + '+' + '-' * (box_width-3) + '+'
print... |
f27e81030ee1c24ef7e0963900bab3d21e0e6051 | vqpv/stepik-course-67 | /3 - Функции. Словари. Интерпритатор. Файлы. Модули./3.2 - Словари/1.py | 442 | 3.90625 | 4 | def update_dictionary(d, key, value):
if key in d.keys():
d[key].append(value)
elif key * 2 in d.keys():
d[key * 2].append(value)
else:
d.update({key * 2: [value]})
if __name__ == '__main__':
d = {}
print(update_dictionary(d, 1, -1)) # None
print(d) # {2: [-1]}
up... |
4453556d7e22358b5edd4b02848abf1dbafd6722 | vqpv/stepik-course-67 | /1 - Операторы. Переменные. Типы данны. Условия./1.8 - Переменные. Стандартный ввод-вывод./2.py | 86 | 3.671875 | 4 | x = int(input())
hour = int(x // 60)
minute = int(x % 60)
print(hour)
print(minute)
|
c69002ffeede06bb90cee4699bd7ab4f362c8a18 | vqpv/stepik-course-67 | /2 - Циклы. Строки. Условия./2.3 - Цикл for/1.py | 285 | 3.515625 | 4 | a = int(input())
b = int(input())
c = int(input())
d = int(input())
f = ''
for i in range(c, d + 1):
print('\t', i, end='')
print()
for ii in range(a, b + 1):
print(ii, end="")
for j in range(c, d + 1):
f = str(ii * j)
print('\t', f, end='')
print()
|
8a5e5a72d91916a9157cc1891870025c018509e4 | MapleStoryBoy/spider | /数据结构/数据分析/numpy和pandas/练习.py | 493 | 3.578125 | 4 | import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
file_path = "./starbucks_store_worldwide.csv"
df = pd.read_csv(file_path)
#print(df.head(1))
#print(df.info())
#使用matplotlib呈现出店铺总数排名前10的国家
#准备数据
data1 = df.groupby(by="Country").count()["Brand"].sort_values(ascending=False)[:10]
_x = data1.... |
3e4e284121a78e8cc8dd191624c23e46a987f21f | MapleStoryBoy/spider | /python爬虫开发与项目实战笔记/爬虫/解析库的使用/BeautifulSoup使用/基本用法.py | 1,622 | 3.9375 | 4 | from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dormouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters;and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!... |
b245c5f1139f9eda59c908bcc8dd5ffb69e99119 | MapleStoryBoy/spider | /python_zero/ajax_spider_demo/demo4.py | 1,726 | 3.515625 | 4 | #encoding: utf-8
# 常见的表单元素:input type='text/password/email/number'
# buttton、input[type='submit']
# checkbox:input='checkbox'
# select:下拉列表
# 操作输入框
# from selenium import webdriver
# import time
#
# driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
# driver = webdriver.Chrome(executable_path=... |
1c6a69361c67989e22f8928441335793935a32ee | viliam-gago/engeto_python_course_projects | /car_database/car_database.py | 11,305 | 3.71875 | 4 | import os
def greet():
separator()
print('Welcome to our car rental database.')
separator()
print('''What would you like to do ? Please choose from options below:
a) Show all available cars
b) Search cars
c) Rent a car
d) Return a car
e) Exit the program''')
separator()
... |
ba27a5fdc08a1c273cdffea48fdb8eb7b027096c | viliam-gago/engeto_python_course_projects | /homeworks/lesson_2/check_start.py | 150 | 3.65625 | 4 | password = input('Type password: ').lower()
if password[0] in ['a','e','f','q','z']:
print('Welcome!')
else:
print('The input does not match') |
cf4baae5b6161d88005c00da62d878ad4f650a78 | viliam-gago/engeto_python_course_projects | /homeworks/lesson_2/convert_day.py | 329 | 4.15625 | 4 | week = ['Monday','Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
choice = input('Please enter the number of the day: ')
if choice not in ['1', '2', '3', '4', '5', '6', '7']:
print('Enter only numbers between 1 and 7')
elif choice == '':
print('No input provided')
else:
print(week[int(ch... |
b22e1bddef7a7801c3d626fe555e622d5027311c | viliam-gago/engeto_python_course_projects | /homeworks/lesson_5/problem30_string_to_list.py | 181 | 3.8125 | 4 | answer = input('Hello, please write your numbers and press enter to confirm: ')
answer = answer.split(',')
new_list = [int(number.strip(' ')) for number in answer]
print(new_list)
|
51bb3ffba1478020803d279193621edb4a10f6b8 | omarASC5/daily-coding-problems | /day2.py | 1,532 | 4.125 | 4 | '''
This problem was asked by Uber.
Given an array of integers, return a new array such that each element at
index i of the new array is the product of all the numbers in the
original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5],
the expected output would be [120, 60, 40, 30,... |
fd4b2ec39861aa888dad9ae4d1163faa691dffe5 | spritz-group/miniV2G | /examples/v2g_tcp.py | 1,709 | 3.5625 | 4 | #!/usr/bin/python
import socket
class TCPClient:
'''
TCP Client which can send a messsage and get the response if available.
'''
def __init__(self, addrinfo, client_name = "client", server_name = 'server'):
# Connect to the server
self.client_name = client_name
self.server_name... |
0c6872a1a5623d4dfad78c482473241e529a503a | psimaj/University-materials | /python_lc_and_gen_lecture/generators/gen_2_multiple_yields.py | 272 | 4.21875 | 4 | """
contrary to how return behaves in function, one may have multiple consecutive yields
the following example is equivalent to big_powers(5) from the previous example
"""
def why_loop():
yield 1
yield 1
yield 4
yield 27
yield 256
print(*why_loop())
|
b60dc9fa9f535ad022137e022222ef7fdc0255ad | psimaj/University-materials | /python_lc_and_gen_lecture/list_comprehension/comp_4_if.py | 582 | 4.25 | 4 | """
let's enrich the list comprehension syntax with conditionals:
[expr for item in iterable if condition]
"""
a = [i for i in range(10) if i % 2 == 0]
print(a)
"""
shall produce the same results as:
"""
a = []
for i in range(10):
if i % 2 == 0:
a.append(i)
print(a)
"""
you can use more than one if whic... |
807ee79a340503bfa0bca39507a72e3af04a4ecc | freemanc70/Leetcode-practice | /addStrings.py | 659 | 3.5625 | 4 | class solution(object):
def addStrings(self,num1,num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
result = []
i, j, carry = len(num1) - 1, len(num2) - 1, 0
while i >= 0 or j >= 0 or carry:
if i >= 0:
carry... |
dff1ed69e3fa8836588af4cb2942231895410abf | erhanhepyasar/Python_Tutorial_Codes | /1_Temel_Programlama/7_karar_yapilari.py | 2,601 | 3.859375 | 4 | # n = 15
# if n > 10:
# print("sayı 10 dan büyüktür")
#diğer int() yöntemi
# sayı = input("Bir sayı giriniz: ")
# sayı = int(sayı)
#parola işlemleri
# print("Lütfen parolayı giriniz: ")
# parola = input("Parola: ")
# if parola == "1234":
# print("Sisteme Hoşgeldiniz!")
# çoklu if yapısı (1 den fazla koşul ... |
c4884c707ad97379903ac9460900f215237ad487 | erhanhepyasar/Python_Tutorial_Codes | /1_Temel_Programlama/4_int_float.py | 1,138 | 3.859375 | 4 | ###################################################
# integer
###################################################
# a = 2
# print(a)
# print(type(a))
###################################################
# float
###################################################
# b = 3.5
# print(b)
# print(type(b))
##################... |
2f8bd7d6de200236df1f6ea5c75ca26abd1fafc2 | erhanhepyasar/Python_Tutorial_Codes | /2_Nesneye_Yonelik_Programlama/3_coklu_kalitim.py | 2,461 | 4.0625 | 4 | ##################################################
# Tüm sınıflar object sınıfının alt sınıfıdır
##################################################
# # Output: True
# print(issubclass(list,object))
# # Output: True
# print(isinstance(5.5,object))
# # Output: True
# print(isinstance("Hello",object))
##################... |
94fc03a7c5a1761d021217ed3f16e2d73262ff10 | erhanhepyasar/Python_Tutorial_Codes | /1_Temel_Programlama/5_aritmetik_ornekler/5_1_dikdortgen_alani_hesaplama.py | 458 | 4 | 4 | #####################################################################
# ORNEK PROGRAM: Diksörtgenin 2 kenarlarını sor, alanını hesapla, ekrana yazdır
#####################################################################
kenar1 = input("Dikdörtgenin 1. kenarının uzunluğu: ")
kenar2 = input("Dikdörtgenin 2. kenarının uzu... |
24c208fddac22a49c0d149ab3dd00f1d579bdf95 | csr/Python-Scientific-Programming | /Data Fitting/CesareDeCal/exercise3.py | 1,416 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Cesare De Cal
Data Fitting
Exercise 3
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import CubicSpline
from scipy.interpolate import lagrange
from numpy.polynomial.polynomial import Polynomial
# Points provided by the chemistry experi... |
96a7788ffd2c99fe72e5b98a09a49de151ac9374 | junseppark/study_python | /FindPrimeNumbers.py | 800 | 3.546875 | 4 | # 완전탐색 > 소수 찾기
# https://programmers.co.kr/learn/courses/30/lessons/42839#
# 테스트 케이스는 괜찮은데, 왜 안되는 거지..
from math import sqrt
from itertools import permutations
def solution(numbers):
answer = 0
# combinations
c_arr = list(set(map(int, [''.join(j) for i in range(len(numbers)) for j in permutations(numbers... |
4dd5ba19c0fd1bee5224cadb9dc3a9563312001f | patchaiy/pythonproject | /greater.py | 145 | 4.0625 | 4 | print("enter the number:")
a=int(input())
b=int(input())
d=int(input())
if a>b and a>d:
print(a)
elif b>a and b>d:
print(b)
else:
print(d)
|
38aa6b947c8704e9433a8f2ce1e00190a83af2df | eivindlie/PuzzleSolver | /main.py | 927 | 3.84375 | 4 | from state import State
from queue import PriorityQueue
def main():
goal = State(
[[1, 2, 3],
[4, 5, 6],
[7, 8, 0]]
)
start = State(
[[1, 5, 0],
[2, 8, 7],
[4, 6, 3]],
goal
)
solution = solve(start, goal)
print_solution(solution)
d... |
071abe1bfd4bc2c05d22010285812bac5c1b977e | MagicCheng/efp | /ex15.py | 297 | 3.96875 | 4 | from sys import argv
script, filename = argv #unpack values two
txt = open(filename) #ready for line 8
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input(">") #ready for line 13
txt_again = open(file_again)
print txt_again.read() |
8b7465e28885217fe2fcf0cf6d83c434cb97a741 | mas212/basic-python2 | /string.py | 222 | 3.984375 | 4 | #argument by position
print("my name is {name} and I age {age}".format(name='mas212', age=29))
a = "hallo"
#capatilize letter
print(a.capatilize())
#make all uppercase
print(a.upper())
#make all lowercase
print(a.lower()) |
7a0cc1df9710b2f5d792224c86e6f0f95bcce994 | designedbyjosh/daily-coding-problem | /solutions/1/solution.py | 947 | 3.84375 | 4 | def calculateRooms(intervals):
# Store the bookings at each time
bookings = {}
# Create the entry and exit values, and if there are duplicates, add another to that time interval
for interval in intervals:
bookings[interval[0]] = bookings[interval[0]] + 1 if interval[0] in intervals else 1
... |
e5729d5c87c2e79fada287c53d5130c0dbaf18b1 | ManuBedoya/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 676 | 3.625 | 4 | #!/usr/bin/python3
"""Module island perimeter
"""
def island_perimeter(grid):
"""find the perimeter of the island
"""
if grid is None:
return 0
max_col = 0
max_row = 0
count = 0
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] == 1... |
6fc0b6ad5f3109b6b25a59f3a45e909ab04b690e | FelpsFon/curso_python | /4/6_sets.py | 186 | 3.90625 | 4 | # add e remove, GARANTE QUE TODO ELEMENTO SÓ APARECE UMA VEZ
numeros_sorteados = {1,2,3}
numeros_sorteados2 = set([3,'2',1])
for item in numeros_sorteados: ## iteravel
print(item) |
8ee0c2c8715a67c7622a65ebaa98f748c40473d5 | FelpsFon/curso_python | /revisao/7_lacos_while.py | 280 | 4.0625 | 4 | # o laço while é utilizado em conjunto a uma expressão condicional, para repetições que não sabemos
# quantas vezes serão repetidas
senha_correta = '123'
senha = ''
while senha != senha_correta:
senha = input('Digite a senha')
print('Senha correta, acesso concedido') |
4374bf5b708c48cc0fcd4ea8462ee9426b68bc40 | FelpsFon/curso_python | /5/3_dict_Duvids.py | 584 | 4.09375 | 4 | #em codigo como faz um array de dicts?
# lista_alunos = [{'nome': 'daniel'}, {'nome': 'lucas'}]
# lista_alunos[0]['idade'] = 19
# print(lista_alunos)
#podemos usar input na estrutura dicts? ou append?
# meu_dict = dict()
# for _ in range(0, 2):
# chave = input('digite a chave do campo: ')
# valor = input('d... |
0a8b2b1ef32e676ce4ed77a09a92b274188035e3 | FelpsFon/curso_python | /revisao/10_sets.py | 420 | 3.953125 | 4 | # estruturas, lineares, não ordenadados, que garante a mesma propriedade de acessos
# da lista, porem não permite itens duplicados,
# semelhante a conjuntos numericos da matematica, ps: não aceita somente numeros,#
# qualquer coisa é possivel incluir
conjunto = {1,2,4}
conjunto.add('lucas')
#print(conjunto.add('lucas'... |
277cb10f4252e7234b8682f107c7c077055ea7cd | lilianwaweru/News-Highlight | /tests/test_news.py | 737 | 3.703125 | 4 | import unittest
from app.models import News
class NewsTest(unittest.TestCase):
'''
Test Class to the the behaviour of the News class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_news = News("bbc-sport","BBC Sport","The home of BBC... |
46b0796d6284ab5120effd726d8d613c5c41d7d0 | asmarakhtar/SortAnalyzer | /sort-analyzer.py | 4,210 | 3.96875 | 4 | # Sort Analyzer by Mr. V
def bubbleSort(anArray)
n = len(anArray)
for i in range(n-1):
for j in range(0, n-i-1):
if anArray[j] > anArray[j+1] :
anArray[j], anArray[j+1] = anArray[j+1], anArray[j]
def selectionsort(anArray):
for i in range(len(anArray)-1):
... |
7e8b561eaee1d9dc3968419039977e5c85494ecd | stoic-signs/ADSA | /dfs.py | 738 | 3.65625 | 4 | # DFS
class Graph:
def __init__(self, vertices):
self.graph = {}
for i in range(vertices):
self.graph[i] = []
def addEdge(self, u, v):
self.graph[u].append(v)
def DFSUtil(self, v, visited):
visited[v] = True
print(v, end=' ')
for i in self.gra... |
a22c514f0714067cdac5ec530b051e9dde9c5aa0 | phammanhhiep/CS231A | /ps1/p2.py | 3,396 | 3.734375 | 4 | # CS231A Homework 1, Problem 2
import numpy as np
'''
DATA FORMAT
In this problem, we provide and load the data for you. Recall that in the original
problem statement, there exists a grid of black squares on a white background. We
know how these black squares are setup, and thus can determine the locations of
specifi... |
acf6e40c7a78216f663280c6f6bc741a412dbae0 | ambreelmee/conflicts-management | /src/models/database_bridge.py | 1,202 | 3.59375 | 4 | """
Define the DatabaseBridge model
"""
from . import db
from .abc import BaseModel
class DatabaseBridge(db.Model, BaseModel):
""" The DatabaseBridge model """
__tablename__ = 'database_bridge'
source_field = db.Column(db.String(30), primary_key=True)
bloc = db.Column(db.String(30))
value_key = db... |
4a6ab06cdf004e8d777f50ef2c3ec68f3f4e4c9e | HamzaUmer/ProTech | /Area of a triangle.py | 110 | 3.890625 | 4 | h=float(input('Height = '))
b=float(input('Breadth = '))
A=(h*b)/2
print("Area Of Triangle = {0} ".format(A))
|
25933a792d508bd14b6149743925a3f70f4751a6 | RandLive/Udacity_MLND_Projects | /CN/Proj_UD_ML_P0/csv_out.py | 3,606 | 3.765625 | 4 | import numpy as np
import pandas as pd
# RMS Titanic data visualization code
# 数据可视化代码
from titanic_visualizations import survival_stats
from IPython.display import display
# Load the dataset
# 加载数据集
in_file = 'titanic_data.csv'
full_data = pd.read_csv(in_file)
outcomes = full_data['Survived']
data = full_data.dro... |
bb6550f3850745cd5c7f03c7a5e7e6fb28189b1b | DavidSouther/software_craftsmanship | /05_input_output/02_reading_files/presidents3.py | 1,152 | 3.625 | 4 | import csv
import os
from datetime import datetime
class President():
def __init__(self, number, name, start_date, end_date, party, vice_pres):
self.number = number
self.name = name
self.start_date = start_date
self.end_date = end_date
self.party = party
self.vice_p... |
e8ef90bf1f2362164b0cd9cc8694d3a7994f563c | DavidSouther/software_craftsmanship | /03_objects/02_rugs/rugs_exercises.py | 4,457 | 4.28125 | 4 | from math import pi
class Rug():
def __init__(self, has_fringe = False, description = "", color=""):
self.has_fringe = has_fringe
self.description = description
self.color = color
def get_values(self):
"""
Ask the user for all the values necessary for this rug.
... |
18ca6307adc426bb1db5940470d2440a63d0470c | E1mir/PySandbox | /src/ds_algs/sorting_algs/selection_sort.py | 469 | 4.09375 | 4 | def selection_sort(arr):
for fill_slot in range(len(arr) - 1, 0, -1):
position_of_max = 0
for location in range(1, fill_slot + 1):
if arr[location] > arr[position_of_max]:
position_of_max = location
arr[fill_slot], arr[position_of_max] = arr[position_of_max], ar... |
1dea949e5fdf58e73218a5f2309d9cd4439b248f | E1mir/PySandbox | /src/ds_algs/binary_heap.py | 1,778 | 3.703125 | 4 | class BinaryHeap(object):
def __init__(self):
self.heap_list = [0]
self.current_size = 0
def insert(self, element):
self.heap_list.append(element)
self.current_size += 1
self.percolate_up(self.current_size)
def percolate_up(self, i):
while i // 2 > 0:
... |
4a8dac04ffb8e7e15c891d84762ce7b4ca591aad | E1mir/PySandbox | /src/ds_algs/sorting_algs/insertion_sort.py | 424 | 4.21875 | 4 | def insertion_sort(arr):
for i in range(1, len(arr)):
current_value = arr[i]
position = i
while position > 0 and arr[position - 1] > current_value:
arr[position] = arr[position - 1]
position -= 1
arr[position] = current_value
if __name__ == '__main__':
... |
eca47f29231d915300b38acd96e73fb046949f36 | E1mir/PySandbox | /src/problems/searching/binary_search.py | 927 | 4.09375 | 4 | def binary_search(arr, ele):
first = 0
last = len(arr) - 1
found = False
while first <= last and not found:
mid = (first + last) // 2
if arr[mid] == ele:
found = True
else:
if ele < arr[mid]:
last = mid - 1
else:
... |
fa632823156c780e08cddb681b2302af41bc46f1 | E1mir/PySandbox | /src/gui/tkinter/message_box_gui.py | 263 | 3.6875 | 4 | import tkinter
from tkinter import *
from tkinter import messagebox
window = Tk()
def func():
messagebox.showinfo("Title", "Message")
btn = Button(window, text="Open Message", command=func)
btn.place(relx=0.5, rely=0.5, anchor=CENTER)
window.mainloop()
|
2700192f7481e660cfc8a7395ab5afa95e0282cf | E1mir/PySandbox | /src/tricks/py_tricks.py | 2,594 | 4 | 4 | import itertools
from collections import OrderedDict, Counter
def list_join_trick():
"""
List joins without loop
"""
some_list = [[1, 2, 3], [4, 5], [6], [7, 8, 9]]
joined = sum(some_list, [])
print(joined)
# It would be better if you use itertools instead of sum func
joined = list(ite... |
e99b861e21b06128012e881fc260a8d04e47b2db | E1mir/PySandbox | /src/problems/recursion/fibonacci_sequence.py | 637 | 3.671875 | 4 | # recursion
def fib_rec(n):
if n == 0 or n == 1:
return n
else:
return fib_rec(n - 1) + fib_rec(n - 2)
# iteration
def fib_iter(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
c_n = 40
cache = [None] * (c_n + 1)
def fib_dyn(n):
# base case
if n == 0 ... |
1095c16090fbced820495e9becbc51f03a21ccd5 | E1mir/PySandbox | /src/gui/tkinter/listbox_gui.py | 160 | 3.59375 | 4 | from tkinter import *
window = Tk()
list_box = Listbox(window)
for i in range(10):
list_box.insert(i, f"Item {i+1}")
list_box.pack()
window.mainloop()
|
debe4ea6db05e8bc94a68e8516e372d6ff0c68ef | kajalkahar/Python_p | /Bmi.py | 651 | 3.875 | 4 | name1 = "kk"
height_m1 = 5
weight_kg1 = 50
name2 = "kk's sister"
height_m2 = 2.1
weight_kg2 = 55
name3 = "kk's brother"
height_m3 = 3.1
weight_kg3 = 45
def bmi_calculator(name, height_m,weight_kg):
bmi = weight_kg / (height_m ** 2)
print("bmi: ")
print(bmi)
if bmi < 25:
retur... |
695bc1d659971149b7736fe88453a60df435c44d | wnsgur4322/CS372---Intro-to-computer-networks | /lab1/ec_lab1.py | 1,072 | 3.53125 | 4 | #written by Junhyeok Jeong
#CS 372 - Lab1 extra credit
#Language: python 3.x
import socket
import sys
import http.client
import urllib
#create an INET and STREAM socket
try:
sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket Successfully created")
#error handling
except socket.error as err:
prin... |
69bc66a8b98855145bba77aebe365c4080bdae58 | BZAghalarov/Hackerrank-tasks | /Cracking coding interview/11 Sorting Comparator.py | 2,433 | 4.125 | 4 |
'''
https://www.hackerrank.com/challenges/ctci-comparator-sorting/problem
In this challenge Quicksort algo is used
Recursive Quicksort
https://www.geeksforgeeks.org/quick-sort/
Iterative Quicksort
https://www.geeksforgeeks.org/iterative-quick-sort/
http://interactivepython.org/courselib/static/pythonds/SortSearch... |
283e67a2772260fbe86df0c7e3cfefac565dbc78 | BZAghalarov/Hackerrank-tasks | /Cracking coding interview/5 Stacks Balanced Brackets.py | 2,324 | 3.921875 | 4 | '''
https://www.hackerrank.com/challenges/ctci-balanced-brackets
'''
def is_matched(expression):
stack = []
pairs = {'{': '}', '[': ']', '(': ')'}
for char in expression:
if char in pairs.keys():
stack.append(pairs[char])
else:
# You need to check if the stack is ... |
9cb65daf3433edbcdc4e3403c7b85672e6d62967 | BZAghalarov/Hackerrank-tasks | /The HackerRank Interview Preparation Kit/Dynamic programming/Abbreviation.py | 1,008 | 3.546875 | 4 |
'''
https://www.hackerrank.com/challenges/abbr/problem?h_l=playlist&slugs%5B%5D%5B%5D=interview&slugs%5B%5D%5B%5D=interview-preparation-kit&slugs%5B%5D%5B%5D=dynamic-programming
'''
def matchstring(a, b, store):
if len(a) < len(b):
return False
dp = [True] + [False] * len(b)
i = 0
while i ... |
1475d70bb87346f1c9026d977f5b6972057c9714 | BZAghalarov/Hackerrank-tasks | /The HackerRank Interview Preparation Kit/Dictionaries and Hashmaps/Sherlock and Anagrams.py | 1,158 | 3.609375 | 4 |
'''
https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem?h_l=playlist&slugs%5B%5D%5B%5D=interview&slugs%5B%5D%5B%5D=interview-preparation-kit&slugs%5B%5D%5B%5D=dictionaries-hashmaps
'''
from collections import *
for i in range(int(input())):
s = input()
check = defaultdict(int)
l = len... |
c9cdb5c20ba4e0f16ceb32eca9371a8d1ebccff9 | BZAghalarov/Hackerrank-tasks | /The HackerRank Interview Preparation Kit/Linked Lists/Insert a node at a specific position in a linked list.py | 843 | 3.84375 | 4 |
'''
https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem?h_l=playlist&slugs%5B%5D%5B%5D=interview&slugs%5B%5D%5B%5D=interview-preparation-kit&slugs%5B%5D%5B%5D=linked-lists
'''
"""
Insert Node at a specific position in a linked list
head input could be None as well f... |
ac24e751eb72acc999a95ef94f853c496d686628 | BZAghalarov/Hackerrank-tasks | /The HackerRank Interview Preparation Kit/Stacks and Queues/Balanced Brackets.py | 2,125 | 4.21875 | 4 |
'''
https://www.hackerrank.com/challenges/balanced-brackets/problem?h_l=playlist&slugs%5B%5D%5B%5D=interview&slugs%5B%5D%5B%5D=interview-preparation-kit&slugs%5B%5D%5B%5D=stacks-queues
'''
#!/bin/python3
class ArrayStack:
'''LIFO Stack implementing using a Python list as underlying storage '''
def __init... |
65ec91060a24faa07984cf130a13e20e94d680d2 | acc-cosc-1336/cosc-1336-spring-2018-jjmareck | /src/homework/main/main_homework8.py | 868 | 4.1875 | 4 | from src.homework.homework8 import add_inventory
'''
Write a main function to create an empty dictionary and
a user-controlled loop to prompt for a widget name and quantity.
Add the values to the dictionary as key(widget name) and value(quantity) pairs.
After user decides to exit write data to file .
'''
def main... |
a4eea38dc8c3d49933c9798eb7d276df2bee3bfd | acc-cosc-1336/cosc-1336-spring-2018-jjmareck | /src/homework/homework5.py | 523 | 4.03125 | 4 | #Create a function named write_sales_data with file_object, item and price as parameters.
#The function should write item and price to a file.
def write_sales_data(file, item, price):
file.write(item + ' ' + price +'\n')
#Create another function named read_sales_data with file_object as a parameter.
#The functio... |
a5c0aac6137e20640fd06ed82bf6acaa8fd6949f | acc-cosc-1336/cosc-1336-spring-2018-jjmareck | /src/assignments/assignment12/win.py | 902 | 3.59375 | 4 | from src.assignments.assignment12.converter import Converter
import tkinter
class Win():
def __init__(self):
self.main_window = tkinter.Tk()
self.top = tkinter.Frame(self.main_window)
self.bottom = tkinter.Frame(self.main_window)
km=100
con = Converter()
mi... |
b347c8a79803df2fd957a9bb7e6232cb324031bb | acc-cosc-1336/cosc-1336-spring-2018-jjmareck | /src/homework/homework9/player.py | 780 | 4.09375 | 4 | #write import statement for Die class
from src.homework.homework9.die import Die
'''
Create a Player class.
'''
class Player:
def __init__(self):
'''
Constructor method creates two Die attributes die1 and die2
'''
self.die1 = Die()
self.die2 = Die()
def roll_doubles(... |
12177e4e3e5a22a13140a527f7a76a040e9cac98 | jptrinastic/Topic_Modeling | /WosClustering/xml_to_dataframe.py | 7,659 | 3.546875 | 4 |
#Libraries
import pandas as pd
import numpy as np
class XmlToDataframe():
"""
Class to convert Web of Science XML query data to Pandas dataframe.
"""
def __init__(self, xmlData):
"""
Initialize class and load xmlData to convert to dataframe.
Parameters
---... |
591bf87552aa1018b09f45dbeaa6ad8a1804f099 | paytaa/nubip | /task 1.py | 2,102 | 3.984375 | 4 | #Оголошуємо змінну, і просимо ввести рядок
sttr = input("Input your string: ")
word=''
num=[]
leng=len(sttr)
print('\t')
print("String is:"+sttr)
#Запускаємо цикл для створення масиву. Цикл шукає число і добавляє його в кінець
p=0
for i in range(leng):
j=sttr[i]
if '0'<= j<='9':
num.append(i... |
accc94dd466d3a7e10616f77ba4c22db346b9d58 | bttcooldown/Study | /DeMo/用Python玩转数据/num guess.py | 507 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 21 21:43:05 2018
@author: Administrator
"""
from random import randint
x = randint(0,300)
go = 'y'
while (go == 'y'):
digit = int(input('Pleae input a number between 0~300'))
if digit == x:
print('Bingo!')
break
elif digit > x:
print('... |
fc83e9569d7a61a8389e7aaf5962412b5b7ff741 | douglasaxel/python | /testeSublime.py | 180 | 3.859375 | 4 | nome = input("Digite seu nome: ")
print(nome)
idade = int(input("Digite sua idade: "))
if idade > 18:
print(nome + "já pode beber")
else:
print(nome + "ainda não pode beber")
|
45a0d90b89295856aea4612ebe78679c28d44b0d | HareshNasit/LeetCode | /Array/intersection_2_arraysII.py | 593 | 3.828125 | 4 | def intersect(self, nums1, nums2):
"""
https://leetcode.com/problems/intersection-of-two-arrays-ii/
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1_dict = {}
intersection = []
for i in nums1:
if i not in nums1_... |
f88bdbebd24f31f96a4bf01a8dba310732bbf7dd | HareshNasit/LeetCode | /Binary_Search/Search_insert_position.py | 763 | 3.90625 | 4 | def searchInsert(self, nums, target):
"""
https://leetcode.com/problems/search-insert-position/
:type nums: List[int]
:type target: int
:rtype: int
"""
#Runs in O(logn)
start = 0
end = len(nums)
while start < end:
mid = start+(e... |
85c3905e018f04ac88b31d753f9db352222e9382 | HareshNasit/LeetCode | /Top Amazon Questions 2020-21/88. Merge Sorted Array.py | 1,977 | 3.8125 | 4 | def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
# 2 pointers problem
# nums1[:] = sorted(nums1[:m] + nums2) # Runtime O((m+n)*log(m+n)) Brute Force
# Runtime: O(m+n), Space: O(m)
... |
f8431bb5d7a34351691ccfab9e1ecaa0acf1abd1 | HareshNasit/LeetCode | /Hash Table/common_characters.py | 260 | 3.609375 | 4 | def commonChars(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
#Brute Force
#Create a dictionary for all all the strings to track the count of letters.
#Compare and keep the count of each letter.
|
7b553ef8c7857be20ae8ccfa782beee38359cbc6 | HareshNasit/LeetCode | /Math/majority_element.py | 432 | 3.65625 | 4 | def majorityElement(self, nums):
"""
https://leetcode.com/problems/majority-element/submissions/
:type nums: List[int]
:rtype: int
"""
nums_dict = {}
for i in nums:
if i not in nums_dict:
nums_dict[i] = 1
else:
... |
da55b352a2b83415838ac5bba9af60247f61f423 | HareshNasit/LeetCode | /Array/longest_consecutive_sequence.py | 1,008 | 3.625 | 4 | def longestConsecutive(self, nums):
"""
https://leetcode.com/problems/longest-consecutive-sequence/
:type nums: List[int]
:rtype: int
"""
#Runtime O(NlogN)
if nums == []:
return 0
nums.sort()
longest_streak = 1
curr_streak = 1
... |
a58b090774d02ed1c6059298a5df3305b055df4f | HareshNasit/LeetCode | /Top Amazon Questions 2020-21/767. Reorganize String.py | 1,149 | 3.53125 | 4 | def reorganizeString(self, S: str) -> str:
# Runtime: O(N*logA) where A is the num of alphabets used
# Space: O(A) Storing characters in HashMap and Heap
freqs = {}
for c in S:
if c not in freqs:
freqs[c] = 1
else:
freqs[c] += 1
... |
935c6d00e584de6feb4856441c1999acc6a3bd48 | HareshNasit/LeetCode | /grind_2.0/Third_max.py | 718 | 3.734375 | 4 | class Solution:
# https://leetcode.com/problems/third-maximum-number/
def thirdMax(self, nums: List[int]) -> int:
# Time: O(N)
first_max = float('-inf')
second_max = float('-inf')
third_max = float('-inf')
for num in set(nums):
if max(num, first_max) == num:
... |
12c457b8c121ae7b97e779c06d602b9f29a0876c | HareshNasit/LeetCode | /Array/uncommon_words_2_sentences.py | 730 | 3.640625 | 4 | def uncommonFromSentences(self, A, B):
"""
https://leetcode.com/problems/uncommon-words-from-two-sentences/
:type A: str
:type B: str
:rtype: List[str]
"""
words = {}
for word in A.split(" "):
if word not in words:
words[word] =... |
014dad53f789f1548c9c5fd61e09903f91f6486b | HareshNasit/LeetCode | /String/longest_common_prefix.py | 751 | 3.65625 | 4 | def longestCommonPrefix(self, strs):
"""
https://leetcode.com/problems/longest-common-prefix/
:type strs: List[str]
:rtype: str
"""
#Idea: Traverse through all the strings, find the intersection one by one.
#Runtime O(N)
if len(strs) == 0:
ret... |
9332e99983bf8f8c9b40675fa49cff6fe5b4e7fe | HareshNasit/LeetCode | /Linked_List/odd_even_linked_list.py | 1,239 | 3.859375 | 4 | def oddEvenList(self, head):
"""
https://leetcode.com/problems/odd-even-linked-list/
:type head: ListNode
:rtype: ListNode
"""
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
retur... |
eb29c19d662dc125b158c76ffa4c8634b0fda4b7 | HareshNasit/LeetCode | /Array/valid_sudoku.py | 1,357 | 3.71875 | 4 | def isValidSudoku(self, board):
"""
https://leetcode.com/problems/valid-sudoku/submissions/
:type board: List[List[str]]
:rtype: bool
"""
#Idea: Create a method to check if an array of 9 numbers are distinct.
# Then call the method on all the possible combinations... |
8cf21509a756dbf40ba5fb56c7a2ed12378da08f | HareshNasit/LeetCode | /String/reverse_words_string.py | 419 | 3.84375 | 4 | def reverseWords(self, s):
"""
https://leetcode.com/problems/reverse-words-in-a-string/
:type s: str
:rtype: str
"""
words = s.split(" ")
reverse_string = ""
print words
for i in range(len(words) - 1, -1, -1):
if words[i] != "":
... |
daec4534c971f9da73138690026b76d41b8afbba | HareshNasit/LeetCode | /Linked_List/remove_duplicates.py | 540 | 3.5625 | 4 | def deleteDuplicates(self, head):
"""
https://leetcode.com/problems/remove-duplicates-from-sorted-list/submissions/
:type head: ListNode
:rtype: ListNode
"""
unique = []
curr = head
prev = None
while curr != None:
if curr.val i... |
945a26b11b0703b7325c0666c488a6ab1112d138 | HareshNasit/LeetCode | /Math/complement_base10_int.py | 442 | 3.59375 | 4 | def bitwiseComplement(self, N):
"""
https://leetcode.com/problems/complement-of-base-10-integer/
:type N: int
:rtype: int
"""
bin_N = bin(N)
bin_N = str(bin_N)[2:]
print bin_N
complement = ""
for i in bin_N:
if i == "0":
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.