blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
c2fbe51a4c53f968c64cf470c86ac1cf6b4b448d | TardC/books | /Python编程:从入门到实践/code/chapter-10/cats&dogs.py | 361 | 4.15625 | 4 | def print_file(filename):
"""Read and print a file."""
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
# msg = "The file " + filename + " does not exist!"
# print(msg)
pass
else:
print(contents)
print_f... |
65dee415796977afd4ff9f2aa33f29f15d070333 | jimenezjl/Decathlon | /lanzamiento_peso.py | 2,041 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 27 09:28:24 2023
@author: jose
"""
import random
max_shotput = 0
def attempt():
global max_shotput
total_shotput = []
results = []
for i in range(3):
total_score = 0
num_of_dice = 0
print(f"INTENTO {i+1}/3")... |
1bed2ec2ebdc4eebfa40805960470e2ea44a5d52 | ChastityAM/Python | /Python-data/identity_operators.py | 396 | 3.96875 | 4 | x = 10
y = 10
print(x == y)
print(x is y)
str1 = "Hello"
str2 = "Hello"
print(str1 == str2)
print(str1 is str2)
list1 = [1, 2, 3] #these have the same values, but are
list2 = [1, 2, 3] # 2 different objects
print(list1 is list2) #checks if they are the same object(identity)
print(list1 == list2) #checks if values are s... |
ba4dc1ab21a2fecb24c763b3a5b8082181a016e5 | ChastityAM/Python | /Python-sys/functions.py | 836 | 4.03125 | 4 | def weird_arithmetic(x, y, z): #function defined
print((x**x + y**z) // z) #code block
weird_arithmetic(5, 6, 7) #function called
def greet_friend(greeting, name):
print(greeting, name + "!")
greet_friend("Hello", "Bethany")
def my_sum(n1, n2):
return n1 + n2
some_number=my_sum(8, 3)
print(some_numbe... |
b295d0857648ad8e09a8a484e58d4745ebe74b69 | ChastityAM/Python | /Python-sys/runner_up.py | 561 | 4.15625 | 4 | #Given participants score sheet for University, find the runner up score
#You're given n scores, store them in a list and find the score of the
#runner up.
list_of_numbers = [2, 3, 6, 6, 5]
print(sorted(list(set(list_of_numbers)))[-2])
#or
list2 = [2, 3, 6, 6, 5]
def second_place(list2):
list2.sort(reverse=True)
... |
9673488c7cfc5abd1e0339bd5815615780fa8b07 | ChastityAM/Python | /Python-sys/lists.py | 721 | 4.21875 | 4 | list_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8]
a = list_of_numbers[5] #selecting an index
b = list_of_numbers[2:5] #slicing the list
#doesn't include last index given in printout
print(a)
print(b)
list_of_numbers[5] = 77
list_of_numbers.append(10)
list_of_numbers.pop(4) #removes at this index, if not indi... |
c4c1bc5ac2c4e5d28656af5dc987968d34c2feaa | ChastityAM/Python | /Python-sys/sqrt.py | 231 | 4.25 | 4 | import math
#Create a function that takes a number n from the user.
#Return a list containing the square of all numbers between 1 and n
num1 = int(input("Please enter a number: "))
def sq_root(num1):
return math.sqrt(num1)
|
ca1344e9c1aeff9d2c31625950efb8e5a06d50d5 | goranbs/teaching | /FYS-MEK1110-mechanics/NewtonsCradle.py | 2,363 | 3.640625 | 4 | # Newtons Cradle simulates a Newtons cradle.
import numpy as np
from scitools.std import *
def force(dx,d,k,q):
if dx<d:
F = k*abs(dx-d)**q
else:
F = 0.0
return F
N = 3 # Number of balls
m = 1.0 # mass of balls
k = 100.0 # [N/m]
#q = 4.0 # exponent
#q = 3.0/4 # exponen... |
4a24013d68d2f0671f20ba5cf6ea2fc5e9e38c97 | bharathims/python3 | /2.variables/data_types.py | 447 | 3.78125 | 4 | #!/bin/python
'''
Print all data types available in python 3
Author: Bharathi M
Date: 2021-03-01
'''
int = 1
float = 2.1
char = 'c'
string = 'sample'
list_type = [1, 2, 3, 4]
tuple_type = (1, 2, 3, 4)
dictionary_type = {'one' : 1, 'two' : 2 }
print('Integer : ', int)
print('Float : ', float)
print('Character : ', ... |
7def5f246e800cd47f5e9ba0b7a056dba8cd9998 | SeezSawz2222/python_basics__001 | /12.py | 313 | 3.640625 | 4 | A=float(input())
B=float(input())
C=float(input())
TRI=.5*A*C
CI=3.14159*(C**2)
TRA=((A+B)/2)*C
S=B**2
R=A*B
print("TRIANGULO: {0:.3f}".format(TRI))
print("CIRCULO: {0:.3f}".format(CI))
print("TRAPEZIO: {0:.3f}".format(TRA))
print("QUADRADO: {0:.3f}".format(S))
print("RETANGULO: {0:.3f}".format(R))
|
cc3012a4c13366fa07553d01621692b7dd2d0f75 | Akashnishad17/javap | /testing_tool.py | 4,026 | 3.8125 | 4 | """Number Guessing interactive judge."""
# Usage: `testing_tool.py test_number`, where the argument test_number is
# either 0 (first test set) or 1 (second test set).
from __future__ import print_function
import random
import sys
# Use raw_input in Python2.
try:
input = raw_input
except NameError:
pass
_ERROR_M... |
6a2ae063899030dc2ff4a763eb167884bbc462fb | zloy-zhake/kaz_nlp_tools | /clean_text.py | 10,323 | 3.546875 | 4 | #!/usr/bin/env python3
# script cleans texts in Kazakh and English.
# # it leaves:
# - letter from alphabets
# - punctuation
# for any other symbol it asks a user for a decision
# TODO добавить '
# docstring for docopt
"""clean_text.py
Usage:
clean_text.py (-i | --input) <input_file> (-l | --lang) <language> ... |
45411d2e44e48fb7ad22a1683ee9268aaecaf7eb | JaredSullin/read_and_addtofile | /read_and_add.py | 576 | 3.953125 | 4 |
def adduser():
adduser = input("choice y/n")
file = open("users.txt",'a')
while adduser == 'y' or adduser == 'Y':
name = input('what is your name')
age = input('what is your age')
else:
print('name and age not added good bye')
file.close()
def readuser ():
... |
f6c4afc3d0cf3c95f19ddce963631c507a9d3cb9 | XOfSpades/learn_you_some_python | /user.py | 375 | 3.90625 | 4 | class User:
def __init__(self, first_name, last_name, email):
self.first_name = first_name
self.last_name = last_name
self.email = email
def name(self):
print(self.first_name, self.last_name)
users = [
User("Kira", "Katze", "Kira@Katze.com"),
User("Hugo", "Hase", "Hugo@Hase.com"),
User("Ingo... |
6fd14730d62a856aabe36f459f15754bac714998 | afcarl/PythonDataStructures | /chapter7/exercise_5.py | 356 | 3.859375 | 4 |
def find2(strng, ch, start):
index = start
while index < len(strng):
if strng[index] == ch:
return index
index += 1
return -1
def count_letters(fruit,ch):
import string
count = 0
for i in xrange(len(fruit)):
if find2(fruit,ch,start=i) != -1:
count += 1
return coun... |
58ffa2b3817a39d26f4083a6a1e19149c39ba9af | afcarl/PythonDataStructures | /chapter6/exercise_9.py | 387 | 3.765625 | 4 | def sum_of_squares_of_digits(n):
"""
>>> sum_of_squares_of_digits(1)
1
>>> sum_of_squares_of_digits(9)
81
>>> sum_of_squares_of_digits(11)
2
>>> sum_of_squares_of_digits(121)
6
>>> sum_of_squares_of_digits(987)
194
"""
n = str(n)
squares = []
for i in n:
... |
0005a28c25142263623a6c52686bd0d1ef6def3f | afcarl/PythonDataStructures | /chapter4/exercise_7.py | 410 | 4.25 | 4 | def is_divisible_by_n(x,n):
if type(x) == type(int()) and type(n)==type(int()):
if x % n == 0:
print "yes,"+str(x)+" is divisible by "+ str(n)
else:
print "no,"+str(x)+" is not divisible by "+str(n)
else:
print "invalid input"
num1 = input("Please input a number ... |
4a118fbc0b36030195ebc7067b6feb98de8c4945 | afcarl/PythonDataStructures | /chapter6/exercise_3.py | 606 | 4.3125 | 4 | def print_multiples(n, high):
#initialize and iterator
i = 1
#while the iterator is less than high, print n*i and a tab
while i <= high:
print n*i, '\t',
i += 1
print #print a new line
def print_mult_table(high):
#initialize an interator
i = 1
#while the iterator is less... |
5acfd68274725cb55b9adf48abb38ead506b4c44 | afcarl/PythonDataStructures | /chapter5/exercise_1.py | 403 | 3.53125 | 4 | def compare(a,b):
"""
>>> compare(5,4)
1
>>> compare(7,7)
0
>>> compare(2,3)
-1
>>> compare(42,1)
1
"""
if a > b:
return 1
elif a < b:
return -1
elif a == b:
return 0
else:
return "no comparison operator for types"+str(type(a))+" "... |
a80fa9b99c1dce2fdb8421a4367da6192278db98 | gameboy1024/ProjectEuler | /src/problem_55.py | 1,821 | 3.9375 | 4 | # -*- coding: utf-8 -*-
'''
Lychrel numbers
Problem 55
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrom... |
412121bdb648cdbb94f90b75d26091acd1b9fa50 | gameboy1024/ProjectEuler | /src/problem_74.py | 1,763 | 3.578125 | 4 | # -*- coding: utf-8 -*-
'''
Digit factorial chains
Problem 74
The number 145 is well known for the property that the sum of the factorial of
its digits is equal to 145:
1! + 4! + 5! = 1 + 24 + 120 = 145
Perhaps less well known is 169, in that it produces the longest chain of
numbers that link back to 1... |
44f8ce384bf96d2f2d42ae22127d28b36aba8773 | gameboy1024/ProjectEuler | /src/problem_59.py | 5,407 | 3.75 | 4 | # -*- coding: utf-8 -*-
'''
XOR decryption
Problem 59
Each character on a computer is assigned a unique code and the preferred
standard is ASCII (American Standard Code for Information Interchange). For
example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryption method is ... |
0c558451db32445c0244d78b8502009b3010c324 | gameboy1024/ProjectEuler | /src/problem_62.py | 922 | 3.71875 | 4 | # -*- coding: utf-8 -*-
'''
Cubic permutations
Problem 62
The cube, 41063625 (3453), can be permuted to produce two other cubes:
56623104 (3843) and 66430125 (4053). In fact, 41063625 is the smallest cube
which has exactly three permutations of its digits which are also cube.
Find the smallest cube for w... |
cc908943a9af228bd91729bb113e4d8504e57ae5 | gameboy1024/ProjectEuler | /src/problem_56.py | 681 | 3.609375 | 4 | # -*- coding: utf-8 -*-
'''
Powerful digit sum
Problem 56
A googol (10100) is a massive number: one followed by one-hundred zeros;
100100 is almost unimaginably large: one followed by two-hundred zeros.
Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of ... |
99b78f5621a8bc43a3d8df1349032f8710e5e6db | gadi42/499workspace | /Lab3/lab2/sensor.py | 581 | 3.78125 | 4 | #!/usr/bin/env python3
from math import sin
from random import gauss
def generate_sensor_data(n, sigma=0.01):
"""
Generate data from a fake sensor. These data are generated according to a sine function, with zero-mean
Gaussian noise, with standard deviation sigma.
"""
data = []
for i in ran... |
4bad22567b2966e77af73848c19bb95542360a1a | gadi42/499workspace | /Lab4/counter.py | 916 | 4.46875 | 4 | def get_element_counts(input_list):
"""
For each unique element in the list, counts the number of occurrences of the element.
:param input_list: An iterable of some sort with immutable data types
:return: A dictionary where the keys are the elements and the values are the corresponding
numb... |
ecac6bd7d37d233e831f930c7230f93cd67c85e8 | gadi42/499workspace | /Lab3/lab2/reverse.py | 1,142 | 4 | 4 | #!/usr/bin/env python3
from itertools import chain
def reverse_i(given_list):
check = list(chain(given_list))
backtrack = []
for i in check:
backtrack.append(check[-1])
check = check[:-1]
i += i
return backtrack
def reverse_r(given_list):
# if isinstan... |
322e9d3f5f519307bf7c344599a2eebba8a01e55 | molberte/DE_CP | /main.py | 2,121 | 3.578125 | 4 | import matplotlib
from tkinter import *
from tkinter import ttk
from plotting import Points, Plot
root = Tk()
root.title("DE_practicum")
matplotlib.use('TkAgg')
mainframe = ttk.Frame(root)
mainframe.grid(column=0, row=0)
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
root.configure(back... |
94ffe72b5a42e77d6af2e16d9c6fdb44688fe3d2 | zhuzhengren/sklearn | /5_4.py | 1,661 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
X_train = [[6],[8],[10],[14],[18]]
y_train = [[7],[9],[13],[17.5],[18]]
X_test = [[6],[8],[11],[16]]
y_test = [[8],[12],[15],[18]]
regressor = LinearRegression()
r... |
46a4bdbaa6ba925270e78cf414c86bd881c51718 | zhuzhengren/sklearn | /3_2.py | 587 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
X_train = np.array([
[158,64],
[170,86],
[184,84],
[191,80],
[155,49],
[163,59],
[180,67],
[158,54],
[170,67]
])
y_train = ['male','male','male','male','female','female','female','female','female']
x = np.array([[155,70]])
distances = np.sqrt(np.sum((X_t... |
ff157549022b7a3a5b5ef0e12bc3591f7dc42856 | lkrych/aoc | /20/python/aoc4.py | 3,252 | 3.796875 | 4 | # part 1
# def is_passport_valid(passport):
# valid_fields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]
# for field in valid_fields:
# if field not in passport:
# return False
# return True
# def passport(data):
# current_passport = {}
# valid = 0
# for line in data:... |
300584ef7b0ffc04328684cf72a128cf72779819 | lkrych/aoc | /20/python/aoc3.py | 1,195 | 3.734375 | 4 | # def toboggan(data):
# trees = 0
# curr_pos = 0
# for line in data:
# line = line.strip()
# if line[curr_pos] == '#':
# trees += 1
# curr_pos = (curr_pos + 3) % len(line)
# return trees
# if __name__ == "__main__":
# text_file = open("../input/aoc3.txt", "r")
# ... |
0a33c0d5763df1081f544975840002f44160997f | lkrych/aoc | /20/python/aoc1.py | 1,446 | 3.96875 | 4 | def two_sum(arr, target):
hash = {}
for el in arr:
diff = target - el
if diff in hash:
return (el, diff)
else:
hash[el] = True
return ()
def three_sum(arr, target):
arr = sorted(arr)
bottom_idx = 0
top_idx = len(arr) - 1
while bottom_idx < top... |
54b2cdc697fcf85dea31701df62f6d8fa6fafc7c | lkrych/aoc | /20/python/aoc16.py | 6,152 | 3.71875 | 4 |
def is_ticket_valid(val, rules):
# print(f"checking the validity of {val}")
found_between_range = False
for rule in rules:
split_by_or = rule.split("or")
for i in range(len(split_by_or)):
split_by_or[i] = split_by_or[i].strip()
for s in split_by_or:
... |
a4e2b3401d7bda242eed2d352896a73253204007 | Yeeyao/cs61a | /ch3/lab10.py | 2,090 | 3.859375 | 4 | def eval(self, env):
"""
>>> env = {
... 'a': Number(1),
... 'b': LambdaFunction([], Literal(0), {})
... }
>>> Name('a').eval(env)
Number(1)
>>> Name('b').eval(env)
LambdaFunction([], Literal(0), {})
>>> print(Name('c').eval(env))
None
"""
"*** YOUR CODE HERE ... |
b2ee525b8f30c93f29157f028e21c863512f3ebb | zoshaikh17/shortest_path | /Project.py | 5,552 | 3.625 | 4 | import copy
from collections import defaultdict
class Building:
def __init__(self):
self.name = ""
self.edgeList = []
self.dist = float("Inf")
self.prev = None
class Path:
def __init__(self, destination, distance):
self.destination = destination
... |
1fe469a732a79d1753a0a886cd9aa6273c84a1fa | RanjitThakur678/new- | /center.py | 501 | 4.3125 | 4 | # name = "Ranjit"
# print(name.center(10,"!"))
# name= input("enter your name :")
# print(name.center(len(name)+8,"*"))
def leap(year):
"year -> 1 if leap year, else 0."
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return f"{year} is a leapyear"
return "Not a leap year"
def _days_bef... |
5bb8b282a4f2b1f6c5e468d53401e71c394fb1b2 | elitejakey/schoolks4 | /birthday.py | 282 | 4.0625 | 4 | name = input('What is your name?')
days = int(input('How many days are there until your birthday?'))
answer = (days*86400)
print(f'Hey {name}, you told me that your birthday is in {days} days. This means it will be roughly {answer} seconds until then! How cool is that?')
|
99c26fd82c71eadd3188749f669e8237e5d45165 | elitejakey/schoolks4 | /ages.py | 233 | 3.984375 | 4 | ages = int(input('What is the total ages of all the students?'))
students = int(input('How many students are there?'))
average = (ages / students)
answer = int(float(average))
print('The average age in the room is', answer)
|
f2af62531654382e875b03c096667e8fadd72bba | HeadYak/COMP3311-database-systems | /Assign3/best | 1,329 | 3.53125 | 4 | #!/usr/bin/python3
# COMP3311 20T3 Ass3 ... print name, year, ratings of top N movies
import sys
import psycopg2
#from helpers import whatever, functions, you, need
# define any local helper functions here
# set up some globals
usage = "Usage: best [N]"
db = None
max_movies = "select count(*) from movies"
# print(... |
49e06f01b2744e0b0d7f972e42944bbbab135c78 | convoliution/Code-Medley | /Python/graphs.py | 4,634 | 3.640625 | 4 | class Node:
def __init__(self, value, num_children):
self.value = value
self.children = [None]*num_children
class LinkedList:
class ListNode(Node):
def __init__(self, value):
super().__init__(value, 1)
@property
def next(self):
return self.childr... |
a87ea9a4bdf195f93370d1b098486c2f3127bb09 | mentekid/myalgorithms | /RSA/stringConversion.py | 1,830 | 3.984375 | 4 | BITS = ('0', '1')
ASCII_BITS = 8
def bitlist2str(bitlist):
"""Returns a string in {0,1} from the bitlist"""
return ''.join([BITS[bit] for bit in bitlist])
def seq2bits(sequence):
"""Returns a sequence of 1s and 0s from a bit sequence"""
return [0 if bit=='0' else 1 for bit in sequence]
def padding(bi... |
8874c382f717ef3828bda2da5763cb2d833f655b | mentekid/myalgorithms | /Permutations/permutations.py | 1,092 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Computes all possible permutations of [0...N-1] for a given N
If you need the permutations of another array, just use N = len(alist)
and then print alist[perm] for perm in p
Author: Yannis Mentekidis
Date: April 28, 2015
"""
from time import clock
import sys
def all_... |
701c2b995e0d5347a67de209fc93a3e5abce2660 | OliverVuong/Python-Chess | /Printer.py | 416 | 4 | 4 | # Prints the board to the console
def printBoard(data):
"""Prints a chess board representation to console"""
print(" 0 1 2 3 4 5 6 7")
for rowIndex, row in enumerate(data.board.board):
for piece in row:
if piece == 0:
print(' 0', end='')
... |
0260a56f3554e26a3419e999bc99b2239bf4b2fa | leewensheng/python-learning | /python/operator/bit.py | 508 | 3.75 | 4 | '''
左移 运算数的各二进位全部左移若干位,由 << 右边的数字指定了移动的位数,高位丢弃,低位补0。
右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,>> 右边的数字指定了移动的位数
'''
a = 3
b = 0b00011
c = 0x00003
d = 0o003
print(a,b,c,d)
print(bin(a))
print(hex(3))
print(oct(4))
bleft = b << 1 #左移1位
bright = b >> 1 #右移1位
print('00000011 left move eq 00000110 ',bleft)
print('00000011 right move ... |
b9ae313b4c9255da1729bd5cfe509e26e291c974 | ravgeetdhillon/project-euler | /004.py | 600 | 3.78125 | 4 | def isPalindrome(num):
rev = 0
a = num
while a != 0:
rev = rev * 10 + a%10
a //= 10
if num == rev:
return True
return False
def largestPalindrome(num):
ans = 0
for p in range(110, 991, 11):
for q in range(100000//p + 1, 1000, 1):
product = p * q
... |
6f915ad6eac1d80bcec52c4cfa5d0f7401f9ccd1 | Coder2100/mytut | /04_while.py | 200 | 3.84375 | 4 | #initial sub sequence og the fibonacci series
a,b = 0,1
while a < 10:
print(a)
a,b = b, a+b
i = 256 * 256
print('The value of is is', i)
while a < 1000:
print(a, end=',')
a,b = b, a+b |
567c3c71afd8baa107f1d3a3a9a130edbb2401f9 | Coder2100/mytut | /13_1_input_output.py | 2,484 | 4.4375 | 4 | print("7.1. Fancier Output Formatting")
year = 2016
event = 'referendum'
print(f"Result of the {year} {event} was BREXIT.")
print("The str.format()")
yes_votes =42_572_654
no_votes =43_132_495
percentage_yes = yes_votes/(no_votes + yes_votes)
results = '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage_yes)
p... |
c55ab25a6d1739b3ef32983dc4d8d456b9ef165a | lucienraeg/name-gender-classifier | /name-gender-classifier.py | 1,936 | 3.921875 | 4 | # Lucien Rae 2017
# A classifier that predicts whether a name is male or female
# Uses a DecisionTree Classifier
# Data from a list of 258000 names, 50/50 ratio between male and female
# Features are the digits that correspond with the letters in the name
# Labels are the gender
import csv
import random
import numpy a... |
c5940bdf85d66da9b09508fdc54ca90575d36d3b | chaingng/algorithms | /tri.py | 966 | 4.03125 | 4 | import collections
class TriNode(object):
def __init__(self):
self.children = collections.defaultdict(TriNode)
self.is_word = False
class TriTree:
def __init__(self):
self.root = TriNode()
def insert(self, word):
current = self.root
for letter in word:
... |
bb11da46ed9ca88d1660deed1492dcb697e0d7bb | ogarnica/Compumaticas | /matrices.py | 362 | 3.78125 | 4 | a = int(input('a: '))
b = int(input('b: '))
c = int(input('c: '))
d = int(input('d: '))
t1 = int(input('t1: '))
t2 = int(input('t2: '))
if a*c == c*b:
print('No tiene soluciones idiota!!!!!!!!')
exit()
res = 1/(a*d-c*b)
alfa = d*res
beta = -c*res
gamba = -b*res
delta = a*res
print(alfa, '|', beta)
print('-... |
fa6b5344990e7a13ad82e2a05d2a3cfa20cd1a16 | ogarnica/Compumaticas | /snake.py | 2,063 | 3.625 | 4 | import pygame as pg
import sys
from turtle import *
import random as r
posix = r.randint(-249, 249)
posiy = r.randint(-249, 249)
screen = pg.display.set_mode((250, 250))
penup()
shape("turtle")
t = Pen()
t.speed(0)
sensibility = 25
screen = Screen()
screen.addshape('turtle.png')
t.shape('turtle.png')
running = True... |
ccb6ecfcbd6983376041de1ff61e281972aa7c45 | ogarnica/Compumaticas | /calculator.py | 86 | 3.828125 | 4 | b = 0
while True:
a = int(input('numero: '))
b = a+b
print('resultado:',b) |
a3d1d460d89c50134b85a3064080acc669d14c9c | ogarnica/Compumaticas | /frutas.py | 541 | 3.84375 | 4 | import math
f1 = 'movimiento'
f2 = 'naranja'
f3 = 'ciudadano'
frutas = [f1, f2, f3]
for x in frutas:
for y in frutas:
for z in frutas:
if x == y or x == z or y == z:
pass
else:
print(x, y, z)
print('\n___________NANANANANAN___NANANANANA_____________... |
0611541f0d8932bc8c605f05795b228cd23c7fd5 | ogarnica/Compumaticas | /espiral_arquimides.py | 225 | 3.765625 | 4 | import turtle
import math
for x in range(1, 101):
t = x / 10 * math.pi
x = (1 + 5 * t) * math.cos(t)
y = (1 + 5 * t) * math.sin(t)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.stamp()
|
052f147372618d4efa3feb4bfc4e3f3d299d8c24 | ogarnica/Compumaticas | /triangulo.py | 421 | 3.65625 | 4 | import turtle
t = turtle.Pen()
turtle.title('triangulos')
turtle.bgcolor('blue')
t.pensize(2)
t.pencolor('purple')
lado = float(input('di el lado: '))
escala = float(input('escala: '))
triangulo_2 = escala * lado
t.forward(lado)
t.left(120)
t.forward(lado)
t.left(120)
t.forward(lado)
t.left(120)
t.forward(triangulo... |
a012f0f8dac497481300c2f0daa35897f11edef4 | kKunov/W1 | /oop_D2/laptop.bg.py | 1,844 | 3.5625 | 4 | class Product:
def __init__(self, name, stock_price, final_price):
self.name = name
self.stock_price = stock_price
self.final_price = final_price
def profit(self):
return self.final_price - self.stock_price
class Laptop(Product):
def __init__(self, name, stock_price, fin... |
2453c16985aec40d292ff95b98e636068fce0fb2 | mikeliddle/CS235-Test-Driver | /Smart_Diff/SmartDiff.py | 988 | 3.5 | 4 | #!/usr/bin/python3
import sys
def smart_diff(file1, file2):
with open(file1, "r") as f1:
with open(file2, "r") as f2:
i = 0
j = 0
student_file = f1.read()
key_file = f2.read()
while i < len(file1) and j < len(file2):
... |
3f0a1e74863e4ac6e13e922287297fed210ea084 | binario200/Python | /censor.py | 210 | 3.671875 | 4 | def censor(text, word):
asterisks = "*" * len(word)
words = text.split()
for w in range(len(words)):
if word == words[w]:
words[w] = asterisks
return " ".join(words) |
f0f521eabd83ae7dd10cb0ecfa3e12fd88550118 | longfeet21/py-reverse-shell | /Single Client/server.py | 7,934 | 3.578125 | 4 | import socket
import sys
import struct
import os
import time
class Server():
def __init__(self):
self.sock = None
self.host = ''
self.port = 5555
# Create socket (allows two computers to connect)
def socket_create(self):
try:
self.sock = socke... |
102485d0cee3d21ecba577a766a071e81afcb952 | eevahanka/ot-harjoitustyo | /src/tests/game_test.py | 2,739 | 3.640625 | 4 | import unittest
from logic.game import Game
class TestGame(unittest.TestCase):
def setUp(self):
self.game = Game()
self.game_with_full_board = Game(225, 15)
self.game_with_empty_board = Game(0, 15)
def test_board_is_correct_width(self):
self.assertEqual(self.game.size, len(sel... |
753500a9c6ca714d44cbf540c08bcc6d05223825 | kavinb07/code_war2019 | /diamond/diamond.py | 859 | 3.671875 | 4 | #!/usr/bin/python
with open('diamond.txt') as f:
data = f.readlines()
def make_diamond(size):
matrix = []
for i in range(1, (size / 2) + 1):
string = ''
string += '#' * (size / 2 - i)
string += '/' * i
string += '\\' * i
string += '#' * (size / 2 - i)
matri... |
d05d2c0ffceaf2c08f974549f9dc179f881dcbc7 | kavinb07/code_war2019 | /share_letters/share_letters.py | 824 | 3.6875 | 4 | #!/usr/bin/python
with open('share_letters.txt') as f:
data = f.readlines()
def find_shared(words):
all_chars = []
for word in words:
for char in sorted(word):
all_chars.append(char)
select = []
words[0] = list(words[0])
words[1] = list(words[1])
words[2] = list(words[... |
06238443208151b1229e79e2c9ac4e5c9033dea0 | kavinb07/code_war2019 | /planet_weight/planet_weight.py | 369 | 3.515625 | 4 | #!/usr/bin/python
with open('planet_weight.txt') as f:
data = f.readlines()
for line in data:
values = line.split()
name = values[0]
if name == 'END':
break
weight = float(values[1])
planet = values[2]
conversion = float(values[3])
print('On ' + planet + ', ' + name + ' would ... |
409f82a86c31c8a4c8d77cf70e817f0c74d64413 | Ilya18322/Algoritmss | /2.1alg.lab.py | 541 | 4.3125 | 4 | import math
def example (x, R):
if x >= -4 and x <= -2:
return x + 3
elif x >= -2 and x <= 4:
return -(x/2)
elif x >= 4 and x <= 6:
return -2
elif x >= 6 and x <= 10:
return math.sqrt((R ** 2) - (x - 8) ** 2) - 2
else:
return("Значение н... |
46a0a26d0c0ae7ae5eefcf51f5ef47e26d0d175f | gstroudharris/PythonAutomateTheBoringStuff | /Lessons/lists.py | 866 | 4.28125 | 4 | #purpose: place items in a list, put them in a function, then call them
myLists = [['Grant', 'Dana', 'ListItem3'], [10, 20, 35]]
#index evaluates to a single item at a time
print((myLists[0][0]) + str((myLists[1][-2])))
#slice will evaluate to a a whole list
print(myLists[1:2])
#replace an item in the list
myList... |
f5eb0c6f1f49d1d4b4cf3d0c21032c27974ef7c3 | d-progonov/IPT-2019-FE71 | /Tkachuk Labs/Lab 6/help.py | 1,149 | 3.953125 | 4 | import math
def value(inpVal):
try:
my_value = inpVal
if my_value == 0:
print("Your value can`t be '0'! Choose another value, please")
elif my_value == "pi":
my_value = math.pi
return my_value
elif my_value == "inf":
my_va... |
bba0634cd9c19d69807095d3eb788e2dffffb867 | d-progonov/IPT-2019-FE71 | /Tkachuk Labs/Lab8.py | 1,624 | 3.96875 | 4 | import matplotlib.pyplot as plt
while True:
try:
left_x = int(input("Input left boundary for 'x':"))
break
except ValueError:
print("Invalid value entered!")
while True:
try:
right_x = int(input("Input right boundary for 'x':"))
if right_x < left_x:
... |
c2fd3122a349a6f0dcb20b8dc9e0fbf11d1de7a8 | jasminedemi/nothingtoseehere | /nothingtoseehere.py | 147 | 3.84375 | 4 | num = input("number here: ")
numb_cap=int(num)
if numb_cap > 5:
print (num, "wrong, you should've entered 4!")
print("nothing to see here") |
2ecad2bed2582c1a70d0a049c5d40e3f4a0dc4ff | alexZeLoCO/Python-While | /Ejercicio3.py | 313 | 3.890625 | 4 | n = int (input("Introduzca el primer número: "))
suma=0
contador = 0
if n>=0:
while n>=0:
contador = contador+1
suma=suma+n
n = int (input ("Introduzca un nuevo número: "))
else:
print ("El primer número ya era negativo.")
print("La media aritmética es igual a:",suma/contador) |
53c177208a03b995c1e0d3ff8b306337d853eeff | nddave/Interval-Skiplist | /skiplist.py | 7,472 | 4.28125 | 4 | # Assignment information
# ---
# Class : COSC 301 - Data structures and algorithms 2
# Assignment : Skiplists - Home Work Assignment 4
# Student : Nirman Dave
# Program information
# ---
# Name : skiplist.py
# Description : A program that creates and edits a skiplist.
# Language : Python 3
# importing modules and lib... |
73a636efa993e4df41d2e0d86f14af29d31a8817 | eshaang/assignments1 | /y.py | 1,287 | 4.1875 | 4 | angle1 = int(input("Enter angle one: "))
angle2 = int(input("Enter angle two: "))
angle3 = int(input("Enter angle three: "))
angletotal = angle1+angle2+angle3
if angletotal == 180:
if angle1 == 60 and angle2 == 60 and angle3 == 60:
print("equilateral")
elif angle1 == angle2 or angle2 == angle3 or angle1 == an... |
1a2e275b70864d8ffa7072f32a12df3232601cfa | minseunghwang/TIL | /programmers/단어변환.py | 735 | 3.6875 | 4 | def solution(begin, target, words):
answer = 0
visited = [0] * len(words)
q = [begin]
print(words)
while q:
print(q)
text = q.pop(0)
print(visited)
for n,word in enumerate(words):
if visited[n] == 0:
cnt = 0
for i,j in zip(... |
865554ff46fabf8b87653c6995d26e1e95123012 | Hoverbear/SPARCS | /week1/1 - variables.py | 520 | 4.09375 | 4 | # Create a variable that contains the result of 2 + 2 (4)
my_num = 2 + 2
print(my_num + 2) # Results in 6.
# Reassign the variable to 2.
my_num = 2
print(my_num + 2) # Results in 4.
# Change (mutate) a variable.
my_num = my_num + 2 # Should be 4 now.
print(my_num + 2) # Results in 6.
# Another way to change a vari... |
802a63767ddf4ac4449b11045c4e5ee1b2f69e04 | Hoverbear/SPARCS | /week4/board.py | 1,386 | 4.125 | 4 | def draw_board(board):
"""
Accepts a list of lists which makes up the board.
Assumes the board is a list of rows. (See my_board)
"""
# Draw the column indexes.
print(" ", end="")
for index, col in enumerate(board):
# Print the index of each column.
# Note: sep="", end="" p... |
2157ab6936bd0e03959d122e9cc4a0c6908081fd | Hoverbear/SPARCS | /week2/2 - Loops.py | 2,579 | 4.90625 | 5 | # Loops! Loops! Loops!
# The above is an example of a loop. Loops are for when you want to do something repeatedly, or to work with a list.
# First, some useful things for us to know.
my_range = range(10)
# This creates an "iterator" which is sort of like a list, in fact, we can use a cast to make a list out of it.
pr... |
060fbaee141a926bceb9d8c42876bdc5b80ee27c | 14E47/Hackerrank | /ProblemSolving/Algorithms/Warmup/staircase.py | 103 | 3.875 | 4 | n = int(raw_input())
d = '#'
for i in range(1,n+1):
width = n
print((d*i).rjust(width, ' '))
|
d02efac81f6ed635712a333ddf21b2a014b5473c | 14E47/Hackerrank | /Python/collections/PilingUp.py | 984 | 3.515625 | 4 | from collections import deque
def pile():
check = 0
while len(d) > 1:
l = d[0]
r = d[-1]
if l > r and check == 0:
check = l
d.popleft()
elif r > l and check == 0:
check = r
d.pop()
elif r == l and check == 0:
ch... |
3428bb3e2794381738752bb1a368b196fcebee13 | 14E47/Hackerrank | /30DaysOfCode/day9_recursion3.py | 302 | 4.125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the factorial function below.
def factorial(n):
if n<=1:
return 1
else:
fac = n*factorial(n-1)
return fac
n = int(input("Enter factorial no. :"))
result = factorial(n)
print(result)
|
c938eda395b289c851ee0d4dd25384022e81eae3 | 14E47/Hackerrank | /30DaysOfCode/day5_loops.py | 132 | 3.5 | 4 | n = int(input())
if n >= 2 and n <= 20:
for i in range(1,10+1):
mul = n*i
print("%d x %d = %d" % (n,i,mul))
|
bfa4aa306b9320deb52ce86d76315d92a226b9a3 | 14E47/Hackerrank | /Python/PythonFunctionals/ValidatingEmailAddressesWithaFilter.py | 668 | 3.5625 | 4 | import re
def fun(s):
try:
a = s.index('@')
b = s.index('.')
z1 = s[:a]
z2 = s[a+1:b]
z3 = s[b+1:]
match = re.match('^[_a-z0-9-]*@[a-z0-9]*.([a-z]{2,3})$', s)
if len(z1)!=0 and len(z2)!=0 and len(z3)<=3:
if match==None:
return Fal... |
0d4aefd6e58d078b83351fb9b65fee433a60fda4 | goncaloadolfo/movies-reviews-prediction | /metricas_desempenho.py | 5,035 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Módulo com métodos auxiliares para a avaliação de um classificador.
Created on Sun Dec 23 17:41:29 2018
@author: Gonçalo Adolfo, Frederico Costa
"""
import matplotlib.pyplot as plt
import itertools
import numpy as np
from sklearn.metrics import confusion_matrix
from sklearn.metrics import ... |
07cbb640a232368e41a1ae098215c2a3147215dd | HebertFB/Curso-de-Python-Mundo-1-Curso-em-Video | /Curso de Python 3 - Mundo 1 - Curso em Video/ex007.py | 272 | 3.859375 | 4 | """Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média"""
nota1 = float(input('Informe a primeira nota: '))
nota2 = float(input('Informe a segunda nota: '))
print(f'\nA média das notas {nota1} e {nota2} é: {(nota1+nota2)/2:.1f}')
|
8d5203e99f35aabfa5710bfae36ba6cc47c479b6 | HebertFB/Curso-de-Python-Mundo-1-Curso-em-Video | /Curso de Python 3 - Mundo 1 - Curso em Video/ex010.py | 342 | 4.125 | 4 | """Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar"""
reais = float(input('Informe quantos Reais a ser convertido para Dólar: '))
cotacao = float(input('Informe a cotação atual do Dólar: '))
print(f'R${reais:.2f} Reais convertidos dará US${reais/cotacao:.... |
4c10f1aa3d9fd6203eb517a1bdd0e8c5dea65fc7 | HebertFB/Curso-de-Python-Mundo-1-Curso-em-Video | /Curso de Python 3 - Mundo 1 - Curso em Video/ex029.py | 432 | 4.0625 | 4 | """Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que
ele foi multado. A multa vai custar R$7,00 por cada Km acima do limite"""
km = float(input('Quantos Km/h o carro está? '))
if km > 80:
print(f'\nVocê está acima da velocidade permitida de 80Km/h!'
... |
a9dc59b43b89dc12b5f2887a61e1857e0affaaa6 | HebertFB/Curso-de-Python-Mundo-1-Curso-em-Video | /Curso de Python 3 - Mundo 1 - Curso em Video/ex009.py | 508 | 4.34375 | 4 | """Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada"""
num = int(input('Informe um número: '))
print(f'=' * 11)
print(f'{num} X {1:2} = {num*1}')
print(f'{num} X {2:2} = {num*2}')
print(f'{num} X {3:2} = {num*3}')
print(f'{num} X {4:2} = {num*4}')
print(f'{num} X {5:2} = {num*5}')
pr... |
3f9e00b5f5198fbf9a5d3ba903492518ceee8f06 | BALAJISB97/DS | /Graph Implementations and Traversals/Queue.py | 363 | 4.03125 | 4 | class Queue:
def __init__(self):
self.q=[]
def enqueue(self,val):
self.q.append(val)
def dequeue(self):
return self.q.pop(0)
def IsQEmpty(self):
return (len(self.q)==0)
#------------ Sample Queue---------------------
q1=Queue()
q1.enqueue(1)
q1.enqueue(2)
q1.enqueue(3)
p... |
687fcef695f56aedc748f4bd17f2915f67511e4d | BALAJISB97/DS | /Graph Implementations and Traversals/GraphImplementationUsingList.py | 2,164 | 3.703125 | 4 | class vertex:
def __init__(self,id):
self.id=id
self.adjacent={}
self.visited=False
#self.distance=sys.maxint
def getConnections(self):
return self.adjacent.keys()
def getCosts(self,key):
return self.adjacent[key]
def addNeighbour(self,cost... |
ae482821b2b633aaa9b6c1e757bd035175354b73 | TareqJudehGithub/intermediate_py_udacity | /lesson_2/comprehensions/comprehensions.py | 1,732 | 4 | 4 | # Comprehensions
squares = [x ** 2 for x in range(10)]
print(squares)
# Comprehensions with conditions:
even_squares = [y ** 2 for y in range(10) if y % 2 == 0]
print(even_squares)
# Dictionary Comprehension:
dict_squares = {a: a ** 2 for a in range(10)}
print(dict_squares)
even_dict_squares = {x: x ** 2 for x in ... |
c377882aac138119c69a19f96d553bbceabcd2d8 | asamailovich/exadel-python-course-2021 | /tasks/task04/task04.py | 725 | 3.671875 | 4 | def collect_leaves(i) -> list:
res = []
if type(i) is list:
return i
if type(i) is dict:
for node, values in i.items():
if isinstance(values, list):
res.extend(values)
elif isinstance(values, dict):
res.extend(collect_leaves(values))
... |
41c379a25452adc44b93ab6e4722c4edc4cd3c35 | joeylmaalouf/complexity-project | /code/ant_food_search.py | 9,170 | 4.1875 | 4 | from math import sqrt
from ant import Ant
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import collections
def dist(p1, p2):
""" Calculate the distance between two points. """
return sqrt((p2[1] - p1[1])**2 + (p2[0] - p1[0])**2)
'''
Create a gr... |
d1db169222333ddf4386dce76e58e8bbfb18e3f4 | mahmoudgamal0/8-queens | /visualizer.py | 370 | 3.6875 | 4 | def visualize_board(board):
for row in board:
for col in row:
val = 'Q' if col else '#'
print(val, end='')
print('\n')
print('-------------------------')
def visualize(paths):
print('===============================')
for board in paths:
visualize_board(b... |
b3f75edfb7963c02bb0f92fe5cb0cca6354f866b | AkashAAD/PythonApps | /Python/app.py | 11,813 | 3.953125 | 4 | # First Programme
print('Akash Deshbhratar')
print('o----')
print(' ||||')
print('*' * 10)
# Second Programme
price = 10 # number
price = 20 # number
rating = 4.9 # floating point number
name = 'Akash' # string
is_published = False # boolean
print(is_published)
print(rating)
print(price)
full_name = 'John Doe'... |
47e18ffa193d64581f13522c9ffb7c4e0ce192a0 | caserwin/daily-deep-learning | /demo_pytorch/5_grad_demo_3.py | 1,033 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/1/12 下午8:36
# @Author : yidxue
import torch
import torch.nn as nn
# Create tensors of shape (10, 3) and (10, 2).
x = torch.randn(10, 3)
y = torch.randn(10, 2)
# 全连接、无隐藏层的神经网络
linear = nn.Linear(3, 2)
print('w: ', linear.weight)
print('b: ', linear.bias)
# 随机梯度下降
criterion =... |
0d19a01a43ef753af9eb1f9f09817c86e99f0dec | jacobbathan/python-examples | /ex8.10.py | 344 | 4.25 | 4 | # a string slice can take a third index that specifies the 'step size'
# the number of spaced between successive characters
# 2 means every other character
# 3 means every third
# fruit = 'banana'
# print(fruit[0:5:2])
def is_palindrome(string):
print(string == string[::-1])
is_palindrome('racecar')
... |
2bdf4b1513b1f50acb93631a0e3e350da2ceffbb | jacobbathan/python-examples | /cards.py | 2,228 | 3.765625 | 4 | import random
class Card(object):
def __init__(self, suit=0, rank=2):
self.suit = suit
self.rank = rank
# class attributes
suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7',
'8', '9', '10', 'Jack', 'Q... |
0e7756f9dbee738a57c7f40a69124b0b1d861a3f | maximeborsen/ExercicesPython | /Chapitre 1/Exercices/Exercices C1C Ennoncés/DébutC1C4.py | 1,787 | 3.640625 | 4 | import sys
def ChooseDestination():
print("1 - Bruxelles\n2 - Mons\n3 - Nivelles \n4 - Charleroi")
_destinationChoice = int(input("Entrez La destination que vous voulez atteindre :\n "))
if _destinationChoice == 1:
_destination = "Bruxelles"
elif _destinationChoice == 2:
_destination = "... |
62eafab89be9ea6eb6778c6dde1299f567f87015 | houssamboudiar/Predicting-fruits-using-Height-Weight-ML | /TP3.py | 5,504 | 3.796875 | 4 | #------------------------- Etape 1 ---------------------------------
import matplotlib as plt
import pandas as pd
pd.set_option('max_rows',5) #shows only 5 rows from the whole dataset
import scipy.stats as sps
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression #... |
14f6cc58493b5694812a4f0f2da91ac55d57c9d9 | a1ip/ASR33 | /bin/pattern | 12,558 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014-2019 Hugh Pyle
"""
Print patterns on paper-tape.
Source material for patterns are in files in a subdirectory 'patterns'.
Each pattern-file has data in Python literal format that defines things we can print.
(The format looks like JSON but isn't... so ... |
9744ecfd730b37731b89a315aee4ef95d9b4c37b | iopkelvin/Algorithms | /Max_pair_wise/stresstest.py | 1,259 | 3.96875 | 4 | def max_pairwise_product_fast(numbers):
index1 = 0
n = len(numbers)
for i in range(1, n):
if numbers[i] > numbers[index1]:
index1 = i
if index1 == 0:
index2 = 1
else:
index2 = 0
for i in range(0, n):
if (i != index1) and (numbers[i] > numbers[index2]):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.