blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b737e0dc9e2362272d198b2364fd808e333d9d37 | cargarma/python-ejercicios | /condicionales.py | 381 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Utilización de IF
print("Programa de evaluación de notas de alumnos")
nota_alumno = input("Introduce la nota del alumno:")
def evaluacion(nota):
if nota < 0 or nota > 10:
return "Error en la nota"
else:
valoracion="aprobado"
if nota<5:
valoracion="suspenso... |
4a42450af059caffdbe97fbe76ceb443aef156f1 | katielkrieger/algorithms | /20170517_SumOfPairs_5kyu_Python/SumOfPairs.py | 833 | 3.65625 | 4 | def sum_pairs(ints, s):
dict = {ints[0]: s - ints[0]}
j = 1
while (j < len(ints)):
if ints[j] in dict.values():
return [s-ints[j],ints[j]]
dict[ints[j]] = s - ints[j]
j+=1
return None
# best practice:
# def sum_pairs(lst, s):
# cache = set()
# for i in lst:
... |
5e6c557a2ac2662d9838f19d1e738936b16612a1 | Shandmo/Struggle_Bus | /Chapters 1-8/cities.py | 1,208 | 4.40625 | 4 | ### 6-11 Cities ###
#use names of three cities as keys, store information about each city, include its country, population, and one fact.
cities = {
"Washington D.C.": {
"country": 'United States',
"population": 1_250_000,
"neat fact": "The \"D.C.\" part stands for District of Columb... |
18deabe68e3200f8e8df925995b01146c962957c | goksinan/Intro-to-PyTorch | /eg_3_nn_module.py | 1,189 | 3.640625 | 4 | import torch
from torch import nn
from torchvision import datasets, transforms
class Network(nn.Module):
def __init__(self):
super().__init__()
# Inputs to hidden layer linear transformation
self.hidden = nn.Linear(784, 256)
# Output layer, 10 units - one for each digit
sel... |
913d7bd51eafc76190dab45bd6d08712e38d452b | All3yp/Daily-Coding-Problem-Solutions | /Solutions/210.py | 1,267 | 4.28125 | 4 | """
Problem:
A Collatz sequence in mathematics can be defined as follows. Starting with any positive
integer:
If n is even, the next number in the sequence is n / 2
If n is odd, the next number in the sequence is 3n + 1 It is conjectured that every
such sequence eventually reaches the number 1. Test this conjecture.
... |
ce7f86a885e80e96d1e572ef0ae0fe9dde1a69fa | Krisva403/Discord_Bot | /games.py | 7,651 | 3.515625 | 4 | import random
# game Snakeeyes
class snakeeyes:
def __init__(self, players):
self.players = players
self.scores ={}
# used for only one player per round
self.turn_left ={}
# score-board
for player in players:
self.scores[player.id] = 0
... |
d71f366648343377ac6123504f8336b46dac4dec | Jennifer0606/Codewares | /8kyu/python/solved/ensure_question.py | 776 | 4.40625 | 4 | """
https://www.codewars.com/kata/5866fc43395d9138a7000006/train/python
Given a string, write a function that returns the string with a question mark ("?") appends to the end,
unless the original string ends with a question mark, in which case, returns the original string.
ensure_question("Yes") == "Yes?"
ensure_quest... |
a8ed2f221fba0b6153061f1a733155390b28320a | nikitakumar2017/Assignment-3 | /TuplesQuestion1.py | 119 | 4.3125 | 4 | '''Print a tuple in reverse order. '''
tup=(1,2,3,4,5)
tuprev=reversed(tup)
print("Reversed tuple is ",tuple(tuprev))
|
7e41f2afca4abd517bed47dbe87a48795e28b49f | zil-kiev/Python-Vladimir2 | /homework_2_6.py | 337 | 3.953125 | 4 | a = int (input('введите число а:'))
b = int (input('введите число b:'))
c = int (input('введите число с:'))
if a == b or a == c or b == c:
print('треугольник равнобедренный')
else:
print('треугольник не равнобедренный')
|
e49ba8662b6908b14f8d100c34a15520566c61e4 | akimi-yano/algorithm-practice | /lc/review_1200.MinimumAbsoluteDifference.py | 1,319 | 4.03125 | 4 | # 1200. Minimum Absolute Difference
# Easy
# 1038
# 47
# Add to List
# Share
# Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.
# Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows
# a, b are from... |
e4593187568d37163318ffe847b427b1dfe9ed9b | tarunkant/exercism_python | /pangram/pangram.py | 198 | 3.875 | 4 | sentence= raw_input("give a sentence ")
sentence= sentence.replace(' ','')
if set(sentence.lower()) >= set('abcdefghijklmnopqrstuvwxyz'):
print"It is pangram"
else: print"It is not pangram"
|
611fd03a850ba534f2cb3abcf2e10ed8d9cd6325 | idiego209/python_exercises | /reverse_string/reverse_string.py | 785 | 4.21875 | 4 | #!/usr/bin/env python
# https://leetcode.com/problems/reverse-string/
# reverse_string.py
# Write a function that reverses a string. The input string is given as
# an array of characters char[]. Do not allocate extra space for another
# array, you must do this by modifying the input array in-place with
# O(1) extra me... |
e3a3f668d3ca5ef8c1827287a8090d7e70b1f4b9 | mau-vela/PythonClass-2015 | /Class3-ErrorsTesting/ordinaltest.py | 578 | 3.578125 | 4 | import unittest
import ordinal
class Testordinal(unittest.TestCase):
def setUp(self):
self.value = 1
def test_first(self):
self.assertEqual(ordinal.ordinal(self.value), "1st")
def test_second(self):
self.assertEqual(ordinal.ordinal(2), "2nd")
def test_third(self):
self.assertEqual(ordinal.ordinal(3), "3... |
487f37b9e463d398b35ea186c82019438c03dbc6 | lingxueli/CodingBook | /Data Structure/BinarySearchTreeOrBinarySearch.py | 1,178 | 3.8125 | 4 | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder(node):
if not node:
return
inorder(node.left)
print(node.val)
inorder(node.right)
def preorder(node):
if not node:
return
print(node.val)
preorder(node.left)
... |
877a679d8b8e24d5600be0fd47729c9b9c94bb34 | oluwafemi2016/Analytics | /Python_Activities.py | 23,436 | 4.0625 | 4 |
# coding: utf-8
# ### Activity 1: The goal of this code is to extract numbers in a text document and sum all the numbers together
# In[3]:
#Importing regular expression library
import re
# In[69]:
#get the 2D array containing array of numbers for each line
handle = open("regex_sum_1119177.txt")
numlist = list(... |
a4d85233ecb8ddfe6a01219c7ce716a61c22d7a6 | ashnaagrawal/python | /avg.py | 173 | 3.953125 | 4 | print('THis program calculates the avg of two numbers.');
num1 = 4;
num2 = 8;
print('the average of', num1, ' and' , num2);
print('The average is:', (num1 + num2)/2 );
|
afd8fcfbdd3fbaee6c1a7604a51bb974a551033f | yunnyisgood/python-oop | /encapsulation/grade.py | 1,256 | 3.875 | 4 | class Grade:
def __init__(self, kor, math, eng):
self.kor = kor
self.math = math
self.eng = eng
def sum(self):
return self.kor + self.math + self.eng
def avg(self):
return self.sum()/3
def get_grade(self):
score = int(self.avg())
# grade = ''
... |
f0fbb98078255ac9eb12099001d3b275e1ebb79a | tripathysamapika5/dsa | /queue/queue.py | 1,968 | 4.125 | 4 | class Queue:
def __init__(self, capacity):
self.front, self.rear = -1,-1
self.capacity = capacity
self.queue = []
def isFull(self):
return self.rear + 1 == self.capacity;
def isEmpty(self):
return self.front == -1 and self.rear == -1
def enqueue... |
f84716f1997a09c8db4ade4f6db7b5e718d74869 | mccarvik/cookbook_python | /7_functions/7_capture_vars_anon_funcs.py | 567 | 4 | 4 |
x =10
a = lambda y:x+y
x=20
b= lambda y:x+y
# "x" edit affects outcome
print(a(10))
print(b(10))
x = 15
print(a(10))
x=3
print(a(10))
x=10
# can capture it and hold it by defining it as a default value:
a = lambda y,x=x : x+y
x = 20
b = lambda y,x=x : x+y
print(a(10))
print(b(10))
funcs = [lambda x: x+n for n in r... |
a0d4a4636d5f8b25c4a39ff5649b75e755fd1330 | zioan/list_comprehensions | /conditions.py | 593 | 3.578125 | 4 | temps = [221, 234, 340, -9999, 230]
new_temps = [temp / 10 if temp != -9999 else 0 for temp in temps ]
#-9999 is changed with 0
print(new_temps)
#### exercices 1
def foo(list):
new_list = []
for i in list:
if isinstance(i, int):
new_list.append(i)
else:
new_list.append(0)
return(new_list)
... |
7c573b8d99321b4e3152891e1b20749a2795a443 | Kirktopode/Python-Homework | /3Program2.py | 893 | 3.90625 | 4 | grade = raw_input("Gimme a grade between 0.0 and 1.0: ")
try:
g = float(grade)
if g > 1.0:
print "Yeah, you could never have gotten more than 100%. Nice try, cheater."
elif g >= 0.9:
print "An A. Whoopdeedoo, go slap it on the fridge at home so mommy and daddy can be proud."
elif g >= 0.... |
d0e641290717078c7ba0c1ffb866dad8df817c23 | boknowswiki/mytraning | /lintcode/python/0969_longest_repeating_substring.py | 1,072 | 3.640625 | 4 |
# hash , binary search
from collections import defaultdict
class Solution:
"""
@param str: The input string
@param k: The repeated times
@return: The answer
"""
def longestRepeatingSubsequenceII(self, input_str, k):
# Write your code here
length = len(input_str)
start,... |
c313781a6cf3d3aa80edabcb918122bbb3f5a940 | RyanNoelk/Sudoku | /common/solver.py | 4,254 | 3.828125 | 4 | #!/usr/bin/env python
# encoding: utf-8
from math import sqrt
from copy import deepcopy
class Solver:
"""Given a raw, unsolved puzzle, this class with return a solved puzzle.
raw_puzzle = [
[0,7,8,5,6,0,1,0,0],
[0,2,3,0,0,0,5,7,0],
[0,0,0,0,0,2,6,0,0],
[7,... |
5ed921042deccca7a57b98b845b6633ee7a35516 | quigsml/PythonTrainingFiles | /Part1_IntroProgramming/Chapter9_Files/Chapter9_Practice.py | 1,029 | 4.0625 | 4 | import os
# "r" open a file for reading only
# "w" opens for writing only. Overites existing or creates new
# "w+" opens for reading & writing. overwrites existing or creates new.
#st = open("st.txt", "w")
#st.write("Hi from Python!")
#st.close()
# use with-statement to automatically close file. f is just a variable... |
124c3499ef5bd5cad01e8a680f10eb2443f3c7b3 | codigoenlaweb/calculator | /src/main.py | 3,887 | 3.875 | 4 | from tkinter import *
from tkinter import font
from typing import Sized
root = Tk()
root.title("calculator")
# VARIABLES
i = 0
# FUNCTION
# ADD INPUT
def click_button(e):
global i
e_text.insert(i, e)
i += 1
# REMOVE INPUT
def clean():
global i
e_text.delete(0, END)
i = 0
def result()... |
7129402aa315d39339923b257b07b99db67a0985 | chenxingyuoo/learn | /python_learn/廖雪峰python/10.进程和线程/2.多线程/2.Lock.py | 1,302 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time, threading
# 假定这是你的银行存款:
balance = 0
def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n
def run_thread(n):
for i in range(100000):
change_it(n)
t1 = threading.Thread(target=run_thread, args... |
b168ddbb428e378710c177eadd4d1f5047d174ed | SSolomevich/Acmp_Python | /acmp/023.py | 101 | 3.71875 | 4 | a=int(input())
summ=0
for b in range(a):
if (b>0 and a%b==0):
summ=summ+b
print(summ+a)
|
444dca5269f336f8d4608473b5fe6364c46b7922 | gayathrig269/Two-Pointers-1 | /sort_colors.py | 989 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
TC : O(N) where N is the length of array given
SC: O(1) as we are not using any extra space
"""
class Solution:
def sortColors(self, nums: List[int]) -> None:
#edge case
if not nums or len(nums) == 0:
return -1
l = 0
m = 0
h... |
a6210a92fdcdeb58c9f3a389d9809548c6c5bdc8 | marygeo91/asteroids | /second.py | 15,301 | 3.5 | 4 | #!/usr/bin/env python
import numpy as np
import timeit as ti
import scipy.stats as st
import scipy.integrate as ig
import matplotlib.pyplot as pl
import matplotlib.ticker as tk
def euler_forward(previous=np.array([[1.0], [0.0]]), step=1e-3):
'''
Using the Euler Forward Method written in the matrix form for t... |
0b6f03088fdb1e09b169efe882a33731173f58f3 | kashishy/MLTraining | /mlpackage01/MLPractical61.py | 2,646 | 3.640625 | 4 | # Spot checking is used to check which model is best for the given data
import pandas as pd
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
import warnings
warnings.filterwarnings(action='ignore')
filename = 'indians-diabetes.data.csv'
hnames = ['preg', 'plas', 'pres', 'sk... |
2965803d3a9b80ad371c3fd0a0f913c1721fdef6 | kyleclo/practice | /stacks-and-queues/stacks-and-queues.py | 1,313 | 4 | 4 | """
Relation between Stacks and Queues
"""
from collections import deque
class QueueUsingTwoStacks:
def __init__(self):
self.outbox = []
self.inbox = []
def dequeue(self):
if len(self.outbox) == 0:
while len(self.inbox) > 0:
self.outbox.append(self.inbox... |
a07516ebb0212f8799774801bf76d76b46bcba12 | mariasykpotter/Maze | /maze.py | 5,813 | 4.15625 | 4 | # Implements the Maze ADT using a 2-D array.
from arrays import Array2D
from lliststack import Stack
class Maze:
'''Class for Maze representation.Defines constants to represent contents of the maze cells.'''
MAZE_WALL = " *"
PATH_TOKEN = " x"
TRIED_TOKEN = " o"
def __init__(self, n_rows, n_col... |
847e65703e1be5951386f88cbfe47f89eb7835aa | paco-portada/Python | /ficherosPython/ejercicio1.py | 986 | 3.515625 | 4 | #_*_ coding=UTF-8 _*_
# ejercicio1.py
# Programa que guarda en un fichero con nombre primos.dat los
# números primos que hay entre 1 y 500.
# @author Alvaro Garcia Fuentes
from io import open
# Funcion para determinar si un número es primo
# @param i
# @return boolean
def esPrimo( i ):
for k in range( 2 , int(... |
ad423e7d08db27f93ac001dca248230071fbb358 | Batto1300/renewable-energy-analysis | /renewable_energy_analysis/cleaning/energy_consumption.py | 2,245 | 3.828125 | 4 | """ This script cleans the original data set
containing the energy consumption figures
for the world countries.
Firsly, we remove some redundant rows.
Secondly, we filter the dataset for those
countries and years which are common to
all datasets.
"""
import pandas as pd
# import class wit... |
9378bbf9f1164c5e1a49e31558581aae21b382e3 | SleepingActor/Example | /example.py | 4,890 | 3.71875 | 4 | ########################################################################################################################
i = int(input("процентная ставка в год: ")) # годовая процентная ставка
i = i / 100
n = int(input("кол-во месяцев: ")) # кол-во месяцев
S = int(input("сумма кредита: ")) # сумма кредита
add = 0
# i =... |
491e27e4ed9b0449210bef4b4ca0421935646397 | abinashdash17/python_progs | /ex22.py | 267 | 3.765625 | 4 | x = input("Enter a sentence: ")
y = x.split(" ")
y_set = set(y)
wc = {}
for word in y_set :
count = 0
for item in y :
if word == item :
count += 1
wc[word] = count
for word in sorted(y_set) :
print("{} : {}".format(word,wc[word]))
|
0facc740467ff83c0f817c12420bd0cd5c19efb0 | bearzk/cracking-the-coding-interview | /chapter-11-sorting-and-searching/src/extend_sort.py | 715 | 3.953125 | 4 | # coding: utf-8
def merge_sort(a, left, mid, right):
cloned = a[:]
cnt = left
leftCnt = left
rightCnt = mid
while leftCnt < mid and rightCnt <= right:
if cloned[leftCnt] < cloned[rightCnt]:
a[cnt] = cloned[leftCnt]
leftCnt += 1
else:
a[cnt] = cl... |
c4b40fd4e0deeca1d7754b32355437c98ee975de | Elmar999/Machine-learning | /churn_telecom_dataset.py | 3,630 | 3.9375 | 4 |
# Customer attrition, also known as customer churn, customer turnover, or customer defection, is the loss of clients or customers.
#predictive analytics use churn prediction models that predict customer churn by assessing their propensity of risk to churn.
# import warnings filter
from warnings import simplefi... |
74cf66b6a01f315aa514f8351f90d991afac1646 | franky3020/Arithmetic_method_class_HW_1 | /BubbleSort.py | 390 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 5 16:56:22 2020
@author: frrr
"""
def is_over_BubbleSort(randomList:list)->bool:
for i in range(len(randomList)):
for j in range(len(randomList)):
if randomList[j] > randomList[i]:
tmp = randomList[j]
randomList[j]... |
f4f6bf40cda8253ca494485d2dc7951b9a932f92 | HenriqueNO/Python-cursoemvideo | /Desafios/Teoria#011.py | 304 | 3.625 | 4 | nome = str(input('Qual é o seu nome?')).strip()
cores = {'limpa':'\033[m',
'azul':'\033[1;34m',
'amarelo sub':'\033[4;34m',
'verde':'\033[1;32m',
'amarelo neg':'\033[1;33m'}
print('Olá! Muito prazer em te conhcer, {}{}{}'.format(cores['azul'], nome, cores['limpa'])) |
1949244339f199d1acb3339113ec7c32391e3cb7 | mckinler1639/CTI110 | /P2HW1_PoundsKilograms_RobertMckinley.py | 363 | 4.1875 | 4 | # Convert pounds into kilograms
# 15 February 2019
# CTI-110 P2HWI - Pounds to Kilograms Converter
# Robert Mckinley
#
# ask the user to enter a number
pounds=int(input("how many pounds you want to convert?"))
# Convert the formula
kg=pounds/2.2046
# Display the converted number
# put in code for two decimal ... |
d2ff9cdc0e751a81d0857bb78c39a57d664e2e6b | GDUTwuchao/leetcode_jianzhioffer | /python剑指offer/对称二叉树.py | 1,004 | 3.921875 | 4 | '''
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
思路:
首先根节点以及其左右子树,
左子树的左子树和右子树的右子树相同
左子树的右子树和右子树的左子树相同即可,采用递归
非递归也可,采用栈或队列存取各级子树根节点
'''
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymme... |
94b074e06b893e09c17ce897b92db857ecf1586a | BrettParker97/CodingProblems | /2021-06-28/sol.py | 1,401 | 3.59375 | 4 | def closest_nums(nums, k, x):
#find closest value in list of nums
rightIndex = None
leftIndex = None
for y in range(len(nums)):
if nums[y] < x or leftIndex == None:
leftIndex = y
elif nums[y] > x:
rightIndex = y
break
#increase/decrease val to... |
c9cbd675cfb5b325b0e266f1a9e42fc72789cd22 | DanielFuentes17083/Lab4 | /GraphInt.py | 2,609 | 3.65625 | 4 | from tkinter import * #https://likegeeks.com/es/ejemplos-de-la-gui-de-python/
from tkinter import messagebox #importa los mensajes de error
import serial #libreria de comunicacion serial
import struct #para convertir valores a formatos deseados
import time #para refrescar valores
while(1): #Se inicializa la conexion c... |
e5ed1bfa9986d59fee741155eedae9a913fee499 | abdullahf97/Detailed-Assignment-01 | /Practice Problem 3.33.py | 164 | 3.828125 | 4 | print('Practoce Problem 3.33')
def reverse_string(word):
return word[::-1]
i = reverse_string('dim')
print(i)
g = reverse_string('bad')
print(g)
|
26f15f34161f52f81a624a8eba787eade847b0f0 | infosergio2020/python-practice-review | /practica-03/p-07.py | 1,132 | 3.75 | 4 |
# Utilizar como estructura de datos de referencia la generada en el ejercicio 3 y generar funciones
# que ejecuten lo siguiente:
# (a) Imprimir los 10 primeros puntajes de la estructura.
# (b) Imprimir los datos de los usuarios ordenados alfabéticamente por apellido.
# (c) Imprimir los datos de los usuarios ordenados ... |
2f86cb060490cfc1a82f95d9ad256953aba8c45b | UWPCE-PythonCert-ClassRepos/Python210_Fall2019 | /students/jammy_chong/lesson04/Mailroom02.py | 3,797 | 3.78125 | 4 | import os
import pathlib
import datetime
donor_list = dict()
def main_menu(dispatch_dict):
while True:
print(main_prompt)
action = input("")
if action in dispatch_dict:
dispatch_dict[action]()
if action == "q":
break
def add_donor(name, total=0, gif... |
b5bb9cb895aad31d9fc18b2a792286271886e6f1 | woody0907/pythonpractice | /sumbmation.py | 864 | 3.8125 | 4 | a = [1,2,3,4,5]
def custom_sumbmation():
sum = 0
for i in a:
sum += i
print(sum)
def recursion_sumbmation(l):
if not l:
return 0
return l[0]+recursion_sumbmation(l[1:])
def ternary_sumbmation(l):
return 0 if not l else l[0]+ternary_sumbmation(l[1:])
def ternary_sumbmation1(l):... |
730b5f47c49a785f5fbb42a8c16b8f6c78d59e96 | jakovlev-fedor/tms_python_fedor_jakovlev | /02_lesson/08_conditional_operators.py | 2,456 | 4.25 | 4 | """"""
"""
---------------------------------
1. Используя функцию > придумать:
3 примера когда результат будет равен True
3 примера когда результат будет равен False
"""
print('#01---------------')
print(100 > 1)
print(1000 > 100)
print(1 > 0.1)
print(1 > 100)
print(100 > 1000)
print(0.1 > 1)
print()
"""
----... |
7b204aa0b1ff134dc2f53d89cb74aed7cea6b154 | ydong08/PythonCode | /sourcecode/05/5.1/call_switch.py | 788 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import switch_class
operator = "+"
x = 1
y = 2
for case in switch(operator): # switchֻfor inѭ
if case('+'):
print x + y
break
if case('-'):
print x - y
break
if case('*'):
print x * y
break
if case('/'):
... |
cb34dd71a8ddf9f1396ea172c4f7912038618b7b | mayconrcampos/Python-Curso-em-Video | /Exercicios/Exercício - 029 - Radar Eletrônico.py | 947 | 4.25 | 4 | velocidade = float(input('Digite a velocidade em Km/h: '))
if velocidade > 80:
multa = (velocidade - 80) * 7
print('MULTADO! Você atingiu velocidade superior a 80km/h')
print('Você deverá pagar uma multa de R$ {}'.format(multa))
print('Parabéns, você atrapalha todo mundo!')
print('Seu carro será recolhido a... |
8022b4b9be23e14a7d5a48fb741d3b4c75255888 | jonjelinek/euler-python | /problems/7.py | 803 | 4 | 4 | # finding the nth prime number
# given the first 6 prime numbers: 2,3,5,7,11,13 what is the 10,001 prime number
known_primes = [2, 3, 5, 7, 11, 13]
def nth_prime_number(n):
if len(known_primes) >= n:
return known_primes[n-1]
current_number = known_primes[-1] + 1
while len(known_primes) < n:
... |
9da4f2dfb70f10b9b15b5a72a3b5a7011afba560 | jaychsu/algorithm | /lintcode/111_climbing_stairs.py | 1,119 | 3.953125 | 4 | """
DP: rolling array with `n + 1`
"""
class Solution:
"""
@param n: An integer
@return: An integer
"""
def climbStairs(self, n):
if n <= 0:
return 0
dp = [0] * 3
pre2, pre1, curr = 0, 0, 1
dp[0] = dp[1] = 1
for i in range(2, n + 1):
... |
17bf3c0bbd6ca7587e8f5860aa6602f31fde8702 | btemovska/ListsAndTuples | /Enumerate_example.py | 261 | 4.15625 | 4 | for index, character in enumerate("abcdefgh"):
print(index, character)
print(index + 1, character)
# 0 a
# 1 b
# 2 c
# 3 d
# 4 e
# 5 f
# 6 g
# 7 h
# the index number matches the character in the string
# #1 a
# 2 b
# 3 c
# 4 d
# 5 e
# 6 f
# 7 g
# 8 h
|
fd6c4e63dd4359cc80b5c16b087263cd90302b0c | enochc/ScoutTrackerUltimate | /scripts/dateutil.py | 470 | 4.15625 | 4 | import datetime
today = datetime.datetime.today()
def addMonth(months, date):
m=0
month = date.month
day = date.day
mod = -1 if months<0 else 1
while m < abs(months):
date = date+datetime.timedelta(days=mod)
if month != date.month:
m+=1
month = date.month
... |
07bbf7724e13dfbc0f6bc9e18332afc28099626f | chendamowang/learnpythonthehardway | /ex14.py | 666 | 3.78125 | 4 | from sys import argv
script, user_name, bb = argv
prompt = '>'
print "Hi %s I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
print "Where do you lives %s?" % user_name
lives = raw_input (prompt)
print "What kind o... |
c9dc5c1a9b54d1892e02f13d5cd54353036ec841 | edureimberg/learning_python | /ternary.py | 216 | 3.5 | 4 | order_total = 247
#classic if/else
if order_total > 100:
discount = 25
else:
discount = 0
print(order_total,discount)
#ternary operator
discount = 25 if order_total > 100 else 0
print(order_total,discount) |
1bd57c07fe511f5c500b290e05db7e3ba703d36d | yani-valeva/Programming-Basics-Python | /Calculations/RadiansToDegrees.py | 77 | 3.65625 | 4 | import math
rad = float(input())
deg = rad * 180 / math.pi
print(round(deg)); |
b0c9bed8704eac1e7970f50ed980167d1b78262a | MiguelSilva96/sdle-practice | /pref_attachment/pref.py | 1,871 | 3.828125 | 4 | '''
Generate edges on a graph using preferential
attachment. The first node is selected randomly and
the second is selected using preferential attachment.
'''
import networkx as nx
import random as rand
import sys
import matplotlib.pyplot as plt
NODES = 100
STEP = 5
list_to_randomize = []
def add_preferential_edge(n... |
47f21dd836ae34ad4a31fd5b787299ee13825208 | sennagardner/P2_SP20 | /Notes/NotesA/03_loops.py | 722 | 4.21875 | 4 | # More on loops
# Basic FOR loop
for i in range(5, 51, 5):
print(i, end=" ")
print()
# RANGE function (alternative for comprehension)
my_list = [x for x in range(100)]
print(my_list)
my_list = list(range(100)) # iterable
print(my_list)
# BREAK (breaks out of the loop)
for number in my_list:
if number > 10:
... |
46c2a174f05eb63b067376ea5ef60788b257cc6b | kanisque/Programming | /betterPythonPractices.py | 2,858 | 4.34375 | 4 | #Better Python practices
#Shift space to run file in terminal (or set shortcut first)
names = ['bob','ross','mat','jack','karen','jess']
colors = ['red','green','blue','yellow','grey','white','black']
#iterating normally
for color in colors:
print(color)
print("----------------")
#iterating in reverse
for color... |
8b5c6733e7a74468c8965e93092cf6f68ccfde8f | ryan-c44/Python-Assignments | /Python Assignments/Assignment1.py | 4,255 | 4.375 | 4 | # Ryan Castles, 6433236, CSIT110
# Question 1
print("Question 1. \n")
#Get input from user for title and author.
song_title = input("Your favourite song title: ")
song_author = input("Your favourite song author: ")
print()
#print the string using string addition.
print("Using string addition")
print("Your favourit... |
5973ab0cdd485705652ea453316124f6fd18a1dd | gohar67/IntroToPython | /Practice/lecture4/practice4.py | 185 | 3.890625 | 4 | d = {'name': 'Armen', 'age': 15, 'grades': [10, 8,8, 4, 6, 7]}
if 'weight' not in d:
n = int(input('write a number: '))
d['weight'] = n
print(d)
else:
print(d['weight']) |
092b2594f9159f72119349177487a3c0ffe8ebde | kronecker08/Data-Structures-and-Algorithm----Udacity | /submit/Task4.py | 1,306 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
call_outgoing = []
call_incoming = []
fo... |
a16a2c04314f8701514b1167c4eae2440022f7b5 | apoorvkk/LeetCodeSolutions | /problems/bin_tree_pruning.py | 813 | 3.90625 | 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 pruneTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root is None:
... |
701131e192bcc629557833cadb5509d02b04dff0 | VibhorSaini88/Assignments | /Assignment04.py | 2,032 | 4.46875 | 4 | #(Q.1)- Write a program to create a tuple with different data types and do the following operations.
# Find the length of tuples
tuple = ("tuple","false",3.2,1)
print(tuple)
print(len(tuple))
#(Q.2)-Find largest and smallest elements of a tuples.
t=(8,9,2,7,1)
print(t)
print(max(t))
print(min(t))
#(Q.3)- Write a pr... |
683c4f57a004cce69b09407c99ce867fd471e32c | erickjsantofimioj/ParcialHerramientasComputacionales | /CalculadoraDescuento.py | 763 | 3.953125 | 4 | print('!!!!!Bienvenido a su cafeteria buen sabor!!!!!')
cedula = input('Por favor digite su numero de cedula: (solo números aqui): ')
rol = input('Por favor digite su rol (Estudiante o Profesor): ')
codigo = input('Digite el codigo del producto: ')
cantidad = int(input('Digite la cantidad de unidades que llevará: '... |
63ad3afe759bb7919a7e3c999452c22f777895d1 | ledbagholberton/holbertonschool-machine_learning | /math/0x05-advanced_linear_algebra/0-determinant.py | 1,358 | 4.40625 | 4 | #!/usr/bin/env python3
"""Function that calculates the determinant of a matrix:
matrix is a list of lists whose determinant should be calculated
If matrix is not a list of lists, raise a TypeError with the
message matrix must be a list of lists
If matrix is not square, raise a ValueError with the message
matrix... |
bac52f55bdaed00ac76279f0ca1bc8a25fc42b12 | bedros-bzdigian/intro-to-python | /week 4/pratical/problem7.py | 84 | 3.59375 | 4 | for x in range(1,21):
if (x%3 == 0) and (x%5 == 0):
break
print (x) |
c1a562a6b82aa8d6cf9a4c3b3b2ea9429e91e0fb | yograjshisode/PythonRepository | /Rocpprsci.py | 3,133 | 4.15625 | 4 | '''Rock, paper, scissors, also know as roshambo, is a simple child's game that is frequently used to settle disputes.
In the game, a rock breaks the scissors, the scissors cut the paper, and the paper covers the rock. Each option is
equally likely to prevail over another. If the players choose the same object a draw is... |
dac461cd6cd6f88947fbf0a0551cfd8b1a80a5a8 | StefanDimitrovDimitrov/Python_Basic | /01. First-Steps in Codding Lab+Exr/06.str_num_concatination.py | 233 | 3.78125 | 4 | def str_num_concat(f_name, l_name, age, town):
print(f"You are {f_name} {l_name},a {age}-years old person from {town}.")
f_name = input()
l_name = input()
age = input()
town = input()
str_num_concat(f_name, l_name, age, town)
|
35245d908e57b04b65f81fff8073fc90d7ade45f | WiktorSa/Operating-Systems | /OS1/algorithms/RR.py | 2,090 | 3.703125 | 4 | import collections
from algorithms.Algorithm import Algorithm
# Round Robin
class RR(Algorithm):
def __init__(self, no_simulations: int, quant: int):
super().__init__(no_simulations)
self.quant = quant
def perform_simulation(self, processes: collections.deque):
overall_waiting_time = ... |
b384ebea193eec83a0b46b678f3480799aef9f67 | aviolette/aoc2020 | /elves.py | 559 | 3.65625 | 4 | def striplines(file_name):
for line in open(file_name, "r"):
line = line.strip()
yield line
def intlines(filename):
for line in striplines(filename):
yield int(line)
def stripsort(file_name, func):
lines = [func(line) for line in striplines(file_name)]
lines.sort()
return... |
2bc6e52b0907409e0737bada10e72881edbae844 | byted/AdventOfCode-2020 | /10/calc.py | 1,976 | 4.0625 | 4 | import sys
import re
with open('input.txt') as f:
voltages = sorted([int(l) for l in f.readlines()])
one_counter = 0
three_counter = 0
current_out = 0
target_range = list(range(current_out+1, current_out+3+1))
for vix, v in enumerate(voltages):
if v > target_range[-1]:
print(f'no fitting adapter')
... |
0427d34457f455ae3f9398d355063616d2cbdb6d | snolbo/TDT4113 | /ex2 rockpaperscissor/PlayerTypes.py | 4,540 | 3.953125 | 4 | import random
import numpy as np
class Player:
dict_str2num = {"rock": 0, "paper": 1, "scissor": 2}
dict_num2str = {0:"rock",1:"paper",2:"scissor"}
def __init__(self):
self.chosen_action = None
def choose_action(self):
choice = input("Rock, Paper or Scissor?: ")
choice = choic... |
0ce9e6c8527d288c8e3604bfe388d590e9497906 | liwang0904/Deep-Learning | /Statistical Methods for Machine Learning/Chapter 6/6.4.5_python_choice.py | 292 | 3.65625 | 4 | from random import seed
from random import choice
seed(1)
sequence = [i for i in range(20)]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
print(sequence)
for _ in range(5):
selection = choice(sequence)
# 4
# 18
# 2
# 8
# 3
print(selection)
|
1ea72be3e24bb59336cba9ebec2ff1aa0b63d230 | SS4G/AlgorithmTraining | /exercise/leetcode/python_src/by2017_Sep/Leet274.py | 433 | 3.609375 | 4 | class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
citations.sort(reverse=True)
h = 0
for i in range(len(citations)):
if citations[i] >= i + 1:
h += 1
else:
... |
9c8b592cdcd9e7cf9d130f80d738c2bae60292e6 | deathboydmi/machine-learning-course | /preproc.py | 4,703 | 3.515625 | 4 | # To add a new cell, type '#%%'
# To add a new markdown cell, type '#%% [markdown]'
# %% [markdown]
# # Best Artworks of All Time
# ## Collection of Paintings of the 50 Most Influential Artists of All Time
# ### https://www.kaggle.com/ikarus777/best-artworks-of-all-time
#
# I am going to solve the problem of recognizin... |
75e21f0ce5ade18a1bc9c89e4edb44129038d306 | Gladarfin/Practice-Python | /turtle-tasks-master/turtle_10.py | 252 | 4.3125 | 4 | import turtle
turtle.shape('turtle')
def draw_circle(direction):
step=2*direction
for i in range(180):
turtle.forward(2)
turtle.left(step)
for i in range(0, 3, 1):
draw_circle(1)
draw_circle(-1)
turtle.right(60)
|
e8386a2b36e4ab7e4ad29899ddc62d63c5a899cc | emmas0507/leetcode | /linked_list_cycle_2.py | 655 | 4.0625 | 4 | class Node(object):
def __init__(self, value, next=None):
self.value = value
self.next = next
def linked_list_cycle_2(list):
slow = list
fast = list
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow.value == fast.val... |
572ac5469dd94fbf3a6e7879dda765e66a94020a | tzyl/hackerrank-python | /week_of_code/31/colliding_circles.py | 6,727 | 4.28125 | 4 | from math import pi
def calculate_expected_square_iterative(n, k):
"""Calculates the expected square of the size of a randomly picked final
component. Equivalent to all radii being 1."""
# Conditioning on first step we just solve the case 1, 1, 1,..., 1, 2.
x = 1
for i in range(k):
... |
a42beb3c69a30bcfd7c660d18a702b484d8c1172 | inovei6un/SoftUni-Studies-1 | /FirstStepsInPython/Advanced/Lab/Multidimensional_Lists/01_Sum_Matrix_Elements.py | 511 | 3.59375 | 4 | """
3, 6
7, 1, 3, 3, 2, 1
1, 3, 9, 8, 5, 6
4, 6, 7, 9, 1, 0
"""
# # 01 solution
# n_rows, m_column = [int(x) for x in input().split(', ')]
# matrix = [[int(y) for y in input().split(', ')] for x in range(n_rows)]
# print(sum(sum(row) for row in matrix))
# print(matrix)
# # 02 solution
n_rows, m_column = [int(x) for x ... |
374b23dc02ffbca702994b7b63230c16de448689 | juleskuehn/comp4107 | /A3/q3.py | 4,762 | 4.03125 | 4 |
'''
COMP4107 fall 2018 assignment 3 question 3
Student name: Yunkai Wang
Student num: 100968473
We can use self organizing maps as a substitute for K-means.
In Question 2, K-means was used to compute the number of hidden layer neurons to be used in an RBF network. Using a 2D self-organizing map compare the clusters ... |
071f3de053aab92497a395b225411ad2d75a2396 | dobis32/reservation-maker | /project/app/src/todayString.py | 461 | 3.71875 | 4 | from datetime import datetime
def getTodayString():
today = datetime.now()
month = None
if today.month < 10:
month = '0' + str(today.month) # add padding zero
else:
month = str(today.month)
day = None
if today.day < 10:
day = '0' + str(today.day) # add padding zero
e... |
bb6183403eb049abcc2f0c5b610bd1f33d068092 | manhar336/manohar_learning_python_kesav | /Revision/tuples.py | 599 | 4.09375 | 4 | fruits = "apple","mango","banana"
places_kms = (10,20,30,40)
print("tuple1 method:",fruits,type(fruits),tuple(enumerate(fruits)))
tup1,tup2 = (10,20,30,40),("a","b","""C""")
list1 = list(tup1)
print("converting tuple into list",list1)
print(tup1,tup2)
alist = [1,2,3,3,5]
print("conversting list into tuple:",tuple(alist... |
abe7b97d29f498e5c759dc692a6b38eb1f515a9d | amangour30/MILPSolver | /input.py | 850 | 3.59375 | 4 | from pulp import *
n1 = raw_input("Please enter number of integer variables: ")
print "N1: ", n1
n2 = raw_input("Please enter number of continuous variables: ")
print "N2: ", n2
print "Please enter the wegihts of the objective function C1 \n"
C = []
for i in range(int(n1)):
n = raw_input("c %d:"%(i+1))
C.ap... |
3dcb2a9ac77771774f0bd79606da019a075ec409 | laisOmena/Recursao-em-Python | /lista2/quest05.py | 559 | 3.84375 | 4 | nome = input("Digite seu nome: ")
nome1 = []
for i in range(0, len(nome)):
nome1.append(nome[i])
nome1 = nome1[::-1]
nome2 = []
for i in range(0, len(nome1)):
nome2.append(nome1[i])
if nome1[i + 1] == " ":
break
nome2 = nome2[::-1]
nome3 = ""
for i in nome2:
nome3 = nome3 + i
letra0 = []
for... |
b73ddfab804a3102d2bffcb8afc8ed93625735e6 | paulhkoester16/automatic_diff | /automatic_diff/learning_rates.py | 5,189 | 3.59375 | 4 | '''
Classes for various learning rate schedules
'''
import numpy as np
class LearningRate:
'''
Base class for learning rates
Base class implements constant learning rate for standard gradient descent.
Child classes can be implemented to add complexity to the learning rate
schedule, for example de... |
90267d507d032032bcc5746168d754bb6112c753 | abay-90/NISprogramming | /Module 3/PRG Module 3 Prax Activity/ShapeManager_Answer.py | 381 | 3.625 | 4 | from Square import *
from Rectangle import *
from Cube import *
from Box import *
shapes = list()
shapes.append(Square("Square 1", 10))
shapes.append(Rectangle("Rectangle 1", 20, 10))
shapes.append(Cube("Cube 1", 10))
shapes.append(Box("Box 1", 20, 10, 5))
print("Number of shapes: ", Shape.count)
print("-" * 50)
fo... |
99b38795e16028bd82c3174ed09776c185a8fd41 | Annapoorneswarid/ANNAPOORNESWARI_D_RMCA_S1A | /Programming_Lab/27-01-2021/2..py | 479 | 4.09375 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
>>>
>>> print("Enter Year")
Enter Year
>>> endYear =int(input())
2040
>>> startYear=2020
>>> print("List of leap year:")
List of leap ye... |
29c7b3a63d0f6020640798d5d758474f28ab6ef0 | deshpande-aditya/Py_Triaining | /class_func.py | 347 | 3.75 | 4 | ##Practice class functions in Python.
from student import student
##use similar code as student program written previously.
student1 = student("Rasika", "Biochem", 89.0, "First")
student2 = student("kayden", "Genetics", 71.0, "First")
student3 = student("Alexa", "Genetics", 89.0, "First")
print(student1.percent)
prin... |
5efd2910e0416f7f85ed8759cfeb127654ffbc7a | fandiandian/python_learning_excerise | /part1.4习题/musice_shuffling(音乐随机播放).py | 1,645 | 3.828125 | 4 | # 音乐随机播放
# music random play(Music shuffling)
# 要求:随机播放 m 首歌各一次,然后重复。
# 估计不按顺序播放两首歌的概率(即歌曲 2 后面不播放歌曲 3 ,歌曲 9 后面不播放歌曲 10)
# 创建一个长度为 m 的数组,打乱顺序
# 不放回的随机取样,样本总量为 m ,抽取 m 个样本
# 还有一种是使用 random.choice() 得到样本,在原始数组中将其删除
# 最直接的方式 random,shuffle()
# 长度为 m ,间隔为 m-1,所需的结果为:连续的次数/ (m-1)
import random
m = int(input('请确定歌曲的数量:\n... |
38aa007de11889faae7b14473ea05c001e73786d | bwest619/Python-Crash-Course | /Ch 3 - Lists/every_function.py | 1,890 | 3.953125 | 4 | #try it yourself, page 50
languages = ['python', 'css', 'html', 'c', 'javascript']
print(languages)
print(languages[1].title())
print("My first computer language is " + languages[0].title() + ".")
print(languages[-1])
languages.append('java')
print(languages)
languages.insert(2, 'php')
print(languages)
languages[... |
2ab4395b7e3849a3f6c702155d01102b044c0d48 | yuqiong11/Data-Structure-And-Algorithms | /recursion/gcd.py | 297 | 3.984375 | 4 | # input: two non-negative integer, output: the greatest common divisor
# example: given 6, 27, output 3
# euclid's division algorithm
def gcd(x, y):
if y == 0:
return x
else:
return gcd(y, x % y)
print(gcd(27, 0))
print(gcd(0, 27))
print(gcd(6, 27))
print(gcd(85, 408))
|
11f98317ae4d6503891293a015b8662b7330dba8 | Santiagonk/Aprende_con_alf | /Ficheros/Ejercicio_5.py | 1,629 | 3.515625 | 4 | from urllib import request
from urllib.error import URLError
def det_pib(url, country = 'ES'):
'''
Funcion toma una url y un codigo de pais, y devuelve diccionario con los PIBs por año del pais seleccionado
- url variable tipo string con la url deseada
- country el codigo del pais
'''
try:
f = requ... |
364c0007fe770d22c324d5dc7c37b6a8d3b4b13e | AdiVittala/Python-Development | /assigning_function_to_variable.py | 2,338 | 4.6875 | 5 | ###Assigning varibales to functions###
#def greet(name):
# return "hello "+name
#greet_someone = greet("John")
#print (greet_someone)
###Define fucntions inside other functions
#def greet(name):
# def get_message():
# return "Hello "
# result = get_message()+name
# return result
#print (greet("Jo... |
49c1344690991f8404e0661ac7f24a1ff86d7b2b | imdasein/zsk | /OOP/01.py | 859 | 4.09375 | 4 | '''
定义一个学生类
'''
# 定义一个空的类
class Student():
# 一个空类,pass必须有,表示跳过,否则会报错
pass
# 定义一个对象
mingyue = Student()
# 定义一个学Python的学生
class PythonStudent():
name = None
age = 8
course = "python"
#def的缩进层级和系统变量一样,二是默认有一个self参数
def doHomework(self):
print("I am doing my homework.")
#推荐在函数末尾使... |
b7afd72beb84315890d677cb69e1061fd2c59b1d | artem12345-png/SAOD | /3 algoritms.py | 3,760 | 3.703125 | 4 | import timeit
import random
import matplotlib.pyplot as plt
import numpy as np
# Метод сортировки Radix Sort
def Radix_sort(list1):
list = list1
long = len(list)
r = 1
max_element = max(list)
is_check = True
ts = 0
fin_ls = [0 for i in range(len(list))]
ts = timeit.default_timer()... |
d22ded25d52af9a2417f67c015c7e91ba69dfe81 | ocder/My-code | /python/判断是否是质数.py | 337 | 3.90625 | 4 | import math
def IsPrime(n):
if n > 1:
for i in range(2, n):
if (n % i) == 0:
print("不是质数")
break
else:
print("是质数")
else:
print("不是质数")
if __name__ == '__main__':
num = int(input("请输入一个数:"))
IsPrime(num)
|
f81b9bee6399c80973901661088366b98e7a147e | Jenny-Jo/AI | /python/python04_tuple.py | 546 | 4.0625 | 4 | #2. 튜플
#리스트[ ]와 거의 같으나, """삭제와 수정"""이 """안된다.""""
a = (1, 2, 3)
b = 1, 2, 3
print(type(a))
print(type(b)) # <class 'tuple'>
# a.remove(2) # AttributeError: 'tuple' object has no attribute 'remove' 속성에러
# print(a)
print(a + b) # (1, 2, 3, 1, 2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.