blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
43544626fb8c5e5ee386221c64b2d68660a79e88 | dominicdaviescodes/py-fundamentals | /Ex_Files/Exercise Files/Chap05/05_04_end.py | 381 | 3.796875 | 4 | # return is a key word
def withdraw_money(current_balance, amount):
if (current_balance >= amount):
current_balance = current_balance - amount
return current_balance
# because we want to use the value later save in a variable
balance = withdraw_money(100, 80)
if (balance <= 50):
print("We need... |
ecc0b829e36533c46c4881c78c648d6c284af5d6 | yanbinkang/problem-bank | /leetcode/binary_search/python/single_element_in_sorted_array_leetcode.py | 1,838 | 3.765625 | 4 | """
https://leetcode.com/problems/single-element-in-a-sorted-array
Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once.
Example 1:
Input: [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: [3,3,7,7,... |
e24885ab26c339ce2a525845896ac0e849158729 | potato179/pythonProjectwlswodnd | /문제300/문제 31~40.py | 1,051 | 3.875 | 4 | # 문자열
# 031.
a = "3"
b = "4"
print(a+b)
# 예상 결과
# 34
# 032.
print("Hi"*30)
# 예상 결과
# HiHiHi
# 033.
print("-"*80)
# 034.
t1 = "python"
t2 = "java"
t3 = t1 + " " + t2 + " " # 문자끼리 +로 연결
print(t3*4)
# 035. %s : 문자 형식 %d : 정수 형식
name1 = "김민수"
age1 = 10
name2 = "이철희"
age2 = 13
print("이름: %s 나이: %d" % ( name1 , age... |
7269a1ebe56d38b758e3adce5a7e9093158d2755 | jc328/CodeWars-1 | /8kyu_ReturningStrings.py | 340 | 4.3125 | 4 | # 8kyu - Returning Strings
# Make a function that will return a greeting statement that uses an input;
# your program should return, "Hello, <name> how are you doing today?".
# [Make sure you type the exact thing I wrote or the program may not execute properly]
def greet(name):
return "Hello, " + name + " how a... |
c21a8684c74e0b9cd46f60d8d5a7f2e8f231000b | Lihengwannafly/Data_Structure_and_Algorithm | /Task1/9.循环链表.py | 2,770 | 4.03125 | 4 | """
插入或者删除的时候,如果操作的节点在tail或者head,需要注意,tail.next->head.next,其余和单向链表基本相同
"""
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
class LinkList(object):
def __init__(self):
"""初始化链表"""
self.head = None
self.tail = None
self.len = 0
de... |
6e7c5229ce68cba93c645af7be4a37550ebc4a17 | Navyashree008/while_loop | /while_loop/perfect_no.py | 201 | 3.859375 | 4 | num = int(input("enter no:"))
i = 1
sum = 0
while i < num:
if num % i == 0:
sum = sum+i
i+=1
if sum == num:
print("its a perfect number")
else:
print("its not a perfect number") |
58466c27c4cafb4c4f03849d43e97e68afe30f46 | 22a/DistributedTelecoms | /packet_pool.py | 1,283 | 3.78125 | 4 | from Queue import Queue
from errors import EmptyQueueException
class PacketQueue:
# @param: Initial size of queue (defaults to 0).
def __init__( self, size = 0 ):
self.packet_queue = Queue()
# Returns: True if the queue does not contain
# any queued packets.
def empty( self ):
return self.packet_queue.emp... |
6f91022a8995a336df0d17d8842992a6f27d80d0 | officialyenum/CS50 | /pset6/mario/less/mario.py | 305 | 3.859375 | 4 | from cs50 import get_int
def main():
while True:
n = get_int("Height: ")
if n >= 1 and n <= 8 :
break
for i in range(1, n + 1):
num_hashes = i
num_spaces = n - num_hashes
print(" " * num_spaces, end="")
print("#" * num_hashes)
main() |
06787d412c58ec49d78a8d9aad4d3384e1cbe13d | hvn2001/LearnPython | /DataStructures/IntroLinkedLists/SearchSinglyLinkedList.py | 1,577 | 4.03125 | 4 | from DataStructures.IntroLinkedLists.LinkedList import LinkedList
# Access head_node => list.get_head()
# Check if list is empty => list.is_empty()
# Node class {int data ; Node next_element;}
# Searches a value in the given list.
# HVN
def search(lst, value):
# Write your code here
if lst.get_head() is no... |
282e75ef273f4e0cb0f48f881760287bd9020d07 | iamksir/studyEveryDay | /learn_exam/exam8.py | 270 | 3.53125 | 4 | while True:
try:
n = int(input())
res = -1
if n < 3:
res = -1
elif n % 3 == 0:
res = 2
elif n % 4 == 0:
res = 3
else:
res = 4
print(res)
except:
break |
9aff04020ea295c118a9458390d5e484f9c68e2a | wancaibida/alfred-workflows | /wf_case/main.py | 3,440 | 3.515625 | 4 | import sys
import json
def to_const(string):
out_const = ''
is_first = True
for s in string:
if s.isupper():
if not is_first:
out_const += '_'
elif s == ' ':
out_const += '_'
out_const += s.upper()
is_first = False
return out_cons... |
24017e46307ea3ac5c46b47f3b31ba74d1dd3153 | Zriyaz/Python-Practice | /MaxOccurenceDigit.py | 552 | 3.8125 | 4 | def countOccurrences(x, d):
count = 0;
while (x):
if (x % 10 == d):
count += 1;
x = int(x / 10);
return count;
def maxOccurring(x):
if (x < 0):
x = -x;
result = 0;
max_count = 1;
for d in range(10):
count = countOccurren... |
4aa18783cc232db4b14ca5f121c2ec9407406d17 | chenzhiliang94/SG-HDB | /AffordabilityCalculator/findMaxLoan.py | 631 | 3.53125 | 4 | def findMaxLoan(interestRate, salary, age, carLoan, homeLoan, otherCommitments):
totalDebtObligation = carLoan + homeLoan + otherCommitments
age = max(age, 21)
numerator = min((0.6 * salary - totalDebtObligation), (0.3 * salary - homeLoan))
a = 0
if (65 - age >= 25):
a = (interestR... |
43cfc8b56b61e22b81191fd8eb98fb0aa16a2941 | sreekanthpv/mypythonworks | /exam/calculator.py | 823 | 4 | 4 |
# 5.create a calculator with functions(addition,subtraction,multiplication,division,floor division,exponent)?
def add(x,y):
return x+y
def sub(x,y):
return x - y
def mul(x,y):
return x * y
def div(x,y):
return x / y
def floor(x,y):
return x // y
def exp(x, y):
return x ** y
a= int(input('en... |
dfa1d41abf59db368bc64a0de722bf6abf35d8ab | KostyaTolok/Lab2_dops | /Lab2_dops/task9_range.py | 339 | 3.734375 | 4 |
def _range(start: int, end=None, step=1) -> iter:
if end is None:
end = start
start = 0
if step < 0:
while end < start:
yield start
start += step
elif step > 0:
while start < end:
yield start
start += step
print([i for i in... |
efd6c40be2385094283e9e881de61693b3272c1a | anbarasanv/PythonWB | /Maximum Sum for Contiguous Sub Array.py | 864 | 3.890625 | 4 | #Time complexity: O(n)
import sys
import timeit
#Timer has been started
start = timeit.default_timer()
def maxSumSubarray(arr):
'''This function returns the maximum sum of contiguous sub array'''
#Here finalMax declared to hold both positive and negative integers.
#So that the array contains negative intege... |
dbbb7d625e78d4f466e0be933fb46ab85d99a21c | MaciejWasilewski/IntroToAlgorithm | /Searching/quicksort_select/python/main.py | 1,039 | 4.03125 | 4 | def quicksort_select(array, start, end, item):
if start > item or item >= end:
raise ValueError('You are looking for an item of index beyond the scope of the array!')
if start == item:
return array[start]
else:
pivot = array[end - 1]
pivot_index = start
for i in rang... |
2622081d440dfc6e84edf88a8e6b07105ee33b01 | godblessY/hahaha | /2.py | 2,719 | 3.96875 | 4 | # _*_ coding:utf-8 _*_
# m = input('请输入月份:')
# m = int(m)
# if 1 <= m <= 12:
# print('输入的月份合理')
# if 3 <= m <= 5:
# print('%d月份是春季' % m)
# elif 6 <= m <= 8:
# print('%d月份是夏季' % m)
# elif 9 <= m <= 11:
# print('%d月份是秋季' % m)
# else:
# print('%d月份是冬季' % m)
# else:
# ... |
b261eeeedc06c74fcb3ead489522c60d4720a9d8 | saleed/LeetCode | /373.py | 2,485 | 3.578125 | 4 | import heapq
class Solution(object):
def kSmallestPairs(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[List[int]]
"""
if not nums1 or not nums2:
return []
visited = []
heap = []
... |
125a33f89e6b29581d0f6c166926fa1cd7b56c38 | xinlee92/PythonDemo | /4_2_1.py | 386 | 4.09375 | 4 | #homework_4_2_1
#判断数字能否被2和3整除,输出结果
num=int(input('Please input a number:'))
if num%2==0 and num%3==0:
print(str(num)+'能被2和3整除')
elif num%2==0:
print(str(num)+'能被2整除,不能被3整除')
elif num%3==0:
print(str(num)+'能被3整除,不能被2整除')
else:
print(str(num)+'不能被2或3整除')
|
1ef211f1f82196d44c4209330c63eb6a6b0eddfe | rperezl-dev/S10-POO | /calculadora_menu/calculadora.py | 549 | 3.59375 | 4 | class Calculadora:
def __init__(self, numero1=0, numero2=0):
self.numero1 = numero1
self.numero2 = numero2
def suma(self):
sumar = (self.numero1 + self.numero2)
return round(sumar, 2)
def resta(self):
res = (self.numero1 - self.numero2)
return round(res, 2)
... |
b656ebcb87f09db4d14083baf925e3a4b5e10d92 | Eschatons/puzzles-and-interview-questions | /string_interview_questions.py | 3,919 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 11 14:31:35 2016
@author: efron
"""
## code interview questions
"""
#1 write code to check if a string is a palindrom
"""
def is_palindrome(string):
# O(n)
if string == string[::-1]:
return True
else:
return False
#test:
#print(i... |
bfa449a9ca786ee6c7c6ba0de7bc51bfc91d4b30 | ahammadshawki8/DSA-Implementations-in-Python | /CHAPTER 05 (array_based_sequences)/caesar ciphar.py | 1,062 | 3.828125 | 4 | # Caesar_Cipher class
class CaesarCipher:
def __init__(self,shift):
encoder=["k"]*26
decoder=["k"]*26
for k in range(26):
encoder[k] = chr((k + shift) % 26 + ord( "A" ))
decoder[k] = chr((k - shift) % 26 + ord( "A" ))
self.forward = "".join(... |
367b787e826237eccfe5fe120e38e20b4f6333e0 | codeAligned/Leet-Code | /src/P-008-String-to-Integer.py | 2,578 | 3.953125 | 4 | '''
P-008 - String to Integer (atoi)
Implement atoi to convert a string to an integer.
The function first discards as many whitespace
characters as necessary until the first non-whitespace character is
found. Then, starting from this character, takes an optional initial
plus or minus sign followed by as many numerica... |
0ada761f507bc8db058e01c81fc2e8cea990d7a1 | FSwordArt/python-learn | /data_structure/23_二叉搜索树_Binary Search Tree.py | 4,303 | 3.953125 | 4 | # -*- coding: utf-8 -*
class Node(object):
def __init__(self, item):
self.elem = item
self.lchild = None
self.rchild = None
self.parent = None
class Tree(object):
def __init__(self,alist=None):
self.root = None
if alist:
for value in alist:
... |
5c862396b08f30230dbbf9b3d89d83c10d194424 | rajdharmkar/Python2.7 | /functions/kwargs2.py | 264 | 3.671875 | 4 | def print_kwargs(**kwargs):
print(kwargs)#the keyworded var pairs are printed as a dictionary of same pairs
print_kwargs(kwargs_1="Shark", kwargs_2=4.5, kwargs_3=True)
foo = {'kwargs_1':"Shark", 'kwargs_2':4.5, 'kwargs_3':True}
print_kwargs(**foo) |
543607f3c60b6a28c4f99b56ad434850dca786af | RobertCordingly/easyRL-v0 | /Agents/agent.py | 3,044 | 4.125 | 4 | from abc import ABC, abstractmethod
"""This is an abstract model-free agent class that allows a user to define
their own custom agent by extending this class as a class named 'CustomAgent'.
"""
class Agent(ABC):
"""
This is a parameter class that defines a parameter of an extended agent
"""
class Param... |
37bd1683785377afe49b17d3aec9700665e3d3db | MyoMinHtwe/Programming_2_practicals | /Practical 5/Extension_3.py | 1,804 | 4.1875 | 4 | def bill_estimator():
MENU = """11 - TARIFF_11 = 0.244618
31 - TARIFF_31 = 0.136928
41 - TARIFF_41 = 0.156885
51 - TARIFF_51 = 0.244567
61 - TARIFF_61 = 0.304050
"""
print(MENU)
tariff_cost = {11: 0.244618, 31: 0.136928, 41: 0.156885, 51: 0.244567, 61: 0.304050}
choice = int(input("Which tariff?... |
f69e94c82926ad4296cf485a73cff162b80cd763 | Nobody0321/MyCodes | /OJ/LeetCode/69. Sqrt(x).py | 395 | 3.53125 | 4 | class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0 or x == 1:
return x
for i in range(0, x+1):
if i * i > x:
return i - 1
# elif i*i >x and (i-1) **2 <x:
# return i-1
if... |
8472fec552d323f8ceade180eca5b8adf1121c3d | kevtan/python-assignments | /assign1/crypto.py | 4,229 | 3.78125 | 4 | #!/usr/bin/env python3 -tt
"""
File: crypto.py
---------------
Assignment 1: Cryptography
Course: CS 41
Name: <YOUR NAME>
SUNet: <SUNet ID>
Replace this with a description of the program.
"""
import utils
# Caesar Cipher
def encrypt_caesar(plaintext):
"""Encrypt plaintext using a Caesar cipher.
Add more imp... |
b489760a1a9dc2f05c3783bad52cf98a24f78007 | Oxyjon/Breakout-Game | /block.py | 699 | 3.625 | 4 | from turtle import Turtle
import random
COLORS = ["red", "orange", "grey", "green", "blue", "purple"]
Xs = [240, 200, 160, 120, 80, 40, 00, -40, -80, -120, -160, -200, -240]
Ys = [250, 230, 210, 190, 170, 150]
class Block(Turtle):
def __init__(self):
super().__init__()
self.ht()
self.block... |
5f31915f73784690a2ed6fd2f7838a701aff8497 | EmilyYLMa/Advent-2020 | /3/three.py | 1,333 | 3.6875 | 4 | import argparse
import numpy
def find_number_trees(grid, route):
# if empty grid, return 0 trees found
if not grid:
return 0
parsed_grid = grid.splitlines()
len_x, len_y = len(parsed_grid[0]), len(parsed_grid)
x_route, y_route = route
x, y = (0, 0) # starting location
num_trees... |
b99c42e2a8a79c578e330e81cac7afc084c14095 | codeSmith12/PCAP-Training | /point.py | 530 | 3.875 | 4 | import math
class Point:
def __init__(self, x=0.0, y=0.0):
self.__x = x
self.__y = y
def getx(self):
return self.__x
def gety(self):
return self.__y
def distance_from_xy(self, x, y):
return math.hypot(self.__x, self.__y, x, y)
def distance_from_point(s... |
7f2d5803299d088adac61cd5f457b7f7d65d4ce3 | omarmohamud23/Lab-1-Hello-Python | /listofclasses.py | 380 | 4.25 | 4 | classes = []
print('what classes are you taking this semester?')
name_of_class = input ('Enter what class(Press Enter to stop): ')
while name_of_class:
classes.append(name_of_class)
name_of_class = input ('Enter what class(Press Enter to stop): ')
print('Your classes this semester are: ')
for ind... |
a8b20865c0e02c9ca9358f4c52cca9ac0850f2af | nickpalenchar/coding-the-matrix-labs | /task_1_4_10.py | 420 | 3.546875 | 4 | """
Plotting a png image
"""
import plotting
from image import file2image
img = file2image('img01.png')
img_plot = []
for y, _ in enumerate(img):
line = [complex(x, y) for x, rgb in enumerate(img[y]) if rgb[0] < 120]
for dot in line:
img_plot.append(dot)
if __name__ == '__main__':
from task_1_... |
10161a2a7f0b7d3b160490d4d4eb58b71c7b9feb | mshsarker/PPP | /WebScraping/Scraping_dad_joke.py | 778 | 3.703125 | 4 | import requests
from random import choice
import pyfiglet
import termcolor
header = pyfiglet.figlet_format("Dad__Joke ###")
header = termcolor.colored(header, color = 'green')
print(header)
user_input = input("What would you like to search for?")
url = 'http://www.icanhazdadjoke.com/search'
response = ... |
cf95f0bef7fffe74471579ac85660c3c1a8b9e2f | TheDinner22/calculator | /pyLib/float.py | 5,862 | 4.15625 | 4 | # my custom float class used to handle floating point numbers
class My_Float:
def __init__(self, value=0):
"""validate value param and turn it into float
Args:
value (int, str, None): Value to be converted into a float
Note:
float isn't a type for the value arg he... |
dcbcdb94adf49e8e995a9dee4a8534abbe9a1b76 | mauro39ar/prueba | /tp2examen/ejercicio_7.py | 268 | 4 | 4 | #!/usr/bin/python
Mark= input("ingrese numero: ")
aNtony = input("ingrese numero: ")
if Mark % aNtony == 0:
print ("el numero %s es divisible por %s " % (Mark, aNtony))
else:
print ("el numero %s no es divisible por %s " % (Mark, aNtony)) |
118b10ef3a3dca9ea7e5ae6318f7d0ea24cefaa3 | zhangping9328/study | /plane/for循环漏删除.py | 533 | 3.71875 | 4 | def remove():
old_list = [11,22,33,44]
new_list = []
# for i in old_list:
# if i ==22 or i ==33:
# old_list.remove(i)
# print(old_list)
# return old_list
# for m in new_list:
# list.remove(m)
# print(list)
# list.remove(i)
... |
0c4af3b53868b1cacffb0dc6c2af2733349b4dc0 | LalityaSawant/Python | /DS and Algo in Python/Basics/012_tuples.py | 346 | 3.78125 | 4 | # tuples are immutable
my_random_tuple = ('first',1,7,6,4,5,8,'hi there',2,3,1,5,2,1,9,10)
my_tuple =('first_value','second_value','third_value')
print(my_random_tuple[0])
print(my_random_tuple[-1])
print(my_random_tuple[::-1])#reverse view
print(len(my_random_tuple))
print(my_random_tuple.count(5))
print(my_random... |
16d9aca43c02e1be77da1500ac0146f6d7d3f150 | FanchenBao/GAME_Alien_Invasion | /missile.py | 1,159 | 3.625 | 4 | '''
Author: Fanchen Bao
Date: 02/18/2018
Description:
Missle class, handle missles fired by aliens.
'''
import pygame
from pygame.sprite import Sprite
class Missile(Sprite):
''' a class to manage alien missile'''
def __init__(self, ai_settings, screen, alien):
super().__init__()
self.screen = screen
self.ai... |
6c91e450b03af440d1d343bb16bc3f4db96fcdcf | BrightBct/AI-Personal-Assistant | /function/window.py | 962 | 3.5 | 4 | import tkinter as tk
def open_windows():
url_list = []
root = tk.Tk()
canvas1 = tk.Canvas(root, width=400, height=300, relief='raised')
canvas1.pack()
label1 = tk.Label(root, text='Summarization')
label1.config(font=('helvetica', 14))
canvas1.create_window(200, 25, window=label1)
la... |
6cb52dd0449937d07bab7f33883e389c1aef47d9 | learnermaxRL/design-pattern-practice-python | /observer.py | 1,095 | 3.640625 | 4 | from abc import abstractmethod,ABCMeta
class Observer:
@abstractmethod
def update(self,value):
pass
class Observable:
def __init__(self) -> None:
self._observers: List[Observer] = []
def attach(self, observer: Observer) -> None:
if observer not in self._observers:
... |
5e94ae7bc20911bbd043dfee561952ce56143790 | Ban0720/Battlefy-Toolkit | /src/battlefy_toolkit/utils/misc.py | 1,140 | 3.734375 | 4 | import re
from typing import Union
def is_valid_battlefy_id(battlefy_id: str) -> bool:
"""
Verify a str is a Battlefy Id (20 <= length < 30) and is alphanumeric.
:param battlefy_id:
:return: Validity true/false
"""
return 20 <= len(battlefy_id) < 30 and re.match("^[A-Fa-f0-9]*$", battlefy_id)
... |
d06e8bbef6b28a931f2873ca55afb3f31e31dd7a | knightrohit/monthly_challenges | /leetcode_aug_2020/20_Reorder_list.py | 772 | 3.984375 | 4 | """
Time Complexity = O(N)
Space Complexity = O(1)
"""
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head:
return
# Find middle
slow = fast = head
while fast and... |
8e97707a8e41df6857c29b005aa46fc4e06281f9 | sunwang33/code | /s14/day01/interaction.py | 583 | 4.25 | 4 | #Author: sun wang
name = input("name:")
age = int(input("age:"))
print (type(age) , type(str(age)))
job = input("job:")
salary = input("salary:")
info = '''
--------- info of %s ----
Name: %s
Age: %d
Job: %s
Salary: %s
''' % (name , name , age , job ,salary)
info2 = '''
--------- info2 of {_name} ----
Name: {_name}
Ag... |
effeae40d3dd8586e0a768c8dcc1bfec38f0d8f1 | daniel-reich/ubiquitous-fiesta | /mJpjpgxkxvTY4Qbwf_15.py | 431 | 3.625 | 4 |
def bingo_check(board):
for i in board:
if i == ['x','x','x','x','x']:
return True
for i in range(5):
if board[0][i] == board[1][i] == board[2][i] == board[3][i] == board[4][i]:
return True
if board[0][0] == board[1][1] == board[2][2] == board[3][3] == board[4][4]:
return True
elif boar... |
f44e57beab95bbb5ceee339a1f2cbf733292869c | Aasthaengg/IBMdataset | /Python_codes/p03719/s114585823.py | 176 | 3.515625 | 4 | def resolve():
a, b, c = map(int, input().split())
ans = str()
if c >= a and c <= b:
ans = "Yes"
else:
ans = "No"
print(ans)
resolve() |
438d72df8ca4d7cf07aeb2d8f56af07fb7281b54 | mustious/Worked-Exercises-Python-Brian-Heinold | /EX5/7.py | 415 | 3.9375 | 4 | import sys
number = int(input("Please enter the your number: "))
divisors = []
squares = [0]
for i in range(1, number + 1):
if i != 1 and squares[-1] < number:
squares.append(i ** 2)
# get the divisors of number
if number % i == 0:
divisors.append(i)
if i in... |
94ecf4b61e61fc0f76931c5be3ee0d6d8ded81a9 | judyfun/python | /demo/guessNum-random.py | 232 | 3.578125 | 4 | from random import randint
a = randint(1,100)
flag=True
while flag:
answer=int(input())
if a==answer:
print("BINGO")
if a<answer:
print("有点大")
if a>answer:
print("有点小")
|
af10357617f8aaa23bb5ef88cef2b3949e340991 | MahmudX/Algorithms | /1. First Duplicate in an Array/main.py | 251 | 3.5 | 4 | def firstDuplicate(intArr):
for x in intArr:
index = abs(x) - 1
if intArr[index] < 0:
return abs(x)
intArr[index] *= -1
return -1
arr = [8, 8, 6, 2, 6, 4, 7, 9, 5, 8]
print(firstDuplicate(arr))
|
5dda266f82a784f1d086909e2c897807db62091a | Vvaradinov/ICS-32 | /Projects/othello_gui.py | 9,271 | 3.6875 | 4 | # Vladislav Varadinov #32979197
import tkinter
import Othello_logic
class Othello_gui():
def __init__(self):
self._root_window = tkinter.Tk()
self._root_window.rowconfigure(1, weight = 1)
self._root_window.columnconfigure(0, weight =1)
self._root_window.columnconfigure(1, weight =... |
4a4eba35a2b9aaaa71988c8d643fb40560f50461 | Fzhou1996/fangzhou | /NYC_taxi_trips.py | 4,421 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 19 18:09:29 2018
@author: 123
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 3.1
### import data
trips1 = pd.read_csv('trips.csv')
## 3.1.1
### Latitude is greater than 40 and less than 41.5
a=trips1.loc[(trips1.pickup_latitud... |
e39fac1a7baef484c617a27e17c15793a1da64af | JoonasStone/hogwarts_zst_lg3 | /lagou_game/src/1Vs1.py | 1,743 | 3.96875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
题目:
一个多回合制游戏,每个角色都有hp 和power,
hp代表血量,power代表攻击力,hp的初始值为1000,
power的初始值为200。打斗多个回合
定义一个fight方法:
my_hp = hp - enemy_power
enemy_final_hp = enemy_hp - my_power
谁的hp先为0,那么谁就输了
'''
import random
import time
print(" ******游戏开始****** ")
time.sleep(1.5)
print("******玩家信息*****")
... |
3f2b69fc1b27459766eb6ad3c13c629887d9f425 | mike-menendez/shiny-potato | /labs/7/task3.py | 933 | 3.921875 | 4 | import math
from PIL import Image
"""
Task 3:
- Create a chroma key photo.
- Steps:
- grab pixel from background
- make background different with chroma key
- display newly created image
"""
def distance(color_1, color_2):
red_diff = math.pow((color_1[0] - color_2[0]), 2)
green_diff ... |
1cf8743a0dfc74ed69f314fc86f9c73c86cb68b9 | ratin42/python_piscine | /j02/ex03/beverages.py | 799 | 4.03125 | 4 | class HotBeverage():
"""Just some hot water in a cup."""
price = 0.30
name = "hot beverage"
def description(self):
return "Just some hot water in a cup."
def __str__(self):
return(
"""
name : %s
price : %s
description : %s
""" % (self.name, self.price, self.description()))
class Coffee(HotBeverage):
... |
552215f797c7b2aae786a80d32b476180e69c986 | yurtsiv/heap-visualizer | /heap/node.py | 1,579 | 3.71875 | 4 | class Node:
def __init__(self, id, key):
self.id = id
self.key = key
self.right = self.left = self.parent = None
def find_relative_side(self):
if not self.parent:
return None
if self.parent.left and self.parent.left.id == self.id:
return 'left'
return 'right'
def sub... |
30098ec1cea98911e9ee8deda1cf59c0f9453468 | PrakashPrabhu-M/pythonProgramsGuvi | /app.py | 2,452 | 3.859375 | 4 | import os,time
def pro():
os.system('clear')
print('Welcome'.upper().center(50,'*'))
run=True
while run:
run=False
name=input("Type your name: ".upper())
if name=='':
print('Type Something')
time.sleep(2)
os.system('clear')
run=True
continue
for i in name:
if ... |
96fb217ffd265400fece41da321c1531c4cadbd1 | Chaaarles/bookish-octo-invention | /ITGK/Øvinger/Øving 6/lister.py | 315 | 3.671875 | 4 | # a)
my_first_list = [1, 2, 3, 4, 5, 6]
print(my_first_list)
# b)
print(my_first_list[-1])
# c)
my_first_list[-2] = 'pluss'
print(my_first_list)
# d)
my_second_list = my_first_list[3:]
print(my_second_list)
# e)
ti = my_second_list[0] + my_second_list[2]
print(my_second_list, " er lik ", ti)
|
58fe9c043e382c0a4d147ace7ea61730ad82ecaf | alevenberg/bullet-journal-cli | /io_generator.py | 2,245 | 4 | 4 | import csv
import os
def write_csv(directory, file, line):
"""
Writes a string to a csv file in a subdirectory where the file exists
Args:
directory (str): the name of the directory
file (str): the name of the file
line (list): a list to write to the file
"""
# Ma... |
be505613c62241e82ab82884a34cdbbfc317e2d4 | wbschrei/python-challenge | /PyBank/main.py | 2,044 | 3.5625 | 4 | import os
import csv
budget = os.path.join("Resources", "budget_data.csv")
# Lists to store data
months = 0
PL = 0
DailyPL = 0
PriorPL = 0
Openval = 0
Closeval = 0
AvgChange = 0
AvgChangeSum = 0
AvgChangeCtr = 0
GreatIncDt = ""
GreatIncVal = 0
GreatDecDt = ""
GreatDecVal = 0
#with open(budget, newline='', encoding =... |
7fe0bb0a5c0cbfb8a7395a63d9a10f31c4628d28 | stackker/cohort3 | /Python/Competencies/readFiles220.py | 1,793 | 4.375 | 4 | # clears the terminal screen
print('\033c')
def countSearchString(searchString, fileNamePath):
""" Takes Regex search Inputs """
import re
# fileName = open(fileNamePath, 'r')
# file_contents = fileName.read()
with open(fileNamePath, 'r') as fileName:
regex = re.compile(str(searc... |
7012da8647cc8d749a60204532657a0bfdb65954 | zhy0313/children-python | /人工智能初步(选修)/test03_NLP.py | 486 | 3.546875 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
from nltk.tokenize import sent_tokenize, word_tokenize, WordPunctTokenizer
input_text = "Do you know what natural language processing is? This is a very interesting technology! We'll look at it in this section."
print("\nSentence tokenizer:")
print(sent_tokenize(input_t... |
d0fa2956c8fccfec4607e31d2f1f4af6b03796ad | ranog/python_work | /capitulo_08-Funcoes/albuns_usuarios.py | 1,403 | 4.03125 | 4 | #! /usr/bin/env python3
"""
NOME
albuns_usuarios.py - FAÇA VOCÊ MESMO.
SINOPSES
chmod +x albuns_usuarios.py
./albuns_usuarios.py
DESCRIÇÃO
8.8 – Álbuns dos usuários: Comece com o seu programa do Exercício
8.7. Escreva um laço while que permita aos usuários fornecer o nome
de um artista e o tí... |
ee8031fddd50cce13e9ba7fdef74f96457bf4ef5 | PrakharimaSingh/prakharimasingh | /program1.py | 253 | 3.625 | 4 | name=inpu("enter name:")
gender=("enter gender:")
branch=input("enter branch:")
college=("enter college:")
age=int(input("enter age:")
print("name: ", name)
print("gender: ",gender)
print("branch: ",branch)
print("college: ",college)
print("age: ",age)
|
7c6350c36b1cfd7d25b60562375942a624020efa | Gorazor/leetcode | /链表/206.反转链表.py | 901 | 4 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur=head
pre=None
while cur:
next=cur.next
cur.next=pre
... |
6d85ae4e9c60d5da333344b5574162ed189ee515 | Abdoul84/Python-Challenge | /Python-Challenge/main.py/PyPoll_Top | 1,816 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 24 02:22:13 2021
@author: moz
"""
# Import csv_file
import csv
# Variables to store data
voterID = []
candidates = []
# Open, read, and skip first row (header) of csv_file
PyPoll = "//Users//moz//Desktop//PyPoll//PyPoll.csv"
with open (PyPoll)... |
6d7265378602c0048f28fd34145c3a0d9ab56add | MANI3415/WebDevelopmentUsingDjango-internship-SRM-University | /16-06-2021/leap_years_in_range.py | 399 | 4.1875 | 4 | # Write a program to find all the leap years in a given range
# Gregorian Calender : one year = 365.246..
def is_leap_year(year):
if year%4==0 and (year%100!=0 or year%400==0):
return True
return False
start_year = int(input())
end_year = int(input())
for year in range(start_year,end_y... |
0c7f86a70a61140f60432a94680d68db2dc27779 | Khudoteplov/Turtle-2 | /randoms.py | 114 | 3.546875 | 4 | import turtle
from random import *
s=1
while (s>0):
turtle.forward(20)
turtle.left(randint(0, 360))
|
2f660bcde607e048a8f782efebef35e75fd56943 | Vernik22/OLC1-Proyecto1-201712057 | /[OLC1]P1_201712057/[OLC1]P1_201712057/_OLC1_P1_201712057.py | 1,054 | 3.828125 | 4 |
import tkinter
ventana = tkinter.Tk()
ventana.geometry("1000x600")
etiqueta = tkinter.Label(ventana, text= "Compi 1", bg = "red") # tambien puedo ponerle color al texto con otro parametro
#etiqueta.pack() el texto simpre esta arriba y centrado
etiqueta.pack(side=tkinter.BOTTOM) #aqui puedo mover el texto a cualquier... |
e814e424792696b9ba14fe4939d67ab00535493d | Gaurav-Pande/MultiThreading | /timerWithLocks.py | 1,295 | 4.46875 | 4 | # a basic timer program which outputs time after a certain interval of time
# Thread usually run along the main thread and shares the common memory
# Even though the execution of the main program ends, the thread continues to run
# here we define a lock and each thread acquire a lock and executes the thread and
# the ... |
c43634c29dd21a4fe185d8067a9ae02e63668d86 | has-g/HR | /testsample-3-datastructures.py | 895 | 3.71875 | 4 | userage = [44, 40, 9, 4]
print('family age = ' + str(userage)) # returns me full list as is
print('family age = ' + str(userage[0:])) # returns me range starting at 0 index until end since not
userage2 = userage.count(5)
print('list userage2 = ' + str(userage2))
userage.append(99)
userage3 = userage
print(userage3)
... |
5df55b289cfdcd8fdd341b2d73c618ff5a9c7bb7 | JaydedCompanion/AcadiaCompSci | /Year 1 - Semester 1/Lab #10/lab10_JuanCallejas_100143996.py | 1,251 | 3.953125 | 4 | #lab10_JuanCallejas_100143996.py
#By Juan Callejas
#COMP 1110L X1
#Instructor: Greg Lee
#QUESTION 1
def masterFunction (word1, word2, num):
#What's even the point of this??
numberChecker (word1, word2, num)
def numberChecker (word1, word2, num):
#Assignment spec indicates that nothing should... |
69492cfae3ea3054f2e29b8f6adce23f3d301654 | BrendonsDad/CSE-111 | /scene.py | 4,889 | 3.6875 | 4 | import tkinter as tk
import math
from random import *
import turtle
def main():
# The width and height of the scene window.
width = 800
height = 500
# Create the Tk root object.
root = tk.Tk()
root.geometry(f"{width}x{height}")
# Create a Frame object.
frame = tk.Frame(root)
frame... |
f6e34acb214ae2fbeabaea2921cddaa4ea5d18c7 | jrreap/StickWarsInSpace | /UI/Button.py | 1,882 | 3.5 | 4 | import pygame
from Scenes.Camera import Camera
pygame.init()
# Preset color presents to allow for quick colors to be set
WHITE = (255,255,255)
GREY = (200,200,200)
BLACK = (0,0,0)
# Main class that handles the creation of buttons. Also manages the tracking of if the button has been clicked
# and then calling the ca... |
1e5bad43366586ff2eebb05fb9ab1f082eeab589 | yiwenx1/Purchase-Analytics-YiwenXu | /src/purchase_analytics.py | 3,675 | 3.6875 | 4 | from functools import reduce
import sys
output_header = "department_id,number_of_orders,number_of_first_orders,percentage"
def map_func1(record):
"""
Map func for phase1. Map a line of raw record into [dept_id, 1, first_ordered] format.
:param record: string
:return: [dept_id (int), 1 (int value 1), ... |
18aaec9fc3a178fe4a9b7e4f4a89924848cab530 | austincreates/python_programming_3640 | /Assignment #1/drunkard_walk.py | 1,359 | 3.875 | 4 | import random
def drunk_walk(n):
total_ver = 0 #total vertical distance
total_hor = 0 # total horizontal distance
choices = []
north = "north"
south = "south"
east = "east"
west = "west"
for num in range(n + 1):
rand = random.random() * 100
#print (rand)
if rand <... |
2473d82c2b939a13afa8f29f123dd3db46e1fbb0 | LadyAnadelia/CS372 | /Project1/chatclient.py | 3,329 | 4.1875 | 4 | #!/usr/bin/env python3
"""This program is for the chat client. It is used so that a client can connect to the chat server.
My main refernce for this program was: https://docs.python.org/3/library/socket.html
Program: chatclient.py
Author: Rob Navarro
Class: CS372
The python socket module is used to handle most of the... |
fe752abcc6ebd5a3675563c6568c7894f934e94a | YanDavid123/myblog | /comment/__init__.py | 937 | 3.796875 | 4 | # import threading
# import time
# #
# # def tstart(arg):
# # time.sleep(0.5)
# # print("%s running...." % arg)
# #
# # if __name__ == '__main__':
# # t1 = threading.Thread(target=tstart, args=('This is thread 1',))
# # t2 = threading.Thread(target=tstart, args=('This is thread 2',))
# # t1.start()
... |
99a939a19d374b9e80905d68e4ffce776a360617 | vijonly/100_Days_of_Code | /Day7/main.py | 1,012 | 3.953125 | 4 | # main.py
"""
Hangman Game
main.py -- contains game logic.
"""
import random
import words
import art
word_list = words.word_list
stages = art.stages
logo = art.logo
choosen_word = random.choice(word_list)
print(logo)
lives = 6
display = []
for _ in range(len(choosen_word)):
display.append("_")
game_over = F... |
3a0eafa9ab349148052b4589d37b8e7d700ff8e3 | kirankalsi/python-exercises | /programs/functions_ex.py | 1,196 | 4.15625 | 4 | def grade_calculator(hwk_mark, ass_mark, final_mark):
if hwk_mark > 25 or ass_mark > 50 or final_mark > 100:
return False
if hwk_mark < 0 or ass_mark < 0 or final_mark < 0:
return False
avg_mark = (((hwk_mark/25) + (ass_mark/50) + (final_mark/100))/3)*100
return avg_mark
def grade_b... |
6a4464d7192fc731cad6e72de2bd3554fc54b37a | Baljeet97/prac_06 | /prac_06/guitar.py | 1,434 | 3.859375 | 4 | CURRENT_YEAR = 2018
VINTAGE = 50
class Guitar:
def __init__(self, name="", year=0, cost=0.0):
self.name = name
self.year = year
self.cost = cost
def __str__(self):
return "{} ({}) : ${:,.2f}".format(self.name, self.year, self.year)
def get_age(self):
return CURREN... |
27986259cdb3f65434033ae102c1dccc5c9497c6 | Geethanjali18-dot/TeluskoPractice2 | /33_FunctionArguments.py | 256 | 3.609375 | 4 | def update(x):
print(id(x))
x=8
print(id(x))
print("x ",x)
def update1(lst):
print(id(lst))
lst[1]=25
print(id(lst))
print('lst ',lst)
lst=[10,30,20]
update1(lst)
print(id(lst))
a=10
update(a)
print(id(a))
print("a ",a)
|
00069f1d8de0bb6527cc02ec1668eea4c6288c23 | pcwerk/jurassic | /analyze/crunch.py | 822 | 3.90625 | 4 | #!/usr/bin/env python
import sys
# create an empty table
data_table = dict()
# read in one line at a time from stdin
for line in sys.stdin:
src, dest, port = line.split() # break each line into three values
if data_table.has_key(port): # check if port exist in data_table
if not data_table[port].ha... |
5b7361f178c8bf03daa0c0139d048252cf2f844a | jayrshah98/ASE-HW1 | /src/hw6/COL.py | 324 | 3.515625 | 4 | from NUM import NUM
from SYM import SYM
class COL:
def __init__(self,n,s) -> None:
self.col = NUM(n, s) if s[0].isupper() else SYM(n, s)
self.isIgnored = self.col.txt.endswith("X")
self.isKlass = self.col.txt.endswith("!")
self.isGoal = self.col.txt[-1] in ["!", "+", "... |
d08f3be7f3d9ce8d3b665d540fb195d9da147ed1 | true-false-try/Python | /A_Byte_of_Python/tuple_()/tuple_tasks/playing_cards.py | 1,351 | 3.875 | 4 | """ Гральні карти мають 2 поля:
масть - піки, хрести, бубни, чирви та
значення - шість, сім, вісім, дев`ять, десять, валет, дама, король,
туз;
Скласти програму, яка перевіряє, чи "б’є" карта K1 карту K2 враховуючи те,
що масть KM є козирною.
"""
import random as rn
tpl_trump_... |
38fcff4961a02995e0c6493c2bf7429bde11f9e0 | troyygan/Crypto3 | /RSA/rsa.py | 1,910 | 3.625 | 4 | from rsa_ob import *
import commands
import os
from datetime import datetime, date, time
@profile
def func_rsa():
print "RSA Encryption-Decryption Started....."
before_time_enc = datetime.now()
r = RSA()
encrypt = r.encrypt
decrypt = r.decrypt
print "RSA Encrypter/ Decrypter"
##If you want to make the ... |
cac3842e8f393ab4bf735118266b6eec834dccac | hirosuzuki/atcoder-2020 | /hhkb2020/hhkb2020_a.py | 82 | 3.78125 | 4 | S = input()
T = input()
if S == "Y":
r = T.upper()
else:
r = T
print(r)
|
816c9fcefb17ee1263660c1b1087cb20c03ab2d0 | tmuweh/tutorial.py | /user.py | 861 | 4.15625 | 4 |
class User(object):
"""stores a user profile and describe user"""
def __init__(self, firs_name, last_name, **properties):
self.profile = {}
self.firs_name = firs_name
self.last_name = last_name
self.login_attempts = 0
for key, value in properties.items():
self.profile[key] = value
def describe_use... |
a280b455f70776dd0f9d6b6a603afe49b92f1290 | PLUTOLEARNS/computerprogramsreal | /patternwithoutnestedloop 04082020 $.py | 176 | 3.984375 | 4 | '''program that prints the following pattern without using any nested loop
$
$$
$$$
$$$$
$$$$$'''
st = '$'
pt = " "
for a in range (5):
pt += st
print (pt) |
b58020a10e3be09216eb6f417125ad247d27cf1d | maddo/learn | /python/ex3.py | 1,228 | 4.21875 | 4 | # Informs output that the coming statistics refer to chickens
print "I will now count my chickens:"
# Calculates and displays Hen count
print "Hens", 25.0 + 30 / 6
# Calculates and displays Rooster count
print "Roosters", 100.0 - 25 * 3 % 4
# Informs output that the coming stastics refer to eggs
print "Now I will cou... |
b7c36226af2c0a4efa443b8ea5ebd621b03f531a | jedzej/tietopythontraining-basic | /students/marta_herezo/lesson_02/if_then_else/bishop_moves.py | 526 | 4.03125 | 4 | # The program directed corrected or not corrected move of bishop
# on the chessboard.
# (x0, y0) - start position, (x, y) - new position on the chessboard.
print('Enter start posiotion for bishop, column x0: ')
x0 = int(input())
print('row y0: ')
y0 = int(input())
print('New position for bishop, column x: ')
x = int... |
4f17e9247ad8627cbdf6aa1aed2e0d46738807ad | Henrikmdk/pcc_4 | /main.py | 3,550 | 3.984375 | 4 | #4-1 looping through a list of pizzas
count = 1
pizzas = ["Meat lover", "Bianca", "Milan", "Quattro stagione", "Havaii", "Pronto"]
print("Our Pizzas")
for pizza in pizzas:
print(f"No {count} {pizza}")
count += 1
print("Happy hour every wednesday 3-4am\n")
#4-2 looping through a list of animals
dwelling_fish =[... |
9a558e4af9fae1aba7bf7af61b0493d4ea40ef0d | SharonNicG/Project-2018 | /data_visualisation/univariate_plots.py | 1,372 | 3.8125 | 4 | # Sharon Gibbons, 29-04-2018
# Visualisation of data analysis on Iris data set
# https://matplotlib.org/
# Load NumPy package
import numpy as np
# Load pandas package
import pandas as pd
# Load libraries for visualisation
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt
# Load csv data fi... |
e6b9386df26092712baa70018885440b223fedc6 | xinlongOB/python_docment | /飞机大战/plane_main.py | 3,624 | 3.609375 | 4 | # 导入pygame模块
import pygame
# 导入sprite的工具模块
from plane_sprites import *
class PlaneGame(object):
""" 飞机大战主游戏"""
def __init__(self):
print("游戏初始化")
# 创建游戏的窗口
self.screen = pygame.display.set_mode((SCREEN_RECT.size))
# 创建游戏的时钟
self.clock = pygame.time.Clock()
... |
2170f65c255838d05df0a984eaabaf4cf69e4db7 | zllion/ProjectEuler | /p042.py | 1,052 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 1 19:57:29 2020
@author: zhixia liu
"""
"""
Project Euler 42: Coded triangle numbers
The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter ... |
29d1c65a1555a0ba8c6eab5b46ba530f1b1549f2 | cshintov/python | /think-python/ch16.Class_n_Function/ex7a_doubleday.py | 1,208 | 4 | 4 | '''
exercise 16.7 Find the n_day of two persons (the day in which one is n times older than the other)
'''
from ex7_birthday import *
def younger(bda,bdb):
if bda < bdb:
return bdb
return bda
def n_day(bda,bdb,n):
s = younger(bda,bdb)
old = abs(bda - bdb)
old = old.days
if old % ... |
e601ece4c37397f07e4947e06cc25eb7c8afdd82 | redherring2141/Python_Study | /Python_200/Basic/ex_025.py | 324 | 4.40625 | 4 | # Ex025 - Understanding bitwise operators (&, |, ~, ^, >>, <<)
bit1 = 0x61
bit2 = 0x62
print(hex(bit1 & bit2)) # 0x60 is printed out.
print(hex(bit1 | bit2)) # 0x63 is printed out.
print(hex(bit1 ^ bit2)) # 0x3 is printed out.
print(hex(bit1 >> 1)) # 0x30 is printed out.
print(hex(bit1 << 2)) # 0x184 is printed ou... |
f40b7429b947f210fd73aa24b3015827823d7ca4 | cule/sphericalDZ | /utils/projection.py | 10,028 | 3.578125 | 4 | from abc import ABC, abstractmethod
import numpy as np
class AbstractProjector(ABC):
"""
Abstract class that represent a general projector
"""
def __init__(self):
super(AbstractProjector, self).__init__()
@abstractmethod
def project_point(self, points):
pass
@abstractmeth... |
17b8892edc73c2a344b36f7e61a40f01ac990cb9 | zkouba19/python | /stars.py | 416 | 3.703125 | 4 | def stars(arr):
for i in range(0, len(arr)):
star = "*" * arr[i]
print star
newarray = [5, 4, 3, 2, 1, 2, 3, 4, 5]
stars_show = stars(newarray)
def stars2(arr):
for i in range(0,len(arr)):
if(isinstance(arr[i], int) == True):
star = "*" * arr[i]
print star
else:
temp = arr[i][0]
letter = temp *... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.