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 |
|---|---|---|---|---|---|---|
135eec4e853dd5d03ef2dab9600affb39d453c93 | emailman/Raspberry_Pi_Heater | /list demos/list demo 2.py | 249 | 4.0625 | 4 | from random import shuffle
# Generate a list of numbers from 1 to 5
s = list(range(1, 6))
# Shuffle the list
shuffle(s)
# Print the list
print(s)
# Print and pop each item from the list
# until it is empty
while len(s) != 0:
print(s.pop(0))
|
da2a894246e305fe13e5a504a495ac747b2afbb3 | emailman/Raspberry_Pi_Heater | /matthew1/function demo.py | 156 | 3.890625 | 4 | def f(x):
m = 2
b = 1
y = (m * x) + b
return y
def main():
for x in range(12, 0, -2):
print("x =", x, ": y =", f(x))
main()
|
956fd0812e6565fa8f6843af933c225e7ae22a7c | emailman/Raspberry_Pi_Heater | /sorted grades/function demo.py | 647 | 4.15625 | 4 | def rectangle_calc(x, y):
area = x * y
perimeter = 2 * (x + y)
return area, perimeter
def main():
try:
length = float(input("Enter the length of a rectangle: "))
width = float(input("Enter the width of a rectangle: "))
units = input("Enter the units: ")
area_, perimet... |
55f0d5b128c78a4f3da8b11f0e428d0c00a36ca7 | emailman/Raspberry_Pi_Heater | /heater/temperature test.py | 1,454 | 3.546875 | 4 | from guizero import *
from gpiozero import CPUTemperature
"""
Display the reading from a DS18B20 temperature sensor
connected on the default GPIO pin #4
The reading will be refreshed automatically in a
GUI window every 2 seconds
"""
# Global widget
txt_temp_reading = None
# Global constant
temp = None
class Temp... |
62d4761fc861827fcd7caee1ad632928f75d142b | Venu2791/Assignment6 | /session6.py | 4,880 | 3.9375 | 4 |
import random
from itertools import groupby
from collections import defaultdict,Counter
vals = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'jack', 'queen', 'king', 'ace']
suits = ['spades', 'clubs', 'hearts', 'diamonds']
cardvalue={'2':2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"jack":11,"queen":12... |
b37df26d6e549c38b1aaa33af176586e04159ce8 | GodHelps/python_demo | /Thread_demo/multThread.py | 1,289 | 3.796875 | 4 | "Thread demo"#采用继承threading.Thread类,重写run方法定制线程执行方法.
from multiprocessing import Pool
import threading
import time, random
import os
seperation=os.linesep
class Counter:
def __init__(self):
self.lock = threading.Lock()
self.value = 0
def increment(self):
self.lock.acquire() # critical... |
0e6ab0e23ee7c8272e53a69786cc22e3faf0e6f7 | isabelmette/pynet | /process/TopConnection.py | 1,196 | 3.5 | 4 | from threading import local
from Queue import Empty
class ConnectionStack(local):
''' this stack stacks all connections currently running in a thread.
use like this
with runningConnection(connection):
assert runningConnection.top() is connection
'''
def __init__(self):
self.connectionStac... |
39519b5d4fc357d1db58c6e6fed8d490e483902e | vighnesh-nagpal/gilaa | /gilaa/plot.py | 5,709 | 4.03125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import astropy
import pandas as pd
def read_input(filename):
'''
This function takes in a csv file containing the data desired to analysed and
returns a pandas dataframe containing the data.
Args:
filename (str): The path to the file
... |
f407d9f61d6c730a067e2aaeabf8d12962dbf926 | tarekmehrez/Taxonomy-Enricher | /lib/taxonomy_extractor/config/option.py | 1,237 | 3.734375 | 4 | """Contains the config option class."""
class Option(object):
"""
Create an option, assign a type and set its value.
"""
def __init__(self, section, param, type, required, default_value):
"""
Initialize option instance.
params:
param (str): param of item
... |
f14e8f7219784e32ba8859b27a60cd7274cde787 | ajboxjr/hangman | /hanggui.py | 1,493 | 3.6875 | 4 | from tkinter import Tk, Label, Button, StringVar, Entry, PhotoImage
class Screen:
def __init__(self, master, photo):
self.hasSecret = False
self.master = master
master.title("A simple GUI")
#Label for the hangman image
self.words = Label(master, image=photo, width=400, hei... |
aa570524b8f873e68b0fd01af85ecd1af4b58df7 | divyatiwari5/pythonPractices | /prime.py | 151 | 3.6875 | 4 | for num in range(1, 10):
prime = True
for i in range(2, num):
if (num%i== 0):
break
else:
print(num)
|
a815dc2c5155310b68aa6a9ae094ce06b06fe17f | divyatiwari5/pythonPractices | /listoverlap.py | 402 | 3.96875 | 4 | a = list()
b = list()
print("Enter items for list 1. Press Enter twice when done.")
current = input("Enter item: ")
while current:
a.append(current)
current = input("Enter item: ")
print("Enter items for list 2. Press Enter twice when done.")
current = input("Enter item: ")
while current:
b.append(curren... |
621e9bd0478b4ed84247b9011c3893d03b658f20 | xuq52/Python3.5 | /7_do_iter.py | 822 | 3.59375 | 4 | from collections.abc import Iterable
d = {1: '11', 2: '22', 3: '33'}
for key in d:
print(key)
for value in d.values():
print(value)
for a in 'abs':
print(a)
print(isinstance('123', Iterable))
print(isinstance(123, Iterable))
for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
def findMinAn... |
7db92003f89f8d698a7f86349cb58bce33e71102 | xuq52/Python3.5 | /6_do_slice.py | 963 | 3.59375 | 4 | L = ["a", "b", "c", "d", "e"]
print(L[:3])
#['a', 'b', 'c']
print(L[-2:])
#['d', 'e']
L1 = list(range(100))
print(L1[:10])
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(L1[::5])
#[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
print(L1[:10:2])
#[0, 2, 4, 6, 8]
print("ABCDEFG"[::2])
# "ACEG"
def... |
9705a2252cc6f9e9c476f8673597e9b77541d878 | Pallavi-Rangaswamy/demo-python | /hello.py | 778 | 4.09375 | 4 | print("********************Hello world***********************")
# Set the tuples
weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
weekenddays = "Saturday", "Sunday"
a = 10
b = 20
c = a + b
# Print the tuples
print(c)
print(weekdays)
print(weekenddays)
#float numbers
x = 35e3
y = 12E4
z = -87.7e100
p... |
4246e62fc319eead8d26817b1a2d52b81cf8e744 | isitix/BregmanToolkit | /bregman/tuning.py | 7,386 | 3.546875 | 4 | # tuning.py - computation of tuning systems in Python
# Author: Michael A. Casey
# Copyright (C) January 2011, Dartmouth College, All Rights Reserved
# Bregman - python toolkit for music information retrieval
__version__ = '1.0'
__author__ = 'Michael A. Casey'
__copyright__ = "Copyright (C) 2010 Michael Casey, Dartm... |
2dea5e0bc311fb273b9177860ba63b7cb12ed8bc | buddino/openstack_scripts | /experiment/iperf/converter.py | 977 | 3.625 | 4 | #!/usr/bin/python
import json
import sys
def mean(data):
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return sum(data) / n # in Python 2 use sum(data)/float(n)
def _ss(data):
c = mean(data)
ss = sum((x - c) ** 2 for x in data)
return ss
def std... |
eedd411fb7c6e5ba9a0c58dcef9e45b3f22241fb | vicchu/leetcode-101 | /04 Recursion/Practice/06_is_palindrome.py | 336 | 3.5625 | 4 |
# Approach 1
def isPalindrome(inpStr, si, ei):
if si >= ei:
return True
if inpStr[si] != inpStr[ei]:
return False
else:
return isPalindrome(inpStr, si + 1, ei - 1)
def isPalin(N):
strNum = str(N)
return 1 if isPalindrome(strNum, 0, len(strNum) - 1) else 0
# Approach 2:... |
6ce9afb4fe1aa6ac61cb91024bf6849c8ce6a974 | vicchu/leetcode-101 | /02 String/Practice/03_check_palindrome.py | 799 | 3.796875 | 4 |
# Approach 1: Using Loop
def checkIfPalindrome1(inpStr: str) -> str:
si = 0
ei = len(inpStr) - 1
while si < ei:
if(inpStr[si] != inpStr[ei]):
return 'No'
si += 1
ei -= 1
return 'Yes'
# Approach 2: Using Slicing - Super Short
def checkIfPalindrome2(inpStr: str) -... |
3da96eba8223961bd87ed52181fb24fff00b6df2 | prudhvi9666/Homomorphic_Algo | /Libraries/generate_keys.py | 3,629 | 4.03125 | 4 | import random
def generate_LCM(p, q):
"""
give lcm of p and q
p is first prime number -1
q is second prime number -1
"""
return p *q // generate_gcd(p, q)[0]
def generate_gcd(a, b):
"""
returns (g, x, y) according to the Extended Euclidean Algorithm
such that, ax + by = g
"""... |
7f14bc3d6c47efc5374fcc5810687c64a9914283 | amvaskar/Hangman | /hangman.py | 3,200 | 4.125 | 4 |
import time
game_word = "secret"
def hangman():
name = raw_input("Your Name?\n")
print "---Hello, " + name, "Time to play hangman!---"
print "---OK! READY!!---"
time.sleep(0.5)
print "---Start guessing the word of 6 letters!!..."
time.sleep(0.5)
turns = 5 #total number to turn to guess
... |
ebe7607742ab2042f62881b23f208a803b71863e | shengchaohua/leetcode-solution | /leetcode solution in python/ProjectionAreaof3DShapes.py | 650 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 17 19:42:45 2019
@problem: leetcode 883. Projection Area of 3D Shapes
@author: shengchaohua
"""
class Solution(object):
def projectionArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
N = len(grid[0])
x... |
9a0109a8be1a658a74091c491cadb1998e7655f1 | shengchaohua/leetcode-solution | /leetcode solution in python/KdiffPairsinanArray.py | 1,575 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 13 08:50:27 2018
@problem: leetcode 532. K-diff Pairs in an Array
@author: shengchaohua
"""
class Solution:
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# AC!
if len(nums... |
f141421a9730a2b314ac99da409fc7f34fca86a4 | shengchaohua/leetcode-solution | /leetcode solution in python/ThirdMaximumNumber.py | 1,290 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 30 21:00:59 2018
@problem: leetcode 414. Third Maximum Number
@author: shengchaohua
"""
class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(set(nums)) < 3:
return max(nums)
... |
31f834351bc63e1f35c176e80cf98efc470a0ed3 | shengchaohua/leetcode-solution | /leetcode solution in python/SortArrayByParityII.py | 778 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 14 10:10:38 2018
@problem: leetcode 922. Sort Array By Parity II
@author: shengchaohua
"""
class Solution:
def sortArrayByParityII(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
i, j = 0, 1
while i < len(A) and... |
b7b4f7e9ae05f23a0c71fd814d7bf1361b1a4fe5 | shengchaohua/leetcode-solution | /lintcode solution in python/Fibonacci.py | 338 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 16 15:24:10 2018
@author: sheng
"""
class Solution:
"""
@param n: an integer
@return: an ineger f(n)
"""
def fibonacci(self, n):
# write your code here
a, b = 0, 1
for i in range(n-2):
a, b = b, a + b
return... |
a3b8a0f2d88832bb2e7954ca1c98be03c4ee1a0f | srpillai/crypto | /helpers.py | 857 | 3.875 | 4 | def alphabet_position(letter):
alphabet = "abcdefghijklmnopqrstuvwxyz"
letter = letter.lower()
for k in range(0, len(alphabet)):
if alphabet[k] == letter:
return k
def rotate_character(char, rot):
alphabet = "abcdefghijklmnopqrstuvwxyz"
alphaCap = "ABCDEFGHIJK... |
c647570a2305b4ffaf8ab6ec3467ea6bb887cab3 | Uncleted123/Codebreaker | /codebreaker.py | 1,079 | 3.84375 | 4 | import random
# Variable Examples
colors_list = ['R', 'O', 'Y', 'G', 'B', 'W', 'P', 'V']
response_list = ['x', 'y', 'z']
solution_list = ['', '', '', '', '']
round = 0
a = ''
b = ''
c = ''
d = ''
e = ''
player_guess = [a, b, c, d, e]
# Methods
def solution_key_generate():
return None
def is_r... |
7687cb899e11fbb6bf65ab6158bf6a91656d1b5c | liangc40/CSC420Assignment-1 | /Q4 (1).py | 9,147 | 3.703125 | 4 | import matplotlib.pyplot as plt
import numpy as np
import cv2
def handle_valid(I, h, filter_length, filter_height, image_length, image_height):
"""
This functions takes in a grayscale image I in matrix representation, a filter h which is also
in matrix representation, the length and height of image I, and... |
39028abf4600601082d0c7f24f718739f5e77c3a | queenskid/MyCode | /labs/introfor/forloop2.py | 542 | 4.15625 | 4 | #!/usr/bin/env python3
# 2 seprate list of vendors
vendors = ['cisco', 'juniper', 'big_ip', 'f5', 'arista', 'alta3', 'zach', 'stuart']
approved_vendors = ['cisco', 'juniper', 'big_ip']
# for loop going through list of vendors and printing to screen with a conditional statement.
for x in vendors:
print("\nThe ven... |
f682148288a375c661d6bbf0be6971f36e432cbb | queenskid/MyCode | /labs/sort03/sorted03.py | 371 | 3.6875 | 4 | #!/usr/bin/env python3
firewall_ports = [5060, 5061, 80, 443, 22, 25565]
def addTen(x):
return x%10
print('Currently firewall_ports looks like this: ' + str(firewall_ports))
print('\nThe results of sorted(firewall_ports, key=addTen) function:', sorted(firewall_ports, key=addTen))
print('\nBut the firewall_ports ... |
18467c40d4a1fe4190587da76cee3a82ad0d2a41 | queenskid/MyCode | /labs/oop-intro/first-oop.py | 631 | 3.90625 | 4 | #!/usr/bin/env python3
from random import randint
class Player:
def __init__(self):
self.dice = []
def roll(self):
self.dice = [] # clears current dice
for i in range(3):
self.dice.append(randint(1,6))
def get_dice(self):
return self.dice
player1 = Player()
player2 = Player()
player1.r... |
7efe5212820fe4058aef52cb8a175c7f0644d35d | queenskid/MyCode | /labs/dict01/dict01.py | 1,100 | 3.515625 | 4 | #!/usr/bin/env python3
## create a dictionary
switch = {'hostname': 'sw1', 'ip': '10.0.1.1', 'version': '1.2', 'vendor': 'cisco'}
## display parts of the dictionary
print( switch['hostname'] )
print( switch['ip'] )
## request a 'fake' key
#print( switch['lynx'] )
## request a 'fake' key with .get() meth... |
bf40a829a9887f981a48f429835956a807d3cf03 | cowsertm1/Python-Assignments | /functions-and-collections.py | 2,974 | 4.6875 | 5 | """
As we saw in class, in Python arguments passed to a function are
treatedly differently depending on whether they are a "normal"
variable or a collection. In this file we will go over some additional
examples so that you get used to this behavior:
1. Write a program that assigns some value to a global variable ca... |
a8990afdbbb60fd3808b78c162f85aed138e74fe | infa2021Vasilev/infa_2021_- | /lab4/4.2.py | 11,597 | 3.671875 | 4 | import pygame as pg
import numpy as np
import random as rn
player = input() #Reading Player's name
pg.init()
FPS = 30
screen = pg.display.set_mode((1200, 700))
#COLORS:
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
... |
54512107d619264d63aa4f85e58c903dfb7091cc | yan8909/leetcode_practice | /0136.Single_Number/single_number.py | 670 | 3.796875 | 4 | # Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
# Example 1:
# Input: nums = [2,2,1]
# Output: 1
# Example 2:
# Input: nums = [4,1,2,1,2]
# Output: 4
# Example 3:
# Input: nums = [1]
# Output: 1
# Solution 1
class Solution:
def singleNumber(self, nums... |
258ccc665fe6922754b0f692476d60d3024f1e03 | julianestebanquintana/ladrillos | /videojuego.py | 6,356 | 3.515625 | 4 | import sys
import time
import pygame
ancho = 640
alto = 480
color_azul = (0, 0, 64)
color_blanco = (255, 255, 255)
pygame.init() # Es necesario para poder usar las fuentes en un juego
# pygame.font.init()
class Bolita(pygame.sprite.Sprite):
# Los objetos que se ven en la pantalla en pygame, son sprites
d... |
bd12342325eadc5529dbc58fc5b96c1c86c4c68a | swathimk/Data-Structures | /Strings/isUniqueWithDS.py | 334 | 3.578125 | 4 | import collections
check_string = "String z c"
check_string = check_string.lower()
results = collections.Counter(check_string)
if ' ' in results.keys():
results.pop(' ')
for count in results.values():
if count > 1:
print("Has repititive values")
break
if count <= 1:
print("Has unique value... |
4d1f9873efd931df85a1b5464f1719a4cf487792 | nicefuu/SortAlgorithm | /testfile.py | 124 | 3.90625 | 4 | def swap(arr, i, j):
arr[i] ^= arr[j]
arr[j] ^= arr[i]
arr[i] ^= arr[j]
arr=[1,2,5,7,9]
swap(arr,0,3)
print(arr) |
f5268f3ed2dd36cd36865547146fae5618121759 | Kinzar97/address_book_Python | /Address_book.py | 3,549 | 4.125 | 4 | import pickle # Импортируем модуль Pickle для сохранения адресной книги в файле на локальном диске
class Address_book:
'''Класс содержит функции которые применяются к адресной книге'''
@staticmethod
def OpenAdd(): # Открытие адресной книги
if Add_book == {}:
print('\nThe address boo... |
496307f017aa2caae2bec971ce40d4e849709804 | 633-1-ALGO/introduction-python-MrLucaYoshi | /11.1- Exercice - Boucle/boucle1.py | 388 | 3.6875 | 4 | # Problème : Etant donné un tableau A de "n" nombres réels, on demande la moyenne des nombres du tableau
# Données : un tableau A de n nombre réels
# Résultat attendu : Moyenne des nombres réels du tableau A
A = [1, 5, 15, 25, 10, 55, 50, 35]
cpt = 0
moyenne = 0
for element in A:
moyenne = moyenne + element
cp... |
723731d9d370b5df06569eadbf139c6b8c41d88f | dtauraso/Algorithms | /recipe_batches/recipe_batches.py | 1,242 | 4.03125 | 4 | #!/usr/bin/python
import math
def we_have_enough_for_1_batch(recipe, ingredients):
# print(recipe)
# print(ingredients)
if(len(recipe.keys()) != len(ingredients.keys())):
return False
count = 0#len(ingredients.keys())
for ingredient in recipe:
if ingredient in ingredients:
if(ingredients[... |
0b9802a4b4ecc2823db5761773af068cad2d0e56 | davifelix5/design-patterns-python | /structurals/adapter/adapter.py | 2,102 | 4.3125 | 4 | """
Serve par ligar duas classes diferentes
"""
from abc import ABC, abstractmethod
class iGameControl(ABC):
@abstractmethod
def left(self) -> None: pass
@abstractmethod
def right(self) -> None: pass
@abstractmethod
def down(self) -> None: pass
@abstractmethod
def up(self) -> N... |
6c194e2ba8f6b26699774b849f9322a47318a153 | davifelix5/design-patterns-python | /bahaviorals/Visitor/visitor.py | 2,020 | 3.875 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
class Insurance(ABC):
@abstractmethod
def for_residencial_building(self, building: ResidencialBuilding): pass
@abstractmethod
def for_bank(self, bank: Bank): pass
@abstractmethod
def for_coffe_hou... |
7c54a4b404e231d0e05d3a6709cf005a2889718c | davifelix5/design-patterns-python | /bahaviorals/State/state.py | 2,265 | 3.859375 | 4 | """
Determina diferentes modos de operação para o método de uma classe dependendo
do estado em que a classe está
"""
from __future__ import annotations
from abc import ABC, abstractmethod
class OrderState(ABC):
def __init__(self, order: Order) -> None:
self.order = order
def show_state(self):
... |
e162d4720d9cdfd2ae2442c63aafc45ada9e72c1 | lyn-phan/trees-practice | /LL_merge_lists.py | 2,154 | 4.0625 | 4 | #Leetcode easy - merge two sorted linked lists
# Input: l1 = [1,2,4], l2 = [1,3,4]
# Output: [1,1,2,3,4,4]
# Example 2:
# Input: l1 = [], l2 = []
# Output: []
# Example 3:
# Input: l1 = [], l2 = [0]
# Output: [0]
#Create a Node class, pass through data and next node
#add function that takes in two node arguments, re... |
aa4cbb5883b930f4e43c4044592fba1cdd3e75f9 | itcsoft/itcpython | /python/day6/if_else_0.py | 211 | 3.734375 | 4 | #
newUserName = 'zalkar'
newPassword = '123'
username = input('Логинди териниз: ')
password = input('Паролду териниз: ')
if password == newPassword and newUserName == username:
print ('Yes.')
else:
print('No.')
|
0d963bccb89bf30a37aa43fb22fcb2c731a87fc9 | itcsoft/itcpython | /python/day2/month.py | 173 | 3.828125 | 4 | year = 2021
month = 12
day = month * 30
hour = day * 24
minute = hour * 60
second = minute * 60
print(year)
print(month)
print(day)
print(hour)
print(minute)
print(second)
|
3f80e2af54baf9f7a9fcddcc096a5708aade5ffc | itcsoft/itcpython | /python/day11/homework_10.py | 3,269 | 4.03125 | 4 |
# 1. Используя while выведи на экран число от 10 до 100:
# a = 10
# while a < 100:
# print(a)
# a = a + 1
# 2. С помощью while у человека имя фамилию и отчество:
# Проси до тех пор пока человек не вводит свои данные
# name = ''
# fname = ''
# while len(name) == 0 or len(fname) == 0:
# name =... |
f3898971bbc5406e3fc481491df72358128f0464 | itcsoft/itcpython | /python/day12/dict_2.py | 1,588 | 3.9375 | 4 |
# Автосалон Bootcamp
car1 = {
'model': 'Honda Fit 2',
'year': '2008',
'vol': 1.6,
'color': 'silver',
'price': 5500.0,
'max_speed': 260
}
car2 = {
'model': 'Mercedes SLG 63',
'year': '2016',
'vol': 4.0,
'color': 'black',
'price': 142000.0,
'max_speed': 350... |
bd5cb730104181ac2296d2a313eb30e514464624 | itcsoft/itcpython | /python/day6/if_elif_0.py | 348 | 3.828125 | 4 |
san = int(input('Сан бериниз мен ошол санды текст менен чыгарам: '))
if san == 0:
print('Ноль')
elif san == 1:
print('Бир')
elif san == 2:
print('Эки')
elif san == 3:
print('Уч')
elif san == 4:
print('Торт')
elif san == 5:
print('Беш')
elif san == 6:
print('Алты')
|
5c868a3b52d6c7296aad2253c592252dfdf2edda | itcsoft/itcpython | /python/day25/plane.py | 771 | 3.625 | 4 | class Plane:
def __init__(self, name, speed):
self.name = name
self.speed = speed
def to_fly(self):
print(self.name, 'Летает на скорости: ', self.speed)
def get_wing_metr(self):
print(self.name, 'Длина крыла 10 метр')
class Boeing(Plane):
def to_fly(self):
... |
2bbeae3e9e12ca64079491f9e6f88a76207beee2 | z0rdd/RockPaperScissors | /main.py | 2,839 | 3.8125 | 4 | import sqlite3
from tabulate import tabulate
class Database:
def __init__(self):
self.conn = sqlite3.connect("scores.db")
self.cur = self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS scores (id INTEGER PRIMARY KEY, name TEXT, p_score INTEGER,"
"c_scor... |
a8bc2f7983b661c1e160e0932f02f4a2da557552 | mrclagman/Codility-Exercises | /tapeEq.py | 1,743 | 3.625 | 4 | '''
A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
The difference between the two parts is the value of: |(A[0] + A[1] + ... |
7bfd6160f69605ad5009e8baca3c065aa739b1d0 | joyrexus/nst | /misc/poset.py | 2,638 | 4.1875 | 4 | '''
In NST Sect 14 (p. 57) Halmos gives three examples of partially ordered sets
with amusing properties to illustrate the various possibilities in their
behavior.
Here we aim to define less_than functions for each example. Each function
should return a negative value if its first argument is "less than" its
second,... |
2b4d9b75ed704f8da4c531e2f2dfd311b07e61ea | bahattin-urganci/python-training | /pd.py | 573 | 3.53125 | 4 | import pandas as pd
import numpy as np
cars = pd.read_csv('cars.csv', index_col=0)
print(cars[['cars_per_cap', 'country']])
dr = cars["drives_right"]
selecteds = cars[dr]
print(selecteds)
# Create car_maniac: observations that have a cars_per_cap over 500
cpc = cars['cars_per_cap']
many_cars = cpc > 500
car_mania... |
f894ad9840de8bcc27d85bb3bb332c82e687ef26 | bahattin-urganci/python-training | /tirmanmayarisi.py | 825 | 3.671875 | 4 | # tırmanma yarışması :)
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(5)
all_walks = []
for i in range(5):
random_walk = [0]
for x in range(100):
step = random_walk[-1]
dice = np.random.randint(1, 7)
if dice <= 2:
step = max(0, step - 1)
elif dice... |
a1c364e2cba00a33fa4233a0e69adb98ecf3b24f | brucewilson1103/python-average-withForLoop | /main.py | 270 | 4 | 4 | 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])
total = 0
for n in student_heights:
total = n + total
average = total/len(student_heights)
print(average)
|
ca99c3a4547201bc90e539cc2f26d4aa7867ecdc | skulumani/MAE3145 | /Homework/HW3/prob3.py | 733 | 3.609375 | 4 | """Solve problem 3 from MAE3145 HW 3
Asteroid impact
"""
import numpy as np
from astro import constants
import pdb
mu = constants.earth.mu
re = constants.earth.radius
asteroids = [(1, 1e5),
(100, 1e5),
(0, 7e4),
(0, 8e4),
(10, 8e4)] # energy, h for several asteroi... |
59b252c6a2308eb7c590901f9aa0090186b83161 | mitalishah25/hackerRank_problems | /introduction.py | 1,525 | 4.21875 | 4 | # Introduction
#Say "Hello, World!" With Python https://www.hackerrank.com/challenges/py-hello-world/problem
print("Hello, World!")
#Python If-Else https://www.hackerrank.com/challenges/py-if-else/problem
#!/bin/python3
N = int(input())
if N%2 == 0:
if 2 <= N <= 5:
print('Not Weird')
el... |
20983b17c271cdf107d580fe7b9dabf8b2ca36db | ljlassi/python-learning | /application.py | 660 | 3.578125 | 4 |
from car import Car
from chat_bot import ChatBot
car_manufacturer = input("Your car manufacturer? \n")
car_type = input("Your car type? e.g. Pickup? \n")
car_max_speed = int(input("Your car's max speed? \n"))
car_weight = int(input("Your car's weight? \n"))
my_car = Car(car_manufacturer, car_type, car_max_speed, car... |
2c979121431b3a0a435a35d7db8b9440fd80cafc | MaddCrazy/PythonPractice | /gradeCalc.py | 543 | 3.984375 | 4 | subjectFinalMark = int(input("Please enter the student's Subject Final Mark: "))
if (subjectFinalMark > 0 and subjectFinalMark < 50):
print ("Fail")
elif (subjectFinalMark >= 50 and subjectFinalMark < 60):
print ("Pass")
elif (subjectFinalMark >= 60 and subjectFinalMark < 75):
print ("Credit")
elif (subjec... |
6fc0ea22ee6af9b445bf1e42a0a6089b717b7809 | kevin-li-195/artificial-intelligence | /assignments/1/q1-optimization.py | 2,575 | 3.515625 | 4 | import math
import random
import csv
test_range = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
test_steps = [0.01, 0.02, 0.03, 0.04 ,0.05, 0.06, 0.07, 0.08, 0.09, 0.1]
def prob(prev, next, temp):
return(math.exp((next - prev)/temp))
def eval_func(x):
try:
return((math.sin((math.pow(x,2))/2))/math.sqrt(x))
... |
8be7ea60b1cd7f0ce2ab030b7d25c63b257a686a | MarcusGraetsch/awsrestart | /Exercise_1_ConvertHourintoSeconds.py | 295 | 4.34375 | 4 | hours = input("How many hours to you want to convert into seconds? ")
hours = int(hours)
seconds = hours*3600
print("{} hours are {} seconds!".format(hours, seconds))
print("Now with usage of a function")
def convert_hours (hrs):
sec = hrs * 3600
print(f"{hrs} are {sec}")
convert_hours(8) |
2b03ff7087d41665ecea8440bdd87ada27d6c200 | thinkingape46/Full-Stack-Web-Technologies | /Python/war_card_game.py | 7,568 | 3.671875 | 4 | # War card game
# Create all the 52 Cards
# Share cards between player and computer.
from random import shuffle
print("WELCOME TO THE WAR GAME")
class allCards():
number = list(range(2, 11))
chars = ["A", "K", "Q", "J"]
suffix = number + chars
symbol = ["♠", "♥", "♦", "♣"]
def __init__(self):
... |
eccc6cac4824435c77a7d706f555976b788e7446 | thinkingape46/Full-Stack-Web-Technologies | /Python/regular_expressions.py | 798 | 4.28125 | 4 | # Regular expressions
# Import regular expressions
import re
# mytext = "I am from Earth"
# USING REGULAR EXPRESSIONS TO FIND THE MATCH
# if re.search("Earth", mytext):
# print("MATCH found")
# else:
# print("MATCH not found")
# x = re.search("Earth", mytext)
# FIND THE START AND END INDEX OF THE MATCH
... |
d5c71aa70bb06ed2dde31e18cf98766caa9c5106 | AdamJSoftware/iti1120 | /assignments/A4/a4_300166171/a4_Q2_300166171.py | 551 | 3.890625 | 4 | # ITI1120 Assignment 4 - PT 2 -2
# Adam Jasniewicz 300166171
def two_length_run(array):
'''
array -> array of floats
Returns True if the give list has at least one run (of length at least two)
'''
last_run = None;
for run in array:
if run == last_run:
return True
l... |
0f76462a6eca506d11f58d6f1314a1a175ddfd5f | AdamJSoftware/iti1120 | /assignments/A2/a2_part2_300166171.py | 1,935 | 4.21875 | 4 | # Family name: Adam Jasniewicz
# Student number: 300166171
# Course: ITI 1120
# Assignment Number 2
# year 2020
########################
# Question 2.1
########################
def min_enclosing_rectangle(radius, x, y):
'''
(Number, Number, Number) -> (Number, Number)
Description: Calculates the x and ... |
d260adf34ad2844e2e85930b715ef9d902678f76 | ph4ge/ost-python | /python1_Lesson04/src/length_counter.py | 194 | 4 | 4 | """Demonstrating the continue statement"""
while True:
s = input("Enter a line: ")
if not s:
break
if s.startswith('#'):
continue
print("Length", len(s)) |
7f2c16d15d19183ceabdbcd7ea311bc4f4c27838 | ph4ge/ost-python | /python1_Lesson06/src/word_frequency.py | 456 | 4.125 | 4 | """Count the number of different words in a text."""
text = """\
Baa, baa, black sheep,
Have you any wool?
Yes sir, yes sir,
Three bags full;
One for the master,
And one for the dame,
And one for the little boy
Who lives down the lane."""
for punc in ",?;.":
text = text.replace(punc, "")
freq = {}
... |
ba43ddaaa5d63025a5e3cb91438ffe8a4d65f195 | ph4ge/ost-python | /Lesson05_Homework/src/word_list.py | 319 | 3.90625 | 4 | #
# word_list.py
#
upc_list, noupc_list = [], []
in_s = input("Input your text : ")
in_s = in_s.strip().split()
for el in in_s:
if not el.islower():
upc_list.append(el)
else:
noupc_list.append(el)
upc_list = upc_list + noupc_list
for el in upc_list:
print(el) |
4530424ca8cecc711e215ab98c0fb922eae40b01 | ph4ge/ost-python | /python1_Lesson06/src/pair_frequency.py | 707 | 4 | 4 | """Count the number of different words in a text."""
text = """\
Baa, baa, black sheep,
Have you any wool?
Yes sir, yes sir,
Three bags full;
One for the master,
And one for the dame,
And one for the little boy
Who lives down the lane."""
for punc in ",?;.":
text = text.replace(punc, "")
words = {... |
2e367d5fef8574eb45cbfa0bdc272119a76ca624 | ph4ge/ost-python | /python1_Lesson08/src/factorial.py | 237 | 3.765625 | 4 | """Print all factorials less than 1000."""
"""
c = 0
f = 1
while (f < 1000):
print(f)
c+=1
f=1
for n in range(c, 0, -1):
f = f*n
"""
c = 1
f = 1
while (f < 1000):
print(f)
c+=1
f*=c |
8180738b281c99f3efd7f666e5fcb2d91ff00679 | himelbrand/classic-ai | /cooperating-adversarial-agents/distance_algs.py | 2,538 | 3.84375 | 4 | import heapq
def get_shortest_path_Dijk(G,origin,dest,blocked=None,nodes_to_avoid=None):
"""Compute shortest path between two nodes ( Dijkstra ) without using the edges in the blocked list.
Return value : The weight of the shortest path and the list of nodes - the path itself , or infinity and empty list
... |
9245767d6c1ff91305ba076b8915473426bb0993 | himelbrand/classic-ai | /search-agents/Graph.py | 1,145 | 3.765625 | 4 | class Graph:
def __init__(self, graph, weights):
self.graph = graph # type: Dict[int,List[int]] # Graph : key - node ,
# value - list of it's neighbors
self.weights = weights # type: Dict[Tuple[int,int],int] # List of blocked edges ( for each edge two
# tuples (node1,no... |
17e0981af5496c8fe8a3c05e7d2ef15b2681064e | Benkimeric/number-game | /number_guess.py | 863 | 4.1875 | 4 | import random
def main():
global randomNumber
randomNumber = random.randrange(1, 101)
# print(randomNumber)
number = int(input("I have generated a Random number between 1 and 100, please guess it: "))
guess(number)
# guess method with while loop to loop when user does not give correct guess
def ... |
9dc958a0c22442c01e76ad8c37dd444bd7c774aa | rootExplorr/codeForAll | /Dictionary/runDictionary.py | 592 | 3.6875 | 4 | from dictionary import Dictionary
dictionary = Dictionary()
dictionary.addWord("hell")
dictionary.addWord("hello")
dictionary.addWord("learn")
dictionary.addWord("learnso")
dictionary.addWord("learner")
#print dictionary.root.list[7].word
#print dictionary.root.list[7].list[4].list[11].list[11].word
#print dictionary... |
7c203bd54f084f5d06d3a69d8edb708b6c14cf68 | twestura/ECL-Ratings | /scrape_ratings.py | 11,109 | 3.53125 | 4 | #!/usr/bin/env python
"""
A script for scrapping ratings from the Voobly website.
The list of players must be stored in a file named `players.csv`.
This file starts with a header line, then each following line is the player name
then the voobly profile link.
For example:
```
player-name, voobly-profile-link
TWest,http... |
63c90181fe378d9bb9093d8395ba0f1f147daf26 | shwesinhtay111/Python-Study-Step1 | /list.py | 1,501 | 4.53125 | 5 | # Create list
my_list = [1, 2, 3]
print(my_list)
# lists can actually hold different object types
my_list = ['A string', 23, 100.22, 'o']
print(my_list)
# len() function will tell you how many items are in the sequence of the list
print(len(my_list))
# Indexing and Slicing
my_list = ['one','two','three',4,5]
print(m... |
723cfd942791ed9266f240781f58118cb30ddea9 | shwesinhtay111/Python-Study-Step1 | /abstract_class.py | 1,280 | 4.6875 | 5 | # abstract class is one that never expects to be instantiated. For example, we will never have an Animal object, only Dog and Cat objects, although Dogs and Cats are derived from Animals
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def speak(self): ... |
bb075966e81bbf18c328841594c8ecee28d1475a | connvoi/leetcode | /g/arrayandstrings/rotateimage.py | 1,174 | 3.703125 | 4 | #https://leetcode.com/explore/interview/card/google/59/array-and-strings/3052/
class Solution:
#転置してreverseするとできる。
#def rotate(self, matrix):
# n = len(matrix[0])
# # transpose matrix
# #i = 1
# for i in range(n):
# #i = 1
# #j = 0,1,2
# for... |
9a0aabdb8932c5afa01cceaafccbcbeeca30badd | connvoi/leetcode | /linkdlist/rotatelist.py | 2,888 | 3.921875 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList:
def get(self, node: ListNode, index: int) -> int:
for _ in range(index+1):
node = node.next
return node.val
def addAtTail(self, node: ListNode, val: int... |
15bc5f4ae99db25d0f171c4521f195f6c7ce9828 | Thossakrai/Hypercube27_machine_learning | /hc27_ml_ sourcecode.py | 1,236 | 3.578125 | 4 | # -*- coding: utf-8 -*-
#created by Thossakrai Nakkasem
#demo 1
#from sklearn import datasets
#import pandas as pd
#
#iris = datasets.load_iris()
#print(iris.keys())
#
#data = iris.data
#target = iris.target
#
#df = pd.DataFrame(data, columns = iris.feature_names)
#print(df.head())
#บรรทัดที่17 พิมพ์ลงใน console
#p... |
156f8252659772d59fe912379b98c2843202df5b | yuzhenbo/leetcode | /leetcode/self/83_RemoveDuplicatesfromSortedList.py | 766 | 3.8125 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# Recursively
if not head or not head.next:
return head
head.... |
9388b31e14bafeb9145a4ece359381ec79dca322 | yuzhenbo/leetcode | /leetcode/standard/69_Squrt(x).py | 629 | 3.609375 | 4 | import numpy as np
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
# 牛顿迭代法
r = x
while r * r > x:
r = (r + x / r) / 2
return r
def sqrt(self, x):
if x == 0:
return 0
low = 1
hi... |
ad63b83d293709fff454662fbe92ae00cfa8e55d | yuzhenbo/leetcode | /leetcode/standard/21_MergeTwoSortedLists.py | 686 | 4.09375 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 2018/5/5
@author: yuzhenbo
"""
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return '{} -> {}'.format(self.val, self.next)
class Solution:
def me... |
fdb7388c8a412c5a166162944bff5defdd3d3151 | smallt-TAO/Reply-Deep-Learning | /smalltao_research/Actor_Audience_Critic_New/plot.py | 1,026 | 3.515625 | 4 | import matplotlib.pyplot as plt
def read_text(text_path, size=1000):
res = list()
avg_res = list()
with open(text_path, "r") as f:
text_list = f.readlines()
for text in text_list:
res.append(float(text.split(",")[2].split(":")[1].lstrip()))
avg_res.append(float(text... |
45f62a211770167f2711fb68074a4656e098c96e | JJSuriyaPrakash/PythonIntern | /Task-10/Task-10(ii).py | 129 | 3.734375 | 4 | import re
txt = "ab de villers"
x = re.findall("^ab",txt)
if x:
print("Match found")
else:
print("Match not found") |
c10e26e54f39d44252b0f7ad6152d85f12817e7f | JJSuriyaPrakash/PythonIntern | /Task-9/Task-9(v).py | 237 | 3.671875 | 4 | import random
randomlist = []
for i in range(0,20):
n = random.randint(1,500)
randomlist.append(n)
list1 = list(filter(lambda even_numbers:(even_numbers % 2 == 0),randomlist))
print("The even numbers in the list is:",list1) |
7f9b83bf0f69b913b70d49a0332e68aba10e6342 | wenyuzheng/codewars_katas | /Kyu7/disemvowel.py | 336 | 3.953125 | 4 | # def disemvowel(string_):
# newString = ""
# for char in string_:
# if char.lower() not in "aeiou":
# newString += char
# return newString
def disemvowel(string_):
return "".join(char for char in string_ if char.lower() not in "aeiou")
print(disemvowel("This website is for losers LOL!")) # "Ths wbs... |
3d20fa99eae7df1270b21c6a08bd3cc5d6adb375 | ocmadin/molssi_devops | /util.py | 694 | 4.4375 | 4 | """
util.py
A file containing utility functions.
"""
def title_case(sentence):
"""
Convert a string into title case.
Title case means that the first letter of each word is capitalized with all other letter lower case
Parameters
----------
sentence : str
String to be converted int... |
287f9cde6b658eecbbea5d5b64778ae09f23bffb | GuillermoDeAnda/Mision_03 | /Pago.py | 632 | 4.03125 | 4 | # Guillermo De Anda Casas, A01375892
# Programa que calcula el salario a pagar por horas extras, el pago normal y el pago total de un trabajador.
def pagoExtra(E,P):
extra = (E*(1.65*P))
return extra
def pagoNormal(N,P):
pago = N * P
return pago
def main():
N = int(input("Teclea las horas normale... |
5c5b972e01913da788d4f5b432be39b7acae120d | sachsom95/my_leets | /decode.py | 636 | 3.90625 | 4 | def helper(curr, code):
if curr == 0:
if code[curr] == '0':
return 0
else:
return 1
if curr == -1:
return 1
ways = 0
if code[curr] == '0':
if code[curr-1] == '1' or code[curr-1] == '2':
return helper(curr-2, code)
else:
... |
9b86666ce1b673812930e23499e122f822310141 | sachsom95/my_leets | /234. Palindrome Linked List/solution1.py | 1,450 | 3.84375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if (head):
fast = head
slow = head
is_even = False
... |
5e058ae1009c62fafbb7ad594e6a094b3191c301 | sachsom95/my_leets | /Merge sort/test.py | 440 | 3.984375 | 4 | def merge_sort(s):
n = len(s)
if n < 2:
return
mid = n // 2
s1 = s[0:mid]
s2 = s[mid:n]
merge_sort(s1)
merge_sort(s2)
merge(s,s1,s2)
def merge(s,s1,s2):
i = j = 0
while i + j < len(s):
if j < len(s2) or ( i < len(s1) and s1[i] < s2[j] ):
s[i+j] = s1[... |
7e17c44653fa2da8c0493f750337aeda45852e74 | kabilasudhannc/simple_coffee_dispenser | /main.py | 2,646 | 4.09375 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
... |
479c80e4210bce5889b5b715e5aa5a687a2ce3ee | tn259/leetcode-accepted-submissions | /add-one-row-to-tree.py | 1,584 | 4.0625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
### Solution 1 ###
# collect node at depth d-1 -> in order traversal
# for each do algorithm
# T Complexity of in order traver... |
183901b86f545388d9b10598e46a2c5c9bfb5111 | ToBeTree/cookbookDemo | /2字符串和文本/2-15字符串插入变量.py | 966 | 3.640625 | 4 | # 创建一个内嵌变量的字符串,变量被它的值所表示的字符串替换掉
# 可以通过format函数来解决这个问题
s = '{name} has {n} message'
print(s.format(name='peter', n=3))
# 如果变量域能 找到变量,使用format_map和var
# 同时var还支持类var(classInstance)
name = 'peter'
n = 4
print(s.format_map(vars()))
# print('%(name) has %(n) messages.' % vars())
# 为了处理变量缺失的问题,定义一个含有__missing__的字典对象
class ... |
a53738ecb0cba48cc18507e71562d2c50baa9007 | ToBeTree/cookbookDemo | /1-数据结构和算法/1-7字典排序.py | 415 | 4.09375 | 4 | # 字典排序用collections模块中的OrderDict
# 但是需要消耗双倍空间资源
from collections import OrderedDict
d = OrderedDict()
d['food'] = 1
# d['food'] = 2
d['apple'] = 2
d['stupid'] = 3
for key in d:
print(key, d[key])
# json格式化
import json
a = json.dumps(d)
print(a)
dd = dict()
dd['food'] = 1
# d['food'] = 2
dd['apple'] = 2
dd['stupi... |
07a41ea64c3168fa6f880929cd3da06c87647506 | ToBeTree/cookbookDemo | /2字符串和文本/2-1字符串分割.py | 399 | 3.59375 | 4 | # str.split函数只能分割相当规则字符串
import re
line = 'a,b,c,d,e'
print(line.split(','))
# 正则表达式的split函数
# 正则表达式不能老是忘啊
line = 'asdf fjdk; afed, fjek,asdf, foo'
print(re.split(r'[;,\s]\s*', line))
# 小括号会保留分割字符串
print(re.split(r'(;|,|\s)\s*', line))
# (?:...)不会保留分割字符串
print(re.split(r'(?:;|,|\s)\s*', line))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.