blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
55d726da1f5c4d38db5efa9a3ca99a5f01fcc87a | clsulli/DataFaker | /Crime.py | 2,024 | 3.6875 | 4 | import random
import time
class Crime:
def __init__(self, caseID):
self.caseID = caseID
self.date = None
self.domestic = False
self.crimeTypes = ['Arson', 'Assault', 'Blackmail', 'Bribery', 'Burglary', 'Embezzlement', 'Extortion', 'False pretenses',
'... |
b5b4612ebb8c8bf09a5811b3ca00867d26c03d82 | aikem26/test1 | /urok19/ter.py | 67 | 3.71875 | 4 | a = [4, 2, 5, 6]
b = [num if num > 3 else 10 for num in a]
print(b) |
18c0853d3337a6ec1abe08e1cc6518ead4b9d5e9 | lxj0276/note-1 | /algorithm/top_interview/grab2.py | 546 | 3.90625 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(S):
# write your code in Python 3.6
if not S:
return S
while 'AA' in S or 'BB' in S or 'CC' in S:
S = S.replace('AA', '')
S = S.replace('BB', '')
S = S.replace('CC', '')
... |
668e7cd085d2d3d336f4284c16705bdfe61ac4f9 | bwest619/Python-Crash-Course | /Ch 4 - Working With Lists/animals.py | 308 | 3.828125 | 4 | # try it yourself, page 60
cats = ['tiger', 'jaguar', 'cheetah']
for cat in cats:
print(cat.title())
print("\n")
cats = ['tiger', 'jaguar', 'cheetah']
for cat in cats:
print("Oh, how I would love to own a " + cat.title() + "!")
print("All of these animals are in the cat family. And can eat you.")
|
b7a7ce9379455e7047f5cfd5ace4b8eef4cbc29e | nav-commits/Python-code | /Practice.py | 849 | 4.03125 | 4 | import random
# function name validation
def nameexcution (fname, lname, names):
# if check if its true
if fname == 'gurveer' and lname == 'gill':
print( fname + ' is his first name ' + 'and his lastname is ' + lname)
else:
print('name not found')
for name in names:
p... |
39c6be0f830da1a60ea4f2c10a9e2a1ff30446a4 | Aishee0810/HackerRank | /removecharanagram.py | 571 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 19 17:09:04 2019
@author: aishee
"""
from collections import Counter
def removechar(s1,s2):
dict1=Counter(s1)
dict2=Counter(s2)
print(dict1)
key1=dict1.keys()
key2=dict2.keys()
print(key1)
count1=len(key1)
count2=len(... |
5f7954c6a643b9a41d89b5d530e51b66ef3924cd | codemunkee/examples | /fizzbuzz.py | 250 | 3.703125 | 4 | #!/usr/bin/env python
for i in range(1, 101):
msg = str()
if (i % 3 == 0) and (i % 5 == 0):
msg = 'FizzBuzz'
elif i % 3 == 0:
msg = 'Fizz'
elif i % 5 == 0:
msg = 'Buzz'
else:
msg = i
print msg
|
429f3f342aa5c3268c8c1ee6e85b727d6a0b959b | marmarmar/dungeon_game | /cold_warm_hot_game.py | 3,719 | 3.8125 | 4 | import random
import os
import time
from termcolor import colored, cprint
def intro_graphic():
"""Read graphic from file cold_intro.txt"""
data = [line.strip() for line in open("cold_intro.txt", 'r')]
print('\n\n')
for i in range(len(data)):
if i == 0:
print(" ", end='')
if... |
58d9cf515080f7d26f64e6525997e0d8ef296f9f | cinhori/LeetCode | /python_src/101.对称二叉树.py | 2,918 | 3.953125 | 4 | #
# @lc app=leetcode.cn id=101 lang=python3
#
# [101] 对称二叉树
#
# https://leetcode-cn.com/problems/symmetric-tree/description/
#
# algorithms
# Easy (51.08%)
# Likes: 766
# Dislikes: 0
# Total Accepted: 137.7K
# Total Submissions: 269.6K
# Testcase Example: '[1,2,2,3,4,4,3]'
#
# 给定一个二叉树,检查它是否是镜像对称的。
#
#
#
# 例如,... |
a2b24178b9a21a622c063a281b6ebd6f6ff9e5da | bfollek/twitter_easy_and_hard | /random_string.py | 291 | 3.578125 | 4 | import random
import string
class RandomString:
"""
From https://pythontips.com/2013/07/28/generating-a-random-string/
"""
@staticmethod
def make(size=32, chars=string.ascii_uppercase + string.digits):
return "".join(random.choice(chars) for x in range(size))
|
bdfb754c2d114f7b62f33351f48a2eccefc830e8 | DaniloBP/Python-3-Bootcamp | /max_and_min.py | 1,548 | 4.34375 | 4 |
# max() returns the largest item in an iterable or between two elements.
nums = (45,-555,36,95,88)
# print(f"Max value in {nums}: {max(nums)}\n")
# print(f"Min value in {nums}: {min(nums)}\n")
expr = "Nice to meet you."
# print(f"Max value in {expr}: {max(expr)}\n")
# print(f"Min value in {expr}: {min(expr)}\n")
nam... |
dbeaf8c49b4a6eddb12f026856a82fbe1e5c4500 | rakeshgowdan/Python_Basics | /Python_Basics/ex2_condition.py | 485 | 4.0625 | 4 | print("welcome to the bank application")
print("enter name")
name=input()
print("enter the age")
age=input()
print("enter the address")
address=input()
print("enter the salary")
salary=input()
print("enter the empid")
empid=int(input())
print("checking number of years in company")
print("-----------------------")
if em... |
e69f6720f77d9ba6eebea51f7fbd31f77f92744c | DayGitH/Python-Challenges | /DailyProgrammer/DP20120827B.py | 2,493 | 4.09375 | 4 | """
[8/27/2012] Challenge #92 [intermediate] (Rubik's cube simulator)
https://www.reddit.com/r/dailyprogrammer/comments/ywm08/8272012_challenge_92_intermediate_rubiks_cube/
Your intermediate task today is to build a simple simulator of a [Rubik's
Cube](http://en.wikipedia.org/wiki/Rubik%27s_Cube). The cube should be ... |
0fad69f1ec8bfc497cffac065df4e60a877e7363 | Lennoard/ifpi-ads-algoritmos2020 | /Fabio02_Parte02a/q20_quadrante.py | 574 | 4.15625 | 4 | #20. Leia a medida de um ângulo (entre 0 e 360°) e escreva o quadrante
# (primeiro, segundo, terceiro ou quarto) em que o ângulo se localiza.
def determinar_quadrante(a):
if (a < 90):
return '1º quadrante'
elif (a < 180):
return '2º quadrante'
elif (a < 270):
return '3º quadrante'
... |
7fbabbc99481bbc482c1506f8ea77c77dd59dce7 | lotka/conwaypear | /conway.py | 1,417 | 3.90625 | 4 | from pprint import pprint
from copy import copy
"""
Conway Rules:
1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with two or three live neighbours lives on to the next generation.
3. Any live cell with more than three live neighbours dies, as if by overpopu... |
7a964e4f20f4d907bbb55fb0c47f2465c0ec62e2 | vnpavlukov/Study | /Stepik/2. Python_Basic_and_application/test_2.3.2.1_iterators.py | 350 | 3.90625 | 4 | from random import random
class RandomIterator:
def __init__(self, n):
self.n = n
self.i = 0
def __next__(self):
if self.n > self.i:
self.i += 1
return random()
else:
raise StopIteration
x = RandomIterator(3)
print(next(x))
print(next(x))
... |
324606f5ef04a76512bbbb819df806e19166cb54 | vmirisas/Python_Lessons | /lesson3/exercise11.py | 188 | 4.0625 | 4 |
a = int(input("insert a number for a: "))
if a == 0:
print("the equation has no solution")
else:
b = int(input("insert a number for b: "))
x = - b / a
print("x = ", + x)
|
b3063f4cb40bd85ca0e31f9061b6a3fb11174eff | zhsheng26/PythonLesson | /基础语法/8_set.py | 713 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/9/12 14:12
# @Author : zhangsheng
# set 没有重复的元素
# 创建一个set
a_set = {6, 3, 4, 2}
print(isinstance(a_set, set))
# 将list转为set
a_list = [5, 1, 3, 6, 5, 6]
print(a_list)
a_set = set(a_list) # 重复元素在set中自动被过滤
print(a_set)
s1 = set([1, 1, 2, 2, 3, 3])
print(s1)... |
36bdcc19ca5b43570f345c5c2fa244c155d5a6f1 | Web-Sniper/python | /captilization.py | 449 | 3.703125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the solve function below.
def solve(s):
f,l = s.split()
f = list(f)
l = list(l)
f[0]=f[0].upper()
l[0]=l[0].upper()
f= ''.join(f)
l=''.join(l)
s= f+' '+l
return s
if __name__ == '__main__':
fptr... |
f6bfc3f6a2b71fc499e65818d68a786154f71fe2 | mufraswid/julius | /classic/affine.py | 1,465 | 3.65625 | 4 | import math
ALPHABET_SIZE = 26
def convert(c, m, b, mod=ALPHABET_SIZE):
pos = ord(c)
pos_A = ord('A')
pos_Z = ord('Z')
pos_a = ord('a')
pos_z = ord('z')
shift = pos_A
if pos >= pos_a and pos <= pos_z: #Lowercase Letter
shift = pos_a
new_c = chr((((pos - shift) * m + b) % mod) +... |
843cae5f9b2fa2f02c519c5da8a8e9cecb5d02e9 | sharmasourab93/CodeDaily | /DataStructures/Advanced/Trie/Tries_HandsOn.py | 1,599 | 3.984375 | 4 | class TrieNode:
def __init__(self):
self.children=[None]*26
# isLeaf is True if node represent the end of the word
self.isLeaf=False
class Trie:
def __init__(self):
self.root=self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self,ch):
#p... |
1e90cf954612abe7a99fec4ce39cfead4178fb49 | SafonovMikhail/python_000577 | /000403StepPyThin/000403_01_12_07_HappyTiket_02_StepikSolvers_ifElse_20191110.py | 140 | 3.546875 | 4 | a, b, c, d, e, f = input()
l = int(a)+int(b)+int(c)
r = int(d)+int(e)+int(f)
if l == r:
"Cчастливый"
else:
"Обычный" |
befa46694a9d93e03ff7b47130ac280bb7eff57a | psyde26/Homework2 | /task2.py | 2,244 | 3.796875 | 4 | # Задание 1
# Необходимо вывести имена всех учеников из списка с новой строки
names = ['Оля', 'Петя', 'Вася', 'Маша']
for each_name in names:
print(each_name)
# Задание 2
# Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём.
names = ['Оля', 'Петя', 'Вася', 'Маша']
fo... |
d8c0998c2996b814b41e28323763ee6eccc57025 | bhawnagurjar27/Programming-Practice | /Codechef/Beginner's Level/HS08TEST/HS08TEST.py | 279 | 3.625 | 4 | Assumed_withdrawal_money, initial_acco_balance = map(float, input().split())
if(Assumed_withdrawal_money % 5 == 0):
if(Assumed_withdrawal_money + 0.5) <= initial_acco_balance:
initial_acco_balance -= (Assumed_withdrawal_money + 0.5)
print(initial_acco_balance)
|
21eaee9fe2843edbc8dab59fe3aab1144d8406d2 | 27Saidou/cours_python | /test.py | 169 | 3.671875 | 4 | vallet=5000
computer_price=5000
if computer_price<=vallet:
print("l'achat est possible")
vallet-=computer_price
else:
print("oui l'achat est possible") |
68709f693e5a4285804472148a3c628fa205e940 | kazenski-dev/01_ling_progr_cesusc | /exercicio_16.py | 485 | 4.09375 | 4 | """
16 - Faça um algoritmo que leia os valores de COMPRIMENTO, LARGURA e ALTURA
e apresente o valor do volume de uma caixa retangular. Utilize para o cálculo a fórmula
VOLUME = COMPRIMENTO * LARGURA * ALTURA.
"""
#Variables
comprimento = float(input("Insira o valor do comprimento:"))
largura = float(input("Insira o va... |
bf92143ac3e9b3c6dbcb40b89795897d9d40c39d | Cloudplement/amiok | /amiok/app.py | 416 | 3.78125 | 4 | import urllib.request
def get_status(url):
""" This function gets the status code of a website.
A response of 200 if the website is okay
"""
try:
conn = urllib.request.urlopen(url)
if conn.getcode() == 200:
return "OK"
except urllib.error.URLError:
return "No... |
9460de6ef4d90a392aab793b0e07bdd882dca7fd | codekacode/Exercisespython | /Zipfunction.py | 921 | 4.4375 | 4 | """Función zip (Ambos iteradores se usarán en una construcción de bucle único):
esta función es útil para combinar elementos de datos de iteradores de tipo
similar (list-list o dict-dict, etc.) en la posición i-ésima. Utiliza la longitud
más corta de estos iteradores de entrada. Se omiten otros elementos de iterad... |
5b998d46676796a85f51230c2fa9da873cb4acb1 | axieax/sort-algorithm-time | /clean.py | 1,322 | 3.53125 | 4 | # Open file
data = open("extracted.txt", "r")
# Saves the lines into a list
lines = data.readlines()
# Lines we want to edit
edit = [3, 4, 5, 7, 8, 9]
# List with edited lines
formatted_output = []
for i in range(len(lines)):
# The first mod specifies the section (different input sizes)
# The second mod determ... |
8fe2af950cee50f14d3c39d04b8fbeb4fdb717bd | ezequielhenrique/exercicios-python | /ExerciciosPython/ex052.py | 355 | 4.03125 | 4 | num = int(input('Digite um número inteiro: '))
div = 0
for c in range(1, num+1):
if num % c == 0: # Conta a quantidade de divisores
div += 1
if div == 2:
print('{} possui {} divisores portanto é um número primo.'.format(num, div))
else:
print('{} possui {} divisores portanto não é um núme... |
921869182cd8ccfd8b7c08d5e3b1a32e8789894e | swetakum/Algorithms | /Sorting/SelectionSort.py | 590 | 4.1875 | 4 | """
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.
"""
def selectionSort(arr):
k = arr
elem = arr[0]
for i in range(0,len(arr)):
elem = arr[i]
for j in range(i+1, len(ar... |
811272fe768145971a1c4d68e10082b3fd18ba18 | zkadam/PythonKurssi | /randrangetest.py | 151 | 3.59375 | 4 |
import random
randomNum = random.randrange(1,21)
for x in range(50):
randomNum = random.randrange(1,21)
print("Random numero: ",randomNum)
|
4676d95dc1e000761253d6b079ee586892dd176f | dmmitrenko/traverse-a-tree | /Pre-order_traversal.py | 593 | 3.796875 | 4 | class Node:
def __init__(self, val = 0,left = None, right = None):
self.left = left
self.right = right
self.val = val
def PreorderTraversal(self, root):
arr = []
if root is not None:
arr.append(root.data)
arr += self.PreorderTraver... |
78b4f8ba47cbd2fa2f562965e5bb5af6faeebcd1 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/swptas001/question1.py | 476 | 3.84375 | 4 | ### Tashiv Sewpersad (SWPTAS001)
### Assignment 6 - Question 1
### 2014 - 04 - 20
## Live Code
# Initialise Variables
aNames = []
iMaxLen = 0
# Get input
sName = input("Enter strings (end with DONE):\n")
while sName.upper() != "DONE":
iLen = len(sName)
if iLen > iMaxLen:
iMaxLen = iLen
aNames.append... |
24d90e3e2ba7787eb6d120d6b2265a28e87d920c | rahulskumbhar1997/ML_projects | /regression/salary_data_example/linear_regression_using_sklearn.py | 1,941 | 3.984375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# ### Read the dataset
# In[3]:
df = pd.read_csv('dataset/Salary_Data.csv')
# ### Get some insights
# In[4]:
print(df.head())
# In[5]:
print(df.info())
# ### Plo... |
43c2cd41f4dcbf64bec301920896083e638563e5 | tanvi355/Video-to-PDF | /script.py | 4,361 | 3.53125 | 4 | from tkinter import *
from moviepy.editor import VideoFileClip
from moviepy.editor import AudioFileClip
from tkinter import filedialog
from tkinter import messagebox
from tkinter import ttk
from fpdf import FPDF
import threading
import speech_recognition as sr
import os
#variables
video_clip = ''
audio_clip = ''
#f... |
356032368303e65817da01cb31f8e8b59b8dcfe1 | tmantock/python | /random-simulation.py | 5,406 | 3.796875 | 4 | import random
class Location(object):
def __init__(self, x, y):
"""x and y are floats"""
self.x = x
self.y = y
def move(self, deltaX, deltaY):
"""deltaX and deltaY are floats"""
return Location(self.x + deltaX, self.y + deltaY)
def getX(self):
return self.x
... |
5664f70b00b22276eb4c78ca10b401b2872e2cd8 | S-Spencer/AoC19 | /day1.py | 1,021 | 4.09375 | 4 | """
Open input file and store in list 'masses'
"""
masses = []
raw = open("input_1.txt","r")
for line in raw:
masses.append(int(line))
raw.close()
"""
Next step calculate the Fuel Total required as the puzzle answer for part one 'FT1'
To calculate fuel for each mass in masses:
Divide mass by 3
Take int of the resu... |
36c8c4918b7975d07773afcc7e218a95d0d86168 | diegommezp28/ExponentialMinimunSimulation | /DataStructures/prueba.py | 326 | 3.71875 | 4 |
def prueba():
print('hola')
yield 1
print('mundo')
yield 2
print('soy ')
yield 3
print('Diego')
# for i in prueba():
# print(i)
class Generator:
def __iter__(self):
list = range(3)
for i in list:
yield i*i
clase = Generator()
for i in clase:
print... |
67e8fd09e75ddb0e1028cde5a9c81a10513b3393 | yfzhang3/UCSD-TritonHacks-2021 | /convert.py | 1,514 | 4.09375 | 4 | import random
import math
"""
PART 5 - Average Price
[list of string prices (e.g. [$, $$]) ] => float
"""
def avg_price(prices):
print("Prices input looks like the following", prices)
# Replace the below code to calculate the average prices!
# Keep in mind the type of our input (list of string)
sum = 0
for ... |
a95534de752e9a509ae9d0a6dc46eddf5ab0ebbb | Cynnabarflower/vk-analyzer | /venv/Lib/graphs.py | 12,676 | 3.53125 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def moustache(dframe, qual1, quant1, lat=12, long=7, show_axes=True):
"""
Maidzhe Alexandra
Creates boxplots from two columns of a dataframe
(qualitative - quantintative)using matplotlib.pyplot.boxplot.
:param dframe: the dataf... |
cfa8d708d00f2227b7a7fd5ac2b7657da8052d98 | rainfidelis/budget_class | /budget_app.py | 2,724 | 4.09375 | 4 | import budget
budget_dict = {
'Food': budget.Budget("Food"),
'Clothing': budget.Budget("Clothing"),
'Entertainment': budget.Budget("Entertainment"),
'Health': budget.Budget("Health"),
'Transport': budget.Budget("Transport")
}
def operations(budget_category):
while True:
try:
... |
f47ce0897b4b12681df869a808f653675f4612af | tarcomurilo/bDevBC1 | /Third/32_datetime.py | 203 | 4.09375 | 4 | #Write a Python program to display the current date and time.
#Sample Output :
#Current date and time :
#2014-07-05 14:34:14
import datetime
print(format(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S'))
|
10c85c75d324100249a6151b2a586bb336e5ea41 | edcoyote16/python_data_structures_and_algorithms_challenges | /Palindrome index.py | 769 | 3.65625 | 4 | # from collections import Counter
# #string='qmdpbsswvmqtyhkobqeijjieqbokhytqmvwssbdmq'
# string='abdccba'
# length=len(string)
# odd_value=0
# counter1=Counter(string)
# for n in counter1.values():
# if n%2==0:
# pass
# else:
# odd_value+=1
#
# counter=0
# results=[]
# string1=string[:(length+1... |
ab9d9b29b21c89ad89c7d80b77b2d39486068cad | reaprman/Data-Struct-algo-nanodegree | /proj2/problem6.py | 3,025 | 3.875 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.head = None
def __str__(self):
cur_head = self.head
out_string = ""
while cur_head:... |
d2552cdafb9934164e554e2fe1ab874c345e118c | seagull1089/random-code | /python/src/getChange.py | 964 | 3.796875 | 4 | #!/usr/bin/python
from collections import deque
'''
Given the number of quarters available,
the number of dimes available,
and number of 5 cent coins available,
return the the change for a given value in the available denominations.
change for less than 5 cents can be ignored.
uses breadth first search to... |
f86bd1aa606e88e0fb53dc9799cfda1a84f9e0b1 | meet-projects/Y2-2016-C3 | /Nir Python Test.py | 296 | 3.6875 | 4 | def Checker(list1,list2):
a = []
for x in list1:
for y in list2:
if(x == y):
a.append(x)
return a
Checker(["hi", "hi there","random letter", "not random"], ["hello", "wassup", "all cool?", "hi"])
|
c80631bc946d501f02f5769ac8ac5114f5911c82 | pkt97/projects | /rsa.py | 1,024 | 3.78125 | 4 | m=1
cipher=3
plain=2
a=1
b=1
c=1
d=1
n=1
e=2
d=1
i=0
f=1
phi=1
def prime(a):
flag=0
for i in range(2,a):
if(a%i==0):
print(a,"is not a prime number")
exit(0)
#return 0
if(flag==0):
return 1
return 1
def gcd(a,b):
if(a%b==0):
return b
else:
return gcd(b,a%b)
a=int(input("Ent... |
85f4a8ab66433bbf2a0770fcb27243fdf09c4e6a | muhdibee/holberton-School-higher_level_programming | /0x0B-python-input_output/8-load_from_json_file.py | 1,074 | 4.09375 | 4 | #!/usr/bin/python3
import json
def load_from_json_file(filename):
"""Creates a Python object from JSON file
Args:
filename (str): string of path to file
Returns:
Python object
"""
data = None
with open(filename, 'r', encoding='utf-8') as json_data:
data = json.load(json... |
61706c3ab9fafb5786d1ed4aa2f8bdfd77196441 | dixit5sharma/Individual-Automations | /CodeChef_Event.py | 644 | 3.515625 | 4 | testcases = int(input())
answer=[]
while testcases>0:
days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
k = input().split()
S_E_sub = days.index(k[1]) - days.index(k[0])
if S_E_sub>0:
diff = S_E_sub+1
else:
diff = len(days)+S_E_sub+1
counte... |
10b19f08b3e288a8cdea6817453d3d13de0dbbe6 | qlccks789/Web-Study | /17_python/part1-basic/test03_자료형_할당.py | 320 | 4.28125 | 4 | """
파이썬에서는 변수의 자료형은 대입되는 값에 따라 자동으로 정해진다.
데이터의 자료형 : type(데이터)
"""
data = 10
print(data, type(data)) # 10 <class 'int'>
data = '10'
print(data, type(data)) # 10 <class 'str'>
data = True
print(data, type(data)) # True <class 'bool'>
|
6db0831aec0d2e382969b2c2218d19f4ede2be80 | ibraheemalayan/Unbeatable_TicTacToe | /players/player.py | 609 | 3.578125 | 4 | class XOPlayer:
'''
this class represnts the xobot, it has the basic functions for a bot to play tic tac toe
Available functions are :
NextStep()
should be overridden according to difficultiy level
Grid object
'''
def __init__(self, sign):
''' Con... |
8c567fc71ece90408819e49093fed138c0743e4f | zanariah8/Starting_Out_with_Python | /chapter_06/q06.py | 1,089 | 4.09375 | 4 | # this program calculates the average of numbers
# stored in names.txt file
def main():
try:
# open the file
infile = open("numbers.txt", "r")
# initialize an accumulator
total = 0.0
# initialize a variable to keep the count of the lines
count = 0
... |
f7d41356e5ee236888604bab2d781ecaf970e460 | Natnaelh/Algorithm-Problems | /Searching/Linear_Search.py | 363 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 2 10:43:46 2020
@author: natnem
"""
def linearSearch(lst , e): #returns the index of item if it exists , if not None
for i in range(len(lst)):
if lst[i]==e:
return i
return None
mylist = [1,5,87,5,13,1,8,4,6,7,4,5,8,5... |
c252632b77c6e471a93e4ab737d650cef44d53bf | thomry/191011_pandas | /string_proce.py | 1,189 | 3.65625 | 4 | multi_str = """Guard: What? Ridden on a horse?
King Arthur: Yes!
Guard: You're using coconuts!
King Arthur: What?
Guard: You've got ... coconut[s] and you're bangin' 'em together.
"""
# splitlines 매서드
multi_str_split = multi_str.splitlines()
# 특정 문자열 가져오기
guard = multi_str_split[::2]
# replace 매서드로 guard: 문자열 빼보기
# G... |
60094482987385bbd36814e90be6b1b641955777 | sriramv95/Python-Programming | /Pandas.py | 3,369 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 5 09:11:09 2020
@author: Sriram
"""
# =============================================================================
# Pandas package - is used to general task such as storing data is in the form of
# a table, sorting of data, by group calculation etc.Arithmetic... |
703425e8fd98c3363919da60f487fb17f8ae88bf | GuptaAman08/CompetitiveCoding | /Other Company Coding Problem/Tree Practice/LCA_ver1.py | 1,059 | 3.546875 | 4 | class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def findPath(root, n1, p):
if root is None:
return False
if root.data == n1:
p.append(root.data)
return True
if findPath(root.left, n1, p):
p.append(root.da... |
38a1e97f5b202383373904a251019d12d8726ec6 | keeny8/Python-DiceGame | /DiceCards.py | 1,748 | 3.890625 | 4 | import random
#Game from when we were kids
# We have 6 dice and we bet if we will match the card or not
class Dice:
@staticmethod
def roll():
return (random.randint(0,5)+1)
class Card:
@staticmethod
def getCard():
card = [0,0,0,0,0,0]
i = 0
while i < len(card):
card[i] = Dice.roll()
i+=1
retur... |
d630735f5374ba6027edfaed217eeb9bc65655fc | Xarct/Matematica-Financeira- | /taxa aparente real .py | 450 | 3.5625 | 4 | ir = float ( input ( " Digite a taxa de juros real anual : "))
i =float ( input ( " Digite o valor da inflação anual: "))
import math
x =(( ir / 100 ) * ( (i /100 )+ 1) )
taxaaparente =(( x + ( i /100 + 1 )) - 1)
taxamensal =((( 1 + taxaaparente )**0.08333) - 1)
tp = taxaaparente * 100
tm =(( taxamensal ) ) * 100
pri... |
3f28e87f38ca5b8929fde2b0f4602f8e6113e132 | majabojarska/tadpole | /src/motor_controller.py | 8,983 | 3.796875 | 4 | import math
import typing
from . import motor
class MotorController:
""" Class for controlling front motors.
Motor pins are defined as BCM GPIO indices.
"""
SQRT_OF_TWO = math.sqrt(2)
LEFT_MOTOR_POSITIVE_GPIO = 13
LEFT_MOTOR_NEGATIVE_GPIO = 6
RIGHT_MOTOR_POSITIVE_GPIO = 26
RIGHT_MO... |
c50f65dd33c41d34de3154ba26897f27b6a054c1 | galya-study/ji | /py/1. inout_and_arithmetic_operations/ex 1 aplusbplusc.py | 308 | 3.859375 | 4 | #Сумма трёх чисел
#Напишите программу, которая считывает три числа и выводит их сумму. Каждое число записано в отдельной строке.
a = int(input())
b = int(input())
c = int(input())
d = a + b + c
print(d) |
f14efaf8822ea077598b103efb39f152f4e42c6c | AbrarJahin/Tree-Implementation-In-Python | /HashTable.py | 1,377 | 3.890625 | 4 | class HashTable:
# default constructor
def __init__(self, maxNoOfElement = 100):
self.currentSize = 0
self.maxSize = maxNoOfElement
self.hashData = [None for _ in range(maxNoOfElement)]
# a method for printing data members
def __repr__(self) -> str:
return "Size : " + str(self.currentSize) + "/" + str(self... |
c46bc5c67f43aeeee467fd7a0077e264d8ab3673 | Digvijay003/pythonbasics | /iteration.py | 395 | 3.578125 | 4 | """iterators """
class Remotecontrol():
def __init__(self):
self.channels = ['a','b','c','d','e']
self.index = -1
def __iter__(self):
return self
def __next__(self):
self.index += 1
if self.index == len(self.channels):
raise StopIteration
return self.c... |
5f295102ec7d2afa6b1ea36f381fe7f9b413e5dd | ulinka/tbcnn-attention | /scripts/test.py | 222 | 3.921875 | 4 | import itertools
list_1 = [1,2,3,4]
list_2 = [3,8,9,10]
list_3 = [list_1, list_2]
for element in itertools.product([list_1,list_2]):
print(element)
cart_prod = [(a,b) for a in list_1 for b in list_2]
print(cart_prod) |
f6e6b767fd6447ec0f0fc337f672100b68821012 | BenMeehan/Data-Structures-and-Algorithms---Revision | /Recursion/sum.py | 116 | 3.640625 | 4 | li=[1,2,3,4,5]
def summ(li):
if len(li)==1:
return li[0]
return li[0]+summ(li[1:])
print(summ(li)) |
9295ce799c6ed507b6a3055c1e501f65f5bfaedb | amohant4/coding-practice | /search.py | 2,107 | 4.34375 | 4 | # Searching algorithms.
import math
def binarySearch(arr, start, end, key):
"""
Compare with mid element and decide if you want to look in upper/lower half of array.
O(logn) complexity
"""
if start > end:
return -1
mid = start + (end-start)/2
if arr[mid] == key:
return mid
... |
511fc2b07773145048c8b3c2c6d90d5ad0aa2550 | minji-o-j/Python | /컴퓨팅 사고와 문제해결/5강 연습문제/5-8.py | 695 | 3.75 | 4 | x1=int(input("큰 원의 중심좌표 x1: "))
y1=int(input("큰 원의 중심좌표 y1: "))
r1=int(input("큰 원의 반지름 r1: "))
x2=int(input("작은 원의 중심좌표 x2: "))
y2=int(input("작은 원의 중심좌표 y2: "))
r2=int(input("작은 원의 반지름 r2: "))
dis=((x1-x2)**2+(y1-y2)**2)**0.5
import turtle
t=turtle.Turtle()
t.shape("turtle")
t.up()
t.goto(x1,y1-r1)
t.down()
t.circle(r... |
e5c61ee16c5cdb429116917f6407bed7d5a8bb4d | leomessiah10/textGame | /for_her.py | 1,128 | 3.953125 | 4 | from random import randint as rd
rand_num = rd(1,10)
tries = 1
condition = 1
#print(rand_num)
user_name = input("Hey !! What's your good name\n:-")
print('Hi',user_name + '.')
ques = input('Do you wish to play a game\n[Y/N]\n')
if ques == 'N' or ques == 'n' :
print("Well..it's the best i can do\nGood B... |
fed27214f2ab2a8e19edbb3159a4dbb28cb4ecb5 | Serdiuk-Roman/for_lit | /L6/dz6/game.py | 1,025 | 3.53125 | 4 | from abc import ABCMeta
class Unit(metaclass=ABCMeta):
def __init__(self, health, recharge):
self.health = health
self.recharge = recharge
@abstractmethod
def attack(self, target):
pass
@abstractmethod
def take_damage(self, dmg):
pass
@abstractmethod
def i... |
747a21750a6d70084cfdc09b28ec8a1fb83fbfe2 | Joy1Feng/data-structure | /03-队列.py | 384 | 3.53125 | 4 | # coding:utf-8
class Queue(object):
"""队列的实现"""
def __init__(self):
self.__list = []
def enqueue(self,item):
self.__list.append(item)
def dequeue(self):
return self.__list.pop(0)
def is_empty(self):
return not self.__list
def size(self):
return len(se... |
afc60f25693a32c6760c52224ea97124216f4aa7 | Mohan110594/Competitive_Coding-3 | /k-diff_pairs_in_array.py | 1,820 | 3.625 | 4 | // Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : None
// Your code here along with comments explaining your approach:
we used two pointers low and high.
1)if nums[high]-nums[low]==k then we add it to the result.
2)If nums[high]-nums[low] is greater than k we have to inc... |
6d9d6669e09c6c5e7d3e87305a3da8a5c006cdbd | james-claar/Python-Projects | /Pysweeper.py | 15,915 | 4.03125 | 4 | """
Minesweeper implementation in python. Played through command prompt.
Note: Although this program has an auto-save feature, it lacks much normal user input error checking and therefore tends to crash upon unacceptable user input.
"""
import random
ROWS = 7
COLUMNS = 7
MINES = 10
AUTOSAVE_BOOL = True # ... |
734f66c70aba353e4248c2cfb7ff60a31907c260 | marysiuniq/advent_of_code_2020 | /25/puzzle_25.py | 3,090 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 25 07:40:56 2020
@author: Piotr.Idzik and Maria Paszkiewicz
Puzzle 25 from https://adventofcode.com/2020/day/25
The handshake used by the card and the door involves an operation that transforms
a subject number. To transform a subject number, start with the value 1. Then... |
c2096d7af295f1e23f48d463ddb1f77b0033338c | jobafash/InterviewPrep | /educative.io/patterns/fast_and_slow_pointers/challenges/challenge3.py | 4,349 | 4.0625 | 4 | '''
Cycle in a Circular Array (hard)#
We are given an array containing positive and negative numbers. Suppose the array contains a number ‘M’ at a particular index. Now, if ‘M’ is positive we will move forward ‘M’ indices and if ‘M’ is negative move backwards ‘M’ indices. You should assume that the array is circular w... |
fb7b3dd91636e46f3c81031f36a4ce5a774d6278 | SachaReus/basictrack_2021_1a | /how_to_think/chapter_4/exercise_4_9_2.py | 557 | 4.09375 | 4 | import turtle
def draw_square(animal, size):
for _ in range(4):
animal.forward(size)
animal.left(90)
window = turtle.Screen()
window.bgcolor("light-green")
raphael = turtle.Turtle()
raphael.shape("arrow")
raphael.color("hot-pink")
raphael.pensize(5)
size = 20
for _ in range(5):
draw_square... |
54e36d09efc8b0f9d7f52b7c862cf77ef9ee50f6 | Joana-Almeida/Projeto-3-Per-odo-ADS--Sistema-Para-Estudo | /assunto.py | 3,303 | 3.5 | 4 | import sqlite3
from sqlite3.dbapi2 import Error
from conexao import Conexao
class Assunto:
def cadastrar(self,tema,descricao_assunto):
try:
conn = Conexao()
conexao = conn.conectar()
cursor = conexao.cursor()
sql = 'INSERT INTO Assunto (tema,descricao_assun... |
5ba0a234c27651064be4801494681ac95b273af6 | B3WD/python_advanced | /Lists as Stacks and Queues - Exercise/08. Crossroads.py | 1,094 | 3.53125 | 4 | from collections import deque
green_light_time = int(input())
grace_time_period = int(input())
car_queue = deque()
passed_cars = 0
crash = False
while True:
if crash:
break
command = input()
if command == "END":
print("Everyone is safe.")
print(f"{passed_cars} total cars passed... |
48413345f8b8e723c4ed9f918944fbbc5114b374 | EgalYue/Head_First_Design_Pattern | /template/barista.py | 1,149 | 3.78125 | 4 | # -*- coding: utf-8 -*-
# @FileName: barista.py
# @Author : Yue Hu
# @E-mail : yue.hu@ninebot.com
class CaffeineBeverage(object):
"""
abstract class
"""
def __init__(self):
return
def prepareRecipe(self):
self.boilWater()
self.brew()
self.pourInCup()
self.... |
3c709e1bba7456ada1246a0bdc388ca076e83f9e | Choojj/acmicpc | /단계별/08. 문자열/09. 크로아티아 알파벳.py | 1,873 | 3.546875 | 4 | import sys
word = sys.stdin.readline().rstrip()
list_num = 0
word_num = 0
while (list_num < len(word)):
if (word[list_num] == "c" and len(word[list_num:]) >= 2):
if (word[list_num + 1] == "="):
word_num += 1
list_num += 2
elif (word[list_num + 1] == "-"):
word_... |
1a746e33fbf3488e44bbad999a0985ad0c8b6c0c | LKWBrando/CP1404 | /practical2/wordGenerator.py | 644 | 4.0625 | 4 | import random
def errorCheck():
for letter in word_format:
if letter == 'c' or letter == 'v':
return True
else:
return False
VOWELS = "aeiou"
CONSONANTS = "bcdfghjklmnpqrstvwxyz"
word_format = str(input("Please enter c for consonants or v or vowels.").lower())
while not e... |
c7cfcde5a854a832c58791b087ddebe8e48f3b6b | adamandrz/Python-basics | /fibbonaci.py | 290 | 3.921875 | 4 | number = int(input("Podaj liczbe dodatnią: "))
def fibb(n):
if n <= 0:
print("Podaj liczbe dodatnia!")
elif n == 1:
print(0)
elif n == 2:
print(1)
else:
print(fibb(n-1) + fibb(n-2))
return fibb(n-1) + fibb(n-2)
print(fibb(number))
|
51cd7804bb6e35d096e9ef617113a315454b6d0a | hhoangnguyen/mit_6.00.1x_python | /midterm/problem_2.py | 222 | 3.921875 | 4 | def f():
for i in range(3):
print(i)
break
print('me')
# f()
L = [1,2,3]
d = {'a': 'b'}
def f(x):
return 3
for i in range(10, -1, -2):
print(f)
# print(int('abc'))
s = 'aaaa'
s[3] = 3
|
a7ca6fc6d2b5f18568edebee3e421fd24c10a7cb | wookim789/baekjoon_algo_note | /인프런/memo/sec1/reverse_prime.py | 592 | 3.703125 | 4 | # 뒤집은 소수
ertos = []
def reverse(x):
x = list(str(x))
x.reverse()
return int(''.join(x))
def isPrime(x):
global ertos
if ertos[x] == 1:
print(x, end =' ')
n = int(input())
arr = list(map(int, input().split()))
reverse_arr = []
for i in arr:
reverse_arr.append(reverse(i))
max_val ... |
f660417ee4130b8e9a2838c482c46c702699ab24 | stevb/project_euler_stuv | /proj_euler34.py | 334 | 3.828125 | 4 | import numpy as np
alist = []
number = 3
while True:
value = 0
for i in range(0,len(str(number))):
value += np.math.factorial(int(str(number)[i]))
if value == number:
alist.append(number)
print alist
print sum(alist)
number += 1
#There are two numbers total; 145 and 40585... |
abd4b6d5c23dd6b7ae15fc31021ae2a7c4f98ef2 | myfairladywenwen/cs5001 | /week03/10_cards.py | 526 | 4.125 | 4 | suit = input('input a card suit:')
value = input ('input a card value:')
if suit == "diamond" or suit == "heart":
color = "red"
else:
color = "black"
if value == "king" or value == "queen" or value =="jack":
isFaceCard = True
else:
isFaceCard = False
if color== "red":
if isFaceCard:
print... |
c94fe6d8fd076e96892363260dadaa09ee08e0cc | rajkumarvishnu/PyLessons | /ex40.py | 423 | 4.3125 | 4 | cities ={'CA':'San Franssisco', 'MI':'Detroit', 'FL':'jacksonville'}
cities ['NY'] = 'new york'
cities ['OR'] = 'Portland'
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not found"
cities['_find'] = find_city
while True:
print "state ?"
state= raw_input(">")
if not... |
a0838d7e3cca9e29e9c5b7cec3aaab356dadd5b1 | Regnier96/EjerciciosPython3_Erick | /Ejercicios/E1/Modulos/añoBisiesto.py | 343 | 3.796875 | 4 | def comprobarAño():
anio = input("Ingrese un año para saber si es bisiesto\n")
try:
anio = int(anio)
if anio % 4 == 0 or (anio % 100 == 0 and anio % 400 == 0):
return f"{anio} es bisiesto"
else:
return f"{anio} no es bisiesto"
except ValueError:
return... |
de325c08336d81e52e5a4c0a5d98b7d89aaa0612 | sharatvarma/python | /Image.py | 1,554 | 3.84375 | 4 | '''
Created on Sep 1, 2016
@author: murthyraju
'''
class Pixel(object):
def __init__(self, red, green, blue, alpha):
self.red = red
self.green = green
self.blue = blue
self.alpha = alpha
def reddify(self, red_increment):
self.red = self.red + red_increment
def __... |
416d28eb1290aba9b79f5a24a5ce4c5c7d00cd56 | jhwang73/datathon-2020 | /data_analysis/data_linker.py | 2,309 | 3.734375 | 4 | import pandas as pd
import csv
"""
Need to be able to take census number and determine what zipcodes lie in it.
"""
def censusToZip(censusDF, censusNum, rows):
zipNum = []
for idx in range(rows):
if censusNum == censusDF['TRACT'][idx]:
zipNum.append(censusDF['ZIP'][idx])
return zipNum
"""
Obtain the census ... |
90dd381e97ffe2f0dc899408a3c7e3fda47db992 | WhiskeyKoz/self.pythonCorssNave | /script/551.py | 665 | 4.09375 | 4 | def is_valid_input(letter_guessed):
"""
collected leter and check if the
letter proper
:param letter_guessed: guess letter
:type letter_guessed: str
:return: if letter proper return true
if letter not proper return false
:rtype: bool
"""
# letter_guessed = input("Guess ... |
55bd2fd27cabcab671253b4e1d2cb4546c6b729e | ator89/Python | /main.py | 134 | 3.84375 | 4 | # -*- coding: utf-8 -*-
a = 14;
b = 15;
def swap(a,b):
temp = a
a = b
b = temp
#swap(a,b)
a,b = b,a
print(a)
print(b)
|
fbbcb8a9efc8970e1cea5ceaac9b9278b64b5553 | whdesigns/Python3 | /1-basics/2-input/mock-exam/bot.py | 621 | 4.5625 | 5 | print("Please enter your name: ")
# The above code uses the string datatype to ask the the user what his/her name is.
name = input()
# "name" is assigned as a variable, because of the "=" sign. The variable is equal to input, meaning that whatever the user types in will be stored in this variable. In other words, na... |
b4ed39ff6e56a4468ca18a7219943b603c4000db | jsillman/astr-119-hw-1 | /operators.py | 843 | 4.34375 | 4 | x = 9 #initialize x as 9
y = 3 #initialize y as 3
#arithmetic operators
print(x+y) #addition
print(x-y) #subtraction
print(x*y) #multiplication
print(x/y) #division
print(x%y) #modulus
print(x**y) #exponent
x = 9.191823
print(x//y) #floor division
#assignment operators
x = 9 #set x equal to 9
x +=3 #in... |
f93ac43306742255ecb74f7237925d5f0bbfae7f | ahmedElsayes/my_projects | /python_assignments/tkinter_GUI/simple_calculator.py | 1,884 | 3.984375 | 4 | from tkinter import *
root = Tk()
root.title('Basic calculator')
# creat an entry. specify width and border width
e = Entry(root, width=30, borderwidth=5)
# the grid is to make the size of all calculator elements consistent with each other
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
def button_press(num):... |
aad7241d4492d9f069ce84806e349f58286d795f | lsx0304good/mpc_ml | /MPC_ML/SigmoidFunction.py | 1,333 | 3.5 | 4 | from Option import *
import numpy as np
#这个地方采用麦克劳林公式来逼近正常的sigmod函数
class SigmoidFunction:
def __init__(self):
#使用麦克劳林公式逼近
# ONE = SecureRational.secure(1)
# W0 = SecureRational.secure(1/2)
# W1 = SecureRational.secure(1 / 4)
# W3 = SecureRational.secure(-1 / 48)
# W... |
9cc1b563b3944d16b68287acd9b886f578b20d68 | jcottongin/git | /calorie2.py | 1,238 | 4.03125 | 4 |
calories = int(input("How Many Calories? "))
carbs = int(input("How Many Carbs? "))
fats = int(input("How Much Fat? "))
protein = int(input("How Much Protein? "))
def carbvalu(calories):
carbval = calories/4 # type: int
return carbval
carbval = carbvalu(calories)
#gram of carb is 4 calories
def carb(carb... |
56b469cbbce8657b44a0da30568f620e2be3b6c0 | bellc709191/01_Skill_Building | /02_input_math.py | 404 | 4.1875 | 4 | # get input
# ask user for name
name = input("What is your name? ")
# ask user for two numbers
num_1 = int(input("What is your favourite number? "))
num_2 = int(input("What is your second favourite number? "))
# add numbers together
add = num_1 + num_2
# multiply numbers together
# greet user and dis... |
4a48324271d5279c4feb0e7b8a1152e2599100fc | rsedlr/Python | /month name.py | 651 | 4.25 | 4 | 1 = "januarry"
2 = "Febuary"
3 = "March"
4 = "April"
5 = "May"
6 = "June"
7 = "July"
8 = "August"
9 = "September"
10 = "October"
11 = "November"
12 = "December"
month = int(input("Enter a month (number) > "))
if number > 12 and number < 1:
print("Between 1 and 12!")
elif number == 1:
print(1)
elif number == 2:
... |
4440603cd64b41a557caefb56044af743106855f | SantoshKumarSingh64/September-LeetCode-Monthly-Challenge | /Day3.py | 1,555 | 3.984375 | 4 | '''
Question Description :-
Repeated Substring Pattern
Given a non-empty string check if it can be constructed by taking a substring of it
and appending multiple copies of the substring together.
You may assume the given string consists of lowercase English letters only
and its length will not exceed 10000.
... |
6f9ccf62c17225f4fd0a80e21fec5b1fea6a8c5c | savitadevi/List | /Q.py | 180 | 3.75 | 4 | n=int(input("enter any number="))
i=1
sum=0
while i<n:
if n%i==0:
sum+=i
i+=1
if sum==n:
print("perfeect number",n)
else:
print("not perfect number",n)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.