blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
4673124923469d303f5a9da199d380e00408e78a | kevharvell/Algorithms | /hw2/merge4Time.py | 3,818 | 4.0625 | 4 | #!/usr/bin/python3
'''
Name: Kevin Harvell
Date: 1/17/19
About: This program has a function called mergeSort that recursively splits
an array in quarters until 1 element in each array. Then builds sorted arrays
by combining the smaller arrays and comparing the values.
It takes an input file and sorts using the mergeSo... |
9cd59e84ae4ca8e11447b26699fce10162107168 | GeorgeBatch/introduction_to_ml_with_python | /scripts/ch7_TfidfVectorizer_example.py | 1,675 | 3.609375 | 4 | import numpy as np
import pandas as pd
# Example from:
# https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
corpus = [
'This is the first document.',
'This document is the second d... |
da64c045ff4ca5b63d81d2099e52a31dbeaebdd4 | GeorgeBatch/introduction_to_ml_with_python | /scripts/ch2_lr_regr_wave.py | 1,386 | 4 | 4 | """
This program shows example of linear regression algorithm working with "wave" data set.
"""
# ----------------------------------------------------------------------------------------------
# Importing packages.
# ----------------------------------------------------------------... |
35795b0e5e856de3013259d6985d443d41598b00 | Potter-Gryffindor/MisionTIC | /Ciclo1/sesion7.py | 1,566 | 3.875 | 4 | """
Mientras Que
Como vimos anteriormente, en Python, el ciclo Mientras Que se maneja con "while".
Por ejemplo:
"""
def ejemplo1():
i = 1
while i < 6:
print(i)
i += 1
ejemplo1()
def actividad1():
print("actividad1")
# Continuemos integrando los conceptos que hemos v... |
f4e77902431f0917237474a3c75dbd29d05f9522 | yenlt6/learningpython | /python4testers_student/code_along/oop/solutions/bank_account.py | 597 | 3.671875 | 4 | class BankAccount:
# Magic methods
def __init__(self, account_number, account_name, balance=0):
self.account_number = account_number
self.account_name = account_name
self.balance = balance
def display(self):
print(self.account_number, self.account_name, self.balance, "₫")
... |
6dbb1bcdbcccf4386a9ea303a96c1d8cd2afff24 | yenlt6/learningpython | /day_8_temp/docfiledic.py | 1,694 | 3.75 | 4 |
#Bài 3: Bài tập tổng hợp phần Basic - Đếm từ
import sys
# Đếm từ
def print_words(filename):
words_count = readfile_count_words(filename)
words_count_sorted = sorted(list(words_count), key = lambda k: k[0])
for i in words_count_sorted:
print (i, ":", words_count[i])
def print_top(filename):
w... |
2533a1f4c43c56997592af1fab8e022dcdc32be7 | Ranjit007ai/InterviewBit-String | /string_based_problems/power_of_2/solution.py | 251 | 4.03125 | 4 | def power_of_2(A):
if int(A) <= 0:
return False
while int(A) != 2 :
if int(A) % 2 != 0 :
return False
A = int(A) // 2
return True
# test case
number = '8'
ans = power_of_2(number)
print(ans) |
6379ec3c54beddf765f8736d50c238fdba4c8260 | 0x0all/coding-challenge-practices | /python-good-questions/node_reverse.py | 549 | 3.96875 | 4 | def Reverse(head):
prev_node = None
next_node = head
while next_node:
copy_prev_node = prev_node
copy_next_next_node = next_node.next
prev_node = next_node
next_node.next = copy_prev_node
next_node = copy_next_next_node
head = prev_node
ret... |
b2b10777497bf79f6353bd04ac19ddb0d69fc281 | 0x0all/coding-challenge-practices | /python-good-questions/reverse_vowels.py | 542 | 4.28125 | 4 | """
The Problem:
Write a function to reverse the vowels in a given string
Example:
input -> output
"hello elephant" -> "halle elophent"
"abcde" -> "ebcda"
"abc" -> "abc"
"""
def reverse_vowels(s):
vowels = 'aeiou'
res = list(s)
pos = [index for index, char in enumerate(s) if char in vowels]
... |
15f49d86db8c7853d387498df68727565d4dab33 | scravy/abnf | /src/abnf/grammars/misc.py | 676 | 3.515625 | 4 | """Miscellaneous functions."""
def load_grammar_rules(imported_rules=None):
"""A decorator that loads grammar rules following class declaration. The code assumes
that cls is a Rule subclass with a grammar attribute.
The imported_rules parameter allows one to import rules from other modules. For examples,... |
1756c5f1e81aaa004f29df39d11dbd64be19af4a | Lucas6675/Ejercicios-basicos | /ejercicio 4.py | 252 | 4.09375 | 4 | vocal=("a","e","i","o","u")
consonante=("b","c","d","f","g","h","j","k","l","m","n","p","q","p","r","s","t","v","w","x","y","z")
letra=input("ingrese letra:")
if letra in vocal:
print(letra,"es una vocal")
else:
print(letra,"es una consonante") |
d8b0261cbd5a4534ef7012794164d4c063cc2ecc | Shilla-crypto/Simple-BMI-calculator | /app.py | 1,638 | 4.28125 | 4 | import datetime
print('Hello world!')
print('*' * 25)
print("Python-3.7.3")
print("*" * 25)
def print_python():
print("__")
print("L"), print("__")
print("I"), print("__")
print("N"), print("__")
print("U"), print("__")
print("X"), print("__")
print_python()
now = datetime.datetime.now()
... |
5dbf8dc8b3b4cce162a4b2c040381404e272f6d7 | ccmissola/script-cambio-moedas | /consulta.py | 1,292 | 3.9375 | 4 | '''
Utilizamos a função get do requests para acessar o servidor da API onde se encontra as informações das moedas.
Ao acessar o servidor, a variável status_code, do requests, é preenchida com a resposta HTTP do servidor. Ea variável content, também do requests,
é preenchida com o conteúdo da API (JSON)
Utilizamos a bib... |
118bca5b7210b3c5038db1cd44d7c205ce6e8690 | HMion/PYTHON_UERJ_2019.1 | /Aula_5/aula05ex02.py | 230 | 3.890625 | 4 | def Somar(lista):
soma=0
for elementos in lista:
soma += elementos
return(soma)
##############################################################################
print(Somar([2, 4, 5, 6, 7, 10, 13, 15, 18])) |
098d4c6335b4a5a27f33711735b7dc39aff1d8bb | HMion/PYTHON_UERJ_2019.1 | /Aula_5/aula05ex03.py | 220 | 3.71875 | 4 | def Multiplicar(lista):
x=1
for elementos in lista:
x *= elementos
return(x)
##############################################################################
print(Multiplicar([2, 4, 5, 6, 10])) |
9c301e5127f198c6d5854d5c4be61c1e11799f85 | vasanth9/10weeksofcp | /numpy/index.py | 2,435 | 3.78125 | 4 | import numpy as np
print(np.__version__)
arr=np.array([1,2,3,4,5]) #list
print(arr)
print(type(arr))
arr=np.array((1,2,3,4,5)) #tuple
print(arr)
"""
1.19.1
[1 2 3 4 5]
<class 'numpy.ndarray'>
[1 2 3 4 5]
"""
#dimensions
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[... |
6736443ed68910ee2e4d2d665da47667024e19c3 | vasanth9/10weeksofcp | /basics/classesandobjects.py | 1,491 | 4.21875 | 4 | #classes and objects
"""
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
"""
class myclass:
x=5
p1=myclass()
print(p1.x)
"""
All classes have a function cal... |
ff2920c2bfa35739fea71e45c5a8525c651231c1 | linggom/postfix_binarytree | /Node.py | 582 | 3.609375 | 4 | class Node(object):
def __init__(self, function=None, args=None):
self.left = None
self.right = None
self.function = function
self.args = args
def add(self, new_node):
if self.left is None:
self.left = new_node
elif self.right is None:
sel... |
9bce9576b576d199e1bfe5edb2471b6e1bc62d28 | 2Meme2code/python_practice | /find.py | 453 | 3.84375 | 4 | def is_in(list1, list2, list3):
for i in list1:
if i in list2 and i in list3:
print(i)
return True
return False
def switch(num1, num2):
num3=num1
num1=num2
num2=num3
return[num1, num3]
def swap_array0(a):
n=len(a)
l=0
r=n-1
while l < r:
t = a[l]
a[l]=a[r]
a[r]=... |
a8a8b028377b298c002fb2695de0250449407a41 | olekhov/LuDis | /sources/quitter.py | 640 | 3.5 | 4 | #######################################
# Module for closing the program. #
# Author: Jarmo Luomala (2013) #
#######################################
from Tkinter import *
from tkMessageBox import askquestion
class Quitter(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
... |
8b9cf14cb13a9434fc7ab243bfdbd22cafcfb4e1 | manji369/HackerRank | /Codes/Even_Tree.py | 934 | 3.859375 | 4 | #https://www.hackerrank.com/challenges/even-tree
def find_num(dict,child):
children = dict[child][:]
num = len(children)
while children:
next_child = children.pop()
num += find_num(dict,next_child)
return num
N,M = map(int,raw_input().strip().split())
dict = {}
for i in xrange(1,N+1):
... |
8c2b75705e1b02a7f0ab3f106535188a28cf1b77 | ALbaron-Awad/tic_tac_toe | /x_o_Project.py | 4,992 | 3.921875 | 4 | import random
import time
global board
# For code style i use PEP-8
board = [' ' for x in range(10)]
def plog_in(input, spot):
""" To insert the letter
in the board
"""
board[spot] = input
def free_space(spot):
# To check if the position
return board[spot] == ' '
def play_again():
a... |
2c78113698d8bc1558da9a734921a1c6d12fa543 | prashant887/concourse-pr-event | /src/Calculator.py | 291 | 3.65625 | 4 | class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def sum(self):
return self.a + self.b
def diff(self):
return self.a - self.b
if __name__ == '__main__':
calc = Calculator(8, 5)
print(calc.sum())
print(calc.diff())
|
2d9bde38df14d957c5f5af02d71668b744768057 | catb406/pythonProject | /inp_sort.py | 964 | 3.625 | 4 | def merge_sort(arr, invcount):
a=[]
if len(arr)<2:
return arr, invcount
# elif len(arr)==2:
# if arr[0]<arr[1]:
# return arr, invcount
# else:
# arr[0], arr[1]=arr[1], arr[0]
# invcount+=1
# return arr, invcount
left, invcount_l=mer... |
7008e69c187d7831bfae3ac2860eddfbdc63b95f | ibendr/ibendr.github.io | /xwd/stevelt/source/xwd2html-slt.py | 1,869 | 3.5 | 4 | #!/usr/bin/python
"""
Simple program to create html xwd files from 'draft'
text xwd files - where each clue is in format:
<n>. <SOLUTION> (<LENGTH>) <CLUE>
and of course we want it as:
<n>. <CLUE> (<LENGTH>)
We also move the solution (grid) to the end,
and add 3 intervening lines of html.
WARNING: This is a crude ... |
335a6bad631ed5d2f9a284858a7d09df60d045cb | Luis587/python | /Taller #6.py | 1,158 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 5 11:43:42 2020
@author: luisa
"""
def isYearLeap(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
resp = 'True'
else:
resp = 'False'
else:
resp = 'T... |
3763e331849fea23906ca632dede9ba0560a3cd1 | Luis587/python | /ejercicios con if y elif ejercicio avac completo con nombre.py | 826 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 11:20:31 2020
@author: luisa
"""
espacio = ''
nombre = input('Ingrese su nombre: '+'\n\n\t\t')
apellido = input('Ingrese su apellido: '+'\n\n\t\t')
location = input("Ingrese su Ubicacion(Pais): "+'\n\n\t\t')
age = int (input("ingrese un rango de edad de 0 h... |
1520e6992ce3562aa8d684deaf3e5dbc79e53253 | Luis587/python | /ejemplo for #2.py | 184 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 12:42:10 2020
@author: luisa
"""
print("comienzo")
for i in range(3):
print("hola ", end="")
print()
print("Final") |
5cc219d87d5d028fd7a55715ed878429fad35eef | Vijay1126/Interview-Prep | /Algoexpert/SuffixTrie.py | 777 | 3.890625 | 4 | # Do not edit the class below except for the
# populateSuffixTrieFrom and contains methods.
# Feel free to add new properties and methods
# to the class.
class SuffixTrie:
def __init__(self, string):
self.root = {}
self.endSymbol = "*"
self.populateSuffixTrieFrom(string)
def populateSuf... |
b16fb2ae4b48453b9d293c4898cbe72d9663bfdc | Vijay1126/Interview-Prep | /Algoexpert/shiftedBinarySearch.py | 428 | 3.640625 | 4 | def shiftedBinarySearch(nums, target):
left = 0
right = len(nums)-1
while left<=right:
mid = left + (right-left)//2
if nums[mid] == target:
return mid
if nums[left]<nums[mid]:
#left side is sorted
if nums[left]<=target<nums[mid]:
right = mid-1
else:
left = mid+1
else:
#right si... |
96e065f81505a0f080db286ae8cf98333b8b5015 | Vijay1126/Interview-Prep | /Tree/Complete Tree Binary Search.py | 1,393 | 3.875 | 4 | # 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 countNodes(self, root: TreeNode) -> int:
if not root:
return 0
depth = self.... |
1ffbd55e18af5ed09374ef4a7ebe7865c626cb77 | Vijay1126/Interview-Prep | /Amazon/boundaryOfBinaryTree.py | 1,316 | 3.703125 | 4 | # 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 boundaryOfBinaryTree(self, root: TreeNode) -> List[int]:
leftBoundary = []
if r... |
381dc5bb0af094eb3c29a3ca0d1f714d35d519d9 | imperialfarmer/algorithm-and-data-structure | /sorting/quickSort.py | 3,214 | 4.375 | 4 | # -*- using: utf-8 -*-
"""
The quick sort performance depends on the choice of the pivot points,
Here three choosing ways are tested
1. always using the first element of the array as the pivot element
2. always using the final element of the given array as the pivot element
3. using 'median'
"""
import numpy as np
imp... |
e7a45d724b2b6b27fac947f18af8131ef8719f39 | Sang-Yeong/Study-CodingTest | /Programmers-Level1/programmers_level1_24.py | 401 | 3.625 | 4 | # 자릿수 더하기
def solution(n):
n = str(n) # int값을 바로 list로 변환해주지 못함. 문자열로 만들어서 변환할 수 있도록 처리
num_list = list(n) # 주어진 형식
num_list = sum([int(num) for num in num_list]) # num_list에 있는 문자를 하나씩 빼서 정수형으로 바꿔주고 합 구하기
return num_list
print(solution(123)) |
3af877ae118a65ff747cb2fd8625252a743404cb | Sang-Yeong/Study-CodingTest | /Programmers-Level1/programmers_level1_25.py | 295 | 3.5 | 4 | # 자연수 뒤집어 배열로 만들기
def solution1(n):
answer = []
while n != 0:
answer.append(n % 10)
n //= 10
return answer
def solution2(n):
answer = []
answer = [int(i) for i in str(n)][::-1]
return answer
print(solution2(12345)) |
8fe505b60d856b172689501e7b637be579fe1463 | Sang-Yeong/Study-CodingTest | /Programmers-Level1/programmers_level1_16.py | 264 | 3.5 | 4 | # 서울에서 김서방 찾기
def solution(seoul):
answer = ''
for i in range(len(seoul)): # 배열을 하나씩 돌면서 'Kim' 찾기
if 'Kim' == seoul[i]:
answer += '김서방은 {}에 있다'.format(i)
return answer |
e0a1d9971de5befcdde3a8770daeace647047879 | Sang-Yeong/Study-CodingTest | /Programmers-Level1/programmers_level1_37.py | 548 | 3.6875 | 4 | # 행렬의 덧셈
def solution(arr1, arr2):
answer = [[]]
arr = [] # 출력형식 맞추기 위해
for a1, a2 in zip(arr1, arr2):
for i in range(len(arr1[0])):
arr.append(a1[i]+a2[i])
answer.append(arr)
arr= []
answer.remove(answer[0]) #answer가 [[]]로 초기화 되어있을 때, 바로 append해주면 [[], ... |
518495a5b1ce35083280171831144ae36d593a7d | Aditi-Billore/competitive_practice | /Decorator/uppercase.py | 356 | 3.625 | 4 | def split_string(function):
def wrapper():
fun = function()
return fun.split()
return wrapper
def upper_case(function):
def wrapper():
func = function()
return func.upper()
return wrapper
@split_string
@upper_case
def say_hi():
return 'Hello narnia!'
# decorate =... |
5ea0d3ddef0310eff6c976c13d1aece05affc3e6 | Aditi-Billore/competitive_practice | /LinkedList/linkedList.py | 1,586 | 4.09375 | 4 | # implementation of linked list and addition of integers in the list in reverse order
class Node:
# node structure
# int val: to give one number value
# Node next: to give next Link
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
def addEnd(self, num):
... |
d234a0cc76aac19a0621f84d03f298502d5065c4 | bhavepurva/Computer-vision | /read_images_videos.py | 967 | 3.59375 | 4 | import cv2
# to read image
img = cv2.imread("money_heist.jpg")
# actual size of image
print(img.shape) # 630,630,3 height,width,color(rgb)
# to resize the image
resized_img = cv2.resize(img, (300, 300))
#to crop images, lis takes height first then width
cropped_img=img[0:300,200:500 ]
# to display i... |
7ac7470b031f494fec28dde9251e9f3101379e04 | adambb9/snakegame | /container.py | 960 | 3.96875 | 4 | #The aim is to recreate the traditional snake game with some new features
#box drawing package
import pygame
pygame.init()
#global width and height variables
WIDTH, HEIGHT = 1300, 700
#draw a surface
SURFACE = pygame.display.set_mode((WIDTH, HEIGHT))
#global colour variables
WHITE = (255,255,255)
BLACK = (0, 0, ... |
217864f822f7436cdd60b643ec3d16a126760078 | JMitnik/uvadlc_practicals_2020 | /assignment_1/1_mlp_cnn/code/convnet_pytorch.py | 2,898 | 4.09375 | 4 | """
This module implements a Convolutional Neural Network in PyTorch.
You should fill in code into indicated sections.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.nn as nn
class ResnetBlock(nn.Module):
def __init__(self, channel_in, c... |
d99f5396d776a8da45b48d430588b0a7b05ec0b5 | MorRoman/my_repository | /Task0.py | 1,045 | 3.796875 | 4 |
import random
#Генерує ряд з 30 випадкових цілих чисел від -100 до + 100
randomlist = random.sample(range(-100, 100), 30)
print("\n")
print(randomlist)
print("\nМаксимальний елемент рядку: ", max(randomlist)) #знаходить і виводить максимальний елемент ряду
print("Порядковий номер: ", randomlist.index(max(ra... |
fdcdcbd2e5111b3d361bb2f67d4b603cb8e5a5e1 | 633-1-ALGO/introduction-python-mbaliacamara | /12.2- Exercice - Listes et Tableaux/liste2.py | 763 | 3.578125 | 4 | # Problème : Etant donné un tableau, afficher l'indice du tableau comportant la valeur la plus elevée.
# Résultat attendu : Un affichage comme ceci : "La valeur maximum est : x et elle se trouve à l'indice [ n ][ m ]
tab = [[4, 7, 3, 20, 42], [2, 4, 5, 7, 2], [23, 24, 15, 75, 23]]
maximum = 0
n = 0
m = 0
for i in r... |
6bc780d508f837ca9c0428fa160e72932b2060c8 | futurice/PythonInBrowser | /examples/session1/square.py | 837 | 4.5625 | 5 | # Let's draw a square on the canvas
import turtle
##### INFO #####
# Your goal is to make the turtle to walk a square on the
# screen. Let's go through again turtle commands.
# this line creates a turtle to screen
t = turtle.Turtle()
# this line tells that we want to see a turtle shape
t.shape("turtle")
# this lin... |
14207390dc1852453b97d8922b1f8b3607f26e64 | futurice/PythonInBrowser | /examples/session1/wall.py | 998 | 4.46875 | 4 | # Goal: help the turtle to find a hole in the wall
# We need to remember to import a turtle every time we want
# to use it.
import turtle
##### INFO #####
# The following code draws the wall and the target. You can
# look at the code but to get to the actual exercise, scroll
# down.
# Here we create a wall to the m... |
8e8a627d17d52d33de2bcdb94ea444d189e0f309 | futurice/PythonInBrowser | /examples/session3-fi/function.py | 2,651 | 3.65625 | 4 | # Funktioilla laskeminen
import turtle
t = turtle.Turtle()
##### INFO #####
# Funktioita voidaan käyttää asioiden laskentaan.
#
# Otetaan esimerkkinä ympyrän pinta-alan laskeminen.
# Saatat muistaa matematiikan tunnilta, että ympyrän
# pinta-ala lasketaan kertomalla ympyrän säde itsellään ja
# luvulla pii.
#
# Pii on... |
39b9b0351e1e196ed3321a95e12b4d954b5102d2 | futurice/PythonInBrowser | /examples/session5-fi/randomwalk.py | 2,795 | 3.703125 | 4 | # Liikuta kilpikonna esteiden ohi
##### INFO #####
import turtle
import random
# Alussa on koodia, joka alustaa esteradan. Skrollaa alas tehtäviin
# Luodaan kilpikonna ja annetaan sille nopeus ja väri
t = turtle.Turtle()
t.speed("fastest")
t.color("black")
# Lasketaan piirtoalueen koko
screen = turtle.Screen()
levey... |
5f66bea9207f8a7149844204245dc09345a636aa | futurice/PythonInBrowser | /examples/session3/function.py | 2,912 | 4.8125 | 5 | # Computing with functions
import turtle
t = turtle.Turtle()
##### INFO #####
# Fucntions can be used for computing things.
#
# As an example, let's consider computing an area of a
# circle. You may remember form a math class that the area
# of a circle is computed by multiplying the radius of the
# circle by itself ... |
4d89aef1dbf6df55171700d09c0d0f99a068790c | piotrbogdanski/predictit_disqus_scraper | /util.py | 951 | 3.625 | 4 | import time
def retry(tries: int = 4, delay: int = 3, backoff: int = 1):
"""Retry calling the decorated function. Adopted from:
https://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
:param tries: number of times to try (not retry) before giving up
:param delay: initial delay betwe... |
155fad4618be8add36e09058591d1faedca95597 | viviandr31/practice | /pro06/pro05.py | 1,384 | 3.890625 | 4 | s = 'y'
while(s is 'y'):
var1, var2 = [int(x) for x in input("Enter two numbers here: ").split()]
res =0
print( "A = " + str(var1) + ' and B = ' + str(var2) )
if(var2>0):
while(var2 >= 1):
if(var2%2 is 1):
res += var1
print('B was odd, we add A to ma... |
3706bbd3c5cf15566eb1f996e235610b68d372c1 | s-tefan/python-exercises | /matplotlibgrejer/mpltest1.py | 391 | 3.546875 | 4 | import random
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig = plt.figure(figsize=(15,15))
x,y = [], []
#index= count()
index = iter(range(100))
def animate(i):
x.append(next(index))
y.append(random.randint(2,20))
plt.style.use("ggplot")
plt... |
8cbd19ff505ae726a93ce62a8c00bb65f10ab34a | s-tefan/python-exercises | /integerbase.py | 552 | 3.859375 | 4 | def int_to_base(n, base):
if not isinstance(n, int):
raise ValueError()
if base < 0:
n = - n
base = - base
digits = []
if n > 0:
while n != 0:
digit = n % base
n = n // base
digits.append(digit)
elif n < 0:
while n != 0:
... |
0d927ff6e20b43bab244c0cd6f681e57bb94795d | s-tefan/python-exercises | /fibo_iter.py | 855 | 3.984375 | 4 | class FibonacciIterator:
n0=0
n1=1
def __iter__(self):
return self
def __init__(self,n0,n1):
self.n0=n0
self.n1=n1
def __next__(self):
n=self.n0 # Första värdet sparas, ska returneras
n2=self.n0+self.n1 # Skapar nästa värde
self.n0=self.n1 ... |
d49dd6686b75e7405d2cd6cc6ca0fcfb8e0679bf | fieteb/nlp15FP | /scripts/processDownloadedTweets.py | 1,249 | 3.5625 | 4 | import csv;
import os;
import sys;
def getCSVFileNames() :
dirName = os.path.dirname(os.path.realpath(__file__));
fileNames = [];
for fileName in os.listdir(dirName) :
if fileName.endswith(".csv") :
fileNames.append(dirName + "/" + fileName);
return fileName... |
5c54ccab13a0c3ce0b89edb53f8efdb4cf479916 | devlunch4/HelloPython | /HELLOPYTHON/day01/myvariable.py | 162 | 3.71875 | 4 | # 주석 사용을 위해 UTF-8 설정 필요
# 파이썬의 문자열
a ='1'
# 숫자 b
b = 2.1
print(a)
print(b)
# 숫자 b 를 문자로 변형
print(a+str(b)) |
d1557cb721269a2cdada461d8caf3443a6bf985e | devlunch4/HelloPython | /HELLOPYTHON/day02/OddEvenNumber.py | 327 | 3.546875 | 4 | import random
mine = input("홀/짝을 선택하시오...")
print(mine)
com = ""
rnd = random.random()
if rnd > 0.5:
com = "홀"
else:
com = "짝"
result = ""
if mine == com:
result = "이겼습니다."
else:
result = "졌습니다."
print("mine", mine)
print("com", com)
print("result", result)
|
7696fa65db52360bde1bb1bc73996eec9e1c0517 | devlunch4/HelloPython | /HELLOPYTHON/day02/RockPaperScissors2.py | 526 | 3.703125 | 4 | import random
mine = input("가위/바위/보 선택하시오...")
com = ""
rnd = random.randint(1, 3)
if rnd == 1:
com = "가위"
elif rnd == 2:
com = "바위"
else:
com = "보"
result = ""
if mine == com:
result = "비겼습니다."
elif (mine == "가위" and com == "보") or (mine == "바위" and com == "가위") or (mine == "보" and com == "바위"):... |
a8009b70667b39f3f4ecf5c8e798a701389d36f6 | elizabethhealy/cs4300sp2021-eah255-klw242-dzy3-sn532-oz28 | /scripts/search.py | 5,362 | 3.5 | 4 | """
Searches for recipes similar to movie and returns top ten.
"""
import scripts.sim
import scripts.edit
import json
import pandas as pd
import csv
import re
"""
Given a query (movie name), a dict of movies to food words, and a list of recipes
Step 1: generate or access similarity matrix
Step 2: use movie_name_to_in... |
6470fee3445ab2adf599c325444147cc6d72cc5f | sdpython/pysqllike | /src/pysqllike/generic/others_types.py | 1,500 | 3.65625 | 4 | """
@file
@brief defines custom types
"""
class long:
"""
Defines the long type as int.
"""
def __init__(self, v):
self._v = int(v)
def __mul__(self, y):
return long(self._v * y._v)
def __add__(self, y):
return long(self._v + y._v)
def __sub__(self, y):
... |
c1927d80c9fc7310d6ef5bb67cc38972b384b73e | lazhenko/my_projects | /perfect-numbers/perfect_numbers.py | 349 | 3.6875 | 4 | def classify(number):
sm = 0
if number <= 0 or number % 1 != 0:
raise ValueError('Input needs to be a positive integer.')
for i in range(1, number):
if number % i == 0:
sm += i
if sm == number:
return 'perfect'
elif sm < number:
return 'deficient'
else... |
fff4dfb33e3e51a619568e86740491aefbaf587c | cshintov/connect-four | /closure.py | 850 | 3.828125 | 4 | """ Showcase utility of higher order functions, closure and decorator """
def memoize(func):
results = {}
def inner(*args, debug=False):
if debug:
print(args)
try:
return results[args]
except KeyError:
if debug:
print("Computing new ... |
2cc5465bc7710a4f511cb8b45d73f65ed7198e55 | asengupta74/GW_RNN | /dataset_generate.py | 4,324 | 3.90625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
import itertools
from sinegaussian import sinegauss
def genSeries(A, fc, sigma, n,noise_add):
'''
Input parameters:
A, fc, sigma, n: Refer to sinegaussian documentation
noise_add: if 1, then gaussian noise with mean 0 and std dev 1 added t... |
d529619f4d5efe143fab51edc8da1c50ff58fa83 | LuisDavilaBermudez/final-project | /devel/MainProgram.py | 1,354 | 3.6875 | 4 | import ThumbnailProgram.py
import LogoProgram.py
import MirrorProgram.py
print('Hello, Which of these languages do you prefer, English or Spanish?')
input()
if input == English:
print('Hello, would you like to make an image a thumbnail size?')
input()
if input() == yes:
os.system("ThumbnailProgram.p... |
0a4d2d267d96e035a4a89652ab9bf3c2520b4d89 | teamday/Learning | /graphs/binary_tree_inorder_traversal.py | 1,155 | 3.796875 | 4 | #!/usr/bin/env python
# runtime O(n)
# space stack(max depth) + result (can be in stream)
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: Li... |
1f8658bfdda2c7605b0590be144435424192a758 | teamday/Learning | /other/merge_intervals.py | 881 | 3.703125 | 4 | #!/usr/bin/env python
# complexity O(n*log(n)) + O(n)
# space O(n) for result, assume inplace sort
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
def merge(self, intervals):
if len(intervals) == 0 or len(intervals) == 1:
return int... |
a03e08150927c00c180a5b7550c51f8bad358501 | teamday/Learning | /graphs/validate_binary_search_tree.py | 1,460 | 3.65625 | 4 | #!/usr/bin/env python
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def f():
stack=[root... |
0630529ae9dcb33d2a27e1304e10ed4fdb982438 | teamday/Learning | /search/sliding_window_maximum.py | 1,519 | 3.671875 | 4 | #!/usr/bin/env python
class QueueItem:
def __init__(self, val, count):
self.val = val
self.count = count
class Monoqueue:
def __init__(self):
self.m_deque = []
def push(self, val):
count = 0
while len(self.m_deque)>0 and self.m_deque[-1].val < val:... |
a18e3f91bf8937dacec07acfc1404f07a33e468b | teamday/Learning | /search/in_rotated_sorted_array.py | 599 | 3.828125 | 4 | #!/usr/bin/env python
def search(nums, target):
left, right=0, len(nums)-1
while left<=right:
mid=(left+right)//2
if target==nums[mid]:
return mid
if nums[mid]>=nums[left]:
if target>=nums[left] and target<nums[mid]:
right=mid-1
else:
... |
2d3a76992f0d37b31ccbcad4660fa89e6dc56461 | segunadeleye/algorithms | /py/merge_sort.py | 2,314 | 3.953125 | 4 | # array[start:stop] = [start,..., stop - 1]
def mergeSort(array):
n = len(array)
if n == 1:
return array
mid = n // 2
left = array[0:mid]
right = array[mid:]
return merge(mergeSort(left), mergeSort(right), n)
def merge(left, right, n):
merged = []
iLeft = 0
iRight = 0
leftLength = len(left)
... |
dff34b5e49dfcd8edbee63ca40a431068d88bf58 | coyleandrew/manhattanDistance | /GUI/controller.py | 1,095 | 4.0625 | 4 | # This is the controller class that is responsible for taking in user input
# and sending it to the model
from tkinter import *
from tkinter import ttk
from view import *
from model import *
class Controller:
# This method is responsible for creating a controller object.
# The controller object then instanti... |
c1d097223420d08d48de8c867f9cd24369f172c7 | stoppable408/algorithms-and-data-structures | /randomize.py | 250 | 3.75 | 4 | import random
test = list(range(15))
print(test)
#O(n) algorithm for randomizing an array
for elem in range(0,len(test)-1):
num = random.randint(1,len(test)-1)
temp = test[elem]
test[elem] = test[num]
test[num] = temp
print(test)
|
05b25c0d322949186cf0a5e52b27bcb3d37de57b | ShaneKoNaung/Python-practice | /linked-list/singly-linked-list/main.py | 1,186 | 4.09375 | 4 | from linked_list import LinkedList
from node import Node
# from node import Node
def main():
ll = LinkedList()
print("List is empty :", ll.is_empty())
print()
print("adding 10 to the front")
ll.push_front(10)
print("adding 20 to the front")
ll.push_front(20)
print("The front item i... |
35c92a9c66af8bcf6ee2eeec1eb9f3743e375091 | ShaneKoNaung/Python-practice | /stack-and-queue/linked_list_queue.py | 1,222 | 4.25 | 4 | ''' implementing queue using linked-list'''
class LinkedListQueue(object):
class Node(object):
def __init__(self, data, next=None):
self._data = data
self._next = next
def __init__(self):
self._head = None
self._tail = None
self._size = 0
def __len... |
2f9976e9ae634c5d370e0a45e4484a9c63e7d363 | ShaneKoNaung/Python-practice | /stack-and-queue/linked_list_stack.py | 1,171 | 4.125 | 4 | ''' Implementation of stack using singly linked list '''
class LinkedListStack(object):
class Node(object):
def __init__(self, data, next=None):
self._data = data
self._next = next
def __init__(self):
''' create an empty stack '''
self._head = None
sel... |
43b337defb269118e6000d556c231cd224e270b9 | ShaneKoNaung/Python-practice | /linked-list/singly-linked-list/node.py | 591 | 3.578125 | 4 | class Node(object):
def __init__(self, data=None, next=None):
''' initialize the node '''
self._data = data # data
self._next = next # next pointer
def get_data(self):
''' return data '''
return self._data
def set_data(self, data):
''' set the value of dat... |
9d30c4e827acb72d6b13932a5d3c8667b6669c96 | gergokutu/cs50-python | /try.py | 912 | 4.28125 | 4 | text = input("Your text: ")
# pay attention > f (format string)
print(f"You typed: {text}")
print("You typed: {text}")
# order counts > cough()
def cough():
print("Cough")
for i in range(3):
cough()
# say no to write anything after the ?s
# named argument > end
# then use print() to write a new line
for i... |
6d719c998ace06c5786ac051fdfd07c3e2bc55b4 | rahulkranjan/FIEM_C_PROGRAMMING | /temp/2nd.py | 175 | 4.0625 | 4 |
x = int(input("Enter 1st number: "))
y = int(input("Enter 2nd number: "))
a = 0
for i in range(x, y+1):
if i % 2 == 0:
a += i
print("sum of even number is ", a)
|
bcabdc7e237d6980d5924ac82da29b91da0bf3ba | rahulkranjan/FIEM_C_PROGRAMMING | /temp/occurrences .py | 362 | 3.953125 | 4 | list1 = []
n = int(input("Enter number of element :"))
for i in range(n):
a = int(input())
list1.append(a)
s = int(input("Enter the element you want to check :"))
q = list1.count(s)
q = int(q)
# print("the searched number appeared:", q)
if(q > 1):
for i in range(q-1):
list1.remove(s)
for i in range(... |
929d54dafa3f52f1b99b571ac9567bbf6af4a286 | krodgers/CS271_Tic_Tac_Toe | /risk_human_move.py | 5,577 | 4 | 4 | def DoHumanMove(self, player):
self.playerJustMoved = player.playerNum
numNewArmies = player.GetNewArmies() # Within this will be code to calculate how many countries captured and if any continents captured
# Place the new armies
while numNewArmies > 0:
numNewArmies = self.placeArmies(numNe... |
a9c9c897a8efca94fcf61183eb3c3e8603eea76f | ZanettaR/API-Challenge | /reverse.py | 987 | 3.734375 | 4 | import requests
import json
#Step 2:
#Sends an HTTP Request to the specified endpoint
#Then takes the string that is returned,
#And reverses it then send it back to be validated.
#Sends http request to an endpoint with expected json dictionary
req = requests.post('http://challenge.code2040.org/api/reverse',auth=('use... |
5151cfe22c6ba893660c49ba006b512c77a74e6b | Suryashish14/Suryashish-Programs | /SpecialCalculator 1.py | 2,115 | 4.25 | 4 | print('::::::::::::::::::::::::::: MENU ::::::::::::::::::::::::::::::::::')
print('Press 1 To Check For Armstrong Number')
print('Press 2 To Check For Duck Number')
print('Press 3 To Check For Perfect Number')
print('\t\t\t\t Instructions')
print('''1.Provide Only Positive Numbers
2.For Using The Menu Use Only 1... |
727075465939f854d8978ce006625fb3147dc331 | wear99/Python_Study | /练习题/计算题练习.py | 2,991 | 3.609375 | 4 | def 计算(a1,b1,c1,a2,b2,c2):
global 解组合
for x in range(1, 20):
for y in range(1, 20):
if a1 * x + 2 * b1 * y == 5 * c1 and a2 * x + 2 * b2 * y == 5 * c2:
#print("x,y的第%5d组解为%5d,%5d, 此时a1,b1,c1的值为%5d,%5d,%5d" % (n, x, y, a1, b1, c1))
... |
4b431a1b584fca8ecdcaa9da7ce12764cc7c3ae9 | wear99/Python_Study | /函数式编程/高阶函数 map reduce.py | 3,869 | 3.875 | 4 | # -*- coding: utf-8 -*-
# 一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数
# 函数名就是一个指向函数的变量,当加()时代表调用函数,不加()则是一个变量
from functools import reduce
def 绝对值加法(a, b, f):
return f(a) + f(b)
print(绝对值加法(-3, 5, abs))
# Python内建了map()和reduce()函数。
# map()函数接收两个参数,一个是函数,一个是可迭代对象(list/tuple/生成器等),map将传入的函数依次作用到序列的每个元素,
# 并把结果作为新的Iterator(迭... |
ddb7f074d209a40906e46fa93c2d3c2ec7e14d92 | wear99/Python_Study | /函数/递归函数.py | 1,201 | 3.828125 | 4 | # 在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
# 对于有些特殊问题,使用递归可以大大简化程序
# 计算 从1 到 n 相乘的结果
def 阶乘(n):
if n == 1:
return 1
return n * 阶乘(n-1) # 5 * ( 4 * ( 3 * ( 2 * (1) )))
# -->阶乘(5)
# --->5* 阶乘(4)
# --->5* 4 * 阶乘(3)
# --->5* 4 * 3* 阶乘(2)
# --->5* 4 * 3* 2* 阶乘(1)
# --->5 * (4 * (3 * (2 * 1)))
# --->5 *... |
459ad480d62c540f80f0160af4fe6d59478cea54 | wear99/Python_Study | /类和实例/类和实例.py | 1,860 | 4.15625 | 4 | # 类是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,
# 每个对象都拥有相同的方法,但各自的数据可能不同。
# 首先要定义类,指定从哪继承
class 学生(object):
# 也可以定义类的属性,这样实例就会自动具备这个属性
性别='女'
# 定义类的实例有什么属性,定义了之后,再生成实例的时候就必须传入这些参数
def __init__(self, 姓名, 学号, 成绩):
self.姓名 = 姓名
self.学号 = 学号
self.成绩 = 成绩
# 数据封装,直接在类里面定义好获得属性的函... |
f0e58bc7380a1167954f5f481b7236b41f259ec9 | wear99/Python_Study | /函数式编程/返回一个函数.py | 846 | 3.9375 | 4 | # 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回
# !!!返回一个函数时,牢记该函数 并 未 执 行 !!!,而是在该返回值后面加()时才执行。返回函数中不要引用任何可能会变化的变量。
def 打印(s):
def 现在打印(m):
print(s,m)
return 现在打印 # 当调用 打印 时返回的是 立即打印 这个函数,并没有被执行
s=打印('hello') #相当于s=现在打印(),并未执行
print('*****加括号时才执行******')
s('可以对内层函数再传入参数')
# 内部函数sum可以引用外部函数laz... |
205989560d9c97a0350408176c55030054412536 | wear99/Python_Study | /基础学习/列表生成式.py | 1,245 | 3.90625 | 4 | # 列表可以快速生成
# 生成一个1到10的列表
x1 = list(range(1, 11))
print(x1)
#带表达式的生成方式,for每循环一次就赋值一次
x2= list(n * n for n in range(1, 6))
print(x2)
# 也可以直接用[]
x3 = [n * n for n in range(1, 6)]
print(x3)
# for后面可以加if语句进行判断,类似条件赋值,if后不要:
x4 = [n * n for n in range(1, 6) if n % 2 == 0]
print(x4)
#还可以使用两层循环,可以生成全排列. 每次for循环都会赋值
x5 = [m... |
e8526da7d661d0965fa85a4b267378bb903ffb4b | adonayab/vigenere | /vigenere.py | 776 | 3.96875 | 4 | from helpers import alphabet_position, rotate_character
def encrypt(text, word_rot):
encrypted = ''
rot_word_text = ''
word_rot_length = len(word_rot)
k = 0
for i in text:
if i.isalpha():
rot_word_text += word_rot[k % word_rot_length]
k += 1
else:
... |
c7e9d77d68fb5ca416f3b5d5784ff7e74704dda7 | vegarsti/aoc2020 | /02_2.py | 459 | 3.703125 | 4 | with open("input/02.txt", "r") as f:
lines = f.readlines()
def xor(b1: bool, b2: bool) -> bool:
return b1 != b2
def valid_line(line: str) -> bool:
positions, letter_with_colon, password = line.split()
letter = letter_with_colon[0]
pos1, pos2 = positions.split("-")
index1, index2 = int(pos1) ... |
9d8eb6ed6d84dafe3bb79c3312421f73afc25990 | vegarsti/aoc2020 | /13_2.py | 573 | 3.578125 | 4 | def solve_congruence(a: int, b: int, m: int) -> int:
x = 0
while (a * x) % m != b:
x += 1
return x
with open("input/13.txt", "r") as f:
lines = f.readlines()
buses = sorted(((i, int(s)) for i, s in enumerate(lines[1].strip().split(",")) if s != "x"))
total_offset, step_length = buses[0]
for of... |
89031d9e5b5682674c23ce7df426d9a46417405b | u101022119/NTHU10220PHYS290000 | /student/101022123/catalan.py | 255 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 15 16:32:09 2014
@author: user
"""
def catalan(n):
n=int(raw_input('Enter a number:'))
x=1
for i in range(n):
y=(i*4.0+2)/(i+2)
x = x*y
print 'C',n,'=',x,
catalan(n)
|
b132e8dcca03948aa11bf3d4e62f93bc70e891b7 | u101022119/NTHU10220PHYS290000 | /student/101020031/111.py | 1,213 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 13 16:58:05 2014
@author: user
"""
class Time(object):
"""pass"""
def print_time(t):
print"%.2d:%.2d:%.2d" % (t.hour,t.minute,t.second)
a=Time()
a.hour=1
a.minute=2
a.second=3
b=Time()
b.hour=2
b.minute=2
b.second=3
print_time(a)
def bigsmall(t1,t2):... |
42ec16f9584e3748216809a6ff8c30a52cecf498 | u101022119/NTHU10220PHYS290000 | /student/101022118/HW1/convert polar.py | 301 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 17 15:53:29 2014
@author: user
"""
import math
def convert_polar():
x=float(raw_input('Put the x component: '))
y=float(raw_input('Put the y component: '))
l=(x**2+y**2)**0.5
r=math.asin(y/l)
print '(' , l , r , ')'
convert_polar() |
a44100cc8c65b23b301406c6a0a41410c5266b67 | u101022119/NTHU10220PHYS290000 | /student/101022161/len.py | 165 | 3.953125 | 4 | fruit = 'banana'
print len(fruit)
length = len(fruit)
last = fruit[length-1]
print last
print fruit[-1]
print fruit[-2]
print fruit[-6]
print fruit[-5]
|
d0dcebe5b920a75272d94a545eeafaebe6ca99d2 | u101022119/NTHU10220PHYS290000 | /student/101022103/my sort.py | 648 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 16 15:08:36 2014
"""
import random
def random_list(N,a,b):
k=[]
for i in range(N):
k.append(random.randint(a,b))
return k
def selection_sort(k,N):
print random.sample(k,N)
def insertion_sort(k,N):
for i in range(N):
k.append(random.... |
3ec8b2046e343d9ef8422f4f83640ad579aa342b | u101022119/NTHU10220PHYS290000 | /student/101022105/fibonacci_rec.py | 327 | 4.1875 | 4 | n=float(raw_input("Put n here."))
def fibonacci_rec(n):
if n==1:
return 1
if n>1:
return n+fibonacci_rec(n-1)
else:
return 0
if fibonacci_rec(n)>0:
print fibonacci_rec(n)
elif n<0 or type(n)!=int or type(n)!=str:
print 'Error, the n given should positive and should be an inte... |
dd2c2c0e36ca956b128d839d471ce3c81c231d1b | u101022119/NTHU10220PHYS290000 | /student/101022108/homework 3/mytime.py | 837 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 19 08:27:30 2014
@author: Mark
"""
class Time:
'''attributes hour, min, sec '''
def print_time(t):
print '%.2d:'%t.hour, '%.2d:'%t.min, '%.2d'%t.sec
def is_after(t1, t2):
sum1 = t1.hour*60*60+t1.min*60+t1.sec
sum2 = t2.hour*60*60+t2.min*60+t1.sec
... |
6b208afa781d007a435e3d16794aa126a0711d9b | u101022119/NTHU10220PHYS290000 | /student/101022109/poke_r.py | 6,250 | 3.5625 | 4 | import random as rand
shape_dict = {0:"S",1:"H",2:"D",3:"C"} ## S = Spade , H = Heart , D = Diamond , C = Club
number_dict = {i:str(i) for i in range(2,11)}
number_dict[1] = 'A'
number_dict[11] = 'J'
number_dict[12] = 'Q'
number_dict[13] = 'K'
class Card():
def __init__(self,shape,number):
if shape in r... |
0a4e79269a9ee963f8cf304c3a9bf68009b87f54 | u101022119/NTHU10220PHYS290000 | /student/101022114/drop_ball_time.py | 256 | 3.875 | 4 | g=10.0
h=float(raw_input("Put the height of the tower: "))
def drop_ball_time(h):
if h>0:
t=(2*h/g)**0.5
return t
elif h==0:
return 0
else:
return'Sorry, the height cannot be negative.'
print drop_ball_time(h)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.