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 |
|---|---|---|---|---|---|---|
068045aa9d8427e3327946b9fc7843ae7d5084cd | Nathan120/Arq_Python_CursoEmVideo | /Curso_Gustavo_Guanabara/Exercicio81.py | 434 | 3.90625 | 4 | lista = list()
cont = 0
while True:
num = int(input('Digite um número: '))
lista.append(num)
cont += 1
op = input('Deseja adicionar outro numero?[S/N]: ')
if op in 'Nn':
break
lista.sort(reverse=True)
print(f'foram adicionados {cont} números na lista')
print(f'A lista em ordem decrescente {l... |
eed4e3eeb389a238d8405fb748f5baeca75fd6c8 | Nathan120/Arq_Python_CursoEmVideo | /Curso_Gustavo_Guanabara/Exercicio94.py | 1,152 | 3.640625 | 4 | pessoa = dict()
total = list()
totp = tidade = 0
while True:
pessoa.clear()
pessoa['nome'] = str(input('Digite seu nome: '))
while True:
pessoa['sexo'] = str(input('Sexo[M/F]: ')).upper()[0]
if pessoa['sexo'] in 'FM':
break
print('ERRO! Por favor, digite apenas M ou F.')
... |
3444ed6f1c2b6f7fea45800f40f1ee33c6c208b9 | Nathan120/Arq_Python_CursoEmVideo | /Curso_Gustavo_Guanabara/Exercicio98.py | 650 | 3.6875 | 4 | def contador(inicio, fim, passo):
print(f'Contagem de {inicio} até {fim} de {passo} em {passo}')
if passo == 0:
passo = 1
if passo < 0:
passo *= (-1)
if inicio < fim:
for p in range(inicio, fim+1, passo):
print(p, end='...')
print()
elif inicio > fim:
... |
28a98b0d7a6abd333cae07a869ab0e8b17e64785 | Nathan120/Arq_Python_CursoEmVideo | /Curso_Gustavo_Guanabara/exercicio029.py | 314 | 3.84375 | 4 | velocidade = int(input('Digite a velocidade do seu carro = KM'))
if velocidade > 80:
multa = (velocidade - 80)*7
print('Você está acima da velocidade permitada, vai pagar multa')
print('R$07,00 por km a mais, vc pagara R${:.2f}'.format(multa))
else:
print('Você está na volocidade permitida') |
f703156fa03a2a07ef555cbe083a8743d6824706 | Nathan120/Arq_Python_CursoEmVideo | /Curso_Gustavo_Guanabara/Exercicio104.py | 307 | 3.875 | 4 | def leiaint(string):
while True:
num = input(f'{string}: ')
if num.isnumeric() == True:
break
else:
print('\033[;31m Erro! Digite um número inteiro \033[m')
return num
n = leiaint('Digite um número')
print(f'Você acabou de digitar no numero {n}') |
657169fe82dedb7c07b9a3a903a05982c51fef5e | Nathan120/Arq_Python_CursoEmVideo | /Curso_Gustavo_Guanabara/Exercico008_013.py | 761 | 3.796875 | 4 | valor = float(input('Digite a medida em metros = '))
cemt = valor * 100
mili = valor * 1000
print('metros {} \n centimetros {} \n milimetros {}'.format(valor,cemt,mili))
altura = float(input('Digite a altura da parede = '))
largura = float(input('Digite a largura da parede = '))
area = (altura * largura)/2
tinta = ar... |
3ea52fd0a495f785d97c66bbcaf3ef15d8a32e5b | arwankhoiruddin/stress-test-resources | /generateFolders.py | 2,661 | 3.90625 | 4 | import os
import random
import shutil
from random_words import RandomWords
import random
import sys
import os
"""
This code is used to generate some levels of directories
with different size of files
The goal of this is to be used as stress test for ScramBox and ScramExplorer
To do the stress test for each products... |
6142fd2542e1535c2c7799b72cf8846ba7a7982d | nzhurovich/Dataquest-assignments | /probability-fundamentals/Estimating Probabilities-377.py | 1,061 | 3.796875 | 4 | ## 2. The Empirical Probability ##
p_tail = 0.44
p_six = 28 / 200
p_odd = 102 / 200
print(p_tail, p_six, p_odd)
## 3. Probability as Relative Frequency ##
p_heads_1 = (300 - 162) / 300
percentage_1 = p_heads_1 * 100
p_heads_2 = (5000 - 2450) / 5000
percentage_2 = p_heads_2 * 100
## 4. Repeating an Experiment ##
#... |
8e27a933c50182841bc52685d7cec8acc9733575 | mzaidi59/Data_Mining_Census_2011 | /Assignment_1/Misc/ass1a.py | 4,737 | 3.515625 | 4 | from pandas import read_csv
import csv
import operator
from math import isnan
import numpy as np
import copy
import os
def filter_word(a):
if a[0:3] == 'A &' or a[0:4] == 'Anda':
b = 'ANI'
elif a[0:3] == 'D &':
b = 'Dadra & Nagar Haveli'
elif a == 'Uttar Pradesh':
b = 'UPA'
elif a[0:3] == 'NCT':
b = 'Delh... |
017171c7b2e093a5a8c58aa7602e28547de71fd1 | ccirelli2/opencv_tutorials | /tutorials/morphological_tranfs.py | 2,672 | 3.640625 | 4 | # DOCUMENTATION ----------------------------------------
'''
Url: https://docs.opencv.org/trunk/d9/d61/tutorial_py_morphological_ops.html
Erosion: Erodes away the boundaries of the foreground object (always try to keep your
objects in white). Uses a 2D convolution. A pixel will only be a one if ... |
2bd88a486aeceb16ca22b88e9e248dea84a1b236 | ccirelli2/opencv_tutorials | /circuit_digest_tutorial/image_manipulation.py | 1,919 | 3.9375 | 4 | # Import Modules
import cv2
import os
import numpy as np
from matplotlib import pyplot as plt
# Documentation
'''
https://circuitdigest.com/tutorial/image-manipulation-in-python-opencv-part2
'''
# Import Image
os.chdir('/home/ccirelli2/Desktop/repositories/OpenCV_tutorial/data')
img_cyber = cv2.imread('cyber_image.jp... |
b8d346a6daeee0cb6747cf0fe4cca8868abc900a | sloscal1/ML-Prob-Perspective | /chapter/five_exercises.py | 4,409 | 3.78125 | 4 | def question_1():
r""" Posterior of a mixture of conjugate priors is a mixture of conjugates.
.. math::
p(\theta|D) &= \frac{p(\theta, D)}{p(D)},~&\textrm{Def. Cond. Prob},\\
&= \frac{\sum_k p(z=k)p(\theta, D | z=k)}{\sum_{k'} p(z=k')p(D|z=k')},~&\textrm{Law of Total Prob},\\
&=... |
1a4f8127f90fde10ec1781216ca3114668444d49 | iwandepe/competitive-programming | /solutions-project-euler/10001st Prime.py | 343 | 3.828125 | 4 | from math import sqrt
prime_list = []
def is_prime(n):
for i in prime_list:
if n%i == 0:
return False
return True
def gen_prime(n):
counter = 0
num = 2
while True:
if (is_prime(num)):
prime_list.append(num)
counter += 1
if counter == n:
return num
break
num += 1
gen_prime(10001)
... |
a717749175155b93a87fbd7e380d0a17c7c4c7a7 | Triglav97/Python | /4 лр/lab_4.py | 1,824 | 3.53125 | 4 | import matplotlib.pyplot as plt
import numpy as np
print("Задание 1\n")
k1, k2, k3 = 4, 15, 3
freq = 100
a, b = -10, 10
xi = np.linspace(a, b, freq)
y = [k1 * t * t + k2 * t + k3 for t in xi]
plt.plot(xi, y)
plt.grid()
plt.show()
print("Задание 2\n")
freq = 100
a, b = 0.1, 10
xi = np.linspace(a, b, freq)... |
969c64b524fe067a2a6d5d5da6488565df37261d | Kevnien/Data-Structures | /heap/heap.py | 1,948 | 3.640625 | 4 | class Heap:
def __init__(self):
self.storage = []
def insert(self, value):
self.storage.append(value)
self._bubble_up(len(self.storage)-1)
def delete(self):
self.storage.pop(0)
storage_length = len(self.storage)-1
if storage_length < 0:
return
last_element = self.storage[storag... |
c8cc85dcd1c79d54cd449a99a02f037386b226df | Hchyeria/LeetCode | /378 Kth Smallest Element in a Sorted Matrix/378.py | 2,193 | 3.53125 | 4 | from queue import PriorityQueue
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
class Cell:
row = 0
col = 0
val = 0
def __init__(self, row, col, val):
self.row = row
self.col = col
... |
bb0dc9c1e19d62683d43f9aa7d769255844b8d11 | Hchyeria/LeetCode | /98 Validate Binary Search Tree/98.py | 648 | 3.8125 | 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 isValidBST(self, root: TreeNode) -> bool:
return helper(root, -math.inf, math.inf)
def helper(root, min_num, max_num):
... |
ae5db84302ba6065810bb29003fa67ad551c7479 | Hchyeria/LeetCode | /143 Reorder List/143.py | 1,534 | 3.984375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head or not head.... |
556219412579861297f16763defeef6772c225bd | Hchyeria/LeetCode | /1123 Lowest Common Ancestor of Deepest Leaves/1123.py | 1,278 | 3.546875 | 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 lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
if not root:
return root
res = [0]
globalMax ... |
9f5b3d61e279ab9302b06799e70ccf27a85f34ff | Hchyeria/LeetCode | /145 Binary Tree Postorder Traversal/145.py | 1,531 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
res = []
if not root:
... |
81425a40dd63b8977722402c43903bd77951cada | joevarghese/python101 | /odd0-99.py | 73 | 3.515625 | 4 | for number in range(1,100):
if number % 2 != 0:
print(number) |
52ff3f53c16637586a0897105e7fc53d0d54fd5f | propriocept/tree_with_nfiles | /tree_count.py | 1,585 | 3.8125 | 4 | from pathlib import Path
import argparse
def dir_with_count(start_dir: str):
# Initialise variables. directories is a list of all found directories.
# n_files is the number of files in the current directory.
directories = list()
n_files = 0
# Convert starting directory (start_dir) to pathlib.Path f... |
194fa04f6e4d61a30b50fc067f14ba7ca2bf9eda | ragraw26/Python_Practice- | /main.py | 1,321 | 4.09375 | 4 | #Question 1:Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included).The numbers #obtained should be printed in a comma-separated sequence on a single line.
result = []
for num in range(2000, 3201):
if (num % 7) == 0 and (num % 5)... |
1856aa954cd5f5c49a803ec654c2ba24cf7020d8 | Dupertroll/Pruebas-Iniciales-Python | /variables/1-attempt.py | 192 | 3.671875 | 4 | introducirEdad = int(input("introduce tu edad: "));
print(introducirEdad);
if(introducirEdad < 20):
print("Felicidades, aun tienes mucho por vivir");
else:
print("ya tas viejo pa");
|
1d59216ce967c71ac1fbbe870bc85b4655e44740 | ZHIYUAN-LIU66/Transport-Canberra | /assignment.py | 26,611 | 4.1875 | 4 | """
COMP1730/6730 assignment template.
Collaborators: <u6511430
u6543401
u6753610>
"""
import csv
import random
import numpy as np
def load_stops(path):
'''
Load a csv file with bus stop information.
The argument should be a string, which is the path to the file.
The r... |
b891127b58d4ee5862e09582c1cde2d0d66ff31c | yamabato/Valture | /attached_players.py | 2,334 | 3.796875 | 4 | #encoding: utf-8
import random
def choice_min(t=[], p={}, p2={}, name=""): # 常に最小を返す
if name:
return "CHOICE-SMALL"
return min(p["card"])
def choice_max(t=[], p={}, p2={}, name=""): # 常に最大を返す
if name:
return "CHOICE-BIG"
return max(p["card"])
def choice_random(t=[], p={}, p2={},... |
b612919e2e63b4a9db6a1d16eb9a0b74c595d831 | Eric-Zhang-Composing/awesome-DeepLearning | /examples/numpy housing.py | 2,473 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def load_data():
# 导入房价数据
datafile = '/home/aistudio/data/housing.data'
data = np.fromfile(datafile, sep=' ')
# 将原始数据进行Reshape操作 并且拆分成训练集和测试集
data = data.reshape([-1, 14])
offset = int(data.shape[0]*0.8)
train_data = data[:offset]
# 进行归... |
250c934695e42bd87c78f1ce3dd5d4f3989940b8 | nishantchauhan00/GeeksForGeeks | /Top 25 Interview Question/20 Thread and Runnable.py | 2,210 | 3.859375 | 4 | '''
A thread can be defined in two ways. First, by extending a Thread class that
has already implemented a Runnable interface. Second, by directly implementing
a Runnable interface. When you define a thread by extending Thread class you
have to override the run() method in Thread class. When you define a thread
imp... |
5cd4a59ccc6118ed36e177e54b10ce5832ca0250 | nishantchauhan00/GeeksForGeeks | /Companies Question/149 Find whether path exist.py | 1,838 | 3.953125 | 4 | """
A value of cell 1 means Source.
A value of cell 2 means Destination.
A value of cell 3 means Blank cell.
A value of cell 0 means Blank Wall.
we can go through blank cell, blank wall stops
# its similar to rat in maze problem
i think it would be more faster if implemented using queue, but space complexity
is defin... |
46b27266e75a17786f161e17f1de7bacc8e39020 | nishantchauhan00/GeeksForGeeks | /Top 25 Interview Question/11 Print a given matrix in spiral form.py | 1,524 | 3.96875 | 4 | import math
class Solution:
def spiralMatrix(self, arr):
row, col = len(arr), len(arr[0])
out = []
def printloop():
left, right = 0, col - 1
up, down = 0, row - 1
while left <= right and up <= down:
# left to right
for i... |
85652a0153f3eba83fac509a8da8176a55883a58 | nishantchauhan00/GeeksForGeeks | /Companies Question/57 Stickler Thief.py | 594 | 3.5625 | 4 | def solver(arr, n):
if n < 3:
return max(arr)
# we can do it by dp, but we need only two previous values
# so to save space we use just two integer variables
prev_before = arr[0]
prev = max(arr[0], arr[1]) # previous value can be first value if its greater
for i in range(2, n):
... |
bc976109c980834055f67b99f4d119d9d8741f81 | nishantchauhan00/GeeksForGeeks | /Companies Question/06 Binary Array Sorting.py | 515 | 3.890625 | 4 | def sortbarr(arr):
l = 0
r = len(arr) - 1
while arr[r] == 1 and r > 0:
r -= 1
while l < r:
if arr[l] is 1:
arr[l], arr[r] = arr[r], arr[l]
r -= 1
l += 1
while arr[r] == 1:
r -= 1
return " ".join(list(map(str, arr)))
N = int(in... |
5b3c2672b0b428beb6ebb298d6e2e7156e0074a4 | nishantchauhan00/GeeksForGeeks | /Companies Question/180 Inversion of array.py | 1,206 | 3.703125 | 4 | def solver(arr, n):
inv_count = 0
def MergeSort(arr, start, end):
nonlocal inv_count
mid = int((start + end) / 2)
if start < end:
MergeSort(arr, start, mid)
MergeSort(arr, mid + 1, end)
temp = []
a1 = start
a2 = mid + 1
i = start... |
33b6db5f13c54151cc5f27f970ec4d4dc52dfb91 | nishantchauhan00/GeeksForGeeks | /Top 25 Interview Question/16 Implement Stack using Queues.py | 932 | 4 | 4 | import queue
'''
it can be done using two queues, one operation either pop or push will be costly
'''
class Stack: # lets make pop costly
def __init__(self):
self.queuest1 = queue.Queue()
self.queuest2 = queue.Queue()
def push(self, n):
self.queuest1.put(n)
def pop(self):
... |
786c5717d2ba0a9ab3c7e87220e63fd6fa368fcd | nishantchauhan00/GeeksForGeeks | /Companies Question/113 Find largest word in dictionary.py | 1,272 | 3.5625 | 4 | class Solver:
def __init__(self, words, n, inp, n1):
self.out = ""
self.words = words
self.n1 = n1
self.inp = inp
# Recursion
# slow, gives tle
def helper(self, word, i):
if (word in self.words) and (len(word) > len(self.out)):
self.out = word
... |
a9f62e4e1e6758deffeaad6e631330d69589cd65 | gleisema/makingGUI | /makingGUI.py | 1,184 | 3.5625 | 4 | from tkinter import *
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(16, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(22, GPIO.OUT, initial=GPIO.LOW)
##hardware
red = 8
yellow = 16
green = 22
## gui definitions ##
win = Tk()
win.title("LED Togg... |
6c68d7d1f6933abed3dbcb2e42cdd074fcba92cc | LanderU/Progr15-16 | /SGE/python/ejercicio14.py | 334 | 3.59375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Definir una tupla con 10 edades de personas.
Imprimir la cantidad de personas con edades superiores a 20.
'''
edades = (18,20,35,42,53,12,90,45,21,19)
cant = 0
for x in edades:
if x > 20:
cant += 1
print 'El número de personas que superan la veintena de años son:... |
7ecfdec6c91667f3f118201a8bf1f44b75b1eade | LanderU/Progr15-16 | /SGE/python/ejercicio13.py | 452 | 3.78125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Almacenar en una tupla 5 nombres. Luego generar un valor aleatorio entre 2 y 4.
Copiar a una tupla el nombre de la posición indicada por el valor aleatorio y los nombres que se encuentran en la posición anterior y posterior.
'''
import random
tNombres = ('Juan','Pepit... |
a6da19e4092629689edc9fc61f3c414c54143f46 | hemory/todoapppython | /main.py | 433 | 3.671875 | 4 | from task import *
import json
from readandwrite import write_to_json_file
file_name = 'task_repo.txt'
proceed = True
while proceed:
task_name = input("What is tasks name?")
task_description = input("Describe your task")
write_to_json_file(task_name, task_description, file_name)
keepGoing = input("Wo... |
107d0ab3acd590237e0bfde00b5275244e80db1c | arkuzya/infa_2019_finalproject | /food.py | 1,260 | 3.765625 | 4 | import pygame
import sys
import random
import time
# STEP --- distance of moving snake per one cycle
STEP = 10
# the upper point of the playing area
Y_STARTING_POINT = 50
# BOARDWIDTH --- the width of the obstacles, which are set on the boards
BOARDWIDTH = 20
class Food:
def __init__(self, barriers, food_color,... |
826a2fbc51b22326eb1f2dd27bf0dba8ec1d6232 | jbeautz/3360 | /unitfind.py | 396 | 3.734375 | 4 | def RSA(x,e,n):
return (x**e)%n
def gcdExtended(a, b):
if a == 0 :
return b, 0, 1
gcd, x1, y1 = gcdExtended(b%a, a)
x = y1 - (b//a) * x1
y = x1
return gcd, x, y
# Driver code
a, b = 20,11
#gcd, x, y = gcdExtended(a, b)
#print(x,"*",a,"+",y,"*",b," = ",gcd)
print(RSA(6,10,11))
##https... |
3807870e5d7b079fe72358a02f8ed66b5297fb5c | dawnyoung/python | /Note9-liao-modules.py | 7,376 | 3.890625 | 4 | # -*- coding: utf-8 -*-
#---------------------------------------------------------------------------------------------
# modules
#---------------------------------------------------------------------------------------------
####################################################################... |
a58411334cd180491029308f31df0a629e217e86 | choyos/dictMaker | /dict_maker_piping.py | 3,385 | 3.765625 | 4 | #!/usr/bin/python
from __future__ import print_function, division
# Get start string in order to know when to start
def get_start_str(lenght):
start_str = ""
for i in range(lenght):
start_str = start_str + "0"
return start_str
# Get end string in order to know when to end
def get_end_str(lenght):
... |
8ebbc4e3ce17ebaadb34a27f7384c397804afd65 | sennayrton/paradigmas-java | /primo.py | 435 | 3.96875 | 4 | def esPrimo(num):
if num < 1:
return False
elif num == 2:
return True
else:
for i in range(2, num):
if num % i == 0:
return False
return True
def main():
num = int(input('Escribe un entero: '))
resul = esPrimo(num)
if resu... |
d12908ac3f419673dc93c1a4afa159f4425dc81f | warahk/exercises | /redblack_tree/redblack_tree.py | 1,161 | 3.703125 | 4 | #!/usr/bin/env python3
class Node:
'''Red/black Node'''
def __init__(self, value, color='red'):
self.value = value
self.left = None
self.right = None
self.parent = None
self.color = color
@property
def color(self):
return self._color
@color.setter
... |
d2c7816153e8a32bcbf4af9de1613a3ec3bb2eca | jithendra2002/LabTest_01-09-2020 | /L4-Additionofsparsematrix.py | 1,568 | 4.0625 | 4 | # Addition of two Sparse matrices
print('''Jithendra
121910313053''')
n = int(input('Enter the value of N in NxN matrix: '))
print('''\nThis is a Sparse matrix.
So input high frequency of zeros.''')
#Inputing the first matrix:
print("\nEnter the values for the first matrix : ")
a= []
for i in range(n):
... |
5816980497d070b07dd11d3b543c9864d66d30a1 | jithendra2002/LabTest_01-09-2020 | /L4-supplement-linear_search_function.py | 466 | 3.96875 | 4 | def linear_search(arr,goal):
for i in range(len(arr)):
if arr[i]==goal:
print(f' Element {arr[i]} found at {i}')
break
else:
print("element not found")
size=int(input("Enter the size of array: "))
a=[None]*size
for i in range(size):
b=int(input(f'Enter {... |
b64bfd30421c097aa02ca86105d4964f94cabab6 | tengrommel/test | /basic/algorithm/heap_sort.py | 1,356 | 3.640625 | 4 | def sift(li, low, high):
"""
:param li:列表
:param low: 堆的根节点位置
:param high: 堆的最后一个元素的位置
:return:
"""
i = low
# i最开始指向根节点
j = 2 * i + 1
# j开始是左孩子
tmp = li[low]
# 把堆顶存起来
while j <= high:
# 只要j位置有数
if j + 1 <= high and li[j + 1] > li[j]:
# 如果右孩... |
4e6ea2bdff4a387c9846c3d26cbb1c93938152d1 | lixue1031/HW1 | /main.py | 458 | 3.765625 | 4 | '''main'''
from myMath import myArithmetic
a1 = float(input("輸入第一個數字 :"))
a2 = float(input("輸入第二個數字 :"))
a3 = float(input("輸入第三個數字 :"))
a4 = float(input("輸入第四個數字 :"))
a5 = float(input("輸入第五個數字 :"))
a = myArithmetic.myAdd(a1,a2)
a = myArithmetic.myAdd(a,a3)
a = myArithmetic.myAdd(a,a4)
a = myArithmetic.myA... |
4cd6efe16e940e18e734a990221b4a376758348e | rwaidaAlmehanni/python_course | /get_started/Comprehensions/problem29.py | 269 | 4.09375 | 4 | #Write a function array to create an 2-dimensional array. The function should take both dimensions as arguments. Value of each element can be initialized to None:
def array(a,b):
x=[]
for i in range(b):
x.append(None)
print [x for y in range(int(a)) ]
array(2, 3) |
1b5fe0672fe6d8b36a071a6591395cec47eb682a | rwaidaAlmehanni/python_course | /get_started/lists/problem6.py | 182 | 4.25 | 4 | # Write a function reverse to reverse a list. Can you do this without using list slicing?
def reverse(array):
print array[::-1]
reverse([1,2,3,4,5])
#reverse(reverse([1,2,3,4,5])) |
e87ed31e6b726aa62e4d41a7d232a31225302800 | rwaidaAlmehanni/python_course | /get_started/Comprehensions/problem25.py | 262 | 4.03125 | 4 | #Python provides a built-in function map that applies a function to each element of a list. Provide an implementation for map using list comprehensions.
def mapfunc(fn,array):
print [fn(x) for x in array]
def square(x): return x * x
mapfunc(square, range(5))
|
7a3053cf2cb1aaa2e616e4be10f68e3e1c993b4f | rwaidaAlmehanni/python_course | /get_started/lists/problem14.py | 395 | 3.84375 | 4 | #Problem 14: Improve the unique function written in previous problems to take an optional key function as argument and use the return value of the key function to check for uniqueness.
def uniqueness(array,fn):
x=[]
array.sort(fn)
for i in array:
if i not in array[i+1:] :
x.append(fn(i))
print x
unique... |
622f93ea01a437ead0616c01901d593092a26927 | rwaidaAlmehanni/python_course | /get_started/Comprehensions/problem28.py | 218 | 4.21875 | 4 | #Write a function enumerate that takes a list and returns a list of tuples containing (index,item) for each item in the list.
def enumerate(array):
print [(array.index(y),y) for y in array]
enumerate(["a", "b", "c"]) |
6356480ddeca712bacc6ce76d0d4f4b1f4866374 | rwaidaAlmehanni/python_course | /get_started/lists/problem8.py | 383 | 3.859375 | 4 | #Write a function cumulative_product to compute cumulative product of a list of numbers.
# in js
# function cumulative_sum(array){
# for (var i=array.length-1;i>=0;i--){
# for(var j=0;j<i;j++){
# array[i]+=array[j]
# }
# }
# return array
# }
def cumulative_sum(array):
z=0
x=[]
for i in array:
x.... |
debdf7ffa39707764c50b961ac060033f7e8c515 | rwaidaAlmehanni/python_course | /get_started/itration/problem10.py | 124 | 3.515625 | 4 | def izip(arr1,arr2):
x=[]
for i in range(len(arr1)):
x.append((arr1[i],arr2[i]))
print x
izip([1,2,3],["a","b","c"])
|
5fb363c4b4037f0ecde6698dcc0b9e6dc8e308ed | rwaidaAlmehanni/python_course | /get_started/modules/problem7.py | 508 | 3.703125 | 4 | #Write a function make_slug that takes a name converts it into a slug. A slug is a string where spaces and special characters are replaced by a hyphen, typically used to create blog post URL from post title. It should also make sure there are no more than one hyphen in any place and there are no hyphens at the biginnin... |
86e745f640009e4a9ebe5b98543b172d72096c8c | rwaidaAlmehanni/python_course | /get_started/Comprehensions/explain_Comprehensions.py | 760 | 3.765625 | 4 | # it is a way to write operation inside [] in easy way like
# ex:
# a=range(10)
# a [0,1,2,3,4,5,6,7,8,9]
# [x for x in a] [0,1,2,3,4,5,6,7,8,9]
# [x+1 for x in a] [1,2,3,4,5,6,7,8,9,10]
# [x*x for x in a] [0,1,2,9,16,25,36,49,64,81]
# also we can use if:
# [x for x in a if x%2 == 0] [0,2,4,6,8]
# ex2:using with z... |
e49c2e2ae37ca4f682e55aa7a79b1181ada73e02 | rwaidaAlmehanni/python_course | /get_started/modules/problem12.py | 423 | 3.515625 | 4 | #Write a program mydoc.py to implement the functionality of pydoc. The program should take the module name as argument and print documentation for the module and each of the functions defined in that module.
import sys
def mydoc():
print sys.argv[1].__doc__
# f={}
# f[NAME]=sys.argv[1].NAME
# f[FILE]=sys.argv[1].FI... |
550f68a14c14aa71e795cd5908d02bddef4b71aa | aatsushiiitoe/flask-pj | /flask-begins/form.py | 448 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# 現在日付と時刻だけを出すプログラム
import datetime
class output_text :
# 初期処理
def __init__(self) :
print("start")
# 日付・時刻を出力する
def output_date(self, mode = 0) :
if mode == 1 :
#
print(datetime.date.today())
elif mode == 2 :
print(d... |
08ba141e31cd34822d2b75408aadf5d6b7ffdfe3 | psy4ak/5_lang_frequency | /lang_frequency.py | 588 | 3.6875 | 4 | import re
from collections import Counter
def load_data(filepath):
text_words = re.findall(r'\w+', open(filepath).read().lower())
return text_words
def get_most_frequent_words(text):
number_of_top = 10
top_text_words = Counter(text).most_common(number_of_top)
return top_text_words
if __name__ ... |
fe6c53fdb7d3a6fd9c72295453fc2d4ca8013538 | Zhaohuiprogrammer/python-study | /code/test_function.py | 776 | 3.984375 | 4 | #!/usr/bin/env python3
# _*_coding: utf-8_*_
# 寻找最大和最小的数字
def find_min_and_max(l):
if not isinstance(l, (list, tuple)):
raise TypeError("wrong type")
if len(l) == 0:
return None, None
if len(l) == 1:
return l[0], l[0]
min_num = l[0]
max_num = l[0]
for n in l:
if... |
28a6f77cddab8da561601b8f743f57d2e1da03bf | Nzembi123/function.py | /functions.py | 2,647 | 4.3125 | 4 | #Function is a block of code that runs only when called
def adding(num1, num2):
x = num1+num2
print(x)
adding(2,4)
#Multiplication
def multiplication():
num1 =15
num2 =30
sum = num2*num1
print(sum)
multiplication()
##arguments
def courses(*args):
for subject in args:
print(sub... |
ddadb9892d0d9e6f4a0e846fba24dc7170f833c9 | adamborbely/ccow | /for_1.py | 400 | 3.53125 | 4 | # Készítsünk programot, amely kiszámolja az első 100 db természetes szám összegét, majd kiírja az
# eredményt. (Az összeg kiszámolásához vezessünk be egy változót, amelyet a program elején kinullázunk,
# a ciklusmagban pedig mindig hozzáadjuk a ciklusváltozó értékét, tehát sorban az 1, 2, 3, 4, ..., 100
# számokat.)
s... |
44f09739b164d18975b37128d2624559bbe8e52e | nishana007/PYTHON- | /book.py | 4,097 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 11 16:36:44 2020
@author: NAVEENA
"""
import xml.etree.ElementTree as ET
def elementtree_to_dict(element):
node = dict()
text = element.text
if text is not None:
node['text'] = text ... |
52fe6ce8ec231c82274539887ca1e69cffa226db | ed1rac/lp2py | /aula03/pessoa.py | 615 | 3.59375 | 4 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
class Pessoa():
def __init__(self,nome,idade):
self.nome=nome
self.idade=idade
def cumprimentar(self):
return "Olá meu nome é "+self.nome
if __name__=="__main__":
renzo= Pessoa("Renzo",30)
print r... |
96410cd2678b127397adaba6810b310e39c3ba91 | amkv/KIFT | /src/server_src/myserver/badinput.py | 649 | 3.65625 | 4 | #! /usr/bin/python
# -*- coding: utf-8 -*-
import random
def badinput():
badinput = [
'I don\'t get it',
'NO!',
'Sorry',
'Marry me first!',
'I am too lazy today',
'Boring...',
'Go away!',
'Try again',
'Make me Great again',
'Something went wrong',
'I don\'t want to talk... |
999280bcea009885715fa49950c547a6000fdffd | RichardChangCA/LeetCodePractice | /136_Single_Number.py | 1,133 | 3.71875 | 4 | class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# new_nums = nums
# i = 0
# while(i<len(new_nums)):
# j = i + 1
# tag = 1
# while(j<len(new_nums)):
# if(new_num... |
81517e2709670ba0017dceef17a5fab75d8f5817 | panda1188/pal | /4.py | 266 | 4.0625 | 4 | #!/usr/bin/python3
num = int(input("enter the number: "))
#we need to import a number
for i in range(1,4):
# i is range from 1 to 4
for j in range(1,11):
#this is the range from 1 to 11
print(i,"x",j,"=",i*j)
#the result is seen after running the program
|
e214ac661d060b1ce887b15ad66ff44caac1947c | jubic/RP-Misc | /System Scripting/Problem15/6P/t50_xml1.py | 1,763 | 4.21875 | 4 | """
h2. XML from List of Dictionary
Create a function @xmlFromList@ that takes a list of dictionaries. The XML must have the root tag @<storage>@.
Each item in the dictionary should be put inside the @<container>@ tag. The dictionary can contain any keys (just make sure the keys are the same for all of the dictionar... |
865cb390eeff4a66ed5f2d2a807ed85fe4df2379 | jubic/RP-Misc | /System Scripting/Problem03/worksheet/SimpleMatchingWithRegex.py | 339 | 3.75 | 4 | import re
a = re.search("\d", "I need to buy 3 watermelons")
b = re.search("\d", "1 apple a day keeps the doctor away")
c = re.search("\d", "One apple a day keeps the doctor away")
if a:
print "FOUND"
else:
print "NOT FOUND"
if b:
print "FOUND"
else:
print "NOT FOUND"
if c:
print "FOUND"
else:
... |
13ee382b9c5a10c6b3a6db4cb8cf2e5148d5718d | jubic/RP-Misc | /System Scripting/Problem15/6P/t10_dict1.py | 520 | 4.0625 | 4 | """
h2. Dictionary Values to String
Write a function @getVals@ that takes a dictionary as an argument. Get all the values from the dictionary, sort them, and return them as a string with each value enclosed in a <> bracket.
bc. {- python -}
d = {"x":"y", "a":"b", "g":"h"}
print getVals(d)
# returns <b><h><y> (s... |
e5739fcfa91149f1f472192e445307d558b6fcbe | jubic/RP-Misc | /System Scripting/Problem03/worksheet/matchingExample5.py | 959 | 3.96875 | 4 | import re
# remember "\d" is equal to [0-9]
a = re.search("\d", "It's 6PM") # matched
b = re.search("\d", "Apple orange") # failed (no digits)
#
# remember "\s" is for "whitespace"
c = re.search("\s", "Apple orange") # matched (a space between Apple and orange)
d = re.search("\s", "Pineapple") # failed (no white... |
9aa94f9c1917a3e572c5e279c60133e9e0b6aa9d | jubic/RP-Misc | /System Scripting/Problem03/worksheet/anchoringExample2.py | 393 | 3.5625 | 4 | import re
date_good = "22 October 2010"
date_bad = "9922 October 201020000"
#
# Note the ^ and $ - match the pattern from the beginning of the string
# until the end of the string. Or in short, match the pattern for
# the entire string.
a = re.search("^\d{1,2}\s+[A-Z][a-z]+\s+\d{4}$", date_good) # matched
b = re.searc... |
d5caa2a03d816740ab7e7e336b0a84ea8d3e1462 | jubic/RP-Misc | /System Scripting/Problem02/worksheet/testwrite2.py | 240 | 3.609375 | 4 | # Open the file for writing. The previous content is deleted.
f = open("testwrite.txt", "wb")
data = ["one\r\n", "two\r\n"]
# Write the list to file
f.writelines(data)
# Close it to ensure the file is written to the storage (disk)
f.close() |
4a2ce6635442bfaf8555a1958b6dd06b1389d52d | jubic/RP-Misc | /System Scripting/Problem15/t40_db1.py | 1,533 | 4.53125 | 5 | """
h2. Putting Data into SQLite Database
Write a function @putData@ that takes 4 arguments as specified below:
# @dbname@ - a string that specifies the location of the database name
# @fnames@ - the list of first names
# @lnames@ - the list of last names corresponding to the first names list
# @ages@ - the list of... |
8ac8ef9b63495ec2678dbad87faa668c9d4d9924 | jubic/RP-Misc | /System Scripting/Problem15/t02_list3.py | 665 | 4.21875 | 4 | """
h2. Zip Two Lists into One
Write a function @zipper@ that takes 2 arguments.
Both arguments are lists of integers. The function must then create a new list to put the first item of the first list, followed by the first item of the second list. Then second item of the first list, followed by the second item in the... |
5deb5b1d13806ec89ab6485ef99e8f378c4f548e | jubic/RP-Misc | /System Scripting/Problem07/6P/solution_simple.py | 2,270 | 3.96875 | 4 | import csv
import sys
Schools = ("SIT", "STA", "SEG", "SOH", "SHL")
# Arguments:
# f: the file object. Use it later as f.write()
# school: is the school name "SIT", "STA", etc. Only prints data based on school
def xmlwriter(f, school):
# name all of the columns for schools.csv (the CSV file doesn't name the colum... |
77a2cd0599658d50d6771108c35dd1f06dbc9e5b | jubic/RP-Misc | /System Scripting/Problem15/6P/t31_email2.py | 1,450 | 3.625 | 4 | """
h2. Mail with Two Image Attachments
Write a function @mailImages@ that takes a list of image files to be attached on an email. The function should return the @MIMEMultipart@ email object.
Additionally, your email must have:
# From: joe@nopoly.dom
# To: bob@nopoly.dom
# Subject: Two Images
# The images are, and t... |
84bc609498599c8be771309ca6604d65612853cf | randyx/leetcode | /isValidSudoku.py | 814 | 3.53125 | 4 | class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
nums = 0
k = 0
list1 = [[0 for col in range(9)] for row in range(9)]
list2 = [[0 for col in range(9)] for row in range(9)]
list3 = [[0 for... |
582affcd4baf6c355328c147329175a1530cff51 | martamaj/LPTHW | /ex6.py | 765 | 3.859375 | 4 | # this defines x
x = "There are %d types of people." % 10
# this defines binary
binary = "binary"
# this defines do_not
do_not = "don't"
# this defines y, using binary and do_not
y = "Those who know %s and those who %s." % (binary, do_not)
# this prints x
print x
# this prints y
print y
# this prints a string wi... |
03d3e107e5fcc7dec7653bd94914a9c033faf4c5 | TheCYBORGIANpulkit/P342Ass2 | /Ass2_Py_Q3.py | 1,740 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
import csv
arrM = []
arrN = []
arrP = []
arrA = []
arrQ = []
for i in range(0,3):
arrP.insert(i,[0,0,0])
arrA.insert(i,[0,0,0])
arrQ.insert(i,[0,0,0])
#1st matrix
with open('M.csv') as csvdf:
csvr = csv.reader(csvdf)
for row in csvr:
for i... |
a08c9b2a1a80d11ab85f67ce4f433b50f3953be0 | GouriManoj/python | /ITT 205 Problem Solving using Python/Tutorial/add.py | 201 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 26 11:52:37 2020
@author: Gouri Manoj
"""
num1=input('Enter first number')
num2=input('Enter second number')
sum=float(num1)+float(num2)
print(sum) |
4c4bb3ad3c2b0a45b1b044891d10805fccabb614 | Montanaz0r/Skychallenge-Chapter_II | /I_write_my_programs_in_JSON/I_write_my_programs_in_JSON.py | 629 | 4.25 | 4 | import re
def sum_the_numbers(filename):
"""
A function that sum up all the numbers encountered in the file
:param filename: name of the file (str)
:return: sum of all numbers (int)
"""
with open(f'{filename}.txt', 'r') as file:
data = file.read()
results = re.findall(... |
3cca31c5eaffd4dbda0ad9af251279ff7438fe30 | sreshtha-pramanick/resume | /Assignments/assignment_1.py | 128 | 3.546875 | 4 | n=int(input("Enter the limit"))
a=0
b=1
print(a)
print(b)
for i in range(2,n):
t=a+b
print(t)
a=b
b=t
|
7b7217db413fa112c266287942996a45e74d68d3 | quasarbright/MachineLearning | /snake_q_cnn/tests.py | 1,569 | 3.890625 | 4 | import unittest
from game import *
class TestSnake(unittest.TestCase):
def setUp(self):
self.g = Game(5,5)
g = self.g
g.tail = [Vector(0,0)]
g.fruitPos = Vector(2,0)
def test_init(self):
self.assertEqual(self.g.tail, [Vector(0,0)])
self.assertEqual(self.g.fru... |
8d4cf36eb68228ecb0c41c468b1eaa6e1c0cd017 | thomasgeoff/Cracking-the-coding-interview | /01_String_unique.py | 601 | 3.875 | 4 | #1.String UNIQUE
def str_unique(str1):
# if len(str1)>26:
# return 'String is Unique'
c = 0
# print(str1.lower())
for i in str1.lower():
# print("i:",i)
if i.isalpha():
for j in str1.lower():
# print("j:",j)
if i==j:
c+=1... |
beaaff1569c17464bb006805d7f2f20ae0b7457a | SpikyClip/rosalind-solutions | /bioinformatics_stronghold/FIB_rabbits_and_recurrence_relations.py | 2,483 | 4.40625 | 4 | # url: http://rosalind.info/problems/fib/
# Problem
# A sequence is an ordered collection of objects (usually numbers), which
# are allowed to repeat. Sequences can be finite or infinite. Two examples
# are the finite sequence (π,−2–√,0,π) and the infinite sequence of odd
# numbers (1,3,5,7,9,…). We use the notatio... |
38c1ae61d68db0606a71e5afa368e1f5ad90ab3b | SpikyClip/rosalind-solutions | /python_village/INI6_dictionaries.py | 813 | 4.09375 | 4 | # url: http://rosalind.info/problems/ini6/
# Problem
# Given: A string s of length at most 10000 letters.
# Return: The number of occurrences of each word in s, where words are
# separated by spaces. Words are case-sensitive, and the lines in the
# output can be in any order.
def word_count(string):
unique_wor... |
e8bcb65bd9bb11fd4a11c030c0885dda1669c43b | SpikyClip/rosalind-solutions | /bioinformatics_stronghold/MRNA_inferring_mRNA_from_protein.py | 2,808 | 4.28125 | 4 | # url: http://rosalind.info/problems/mrna/
# Problem
# For positive integers a and n, a modulo n (written amodn in shorthand)
# is the remainder when a is divided by n. For example, 29mod11=7
# because 29=11×2+7.
# Modular arithmetic is the study of addition, subtraction, multiplication,
# and division with respect ... |
e421b78f4d1ac6e0995be9d3cc5058a2f086d42b | SpikyClip/rosalind-solutions | /bioinformatics_textbook_track/BA1C_reverse_complement.py | 368 | 3.921875 | 4 | def reverse_complement(seq):
'''Returns the reverse complement of a DNA nucleotide sequence'''
complement_table = str.maketrans('ATCG','TAGC')
complement_seq = seq[::-1].translate(complement_table)
return complement_seq
seq = 'GTACGCTGGAAAAAGCCTGAAAGCTTACT'.upper()
print(reverse_complement(seq))
# re... |
ebe76ce9a2cac30d3c2498942d39ba9b7e1d87e4 | SpikyClip/rosalind-solutions | /bioinformatics_stronghold/TRAN_transitions_and_transversions.py | 1,939 | 3.65625 | 4 | # url: http://rosalind.info/problems/tran/
# For DNA strings s1 and s2 having the same length, their
# transition/transversion ratio R(s1,s2) is the ratio of the total
# number of transitions to the total number of transversions, where
# symbol substitutions are inferred from mismatched corresponding
# symbols as when... |
ff1dddd7f081ef43b67db415bc507c90b5d5f1c5 | rmstar/python-test | /tree.py | 506 | 3.515625 | 4 | #!/usr/bin/env python3
from collections import defaultdict
def postorder(tree):
if not tree:
return
yield from postorder(tree['left'])
yield from postorder(tree['right'])
yield tree['value']
tree = lambda: defaultdict(tree)
T = tree()
T['value'] = '*'
T['left']['value'] = '+'
T['left']['left'][... |
1e0382442c4c5c2c87899e2084d88182bf589c11 | VIncentTetteh/Python-programming-basics | /my_math.py | 868 | 4.125 | 4 | import math
def calculate(enter, number1, number2):
print("choose from the list.")
print(" 1. ADD \n 2. SUBTRACT \n 3. MULTIPLY")
if enter == "add" or enter == "ADD":
#number1 = input("enter first number ")
#number2 = int(input(" enter second number "))
answer = number1 + number2
... |
5a3ef30e9acf4e8168361e646ca9124c65df4973 | edigar/pystime | /play_games.py | 277 | 3.640625 | 4 | import common
import hangman_game
import guessing_game
common.head("Escolha o seu jogo")
print("(1) Forca\n(2) Adivinhação")
game = int(input("Jogo: "))
if(game == 1):
hangman_game.play()
elif(game == 2):
guessing_game.play()
else:
print("Opção inválida")
|
56d65af575b30a6a2658ff94f4fe43b421a2a40c | isham-mohamed/python | /linklist.py | 540 | 3.765625 | 4 | class node:
def __init__(self,data=None):
self.data=data
self.next=None
class link:
def __init__(self):
self.head=node()
def append(self,data):
new_node =node(data)
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=new_node
def length(self):
cur= self.head
t=0
while cur.next!=None:
... |
1b358bd02b912043dafdc066ea5a2a542bdced5b | to-yuki/pythonLab-v3 | /ans/7/UDThread.py | 750 | 3.84375 | 4 | from threading import Thread
from time import sleep
# スレッド化する関数1
def thread1():
# 1秒間隔で 'T1' を表示
for i in range(0,10):
sleep(1)
print('[T1:' + str(i) + ']',end="",flush=True)
# スレッド化する関数2
def thread2():
# 2秒間隔で 'T2' を表示
for i in range(9,-1,-1):
sleep(1)
print('[T2:' + s... |
44e899390849c60c8132bff89ae092d1dd4885b7 | to-yuki/pythonLab-v3 | /ans/4/BMI2.py | 133 | 3.53125 | 4 | def bmi(weight,height):
return weight / (height * height)
weight = 75.0
height = 1.75
bmi_val = bmi(weight,height)
print(bmi_val)
|
9e3dbf46dc181a269216335c10726a82d1ad659f | to-yuki/pythonLab-v3 | /ans/4/Calculation.py | 324 | 4.375 | 4 | #-- Calc Function --#
def calc(val1,operator,val2):
if operator == '+':
return val1 + val2
elif operator == '-':
return val1 - val2
elif operator == '*':
return val1 * val2
elif operator == '/':
return val1 / val2
else:
raise ArithmeticError("Operator Err... |
62ce786f96330b2aff0b5259d0a11b03911bd6f9 | to-yuki/pythonLab-v3 | /sample/3/While.py | 63 | 3.640625 | 4 | a = 0
while a < 10:
print(a)
a += 1
else:
print('loop-end')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.