blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5f47201109dc147b4ff482e706d067cd68e1f53c | hidalgowo/CC1002 | /Clases/Clase_06_modulos/ejemplos-recursion.py | 1,106 | 4.03125 | 4 | #suma: int int -> int
#Calcula x + (x+1) + ... + y
#ej: suma(3,5) debe ser 12
def suma(x,y):
assert (type(x)==int) and (type(y)==int)
if x>y:
return 0
else:
return suma(x,y-1) + y
assert suma(3,5)==12 #caso general
assert suma(3,3)==3 #caso especial
assert suma(5,3)==0 #caso base
# ... |
479ba9809ff46ce68cd49c9fd371b0d6b2b39dd6 | hidalgowo/CC1002 | /Clases/clase_23_modulos/caso_estudio_IV.py | 1,977 | 3.8125 | 4 | # -*- coding: utf-8 -*-
from tkinter import *
from DiccionarioLista import *
# Variable global
# (Nota: no se requiere agregar una línea 'global D' dentro de cada función que usa D porque
# D fue definido primero *fuera* de todas las funciones. Sólo se necesita cuando la variable es definida
# primero dentro de una ... |
3dd3a086acfcea938b75ddc7600f07920966665c | hidalgowo/CC1002 | /Clases/Clase_19_modulos/busqueda-y-ordenamiento.py | 7,229 | 3.703125 | 4 | # -*- coding: utf-8 -*-
#Clase_19_Caso-de-Estudio-III_Busqueda-y-Ordenamiento_2020
# Busqueda Secuencial
# busquedaSecuencial: list(int) int -> int o None
# devuelve el indice de la lista donde se encuentra valor haciendo una
# busqueda secuencial, o devuelve None si no esta
# ejemplo: busquedaSecuencial([258, 45, 99... |
b9dd2517b04f752cabec9b59b05b6258f3985ff5 | Rahul-shakya/LeetCode-Questions | /isValid.py | 551 | 3.640625 | 4 | class Solution:
def isValid(self, s: str) -> bool:
brackets = {'(':')', '[':']', '{':'}'}
stack = []
for currBracket in s:
if currBracket in brackets.keys():
stack.append(currBracket)
else:
if(len(stack) == 0):
retu... |
17e3e71ce754d8e62c13f1f42f75041f9f1038d0 | prakharrathi25/the-tool-bmwi | /archive/cinny_page.py | 3,240 | 3.6875 | 4 | # interactive map with plotly
# Import necessary libraries
from typing import Optional
import pandas as pd
import streamlit as st
import base64
import geopandas as gpd
import json
import matplotlib.pyplot as plt
import json
import plotly.express as px
# Custom modules
from .utils import *
# Suppress warnings in ... |
9187782fef329dfad773be63582bd0f18b133f0b | willoughbys70590/Animal_quiz | /00_sandbox_v1.py | 6,248 | 3.78125 | 4 | from tkinter import *
from functools import partial # To prevent unwanted windows
import random
import csv
class Start:
def __init__(self, partial):
# GUI to get starting balance and stakes
self.start_frame = Frame(padx=10, pady=10)
self.start_frame.grid()
self.heading_... |
39e6bf7406f720f4d6e38c121b69b2fd10afaabe | TylerHJH/DataStructure | /lab1_e1.py | 1,329 | 4.3125 | 4 | """
Input:
a, b: line1 represented as y1 = a*x1 + b
x, y: point A(x,y), which is on the line above
Output:
the line and c, d or none: line2 represented as y2 = c*x2 + d, which point A is on the line,
and line2 is perpendicular to line1 or line2 represented as y2 = y.
"""
# Here is a fu... |
870137cf1c812f52d83a29a95231a16ad363e87b | TylerHJH/DataStructure | /DoublyLinkdedList.py | 5,019 | 4.0625 | 4 | """双向链表实现"""
"""节点类"""
class Node:
def __init__(self, data=None):
self.data = data
self.pre = None
self.next = None
"""双向链表"""
class DoublyLinkedList:
"""初始化"""
def __init__(self):
head = Node()
tail = Node()
self.head = head
... |
6fd2fe70aac57afe6d8f3eb8d4977509569f8c30 | H4rliquinn/Hash-Tables | /dynamic_array/dynamic_array.py | 926 | 3.921875 | 4 | class DynamicArray:
def __init__(self,capacity=8):
self.count=0
self.capacity=capacity
self.storage=[None]*self.capacity
def insert(self, index,value):
if self.count==self.capacity:
print("Error: Array is full")
return
if index>=self.count:
... |
9e42bd585232a9bad143eec87697cfcafbd239c5 | OlaSoko/game-of-life | /gameoflife/__init__.py | 3,589 | 3.703125 | 4 | import os
import random
import time
from typing import Tuple, Iterable, Set
Position = Tuple[int, int]
class GameOfLife:
def __init__(self, seed: Iterable[Position]):
"""
:param seed: starting state of the game
"""
self._state = set(seed)
self._next_state = set(self._stat... |
bc8574857979fc0e8de9c46822c0cadf8383253e | quangloc99/CompetitiveProgramming | /Topcoder/SRM355-D1-500.py | 2,675 | 3.65625 | 4 | # Author: Tran Quang Loc
# Idea:
# Let's call 4 points A, B, C, D.
# First I used triangle inequality to check for each triple of points.
# If the above is true, then we got triangle ABC. Now I check if 3 spheres (A, AD), (B, BD) and (C, CD) are intersected or not.
# It is easy to see that they are intersected iff the ... |
74228f7b614e27bb5b95d8aded8e2a170a83e289 | debaraj-barua/amr-lab-ss17-dbarua2s | /amr_braitenberg/src/amr_braitenberg/braitenberg_vehicle.py | 2,866 | 3.53125 | 4 | #!/usr/bin/env python
class BraitenbergVehicle:
TYPE_A = 0 # direct connections
TYPE_B = 1 # cross connections
TYPE_C = 2 # direct and cross connections
def __init__(self, *args):
"""
init with default params (type A, factor 1.0)
"""
self.set_params()
... |
40b21c42d7fcb8fcaca692824e4ecb60bccdb043 | nostalgia1367/basicPython | /15/update_record.py | 463 | 3.78125 | 4 | import sqlite3
conn = sqlite3.connect('test.db')
cursor = conn.cursor()
cursor.execute("""
UPDATE PHONEBOOK SET PHONE=?, EMAIL=? WHERE NAME=?
""", ('123-1234-4567', '123@shinhye.com', '박신혜'))
conn.commit()
cursor.execute("""
SELECT NAME, PHONE, EMAIL FROM PHONEBOOK
WHERE NAME=?
""", ('김범수',))
rows = cursor.fetchal... |
cc5ba1c6f44e90f241ce50a01d29e319285d2526 | codebind-luna/problem-solving | /word_search/word_search.py | 1,822 | 3.6875 | 4 | class TrieNode:
def __init__(self):
self.if_word = False
self.children = {}
class Trie:
def __init__(self):
self.root = TrieNode()
def addWord(self,word):
curr = self.root
for s in word:
if s not in curr.children:
curr.chi... |
f24b390d132c825a29377161be802326061b2b55 | codebind-luna/problem-solving | /sum_of_left_leaves/sum_of_left_leaves.py | 1,065 | 3.78125 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
def sumCalculator(root: TreeNode, is_left_child: bool, is_not_root_node: bool = True):
... |
24089d422f334f17f618f705e4074bac1885ee5e | codebind-luna/problem-solving | /minimum_number_of_powers/minimum_number_of_powres_of_2_needed.py | 379 | 4.0625 | 4 | def minPowersOfTwo(number):
comple = (1 << number.bit_length()) - number
pos = neg = 0
while number:
number, bit = divmod(number, 2)
comple, comple_bit = divmod(comple, 2)
pos += bit
neg += comple_bit
pos, neg = min(pos, 1 + neg), min(neg, 1 + pos)
return pos
pr... |
cb5ff09d8e330c23bb9862d20778122a5bf8806c | jmharish/NLP | /Speech_Recognition/speech_rec.py | 265 | 3.59375 | 4 | from nltk import word_tokenize as w
import nltk
def find_noun(t):
l = nltk.pos_tag(w(t))
nouns = []
print(l)
for (a,b) in l :
if b == "NN" or b == "NNS":
nouns.append(a)
print(a)
return nouns
|
5912d1ca4e1cc413fc9ccac347092d95a2943e7a | michaelbuchar/mais-202-coding-challenge | /Interest_Rates.py | 3,706 | 3.671875 | 4 | import csv
import numpy as np
import matplotlib.pyplot as plt
class interest_rate_calc:
### IMPORTS DATA FROM THE CSV FILE
f = open('data.csv') # opens the file
csv = csv.reader(f) # csv reader
values = [] # a list with (purpose, interest_rate)
possible_purposes = set() # a set with no duplicates ... |
d7b92d930c0c687b81eacf43ec82fb391d7bae4e | NMGRL/pychron | /pychron/core/helpers/tests/strtools.py | 982 | 3.609375 | 4 | import unittest
from pychron.core.helpers.strtools import camel_case, ratio
class CamelCaseTestCase(unittest.TestCase):
def setUp(self):
self.expected = "AbqVolc"
def test_already_camelcase(self):
n = self.expected
cn = camel_case(n)
self.assertEqual(n, cn)
def test_unde... |
58bd0d9a2373899c0750dfbab683267e94b10aaf | slaytr/AlgoNotes | /bfs.py | 1,090 | 4.5 | 4 | # Python3 Program to print BFS traversal
# from a given source vertex. BFS(int s)
# traverses vertices reachable from s.
from collections import defaultdict
# This class represents a directed graph
# using adjacency list representation
class Graph:
# Constructor
def __init__(self):
self.graph = defau... |
77894e9ee3782fa7f9893a98e6e3000a0739c774 | AdityaPradhan1/MistWorkshopJan | /Ceaser.py | 1,880 | 4.15625 | 4 |
def encrypt(text,s):
result = ""
# transverse the plain text
for i in range(len(text)):
ch = text[i]
# Encrypt uppercase characters in plain text
if (ch.isupper()):
result += chr((ord(ch) + s - 65) % 26 + 65) #ord used to convert char to int
... |
0066407bd830bda1eb55cb2decfab6f85bc6d6f0 | ArunVasanthmdu/pythonsamples | /weathermap.py | 592 | 3.921875 | 4 | #Sample file for python training
import requests
import json
api_key=r"1c790f0cbdcb53f589706b73afac9b8b"
cityname=input("Please enter city name:")
base_url="http://api.openweathermap.org/data/2.5/weather?q="+ cityname + "&appid=" + api_key + "&units=metric"
print(base_url)
response=requests.get(base_url)
x=response.js... |
23a507d18a5bb704f51c03c2282d1419bde36706 | Emadabdelhamied/Coursera-Algorithmic-Toolbox-master | /assignment solutions/3.1 change.py | 240 | 3.609375 | 4 | def get_change(m):
coins=[10,5,1]
num_of_coins=0
for coin in coins:
num_of_coins+=int(m/coin)
m=m%coin
return num_of_coins
import time
if __name__ == '__main__':
m = int(input())
print(get_change(m))
|
3b00a8765a8846257be72e10e14c09fee59e64f5 | YOON93KYS/python_renshu | /BAEKJOON/for文/2742.py | 441 | 3.625 | 4 | '''
문제
자연수 N이 주어졌을 때, N부터 1까지 한 줄에 하나씩 출력하는 프로그램을 작성하시오.
입력
첫째 줄에 100,000보다 작거나 같은 자연수 N이 주어진다.
출력
첫째 줄부터 N번째 줄 까지 차례대로 출력한다.
'''
A = int(input())
for i in range(A, 0, -1):
print(i)
'''
気づいたこと
range(A, B, C) → Aから Bまで Cずつ増加または減少
'''
|
a25051d742b7f7ead979d4c2ef7c1a0ff2e914f1 | YOON93KYS/python_renshu | /basic/5-3-2/main1.py | 529 | 3.9375 | 4 | '''
5-3-2. 実践演習
1)5-1-2の関数(def)で定義したadd関数でnum_1とnum_2という数型の引数を受け取り、渡したnum_1とnum_2を足すように変更せよ
2)add関数に10,20を渡し、30が出力されることを確認せよ
(目標20分)
'''
'''
#1)5-1-2の関数(def)で定義したadd関数でnum_1とnum_2という数型の引数を受け取り、渡したnum_1とnum_2を足すように変更せよ
'''
def add_2(a, b):
print(a + b)
add_2(10, 5)
|
e7c4a5a366580e20eb1e157506a25360858414e2 | YOON93KYS/python_renshu | /BAEKJOON/IF文/2753.py | 2,301 | 3.828125 | 4 | '''
IF文・論理演算子・比較演算子関連
https://www.acmicpc.net/problem/2753
연도가 주어졌을 때, 윤년이면 1, 아니면 0을 출력하는 프로그램을 작성하시오.
윤년은 연도가 4의 배수이면서, 100의 배수가 아닐 때 또는 400의 배수일 때이다.
예를 들어, 2012년은 4의 배수이면서 100의 배수가 아니라서 윤년이다. 1900년은 100의 배수이고 400의 배수는 아니기 때문에 윤년이 아니다. 하지만, 2000년은 400의 배수이기 때문에 윤년이다.
'''
x = int(input())
# 間違った1 (1をinputしたら1が出る)
... |
554a52085f23b566356105f59f89abad914e05a1 | YOON93KYS/python_renshu | /basic/7-2-1/main5.py | 531 | 3.53125 | 4 | '''
5)4)のデータを別名でcsvファイルとして書き出す
'''
import pandas as pd
adult = pd.read_csv('adult.csv')
# 方法1 データフレームの書き方が一般的ではない
a = adult.gender == 'Female'
a_1 = adult.age >= 30
a_2 = adult.age < 40
a_3 = adult.income == '>50K'
adult[a & a_1 & a_2 & a_3].to_csv('test.csv')
# 方法2 可読性良い
adult[
(adult['gender'] == 'Female') &
... |
da38f614d96388d725334d29093cfd66c1fdbc81 | JuanZapa7a/OpenCV-python | /imagepyr.py | 606 | 3.5625 | 4 | import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('fruits.jpg')
print " Zoom In-Out demo "
print " Press u to zoom "
print " Press d to zoom "
print " Press esc to exit "
# img = cv2.imread('home.jpg')
while(1):
h,w = img.shape[:2]
cv2.imshow('image',img)
k = cv2.waitK... |
dd14f3d6a50fe159ab8f2e443c88d302d149d653 | bxclib2/jianzhi-offer | /searchArray.py | 350 | 3.609375 | 4 | #array = [[1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6,7]]
def searchArray(a,key):
M = len(a)
N = len(a[0])
m = 0
n = N - 1
while m<M and n>=0:
temp = a[m][n]
if key == temp:
return m,n
if key < temp:
n = n - 1
if key > temp:
... |
810dbcc76f60cff93167d418caabe576a0bd93da | bxclib2/jianzhi-offer | /ConstructBinaryTreefromPreorderAndInorderTraversal.py | 890 | 3.78125 | 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 buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if preorder == []:
return None
root... |
a1c02f9194e9b317e4f149c6d0b4362f30feb6cf | bxclib2/jianzhi-offer | /levelOrder.py | 919 | 3.734375 | 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 levelOrder(self, root: TreeNode) -> List[List[int]]:
if root is None:
return []
res = []
... |
a2ad7e2003ab4401b8b1a66b9ae04853ea0d033e | salekinsirajus/maze_search | /tmp2.py | 893 | 3.546875 | 4 | def heuristic(a, b):
(x1, y1) = a
(x2, y2) = b
return abs(x1 - x2) + abs(y1 - y2)
def a_star_search(graph, start, goal):
explore_next = PriorityQueue()
explore_next.put(start, 0)
predecessors = {}
visited_w_cost = {}
predecessors[start] = None
visited_w_cost[start] = 0
whil... |
a1a60bf7e442551e02d36810dfae489fd77293ee | kannor/angry_search | /practise Unit2/if_statements.py | 660 | 3.625 | 4 | import re
def is_friend(name):
name1= name.lower()
if name1[0] == 'd':
return True
if name1[0] == 'n' :
return True
return False
def biggests(a,b,c):
if a>b>c:
print a
else:
if a<b<c:
print c
elif b>a or c:
print b
else : print 'empty'
def bigger(a,b):
if a>b:
retu... |
1f82a8e40f093a47ea219755b638b24a501c58b8 | kannor/angry_search | /prac Unit3/hash_functions.py | 326 | 3.5 | 4 | def bad_hash_function(keyword, buckets):
return ord(keyword[0])%buckets
def test_hash_function(func, keys , size):
results = [0] * size
keys_used = []
for w in keys:
if w not in keys_used:
hv = func(w , size)
results[hv] += 1
keys_used.append(w)
return re... |
2a4389fea2069a9a4fbe786a9069414553ab75a6 | jahnavi-karanam/Python | /task1.py | 2,193 | 4.34375 | 4 | #1. Create three variables in a single line and assign values to them in such a manner that each one of them belongs to a different data type.
x = 4
y = 234.345
z = "Test_string"
print("The variables are:", x, y, z)
#2. Create a variable of type complex and swap it with another variable of type integer.
x = 7... |
101c42d572346bf333c863ba3052cf26a511b367 | Bibjim/PAPY_BOT_P7 | /pbapp/API_wiki/wiki.py | 1,947 | 3.75 | 4 | # -*- coding: utf-8 -*-
import requests
class Wiki:
"""
Method for finding an article on the Wikipedia API with the GPS data returned by the Google API according to the
user request
Input parameter to search for the page according to user request: 'Lat' and 'lng'
Return: the page id according... |
98028e49386f59db89bc3d47ce8dff50942960c4 | Ubagaly/lessons_py | /Lessons 1/zadacha6.py | 338 | 3.859375 | 4 | # Решение 6 задания
a=float(input("Спортсмен пробегает за день:"))
b=float(input("Спортсмену необходимо пробежать:"))
den=1
while a < b:
a=float(a+a*10/100)
den=den+1
else:
print(f"Спортсмен пробежал больше {b}км на {den} день") |
4975a7ae611b34358483fe034673ee608504b27e | Ubagaly/lessons_py | /Lessons 1/zadacha3.py | 276 | 3.734375 | 4 | # Решение 3 задания
a=int(input("Задайте любое число :"))
c=int(input("Задайте max колличество n :"))
n=0
sum=0
st=1
while st <= c:
n=int(f"{n}{a}")
sum=sum+n
st=st+1
else:
print(f"Сумма равна: {sum}") |
6d35bc336c78c87090dc5a748e5b9abb911bf941 | Ubagaly/lessons_py | /Lessons6/zadacha5.py | 1,431 | 4.0625 | 4 | #Реализовать класс Stationery (канцелярская принадлежность). Определить в нем атрибут
# title (название) и метод draw (отрисовка). Метод выводит сообщение “Запуск отрисовки.”
# Создать три дочерних класса Pen (ручка), Pencil (карандаш), Handle (маркер).
# В каждом из классов реализовать переопределение метода draw. Для... |
9e6a12dadb01a672a4347a7b9e41559e8f2b0922 | eranirudhkumar/CustomRandomNumber | /generate_random_number.py | 1,422 | 4.03125 | 4 | import time
class GenerateRandomNumber:
# set range in constructor #
def __init__(self, start=0, stop=0):
self.start = start
self.stop = stop
self.seed = start
# gernerate random number function definition #
def nextNumber(self):
start = self.start
stop ... |
1c8e3d8d83bc0af89c33b430bce1c659e976ffa1 | kas/ctci | /02-linked-lists/04.py | 956 | 3.890625 | 4 | # write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x
from doublylinkedlist import DoublyLinkedList
def partition(x):
found = False
itr_nd = doubly.head
c = 0
while itr_nd:
if not found:
if itr_nd.... |
f3ba3feeba5d8d2a9e091d4c8b41f27e250a2f1b | kas/ctci | /01-arrays-and-strings/hashtable.py | 1,581 | 3.875 | 4 | # implemented with help from https://github.com/calebmadrigal/algorithms-in-python/blob/master/hashtable.py
class HashTable:
'''Hash table which uses strings as keys'''
def __init__(self, capacity=1000):
'''Initialize the HashTable'''
self.table = []
for i in range(0, capacity):
... |
bacde8af595238ef9d406fec320903d3c3ae27b4 | kas/ctci | /01-arrays-and-strings/07.py | 1,331 | 3.796875 | 4 | # write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0
from random import randint
ROWS = 5
COLUMNS = 6
def print_m(m): # from 1-06
for y in range(0, ROWS):
for x in range(0, COLUMNS):
print('{}\t'.format(m[y][x]), end='')
print()
... |
6b2e42521e3f685a1a430e63b3b8816686a5b4b3 | AlexisKauil/Ejercicios_python | /elefantes.py | 376 | 3.84375 | 4 |
print ("Este programa fue realizado por alexis")
elefantes =int (input("Cuatos elefantes"))
cant_elefantes=0
while elefantes > cant_elefantes:
cant_elefantes=cant_elefantes + 1
if cant_elefantes == 1:
print ("1 elefante se columpiaba sobre una tela de la araña")
else:
print (cant_elefante,... |
95a629e3e4f5d0bb07e1e6657b932b3d82eee9a3 | gleich/OpenCV_Tutorials | /Old-Documentation-Lessons/Core_Operations/Basic_Operations/MOD_Pixel_Values.py | 802 | 3.75 | 4 | """
Created on Thur Feb 14 4:43:33PM 2019
@author: Matt-Gleich
This file demonstrates how to Access and Modify Pixel Values
Lesson on actual website:
"""
import numpy as np
import cv2
photo_path = '/Users/matthewgleich/Desktop/First/CV2_Test_Images/Solid_Red_Sized__25214.1507754519.jpg'
img = cv2.imread(photo_path)... |
2819a1365a8b02f224e42d930ab6828a6c394458 | cdamiansiesquen/Trabajo05Damian.Carrillo. | /Boleta 4.py | 664 | 3.859375 | 4 | # Boleta 4
#INPUT
cliente=input("nombre del cliente")
precio_de_jarras_de_jugo=int(input("ingrese el precio de jarras de jugo"))
numero_jarras_jugo=int(input("ingrese el numero jarras jugo"))
# Processing
total=(precio_de_jarras_de_jugo*numero_jarras_jugo)
#OUPUT
print("#####################################")
... |
cb839f7d1d74170f753ff8922aa55792f1b9bf1e | cdamiansiesquen/Trabajo05Damian.Carrillo. | /Boleta 2.py | 598 | 3.5 | 4 | # Boleta 2
#INPUT
cliente=input("nombre del cliente")
precio_de_laptop=int(input("ingrese el precio de laptop"))
precio_de_mouse=int(input("ingrese el precio de mouse"))
# Processing
total=(precio_de_laptop+precio_de_mouse)
#OUPUT
print("#####################################")
print("# Ventas JUANITO ... |
eb924c08d5653812eb48808c7c65b69035920cbb | glee1228/TIL | /PostechAI/basic_python/python_class1.py | 1,358 | 3.921875 | 4 | class Account:
# 계좌의 속성(Attr)
number = '0000-000-000000'
balance = 0
rate = 1.0
# def __init__(self): Default 생성자
def __init__(self, num='OOO-OOO-OOOOO', amnt=0, rate=1.0):
self.number = num
self.balance = amnt
self.rate = rate
# 계좌의 기능(Method)
def deposit(self, ... |
3fc0d7867a85607f754327cc914f3ffa22844442 | glee1228/TIL | /test/machinelearning.py | 590 | 3.578125 | 4 | from sklearn import linear_model
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from sklearn import datasets
boston_house_prices = datasets.load_boston()
data_frame = pd.DataFrame(boston_house_prices.data)
data_frame.columns = boston_house_prices.feature_names
data_fr... |
04fb940460478c006d65ca2c739402a2a29b7a25 | joelcede/programming_languages | /python3/ahorcado.py | 1,561 | 3.71875 | 4 | import random
"""jUEGO DEL AHORCADO """
img = ['''
+---+
| |
O |
|
|
|
=========''','''
+---+
| |
O |
| |
|
|
=========''','''
+---+
| |
O |
/| |
|
|
=========''','''
+---+
| |
O |
/|\ |
|
... |
a4bb539dcdf7c650f8b776ad99de651dcd7f5d65 | ashleynkomo/Lists | /square.py | 176 | 3.984375 | 4 | def squared_numbers():
numbers = [x**2 for x in range(51)]
print('\n'.join('{}: {}'.format(*k) for k in enumerate(numbers)))
#main program
squared_numbers()
|
74596136746175a1e4d08a60a3e524ed0b5b987e | rafik21999/rafik21999 | /character or not.py | 99 | 4.125 | 4 | r=input("value is:")
if((r>='a')or(r>='A')):
print('character')
else:
print('not')
|
e92b587b3314c5c7702eff6ceb99e31c517bc2f9 | mandamg/Exercicios-de-Python-do-Curso-em-Video | /Mundo 1/Aula 7/EX012-Calculando Desconto.py | 117 | 3.625 | 4 | a = float(input('digite o valor do produto'))
b = a - (a*0.05)
print(f'o valor do produto com 5% de desconto é {b}') |
08cc3b5a229bb9b28bda4b234f9d12fbbab17784 | mandamg/Exercicios-de-Python-do-Curso-em-Video | /Mundo 1/Aula 7/EX008-Conversor De Medidas.py | 243 | 3.609375 | 4 | md = int(input('diga a medida em metros'))
dm = md * 10
cm = md * 100
mm = md * 1000
dam = md * 0.1
hm = md * 0.01
km = md * 0.001
print(f' {md}m em: \ndm é {dm} \ncm é {cm} \nem mm é {mm} \nem dam é {dam} \nem hm é {hm} \nem km é {km}') |
049606ba0c1b3c2ad5133741c8e63115bed5bd15 | mandamg/Exercicios-de-Python-do-Curso-em-Video | /Mundo 2/aula14/desafio3.py | 888 | 3.859375 | 4 | n1 = int(input('Digite um valor:'))
n2 = int(input('Digite um valor:'))
op = 0
maior = 0
while op != 5:
op = int(input('Qual operação deseja realizar?\n[1] soma\n[2] multiplicar\n[3] maior\n[4] novos numeros\n[5] fechar programa\n'))
print('=' * 25)
if op != 5:
if op == 1:
print(f'o resu... |
3b569e24e3d11ae9481b387388089d4edbe79ad6 | mandamg/Exercicios-de-Python-do-Curso-em-Video | /Mundo 2/aula15/desafio61.py | 519 | 3.671875 | 4 | letra = 'BANCO POBRE'
print('-'*30)
print(f'{letra:-^30}')
print('-'*30)
s = int(input('Qual valor deseja sacar? '))
tudo = s
nota = 50
total= 0
while True:
if tudo >= nota:
tudo -= nota
total += 1
else:
if total > 0:
print(f'Você receberá {total} notas de R$ {nota}')
... |
a94577f5910b269a681ccdea41e492366aad09da | mandamg/Exercicios-de-Python-do-Curso-em-Video | /Mundo 2/aula14/desafio2.py | 370 | 4.0625 | 4 | from random import randint
n = randint(0,10)
p = 0
r = -1
print('Digite o numero que eu pensei:')
while r != n:
r = int(input('Qual seu palpite?'))
p += 1
if n < r:
print('menos, tente novamente.')
if n > r:
print('mais, tente novamente.')
print(f'Você acertou eu ... |
3e9e3bb3ae0a181836bdf936406d9e896cba81ed | mandamg/Exercicios-de-Python-do-Curso-em-Video | /Mundo 2/aula14/desafio7.py | 232 | 3.671875 | 4 | fn = int(input('Até onde a sequencia deve ir: '))
t1 = 0
t2 = 1
print(f'{t1} -> ', end='')
print(f'{t2} -> ', end='')
c = 3
while c <= fn:
t3 = t1 + t2
print(f'{t3} -> ', end='')
t1=t2
t2=t3
c+=1
print(' Fim.')
|
b733522a3b2c0238b4e4724824e679f1b99262d2 | mandamg/Exercicios-de-Python-do-Curso-em-Video | /Mundo 2/aula 13/desafio8.1.py | 232 | 3.609375 | 4 | f = str(input('digite ')).strip().lower().split()
d = ''.join(f)
i = ''
for fr in range (len(d)-1,-1,-1):
i += d[fr]
if i == d:
print(f'O termo é palindromo')
else:
print('não é palindromo')
print(len(d)-1)
print(i)
|
e203e2bcacc420b12020a6f37edca483528d8232 | mandamg/Exercicios-de-Python-do-Curso-em-Video | /Mundo 2/aula14/desafio5.py | 156 | 3.75 | 4 | p1 = int(input('digite o primeiro termo:'))
r = int(input('digite a razõ da P.A'))
t = p1
cont = 1
while cont <= 10:
print(t)
t += r
cont += 1
|
ed70026a0eb17d653a065f5e0d41eaa95a515b56 | mandamg/Exercicios-de-Python-do-Curso-em-Video | /Mundo 2/Aula 12/EX037-Conversor Bin, hex, oct.py | 292 | 4.03125 | 4 | v = int(input('Digite o numero que deseja converter:'))
op = int(input('Para qual base deseja converter?\n1. Binário\n2. Hexadecimal\n3. Octal\n'))
if op == 1:
print(bin(v)[2:])
elif op == 2:
print(hex(v)[2:])
elif op == 3:
print(oct(v)[2:])
else:
print('opção inválida')
|
bf266d688d4ff0677c5afe9738149d163d6543bd | mandamg/Exercicios-de-Python-do-Curso-em-Video | /Mundo 2/Aula 12/EX041-Qual a categoria.py | 366 | 4.03125 | 4 | from datetime import date
i = int(input('Digite o ano de nascimento:'))
m = date.today().year - i
print(f'Voce tem {m}.')
if m <= 9:
print('Sua categoria é mirim')
elif m <= 14:
print('Sua categoria é infantil')
elif m <= 19:
print('sua categoria é junior')
elif m <=25:
print('Sua categoria é sênior')
e... |
939ccd67eefa1589e08c76aa550a3654143496b3 | JEpifanio90/Python-Backyard | /test.py | 381 | 3.828125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'Josefoo'
def computepay(h,r):
if h<=40:
pay=r*h
else:
pay=r*40+(r*1.5*(h-40))
return pay
try:
hrs = raw_input("Enter Hours:")
hrs=float(hrs)
rate= raw_input("Enter Rate:")
rate=float(rate)
except:
print("Write only ... |
196ba7ebf7f780da779f0ab2047ae7ed71bdff05 | dirty-cat/dirty_cat | /dirty_cat/_fast_hash.py | 3,086 | 3.921875 | 4 | """
n-gram hashing by simple dot products
The principle is as follows:
1. A string is viewed as a succession of numbers (the ASCII or UTF8
representation of its elements).
2. Each n-gram is then an n-dimensional vector of integers "g". A simple
hash function is then computed by taking the dot product wit... |
c2c4d565758c55ee6ebb7b98b14b479f1e76a490 | evro77777/python_algoritms | /binarySearch.py | 627 | 3.96875 | 4 | def left_bound(arr, key):
left = -1
right = len(arr)
while right - left > 1:
middle = (left+right)//2
if arr[middle] < key:
left = middle
else:
right = middle
return left
def right_bound(arr, key):
left = -1
right = len(arr)
while right - left... |
dc9685c9e6ca836285c7751df9dc14d2721ba60b | evro77777/python_algoritms | /ABC.py | 2,416 | 3.953125 | 4 | from abc import ABC, abstractmethod
from collections import namedtuple
Customer = namedtuple('Customer', 'name fidelity')
class LineItem:
def __init__(self, product, quantity, price):
self.product = product
self.quantity = quantity
self.price = price
def total(self):
return s... |
71b4fdf77170ff678f99407d2015ce1b7f179889 | AnasBrital98/Regression-analysis | /Polynomial_Regression_Using_Gradient_Descent.py | 4,432 | 3.9375 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_regression
def Generate_Points(start , end , nbr_points , coefficient , noise ):
#Creating X
x = np.arange(start , end , (end -start) / nbr_points)
#calculating Y
y = coefficient[0]
for i in range(1 , le... |
5b3c0c190801139b9f62f1ea58b82f6230c34b52 | MarcoRevolledo/FUND-PROGRAMA | /junio 05/p.py | 447 | 3.78125 | 4 | def op(a,b,o):
if o == 1:
return '={}'.format(a+b)
elif o == 2:
return '={}'.format(a-b)
elif o == 3:
return '={}'.format(a*b)
elif o == 4:
return '={}'.format(a/b)
elif o == 6:
exit()
print(op(int(input('Ingrese el primer numero: ')),
int(input('Ingrese el se... |
fdffd91ce58372e483e036a0530e006f9c6e35d9 | MarcoRevolledo/FUND-PROGRAMA | /Reto1.py | 1,357 | 3.921875 | 4 | '''
Autor: Marco Revolledo Jaramillo
Programa: Mision Tic 2022
Universidad: UNAB
Reto 1
¡Qué bueno! Acabas de recibir tu primer salario luego de una ardua jornada de trabajo.
Piensas por unos instantes en lo que vas hacer con el dinero que has recibido. De manera
casi inmediata, vienen a tu mente varias ideas; sin ... |
90e19e2472b5661c8f1a1adb2a3844efd5f363b1 | lgabs/lazyprogrammer-courses | /abtests/bayes/bayesian_bandits.py | 2,044 | 3.59375 | 4 | from typing import Dict, Text, Any, List
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import beta
class Bandit:
def __init__(self, p: float):
self.p = p # this is usually not know in reality!
self.a = 1
self.b = 1
def pull(self):
"""
simulares a... |
60c28aa75cece794906d2496134277dcbf030929 | miallema/ESC | /src/helpers_classification.py | 4,261 | 3.5 | 4 | from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection import SelectKBest, f_classif
import pandas as pd
import numpy as np
import torch
from torch import optim, Tensor, nn, argmax
mini_batch_size = 100
'''
This function takes t... |
9f2528d53dc46ae192bd179587bca6bca7a3def5 | ioneliabuzatu/evolving | /leetcode/pascal_triangle.py | 505 | 3.734375 | 4 | # n = 5
#
#
# def pascal(n):
# output = []
# while len(output) < n:
# output.append([])
# for l in output:
# l.append(1)
# for i in range(1, 5):
# output[i].append(sum(output[i-1]))
#
#
# return output
#
#
# print(pascal(n))
def removing(nums, val):
# try:
# ... |
17502a7bca81ea63d44465a85983b38778032d90 | ioneliabuzatu/evolving | /bio-algorithms/alignment.py | 2,321 | 3.5625 | 4 | import numpy as np
from editdistance import edit_distance
class Align:
"""
Given two sequences align each letter to a letter or a gap
"""
def __init__(self, string1, string2):
self.x = string1
self.y = string2
self.matrix = edit_distance(self.x, self.y)
self.path = []... |
6e25735a496ab931b9f8ff1088c6addfba9898c5 | ioneliabuzatu/evolving | /rosalind/knuth_all_overlapps.py | 2,074 | 3.53125 | 4 | class MATCHES():
"""
Finds all overlapps of the pattern in the text using knuth-morris-pratt algorithm
"""
def __init__(self, pattern, text):
self.len_pattern = len(pattern)
self.indices = []
self.pi_func = [0 for _ in range(self.len_pattern)] # initialize to 0
self.com... |
a0495b25a4af1fc9f249f40daf7d9db7ee1531b5 | ioneliabuzatu/evolving | /leetcode/bitsDP.py | 426 | 3.734375 | 4 | def bin(n):
if n > 1:
bin(n // 2)
print(n % 2, end="")
def dpBits(n):
out = []
for number in range(n+1):
count1 = 0
while number >= 1:
bit = number % 2
if bit == 1: count1 += 1
number = number // 2
if count1: out.append(count1)
... |
4eeb5466465f384fa5ab16b4efc6bd93354a621c | ioneliabuzatu/evolving | /leetcode/dynamicProg.py | 1,019 | 3.71875 | 4 | # name = input() # Reading input from STDIN
# print('Hi, %s.' % name)
#
# output = []
# for number in range(int(name)):
# #print("the number is: " + input())
# # for i in range(1, int(input())):
# # p = [i]
# # n = int(input())
# factorial = 1
# for n in range(1, int(input()... |
ef1e8c0349bd85b66dacc59f92e181c61d616678 | TorresJoe---Soturnt/lab10 | /70-100pt.py | 1,434 | 4.40625 | 4 | ##########################################
# #
# Draw a house! #
# #
##########################################
# Use create_line(), create_rectangle() and create_oval() to make a
# drawing of a house using the tKin... |
284dde4d5199e50921d56b9e1362ffec03c3ee33 | geodimitrov/Python-OOP-SoftUni | /Iterators-&-Generators/Exercises/02. dictionary_iterator.py | 498 | 3.78125 | 4 | class dictionary_iter:
def __init__(self, dict):
self.dict = dict
self.keys = [key for key in self.dict]
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.keys):
raise StopIteration
key = self.keys[self.... |
1435f35432167ebb471c42cdbbf464bc98ae50c2 | geodimitrov/Python-OOP-SoftUni | /Decorators/Lab/02. vowel_filter.py | 425 | 3.671875 | 4 | from functools import wraps
def vowel_filter(func):
VOWELS = ["a", "A", "e", "E", "i", "I", "o", "O", "u", "U", "y", "Y"]
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return [char for char in result if char in VOWELS]
return wrapper
@vowel_filter
def get... |
436590b13b31ab891aa97f5892afe68136d54f27 | geodimitrov/Python-OOP-SoftUni | /Testing/Lab/Tests/01. test_worker.py | 1,946 | 4.21875 | 4 | import unittest
from worker import Worker
class WorkerTests(unittest.TestCase):
name = "Gosho"
salary = 1000
energy = 5
def setUp(self):
self.worker = Worker(self.name, self.salary, self.energy)
"""Test if the Worker is initialized with correct name, salary and energy"""
def test_work... |
76121c93c16c534ca87264c07beac7e853cf9a5c | rbabaci1/CS-Module-Hash-Tables | /applications/histo/histo.py | 514 | 3.71875 | 4 | import sys
sys.path.append("../word_count")
from word_count import word_count
def draw_histogram(file_name):
with open(file_name) as f:
words = f.read()
words = word_count(words)
sorted_words = sorted(words.items(), key=lambda x: (-x[1], x[0]))
longest_word = max(len(w) for w in words)
f... |
36d5b324e6b4c779717d63165154f269f96a9804 | bradyrcotton/Rock_Paper_Scisssors_Lizard_Spock | /ai.py | 1,152 | 3.5 | 4 | from player import Player
from gesture import Gesture
import random
class AI(Player):
def __init__(self):
super().__init__()
def pvp(self):
print("Please enter the number of your choice from the gestures below")
print(Gesture().gestures)
self.choice_1 = int(input("Player On... |
4272b616d8b9aa8090939f7ad0528310c2b88434 | tine0tine/phiriya-2235-lab2 | /phiriya-2235-lab3/lab3 p3.py | 695 | 4.25 | 4 | # Phiriya Trakoolwang 633040223-5
"""
Write a program to check whether a character is a vowel or not and if it is,
then convert that character to an uppercase letter and display those uppercase vowels.
Note: use for loop, not list comprehension
"""
vowels = ['A', 'E', 'I', 'O', 'U']
vowels_list = []
input_string = inp... |
64b9782488280110e1a96e98acf843d1345d31c8 | tine0tine/phiriya-2235-lab2 | /lab2 p4.py | 293 | 3.953125 | 4 | """
Phiriya Trakoolwang, 633040223-5
Lab 2 Problem 4
"""
str_intput = str(input("Enter string input: "))
vowels = "AEIOUaeiou"
def check_vowels(string, vowels):
result = [each for each in string if each in vowels]
print(f"Vowels in {str_intput} are {result}")
check_vowels(str_intput, vowels)
|
e3c9d845fc106ef0a25a75cd4a90d314d5215ff9 | manoflogan/goodrx | /superstack.py | 552 | 4.0625 | 4 | """Implements a super stack"""
class SuperStack(object):
def __init__(self):
self.stack = list()
def push(self, k: int) -> None:
"""Inserts entry to the list."""
self.stack.append(k)
def pop(self) -> int:
"""Pops the top element from the list"""
return self.stack... |
df2668cb06c4eb90418f64110c1f167d5e1822e1 | tkiley1/Labs-to-Py | /Lab8/udict.py | 2,011 | 3.734375 | 4 | from dictnode import *
import copy
# This udict class is our own personal 'associatave array' or dictionary that autobalances into a max heap
# this improves the search time of our game when trying to find the largest bucket of strings.
class udict:
# Initialization function - all we need is a list that holds our ... |
985b57efcf73d698d0d748637da343fc75fb473d | tkiley1/Labs-to-Py | /Lab3/unit.py | 3,046 | 3.921875 | 4 | from string import *
# Unit testing framework for hangman project
# each function should run tests with intuitive output, and printing ok for passed and
# Failed for failed tests. Each function should return 0 if test was passed, and 1 if there
# were one or more errors.
def string_inst_test():
errors = 0
... |
4797f8965fc6cfe64401308a55cebcdb81ee41e6 | bustin1/Math | /graphs/experiment.py | 250 | 3.671875 | 4 | from matplotlib import pyplot as plt
import numpy as np
data = np.linspace(0, 2*np.pi)
print(data)
''' use of context manager to draw dark background'''
with plt.style.context('dark_background'):
plt.plot(data, np.sin(data), 'r-o')
plt.show() |
df8020193ff8ce780c7cc9dfd5bbbfcb281acf4a | wattsjon2/HW-10-18 | /Week 2 Day 1 HW.py | 925 | 3.984375 | 4 | def cubes_under1000():
num = 1
while num*num*num <= 1000:
print(num*num*num)
num += 1
cubes_under1000()
def age_type():
age_input = int(input('What is your age?'))
if age_input < 18:
print("kids")
elif age_input > 65:
print("seniors")
else:
print("ad... |
77e6ba2c813e1fcdce6fb140af7833a13c5bccbb | Hahany/Python | /class.py | 1,011 | 3.890625 | 4 | import math
class triangle():
#用于计算三角形边长、周长以及面积
def __init__(self,p0,p1,p2):
self.p0 = p0
self.p1 = p1
self.p2 = p2
def lenth(self):
l0 = math.sqrt ((p1[0]-p2[0])**2+(p1[1]-p2[1])**2)
l1 = math.sqrt ((p0[0]-p2[0])**2+(p0[1]-p2[1])**2)
l2 = math.sqrt (... |
d00d49d82fb7a2958099e40dd9d1c27cb6f11382 | CodeUnique90/Pattern-Programming | /pattern4.py | 347 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 19 14:51:26 2021
@author: Lenovo
"""
for row in range (6):
for col in range (7):
if (row == 0 and col%3 != 0) or (row == 1 and col%3 == 0) or (row - col ==2) or (row + col == 8):
print("*" , end="")
else:
print(end=... |
1ee9ff4382658b8f3aa8089199f59cbef6b0fbfd | CodeUnique90/Pattern-Programming | /pattern30.py | 330 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 8 02:23:00 2021
@author: Lenovo
"""
for row in range(5):
for col in range(5):
if (col==2 and row>1) or (row==col and col<2) or (row==0 and col==4) or (row==1 and col==3):
print("*" , end="")
else:
print(end=" ")
... |
ee7fe7d5c87d7f2d2b95c01692e031ee0534b30c | FrostMegaByte/random-python-projects | /scraping.py | 1,302 | 3.515625 | 4 | from bs4 import BeautifulSoup
import requests
# import numpy as np
# import pandas as pd
def main():
team = input("Team informatie van: ")
webscrape(team)
def webscrape(team):
URL = "http://kvtempo.nl/competitie/teams/tempo-" + team
headers = {'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) A... |
4a0597a4d5d3cba927ac1315de718dc82463688e | afraj18/DSATutCode | /custom_LList.py | 659 | 3.921875 | 4 | class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Linked:
def __init__(self):
self.head = None
def show(self):
node = self.head
while node is not None:
print(node.data)
node = node.next
def add(self, new... |
14d21bb57d0f9a2cf68d809dd4818029be65525b | XandLin/curso-do-zero-ao-python-kenzie | /aulas/kenzie_zero_ao_python.py | 1,044 | 3.953125 | 4 | '''exemplo1'''
print('Olá Mundo')
print(5 + 10)
print('5'+'10')
'''#exemplo2'''
print('Olá Mundo', 10)
'''#exemplo3'''
nome = 'Xand_LIn'
idade = 20
peso = 55
print('Nome:', nome, '\nidade:', idade, '\nPeso:', peso)
'''#exemplo4'''
nome1 = input('Qual é o seu nome?: ')
idade1 = input('Sua idade?: ')
peso1 = input('Qual ... |
3c02d1a3175ea405a8696699a130ec351bd3f844 | vaquarkhan/MachineLearningA2Z | /Regression/SimpleLinearRegression.py | 847 | 3.90625 | 4 | # -*- coding: utf-8 -*-
# read dataset
import pandas as pd
dataset = pd.read_csv('Salary_Data.csv')
x = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
# split dataset into train and test
from sklearn.cross_validation import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_siz... |
4784f3ba95c14689ffb52f002008f94dda8dae88 | ankithasalian9/Python_task1 | /taskfinal1.py | 428 | 3.625 | 4 | import numpy as np
import pandas as pd
df = pd.read_csv('csv_1.csv')
income_total=df['Income'].sum()
expense_total=df['Expense'].sum()
print('sum of income ' +str(income_total))
print('sum of expenses ' +str(expense_total))
#difference
difference=(income_total)-(expense_total)
print(difference)
df1=df.drop(["Income",... |
d60c665aeeacaf1b394aab95f9304ad87108edd8 | nangongyiling/py-test | /venv/t2.py | 1,307 | 3.890625 | 4 | '''
count=0
while count<=5:
count+=1
if count == 10:
break
print('loop',count)
else:
print("正常循环完毕")
'''
#and or not
#优先级 ()>not>and>or
#print(2>1 and 1<4) #True
#print(2>1 and 1>4) #False
#print(2>1 and 5>4 or 4<3 and 9<6 or 1>4 and 3>2) #直接按照优先级来
'''
print(bool(2))
print(bool(0))
print(bool... |
8b01cf7d9d64c293be9356feabd95099d9015b32 | B3W/Endpoints | /src/shared/synceddict.py | 1,159 | 3.515625 | 4 | '''
'''
import collections
import threading
class SyncedDict(collections.MutableMapping):
'''
Class representing simple, synchronized dictionary
'''
def __init__(self, *args, **kwargs):
self._map = dict() # Structure for storing data
self.update(dict(*args, **kwargs))
... |
2167664c4657b2187addb77d52f7de0eaa1be4c3 | lxj0276/Quant-Util | /quantlab/backtest/TradeOutput.py | 2,800 | 3.65625 | 4 |
#回测交易订单
class TradeOutput:
#手续费买入卖出都需要交
#印花税仅卖出需要交
#默认两者为0
#输入为 当前订单,真实交易时间,真实平均股票交易价格,真实交易数量,手续费,印花税仅当卖出时有效
def __init__(self, order, real_time, real_stock_price, real_amounts, earnorloss,poundage, stamp_cost=0):
self.code = order.code # 股票代码
self.date = order.date # '201706120... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.