blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
94ceb825a3a4f5b6599b2a92921d0451f3a15740 | MohammedAziz123/mo-projects | /RNG (built in stop).py | 329 | 3.734375 | 4 | import random #so we can create random numbers
x = 1 #for our built in stop
y = random.randint(1, 100) #for random numbers
while x == 1:
y = random.randint(1,100)
x+=x #will constantly add up x, so we can predict values, to create stop point
if x >= 256: break #when x exceeds a given value, it wi... |
d620c70cae1cbea7d49e77efae0dbb4c9ba9118a | blogart/Python | /estructuras_control.py | 2,485 | 4.0625 | 4 | #IF
"""
print("Programa de evaluacion de notas de alumnos, introduce la nota del alumno:")
notas = input()
#igual que el cin y en python cualquier cosa que introduzcas es considerado como
#texto por lo que habría que castear a int para que funciones"""
"""
def evaluacion(nota):
valoracion = "aprobado"
if nota < 5... |
c96f8b53bb4cd705250e3810b6a0805c1794cdc4 | daniel-reich/turbo-robot | /jTBQTDQ568ppnGvq7_14.py | 693 | 4.09375 | 4 | """
Write a function that sorts a list of integers by their digit length in
**descending order** , then settles ties by sorting numbers with the same
digit length in **ascending order**.
### Examples
digit_sort([77, 23, 5, 7, 101])
➞ [101, 23, 77, 5, 7]
digit_sort([1, 5, 9, 2, 789, 563, 444])
... |
e3bbe293c42a1f9021ad63a7278dbcd0c84306af | syam7/PracProject | /Assessment/problem5.py | 286 | 3.75 | 4 | input_ = raw_input("Give the list")
input_ = input_[1:len(input_)-1]
input_ = [int(x) for x in input_.split(',')]
misssing = 0
for i in range(input_[0],input_[len(input_)-1]):
if i != input_[i-1]:
missing = i
break
print "Missing number in the list is ",missing
|
f0bc36ee9b79d2b5c9d90c33648b8c08fe5be575 | robisen1/AndroidWifiCracker | /services/gps/NmeaEvents.py | 4,249 | 3.53125 | 4 | #!/usr/bin/env python
import NmeaParser
import NmeaSentences
class NmeaEventListener:
"""A base class for any class that wishes to receive NMEA events"""
def gpggaEvent(self, gpgga):
"""Method called when a GPGGA NMEA sentence is encountered
Arguments:
gpgga -- the GpggaS... |
c587ac2fb5681a791e9642aa6fb4970cc555723c | j-bennet/coursera | /posa1/eval/python/04.py | 988 | 3.5 | 4 | #!/usr/bin/python
import threading
import time
class Player(threading.Thread):
'''play ping pong!'''
def __init__(self, string):
'''init, call the super.__init__'''
super(Player, self).__init__()
self.string = string
def run(self):
'''run to print string'''
... |
3d3a4b669f9c30c81770af7307adaad72f345c83 | haidarontor/python | /module.py | 176 | 3.53125 | 4 | #import random
#value=random.randint(1,100)
#print value
#from math import pi ,sqrt
#print pi
#print sqrt(100)
from math import sqrt as square_root
print square_root(25) |
74988297d5b525b330e2e9e578da7185bb9910a7 | arun-k/python-pgms | /reverse-words.py | 261 | 3.953125 | 4 | import sys
def reverse_lines():
filename=sys.argv[1]
f=open(filename,'r')
for line in f.readlines():
for i in range(len(line.split())-1,-1,-1):
print line.split()[i],
print "\n",
if __name__ == '__main__':
reverse_lines()
|
500a250fb338793ad1f648acddd029951f50505e | KitimboRino/python_practice_tunga | /km_to_mile.py | 492 | 4.34375 | 4 | # Programme to Convert kilometers to Miles
# Initialize to a non numeric value
kilometers = ''
# while not loop to shift numeric values
while not kilometers.isnumeric():
kilometers = input('Enter the number of kilometers:')
# Convert Km to floating point number
kilometers = float(kilometers)
# km/mi conversion... |
cd1b24711ee333690bebebd7adfd7469bc60b3a4 | maximega/course-2019-spr-proj | /robinhe_rqtian_hongyf_zhjiang/Statistics.py | 8,038 | 3.5625 | 4 | '''
Problem:
The number of injuries depends on the severity of the crash. Here in the dataset, we have columns of data about
injuries in every accident, non-fatal and fatal ones. We also have columns about number of cars involved in the
accident. We want to find out if there is any relation between them.
... |
ca0133e32bdb2a7196c3b61a65f84bc339ddb8a5 | thiagonantunes/Estudos | /aulas/classes/static_method.py | 3,330 | 3.546875 | 4 | class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__ (self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = f'{first.lower()}.{last.lower()}@company.com' #first + '.' + last + '@company.com'
Employee.num_of_emps += 1
... |
c5b9cd4efb400faed6e6ca07ed0722f35129fc42 | vardhan-duvvuri/Challange | /ch16.py | 380 | 3.765625 | 4 | def isAllLettersUsed(word, required):
letters = []
requiredlist = []
for i in required:
letters.append(i)
letters = set(letters)
for i in word:
requiredlist.append(i)
requiredlist = set(requiredlist)
if len(letters.intersection(requiredlist)) == len(letters):
return True
else:
return False
if __name... |
dc9dfc308b4486f9a52ab24e25b6624269ce6b5c | grigor-stoyanov/PythonOOP | /testing/vehicle/test/test_vehicle.py | 1,643 | 3.765625 | 4 | import unittest
from project.vehicle import Vehicle
class TestVehicle(unittest.TestCase):
def setUp(self) -> None:
self.vehicle = Vehicle(30.3, 150.4)
def test_correct_init(self):
self.assertEqual(self.vehicle.fuel, 30.3)
self.assertEqual(self.vehicle.horse_power, 150.4)
self... |
af16fd4fbcaa23590d0be0e499feca98d39ba023 | Laurentlsb/Leetcode | /leetcode/editor/en/[102]Binary Tree Level Order Traversal.py | 2,255 | 4.21875 | 4 | #Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
#
#
#For example:
#Given binary tree [3,9,20,null,null,15,7],
#
# 3
# / \
# 9 20
# / \
# 15 7
#
#
#
#return its level order traversal as:
#
#[
# [3],
# [9,20],
# [15,7]
#]
#... |
bebadc275e04078333abcb3230b6c67956bed3df | WalterBluman/Tecnologo-ADS | /Algoritmos/Lista 03 - Estrutura de Repetição/QUESTAO11.py | 865 | 3.953125 | 4 | '''11. Leia LimiteSuperior e LimiteInferior e escreva todos os números primos entre os limites lidos.'''
print('Questão 11:')
def main ():
limite_inferior = int(input('Digite o limite inferior da lista: '))
limite_superior = int(input('Digite o limite superior da lista: '))
range (limite_inferior, limite_su... |
72dc70e7b5e6371d687ec820621cb2862d929bc0 | Ebtihaj1995/PythonProject | /day14.py | 936 | 4 | 4 | Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> thislist=["A","B","C","D","E"]
>>> print(thislist[1:3])
['B', 'C']
>>> print(thislist[0:5-1])
['A', 'B', 'C', 'D']
>>> print(thislist[0:6-1])
['A',... |
b9b51d7314a3c56c56b044c0e272a45040b0d63e | alecorguill/algonum_5 | /src/trapeze.py | 366 | 3.5625 | 4 | import numpy as np
def trapeze(f ,a ,b ,n):
"""
Calcule l'aire sous la courbe d'une fonction avec un intervalle donné
en utilisant la méthode des trapèzes
:param f: fonction
:param a: début de l'intervalle
:param b: fin de l'intervalle
:return: aire sous la courbe
"""
res = 0.0
for i in np.arange(a,b,n):
... |
577c38cc96c979d73fd0f7aae6dedd935d412706 | KamilJantos/Python_II | /moj_pakiet/pętle.py | 1,181 | 3.796875 | 4 | #Pętla For
for i in range(3):
print(i)
print("\n")
lista = [4, 5, 6]
for i in lista:
print(i)
for index, wartosc in enumerate(lista):
print(str(index) + " -> " + str(wartosc))
print("\n")
for krotka in enumerate(lista):
print("idx: {0}, value: {1}".format(krotka[0], krotka[1]))
print("\n")
print(... |
0b595c696b64d2a0d50ea2e00783a4e2d0358d7f | Makhambet1/homework | /ShellSort/main.py | 606 | 3.859375 | 4 | def shell_sort(lst):
gap = len(lst) // 2
while gap > 0:
for value in range(gap, len(lst)):
current_value = lst[value]
position = value
while position >= gap and lst[position - gap] > current_value:
lst[position] = lst[position - gap]
... |
16c9c0b87e9221dcba7cbec1840cc566a49c257e | brenoajs/learnpython | /Cap 8/tshirt.py | 407 | 3.84375 | 4 | def make_tshirt(text,size='g'):
"""Define o tamanho da camiseta e printa uma mensagem bonitinha"""
print(f"O tamanho da camiseta escolhido foi {size}")
print(f"A mensagem que será impressa na camiseta será: \"{text}\"")
print("\n--- Sumário do Pedido --- ")
print(f"Camiseta \"{size}\" com frase \"{text.title(... |
29ff20b330cb65b11cf002499a1f16422832514f | Yang-Jianlin/python-learn | /LeetCode/链表合并.py | 1,754 | 4.03125 | 4 | # 一个链表,奇数位升序偶数位降序,让链表变成升序的
from LeetCode.链表排序 import CreateLink
class LinkNode:
def __init__(self, element):
self.element = element
self.next = None
class LinkList:
def __init__(self):
self.head = LinkNode(None)
self.tail = LinkNode(None)
self.head_tail = self.tail
... |
3a47fee77984fa146e43b48dcbccab70b9bd25b2 | purcell3a/Dictionaries-Word-Count | /wordcount.py | 578 | 3.859375 | 4 | # put your code here.
def word_count_in_dict(file):
''' Defines count of each letter in dictionary'''
nFile = open(file)
counted_words= {} #empty dictionary
for line in nFile: ## for line in nFile:
line = line.split(" ")
# counted_letters[letter] = counted_letters.get(letter... |
5f7d07cbad8705acd1d795391f6742b987f67e86 | ziyuan-shen/leetcode_algorithm_python_solution | /medium/ex545.py | 1,536 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def boundaryOfBinaryTree(self, root: TreeNode) -> List[int]:
if not root:
return []
... |
89f53eea03fd5566938a2c5cd9c4fe93d7a2536f | GiovanniSinosini/functionsAndArrays | /teste copy.py | 2,387 | 3.671875 | 4 | import random as r
import test2_functions as f
def contaOccorencias(valor,vetor) : # conta quantos vezes o elemento aparece no vetor
count = 0
for x in vetor:
if valor == x :
count += 1
return count
def eRepetido(valor, vetor):
for n in vetor: # se N elemento do vetor
... |
1b5e3ecb66d3501dbd969772851fdd00a35585f5 | Shervink213/Algorithm-Visualizer | /algorithms/insertionSort.py | 967 | 3.75 | 4 | import time
from colours import *
def insertion_sort(data, drawData, timeTick):
#go through the array
for i in range (1, len(data)):
#J will the best value being compared to the key
key = data[i]
j=i-1
#move value of data[j] ahead of the key if the value is grea... |
7a33b6d2011cf56b36a97b4ae305510eba782633 | effyhuihui/leetcode | /linkedList/convertSortedLinkedListToBinaryTree.py | 1,157 | 3.828125 | 4 | __author__ = 'effy'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution_secondround:
# @param head, a list node
# @return a tree nod... |
dd63e325c9aef95ae42715c15b220f12b113ff24 | adrianna567/rockPaperScissors | /rockPaperScissors.py | 2,488 | 4.34375 | 4 | '''
Created on Nov 3, 2018
@author: ITAUser
OBJECTIVE:
We want to create a rock, paper, scissors game
ALGORITHUIM:
First we will create code that checks who won each round
Second we will create code that takes they input (choices) of the user
Third we will create code that creates the input(choices) of the computer
F... |
3fb78566bc808cc89a631eacad241297592b18a8 | WaleedSehgal/Interview-Questions | /Dynamic-Programming/O1Knapsack.py | 610 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Waleed
"""
cap = 50
value = [200,300,50,120]
weight = [10,50,20,30]
n = len(weight)
valmax = [[None for x in range(cap+1)] for y in range(n+1)]
def KnapSack(n, cap):
if valmax[n][cap]!=None:
return valmax[n][cap]
if n==0 or cap==0:
return 0
... |
770b39c04543305d6332324c0c1cee7918b19ef7 | TwoShot22/Likelion_BoostCourse | /File_Compression/Look_And_Say_Recursive.py | 633 | 3.796875 | 4 | def lookandsay(char, current_count, line):
if current_count < line:
i = 0
limit = current_count
output = ""
while i < len(char):
is_char_equal = char[i]
count = 1
while i+1 < len(char) and is_char_equal == char[i+1]:
co... |
cb1b4c90471f57bc2092f7e68ba4f706f8a5f00e | santiagozdw/Palindromy | /palindromy.py | 483 | 3.890625 | 4 | palindrom = '"U Gorgon" je loda Ikar. Bawi po balu car. Da łowy. Na lwicę troglodyta i "Rak", co ma moc kariatyd. Olgo - rtęci! Wlany woła Dracula, bo piwa braki. A dolej no grogu!'
palindrom_without_special_chars = ''.join(e for e in palindrom if e.isalnum())
letters = palindrom_without_special_chars.replace(" ","")... |
2ab49bbbbbbd1bb01e81fc546950b856e7a24e3f | SafonovMikhail/python_000577 | /001719StepPyStudyJr/StepPyStudyJr_lesson07_01_strings-chars_00_20210307.py | 2,172 | 4.34375 | 4 | s = "Hello! This is my new game\
Guess my number"
print(s) # Hello! This is my new game Guess my number
# работа со строками
print("Start:\n\tstring\n\tstring\n\tstring\nEnd")
print()
s1 = "Hello"
s2 = "World"
print(s1 + s2) # HelloWorld
s1 = "Hello"
print(s1 * 3) # HelloHelloHello
print()
# индексация строк
s =... |
4641dc15c85755e0ca68d94904fd2e3418ae248b | minotaur423/DevOps-TNG | /python3Scripts/string_methods.py | 167 | 3.703125 | 4 | # Practice with string methods.
s = 'abcdef'
print(s[0])
print(s[0:3])
print(s[0:4:2])
print(s.find('c'))
print(s.replace('d','z'))
print(s.count('e'))
print(len(s)) |
3444506704b5d6c97783235b8a1d7fb09bf27394 | kuatroka/pytho_web_scraping_book_lawson | /pytho_web_scraping_lawson.py | 68,245 | 3.59375 | 4 | # To add a new cell, type ' '
# To add a new markdown cell, type ' [markdown]'
import urllib.request
import pprint
def download(url):
print(urllib.request.urlopen(url, context=ctx).read())
# return urllib.request.urlopen(url).read()
# a = download('http://example.webscraping.com/places/default/index/1')
do... |
cbe28d2ee4d28bca81ed4ee4b8432ed418988367 | Aiyush-G/stringManipulationTasks | /25.py | 423 | 3.640625 | 4 | # Aiyush Gupta 10ST
# String Manipulation
# Task 25 - Ceaser Cypher
import passage
shift = -9
# zip() joins two tuples together
lower = dict(zip(range(26),"ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
upper = dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ",range(26)))
encoded = ''
for x in passage.text.upper():
if x.isalpha():
en... |
aa05f5ffaaf225a34ffc6385caf09ff3a33b26d1 | mihikabairathi/PyPI-Package-Prediction | /pypi data cleaning.py | 2,239 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
This program cleans up the data scraped by "pypi web scraping.py"
and saves it in a csv file.
"""
import pandas as pd
def change_month_to_number(datestr):
"""
converts date string to string without text, just numbers
"""
mdict = {"Jan":'1', "Feb":'2', "Mar":'3'... |
eedca9690d131604433ef3a3e28ad7a13d0c785b | Janhvi-Chauhan/programs | /mudit/anagrams.py | 258 | 4.0625 | 4 | def check(s1,s2):
if(sorted(s1)==sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings are not anagrams.")
s1=input("Enter the first string")
s2=input("Enter the second string")
check(s1, s2)
input()
|
5f7089b5f2c40a856047e6602aaca3035bf92a8c | jnasd/ctflearn | /crypto/easy/reverse_polarity.py | 524 | 3.9375 | 4 |
ciphertext = "01000011010101000100011001111011010000100110100101110100010111110100011001101100011010010111000001110000011010010110111001111101"
count = len(ciphertext)
if (not(count % 8 == 0)):
print("format of ciphertext is error, len is !" + str(count))
exit(-1)
flag = ""
i = 0
while (i < count):
byte... |
cf0ebe5d283f7c662ee5bafd86d25cc9c0e8018b | ericmintun/rl-tools | /examples/nets/rl_cnn.py | 2,572 | 3.96875 | 4 | '''
A basic CNN using RL layers. The graph is two 2d convolutional layers
with stride 1 and dilation 1, two 2d pooling layers, and one dense fully
connected layer. ReLU activations are on all steps. The default
setting are a typical MNIST net (Google's MNIST tutorial, specifically.
Input shape is a 3-tuple of the f... |
4f728345c29a644e52947686b8b3d6988993a1a0 | ironsketch/Networking | /FallQuarter/2PythonEx/listFiles.py | 776 | 3.953125 | 4 | import os
# Getting user input
repeating = False
while not repeating:
dir = raw_input("(For current directory just hit ENTER)\nIf unsure of where you are just type pwd to get location.\nType the directory to list files in it then hit ENTER: ")
# Editing input
if dir == "pwd":
print("")
prin... |
66d7c58d1a36362d6e96f119435edbe45955c98e | wulinlw/leetcode_cn | /中级算法/math_2.py | 927 | 3.890625 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/53/math/113/
# 阶乘后的零
# 给定一个整数 n,返回 n! 结果尾数中零的数量。
# 示例 1:
# 输入: 3
# 输出: 0
# 解释: 3! = 6, 尾数中没有零。
# 示例 2:
# 输入: 5
# 输出: 1
# 解释: 5! = 120, 尾数中有 1 个零.
# 说明: 你算法的时间复杂度应为 O(log n) 。
# https://blog.csdn.net/qq_3... |
33a7825d851fa72faf652f893e99ba83a1c7c755 | blurrcat/leet | /leet/problems/208_implement_trie.py | 2,241 | 4 | 4 | """
Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
>>> t = Trie()
>>> t.insert('hi')
>>> t.search('hi')
True
>>> t.search('ho')
False
>>> t.search('h')
False
>>> t.insert('h')
>>> t.search... |
d2202be3ab5fdc88f57fa63d845579282007fa21 | BVGdragon1025/-wiczenia | /Semestr 1/cwiczenia10/cwiczenie.py | 3,054 | 3.703125 | 4 | import random
lista = ["Real Madryt", "Bayern Monachium", "Manchester City", "Manchester United", "Borussia Dortmund",
"Legia Warszawa", "Chealsea Londyn", "Juventus Turyn", "Athetico Madryt", "F.C. Liverpool",
"Inter Mediolan", "Szachtar Donieck", "Ajax Amsterdam", "FC Porto", "Red Bull Salzburg",
... |
cd95b35824fd67034ec7b52e1ff53cf043837493 | parshuramsail/PYTHON_LEARN | /paresh52/a1.py | 201 | 3.9375 | 4 | while True:
guess=int(input("IAM THINKING OF A NUMBER BETWEEN 1 AND 100.\n WHAT IS YOUR GUESS?"))
if guess<1 or guess>100:
print("OUT OF BOUND ! TRY AGAIN")
continue
break
|
2c33034a8dd752ed36f62b4a8ef77f05fcfcbdc4 | joshHarter03/Python | /Chpt_3/harter_tiy.3.8.py | 368 | 3.625 | 4 | destinations=['my bed','arby','new york','japan','the moon']
print(destinations)
print(sorted(destinations))
print(destinations)
print(sorted(destinations,reverse=True))
print(destinations)
destinations.reverse()
print(destinations)
destinations.reverse()
print(destinations)
destinations.sort()
print(destinations)
dest... |
a248a76f406c7b82d88a144b8aca8463f40d6a0c | haibeey/codeParty | /cd4.py | 261 | 3.9375 | 4 | n=int(input())
for cc in range(n):
word=input().strip()
#ord() get the ascii value of a charcater
number=sum(ord(i) for i in word)
if not number&1:#checks if a number is even
print("ENTER")
else:
print("SORRY")
|
bdc6ea7bcc06523470e6751814a154d92a974758 | alasdairnicol/Project-Euler | /python/problem018.py | 2,241 | 3.546875 | 4 | """
Project Euler Problem 18
http://projecteuler.net/index.php?section=problems&id=18
By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom ... |
f7c1fd985994fa227efc2e15bd3d2facdd579f3a | bbansalaman0/ML | /Python Learning/break statement.py | 478 | 4.21875 | 4 | print("exp=1")
x=int(input("enter a element= "))
while x>=1 and x<=20:
print('x= ',2**x)
x+=1
print('out of loop')
print()
print()
print('exp=2')
x=int(input("enter a element= "))
while x>=1:
print('x= ',x)
x-=1
if x==5:
break
print('out of loop')
print()
print()
print('exp... |
62a65e38cf52af30ae303d5223be7161ee945007 | Hashah1/Leetcode-Practice | /medium/6. ZigZag Conversion.py | 1,034 | 3.59375 | 4 | class Solution:
def convert(self, s: str, numRows: int) -> str:
"""
Thought process:
TC: O(len(numRows)), SC = O(matrix)
- Create rows with length of numRows
- Loop through all char in s:
if first or last row is reached, toggle whether to go down or zigzag up
... |
bea49a62cbde30c9b6c905e8fdf7fe8541947c34 | Dhathri29/Guvi-Sessions | /factorial_again.py | 67 | 3.609375 | 4 | n=int(input())
a=1
for i in range(1,(n+1)):
a=a*i
print(a)
|
179a78e5b68e6de9a5e30ee64d5f22fefe2ecde2 | nicleong27/Codewars_Solutions | /Python/6_kyu/Find_within_array.py | 689 | 4.1875 | 4 | # We'll create a function that takes in two parameters:
# a sequence (length and types of items are irrelevant)
# a function (value, index) that will be called on members of the sequence and
# their index. The function will return either true or false.
# Your function will iterate through the members of the sequence ... |
9decdb1660dbffe90f991f7128e18020a909a138 | Air-Zhuang/MachineLearning | /lib_base/pandas_test/pandas7_Binning_GroupBy_Aggregation.py | 3,010 | 3.5625 | 4 | import numpy as np
import pandas as pd
from pandas import Series,DataFrame
import random
def gen_rand_str():
s_list='QWERTYUIOPASDFGHJKLZXCVBNM'
s=''
for i in range(3):
s+=random.choice(s_list)
return s
print("==================数据分箱技术Binning(多用于求分布情况)=================================")
print("... |
110cafff142b765a04c68172a8e6d35802e80a2e | tlarson07/basicPasswordCracker | /practice.py | 430 | 3.703125 | 4 | import hashlib
#Hash of User 0's password
user_0_hashed_pass = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
#User 0 guesses password (they have a really bad password... password)
user_0_guess = "password"
#Comparing SALT of user entered password with orignal hash
user_0_guess_hashed = hashlib.sha1(user_0_guess).hexdigest... |
94108fe282047de94e4067cc713c047ec9f9d308 | zhangran653/py | /student.py | 921 | 3.828125 | 4 | # -*- coding: utf-8 -*-
class Student(object):
count = 0
def __init__(self, name, score):
self.score = score
self.name = name
def print_score(self):
print('%s ,%s' % (self.score, self.name))
def __getattr__(self, item):
if item == 'age':
return 34
de... |
8c3c77dc03fda35eda9629814aaabbb7db89921d | cpl17/python-algos | /SortingAlgoRuntime/analyzer.py | 1,372 | 4.125 | 4 | from random import randint
import time
from sorting_algos import quicksort, mergesort, selection_sort, bubble_sort
#Function to generate lists of a certain size
def list_generator(size,max):
list = []
[list.append(randint(0,max)) for x in range(size)]
return list
#Function to determine time elapse of so... |
849daa70f1f590d8211946c1f1cfe101f3a6e9f1 | jdukosse/LOI_Python_course-SourceCode | /Chap12/enterintexcept.py | 150 | 3.640625 | 4 | try:
val = int(input("Please enter a small positive integer: "))
print('You entered', val)
except ValueError:
print('Input not accepted')
|
d1797e748a0bd7824c9ec7c726eb2bd1700217f3 | rompe/prakti-dojo | /sum_all_numbers.py | 345 | 4.125 | 4 | #!/usr/bin/env python
"""Print the sum of all numbers given on command line."""
import sys
def sum_all_numbers(args):
"""Return the sum of all numbers in a list of strings, ignoring all non-numbers."""
return (sum(int(arg) for arg in args if arg.isdecimal()) + 1)
if __name__ == "__main__":
print(sum_all... |
fb6be5dc3cdff679fba5b6bc0c63bd939e111ac3 | DanielTakeshi/Algorithmic-HRI | /scripts/human_player.py | 7,888 | 3.546875 | 4 | """
This is code to let humans play Atari games, via the Arcade Learning Environment
and the pygame library. This is based on code originally written by Ben
Goodrich, who modifed ale_python_test_pygame.py to provide an interactive
experience to allow humans to play.
I can also display RAM contents, current action, and... |
1709e3396d70214f2b77be80f54405c80b322075 | Minkov/python-oop-2021-02 | /inheritance/demos_static_class_props.py | 1,626 | 3.921875 | 4 | MIN_AGE = 0
MAX_AGE = 150
class Person:
min_age = 0
max_age = 150
def __init__(self, name, age):
self.name = name
self.age = age
# self.__age = age # Don't do this
# @staticmethod
# def __validate_age(value):
# if value < MIN_AGE \
# or MAX_AGE < ... |
782afbaab70b60f488d8b2aab4738a891401b50a | tzerchyuan/Coup | /coup/classes/Card.py | 1,390 | 3.875 | 4 | """A class representing a card in a player's hand or in the deck."""
if __name__ == "Card":
from characters import Character
else:
from .characters import Character
class Card:
def __init__(self, character: Character, id_: int, assigned: bool = False) -> None:
self._character = character
... |
cf403fea94e07e75e012b4d364155ce72526d91a | davixcky/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 181 | 3.921875 | 4 | #!/usr/bin/python3
'''Module for task 4'''
def append_write(filename="", text=""):
'''Append text to a file'''
with open(filename, 'a') as f:
return f.write(text)
|
99bffeab32ebb824d3150026fbc18de9d912c777 | bluecube246/Programming_Abstractions | /Python Game Simulation/KnightErrant.py | 1,606 | 3.703125 | 4 | from Warrior import *
from random import randint
class KnightErrant(Warrior):
"""
This class is the KnightErrant class that extends the warrior class.
An additional functionality iis that the KnightErrant can travel and gain wealth after the travel by chance.
"""
def __init__(self, name: str, age:... |
950d053477144b65b625fcd8933469df6ad5558c | ramyashah27/chapter-2-and-3-strings-and-variables | /chapter2 variables and datatypes/05pr01add.py | 141 | 3.609375 | 4 | # a=34
# b=45
# print('the sum of two integer is' , a+b)
# c=4000
# d=5
# print("the division of 2 numbers is", c/d)l
a=45
b=50
a>b |
0d83c345947c427e472855b391e3fe64a90a5d26 | subhashtodkari/py_tutorials | /com/subhash/hackerrank/practice/basic/collections/piling_cubes.py | 551 | 3.546875 | 4 | if __name__ == "__main__":
tc = int(input())
for t in range(tc):
n = int(input())
arr = list(map(int, input().split()))
# print(arr)
possible = "Yes"
slope = None
prev = arr[0]
for num in arr[1:]:
if num > prev:
slope = 1
... |
8bba9672f7caae44d12743b936e20209c829feb2 | FedorDL/Homeworks | /Homework/Lesson 6/normal.task.Lesson6.py | 4,062 | 4.3125 | 4 | # Задача-1:
# Примечание: Если уже делали easy задание, то просто перенесите решение сюда.
# Следующая программа написана верно, однако содержит места потенциальных ошибок.
# используя конструкцию try добавьте в код обработку соответствующих исключений.
# Пример.
# Исходная программа:
def avg(a, b):
"""Вернуть сред... |
bfde2743fb561b337733f2f8464f4c2971d03ce6 | wenlarry/VisualizationPython | /die_visual.py | 1,507 | 3.640625 | 4 |
# Rolling the Die
from die import Die
# Create a D6
die = Die()
# Make some rolls, and store results in a list
results = []
for roll_num in range(100):
result = die.roll()
results.append(result)
#print(results)
# Analyzing the results
# We can increase the number of simulated rolls to 1000
# We c... |
5d77b92702b1fc9ffeb457522c53cdae37f80ddc | eoinpayne/Python | /Lab5solvequadratic.py | 1,148 | 3.921875 | 4 | ##page 35 6.24
from cmath import *
'''def quadratic (num1, num2, num 3):
quad = (num1 x**2 + bx + c)
return quad '''
def calcDiscriminator (a, b, c):
discriminator = (b**2) - (4*a*c)
sol1 = (-b - sqrt(discriminator)) / (2*a)
sol2 = (-b + sqrt(discriminator)) / (2*a)
print ("discriminator =... |
bec30cb90bbd995d747b284245e86d008307515a | MysteryPuppy/iKanji | /IKanji.py | 2,618 | 3.953125 | 4 | #!/usr/bin/python
#Imports
import pandas
import random
#Quiz
def quiz(x):
test=True
counter=0
correctCounter=0
filename='Kanji/'+levelChoice+'.csv'
df=pandas.read_csv(filename)
Questions=[random.randint(0, df.shape[0])for iter in range(10)]
print("Quiz Started - "+levelChoice)
optionsC... |
e58b0d0f9f7e963fc2182541f5581a7f32cd2429 | Artarin/babilon5--alien-invasion | /ship_missile.py | 1,389 | 3.78125 | 4 | import pygame
from pygame.sprite import Sprite
class ShipMissile(Sprite):
"""class for firing missile"""
def __init__(self, ai_game):
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
self.max_on_display = 3
self.missile_speed_per_sec =... |
48bec21b2f72f551106e628f76e729b85c13d200 | seym45/erc2018 | /backend/test_in.py | 440 | 3.5 | 4 | from scipy.interpolate import interp1d
import numpy as np
y = [68 ,75, 100, 110, 123, 132, 153]
x = [318, 770, 1160, 1260, 1580, 1675, 1900]
f = interp1d(x, y)
f2 = interp1d(x, y, kind='cubic')
xnew = np.linspace(318, 1900, num=100, endpoint=True)
import matplotlib.pyplot as plt
plt.plot(x, y, 'o', xnew, f(xnew), '-'... |
fe3f2539fd48653574cc98bc4c78d2043ac1cc11 | caoliyan123/pythonStudy | /学生类父类继承.py | 988 | 3.859375 | 4 | #coding:utf-8
class SchoolKid:
def __init__(self,name,age):
self.name = name
self.age = age
#更改年龄,姓名
def re_age(self,new_age):
self.age = new_age
return self.age
def re_name(self,new_name):
self.name = new_name
return self.name
# 获取年龄,姓名
def get... |
ae395c8581efaa0513b9ba2a325b4d019988b3d1 | lijie28/PokerGame | /test.py | 2,514 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# !/usr/bin/env python
# coding: utf-8
import threading
import time
import time
bushu = 0
def count():
global bushu
bushu += 1
# print('步')
def fakein_quickSort(num,l,r):
count()
if l>=r:#如果只有一个数字时,结束递归
return
flag=l
for i in range(l+1,r+1):#默认以第一... |
548f0e1b4fb5bc51bd94c7bdd2117d28de3696c9 | IronE-G-G/algorithm | /数据结构和算法的50个代码实现/链表/LRU.py | 2,083 | 3.640625 | 4 | class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.prev = None
self.next = None
class LRUCache:
"""
O(1)的复杂度增删改查key的值,双向链表+哈希表
"""
def __init__(self, capacity):
self.capacity = capacity
self.head = Node(-1, -1)
self... |
110db9c0f420c2d460170b79657d7302dcf4f2b0 | KiranChilledOut/UdemyPythonLearn | /MyPythonLearning/MyScripts/inputCommand.py | 198 | 3.703125 | 4 | fruit1=input("whats your favorite fruit?\n")
veg1=input("whats your favorite vegetable?\n")
sweet1=input("whats your favorite sweet?\n")
print(f"\n\r{fruit1}\n{veg1}\n{sweet1}\nare your favorites?") |
103b0304a66d1c12d13fe316ef9e4a50b4575786 | jay0o0o/SnapToSnap | /descriptor/integer.py | 863 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# 使用描述符来对以Integer类型为属性的限制
class Integer(object):
def __init__(self, name):
self.name = name
def __get__(self, instance, cls):
if instance is None:
return self
else:
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, int):
rai... |
130fa02f6a822b3c160ebdf1f0c176f512d29e7b | hyerin315/boostcourse_py4e | /2ndWeek/mission/2_3.py | 1,190 | 4 | 4 |
def program():
try:
name = input("이름을 입력하세요 : ")
score = int(input("점수를 입력하세요 : "))
def grader(name, score):
if 100 >= score >= 95:
grade = "A+"
elif 95 > score >= 90:
grade = "A"
elif 90 > score >= 85:
gra... |
ac473e7a658caaed895e0cba54f400b2499bdd7f | davidlegorreta/100-days-of-Code | /Day005-100-Start.py | 459 | 4.125 | 4 | # 🚨 Don't change the code below 👇
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
total_height = 0
for height in student_heights:
to... |
e3eacc2e7aef6a075a6b3c6a9810739b1ff6e15e | VandalTryHard/Test-Task-for-work | /Consult_Test_task/task3.py | 559 | 4.125 | 4 | """3. Создать процедуру обратного отражения порядка строк (сортировки по номеру строки в обратном порядке.
Например номер строки был
1 ae1234
2 bc5678
стал
10000 ae1234
9999 bc5678"""
import csv
with open('file_task3.csv', 'r') as textfile:
for row in reversed(list(csv.reader(textfile))): #reversed возвращ... |
0e3dc064446ec43196047866b9e9b686c7bf2d66 | Kaggle/learntools | /learntools/deep_learning_intro/ex5.py | 5,329 | 3.75 | 4 | from learntools.core import *
# Add Dropout
class Q1(CodingProblem):
_hint = """Your answer should look something like:
```python
model = keras.Sequential([
# Dense
# Dropout
# Dense
# Droput
# Dense
])
```
"""
_solution = CS("""
model = keras.Sequential([
layers.Dense(128, activation=... |
9b7ac65e1e4c965d4d653f37002a0c2ee630ddf5 | ashutoshdhondkar/basic-python | /random.py | 393 | 3.890625 | 4 | '''
hi apple hello apple good apple
list1=[apple,good,hello,hi]
list2=[occurrence]
'''
str1=input("Enter a string : ")
a=str1.split(' ')
unique=[]
occurrence=[]
for x in a:
if x not in unique:
unique.append(x)
unique.sort()
for x in unique:
count=0
for val in a:
if(x==val):
cou... |
da672d9f8959cf41be5dbe0bf37cd25056ae117f | Gregcake/watch-your-back | /Part B 2/player.py | 2,023 | 3.8125 | 4 | '''
Written by Greg Tan (726323) & Luis Adjero (762095)
COMP30024: Artificial Intelligence
Project Part B: Watch Your Back!
Last Edited 11/04/2018
PLayer Class
'''
import time
from board import Board
from strategy import Strategy
MOVEMENT = 24
SHRINK_1 = 128
SHRINK_2 = 192
WHITE = "O"
BLACK = "@"
class Player:
... |
1cf506be309727bc0ec04f46c39e272397e42e17 | maro199111/programming-fundamentals | /Exercises/exercise29.py | 1,366 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 26 19:23:13 2019
@author: edoardottt
https://www.edoardoottavianelli.it
https://www.github.com/edoardottt
"""
'''
Scrivere una funzione che prende una stringa contenente una serie di parole
separate da spazi e costruisce un dizionario in cui le chiavi sono le... |
9ae9b7f28ac140f02168b54b51a8407945c9cf25 | Raghu-N-Yadav/python_codes | /create_function.py | 210 | 3.53125 | 4 | #using functuons to do thinfs
def user():
print('you have done this using a function')
def sum():
a = 0
for i in range(1,11):
a+=i
return a
#calling function
user()
x = sum()
print(x) |
10e5252b5783cb2b5596cefaeec826f203ed61e6 | Iudina/Berkley_DataScience_Bootcamp | /03_Python/PyBoss/main.py | 1,473 | 3.578125 | 4 | import os
import csv
# Path to collect data from the Resources folder
employee_data = os.path.join('..', 'Resources', 'employee_data.csv')
# Specify the file to write to
output = os.path.join ('employee_data_converted.csv')
# Read in the CSV file
with open(employee_data, 'r') as csvfile, open(output, 'w', newline=''... |
e7899fd19dfa08be8fef43bc3b02887a32cc8a71 | SeongHyukJang/HackerRank | /Python/Regex and Parsing/Detect Floating Point Number.py | 442 | 3.578125 | 4 | import re
pattern = re.compile('[+-.]?[0-9]*\.[0-9]+')
n = int(input())
for i in range(n):
string = input()
match = pattern.fullmatch(string)
if match != None:
print(True)
else:
print(False)
'''
n = int(input())
for i in range(n):
s = input()
if(s.count(".") != 1 ):
pr... |
b8043d2b38c90706529bfc81d225b49730eeacc2 | maysasaad/programmeren | /python/week6/lectures.py | 782 | 3.75 | 4 | def count_matches(s1, s2):
num_matches = 0
for i in range(len(s1)):
if s1[i] == s2[i]:
num_matches = num_matches + 1
return num_matches
def averages(grades):
"""
list of list of number) -> list of float
Precondition: grades contains at least one element with one grade
... |
12fb0b0244303871b041088c2455b1f9bcdf88e1 | Fatema110/Reverse-of-a-number | /p1.py | 268 | 4.1875 | 4 | """
REVERSE OF A GIVEN NUMBER
"""
n=int(input(" enter the number to be reversed "))
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of the number ",rev)
OUTPUT-
enter the number to be reversed 21
Reverse of the number 12
|
769bcb3c44ab27321ecbe0ab08b187a681f3656e | Dev-Vithushan/Hacker_Rank | /List_Check.py | 772 | 4.03125 | 4 | def isUnique(tested_list): #Testing the uniquness of list
if len(tested_list) == len(set(tested_list)):
print("Uniquness")
else:
print("no uniquness found")
My_List1 = [1, 3, 4, 2, 4, 2, 3, 4, 2, 4] # Creating a list
# Filltering a list using linear function
My_L... |
86aa2df21184214b41d06253f511d90ad086b736 | LuizFernandoS/PythonCursoIntensivo | /Capitulo07_InputUsuario_While/07_01LocacaoAutomoveis.py | 407 | 3.609375 | 4 | '''7.1 – Locação de automóveis: Escreva um programa que pergunte ao
usuário qual tipo de carro ele gostaria de alugar. Mostre uma mensagem
sobre esse carro, por exemplo, “Deixe-me ver se consigo um Subaru
para você.”
livro pg 171 pdf pg 156
'''
carro = input("\nQual marca de carro você gostaria de alugar? ")... |
70219231dc16edc97ca4a42a2d64c0717905cfb3 | obDann/TEQApp | /src/graphs/graph.py | 1,567 | 3.640625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from label_not_in_data_frame_error import LabelNotInDataFrameError
from abc import ABC, abstractmethod
class Graph(ABC):
'''
Abstract for graphs
'''
def __init__(self, df, x_axis, y_axis=None, title=None):
''' (Graph, DataFrame, str, str, str)... |
695991d3ed18bdbefba4188a26f1b663bd981f92 | TonyJenkins/python-workout | /15-rainfall/get_rainfall.py | 605 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Exercise 15: Rainfall
Gather and summarise rainfall data.
"""
def get_rainfall():
rainfalls = {}
while True:
city = input('Enter City: ')
if not city:
break
else:
try:
rain = int(input('Enter Rain: '))
... |
fe26f52926f33a8de5ba72eedbbf76c026afa667 | tmoerman/uncurl_python | /uncurl/vis.py | 2,344 | 3.53125 | 4 | # basic functions for visualization of clustering, state estimation, lineage
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
def visualize_poisson_w(w, labels, filename, method='pca', figsize=(18,10), title='', **scatter_options):
"""
Saves a scatter plot of a visualization of W, the res... |
312549508a5b6671fd05716c2224a27968bbfe6f | Bartekkur1/ProjektyPY | /SpacePY/vec2.py | 514 | 3.59375 | 4 | class vec2:
def __init__(self, _x, _y):
self.x = _x
self.y = _y
def add(self, vec2):
self.x += vec2.x
self.y += vec2.y
def sub(self, vec2):
self.x -= vec2.x
self.y -= vec2.y
def toString(self):
return "x: " + str(self.x) + " y: " +... |
eea1698a74fc4ed6241f046ba0dea2ce63fa9df1 | Vishal45-coder/Day11 | /Module4_A3_List(Empty or Not).py | 192 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 30 19:25:22 2020
@author: vishal
"""
list=[]
if(list==[]):
print("the list is empty")
else:
print("list is not empty") |
0a2c8e176b0ba5b55528011ba746f8f76ae569c4 | mpatrickaires/curso-python | /ExerciciosPython/ex103.py | 333 | 3.703125 | 4 | def ficha(nome, gols):
if nome == '':
nome = '<desconhecido>'
if not gols.isnumeric():
gols = '0'
gols = int(gols)
print(f'O jogador {nome} fez {gols} gol(s) no campeonato.')
jogador = str(input('Nome do Jogador: ')).strip().title()
gol = str(input('Número de Gols: ')).strip()
ficha(jo... |
128a65494634499255bf12a38afcb4a2f1e4527d | MagdalenaKoltuniak/Practice | /zframez_exercise.py | 6,972 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 22 18:56:14 2020
@author: Magdalena
"""
# =============================================================================
# 1. Write a python program to print the square of all numbers from 0 to 10
# =========================================================================... |
8357a3aeaaf8112ae46f02900ec237f19abea7be | nn98/Python | /Python-19_2/P1718.py | 310 | 3.5 | 4 | # -*- coding: ms949 -*-
# 11/21 13:30
word=input()
code=input()
nowC=-1
R=''
for i in word:
nowC+=1
if i==' ':
R+=i
continue;
w=ord(i)-97
c=ord(code[nowC%len(code)])-96
p=w-c
if p<0:
r=chr(123+p)
else:
r=chr(97+p)
R+=r
print(R) |
0eaa91e2e1860016f4967b063c78f469209e5c50 | vincent-kangzhou/LeetCode-Python | /245. Shortest Word Distance III.py | 590 | 3.53125 | 4 | class Solution(object):
def shortestWordDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
last1 = float('-inf')
last2 = float('-inf')
ret = float('+inf')
for i,w in enume... |
37822784b0c03d039339ec1d277fedd29358215a | xushubo/learn-python | /learn34.py | 6,800 | 4.75 | 5 | #继承和多态
#在OOP程序设计中,当我们定义一个class的时候,可以从某个现有的class继承,新的class称为子类(Subclass),
#而被继承的class称为基类、父类或超类(Base class、Super class)。
#比如,我们已经编写了一个名为Animal的class,有一个run()方法可以直接打印:
class Animal(object):
def run(self):
print('Animal is running...')
#当我们需要编写Dog和Cat类时,就可以直接从Animal类继承:
class Dog(Animal):
pass
class C... |
219f1b0a470b1f24234096bb5552f90d6c3b8eba | 1144063098/python_source | /python_oop/file2.py | 125 | 3.9375 | 4 | a={"name":"张三","age":18,"addr":"长沙"}
s={k:v for k,v in a.items() if k=="age" or k=="addr"}
print(a.get("named",18))
|
2d1cdb7ed9c2b3edff97a36cfb9424c56f47462a | KeerthikaElumalai/Program | /pro33.py | 181 | 3.515625 | 4 | n=input()
flag3=0
for i in range(0,len(n)-1):
for j in range(i+1,len(n)):
if n[i]<n[j]:
flag3=1
print(n[j:])
break
if flag3==1:
break
else:
print(n)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.