blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2818b43c8741fa7e68c8e51f59b42952f116e965 | manishhedau/Python-Projects | /Tkinter/simple_form.py | 1,634 | 3.71875 | 4 | from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("Button object")
first_name = Label(root,text='First Name :')
first_name.grid(row=0,column=0)
first_name_entry = Entry(root,justify=CENTER)
first_name_entry.grid(row=0,column=1)
last_name = Label(root,text='Last Name :')
last_name.grid(row... |
3f3353508b485f99d7fc385a5472ef2c2fb0f5a2 | utshav2008/python_training | /random/csv.py | 406 | 3.6875 | 4 | import csv
dic = {"John": "john@example.com", "Mary": "mary@example.com"} #dictionary
download_dir = "numbers.csv" #where you want the file to be downloaded to
csv = open(download_dir, "w")
#"w" indicates that you're writing strings to the file
columnTitleRow = "minute,number_of_messages\n"
csv.write(columnTitleRow... |
96327a873468c716021dbdfde22e9e3e3f6cbc72 | Malixlocate/Single-Etudes | /Etude11/arithmatic.py | 1,799 | 3.703125 | 4 | import itertools
import shlex
import os
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-file', metavar='FILE', help='input a file using -file <filename>')
args = parser.parse_args()
targetFound = False
with open(args.file) as file:
inputs = []
count = 0
for line in file... |
7fbdcad8857a9615ce807ab15fce77c80e17f6d2 | conwayjj/AdventOfCode2020 | /day10/day10_2_bonus.py | 1,597 | 3.609375 | 4 | import time
def calculatePaths(array):
#Hack here because there are no two jumps in input
size = len(array)
if size == 1 or size == 2:
return 1
if size == 3:
return 2
if size == 4:
return 4
if size == 5:
return 7
print("LEN NOT SUPPORTED: ", size)
return 1
start = ti... |
068efaf28dfecdb4fbfea4a2df1b53c3c2c39f52 | jasongros619/Settlers-of-Catan | /roadclass.py | 2,497 | 3.625 | 4 |
from basic_functions import abxy
class Road(object):
def __init__(self,data):
self.id=data[0]
self.c1=(data[1],data[2]) #(a,b) of 1st corner
self.c2=(data[3],data[4]) #(a,b) of 2nd corner
self.p1=abxy( self.c1 ) #(x,y) of 1st corner
self.p2=abxy( self.c2 ) #(x,y... |
ff00ef2649206f827765554aabb779eb555c4b6c | akhilram/wisebite | /backend python/getItems.py | 4,208 | 3.953125 | 4 | import csv
import sys
import string
import re
complete_food_string = ""
transtable = {ord(c): " " for c in string.punctuation} # if c!= ','
stopwords = []
def buildStopWords(stopfile):
"""This function builds a stopword list from a stopwords file given as input.
stopwords list is kept global.
stopwords file... |
98f0bc25a75dd83f0fa03576fc6259abd97dd88b | pandiyan07/python_2.x_tutorial_for_beginners_and_intermediate | /samples/conceptual_samples/class/class_and_object_variables.py | 1,424 | 4.3125 | 4 | # this is a sample python script program which is created to demonstrate the nature of class and object variables
class robot:
"""represents the robot with a name."""
# this is a class variable which is created to count the number of robots.
population=0
def __init__(self,name):
"""initializes the data... |
8d48eb05e3ba95ea9a2818f1b4ac5729c39aa3e8 | AshTiwari/Python-Guide | /Basic Python/user_defined_functions.py | 1,157 | 4.09375 | 4 | #User Defined Functions in python
# Functions
#Syntax
'''
def funct_name (parameters):
statements
return (expression)
x = funct_name(parameter_value)
#x takes the value returned by function.
#If the function dosen't return any value the x will take value 'None'.
'''
def ... |
450bdab51ac97a1108e3d353a6073a83398eac64 | cain19811028/python-codility | /python_count_semiprimes.py | 2,384 | 4.28125 | 4 | import json
from math import sqrt
"""
Task:CountSemiprimes
Count the semiprime numbers in the given range [a..b]
------------------------------
A prime is a positive integer X that has exactly two distinct divisors: 1 and X.
The first few prime integers are 2, 3, 5, 7, 11 and 13.
A semiprime is a natural number that ... |
c5382550016a36833e93fa5add87b2e0f685dece | ArunkumarRamanan/CLRS-1 | /ProgrammingInterviewQuestions/4_Print2DArrayInSpiralOrder.py | 1,097 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 20 10:10:30 2016
@author: Rahul Patni
"""
# Print 2 D array in spiral order
def printSpiral(A, length, breadth):
currLength = length - 1
currBreadth = breadth - 1
row = 0
col = 0
offset = 0
for i in range(length * breadth):
track = i
... |
5e579db5383be32e820e762895822e3ba5c30b64 | Winni8/python-project | /py_workspace/test_case/继承/继承2.py | 615 | 3.515625 | 4 | # _*_ coding:utf-8 _*_
# @Author :cjj
# @time :2018/7/10 11:37
# @File :继承2.py
# @Software :PyCharm
class X(object):
def f(self):
print( 'x')
class A(X):
def f(self):
super(A, self).f()
print( 'a')
class B(X):
def f(self):
super(B, self).f()
print( 'b')
clas... |
9822e46b9a7c1193f221fcb33dade1e5bc75466a | sonwonrak92/dataStructure_algorithm | /python_03.py | 1,605 | 3.734375 | 4 | '''
### Python Algorithm Study ###
# author : laziness
# date : 2019/08/06
세 번째 과제
::이진탐색 구현하기::
최초의 값이 중간 값과 같으면 중간 값의 인덱스를 리턴한다
최초의 값이 중간인덱스 값 보다 작으면 처음값과 중간값의 사이값과 비교한다
여기서 중간인덱스를 다시 마지막 인덱스로 설정한다
최초의 값이 중간 값 보다 크면 중간값과 마지막값의 사이값과 비교한다 여기서 중간값은 다시 처음 인덱스가 된다
따라서 최초의 인덱스, 중간 인덱스 , 마지막 인덱스, 결과인덱스 변수가 필요하다
'''
... |
7f4ee3fd3ce06fb83f540ee60ba4245a2dca90f2 | louisbemberg/python_notes | /py4e/921-python_objects.py | 297 | 3.796875 | 4 | class Dog:
def __init__(self, breed, gender, age):
self.age = age
self.breed = breed
self.gender = gender
dog1 = Dog("border collie", 'female', 14)
print('A', dog1.age, 'year-old', dog1.gender, dog1.breed, '.')
# IMPORTANT
# in dog.age, the "." is the OBJECT LOOKUP OPERATOR :)
|
62089574045cca63d799d2b3103536bc2cdb5518 | ivan-samardzic/python-basics | /getting_input_from_users.py | 257 | 4.28125 | 4 | #input from user stored into variable
name = input("Enter your name: ")
print("Hello " + name + "!")
#getting name and age
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello " + name + "! You are " + age + " year old!") |
5dc6a0222a909d27eaa8ac2d661a5a64c8868485 | KeithLacey/Python_assignments | /StringsandList.py | 387 | 3.890625 | 4 |
words = "It's thanksgiving day. It's my birthday,too!"
print words.find("day")
print words.replace("day","month")
x = [2,54,-2,7,12,98]
print min(x)
print max(x)
x = ["hello",2,54,-2,7,12,98,"world"]
print x[0],x[len(x)-1]
x = [19,2,54,-2,7,12,98,32,10,-3,6]
x.sort()
print x
first = x[:len(x)/2]
print first
seco... |
92804a3d253460d13e39a7a8559247ea958dca24 | akjadon/HH | /Python/MachineLearning/Regression/02 - Multiple Linear Regression/MLR.py | 1,119 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 18 23:20:36 2018
@author: abdul
"""
# Multi Linear Regression
import numpy as np #for mathematical calculation
import matplotlib.pyplot as plt #for ploting nice chat and graph
import pandas as pd
dataset = pd.read_csv('50_Startups.csv')
X =... |
d6fe41bfe52fe7837609b3fe52b78ff0e2f9510d | b1ck0/python_coding_problems | /Search_Sort/merge_sort.py | 1,038 | 4.28125 | 4 | def merge_sort(array):
if len(array) > 1:
i = len(array) // 2
left = array[:i]
right = array[i:]
merge_sort(left) # sort left half
merge_sort(right) # sort right half
i, j, k = 0, 0, 0
# if both lists have the same length this will be the only while block... |
3f568df42291ce15c2ac3324f9c866185ad8eb5e | Pirci/leetcode | /problems/90. Subsets II/90.py | 1,067 | 3.75 | 4 | class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
"""Returns all possible subsets
Args:
nums (List[int]): integer array
Returns:
List[List[int]]: possible subsets output
Time Complexity:
n... |
4abc18571d4e2914a8b2729b5f0811af1de34b10 | HawkinYap/Leetcode | /leetcode9.py | 601 | 3.71875 | 4 | class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return (False)
len = 1
while int(x / len) >= 10:
len = int(len * 10)
while x > 0:
l = int(x / len)
r = int(x % 10... |
fb87caa57fbcdac4a8e95c05f71f2824c0c82f20 | grcninja/Small_Tasks | /LookUpDomainByIP.py | 2,317 | 4.1875 | 4 | '''
Language & Version: Python 3.4
This script allow the user to identify the path and file that holds a list of IP addresses
that they would like to look up the domain name for.
The user can also indicate where to save the file and what to name it.
'''
import csv
import datetime
import fileinput
import os
import soc... |
6988799c868dd544f4fc24ff3380f5f7d9482425 | DQder/WHN-Codefest-2020 | /code/Problem 10.py | 164 | 3.9375 | 4 | i = 0
Sum = 0
while i < 5:
i += 1
x = int(input("Enter a number:"))
Sum += x
ortalama = Sum / i
print("Girdiğiniz sayıların ortalaması: ", ortalama) |
074af21935d398f464fbb7b7a8f8be9800011271 | JoshsHiddenTrove/ChessAI | /ReactApp/python/Board.py | 848 | 3.796875 | 4 | from typing import List
import Pieces.Pieces as Pieces
class Board:
BackLine = ["R","K","B","Q","K","B","K","R"]
def __init__(self):
self.ChessBoard = [[None] * 8] * 8
self.GeneratePieces()
def getBoard(self):
return self.ChessBoard
def GeneratePieces(self):
... |
ccd652427fbc4bbf97ee89ec2711fe34015941be | agbarker/Cracking-the-Coding-Interview-Python | /ArraysAndStrings/URLify.py | 746 | 4.3125 | 4 | """Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string."""
"""Replacement in place is not possible in python as strings are immutable. Much of the input is... |
a06a2a8ecb4f485a11819ced8b9dec1e21677131 | MoutyWong/Python3-learning-Notes | /day01/day01_second.py | 264 | 3.796875 | 4 | # !/usr/bin/env python3
i = 100
while i > 0:
if i > 50:
print('This number greater than 50')
if i < 50:
print('This number less-than 50')
i -= 1
str = 'I\'m OK'
print (str)
print (r'\\\n\\')
print('''*
**
***''')
print(r'''r
rr
rrr''')
|
ea85ac3b7a019fdb6eaa7cfe77466e72ed6f8928 | jrmullen/cse233 | /problem7/problem7.py | 446 | 3.75 | 4 | __author__ = 'Jeremy'
import random
def main():
random_numbers = open('random_numbers.txt', 'w')
num_of_rands = int(input('How many random numbers should be written to the file?: '))
print('Numbers written: ')
for count in range (num_of_rands):
number = random.randint(1,500)
print(n... |
7cc8a68fea4bb57fab7550731b1ab183a408cb27 | Sugandha05/learn-python | /while_loop_list.py | 280 | 3.609375 | 4 | book = ['ram', 'shyam', 'su', 'mo']
page = 0
# while book is not finished (till 6)
# read(print) and update page number
# while condition is true do following
while page != 4:
# print(page!=4)
print(book[page])
page = page + 1
#print(book[page])
print(page!=4)
|
28546060b6b51e99c7e68f1bd01883f254e5ab84 | tockata/HackBulgaria | /exam/loss_or_profit.py | 513 | 3.53125 | 4 | def loss_or_profit(income, outcome):
total_income = 0
total_outcome = 0
for x in range(0, len(income)):
total_income += income[x]
for x in range(0, len(outcome)):
total_outcome += outcome[x]
result = total_income - total_outcome
if result > 0:
return ("+" + str(result)... |
734083d2e8bfe0160cc3c28eb80d19bc2c251b6d | Dyr-El/advent_of_code_2017 | /FredrikB-Python/day2/day2.py | 217 | 3.515625 | 4 | #!/usr/bin/env python
import re
def solver(data):
result = 0
f = open(data, 'r')
for line in f:
data = [int(x) for x in line.split()]
result += max(data) - min(data)
return result
print solver('input.txt') |
8257096c035180b699af17be48506b52b44eda21 | erpost/python-beginnings | /etc/shirt_order_basic.py | 647 | 4.03125 | 4 | sm_price = 6
med_price = 7
lg_price = 8
shirt_order = 0
size = input("What size shirt would you like: ")
quantity = input("How many shirts total: ")
if size.lower() == "s" or size.lower() == "small":
shirt_order = int(sm_price) * int(quantity)
print("Your total will be $", shirt_order)
elif size.lower() == "m... |
ff56084078ad7cc8a270b41bf433ac49e62eb9aa | mgbvox/davide_b | /proj3.py | 3,963 | 3.90625 | 4 | from person import Person
class DynasticDescent:
def __init__(self):
self.tree = dict()
self.ids = []
self.next_id = 1
def add(self):
name = str(input('What is the name of the human?'))
self.add_person(Person(name))
def add_person(self, person):
'''
... |
f8c8f59b94d81cc981bf589613fc350151a16abf | 786662216/backup-for-python2 | /练习/filter().py | 236 | 3.625 | 4 | #判断素数
def not_prime_num(n):#
if n == 1 :
return False
else:
for i in range(2,n):
if n % i == 0:
return True
return False
l = range(1,101)
print filter(not_prime_num,l)
|
33f761e75ad838ec23f2451085d345a476bbad79 | tmtrinesh/PythonBasics | /search.py | 283 | 3.59375 | 4 |
pos = -1
def search(list,n):
i= 0
while i< len(list):
if list[i] == n:
globals()['pos'] = i
return True
i = i+1
return False
list = [5,8,4,9,7,1]
n = 7
if search(list,n):
print("Found at",pos)
else:
print("Not found") |
ab72c074d1213cfe55b0c914fb75a01e2d0ee28e | frasertweedale/drill | /py/treespan.py | 531 | 3.546875 | 4 | class Tree:
def __init__(self, l, r):
self.l = l
self.r = r
def treespan(tree):
"""Return max span of tree assuming all links have weight of 1."""
if tree is None:
return (0, 0, 0)
lspan = 0
ldepth = 0
rspan = 0
rdepth = 0
if tree.l:
lspan, lldepth, lrde... |
81df55c66c7bcc6f400d6a7d66a79f0e65591935 | JoshuaShin/A01056181_1510_assignments | /A5/q09.py | 2,297 | 3.84375 | 4 | """
q09.py
A base conversion module.
"""
# Joshua Shin
# A01056181
# April 15th 2019
import doctest
import math
def base_conversion(original_base: int, original_number: int, destination_base: int) -> int:
"""
Convert original number in original base to destination base.
PRECONDITION original base mu... |
180a4959170d5d19711d385047b49299a95b619b | andrekorol/logica-programacao | /Python/particle.py | 4,602 | 3.984375 | 4 | from __future__ import annotations
from typing import List
class Vec:
"""Vetor com componentes x e y."""
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def plus(self, other: Vec):
"""Soma um vetor com o outro."""
return Vec(self.x + other.x, self.y + other... |
09437bd4d05ecdbc03d4659e36ceeec9cb3de9f1 | gvsharshavardhan/python_go4guru | /string_case.py | 777 | 3.84375 | 4 | currntamt = 500
flag = True
trail = 0
while flag:
trail += 1
username = input("please enter your user name:")
password = input("please enter your password:")
if(username.lower() == "harsha" and password == "password123"):
withdrawamt = int(input("please enter some amt to withdraw:"))
i... |
6ccd1c0951b093b8f03c4d7a12d86a5467e2ed89 | sujivennapusa/python-program | /w3day13task/myfile.py | 285 | 3.765625 | 4 | myfile=open('demo.txt','a+')
""" myfile.write("hello world") """
i=input("enter the name:")
myfile.write(i+"\n")
print(myfile.tell())
myfile.seek(0)
""" myfile.write("karnataka is a state in india") """
""" myfile=open('demo.txt','r') """
x=myfile.read()
print(str(x))
myfile.close() |
546feec896e27325096c592ab06cb55495b50685 | olekmali/eTCP_Python | /20_intro_to_python/205_more_on_lists.py | 975 | 4.4375 | 4 | # More on lists
# pointer/alias to existing list demonstrated
days_of_the_week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
print( days_of_the_week )
work_days = days_of_the_week
work_days.remove('Saturday')
work_days.remove('Sunday')
print( work_days )
print( days_of_the_w... |
a16f13ee1dce613701a044f8ed5684ad997dc2af | Lempi-sudo/ParserDocument | /emailParser(3).py | 1,002 | 3.75 | 4 | #Создать текстовый документ содержащий список адресов электронных почт,
# их можно придумать самому. Количество не менее 50.
#Записать в выходной файл список доменов электронных почт из входного файла.
import re
def ReadFile(filename):
with open(filename,"r", encoding="utf8") as myfile:
text = myfile.rea... |
92ff27214b5985b003d8f2d3d5bd8dc5fb7357cd | gitStanden/2DAlienInvasion | /alienInvasion/ship.py | 1,550 | 3.90625 | 4 | import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""A class to manage the ship."""
def __init__(self, aiGame):
"""Initilise the ship and set its starting position."""
super().__init__()
self.screen = aiGame.screen
self.screenRect = aiGame.screen.get_rect()
... |
700d89e364197deaeff90928068b39090743f912 | BioroboticsLab/bb_behavior | /bb_behavior/plot/background.py | 7,005 | 3.515625 | 4 | import cv2
import numba
import numpy as np
def generate_median_images(gen, N=10):
""" Takes an image generator and yields a median image of the last N images every N images.
Arguments:
gen: generator
A generator that yields greyscale images.
N: int
A median image is... |
1d549c2f3ae68c869cf8b23bcbbba3244b360bfb | arijort/prep | /ctci/isunique.py | 729 | 4.28125 | 4 | #!/usr/bin/env python
import unittest
def isunique(s):
""" Function to determine whether a given string has unique values. """
# 1 use a set to keep track, iterate
st = set()
for c in s:
if c in st:
return False
else:
st.add(c)
return True
class UniqueTest(unittest.TestCase):
""" Test... |
afd8c6f155739c12ad00518c0d2c454dddfdd097 | shukyp/Python-Lang | /oo_derived_class.py | 5,790 | 3.5625 | 4 |
#===========================================================================
# BaseClass Module
#===========================================================================
"""
#BaseClass - Shows How a calss looks loke
#
# Author: Shuky Persky
#
"""
from oo_base_class import *
#===========... |
5288c0a123723effa90b80b32d9d1b53b08d8879 | huffmp2/python | /ticketprompt.py | 523 | 4.125 | 4 | prompt= input("How old are you?")
prompt = int(prompt)
if prompt <= 3:
print ("Your ticket is free!")
elif prompt <= 12:
print ("Your ticket is $10!")
else:
print ("Your ticket is $15!")
while prompt < 12:
prompt= input ("Children must be accompanied by an adult. Please enter your age.")
... |
25cf02674109d8553fa243d7e57af5ca7b6e6a4c | gustavoddainezi/Exercicios-URI-Online-Judge | /Python/1133.py | 190 | 3.96875 | 4 | # -*- coding: utf-8 -*-
x = int(input())
y = int(input())
aux = x
if x > y:
x = y
y = aux
while(x < y):
x += 1
if(x % 5 == 2 or x % 5 == 3 and x != y):
print(x) |
10eee9175b724f1666808915cbd3ae7035869ede | diceitoga/regularW3PythonExercise | /data_analytics_sentdex1.py | 648 | 3.765625 | 4 | #sentdex data analytics.
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
'''
simple line plot....you will be using pyplot all of the time.
import matplotlib.pyplot as plt is always the convention
'''
#plt.plot(x,y) when you plot, you plot [x,y] where both x =[] and y=[] with list... |
6b917e485dc27ed71ce91600675c1c2bb61dc13d | p-lots/codewars | /7-kyu/rearrange-number-to-get-its-maximum/python/solution.py | 177 | 3.53125 | 4 | def max_redigit(num):
if not 99 < num < 1000:
return None
result = int(''.join(sorted(str(num), reverse=True)))
return result if result >= num else None |
096b96d557ccbdadb99c367e1553fcad66ff4fdd | deemcher/homework2 | /date_and_time.py | 1,234 | 4.53125 | 5 | """
Домашнее задание №2
Дата и время
* Напечатайте в консоль даты: вчера, сегодня, месяц назад
* Превратите строку "01/01/17 12:10:03.234567" в объект datetime
"""
from datetime import date, datetime, timedelta
def print_days():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В н... |
5920eb6aa694fde56eb4a5cc1655547f624a451d | julianalvarezcaro/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 249 | 4.03125 | 4 | #!/usr/bin/python3
"""MyList class module"""
class MyList(list):
"""
MyList class which inherits from list
"""
def print_sorted(self):
"""Prints a list in ascending order without altering it"""
print(sorted(self))
|
c192177295a380d324e4822d27d4b2907f044900 | joshcabral/FlexTracker | /database/row.py | 2,696 | 3.875 | 4 | class row:
"""A base row class for holding the information of a row before it is
inserted, updated or deleted from a table.
Each of these classes can be treated as a builder.
A good way to create a row would be like this:
r = users_row().set_user_id("_____").set_password("___") and so on.
Eac... |
a8b3d60080604ec5c04e16e37138eb2ef10fa9ab | th3c0d3br34ker/File-Splitter | /fileSplitCore.py | 2,192 | 3.8125 | 4 | from traceback import print_exc
from os import getcwd, remove, chdir, listdir, mkdir
from os.path import basename
def fileJoiner(folder):
"""
This function joins all the files in the input folder and outputs a single file.
Args:
folder: path of the folder which contains the splitted f... |
08776a9a7d1a3edaade60ef2989758495c20cc02 | Moly-malibu/cs-module-project-algorithms | /single_number/single_number.py | 683 | 3.890625 | 4 | '''
Input: a List of integers where every int except one shows up twice
Returns: an integer
'''
def single_number(arr):
no_dups = []
for x in arr:
if x not in no_dups:
no_dups.append(x) #add
else:
no_dups.remove(x)
return no_dups[0]
def single_number_best(nums):
cou... |
e533f12a91a6bcbeac43c136174d419f6389ad43 | neilshah101/daily-practise | /weekly_journal/week_1/day5/live class practise/bubble-sort.py | 674 | 3.921875 | 4 | numbers = [2,1,45,67,89,4,5,7,9,100]
def bubble_sort_ascending(alist):
for i in range(len(alist)-1 , 0 , -1):
for j in range(i):
if alist[j] >alist[j+1]:
temp = alist[j]
alist[j] = alist[j+1]
alist[j+1] = temp
return alist
print (bubble_sort_... |
69ce3f8d06145c416737a163e7947bdc93c19a99 | rheaganguli/stratagem | /level1.py | 4,555 | 3.859375 | 4 | import turtle
import math
import random
import os
import sys
from game_constants import const
wn = turtle.Screen()
wn.bgcolor(const.COLOR_WHITE)
wn.addshape("investigation.gif")
wn.update()
wn.setup(const.DIM_1000,const.DIM_1000)
wn.tracer(0)
questions = []
CURR_NUMB = 0
Y_OFFSET = 0
SPACE = 24
instructionsShown =... |
814eac6f47fe61928c585589f7de698b5aa8159a | MacHu-GWU/rolex-project | /tests/test_std_datetime_flaw.py | 1,347 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Limitation of standard datetime library.
**中文文档**
- 在Python27中, datetime类没有实现 ``datetime.timestamp()`` 方法
- 在Python3中, 对于1970年之前的时间无法获得timestamp
- 在Python3中, datetime.fromtimestamp(timestamp) 不支持负值
"""
from __future__ import print_function
from datetime import datetime, date
def dateti... |
0a4313082e817159e85e477efa2ac2556a5f8984 | calebl37/tic-tac-toe-python | /tic-tac-toe-simulator.py | 2,190 | 4 | 4 | board=[]
import math
import random
def print_board(sidelength):
row = ''
for i in range(0,(sidelength*sidelength)):
row += "| " + board[i] + " "
if (i+1) % sidelength == 0:
print("+---"*sidelength + "+")
print(row + "|")
row = ''
print("+---"*sidelength + "+")
d... |
0cdcceb766d3f864bf89fe5cac2e4c76e91e655c | bksahu/dsa | /dsa/patterns/binary_search/rotation_count.py | 1,026 | 3.8125 | 4 | """
Given an array of numbers which is sorted in ascending order and is rotated
‘k’ times around a pivot, find ‘k’.
You can assume that the array does not have any duplicates.
Input: [10, 15, 1, 3, 8]
Output: 2
Explanation: The array has been rotated 2 times.
Input: [4, 5, 7, 9, 10, -1, 2]
Output: 5
Explanation: Th... |
f44b41800b324da9cfb47544a2d84f5634ba739c | Jose0Cicero1Ribeiro0Junior/Curso_em_Videos | /Python_3/Modulo 2/3_Repetições em Python (while)/Exercício_064_Tratando_vários_valores_v1.0_v1.py | 568 | 4 | 4 | #Exercício Python 64: Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag).
núm = cont = soma = 0
núm = int(input('... |
f27a459b02f64f1dce5157dbefe219ff5dc0cc3a | Vivekagent47/HackerRank | /Problem Solving/40.py | 586 | 3.5 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the kaprekarNumbers function below.
def kaprekarNumbers(p, q):
result = []
for i in range(p, q + 1):
x = str(int(pow(i, 2)))
l = x[0:int(len(x) / 2)] if x[0:int(len(x) / 2)] else 0
r = x[int(len(x) / 2):... |
6ad5172e4f82e192d75b5921c1901fd7b0d66990 | KurinchiMalar/DataStructures | /Sorting/BubbleSortOrig.py | 1,113 | 3.6875 | 4 | def swap(Ar,x,y):
temp = Ar[x]
Ar[x] = Ar[y]
Ar[y] = temp
return Ar
def do_bubblesort(Ar): #O(n*n)
count = 0;
for i in range(0,len(Ar)):
for k in range(len(Ar)-1,i,-1):
#if k == 0: #when k = 0 ; Ar[0] and Ar[-1] will be compared
# break
if Ar[k]... |
92ce4da5ccfd4bb5492ec4115538abb13a504992 | GINK03/yukicoder-solvers | /0841.py | 183 | 3.84375 | 4 | s1, s2 = input().split()
if len([x for x in [s1, s2] if x in {'Sat', 'Sun'}]) == 2:
print('8/33')
elif len({s1} & {'Sat', 'Sun'}) == 1:
print('8/32')
else:
print('8/31')
|
2a7fb47c3ff3894d743789692304be8413e0ff62 | slabykonrad/basis-of-writing-scripts | /task8_v2.py | 551 | 3.734375 | 4 | #!/usr/bin/python3
def chooseElementsByCriterium(stud_list,kryterium):
listOfStudents=[]
for item in stud_list:
if float(item["grade"]) == float(kryterium) :
listOfStudents.append(item)
return listOfStudents
def readFromFile(name):
studentList=[]
with open(name) as fin:
for line in fin:
line=line.split... |
25c3ca3c1c65e30c86974644efb173dcbe3338a8 | JoshMez/Python_Intro | /Functions/Default_Values.py | 777 | 3.75 | 4 | #When you write a function you can assign a default value to a parameter.
#
#
#Dont think of think of the default value of being set in stone.
#It will only be used when you have not see anything else.
############################################################
#
def Charecter(charecters, studio='Marvel' ):
"""See... |
871ae0fafa18d35475676f2ea2e25cbdae4c3dac | jasonphx1/python_courses | /ProgramWiz_Tutorials/calendar_display/display_calendar.py | 166 | 3.75 | 4 | #!/usr/bin/env python3
#URL: https://www.programiz.com/python-programming/examples/display-calendar
import calendar
yy = 2014
mm = 11
print(calendar.month(yy, mm))
|
c94fc4c14e2c387cbe74a68a2930275d5746747e | Haker3310/domashka | /2020/December/12.12.2020/_1.py | 717 | 3.734375 | 4 | import random
class Stack:
def __init__(self):
self._stack = []
def push(self, x):
self._stack.append(x)
def pop(self):
try:
return self._stack.pop(0)
except IndexError:
return "Очередь пуста."
def peek(self):
try:
return se... |
2ffd1e40ca982e6247860af85e7363fbc6d1d8d7 | sujasriman/guvi | /code/prog4.py | 107 | 3.875 | 4 | a=input()
b=ord(a)
if((b>=97 and b<=122) or (b>=65 and b<=90)):
print("Alphabet")
else:
print("No")
|
33ee772b20cd5c7491d1f45c2cc0f797de006cb3 | stevalang/Data-Science-Lessons | /Pandas/pandas_group_challenge.py | 1,358 | 4.1875 | 4 | import pandas as pd
import numpy as np
grocery = pd.DataFrame({'category':['produce', 'produce', 'meat',
'meat', 'meat', 'cheese', 'cheese'],
'item':['celery', 'apple', 'ham', 'turkey', 'lamb',
'cheddar', 'brie'],
... |
6fb6689d4a03122d6013f244fe7647d307042091 | amberno1111/Data_Structure_and_Algorithm | /LeetCode/Python/Add_Strings.py | 897 | 3.890625 | 4 | # Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.
# Note:
# 1. The length of both num1 and num2 is < 5100
# 2. Both num1 and num2 contains only digits 0-9
# 3. Both num1 and num2 does not contain any leading zero
# 4. You must not use any built-in Biginteger ... |
53e85eb6f62e975ecc8d16df928439b4c3d1701b | Vincent105/python | /04_The_Path_of_Python/11_function/0113_filter.py | 265 | 3.734375 | 4 | def oddfn(x):
return x if (x % 2 == 1) else None
mylist = [5, 10, 15, 20, 25, 30]
'''
filter_object = filter(oddfn, mylist)
oddlist = [item for item in filter_object]
print(oddlist)
'''
oddlist = list(filter(lambda x: ( x % 2 == 1), mylist))
print(oddlist)
|
7a0907e119535fea487f0fffbf6283a9826e5ed5 | nickest14/Leetcode-python | /python/medium/Solution_19.py | 795 | 3.953125 | 4 | # 19. Remove Nth Node From End of List
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
... |
aca83edb832a20f2c62db41f2c0bcc47b0f79cea | Roberto1987/ml_for_trading | /test/test_scipy_optimizer.py | 685 | 3.515625 | 4 | import scipy.optimize as opt
import numpy as np
import matplotlib.pyplot as plt
import pandas as p
def f(X):
Y = (X - 1.5)**2 + 0.5
print('X = {}, Y = {}'.format(X, Y))
return Y
def test_run():
Xguess = 0.0
min_result = opt.minimize(f, Xguess, method='SLSQP', options={'disp': True}... |
5b882487a563eed6ad631dd117bc721aa595fd94 | Djusk8/CodeWars | /8 kyu/Convert a Boolean to a String.py | 633 | 4.28125 | 4 | # ------------ KATA DESCRIPTION ------------
"""
https://www.codewars.com/kata/551b4501ac0447318f0009cd
8 kyu - Convert a Boolean to a String
Implement a function which convert the given boolean value into its string representation.
"""
# --------------- SOLUTION ---------------
import codewars_test as test
boo... |
c3ef38fcbe37d3c8512f2d510d26ec6b1b4a0779 | nsshayan/Python | /Learning/Network_process_WA/Day1/july24/requests/weather_report.py | 1,308 | 3.9375 | 4 | """
A simple program to fetch weather report for a city
(defaults to 'Bengaluru') using OpenWeatherMap API
"""
API_KEY = "932c152d6ff8d185bfdd9d2a5f8e33e4"
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
Output = """
Location: {}
Description: {}
Current temperature: {}\u00B0 Celsius
Mi... |
16ac6e5969d58e267ffc2815b787e12a86d10f74 | VinuthnaGummadi/Python | /PhytonProject/Assignment1/Source/Lab1/Assignment1/RectanglePerimeter.py | 1,007 | 4.53125 | 5 | # This program displays the perimeter of a rectangle
#Take input from user
length = input("Enter Length:")
breadth = input("Enter Breadth:")
perimeter = 0
# Check if entered values are not null
if(length!="" and breadth!=""):
# Exception if entered value if not int.
# This block is executed when the entered num... |
0e9ce365b22995f54b0ed4656e38d7f1dd5d8f99 | michaelwayman/python-genetic | /genetic/evolvable.py | 2,248 | 4.3125 | 4 | from abc import ABCMeta, abstractmethod
class Evolvable(object):
"""Abstract Base Class to create "evolvable" objects
An `Evolvable` represents an object that has a specific set of "genes" and "alleles".
A "gene" represents a broader idea, like "hair color", whereas an "allele" is a particular
mutati... |
81927bb8b58c77813454e32aa6cc7d02de90e9ff | jamesljeffrey1995/DevOpsPython | /Challengeoftheday/countVowels.py | 183 | 3.640625 | 4 |
def countVowelsCalc(word):
vowels = "aeiou"
count = 0
for i in range(len(word)):
for e in range(len(vowels)):
if vowels[e] == word[i].lower():
count += 1
return count
|
0f6eb066777d946bfc24c9ad49a1550f82ab0ade | taras193/pythonhomework | /homework_06_05_2019_task_2.py | 442 | 3.71875 | 4 | #1 multiplying
# a="7271"
# first_digit=int(a[:1])
# second_digit=int(a[1:-2])
# third_digit=int(a[2:-1])
# four_digit=int(a[3:])
# multiplying=first_digit*second_digit*third_digit*four_digit
# print (multiplying)
# #2 reverse
# a_reversed=a[::-1]
# print (a_reversed)
#3 sorting
# list=[first_digit,second_digit,third... |
cd50e5778232127dbe8dc47e36f2b3ea66002c48 | raadxrahman/CSE423-COMPUTER-GRAPHICS | /Theory/MidpointLineAlgorithm.py | 735 | 4.1875 | 4 | #Midpoint Line Algorithm
def midpointline(x0,y0,x1,y1):
dx = x1 - x0
dy = y1 - y0
d_init = (2*dy) - dx
d = d_init
while x0!=x1 and y0!= y1:
print(x0,y0)
if d > 0:
x0 += 1
y0 += 1
d += 2*(dy - dx)
else:
x0 += 1
d +=... |
2452f2ac0ccceb1cdb02880202bb70918eba9f03 | dumalang/python-cheatsheet | /1.5.classes.py | 622 | 3.921875 | 4 | class myClass():
def method1(self):
print("myClass method 1")
def method2(self, someString):
print("myClass method 2 " + someString)
def method3(self, someString=""):
print("myClass method 3 " + someString)
class childClass(myClass):
def method1(self):
myClass.method1... |
e129f04af242760693543ecb5aae02755e03afe4 | SteveChristian70/Projects | /MortgageCalc.py | 1,374 | 4.3125 | 4 | #Mortgage calculator with additional payments
# ask for loan amount
amount = int(input("Please enter the loan amount you are seeking without a comma: " ))
# annual percent interest
percInterest = float(input("What percent interest rate will the loan be at? " ))
# calculating monthly interest rate
monthlyInterest = ... |
3b2ad85b9bd9cf1a37948c8b939756924a7f1085 | sashank-kasinadhuni/CodeEvalSolutions | /Easy_Lowest_Unique.py | 748 | 3.578125 | 4 | import argparse
def Lowest_Unique():
parser = argparse.ArgumentParser()
parser.add_argument("filename")
args = parser.parse_args()
with open(args.filename) as f:
for line in f:
line = line.rstrip('\n')
line = [int(i) for i in line.split()]
counts = dict()
for... |
e2df98b9183f8cd028a563fdcee6ead253e6f67e | orel1108/hackerrank | /practice/algorithms/implementation/the_grid_search/the_grid_search.py | 959 | 3.65625 | 4 | #!/bin/python
def contains(grid, pattern, row, col):
for ROW in range(len(pattern)):
for COL in range(len(pattern[0])):
x = ROW + row
y = COL + col
if (x >= len(grid)) or (y >= len(grid[0])):
return False
if grid[x][y] != pattern[ROW][COL]:
... |
d62ecfc1e4168f6f706cf8bd26d998314e3a48e1 | Tmk10/exercism.io | /secret-handshake/secret_handshake.py | 1,115 | 3.5 | 4 | def handshake(code):
result = []
secret = {0: "wink", 1: "double blink", 2: "close your eyes", 3: "jump"} # mapping gestures to positions in string
position = list(enumerate(bin(code)[-1:1:-1])) # cutting "0b" and enumerate bin numbers with place in string
for flag in position:
if flag[0] == 4... |
32c905b111ced7765fa029a09b62dc51e0a2c24c | v1v3k/DecisionTree | /tree_r.py | 7,803 | 3.59375 | 4 | import pandas as pd
import math
import sys
import numpy as np
# <codecell>
import sys
data_file_loc, = sys.argv[1:]
# This piece of code reads the csv file as a table
data_set = pd.DataFrame.from_csv(data_file_loc, sep='\t')
data_set.reset_index(inplace=True)
# <codecell>
# Create three sets of columns, integer,... |
461fe2de6f91d53a02bf642e3a3d23847551a051 | el-mat/ectools | /algorithm.py | 1,205 | 3.984375 | 4 | import sys
def binarySearch(inlist, cmp_func, first=0, last=None):
'''Returns index of first item that cmp_func returns 0.
None if can't be found
cmp_func is < 0 if the value you are looking for is
less than what is passed to cmp_func by this function.
> 0 if it is more, 0 if equal.
'''
la... |
2aefec1431dfbfd2f8be2646ce6c415da9139001 | nberger62/python-udemy-bootcamp | /Built_In_Functions/filter.py | 462 | 3.90625 | 4 | #filter : Returns filter objects which can be converted into other iterables
#The object contains only the values that return true to the lambda
#evens = list(filter(lambda x: x % 2 == , 1))
#evens # 2, 4
#using filters and maps
[user for user in users if not user["tweets"]]
usernames = list(map(lambda user: user["u... |
3bd13e62b56fb06c8b710b33e5c85b6e31c40d2a | zxpgo/Python | /069test.py | 404 | 3.5625 | 4 | from tkinter import *
root = Tk()
text= Text(root, width=30, height=30)
text.pack()
text.insert(INSERT,"I Love\n")
text.insert(END, 'Fish.com!')
#插入按钮
#插入图片
photo = PhotoImage(file="bg.gif")
def show():
text.image_create(END,image=photo)
b1 = Button(text, text='点我点我', command=show)
... |
92d3852c59b4d161c7373507bdc64d5f028f8d99 | elsandkls/SNHU_IT140_itty_bitties | /dynamic.py | 592 | 3.5625 | 4 | # Get our arguments from the command line
import sys
A= int(sys.argv[1])
B= int(sys.argv[2])
# Write your code below
myList = []
myString = ""
# We pass in 2 numbers, A and B.
# You should create a list with A rows and B columns.
# You should then populate each cell like this
# R0C0, R0C1, R0C2 etc.
for i in range... |
49381ec0ae62ca673bcb977b7cde9e8ee421afa4 | ramalho/propython | /fundamentos/execucao.py | 1,103 | 3.578125 | 4 | import sys
import atexit
print '-> 1 inicio'
def funcaoA():
print '-> 6 funcao A'
return 'resultado A'
def funcaoB():
print '-> 8 funcao B'
def funcaoC():
print '-> 11 funcao C'
return funcaoC
funcaoD = lambda:sys.stdout.write('-> 12 funcao D\n')
def funcaoE():
print '... |
8023eeb5fdc2cefdd2a9c75cffe5a95c8a3a62fc | Kirktopode/Python-Homework | /LearnProgram3.0.py | 203 | 3.53125 | 4 | def birthday(child):
print "Happy birthday to you, happy birthday to you, happy birthday, dear", child + ", happy birthday to you!"
person = raw_input("Who is the birthday child? ")
birthday(person)
|
1c088281b1968db3b11d3d68a23597282bdb0a9a | roberg11/is-206-2013 | /Assignment 2/ex14.py | 1,053 | 4.03125 | 4 |
from sys import argv
script, user_name, country = argv
prompt = 'Ummm... '
print "Hi %s, I'm the %s script, and I will take you to %s." % (user_name, script, country)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
print "Where do you live %s" % user_nam... |
d982313da041492dff6375549996a795cc910d32 | alexander-colaneri/python | /studies/curso_em_video/ex009-tabuada.py | 1,497 | 4.28125 | 4 | # Nº 9 - Tabuada
# Descrição: Faça um programa que leia um número Inteiro qualquer e mostre na tela a
# sua tabuada.
class CalculadoraDeTabuada():
'''Calcula um número indicado pelo usuário multiplicado de 1 a 10.'''
def __init__(self):
self.numero = 0
self.resultados = []
def iniciar(self... |
b80ad2a23f283f13c94e85d16c363748dbf173d3 | kenwoov/PlayLeetCode | /Algorithms/Medium/1574. Shortest Subarray to be Removed to Make Array Sorted/answer.py | 622 | 3.5 | 4 | from typing import List
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
N = len(arr)
j = N - 1
while j > 0 and arr[j-1] <= arr[j]:
j -= 1
if j == 0:
return 0
res = j
for i in range(N):
if i > 0 and a... |
5526347bc49ea232d34d2dffbdcb8596479f891f | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Fundamentals/06_OOP/demo.py | 686 | 3.71875 | 4 | class Animal:
def __init__(self, command, name, food_limit, location):
self.name = name
self.food_limit = food_limit
self.location = location
self.command = command
def feed(self):
pass
animals = []
# Add:Bonie:3490:RiverArea
print(animal.name)
print(animal.locati... |
a30eea690236389d1f7f9d3f531c395e7af6f005 | happyssun96/baekjoon | /배열/4344_평균은넘겠지.py | 277 | 3.78125 | 4 | N = int(input())
for _ in range(N):
scores = list(map(int, input().split()))
avg = sum(scores[1:]) / scores[0]
count = 0
for i in scores[1:]:
if i > avg:
count += 1
percent = (count / scores[0]) * 100
print('%.3f' %percent + '%')
|
2ed3be2792812023d6a59ec88fbb29bf3e6ad5d4 | Programmer-Admin/binarysearch-editorials | /Level Order Traversal.py | 440 | 3.859375 | 4 | """
Level Order Traversal
Simplest form of breadth-first search. Use a double-ended queue to do popleft() in constant time.
"""
from collections import deque
class Solution:
def solve(self, root):
ans=[]
q=deque([root])
while q:
node = q.popleft()
ans.append(node.val... |
5700c74126ecd0f198960c9a6c0315a6e28fe5ed | zzz686970/leetcode-2018 | /744_nextGreatestLetter.py | 700 | 3.609375 | 4 | def nextGreatestLetter(letters, target):
if not letters: return ''
for letter in letters:
if letter > target: return letter
return letters[0]
def nextGreatestLetter(letters, target):
l, r = 0, len(letters)
while l < r:
mid = (l + r) // 2
if letters[mid] > target:
r = mid
elif letters[mid] <= target:
... |
7fff49761051d9ad84bae2b16bdd8987d1c59c33 | aelzeiny/WhenItRains | /sprites/apple.py | 1,086 | 3.71875 | 4 | import pygame
from sprites.anim import Animation
WIDTH = 32
HEIGHT = 32
class Apple(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.x = x
self.y = y
self.animation = self._load_anim()
def update(self, dt: float):
"""
This function is... |
5b08942f3d98150706fda1d3ace5ed36291e713f | nguyenngochuy91/companyQuestions | /facebook/phoneScreen/cleanRoom.py | 4,622 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 20 11:48:03 2019
@author: huyn
"""
#489. Robot Room Cleaner
#Given a robot cleaner in a room modeled as a grid.
#
#Each cell in the grid can be empty or blocked.
#
#The robot cleaner with 4 given APIs can move forward, turn left or turn right. Each turn it made is 90 deg... |
ffe524518f6b27828767c8e0f4da7bf6d29acf18 | janeon/automatedLabHelper | /testFiles/primes/primes37.py | 775 | 3.90625 | 4 |
def main() :
print()
n=eval(input("How many prime numbers would you like? "))
print()
i=1
PRIME_CNT=0
TWIN=0
def isPrime(x) :
i=1
if x<=1 :
return False
elif x==2 :
return True
else :
while i<x-1 :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.