blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4cee72deeed8bb8b31de22fd1669b97821a20276 | Gamillkar/work_2.5_context_manager | /work_2.5.py | 812 | 3.609375 | 4 | import time
import datetime
class Time:
def __init__(self, name_text):
self.name_text = name_text
print(f'Время начало работы {datetime.datetime.utcnow()}')
self.diff_time = time.time()
def __enter__(self):
self.text_s = open(self.name_text, 'w', encoding='utf8' )
retu... |
becc41d0a96db7d11079c5ae83e6ee8c99e877f5 | vsanghan/function_assignment | /exercise_06_rupeesConverter.py | 252 | 4.15625 | 4 | ''' write a function which will take an integer representing dollars as input, and returns the equivalent rupees value as the output '''
def rsConverter(dollar):
rupees = dollar * 70 # Assuming $1 = Rs.70
return rupees
print (rsConverter(5)) |
29850e2b46bf6da4ca722d6e5efc1a9da650784e | hyunjeeChoi/effectivePython | /study/14_none을반환하지않고예외를일으키자.py | 264 | 3.609375 | 4 | def divide(a, b):
try:
return a / b
except ZeroDivisionError as e:
raise ValueError('Invald inputs')(e)
x, y = 5, 2
try:
result = divide(x, y)
except ValueError:
print('Invalid input')
else:
print('Result is %.1f' % result)
|
7f5dab4f168a2f7e99ae8cf9a06ac1b209f87e09 | SaadAhmad123/myCodeRepo | /python/fibonacciGenerator.py | 289 | 3.515625 | 4 | '''
This is a fibonacci generator function.
It employs the yeild keyword
'''
def genFib():
n1 = 1;
n2 = 0;
while True:
next = n1 + n2;
yield next;
n2 = n1;
n1 = next;
#end
#end
f = genFib();
for i in range(0,6):
print f.next(); |
70aa4e0ae6a02687a54c05f5cf9cd7d8b334db62 | SaadAhmad123/myCodeRepo | /python/knapSackGreedyAlgo.py | 1,306 | 3.78125 | 4 | '''
The greedy algorithm follows the algorithm:
while knapsack is not full
add the "best" possible element to it.
To use the implementation below the list should be
a list of objects with following functions.
- getValue() -----> this function will be maximized for all the elements in the list
... |
66a0505fb6dfa0eac73cd83df9b396b1a22a68f1 | icething/Python_lessons_basic | /lesson03/home_work/hw03_easy.py | 1,848 | 3.921875 | 4 | # Задание-1:
# Напишите функцию, округляющую полученное произвольное десятичное число
# до кол-ва знаков (кол-во знаков передается вторым аргументом).
# Округление должно происходить по математическим правилам (0.6 --> 1, 0.4 --> 0).
# Для решения задачи не используйте встроенные функции и функции из модуля math.
def ... |
bfeaffa5273e8407d5cef825ae206d48a26924d5 | ekut2104/python-course-alphabet | /oop/hw_oop/1.py | 346 | 3.84375 | 4 | def create_wall(width: float, height: float):
if width == 0 or height == 0:
raise ValueError('Value must be not 0')
print('11111')
if get_count_of_walls() == 4:
raise ValueError('Our house can not have more than 4 walls')
def get_count_of_walls():
return 4
if __name__=='__main__':
... |
f76c14671f78b2658732407420b92ddc1d9a74a6 | cgsarfati/CodingChallenges-Reverse-LL-In-Place | /reversellinplace.py | 3,005 | 4.1875 | 4 | """Given linked list, reverse the nodes in this linked list in place.
Iterative solution doctest:
>>> ll1 = LinkedList(Node(1, Node(2, Node(3))))
>>> ll1.as_string()
'123'
>>> reverse_linked_list_in_place(ll1)
>>> ll1.as_string()
'321'
Recursive solution doctest:
>>> ll2 = LinkedList(Nod... |
69d3fedaf9b97a57d673e0bbd6b95e7f0460b8a4 | grademacher/PrimeSteg | /Decoder_GUI.py | 5,098 | 3.96875 | 4 | from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter import messagebox
import string
import decoder
input_file_name = ""
decrypted_message = ""
output_file_name = ""
decryption_key = ""
brute_force_iterations = 100
def get_input_file(event):
Tk().withdraw()
global input_file_name... |
0086f9778adac149ca6b529cfcf2ac538d38887b | daniellop199731/LibreriaNotificaciones | /libreriaDeNotificaciones/mainLibreriaDeNotificaciones.py | 1,106 | 3.578125 | 4 | from libreriaDeNotificaciones import Notificador
# Asocia un número y un nombre que son de tipo de notificador
number_notificador_name_association = {
1: "Correo",
2: "Facebook",
3: "SMS",
4: "Empresarial",
}
# Muestra los tipos de notificador en una lista para decirle al usuario cual escoger
print("... |
406ef267eab49c38fd043583f79ea48ba35f8491 | JayantGoel001/Turtle | /Kaleido Spiral with Squares.py | 668 | 3.828125 | 4 | import turtle as t
from itertools import cycle
colors = cycle(["red", "green", "yellow", "gray", "blue", "pink", "white", "purple", "orange"])
def createCircle(rad, angle, forward):
t.pencolor(next(colors))
t.circle(radius=rad)
t.right(angle)
t.forward(forward)
createSquare(rad + 5, angle + 1, fo... |
7c0cea16006a6526ed997c5f2597638905d2ede0 | ConorT38/2016-Elections-Analysis | /Hillary/reducer.py | 1,154 | 3.625 | 4 | from operator import itemgetter
import sys
current_word = None
current_count = 0
word = None
# These are the terms we will search for regarding trump
slurs = {'whichhillary' : 0, 'fraud' : 0,'emails' : 0,'alcoholic' : 0,'benghazi' : 0,'murderer' : 0,'satan' : 0,'shill' : 0,'fuck' : 0,'rapist' : 0,'fbi' : 0,'evil' : 0... |
97d6b5f43e2083ece280867fe8f0c31cd5e57c36 | dhruvsanchety/Order-Book | /orderbook.py | 6,810 | 3.765625 | 4 | '''
The order book contains a Dictionary for both bids and asks, where the keys are the price. The values are dictionaries
that contain the head and tail of a linked list with orders at that price. The head of the linked list stores the correct netsize at that
price level. There is another dictionary, where they k... |
0b395475b88088c722404a6701a7de9ca7847733 | cmsystems/PycharmProjects | /Programmierkurs/Spiel/operator_vergleich.py | 175 | 3.703125 | 4 | # coding: latin-1
__author__ = 'Thomas'
x =12
y = 15
z = 20
print("x: ", x)
print("y: ", y)
print("z: ", z)
#Bedingung 1
if x < y < z:
print("y liegt zwischen x und z") |
9c98b5cefb6be2e0c2875bb7552437195489ad42 | Theoblanc/algorithm | /ProblemSolving/boggle.py | 843 | 3.578125 | 4 |
dx = {-1, -1, -1, 1, 1, 1, 0, 0}
dy = {-1, 0, 1, -1, 0, 1, -1, 1}
board = [["U", "R", "L", "P", "M"],
["X", "P", "R", "E", "T"],
["G", "I", "A", "E", "T"],
["X", "T", "N", "Z", "Y"],
["X", "O", "Q", "R", "S"]]
test = ["PRETTY",
"GIRL",
"REPEAT",
"KARA",
... |
2799bf54b6e0309f01907009f875280bc626fc31 | Theoblanc/algorithm | /Sort/insert.test.py | 319 | 4.03125 | 4 | list = [10, 5, 6, 8, 2, 1]
def insertSort(list):
n = len(list)
for i in range(n):
for j in range(i, 0, -1):
if(list[j] < list[j-1]):
list[j], list[j-1] = list[j-1], list[j]
print(list)
else:
break
insertSort(list)
print(list)
|
cdee3bfb733f365c7ae2804b26dd99c150846981 | thetealpickle/python-swe | /refresher/01_variable_methods.py | 600 | 3.703125 | 4 | # Created by Jessica Joseph on 02/21/18
## variables
a = 9
b = 10
my_variable = 26
any_variable_name = 10 # number cannot be at the start of your variable name
string_variable = "jessica" # python only knows this is 7 chars and the first char is a 'j'
single_quotes = 'strings can have single quotes'
print(my_varia... |
48803397d492af6e172854624046da082ddb29ff | hujunalex1/python3 | /samples/tuple.py | 237 | 3.953125 | 4 | #一种有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改
classmates=("hujun","alex","sim") #注意括号是小括号
print('classmates =', classmates)
classmates[1]
print(classmates[1])
|
eeb460737d8ef085158f224f8ac8656bdf8c7a65 | shivam-pixel/spiral_3d | /ef.py | 303 | 3.75 | 4 | import turtle
t=turtle.Turtle()
screen=turtle.Screen()
screen.bgcolor("black")
list=["red","blue","yellow","orange","pink"]
for i in range(500):
t.color(list[i%5])
t.circle(15+i)
t.clone()
t.forward(i+5)
t.circle(i+2)
t.pensize(3)
t.left(180)
t.speed(0000)
|
4d61248479bf76196ba300390cc1d8647fefb460 | JHanek3/HackerRank | /python/tuples.py | 527 | 4.09375 | 4 | #Task given an integer, n, and n space-separated integers as input, create a tupe t of those n integers
#Then compute and print result of hash(t)
#Input Format
#The first line contains an integer, n denoting the number of elements in the tuple
#The second line contains n space-separated integers describing the element... |
0c30a8141ceae60666cc87595f0040c04770e3d8 | JHanek3/HackerRank | /python/swapcase.py | 577 | 4.34375 | 4 | # Task
# You are given a string and your task is to swap cases
# Input Format
# A Single Line Containing a String S
# Output Format
# Print modified string
def swap_case(s):
swaped_str = ''
for char in s:
if ( 90 >= ord(char) >= 65):
swaped_str += char.lower()
elif (122 >= ord(char) >= 61):
s... |
d90debe507484822a66d3b37824351e4d8b006c6 | JHanek3/HackerRank | /python/string_formatting.py | 901 | 4.03125 | 4 | # Task
# Given an integer, n, print the following values for each integer i from 1 to n
# Decimal, Octal, Hexadecimal(capitalized), Binary
# Input Format
# A single integer denoting n
# Output Format
# Print n lines where each line i contains the respective decimal, octal, capitalized hexadecimal, and binary values o... |
3bfb7ad0c29552445aa98fa89d255f348cc0cb8e | JHanek3/HackerRank | /python/print_function.py | 372 | 4 | 4 |
#Input Format
#The included code stub will read an integer, n, from STDIN
#Without using any string methods, try to print the following
#123...n
#Input Format
#The first line contains an integer n
#Output Format
#Print the list of integers from 1 through n as a string, without spaces
eList = []
for x in range(1, n ... |
110ef0de9a7174c298ffda640a731f6dda22d0ad | JHanek3/HackerRank | /python/loops.py | 355 | 3.984375 | 4 | #Task
#The provided code stub reads an integer,n, from STDIN. For all non-negative integers i < n, print .
#print i^2
#Input Format
#The first and only line contains the integer n.
#Output Format
#Print n lines, one corresponding to each i,
def square():
n = int(input())
for i in range(n):
if i >= 0:... |
a48eda690cb4173a7aec5d03c760bcc4392769ba | Softtery/py | /strstr.py | 358 | 3.640625 | 4 | def strstr(stroke, x):
i = 0
while i < len(stroke):
i += 1
if x in stroke:
return i
else:
i = -1
return i
#stroke = input("Введите строчку/текст для поиска: ")
#x = "two, one"
print("123one".find("one"))
print(strstr('123one', 'one'))
#print(strst... |
70fbea73c0737e20df6e8602a56aafd4cfaf2400 | mastayb/conways-game-of-life | /conways.py | 2,411 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#######################################
#
# Conway's Game of Life
# Implemented by Ben Mastay
#
#######################################
import time
import curses
import random
from grid import Grid
def init_random_grid(r,c):
g = Grid(r,c)
for _ in range(random.ra... |
522e29836d8a9c0f43d09c8d87bb4bc265a6234e | ssono/ctci | /array/arr1.py | 1,327 | 3.71875 | 4 | "Is Unique: Implement an algo to determine if a string is composed of unqiue characters. What if you dont have any additional datastructures"
# time=O(N*N) Space=O(1)
def isUnique(s):
startLength = len(s)
s += " "
for i in range(0, startLength):
if s[i] in s[startLength:]:
return False
... |
3bccbdd1ce69161816a1da9ae1e50a71bc2d297e | benoitvallon/phonebook-cli | /actions.py | 2,413 | 3.515625 | 4 | import re
from helpers import printEntries, checkParams, closeDatabase, getPhonebook
def create(argsList):
params = checkParams('create', argsList)
file = open(params['database'], 'w')
print "Database created"
closeDatabase(file)
def lookup(argsList):
params = checkParams('lookup', argsList)
... |
1b3fe2f82e476505b896239e74f817ee629a3228 | sasikrishna/python-programs | /com/algos/gfg/mustdo/stacks/Stack.py | 560 | 4 | 4 | '''
Problem statement: Implement stack
'''
class Stack:
def __init__(self):
self.stack = []
self.top = -1
def push(self, item):
self.stack.append(item)
self.top += 1
def pop(self):
if self.top == -1:
raise Exception('No element to pop.')
self... |
e827a7fb8bb1807118d25b033a468777a31a4eac | sasikrishna/python-programs | /com/algos/sortings/SelectionSort.py | 447 | 4.15625 | 4 |
def selection_sort(array):
for i in range(0, len(array) - 1):
min_index = i
for j in range(i + 1, len(array)):
if array[min_index] > array[j]:
min_index = j
if i != min_index:
temp = array[min_index]
array[min_index] = array[i]
... |
f8f52aa9ee041daacbff18bf8d68607597afb330 | sasikrishna/python-programs | /com/algos/gfg/mustdo/arrays/ZigZag.py | 1,143 | 4.03125 | 4 | '''
Problem statement: Given an array A (distinct elements) of size N. Rearrange the elements of array in zig-zag fashion.
The converted array should be in form a < b > c < d > e < f. The relative order of elements is same in the output i.e
you have to iterate on the original array only.
'''
def swap(num_list, index1... |
17818d89d65e90504acedb75349e558dbe8f9a3d | sasikrishna/python-programs | /com/algos/gfg/mustdo/stacks/NextGreaterElement.py | 855 | 3.609375 | 4 | '''
Problem statement: Given an array A of size N having distinct elements, the task is to find the next greater element for
each element of the array in order of their appearance in the array. If no such element exists, output -1
'''
if __name__ == '__main__':
test_cases = int(input())
list_counts, lists = []... |
ac836d87d41fd7dc881073500ea29fee13cd7b36 | sasikrishna/python-programs | /com/algos/strings/RemoveNumbers.py | 374 | 4.15625 | 4 |
'''
Program to remove numbers from given string.
'''
def remove_numbers(string):
string = ''.join([i for i in string if not i.isdigit()])
return string
if __name__ == '__main__':
print('String after removing numbers from A1B2C3D4 is', remove_numbers('A1B2C3D4'))
print('String after removing numbers... |
869532ebf23d236b95806b2c6cb22787e3fd2c19 | sasikrishna/python-programs | /com/algos/gfg/mustdo/trees/BalancedTree.py | 1,539 | 3.984375 | 4 | '''
Problem statement: Given a binary tree, find if it is height balanced or not.
A tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes
of tree.
'''
class Node:
# Constructor to create a new Node
def __init__(self, data):
self.data = data
... |
7e8e4de097813c4acca7a15dc623efb7267a2f7e | secworks/advent_of_code_2018 | /day_5/code_day_5.py | 3,116 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#======================================================================
# Code for solving day 5 of AoC 2018
#======================================================================
VERBOSE = True
#------------------------------------------------------------------
#-----... |
242de40678154e11ad7f0ba6062af6d8c586326e | bachsxi/hoangduybach-fundamentals-C4E20 | /Lec01/HW/tt_cir2.py | 106 | 3.5 | 4 | from turtle import *
color("orange")
speed(-1)
for i in range (6):
circle(100)
left(60)
mainloop() |
5d980c20af39e5216acd3b68b81c4c94e393e1d8 | bachsxi/hoangduybach-fundamentals-C4E20 | /lec03/Homework.03/turtle/turt_02.py | 273 | 3.671875 | 4 | from turtle import *
mau= ['red', 'blue', 'brown', 'yellow', 'grey']
for i in range(len(mau)):
color(mau[i])
begin_fill()
for i in range(2):
forward(50)
left(90)
forward(100)
left(90)
forward(50)
end_fill()
mainloop() |
30e26fcdd9e36af734cc02f1a50dc1f77fc17478 | bachsxi/hoangduybach-fundamentals-C4E20 | /lec02/Homework.02/Serious Excercises/se_1_BMI.py | 534 | 4.0625 | 4 | print("Welcome to the Body evaluation session! ")
cao=int(input("Your height in cm: "))
nang=int(input("Your weight in kg: "))
cao= cao/100
BMI= nang/(cao*cao)
if BMI < 16:
print(BMI,"< 16 = You're severely UNDERWEIGHT!")
elif BMI <=18:
print("Your BMI is ",BMI," is between 16 and 18.5 = You're UNDERWEIGHT!")
e... |
1285c5a157aca076a04c3eb68f185318b200d64a | virenparmar/Snake-Game-Using-Python | /snake.py | 2,378 | 3.9375 | 4 | # Snakes Game
# Use Arrow Keys to play, SpaceBar for pausing/Resuming and ESC Key for exiting
import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
from random import randint
curses.initscr()
win=curses.newwin(20,80,0,0)
win.keypad(1)
curses.noecho()
curses.curs_set(0)
win.border(0)
win.nodelay(1)
k... |
86a6ed0aac956db66cff76448f7d4e9712d0eef5 | tcrundall/workshop_exercises | /2_python_class_intro/exercise_1.py | 5,945 | 4.21875 | 4 | """
This is the first exercise.
Attendees will witness how to write the Person class.
Attendees will then write their own TurnablePerson class,
by filling in the empty methods.
Since Person is already written, you can import this Class
into a python environment by opening a terminal in the same
directory and running ... |
b1b3387d2cf7d7530a8fa057d56cd48e8d42604b | frostdpr/cs4740-cloud-computing | /PA4/Airline2_mapper.py | 573 | 3.71875 | 4 | #!/usr/bin/env python3
import sys
# input comes from STDIN (standard input)
for line in sys.stdin:
line = line.strip()
# split the line into words
words = line.split(',')
# increase counters
# print(words[6], words[34], words[45])
#print("{0},{1},{2}\t1".format(words[6], type(words[35]), words[... |
bbb56ea1a2d33e6d9a87f7a9d401cfa5a1c48179 | PeterCassell92/Python-Exercises | /ex6.py | 81 | 3.625 | 4 | #!/usr/bin/python
a=[4,5,6,5,4]
b= list(reversed(a))
if b == a:
print("Boop")
|
22312b85a55d45f8cb0e09ad9200051a6d2a13c7 | PeterCassell92/Python-Exercises | /ex21.py | 754 | 3.671875 | 4 | #!usr/bin/python3
#This program takes all the text from an article across two pages and writes the text to a file.
import requests
from bs4 import BeautifulSoup
def print_webpage_text(base_url):
r = requests.get(base_url)
soup = BeautifulSoup(r.text, "html.parser")
title = soup.find('title').string
for text in... |
dea6faf0805d453a097005cddb787773b85840fa | PeterCassell92/Python-Exercises | /ex35.py | 2,471 | 3.921875 | 4 | #!/usr/bin/python3
#using json file as a database for names / birthdays.
import json
import re
from collections import Counter
def addnewentry(mydict):
name = input("\nType name for new entry. ")
while True:
birthday = input("Type birthday of new entry. ")
if verifydateformat(birthday) == True:
mydict.update... |
f1f9a85dbf7a9217787f7cdd3de64633970cc305 | ShubhamKunal/cs102 | /cs102/homework01/caesar.py | 2,093 | 4.1875 | 4 | ''' This is Caesar's Cipher'''
def encrypt_caesar(temp: str, key=3) -> str:
"""
Encrypts plaintext using a_1 Caesar cipher.
>>> encrypt_caesar("PYTHON")
'SBWKRQ'
>>> encrypt_caesar("python")
'sbwkrq'
>>> encrypt_caesar("Python3.6")
'Sbwkrq3.6'
>>> encrypt_caesar("")
... |
3abee2d6a9b2340f62a440a620965e2a81840676 | remnantdochi/SmartCarrier | /190515.py | 8,697 | 3.59375 | 4 | """ Google Vision API Tutorial with a Raspberry Pi and Raspberry Pi
Camera. See more about it here:
https://www.dexterindustries.com/howto/use-google-cloud-vision-on-the-raspberry-pi/
Use Google Cloud Vision on the Raspberry Pi to take a picture with the Raspberry Pi Camera and classify it with the Google Cloud Vis... |
3c8bc156a2b65dd430f033e92a101c0f5f490e73 | alessandroampala/HCI-Connect4 | /Game.py | 1,979 | 3.96875 | 4 | from Board import *
from Player import *
class Game:
# players: a list of Player object
# size: length of a single board row
# points: points list. Index represents the length, value the points associated
# win_points: points needed to win a game
def __init__(self, players, size, points, win_poi... |
e89a8d94cd2cf65c3dd4f0f90769fa0d311b2669 | angel-becerra/trabajo-de-varialbles | /trabajo03_becerra.py | 34,776 | 3.546875 | 4 | nombre="angel"
print("el valor de la variable nombre es:",nombre)
sexo="masculino"
print("el valor de la variable sexo es:",sexo)
edad=17
print("el valor de la variable edad es:"+ str(edad))
dni=75805360
print("el calor de variable dni es:"+ str(dni))
primer_apellido="becerra"
print("el valor de la variable pr... |
4aea81b164062b407118a89435e6af29c28d8023 | SLakshmiHarish/guvi_codekata | /harish3.py | 200 | 3.921875 | 4 | x="aeiou"
b="bcdfghjklmnopqrstvwxyz"
a=raw_input("x is:")
print(a)
if(a in x):
print("the letter is vowel")
elif(a in b):
print("the letter is consnant")
else:
print("the letter is invalid")
|
91130ba1c56fe4851842f7a4884f0745a500dab5 | suchi2001/Batch-6-Python-Day-6-Assignment | /Batch-6 Python Day-6 Assignment.py | 769 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
print("Question:1")
# In[2]:
print("Convert to a dicitionary in one line code using list comprehension (without using zip method)")
# In[7]:
# Python3 code to demonstrate
# conversion of lists to dictionary
# using naive method
# initializing lists
list1 = ... |
f2666387a3e0de31fef5d17f680e1ca283046604 | joannaluciana/Python-OOP- | /oop/day1/klasakot.py | 1,251 | 3.671875 | 4 | class Cat:
def __init__(self, imie, rasa, waga, sluga):
self.imie = imie
self.rasa = rasa
self.waga = waga
self.sluga = sluga
def __str__(self):
return f"""Jestem {self.imie} kot waze {self.waga} kg
moim sluga jest {self.sluga} jestem rasowcem rasy {self.rasa} """
d... |
b68843920827e6a477e1c6869bfcd23b6c16dc25 | joannaluciana/Python-OOP- | /oop/day3/exercises/point.py | 1,276 | 4.03125 | 4 |
class Point():
def __init__(self, x, y):
self.x=x
self.y=y
def distance (self,other_point):
x_diff= self.x - other_point.x
y_diff=self.y - other_point.y
dist=(x_diff**2 + y_diff**2)**0.5
return dist
def __eq__(self, other_point):
return(self.x==other_... |
f6563ce64a3e0ee0599de6ad73aafb816d673c16 | Patrycja147/pp1 | /02-ControlStructures/02-30.py | 309 | 3.828125 | 4 | x=0
PIN="0805"
while x<3:
PIN2=str(input("Podaj kod PIN: "))
if PIN==PIN2:
print("Kod PIN jest poprawny.")
break
elif PIN!=PIN2 and x==2:
print("Kod PIN jest niepoprawny.\nKarta płatnicza zostaje zablokowana.")
else:
print("Kod PIN jest niepoprawny.")
x+=1 |
500bed36b6e2db597ea7fb31ceee5844fdf250ed | Patrycja147/pp1 | /01-TypesAndVariables/01-29.py | 209 | 3.671875 | 4 | import random
a=random.randint(1,6)
b=int(input("Podaj, ile oczek kostki wyrzucił komputer: "))
print("Komputer wyrzucił",a,"oczek")
if a==b:
print("Zgadłeś: TRUE")
else:
print("Zgadłeś: FALSE")
|
a492695c548599520c135f0fc21ebb029ccfd938 | Patrycja147/pp1 | /02-ControlStructures/02-44.py | 268 | 3.796875 | 4 | x=int(input("Podaj limit prędkości (km/h): "))
y=int(input("Podaj prędkość pojazdu (km/h): "))
if y-x<0:
print("Pojazd nie przekroczył prędkości.")
elif y-x>0 and y-x<10:
print("Mandat (zł): ",5*(y-z))
else:
print("Mandat (zł):",5*10+15*(y-x-10)) |
ced551963e71777379023fa0da0fd878f670869c | Patrycja147/pp1 | /02-ControlStructures/02-10.py | 252 | 3.921875 | 4 | x=int(input("Podaj dowolną liczbę: "))
if x>0 and x%2!=0:
print("Liczba jest dodatnia i nieparzaysta.")
elif x<0 and x%2!=0:
print("Liczba nie jest dodatnia, ale jest nieparzysta.")
else:
print("Liczba nie jest dodatnia i jest parzysta.") |
a2a40a5a710e17518086dbc8c2e20657c822d602 | Patrycja147/pp1 | /02-ControlStructures/02-35.py | 746 | 3.609375 | 4 | a=int(input("Podaj liczbę a: "))
b=int(input("Podaj liczbę b: "))
c=int(input("Podaj liczbę c: "))
import math
if a==b==c==0:
print("Brak równania")
else:
if a!=0:
print("Równanie kwadratowe.")
delta=b**2-(4*a*c)
if delta<0:
print("Delta mniejsza od 0. Równanie nie ma pierwia... |
facdca1da9cd7421886f18438d9129961ac2a2d3 | Patrycja147/pp1 | /02-ControlStructures/02-18.py | 181 | 3.78125 | 4 | x=1
while x<=30:
if (x%15==0):
print("BINGO")
elif (x%5==0):
print("FIVE")
elif (x%3==0):
print("THREE")
else:
print(str(x))
x+=1 |
d1f7598f12044f5b2e2ec87939c876d3a9876ee8 | groodt/facebook-puzzles | /hoppity/hoppity | 382 | 3.515625 | 4 | #!/usr/bin/python
import sys
if __name__ == '__main__':
fname = sys.argv[1]
with open(fname) as f:
#assume file is in correct format
number = int(f.read().strip())
for i in range(1, number+1):
if i % 15 == 0:
print 'Hop'
elif i % 3 == 0:
print '... |
01cee77a5713be2003606fd28f150ab1e7c24bff | ballenwillis/CS-357-Utils | /HW3/natural-log-taylor-approximation.py | 419 | 3.859375 | 4 | import math
import sympy as sy
import numpy as np
# Modify these variables only
center = 0
degree = 2
value = 0.2
# Modify these variables only
def taylor(x, n):
i = 0
p = 0
while i <= n:
if (i % 2 == 0):
p = p + (x**(i+1)/(i+1))
else:
p = p - (x**(i+1)/(i+1))
... |
7f1fc54bf251107080d365fc0dfbca2543c70278 | jmontara/become | /Ch4/shell.py | 843 | 3.546875 | 4 |
import os
from os import path
import shutil
from shutil import make_archive # zip
from zipfile import ZipFile # zip with file selection
def main():
if path.exists("textfile.txt"):
src = path.realpath("textfile.txt")
dest = src + ".bak"
shutil.copy(src, dest)
shutil.copystat(src, dest)
# renam... |
473691d99e7eeefa64c41ccf21b06ebc79adffed | jmontara/become | /Ch2/functions.py | 488 | 4.125 | 4 | #
# example file for working with functions
#
def func1():
print("This is a function")
def func2(arg1, arg2):
print (arg1, " ", arg2)
def power(num, pwr):
ret = num
for x in range(pwr-1):
ret = ret * num
return ret
def multi_add(*args):
result = 0
for x in args:
result = result + x
... |
6ec8de0d1f9e2087ba30dffaad3fdd1fb6084c24 | jmontara/become | /Ch5/xmlparsing.py | 913 | 3.828125 | 4 | #
# manipulate XML code in memory
#
# see python 3.6.3 documentation, language reference
import xml.dom.minidom
def main():
# use parse() function to load and parse an XML file\
doc = xml.dom.minidom.parse("samplexml.xml")
# print document node and first child name
# these are standard elements of doc
print(do... |
ff1c659c2b6d74db68410e3c2f8c41d15b404a4e | galursa/UWM | /WD/Przyklady/Cw3/Ćw3_przyklad9.py | 431 | 3.609375 | 4 | #Mamy dwa rodzaje zmiennych: lokalne i globalne
#lokalne są widoczne tylko wewnątrz funkcji
#czyli po zakończeniu działania funkcji nie możemy się do nich dosać
#globalne są widoczne dla wszystkich procedur i funkcji
#Nie zaleca się jednak stosowania zmiennych globalnych
def dodaje():
global a
a=1
b... |
cb8f687c995977f25bfa2a7a3ab5749c34db8b03 | galursa/UWM | /WD/Przyklady/Cw3/Ćw3_przyklad3.py | 268 | 3.703125 | 4 | #Zagnieżdżanie
#Zamiast pisać tak:
lista=[]
for i in [1, 2, 3]:
for j in [4, 5, 6]:
if i != j:
lista.append((i,j))
print(lista)
#można to zrobić krócej
lista2=[(i,j) for i in [1, 2, 3] for j in [4, 5, 6]]
print(lista2)
|
ff7df86f6d0096b64de96230db429a3321adf4bd | galursa/UWM | /WD/Przyklady/Cw7/W7_Przykład1.py | 362 | 3.546875 | 4 | #importujemy odpowiedni moduł z nazwą skróconą plt
import matplotlib.pyplot as plt
#Tworzymy tablicę x i tablicę y
x=[-4,-3,-2,-1,0,1,2,3,4]
y=x
#Ponizsze 3 komendy sa podobne do matlabowych
# Plot rysuje, xlabel i ylabel nadaja nazwy dla etykiet
plt.plot(x,y,'ro-')
plt.xlabel('X')
plt.ylabel('Y')
#... |
7701140d4bd0dbd961b38c03f5748fc54001c3ab | rgott/build-monitor | /build.py | 2,424 | 3.5 | 4 | #!/usr/bin/env python
# Display a runtext with double-buffering.
import time
import datetime
if(__debug__):
from rgbmatrix_emulator.simplebase import SampleBase
from rgbmatrix_emulator import graphics
else:
from samplebase import SampleBase
from rgbmatrix import graphics
class RunText(SampleBase):
... |
21c5dc8547f5d26b598885712c73070a39c47b63 | elviragolubtsova/sort_algorithms | /sort_algorithms/sort_algorithms.py | 2,703 | 3.96875 | 4 | from random import randint
class SortAlgorithms:
def bubble(nums):
swapped = True
while swapped:
swapped = False
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
nums[i], nums[i + 1] = nums[i + 1], nums[i]
swa... |
3e7dc215ba6cf344d11773286da7f3210fd935aa | davidbabbs/Problem-Sets-for-MIT---6000.1-Introduction-to-Computer-Science-and-Programming | /MIT60001_ps0.py | 574 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thurs Oct 17 23:34:34 2019
@author: David Babbs
"""
# Write a program that does the following in order:
#1. Asks the user to enter a number “x”
#2. Asks the user to enter a number “y”
#3. Prints out number “x”, raised to the power “y”.
#4. Prints out the log (bas... |
c0b6b70aaf857e60499b027f197e135e5cdc3cad | luzdace/luzda | /juego.py | 446 | 4.15625 | 4 | import random
intentos = 2
max_intentos = 3
num_random = random.randint(0,10)
print("Inicia ingresando un numero Que estoy pensando! - Numero de intentos 3")
while True:
numero = int(input ("Que numero estoy pensando - Ingrese un numero: ") )
if num_random == numero:
break
if intent... |
f36caaba868ade2cb8b49834b18a7b641e058bd4 | farhan1ahmed/Training | /Week3Day1+2/Lilys homework.py | 491 | 3.765625 | 4 | #!/bin/python
import math
import os
import random
import re
import sys
# Complete the countingSort function below.
def lilysHomework(arr):
swaps = 0
for i in range(len(arr)-1):
small = min(arr[i:])
index = arr.index(small)
if index != i:
arr[i], arr[index] = arr[index], arr... |
a8b3865214cfe19a4757c6b8a485eeeb5ba35391 | farhan1ahmed/Training | /Week2Day3/Intro to Sets.py | 186 | 4.03125 | 4 | number = input("Number of plants: ")
distinct_heights = [int(x) for x in set(input("Number of plants: ").split())]
print("Average: " + str(sum(distinct_heights)/(len(distinct_heights)))) |
f2ba9dcba4fb22c8dd98d13f1cd92c1e57d712b5 | farhan1ahmed/Training | /Week2Day3/No Idea!.py | 245 | 3.625 | 4 | your_elements = input("Your elements: ").split()
setA = set(input("Set N: "))
setB = set(input("Set M: "))
happy = 0
for element in your_elements:
if element in setA:
happy += 1
if element in setB:
happy -= 1
print(happy) |
3d5d6c0147565cd5f8d0ec10f2a71a0b7cd3c402 | farhan1ahmed/Training | /Week2Day3/Lists.py | 295 | 3.515625 | 4 | tries = int(input("Enter number of commands: "))
l = []
for t in range(tries):
com = input().split()
command = com[0]
arguments = com[1:]
if command != 'print':
s = ", "
eval("l."+command+"("+s.join(arguments[:])+")")
elif command == 'print':
print(l) |
d5fa59b1be7e1e4e99649c84d1e50027643e6c68 | farhan1ahmed/Training | /Week2Day3/Compare the triplets.py | 339 | 3.84375 | 4 | def compare_triplets():
a_score = input('Enter Alice\'s score: ').split()
b_score = input('Enter Bob\'s score: ').split()
a = 0
b = 0
for n in range(len(a_score)):
if a_score[n] > b_score[n]:
a += 1
if a_score[n] < b_score[n]:
b += 1
return [a, b]
print(... |
69bcfafeb357cb554dd29fc3d477a1426912b07d | farhan1ahmed/Training | /Week1Day1/Division.py | 141 | 3.953125 | 4 | a = int(input("First Number: "))
b = int(input("Second Number: "))
print('Integer Division: {0}\nFloat Division: {1}'. format((a//b), (a/b))) |
440a88268d722904e5c59cbd50a27b04c78d9841 | farhan1ahmed/Training | /Week1Day2/Find Percentage.py | 281 | 3.984375 | 4 | n = int(input("Enter number of Students: "))
my_dict = {}
for i in range(0, n):
record = input().split()
my_dict[record[0]] = record[1:]
query = input()
if query in my_dict:
score = map(float, my_dict[query])
print(sum(score)/3)
else:
print("Student not found") |
ca5c99063218128e02feb4fa16d3302250438b7b | deolekarmayuresh/Security_Hacking_Scripts | /MD5 Hashing.py | 735 | 4.5 | 4 | #!/usr/bin/env python3
# Python code to generate MD5 hashing and check their similarity based on Hash
#By Vivek Ray
import hashlib # Supports hashing functions such as MD5,SHA
message1= str(input("Enter message 1 ="))
message2= str(input("Enter message 2 ="))
encoding1 = message1.encode()
encoding2 = message2.encode... |
1993d2eb7c17d741f7c6859cdd79464b45845679 | Bohdan-KL/python_practice | /Practice_15_KM-01_Klots/exp_root/root.py | 231 | 3.625 | 4 | def root2(n):
if n<0:
return 'number should be natural.'
else:
from math import sqrt
return round(sqrt(n), 4)
def root3(n):
return round(-((-n) ** (1/3)), 4) if n < 0 else round(n ** (1/3), 4)
|
e1d7eb95cf04c0ef13b143c8aa5cc1e90c814753 | MartinThoma/akademie-2015 | /Justus-Blackjack/blackjack.py | 28,514 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Blackjack simulation
"""
import matplotlib.pyplot as plt
import numpy as np
import random
import sys
def input_string(question=""):
"""A function that works for both, Python 2.x and Python 3.x.
It asks the user for input and returns it as a string.
""... |
ba7a3f8e71096b18a84e58e71c095f1c64d5ab9b | pavlyhalim/Adventure_Game_El-Khanka_Edition | /adventure_game_El-khanka_Edition.py | 5,389 | 3.8125 | 4 |
import time
import random
items = []
weapon = ['M416', 'DP28', 'MK14']
monster = ['Adly', 'David', 'Basel', 'Osama', 'Soudy']
def print_pause(message_to_print):
print(message_to_print)
time.sleep(2)
def intro():
print_pause("Welcome adventurer!")
name = input("What is your name ?... |
020f79dd0bb0007e771fa55e4c3ffb5f3f886249 | Vladislav1223/lab11 | /файл2.py | 749 | 3.96875 | 4 | #Дан файл f, компоненти якого є цілими числами. Знайти кількість парних та
#кількість двозначних чисел серед компонентів файлу. Результат вивести на екран.
#Павлюк Владислав
print('Исходный файл:')
f=open('fg.txt', 'r')
print(f.read())
f=open('fg.txt', 'r')
count1=0
count=0
for i in f:#Пройдемся по строкам файла
num... |
4c297c6e1da0454039dfd3e6fd76fdffbab12225 | machotico/Tarea-2 | /Tarea 2B.py | 774 | 3.75 | 4 | #Tarea 2B: hecha por Luis Guevara Chacón
def is_in_range(num, min, max): #establece si un número está en rango y devuelve un 'si' o un 'no'
for y in range (min,max+1):
#print(y)
if y == num:
respuesta = ": Si"
#break
return respuesta
else:
... |
674f9ab853845f44bd7b60fe6cbc7bd61739bdf3 | BlitheBrandon/advent2020 | /day07/day07.py | 2,646 | 3.640625 | 4 | from sys import exit
def get_exercise_input_from_file(num):
"""Read aoc input from file and return as list"""
fname = f"day{num:02}_input.txt"
try:
with open(fname, "r") as f:
return f.read().split("\n")
except FileNotFoundError:
exit(f"File {repr(fname)} not found.")
def... |
e8d5de2cac243069b03ac75dae54a2387ec11659 | congsonag/udacity-data-structures-algorithms-python | /Graphs/graphs_bfs.py | 574 | 3.65625 | 4 | class Vertex:
def __init__(self, id, val):
self.id = id
self.val = val
self.edges = []
class Edge:
def __init__(self, to, from, weight):
self.from = from
self.to = to
self.weight = weight
def bfs(node):
result = []
queue = [node]
seen = set()
whi... |
b373571d3876f799c5b962438fc06fcfe4cfde2e | congsonag/udacity-data-structures-algorithms-python | /sorting and searching/find_square_root.py | 1,395 | 4.71875 | 5 | def find_square_root_int(number):
'''Find the integer value of the square root of a given non-negative whole number.
Examples:
find_square_root_int(9) --> 3
find_square_root_int(8) --> 2 (square root is ~2.828, which as an int is 2)
Time/Space Complexity of Function (taken from Leetcode):
Runt... |
96c1393fe67c26fdbb1419d5de059874b82d34af | oakkub/Hacktoberfest-2k17 | /nishanthebbar2011/eratosthenes.py | 355 | 3.53125 | 4 | #Sieve of eratosthenes
n=int(input("Please Enter the positive number up till which you want the prime numbers to be printed"))
arr=[]
for i in range(n+1):
arr.append(int(i))
for i in range(2,int(n**(0.5))):
if arr[i] != -1:
k=2*i
while k<=n:
arr[k]=-1
k+=i
for i in arr:... |
a8a21cf721371fd8936eab4c37b3e960ae8bace8 | Tsedao/Structure_and_Interpretation_of_Computer_Programs | /lab/lab06/lab06_extra.py | 1,305 | 4.25 | 4 | from lab06 import *
## Extra Questions ##
## Optional List Mutation ##
def deep_map_mut(fn, lst):
"""Deeply maps a function over a Python list, replacing each item
in the original list object.
Does NOT create new lists by either using literal notation
([1, 2, 3]), +, or slicing.
Does NOT return ... |
60561830f166ce88f5ff8ae31c8661d4456be37d | Tsedao/Structure_and_Interpretation_of_Computer_Programs | /lab/lab12/lab12.py | 2,104 | 3.75 | 4 | from stream import *
def countdown(n):
"""
A generator that counts down from N to 0.
>>> for number in countdown(5):
... print(number)
...
5
4
3
2
1
0
>>> for number in countdown(2):
... print(number)
...
2
1
0
"""
while n >= 0:
... |
e45b8e58509527d2626b97c29b1a07f093896344 | muchammadardan/py-belajar_python | /string.py | 1,179 | 4.0625 | 4 | #String are array
a = 'akuRDA'
print (a[1])
print ('--------------------------')
#Slicing / irisan
a = 'hurawqefd'
print (a[2:5])
print('----------------------------')
#Leght String
a = 'bakul sayur'
print (len(a))
print ('---------------------------')
#String Metods
#Strip
a = ' rujwq'
print (a.strip())
print ('---... |
67b6e81c8022551d2074fbf4bce7758e66446690 | muchammadardan/py-belajar_python | /kedai.py | 428 | 3.859375 | 4 | #input data
orders = [1, 2]
minuman = ['susu', 'coklat', 'kopi', 'teh']
harga = [5000, 4000, 3000, 1000]
tot_yar = 0
#diberi proses karena ada yanng pesan
#menggunakan looping dikarenakan mengulang data
for order in orders:
mnm = minuman[order]
hrg = harga[order]
tot_yar += hrg
print('{} {}'.format(m... |
2450c7eb83101f4f32d64e33f8129157df0351dd | bnmcintyre/biosystems-analytics-2020 | /assignments/01_strings/vpos.py | 2,818 | 4.5625 | 5 | #!/usr/bin/env python3
"""
Author : bnmcintyre
Date : 2020-01-28
Purpose: Find a given vowel in given text
"""
import argparse
import os
import sys
# --------------------------------------------------
def get_args():
"""Get command-line arguments from user"""
"""asks for two inputs - a vowel and some text ... |
aa97f941bc3931000578bc05ce9690a0d7321342 | vishalbelsare/pymanopt | /pymanopt/manifolds/manifold.py | 7,721 | 3.640625 | 4 | import abc
import functools
import numpy as np
class Manifold(metaclass=abc.ABCMeta):
"""
Abstract base class setting out a template for manifold classes. If you
would like to extend Pymanopt with a new manifold, then your manifold
should inherit from this class.
Not all methods are required by ... |
5b1657fb3bb5311a444b1a638b81a3cc3923b5a7 | vishalbelsare/pymanopt | /pymanopt/autodiff/backends/_backend.py | 3,978 | 3.671875 | 4 | import abc
import functools
class Backend(metaclass=abc.ABCMeta):
"""Abstract base class defining the interface autodiff backends must
implement.
Parameters
----------
name : str
The name of the backend.
"""
def __init__(self, name):
self._name = name
def __str__(sel... |
6dac36136200a476499e33082376cf1cd59ce76d | steven-mcmaster/python | /stocks/stocks.py | 762 | 3.65625 | 4 | class Stock:
def __init__(self, ticker, cost, name):
self.ticker = ticker
self.cost = int(cost)
self.name = name
def __str__(self):
return self.ticker + " " + self.name + " " + str(self.cost)
with open('file', 'r') as file:
for line in file:
try:
s1 = S... |
7cbdca54d6d5587d242f94ff5889849b2e70cf21 | Eduardo-Vinicius/LPII | /Atividades/heranca.py | 1,217 | 3.828125 | 4 | class Funcionario:
def __init__(self, hora_trabalho, qtd_hrs_trab):
self.salario_hora = hora_trabalho
self.hrs_trab = qtd_hrs_trab
def calcula_salario(self):
return (self.salario_hora * self.hrs_trab)
def dar_aumento(self):
salario = self.salario_hora * self.hrs_trab
... |
f2ea15df1c5ab7a56e4c1a265676644d7e3f69b7 | jane624609/lesson-2 | /圖表套件.py | 907 | 3.625 | 4 | #https://matplotlib.org/1.3.1/users/pyplot_tutorial.html
#直線圖
import matplotlib.pyplot as plt #一句套入套件並設入簡稱
plt.plot([1,2,3,4])#y值
plt.ylabel('some number') #ylabel:Y的標示
plt.show()
#點圖
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro') #點的位置,ro是劃出紅點,沒寫就是預設藍線
plt.axis([0, 6, 0, 20]) #x軸跟y軸範圍
plt.sh... |
45687c7e50248de640b382095bdd722114926256 | jane624609/lesson-2 | /class.py | 1,610 | 3.890625 | 4 | #class 類別(種類)
#dir 屬性
#寫class是在設計藍圖
#class寫法:
#class<class名稱>:
# def__init__(self):
# ....
# def 其他func(self):
# ....
class Student:
def __init__(self, name, score) : #init:initialize是指初始化 #初始化參數name,設完就設定屬性
self.name = name #增加身上屬性
self.score = score
self.x = '5'
pri... |
2c9dc956e451ef3f32f5012b7c07f20ca5830d44 | jane624609/lesson-2 | /import.py | 940 | 3.828125 | 4 | #產生1~100隨機數
import random #插入隨機功能
r = random.randint(1, 1) # . 是指的,randint是random跟int結合
print(r)
#猜數字遊戲
#產生一個隨機整數數字範圍給使用者設定(不要印出)
#讓使用者重複輸入數字去猜
#猜對的話 印出 "終於猜對了!"
#猜錯的話 要告訴他 比答案大/小
#印出猜了第幾次
import random
small = input('請輸入範圍開始值')
large = input('請輸入範圍結束值')
small = int(small)
large = int(large)
r = random.randint(small... |
e6987134f56026f870fb66021f87a76632f67c6a | mtgjarvis/python_fundamentals1 | /exercise4-4.py | 280 | 4.0625 | 4 | import random
num = random.randint(1, 10)
print('Pick a number between 1 and 10')
guess = int(input())
if guess == num:
print('You Win!')
elif (guess - 1 == num) or (guess + 1 == num):
print('So Close!')
else:
print('Try Again')
print('The number was {}'.format(num)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.