blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
42124d2221f70aae2cf3ea3487dcedc6104d8c31 | mani319/DSA | /binary_trees/01_binary_search_trees/bst_subtrees_in_given_range.py | 1,028 | 3.859375 | 4 | class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def subTreesInRange(root, low, high):
if(root is None):
return True
leftInRange = subTreesInRange(root.left, low, high)
rightInRange = subTreesInRange(root.right, low, high)
ro... |
fff7068b464ffd4c197367d41dd8821958cb8539 | dev-osiris/machine_learning | /IBM_coursera/layers.py | 1,549 | 3.6875 | 4 | import numpy as np
# only forward propagation is performed.
"""
w1, w2, w3: are the wieghts in each layer.
x_in: is a vector representing single input.
x_mat_in: is a matrix representing 7 different inputs.
This will be a N.N. with 2 hidden layers of length 4, input layer is of dimensions 7 x 3,
... |
bcba593ef81b7e8df2b05ad35f22c69dadce6514 | nnininnine/Data_Structure_lab | /Lab02/Class_Stack.py | 351 | 3.765625 | 4 | class Stack:
def __init__(self, list=None):
if list == None:
self.items = []
else:
self.items = list
def push(self, i):
self.items.append(i)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def isEmpty(self):
return len(self.items) == 0
def peek(self):
return ... |
f38f1d96a6329cfb6abe45910be918f75a49859d | karm1311/Regression | /Linear Regression Implementation from scratch (1) (1).py | 7,914 | 4.1875 | 4 |
# coding: utf-8
# Linear Regression is one of the most common, years old and most easily understandable in statistics and machine learning. It comes under predictive modelling. Predictive modelling is a kind of modelling here the possible output(Y) for the given input(X) is predicted based on the previous data or val... |
eabc6b11c43496de350b7528f22a2a4fdf06e70f | AlSavva/Algorytms_and_data_structure | /Lesson5/colllectionmod_Defaultdict.py | 1,545 | 3.609375 | 4 | # объект максимально похожий на словарь, с теми же методами
# что и у обычного словаря. Но в отличии от словаря, при создании ему необхо
# димо передать какую либо функцию.
from collections import defaultdict
a = defaultdict()
print(a)
s = 'qwertyuioasdfghjkzxcvbnmlkjhgfdsiuytre'
b =defaultdict(int)
for i in s:
... |
be9a2fc535ca0b501ab9fe960d7046d4b73116f0 | UW-ParksidePhysics/Luccas-Michael | /sum_int.py | 129 | 3.546875 | 4 | sum = 0
count = 0
n = 3
while count <= n:
sum += count
count += 1
print(sum)
n= 3
S = n*(n + 1)/2
print(S)
|
f347bee2d30020df9e1b3ba68004c99bbaee323a | WozMit/Basic-Deep-Learning-with-TensorFlow | /1. Simple.py | 2,162 | 4.09375 | 4 | import tensorflow as tf;
# You can create constants in TF to hold specific values
a = tf.constant(1);
b = tf.constant(2);
# Of course you can add, multiply, and compute on these as you like
c = a + b;
d = a * b;
# TF numbers are stored in "tensors". A fancy term for multidimensional arrays
# If you pass TF a Python ... |
97e97037fb41ae843a7d372556a48b6322029207 | weiting1608/Leetcode | /61 Rotate list.py | 1,114 | 3.921875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not head or not head.next:
return head
# close the linked... |
a54469049777d781c07ab09d975a0aabfe0fa513 | salwandhruvdev/code-wars | /count_char_in_string.py | 1,214 | 4 | 4 | '''
This program takes a String as an input
and outputs:
- number of times each character occured
- number of white spaces
- handles exceptions(if string is empty/ out of bounds)
'''
import string
def count_all(string_inp):
if not string_inp:
print("String is empty")
tota... |
7bcb73db98b3c593be479799b1c548e8d83bbfed | ParkerCS/ch18-19-exceptions-and-recursions-elizafischer | /recursion_problem_set.py | 2,681 | 4.125 | 4 | '''
- Personal investment
Create a single recursive function (or more if you wish), which can answer the first three questions below. For each question, make an appropriate call to the function. (5pts each)
'''
#1. You have $10000 on a high interest credit card with an APR of 20.0% (calculated MONTHLY, so MPR is APR... |
119f9aacc25ee1ddace9c2d501a0ebc329629d8b | AdamZhouSE/pythonHomework | /Code/CodeRecords/2938/60764/257646.py | 135 | 3.59375 | 4 | for i in range(1,10):
print(i)
for j in range(10):
print("%d%d"%(i,j))
if i==1 and j==0:
print(100) |
b260db4afa835d0e3cb230b70c4782d178e2125b | hrishikeshtak/Coding_Practises_Solutions | /leetcode/LeetCode-150/Trees/236-Lowest-Common-Ancestor-of-a-Binary-Tree.py | 2,059 | 3.890625 | 4 | """236. Lowest Common Ancestor of a Binary Tree"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# using Path logic
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'Tre... |
6be4da2065ee74741b2b3b20d109aa8e0084fc56 | JackReis01/Hawkeye_Py | /Hawkeye_RPS.py | 753 | 3.921875 | 4 | import random
user=input("Rock, Paper or Scissors")
user = user.capitalize()
comp=["Rock", "Paper", "Scissors"]
random.shuffle(comp)
if user == comp[0]:
print("You chose " + user + " and tied")
if user == "Rock":
if comp[0] == "Paper":
print("You Lose! You chose " + user + ".")
if comp[0... |
dbb0a138b681dffec4d7350c01cfe5e0a8199d10 | asarfraaz/stylk | /user_name.py | 641 | 4.40625 | 4 | """This is a doc string
This program will take the user name and the surname. Then it will give the output on the proper formate and also write the user name in the upper case letters
"""
def get_input():
first=str(raw_input('Enter ur first name'))
last=str(raw_input('Enter ur last name'))
retur... |
d0ea039f347c2f1715ddcfae5b5794ad9c892120 | ShanePAustin/pands | /code/week08/Lab8/salaries.py | 411 | 3.578125 | 4 | #salaries.py
#A program that makes a list that generates 10 random numbers between 20000-80000
#Author: Shane Austin
import matplotlib.pyplot as plt
import numpy as np
minSal = 20000
maxSal = 80000
numOfSal = 10
np.random.seed(1)
salaries = np.random.randint(minSal,maxSal,numOfSal)
bonusSal = salaries + 5000
incSa... |
153aefb40a231eadfeb5fd693a43cf87a2c0846a | azcj/PortugueseStudents | /hervas-diaz-with-R.py | 8,672 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 22 15:16:55 2018
@author: Nord
"""
"""
Aryana Collins Jackson
R00169199
Assignment 1
"""
# import libraries
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LinearRegression, La... |
5e379a7dd6724b7298056996104159abd0d82240 | roomyt/dancoff_util | /expandFIDO.py | 829 | 3.9375 | 4 | import sys
import re
def expandFIDO(list_):
""" Given a list of strings, this function will check each element for FIDO
style input and expand it if found. """
read_shorthand = re.compile(r'^(\d+)([rp])([a-zA-Z0-9.\-+]*)')
# ie for 4p5.43e-5 the returned list will contain ['4', 'p', '5.43e-5']
for i ... |
d553c26a7f39ad807e08212316915cacbb10a5c3 | fusionbox/django-fusionbox | /fusionbox/unicode_csv.py | 2,797 | 3.59375 | 4 | """
Unicode Readers and Writers for use with the stdlib's csv module.
See <http://docs.python.org/library/csv.html> for details.
"""
from csv import *
import codecs
from six import StringIO
class UnicodeRecoder:
"""
Iterator that reads an encoded stream and reencodes the input to the
specified encoding
... |
0cbf7a28bf253eabefa265bdd871b65e29fff931 | thelsandroantunes/EST-UEA | /LPI/Listas/L1_LPI - básico/exe13l1.py | 585 | 3.734375 | 4 | # Autor: Thelsandro Antunes
# Data: 28/06/2017
# EST-UEA
# Disciplina: LP1
# Professora: Elloa B. Guedes
# 1 Lista de Exercicios (25/03/2015)
# Questao 13: Faca um programa que leia da entrada padrao um tempo formado por
# hora e minutos (um numero em real) e apresente o tempo digitado
# apenas ... |
6957a6cc06bc759dc9f12cfe921a2915978c6187 | belea7/BitNet | /neural_network.py | 8,543 | 3.84375 | 4 | """
Contains Neural Network class.
"""
from layers import *
from data_generator import data_generator
from tabulate import tabulate
from termcolor import colored
class NeuralNetwork:
"""
Class representing Neural Network
"""
def __init__(self, bias):
"""
Constructor for ... |
e4af8e708d961e238b974db72071c6c7a0618d96 | Diego300591/PRACTICA-1 | /Ejercicio 4/Valor_cadena.py | 279 | 3.78125 | 4 | def ValorCadena(cad1,cad2):
cad1=str(cad1)
cad2=str(cad2)
val=""
if(len(cad1)==len(cad2)):
val=cad1+cad2
elif (len(cad1)>len(cad2)):
val=cad1
else:
val=cad2
return val
cadena1=raw_input()
cadena2=raw_input()
comparacion=ValorCadena(cadena1,cadena2)
print comparacion |
f5ceb09621542fc91901a3b6d7f5c234ede64687 | CodeGirl33/Python | /SomeIterator.py | 542 | 4 | 4 | class Range:
#home built Range function
def __init__(self, start, end):
#init our Range function it's a special method
self.start = start
self.end = end
self.current = start
def __iter__(self):
#this declares this object as an iterable
return self
def __next__(self):
#this return the next item i... |
ed307198b92aa6f44bea49c9071deaf6b824a147 | need4spd/eulerproject | /skywing/eulerPrj_04.py | 686 | 3.75 | 4 | def MaxSymmetryNumber(n):
rangeMinNum = pow(10,n-1)
rangeMaxNum = pow(10,n)
number1 = range(rangeMaxNum, rangeMinNum, -1)
number2 = range(rangeMaxNum, rangeMinNum, -1)
symmetryNumberList = list()
for i in number1:
for j in number2:
multiNum = str(i*j)
... |
291f47f9dcb12813bc82ba0509668a4c5b27b551 | jgadasu/GeoCoding | /mbta_finder.py | 3,549 | 3.5625 | 4 | """
Geocoding and Web APIs Project Toolbox exercise
Find the MBTA stops closest to a given location.
Full instructions are at:
https://sites.google.com/site/sd15spring/home/project-toolbox/geocoding-and-web-apis
"""
import urllib
from urllib.parse import urlencode
from urllib.request import urlopen
import json
from pp... |
52cb61f6b90a2645865cf38d38d4f7a7d543c1e4 | coderlzy/python- | /第四章 函数/汉诺塔.py | 427 | 4 | 4 | #汉诺塔,三个塔,每次只能移动一个盘子,保持大盘子在下小盘在下,把A塔的盘子全部移到C塔上
def hanoi(n,ch1,ch2,ch3): #n 盘子个数,ch1初始位置,ch2借助位置,ch3最终位置
if n==1:
print(ch1,"->",ch3)
else:
hanoi(n-1,ch1,ch3,ch2)
print(ch1,"->",ch3)
hanoi(n-1,ch2,ch1,ch3)
N=int(input("请输入盘子数:"))
hanoi(N,'A','B','C')
|
dfb523ac5b1017fdb8f4faa298a68efbfcc40504 | Dioclesiano/Estudos_sobre_Python | /Exercícios/ex040 - Media.py | 837 | 3.65625 | 4 | # Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de
# acordo com a média atingida:
# * Média abaixo de 5.0: REPROVADO
# * Média entre 5.0 e 6.9: RECUPERAÇÃO
# * Média 7.0 ou superior: APROVADO.
n1 = float(input('Digite sua primeira nota [0 a 10]: '))
n2 = float(i... |
189573dd1037c5cd2fdfce027ea8854e9d882217 | vasetousa/Python-Advanced | /Exams/Exam_June_2021/problem1.py | 1,348 | 3.75 | 4 | from collections import deque
milkshake = 0
chocolates = deque([int(el) for el in input().split(", ")]) # last one
cups_of_milk = deque([int(el) for el in input().split(", ")]) # first one
made_5 = False
while True:
if not chocolates:
break
if not cups_of_milk:
break
last_choco = chocola... |
3ff842c00135b910542bfbe0ee4c298f10f53590 | FireAmpersand/231PythonProjects | /testTur2.py | 284 | 3.65625 | 4 | import turtle
wn = turtle.Screen()
wn.title("Hello, Zach")
wn.bgcolor(input("Enter BackGround Color: "))
zach = turtle.Turtle()
zach.color(input("Enter Turtle Color: "))
zach.pensize(int(input("Enter The Pen Size: ")))
zach.forward(50)
zach.left(120)
zach.forward(50)
wn.mainloop()
|
41427bb299a4e5a161614a0775733481e781b108 | PPavlidis7/Aida-Computational-Optimization | /hw_4/improvment_heuristic.py | 2,523 | 3.59375 | 4 | import time
from random import shuffle
import construction_heuristic as con_heu
def reorder_truck_path(truck, node_coords):
""" truck path's first node will be kept. The other nodes will be shuffled"""
best_distance = truck['distance_made']
# if we find 4 continuous worse paths we exit from new_path_calc... |
d57cac1e8b616d802b6b42d3ee1a577ec8eb5cf3 | artemlucik/lesson2.1 | /string_challenges.py | 1,234 | 4.1875 | 4 | # Вывести последнюю букву в слове
word = 'Архангельск'
print(f'Last letter: {word[-1]}')
# Вывести количество букв а в слове
word = 'Архангельск'
print(f'Amount of "a" letters: {word.lower().count("а")}')
# Вывести количество гласных букв в слове
word = 'Архангельск'
vowels = ['а', 'у', 'о', 'ы', 'и', 'э', 'я', 'ю', ... |
dafb19b71670eece71f3641fe0b17fc5bee13230 | dparso/Principles-of-Programming-Languages | /Assignment 3/myParser.py | 14,208 | 3.828125 | 4 | # Disclaimer: Prof. Irfan is not responsible if this program crashes your computer :)
# How to run in terminal: python myParser.py tokens.txt
# Dylan Parsons (2017)
# Recursive-descent parser for CLite
# Input: A text file where each line has a token and the corresponding lexeme
# Output: True iff no syntax error
i... |
a89ea4ce058601df6527f18c953a6b28fabfa61b | pwiecha/python_snippets | /algos/search/old_code/linear_binary_search.py | 3,457 | 4.15625 | 4 | import algos_search_common
''' Linear and binary (normal and recursive) search implementations
Both looks for the element in the sorted array '''
#@algos_search_common.time_this
def linear_search(target, sequence):
'''
Linear search algorithm
For list of len n:
Best case O(1)
Worst case O(n)
... |
d53889330d60807c69559c12a0cd5a454d3b94f3 | sayush23/Python | /Q2.py | 98 | 3.875 | 4 | word=input("Enter a Word")
wordlen = len(word)
for i in range(wordlen-1,-1,-1):
print(word[i]) |
e3d43336a158b476f424d5dcb0f3779bcadeb87d | mateusKoppe/uffs-algorithms | /python/binomial/main.py | 1,058 | 4.125 | 4 | from math import factorial
def calc_combinacao(n, x):
return factorial(n)/(factorial(n-x)*factorial(x))
def binomial(n, x, p):
q = 1 - p
fatorialC = calc_combinacao(n, x)
return fatorialC*(p ** x)*(q ** (n-x))
def binomial_acc(n, x, p):
i = 0
acc = 0
while (i <= x):
acc += binomia... |
8c3758de277113def3ba8b59b7c45ed0f24d299b | bhi5hmaraj/APRG-2020 | /Assignment 2/solutions/BMC201959/BMC201959.py | 6,541 | 3.765625 | 4 | class Node:
def __init__(self, value, rb):
self.size = 1
self.color = rb
self.left = None
self.right = None
self.parent = None
self.value = value
class RedBlackTree:
def __init__(self):
self.root = None
def element(self, a, b):
if a is None:... |
7630027f17561cb90615736bc6abf46514de2cd8 | Code-Institute-Submissions/stats | /PycharmProjects/adventure/adventure.py | 1,094 | 3.9375 | 4 | from data import locations
def got_to(directions, position):
direction_error = directions
position_error = position
location = locations[position]
print('you are at the %s' % location)
valid_directions = {}
for k, v in directions.items():
possible_position = ... |
57e21e641b790991c639e37efe1ce0caa61ab722 | Warp-12/phd_tools | /exerciseLangtangenPython/part_1/zad03.py | 724 | 3.53125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Zrobic zadanie 2.35 ze str. 107
def kinematics(x, y, t, dt = 1E-6):
vx = (x(t+dt)-x(t-dt))/(2.0*dt)
vy = (y(t+dt)-y(t-dt))/(2.0*dt)
ax = (x(t+dt)-2*x(t)+x(t-dt))/float(dt**2)
ay = (y(t+dt)-2*y(t)+y(t-dt))/float(dt**2)
... |
b6cfee668037843157584bb572ec988c057d4e3b | thomasm1/python_2018 | /PY_FUNCTION/__2inputArea.py | 651 | 3.984375 | 4 | # -*- coding: utf-8 -*-
#MaestasP1
#Programmer: Thomas Maestas
#EMail: tmaestas29@cnm.edu
#Purpose: Area of Triangle Calculator
"""
Created on Wed Sep 17 18:44:38 2017
@author: tom
"""
print("Welcome to your personalized triangle calculator!")
print('')
height = float(raw_input('What is the height of the triangle? ')... |
c41577c173a4eba19271f7379cb12713bf779e72 | JimKass/Practicals | /prac_03/oddName.py | 350 | 4.0625 | 4 | def main():
name = get_name()
print_name(name)
def print_name(name):
for i, letter in enumerate(name):
if i % 2 == 1:
print(letter, end=" ")
def get_name():
name = input('Enter your name: ')
while name == "":
print("Invalid name")
name = input('Enter your name... |
37a09202f959a286e90f0c8cc4a4e4aa68860b04 | GiantMolecularCloud/my_casa_tools | /get_idx2.py | 207 | 3.65625 | 4 | def get_idx2(alist, name):
"""
return the the index of an item called by its name in dictionary
"""
for idx, itm in enumerate(alist):
if (name in itm['name']):
return idx
|
d1cc286f8a4ed6abf1be8466476f9ca9b5879809 | victorbertoldo/aprendendo_python | /Testes/teste_strings.py | 413 | 3.953125 | 4 | str = 'Victor hugo ROCHA'
#maiusculo
str = str.upper()
print(str)
#minusculo
str = str.lower()
print(str)
# Quantos caracteres tem?
print(len(str))
# Substituir caracter
str = str.replace('rocha','bertoldo')
print(str)
# Contar caracter dentro de uma string
var = 'cc bb eee fodfd c tifdc'
print(var.count('c'))
... |
bb032b47d6e3913fae90097fafda9007f4540df8 | digitalladder/leetcode | /problem121.py | 913 | 3.578125 | 4 | #problem 121 /Best Time to Buy and Sell Stock
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
minprice = float("inf") #表示正无穷大,负无穷为float("-inf")
maxprofit = 0
for price in prices:
if price < minpr... |
51ab8bda3eb933169b7ff2cf11654d4156278d87 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/rna-transcription/b8f8d6e6426f4649849815c3bb7a04cc.py | 219 | 3.59375 | 4 | dna_to_rna_map = {
'G': 'C',
'C': 'G',
'T': 'A',
'A': 'U'
}
class DNA(object):
def __init__(self, dna_str):
self.dna_str = dna_str
def to_rna(self):
return ''.join([dna_to_rna_map[c] for c in self.dna_str])
|
feef9c5ba615b4b9dcecd7fff3e4cc41f64f93dd | AbrarAlzubaidi/amman-python-401d7 | /class-03/demo/unpacking.py | 375 | 3.890625 | 4 | def my_sum(*args):
result = 0
for x in args:
result += x
return result
if __name__=="__main__":
nums = {3,7,5,6}
print(my_sum(2,7,3,9,0,5))
print(my_sum(4,5))
print(my_sum(*nums))
def fun(*args):
# for arg in args:
# print(arg)
print(type(args))
fun(3,5,6,7,1,2,... |
82f6c50c41355cd76942c842faf1543ca65e4417 | tanishshadow/Python-tutorial-2- | /more on lists comprehensions.py | 670 | 4.21875 | 4 | # combining two elements of two lists like cartesian product of sets if they are not equal-----
list_comp = [(x,y) for x in [1,2,3] for y in [3,1,4] if x != y]
print(list_comp)
# this is equivalent to --
lst = []
for i in [1,2,3]:
for b in [3,1,4]:
if i!=b :
lst.append((i,b))
print(lst)
... |
db170ac56e6d0f10f73b752d1debf33847ddd82d | ChrisBarnes2000-MS-DU/SPD-2.31-Testing-and-Architecture | /lab/weather_station.py | 7,069 | 4.21875 | 4 | # Resources
# https://www.geeksforgeeks.org/observer-method-python-design-patterns/
# https://docs.google.com/document/d/1jyrxxQyrVxBG9S_hXYI69ytUMdxQdApyM6MO2CwvYj4/edit
class Subject:
"""Represents what is being observed"""
def __init__(self):
"""create an empty observer list"""
self._obser... |
af046d750ec4bf6053a0e0bad9a1b5d1e30b8751 | Programacion-Algoritmos-18-2/2bim-clase-01-JosePullaguariQ | /ejercicio-clases/clase1-2bim/manejo-excepciones/principal.py | 337 | 3.8125 | 4 | #Ejemplos de manejo de excepciones
try:
edad = input("Ingrese su edad: \n")
edad = int(edad)
print("Su edad es %d"%(edad))
except NameError as e:
print("Existe un error:%s %e")
except ValueError as e:
print("Existe un error:(%s) %s" % (e.__class__, e))
#except Exception as e:
# print("Existe un error:(%s) %s" % ... |
24a1a518f8cdfe2075bb1c89a4a005d07f46dc9f | AdamZhouSE/pythonHomework | /Code/CodeRecords/2483/60580/313799.py | 368 | 3.59375 | 4 | size = int(input())
a = 0
while a < size:
firstStr = input()
# 将字符串转换成list
SecondStr = list(input())
i = 0
signal = False
while i < len(firstStr):
if (firstStr[i] in SecondStr):
print(firstStr[i])
signal = True
break
i = i + 1
if not signal... |
5f2c7685e202ec729dd8890f0574f7858b889707 | alex-crash/geekbrains_python | /hw08/task02.py | 1,415 | 3.953125 | 4 | """
2. Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. Проверьте его работу на данных,
вводимых пользователем. При вводе пользователем нуля в качестве делителя программа должна корректно обработать эту
ситуацию и не завершиться с ошибкой.
"""
class ZeroDivisionException(Exception):
... |
665e01a9e0d22cd35dc258af45970bb53c062b76 | konovalovatanya26/prog_Konovalova | /turtle_new/упр 11.py | 279 | 3.984375 | 4 | import turtle
t = turtle.Turtle()
t.shape('turtle')
N = 100
L = 5
def circle(N, L):
for step in range(N):
t.forward(L)
t.left(360/N)
for step in range(N):
t.forward(L)
t.right(360/N)
for _ in range(10):
circle(N, L)
N = N + 10
|
b976796fc3f7a2e5032280000ae060f236b9c427 | brianleonard15/cgu | /experiment/builds/build_trials.py | 9,837 | 4.09375 | 4 |
# A couple of essential imports. We'll need random.uniform to be able to
# randomly assign income values when desired, shuffle so that we can randmoize
# the order of the life cycles, and xlrd is so that we can read the Excel
# document where the trials are stored.
from random import uniform, shuffle
from ..helpe... |
d3b7280ad30ed07f0a4e17b228074e30b906d15f | ritikapatel1410/Python_Data_Structure | /set/set_remove_element.py | 1,741 | 3.984375 | 4 | '''
@Author: Ritika Patidar
@Date: 2021-02-25 23:45:10
@Last Modified by: Ritika Patidar
@Last Modified time: 2021-02-25 23:45:38
@Title : remove element to the set problem
'''
import sys
import os
sys.path.insert(0, os.path.abspath('LogFile'))
import loggerfile
def remove_element(element,created_set):
"""
... |
7e41e965e3d9059056e253f9e6679dc24c11b03c | TahaKhan8899/Coding-Practice | /LeetCode/aliceGame.py | 804 | 3.5 | 4 | class Solution:
def divisorGame(self, N):
# alice = 0 bob = 1
player = 0
players = ["Alice", "Bob"]
# check if player can make a move
while(N >= 1):
move = chooseNum(N)
print(players[player], ": ", "N = ", N, " Choose: ", move)
N -= mov... |
130f38b1728ed80163a46272c4e6fd8834ac8539 | ThomyRa/MisionTic2022 | /semana3/taller2/taller2.py | 3,010 | 3.78125 | 4 | """ Programa calculadora artimética super amigable#
Realiza las 4 operaciones (+,-,* /)
dada como entrada una cadena de caracteres
incorpora al modulo calculadora_aritmetica.py
Thomas Ramirez Rozo
Mayo 3-2021 """
# ---------------- Zona librerias------------
import calculadora_aritmetica as calc
#... |
640610a06af7d421dad7b8eb2e0a4499162e27b2 | vasundhara7/DataStructuresAndAlgorithms | /Trees/IterativePreOrder.py | 802 | 4.1875 | 4 | # Given a binary tree, return the preorder traversal of its nodes’ values.
# Example :
# Given binary tree
# 1
# \
# 2
# /
# 3
# return [1,2,3].
# Using recursion is not allowed.
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# s... |
2f67ef680ec6a443171bb52a8529a247ce20d7fe | Rizat19/python-esep | /eds.py | 111 | 3.78125 | 4 | f=1
n=int(input('input n:'))
for i in range(n):
i+=1
f*=i
print('{} факториалы:'.format(n),f) |
81576ad1261b9dfcbfff11efbb853c52967c659d | ticklepizza/me | /week2/exercise1.py | 1,844 | 4.5625 | 5 | """
Commenting skills:
TODO: above every line of code comment what you THINK the line below does.
TODO: execute that line and write what actually happened next to it.
See example for first print statement
"""
import platform
# I think this will print "hello! Let's get started" by calling the print function.
print("h... |
5d8e299b3dea7002d7322225f974ad47d48e5b8d | mrakrathod/django-rest-service-with-docker | /api_service/utils.py | 506 | 4.125 | 4 | import itertools
def convert_day_to_year(number_of_days):
DAYS_IN_WEEK = 7
year = int(number_of_days / 365)
week = int((number_of_days % 365) / DAYS_IN_WEEK)
days = int((number_of_days % 365) % DAYS_IN_WEEK)
return "Average age record is {year} year {week} week and {days} days".format(
ye... |
3e26ca52d379ce6671d0b5752845f96b278e1a7b | ShashwathKumar/Pyth_for_interview | /leetcode/18_FourSum.py | 1,632 | 3.828125 | 4 | """
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target?
Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
A soluti... |
cc25bcd60748c32c3c282b5fe999a7c437373e8c | Amro192/PythonStack | /_python/python_fundamentals/for_loop_basic2/for_loop_basics2.py | 1,769 | 3.640625 | 4 | #-1
def noPositive(ar):
for x in range(len(ar)):
if ar[x]>=0:
ar[x]="big"
print(ar)
noPositive([1,4,-1,-2])
#-2
def numPositives(ar):
counter=0
for i in range(len(ar)):
if ar[i]>0:
counter+=1
ar[-1]=counter
return ar
print(numPositives([3,4,5,... |
301d84fd5cd7c034d3e47a324fd364d00e270913 | jeffliao8888/zerojudge | /a013.py | 179 | 3.921875 | 4 | import sys
for word in sys.stdin:
word = input()
# why does word is # but not word == '#'
print(word is '#')
print(word == '#')
if(word is '#'):
break
|
844fdadcd6c2fa5ea0e0e9090f4748569cb99789 | monteiroruim/AdventOfCode | /AoCPython/AoC2021/d18.py | 6,530 | 3.859375 | 4 | from unittest import TestCase
from math import ceil
from ast import literal_eval
class d18:
def __init__(self, input):
self.escape_chars = ["[","]", ","]
self.init_val = self.parse_input(input)
# https://adventofcode.com/2021/day/18
self.result1 = 0
self.result2 = 0
def... |
7b4f066e5ba91cf5eafa780f5a90a831725488b8 | skeeph/hackerrank | /algorithms/strings/reduced-string.py | 370 | 3.5 | 4 | def reduce(s: str) -> str:
s += "/"
res = ""
i = 0
while i < len(s) - 1:
if s[i] == s[i + 1]:
i += 2
continue
else:
res += s[i]
i += 1
if res != s[:-1]:
res = reduce(res)
return res
red = reduce(input().strip())
if len(red) > ... |
4a8e095c5a166c6b32ce3e3045b860742812c213 | ErdenebatSE/resource-of-python-book | /7-python/collections/lists.py | 2,675 | 4.21875 | 4 | # list
жагсаалт = ['элемент1', 'элемент2', 'элемент3']
print(жагсаалт)
# ['элемент1', 'элемент2', 'элемент3']
newlist = list(('элемент1', 'элемент2'))
print(newlist) # ['элемент1', 'элемент2']
weekdays = ['Даваа', 'Мягмар', 'Лхагва', 'Пүрэв', 'Баасан']
print(weekdays[0]) # Даваа
print(weekdays[4]) # Б... |
8a6c6b0ec8505c4bb7ae2b2d96848c487594e023 | gudduarnav/Acceleratron-Python-Workshop-Assignments | /assignment02/program_11.py | 334 | 4.25 | 4 | # 11. Write a program to check whether a entered character is lowercase ( a to z ) or uppercase ( A to Z ).
ch = input("Enter a Character:")
if len(ch) >= 1:
ch = ch[0]
if ch.isupper():
print(ch,"is UPPER CASE")
elif ch.islower():
print(ch,"is LOWER CASE")
else:
print(ch, "I do... |
68cf24fbe69b950b84be3533518e37157e049b73 | AbdulkarimF/Python | /Day44.py | 1,756 | 4.5625 | 5 | # Python Inheritance:
print('Example 1')
class Person:
def __init__(self, Fname, Lname):
self.firstname = Fname
self.lastname = Lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, Fname, Lname):
super().__init__(... |
00407868eb92a1664ff70adbc1c535a6f7c63cd2 | Ogasawara610/blackjack | /blackjack.py | 3,126 | 3.734375 | 4 | import random
import sys
rank = 0
def get_point(hand):
result = 0
for card in hand:
if card[rank] > 10:
num = 10
else:
num = card[rank]
result = result + num
return result
def all_card():
marks = ["♠","♧","♡","♦"]
num = range(1,14)
... |
e11edc44bc64812e6327d147839c16d6ea1c7371 | dexterchan/DailyChallenge | /DynamicProgramming/FrozenLake/Arena.py | 8,248 | 3.5 | 4 | from enum import Enum
from io import StringIO
from typing import List, Tuple, Dict, NamedTuple
import random
from collections import deque, namedtuple
from functools import reduce
import logging
logging.basicConfig(format="%(levelname)s %(filename)s-%(lineno)s: %(message)s")
logger = logging.getLogger(__name__)
logge... |
61c7043bb516a38691131526b20fce5451672868 | juliakennard/Python_practice | /bank_account.py | 1,031 | 3.875 | 4 | # Create class BankAccount
class BankAccount:
def __init__(self, int_rate = .01, balance = 0):
self.int_rate = int_rate
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
if self.balance - amount <0:
... |
4e8618e2d6156f20e3585a6ccb14930ea5d22fb2 | gregpuzzles1/Euler-Python | /problem_49.py | 1,231 | 3.703125 | 4 | # Python version = 2.7.1
# Platform = win32
import gmpy
import itertools
def get_primes():
"""Get a list of all 4 digit prime numbers"""
L = []
for n in range(1000, 10000):
if gmpy.is_prime(n) > 0:
L.append(n)
else:
continue
return L
def isprime(n):
"""Chec... |
02faf7dbc78b258b150f0624636d61f668881de6 | wulichunchun233/Pythonbigdata | /source/8.大数据可视化/hello.py | 296 | 3.578125 | 4 | '''
Created on 2019-8-14
@author: zhangxiao
'''
import matplotlib.pyplot as plt
import math
x=range(721)
y=[math.sin(i*3.14/180) for i in x]
plt.axis([0,720,-1.1,1.1])
plt.plot(x,y,'b')
plt.xticks(range(0,721,90))
plt.xlabel("degree")
plt.ylabel("sin")
plt.title("sin function")
plt.show()
|
e1a28a5e396de79cb9fba3d301698fccce292940 | ehmsu/Python-Tests | /April 13 coding.py | 2,461 | 4.53125 | 5 | Python 2.7.13 |Anaconda 4.0.0 (64-bit)| (default, May 11 2017, 13:17:26) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> float('12')
12.0
>>> float('123.456789')
123.456789
>>> #floating is for converting values into proper numbers
>>> your_age = input('E... |
d92f4ae8be81f0838a9aace761aa0996d1b8d42f | garypush/leetcode-notes | /leetcode/887.py | 1,992 | 3.734375 | 4 | class Solution1:
'''
time: O(KN^2)
space: O(KN)
For every floor i in 1..N, calculate the max moves required between broken or not broken.
The result is the minimum of the max moves.
'''
def superEggDrop(self, K, N):
"""
:type K: int
:type N: int
:rtype:... |
b7efa26bc2b49f9651fcb80f5e35aff95c56177e | j-carpentier/rax-python-test | /2.py | 260 | 4 | 4 | #!/usr/bin/python
import itertools
array = [[1,2,3],
[8,9,4],
[7,6,5]]
def TransposeAndFlip(array):
while array:
yield array[0]
array = list(reversed(zip(*array[1:])))
print list(itertools.chain(*TransposeAndFlip(array)))
|
c61c8f95784a8ac91a1a85f0e6b12b8552d2cc03 | alosoft/bank_app | /bank_class.py | 2,453 | 4.3125 | 4 | """Contains all Class methods and functions and their implementation"""
import random
def account_number():
"""generates account number"""
num = '300126'
for _ in range(7):
num += str(random.randint(0, 9))
return int(num)
def make_dict(string, integer):
"""makes a dictionary of Account N... |
8c9500820d1ee8100bcd98feff6bb98d8c1fa248 | andremenezees/CursoPython | /Aulas/7_Testes_com_python/3_intro_unnittest.py | 628 | 4.15625 | 4 | """
Introduo ao modulo Unittest
Unittest -> Testes unitarios
o que so teste unitarios?
Testes a forma de se testar unidades individuais do codgo fonte.
Unidades individuais podem ser: Funcoes, mtodos, classes, mdulos...
#OBS: Teste unitrio no especifico da linguagem python.
Para criar nossos testes, criamos cla... |
8a604bccd1464affed30a4f8dc22d2ac534b0331 | BramKerk/Groep-1 | /opdracht1publish.py | 1,466 | 3.78125 | 4 | # Opdracht 2.1
print( """
Name
Adres
Mobiel
""" )
# Opdracht 2.2
sales = float(input('Total sales: '))
profit = sales * 0.23
print("Total profit is: ", profit)
# Opdracht 2.3
pounds = float(input('Pounds: '))
kg = pounds * 0.454
print('Kg: ', format(kg, '.2f'))
# Opdracht 2.4
item0 = float(input('Price of ... |
a29df93fb08028f74854b63b8dc4b5c1a9b5432e | NGL91/datastructure_algorithm | /rotate_array.py | 616 | 4.1875 | 4 | '''
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
'''
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return an... |
2c712411245f3b559771de6fa427ef9b124e8624 | tecnology8/PythonBasics | /strings.py | 658 | 4.3125 | 4 | myStri = "Ruddy"
print("My Name is " + myStri)
print(f"My Name is {myStri}")
print("My Name is {0}".format(myStri))
# print(myStri.upper())
# print(myStri.lower())
# print(myStri.swapcase())
# print(myStri.capitalize())
# print(myStri.replace('hello','bye'))
# print(myStri.count('l'))
# print(myStri.count... |
8a6a0593cf81bb678a2fb5c536c46a005e8332f7 | RicardoLima17/lecture | /week03/lab 3.3/lab 3.3.X/len.py | 263 | 3.953125 | 4 |
# Author Ricardo
inputString = input('enter a string:')
# len count all caracter including space
lenghtOfString = len(inputString)
print('The lenght of {} is {}'.format(inputString, lenghtOfString))
message = 'John said\t"hi"\nI said\t\t"bye"'
print (message) |
865d20bffa79c184ba088b7421b7c81b21f2b05d | GoetzEdinger/TextAnalyzer | /TextAnalyzer.py | 10,060 | 3.8125 | 4 | # -*- coding: utf-8 -*-
'''
Created on 09.07.2015
@author: Goetz Edinger
'''
import enchant
import nltk.data
from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize
import string
import sys
debug = True
dict_sentence_length = {}
dict_word_length = {}
number_of_letters ... |
0c6f33ec65adb75d5520e65578c61afed7fc10e3 | MrWANGDACHUI/- | /ex.2_7.py | 277 | 3.796875 | 4 | #六芒星
import turtle as t
def drawTriangle(e,direct=120):
for i in range(3):
t.fd(e)
t.left(direct)
t.seth(-90)
drawTriangle(200,120)
t.up()
t.seth(0)
t.fd(115.5)
t.seth(-90)
t.fd(200)
t.down()
t.seth(90)
drawTriangle(200,120)
|
976899ae5d963dc18cd387c278a750b7d6f14c67 | IgorLark/Brows | /test_test.py | 588 | 3.796875 | 4 | print("поиск совпадений")
A = [2, False, 9.1, 2 - 1j, "hello", 5, "python"]
B = [5, 3, "HELLO", 7, 12.5, "Python", True, False]
print("1-й список:", A)
print("2-й список:", B)
print("Совпадения:")
i = 0
for a in A:
i = i + 1
j = 0
for b in B:
j = j + 1
if a == b:
# если элементы ... |
3c633827361d90131f84916257d6287a6dc64f73 | gandrew313/Python | /condition.py | 315 | 3.9375 | 4 | a = 1
b = 2
print('\nVariable a is:', 'One' if (a == 1) else 'Not one')
print('\nVariable a is:', 'Even' if (a % 2 == 0) else 'Odd')
print('\nVariable b is:', 'Two' if (b == 2) else 'Not two')
print('\nVariable b is:', 'Even' if (b % 2 == 0) else 'Odd')
max = a if (a > b) else b
print('Greater Value is', max)
|
2bb225a750746e0e252f37b7ba7c30146205d153 | selym3/conjugemos-bot | /test.py | 167 | 3.796875 | 4 | from conjug_wrapper import Conjug
conjug = Conjug()
while True:
word = input("english word: ")
if word == ".":
break
print(conjug.get_all(word))
|
343231c351b623f776c19e4172cd99f9837e7598 | ryanrozanitis/Cryptography-Programs | /ProgramsForCS608FInal/ZeroKnowledgeVerification.py | 3,922 | 3.59375 | 4 | # I can actually always leave a, b, and c as 2, 3, and 4. "Random" selection. Makes it easier for the final.
a = 2
b = 3
c = 4
print("1. Alice randomly selects {a, b, c}: {" + str(a) + ",", str(b) + ",", str(c) + "}")
# predetermined primes by the question
p = 43
q = 47
N = p*q
# Use FindPubPriKeysForZeroK... |
f721704c92e5d5ca90b18545947d8fba8086770a | Pawansingh2203/264719_Pawan_Python_Practice | /dscvtype.py | 601 | 3.671875 | 4 | def dscvtype():
s=input("Enter the Value ")
if s in 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z' and len(s)==1:
print("Charecter")
elif s in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' and len(s)==1:
print("Charecter")
elif s in '123456789':
print("Integer")
elif s in '.':
... |
9e88d4f5f9aea4a7a56aa21d2e77f5b9fbba360d | ashwinids/python | /learning_scripts/unique2.py | 476 | 4.0625 | 4 | #!/usr/bin/env python
def unique(input_string):
length = len(input_string)
print(length)
if length > 36:
print("not unique")
A = True
for i in range(0,length):
#print(input_string[i])
for j in range(i+1,length):
#print(input_string[j])
if(input_string[i] == input_stri... |
d1d6f8d3bbbe1cc154675e300d9e37876accb4d5 | shivamnegi1705/Competitive-Programming | /Leetcode/January Challenge 2021/1662. Check If Two String Arrays are Equivalent.py | 320 | 3.625 | 4 | # Question Link:- https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
s = ''
w = ''
for i in word1:
s+=i
for i in word2:
w+=i
return s==w
|
22edd2617fb307f003d7aa199efbc82a192358c2 | ChillOrb/CS_basics | /leetcode_python/Tree/merge-two-binary-trees.py | 9,491 | 3.875 | 4 | # V0
# IDEA : DFS
class Solution:
def mergeTrees(self, t1, t2):
return self.dfs(t1,t2)
def dfs(self, t1, t2):
if t1 and t2:
newT = TreeNode(t1.val + t2.val)
newT.left = self.mergeTrees(t1.left, t2.left)
newT.right = self.mergeTrees(t1.right, t2.right)
... |
5ebafc4d697e7bef5161d48ebc1ac53cdba13a5f | WonJunPark/python_web | /syntax/for.py | 92 | 4 | 4 | #list
a = [1,2,3]
for value in a:
print(value)
for value in range(5):
print(value)
|
9864df07fd7ae36109c78ee5a2eaee1e1f162412 | pranavprasannan/Luminar-Python | /LuminarPython/Functionprograms/pgms.py | 356 | 3.859375 | 4 | import Functionprograms.operations
num1=int(input("Enter the first number "))
num2=int(input("Enter the second number "))
add=Functionprograms.operations.add(num1,num2)
sub=Functionprograms.operations.sub(num1,num2)
mult=Functionprograms.operations.mult(num1,num2)
div=Functionprograms.operations.div(num1,num2)
print(ad... |
29db48ebcec46ffecabe842fa3b3d7ff5ec3162d | Dagiman007/Python-exercise | /AreaOfTriangle.py | 908 | 4.40625 | 4 | '''A program the computes an area of triangle
for three points specified by the user'''
import math
#Get the three points from the user
x1,y1 = eval(input("Enter the coordinates of the first point separated by comma: "))
x2,y2 = eval(input("Enter the coordinates of the second point: "))
x3,y3 = eval(input("... |
f8a7bf81a16a5c1fcd8da6e5848f3077ab91c9d0 | vinceajcs/all-things-python | /algorithms/other/randomized_set.py | 1,241 | 3.796875 | 4 | """Design a data structure that supports all following operations in average O(1) time.
insert(val): Inserts an item val to the set if not already present.
remove(val): Removes an item val from the set if present.
getRandom: Returns a random element from current set of elements. Each element must have the same probabi... |
59c7e04c257cfd0f2059fc9dcb647816ecadc97f | Hemant-Jain-Author/Design-Patterns-Using-Python | /State/StatePattern.py | 732 | 3.671875 | 4 | from abc import ABC, abstractmethod
import math
class BulbControl:
def __init__(self):
self.current = Off()
def set_state(self, state):
self.current = state
def flip(self):
self.current.flip(self)
def to_string(self):
return self.current.to_string()
class BulbSta... |
72dc3ab07b1127e5da72a8baa3bbf36fb1d5438b | FurfurV/programming_for_data_analytics | /lab3/conditions and loops/if_elif.py | 577 | 3.984375 | 4 | # Created by Viktoria
# (▰˘◡˘▰)
# 21/10/2020
# Student number: R00180598
price=99
discount=0
package_num=int(input("How many packages? :"))
if(package_num<=0):
print("Should be greater than 0")
elif(package_num>=10 and package_num<=19):
discount=0.2
elif(package_num>=20 and package_num<=49... |
d6e00ce95ef95c8eeb12332c7287cfd0b6e79e78 | Alhenri/Codigos | /Python/Mundo_03_CV/003/Listas(p2).py | 407 | 3.625 | 4 | teste = list()
teste.append('Alexnadre')
teste.append(19)
galera = list()
galera.append(teste[:])
teste[0] = 'Cloe'
teste[1] = 22
galera.append(teste[:])#Lista dentro de lista
print(galera)
galera = list()
dado = list()
for c in range(0, 3):
dado.append(str(input("Nome: ")))
dado.append(int(input("Idade: ")))
... |
0c29e056ad03a4c33a459452a3307b34f78c5de9 | vy3191/Graphs | /projects/graph/graph.py | 8,903 | 4.40625 | 4 | """
Simple graph implementation
"""
from util import Stack, Queue # These may come in handy
class Graph:
"""Represent a graph as a dictionary of vertices mapping labels to edges."""
def __init__(self):
self.vertices = {}
def add_vertex(self, vertex):
"""Add a vertex to the graph."""
... |
0d8a083892538adc0c359528411d549924e8f6c6 | GayatriDPatil/PythonWeek1 | /Week1/Tuples/convertListtoTuples.py | 361 | 4.21875 | 4 | #list = [7, 8, 5, 3, 2]
#print(list)
#tuplex = tuple(list)
tuple = [7, 8, 5, 3, 2]
listnew = list(tuple)
listnew.remove(8)
#tuplex = tuple(listnew)
#print(tuplex)
print(listnew)
#reverse tuple
x = ("w3resource")
# Reversed the tuple
y = reversed(x)
print(tuple(y))
#create another tuple
x = (5, 10, 15, 20)
# Reversed ... |
bd9b8742ba752a790ebe688a457b71effbead1eb | ashokmeghvanshi/CP-CIPHER-Assignments | /Day-09 Leetcode Binary Tree/Cousins in Binary Tree.py | 1,316 | 3.625 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
self.siblings(root, x, y)
if(self.height(r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.