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 |
|---|---|---|---|---|---|---|
d220677d5a67161d1d6234f5e4ea0109d065eaf0 | srac1777/learnPython | /Codecademy-Basic/cA_loops_adv.py | 1,426 | 3.859375 | 4 | #Write your function here
def larger_sum(lst1, lst2):
sum1 = cal_sum(lst1)
sum2 = cal_sum(lst2)
if sum1 >= sum2:
return lst1
else:
return lst2
def cal_sum(lst):
count = 0
for item in lst:
count += item
return count
#Uncomment the line below when your function is done
print(larger_sum([1, 9,... |
bb9ade0c929e974510bbaa4e556513aa9bf196b0 | srac1777/learnPython | /Algos/merge.py | 507 | 3.78125 | 4 | def merge(list1, list2):
i, j = 0, 0
res = []
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
res.append(list1[i])
i += 1
else:
res.append(list2[j])
j += 1
while i < len(list1):
res.append(list1[i])
... |
e1c8a440c3c24340a3510d586f58d25166a390c1 | wzgdavid/myCoding | /2015and_older/_201410and__older/cards/utils.py | 2,563 | 3.71875 | 4 | # encoding: utf-8
from __future__ import division # python 3 不用
import unittest
from collections import Counter
from math import factorial as fa
def one_pair(lst):
'''
list中有且仅有两个元素是相同,返回True
'''
return only_n_same(lst, 2)
def only_n_same(lst, n):
'''
list中有且仅有n个元素是相同,其他各元素都不相同,返回True
'... |
f98e44f3e50bffb659780d14473226c82bb96755 | Whitie/AdventOfCode | /2019/Day_01/day1p1.py | 375 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
INPUT_FILE = 'input.txt'
def main():
with open('input.txt', 'r') as fp:
modules = [int(line) for line in fp if line.strip()]
print(modules, len(modules))
tmp = []
for mod in modules:
tmp.append(mod // 3 - 2)
print(tmp, len(tmp))
p... |
a9910e9427fc5119d0e21bb020fc07285d137ad1 | Whitie/AdventOfCode | /2020/06/day_06_02.py | 785 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pathlib import Path
PATH = Path(__file__).parent.resolve()
INPUT = PATH / 'input.txt'
TEST = """\
abc
a
b
c
ab
ac
a
a
a
a
b
"""
def read_input(filepath):
with filepath.open() as fp:
return fp.read()
def get_groups(raw_input):
data = raw_input... |
7c85da058a5aa5c1d94dd86ca3af57df8e27c98f | Whitie/AdventOfCode | /2020/18/day_18.py | 1,691 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from pathlib import Path
PATH = Path(__file__).parent.resolve()
INPUT = PATH / 'input.txt'
TEST = """
1 + 2 * 3 + 4 * 5 + 6
1 + (2 * 3) + (4 * (5 + 6))
2 * 3 + (4 * 5)
5 + (8 * 3 + 9 + 3 * 4 * 3)
5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))
((2 + 4 * 9) * (6 + 9 ... |
7c20cdb966527e37943481ecb1d049a7f86b8652 | Whitie/AdventOfCode | /2018/Day_01/day1p2.py | 638 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
INPUT_FILE = 'input.txt'
def main():
frequency = 0
frequencies = []
seen = {0}
with open(INPUT_FILE, 'r') as fp:
for line in fp:
l = line.strip()
if l:
frequencies.append(int(l))
not_seen = True
whi... |
7b683b972accd14c161f79cb23a585863a9ab556 | rubayetalamnse/Basic-Python-Codes | /string-finction.py | 1,224 | 4.5625 | 5 | print(len("rubayet"))
#string functions------->>>>
passage = "nuclear energy provide zero carbon electricity, most reliable and cheap one. This energy is better than renewable energy! If we talk about wind power or solar or hydro, nuclear takes lowest place and produces maximum energy. And obviously we should come out... |
15ebf10a3472773fff3c4401fc306b52e01c0012 | rubayetalamnse/Basic-Python-Codes | /problem5.1-twitter.py | 2,555 | 4.0625 | 4 | import math
tweets = [
"Wow, what a great day today!! #sunshine",
"I feel sad about the things going on around us. #covid19",
"I'm really excited to learn Python with @JovianML #zerotopandas",
"This is a really nice song. #linkinpark",
"The python programming language is useful for data science",
... |
62d9880dce567021ad68a2cc1862e35e8a2aaabd | rubayetalamnse/Basic-Python-Codes | /4-6-odd-book.py | 153 | 3.953125 | 4 | #for i in range(1,21,2):
odd_list=[]
for i in range(1,21,2):
#print(list(i))
odd_list.append(str(i))
print(" ".join(odd_list))
print("Done!") |
eeb24838ff1e76e6e73c80e79741e364e5716782 | rubayetalamnse/Basic-Python-Codes | /geeks-1.py | 353 | 4.15625 | 4 | #printing sum of two numbers
num1 = 10
num2 = 45
sum = num1+num2
print("Sum of {0} and {1} is : {2}".format(num1,num2,sum))
#printing sum of two decimal or float numbers
no1 = input("enter any decimal Number: ")
no2 = input("enter another decimal number: ")
sum2 = float(no1)+float(no2)
print("The sum of {0} and {1... |
7e36b539f5178e27d64d421b45085dbbec0e0f1c | rubayetalamnse/Basic-Python-Codes | /full_name.py | 462 | 4.03125 | 4 | first_name="rubayet"
last_name="alam"
full_name= f"{first_name} {last_name}"
print(full_name)
#f is for format, f-strings
#never put space between f" and {gdgsdg}
#to insert a variable's value into a string, use the f immediately before
#the openning of quotation mark.
first_name="yeasin al"
last_name="Yeasa"
full_name... |
8467ad15dcfeb454383e1ef26143328ccca9ec7d | rubayetalamnse/Basic-Python-Codes | /functions11.py | 2,640 | 4.40625 | 4 | """You're planning a vacation, and you need to decide which city you want to visit. You have shortlisted four cities and identified the return flight cost, daily hotel cost, and weekly car rental cost. While renting a car, you need to pay for entire weeks, even if you return the car sooner.
City Return Flight ($) Hote... |
933857731a1e75f757c5f57ef7913ca5585b0f7e | rubayetalamnse/Basic-Python-Codes | /celsius-farenheit.py | 598 | 4.3125 | 4 | #Write a Python program to convert temperatures to and from celsius, fahrenheit.
temperature = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) : ")
degree = int(temperature[0:-1])
temp = temperature[-1]
if temp.upper() == "F":
celsius_temp = float((degree - 32) * 5/9 )
print("The tem... |
89913ec560216c462b94d7ca56767593235bbac6 | rubayetalamnse/Basic-Python-Codes | /formatting-output.py | 421 | 3.78125 | 4 | name = "Rubayet"
age = 22
payment = 820.00
#approach--1
print(name,age,payment)
#approach--2
print("Name is : ", name)
print("Age is : ", age)
print("Payment received :",payment)
#approach--3
print("Name is %s Age: %d payement received: %f" %(name,age,payment))
#approach--4
print("Name:{} Age: {} Payment: {}".forma... |
5f7c516bac769a5286c34eb8c0570a8ba7a98464 | rubayetalamnse/Basic-Python-Codes | /squarenum.py | 76 | 3.875 | 4 | a = int(input("enter a number ")) #a=3
square =a**2
print(square) #square =9 |
716e6505afcf8a2ac77c1f798b04ef142b4a2d8e | rubayetalamnse/Basic-Python-Codes | /ifelse5.py | 137 | 3.8125 | 4 | age = int(input("enter your age: "))
if (age>20 and age<35):
print("you can work in team A!")
else:
print("Please join team B")
|
6893267586fc8f08364c855ae0b8f0500e8a9571 | rubayetalamnse/Basic-Python-Codes | /oop8.py | 216 | 3.65625 | 4 |
class Computer:
def __init__(self):
self.name ="Rubayet"
self.age = 22
def update(self):
self.age =30
c1 = Computer()
c2= Computer()
if c1==c2:
print("Both objects are equal")
|
94529887c259ec0c647cf90102487626a0b36fd5 | rubayetalamnse/Basic-Python-Codes | /for-break.py | 241 | 4.1875 | 4 | for i in range(5,20):
print(i)
if i==10:
break
#when i ==10, the loop ends. We see values from 5 to 10 in the terminal.
else:
print("as we used break at 10, 5 to 10 is printed. after that this else loop won't be printed") |
622019a68abba6e0c1d31bdec0ad3c2d7778809a | rubayetalamnse/Basic-Python-Codes | /functions6.py | 1,310 | 4.15625 | 4 | #If you borrow $100,000 using a 10-year loan with an interest rate of 9% per annum, what is the total amount you end up paying as interest?
import math
#for loan emi------------------------
loan = 100000
loan_duration = 10*12 #10 years
interest_rate = .09/12 #compounded monthly
#reusing our previous function to calc... |
398f80e41bbd1c39caaa732ea87983633adbbf38 | rubayetalamnse/Basic-Python-Codes | /practice-dictionary2-ha.py | 672 | 3.953125 | 4 | s ={}
print(type(s))
#type is ---> <class 'dict'>
s2 = set()
print(type(s2))
#<class 'set'>
#problem-1
#enter an empty dictionary where 4 people will input there favourite language:
favlang ={}
lan1 = input("enter your favorite language Rubayet: \n")
lan2 = input("enter your favorite language Alam: \n")
lan3 = input(... |
0222a254febad84b8e9032d9c0d1cb263a01f369 | rubayetalamnse/Basic-Python-Codes | /loops3.py | 93 | 3.734375 | 4 | i = 1
while i>0: #this loop keeps running infinitely
print("rubayet ",i )
i +=1 |
c906588466eab7370fdbf6f6c8ec7706130706a2 | rubayetalamnse/Basic-Python-Codes | /basic-tuple2.py | 250 | 4.1875 | 4 | #got to know something new:----------------
#let's create a tuple----->
numbers = (1,2,3,4,5,6,7,8,9,10)
#reverse tuple ----
b = numbers[::-1]
print(b)
#output---(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
c = numbers[::2]
print(c)
#output--->(1, 3, 5, 7, 9) |
c81b693f9dcca328b6d547ed885ed5403a266cbf | rubayetalamnse/Basic-Python-Codes | /q4b.py | 845 | 4.125 | 4 | #Use a for loop to display the type of each value stored against each key in person
person = {
"Name":"Rubayet",
"Age": 21,
"HasAndroidPhone": True
}
for i in range(len(person)):
print(type(person.keys()))
print(type(person.values()))
for value in person:
print(type(value))
for key in person... |
a2ed9bf8f72007e8dc2ddc28f472a48d0b3d41ba | rubayetalamnse/Basic-Python-Codes | /project-2-making -a-friend.py | 446 | 3.546875 | 4 | import pyttsx3
friend = pyttsx3.init()
speech= input("Say Something: ")
#friend.say("nuclear energy provide zero carbon electricity, most reliable and cheap one. This energy is better than renewable energy! If we talk about wind power or solar or hydro, nuclear takes lowest place and produces maximum energy. And obvio... |
138aa4077a0b52fe7672067454f830a2f35d3604 | Adrian-Montemayor/hackingciphersbook | /ciphersbook/transpositionHacker.py | 972 | 3.515625 | 4 | import pyperclip, detectEnglish, transpositionDecrypt
def main():
myMessage = "Cenoonommstmme oo snnio. s s c"
hackedMessage = hackTransposition(myMessage)
if hackedMessage == None:
print('Failed to hack encryption.')
else:
print('Copying hacked message to clipboard: ')
print(hackedMessage)
#pyperclip.co... |
7b382b2e27222a5f472af82b3b3d69350bfeccab | developersage/PythonProjects | /snake_game/main.py | 1,261 | 3.671875 | 4 | from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import ScoreBoard
import time
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Sage's Snake Game")
screen.tracer(0)
snake = Snake(10)
food = Food()
score = ScoreBoard()
s... |
ce313252b917a9bdc2f9391a69887f0204b1eb6c | developersage/PythonProjects | /password-manager-start/main.py | 4,093 | 3.578125 | 4 | from tkinter import *
from tkinter import messagebox
from random import choice, randint, shuffle
from pyperclip import copy
import json
import string
import pandas as pd
# try:
# df = pd.read_csv("data.csv")
# except FileNotFoundError:
# df = pd.DataFrame(columns=["Website", "Email/Username", "Password"])
# ... |
8b81f4ca9ca8ece25e7f234c4b4837228ce66cd4 | francispoulin/SPINSpy | /spinspy/grid.py | 540 | 3.578125 | 4 | from reader import reader
## Read in the grid
## ------
def grid(type='vector'):
# This reads in the grid and produces a dictionary
# that contains x, y, z, dx, dy, dz, Lx, Lx,
# Lz, Nx, Ny, and Nz.
if type == 'vector':
x = reader('x', [0,-1],0,0)
y = reader('y', 0,[0,-1],0)
... |
bfd09a9ba63ea42a1a4d2f8a1fed37595e0a8c76 | Dayana-Marinova/HackBulgariaHomework | /week0/day2/member_of_nth_fib_lists/solution.py | 359 | 3.578125 | 4 | def member_of_nth_fib_lists(listA, listB, needle):
new_list = []
if needle == listA:
return True
if needle == listB:
return True
for i in range(2, len(needle)):
new_list = listA + listB
listA = listB
listB = new_list
if new_list == needle:
retu... |
690b7a6aa2828a088bec1baa6181d0d5a42d4b97 | Dayana-Marinova/HackBulgariaHomework | /week4/grocery_stor/tests_store.py | 194 | 3.625 | 4 | import sqlite3
conn = sqlite3.connect("store.db")
cursor = conn.cursor()
result = cursor.execute("SELECT id, name, price_per_kg, quantuty_in_kg FROM store")
for row in result:
print(row)
|
a89c2387debac6509fd60b28fc3d9bcf09df561e | Dayana-Marinova/HackBulgariaHomework | /week0/day1/prime_factorization/solution.py | 275 | 3.671875 | 4 | def prime_factorization(n):
dictionary = {}
if n > 2:
for i in range(2, n):
if n % i == 0:
dictionary[i] = 0
while n % i == 0:
n /= i
dictionary[i] += 1
return dictionary
|
2ff8ddac582aff1723d1e651c7580f4142fb1b3b | Dayana-Marinova/HackBulgariaHomework | /week0/day1/count_substring/solution.py | 459 | 3.5625 | 4 | def count_substrings(haystack, needle):
count = 0
for i in range(0, len(haystack)):
if haystack[i] == needle[0]:
for k in range(0, len(needle)):
if haystack[i] != needle[k]:
break
else:
i = i + 1
if(k == ... |
59a8c9b981bb0203fae5aabe709451ef4706a7c5 | edpretend/learn_python | /defs/def_txt.py | 1,264 | 4.34375 | 4 | """文本处理函数库"""
def watch_txt(filename):
"""watch txt and read"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
message = "Sorry, the file " + filename + " does not exist."
print(message)
else:
print(contents)
... |
86e7af0c89f72ae192f7c2e6936f7cbb28c47068 | Joyce-w/Python-practice | /09_is_palindrome/is_palindrome.py | 752 | 4.1875 | 4 | def is_palindrome(phrase):
"""Is phrase a palindrome?
Return True/False if phrase is a palindrome (same read backwards and
forwards).
>>> is_palindrome('tacocat')
True
>>> is_palindrome('noon')
True
>>> is_palindrome('robert')
False
Should ignore capi... |
41ce741f9f664c96fbaed7b8948c3634852cf3e6 | emilybache/PipelineSimulation | /src/util.py | 1,150 | 3.671875 | 4 | from datetime import timedelta
class OfficeHours:
def __init__(self):
self.working_hour_start = 8
self.working_hour_end = 18
def interval(self, start_time, end_time):
interval = end_time - start_time
# if its overnight, don't count the night
if start_time.day != end_ti... |
fcc5cb61e1df70e4020dc3c6f25b76c55ba07533 | alisson-fs/POO-II | /Lista de exercicios 1/Q2.py | 2,729 | 4.15625 | 4 | #Aluno: Alisson Fabra da Silva Matricula: 19200409
'''Neste exercício criei uma classe Biblioteca que recebe os livros que vão estar disponiveis
e criei a classe livro, que recebe todas as cadacteristicas de cada livro.'''
class Biblioteca:
def __init__(self, livros: list):
self.__livros = livros... |
e0bbcd02c2e9a03fab7517c0bdccd08efa4e99a6 | alisson-fs/POO-II | /Lista de exercicios 1/Q7.py | 4,621 | 4.25 | 4 | #Aluno: Alisson Fabra da Silva Matricula: 19200409
'''Neste exercício reutilizei as classes biblioteca e livro e criei uma classe usuário
que é utilizada para chamar os metodos da classe biblioteca.'''
class Usuário:
def __init__(self, usuario: str, senha: str):
self.__usuario = usuario
s... |
2ca5c2ecde0c9cc234f891a6837d7accc7987a8a | yzfx303/pyflight | /rigidbody.py | 9,635 | 3.53125 | 4 | # Implements the airplane as a rigid body. Airplane.py handles the forces
# acting on the airplane, this module computes the actual effect of those
# forces on the plane's position and rotation.
#
# I used the following sources to figure this out:
#
# David Baraff - Phyically Based Modeling: Rigid Body Simulation
# htt... |
685ac7bd1a40d0385519865043aff605dfd449b4 | shashwat397/Python-Assignment-1 | /Python Program to Put Even and Odd elements in a List into Two Different Lists.py | 188 | 4.0625 | 4 | odd = []
even = []
originallist = [1,2,3,4,5,6,7,8,9,10,11,11]
for i in originallist:
if(i%2==0):
even.append(i)
else:
odd.append(i)
print(odd)
print(even) |
bbd5ed5a2764ab3cb8371c5d9098d441ed57f102 | paddydoyle/exercism-python | /darts/darts.py | 581 | 3.96875 | 4 | import math
def score(x, y):
# List of tuples:
# - the first element is the minimum radius
# - the second element is the corresponding score
# Order them in decreasing radius.
scores = [
(10, 0),
(5, 1),
(1, 5),
(0, 10)
]
# Euclidean... |
25513fcac7cb60eeb3b4101d47fb999cfd83c5ef | paddydoyle/exercism-python | /yacht/yacht.py | 3,915 | 3.515625 | 4 | # Score categories
# Change the values as you see fit
YACHT = 1
ONES = 2
TWOS = 4
THREES = 8
FOURS = 16
FIVES = 32
SIXES = 64
FULL_HOUSE = 128
FOUR_OF_A_KIND = 256
LITTLE_STRAIGHT = 512
BIG_STRAIGHT = 1024
CHOICE = 2048
def score(dice, category):
# We were told that it will always be 5, so this is probably not ne... |
616c09fdff56cc928a6e6f5c70533d1bbde6df40 | paddydoyle/exercism-python | /acronym/acronym.py | 848 | 3.890625 | 4 | import re
def abbreviate(words):
# 2nd attempt:
#
# Re-do with generator expression, rather than the lambda functools
# approach. Running lambdas generates a new stack frame.
# The genexpr does seem a bit nicer.
return ''.join(x[0] for x in re.split(r'[ \-_]', words) if x).upper()
def abbre... |
bb564b4db7f50f42dc92e275f8a4844a2135ac5e | paddydoyle/exercism-python | /word-count/word_count.py | 333 | 3.8125 | 4 | import re
from collections import Counter
def count_words(sentence):
RE_WORD_INCL_SINGLE_QUOTE = r"([a-z\d]+(?:'[a-z\d]+)?)"
# Allow single quote inside the word only.
pattern = re.compile(RE_WORD_INCL_SINGLE_QUOTE)
return Counter(match.group()
for match in pattern.finditer(senten... |
84a0b525dfc9aae0db99464db6f84ceb256f19dc | paddydoyle/exercism-python | /matrix/matrix.py | 1,453 | 3.921875 | 4 | class Matrix(object):
def __init__(self, matrix_string):
if not matrix_string:
return
# Convert into a two-dimension array.
# First split on '\n' to get the rows
# Then split on ' ' to get the columns
# And convert from string to int.
self.rows = [[int(x)... |
aa363b2b51ef10a3eb6c553365c0285a51ffa0d4 | tyrande/spbot | /tools/svglit/point.py | 1,580 | 3.75 | 4 | import math
class point:
def __init__(self, _x, _y):
self.x = float(_x)
self.y = float(_y)
self.end = self
def __add__(self, p):
return point(self.x + p.x, self.y + p.y)
def __mul__(self, t):
return point(self.x * float(t), self.y * float(t))
... |
7a97bf7067249f409a7cf590bbfa4bf859850c6f | NiuCoder/quantstudy | /practise.py | 1,614 | 3.734375 | 4 | # -*- coding: utf-8 -*-
#习题中的精选
#9.1 创建账户的函数,并对账户名和密码进行校验
def create_name():
name = input('请输入用户名\n')
if ord(name[0])<65 or ord(name[0])>122:
print('用户名必须以字母开头')
return(create_name())
else:
return(name)
def verify_passwd(passwd):
head = 65<=ord(passwd[0])<=122
contain_numbe... |
ea6e710bb653466d155897f4267b4dc8dda11282 | chandra236/MyCodes | /linked_list.py | 1,225 | 3.90625 | 4 | class Node:
def __init__(self):
self.val = None
self.next = None
def set_val(self, val):
self.val = val
def set_next(self, node):
self.next = node
class Llist:
def __init__(self):
self.head = None
def add_node(self,val):
n = Node()
n.val... |
88534b1ed60e491922e401a1d6a59ff15962a464 | ProfessorChill/CLI-StopWatch | /__main__.py | 3,870 | 3.9375 | 4 | """ Just a simple CLI Stopwatch that supports multiple watches """
import sys
import threading
import curses
from time import sleep
class StopWatch(threading.Thread):
""" The stopwatch class which handles the counting of all watches """
seconds = []
minutes = []
hours = []
paused = []
seconds... |
412fd61fc9e72edbbc52a2b3d8af4b116d9dee69 | dansat/s11 | /s11py/tools/tool.py | 288 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 30 21:35:11 2015
@author: dana
"""
class HEX_TOOL(object):
def hex_convert_from_int(self, hexstring, base):
'''Convert a hextring with a specified base to integer'''
return int(hex(hexstring), base)
|
232923160d07ee83a6973f207e46354253aa4fd4 | dongqui/problemSolving | /structure/PriorityQueue.py | 1,567 | 3.796875 | 4 | import unittest
class PriorityQueue:
def __init__(self):
self.items = [0]
def __len__(self):
return len(self.items) - 1
def percolate_up(self):
i = len(self)
while i // 2 > 0:
if self.items[i] < self.items[i // 2]:
self.items[i // 2], self.ite... |
a73d71f63d1f0f6f70915a067d1ad83683b876b5 | dongqui/problemSolving | /structure/Queue.py | 547 | 3.6875 | 4 | import unittest
class Queue:
def __init__(self):
self.items =[]
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
self.items.pop()
def printQueue(self):
print(self.items)
def size(self):
return len(self.items)
class QueueTest(unit... |
0288920863e5eb40ccdd3e73c7d2588a7146e8df | ShibuyaSundays/BasicPythonProjects | /2-Intervals/Intervals.py | 1,181 | 3.796875 | 4 | #File about merging separate intervals into non intersecting intervals
#Isaac Lee
InputFile = open("Intervals.txt", "r")
InputContents = InputFile.readlines()
FileList = []
FilterList = []
def Difference(Tuple):
return abs(Tuple[1] - Tuple[0])
for i in range(len(InputContents)):
InputNoWhitespace = InputContents[i... |
a53af1d873b2238aa568577ae9ebd48bd7d8a846 | rgederin/python-sandbox | /python-code/src/collections/set.py | 2,859 | 4.46875 | 4 | x = {'foo', 'bar', 'baz', 'foo', 'qux', 'bar'}
print(type(x))
print(x)
x = set(['foo', 'bar', 'baz', 'foo', 'qux'])
print(type(x))
print(x)
x = set(('foo', 'bar', 'baz', 'foo', 'qux'))
print(type(x))
print(x)
_str = "quux"
print(list(_str))
print(set(_str))
# A set can be empty. However, recall that Python inte... |
877aa67f3757ac446a64f2a981a014632bcb491e | kickserves/tdd-money | /money/Franc.py | 256 | 3.5625 | 4 | from Money import Money
class Franc(Money):
def times(self, n):
return Franc(self.amount * n)
def __eq__(self, other):
return self.amount == other.amount
def __repr__(self):
return "Franc(" + str(self.amount) + ")"
|
c0b247a685010551b0fdaa1452d2fc1a4ef6ef1a | DuffAb/coursera-ml-py | /machine-learning-ex2/ex2/plotData.py | 651 | 3.6875 | 4 | import matplotlib.pyplot as plt
import numpy as np
def plot_data(X, y):
plt.figure()
# ===================== Your Code Here =====================
# Instructions : Plot the positive and negative examples on a
# 2D plot, using the marker="+" for the positive
# examples ... |
2e627275cd40eb6649807a9ddcbadcb7ea7d02e4 | lkz12/Applied-Data-Science-with-Python | /Machine Learning/Module+2.py | 30,982 | 4 | 4 |
# coding: utf-8
# ---
#
# _You are currently looking at **version 1.1** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-machine-learning/resources/bANLa) course resource._
... |
b9f063da9f24363d71b6350332d5210d617c534f | lkz12/Applied-Data-Science-with-Python | /Plotting/Assignment2.py | 5,542 | 3.59375 | 4 |
# coding: utf-8
# # Assignment 2
#
# Before working on this assignment please read these instructions fully. In the submission area, you will notice that you can click the link to **Preview the Grading** for each step of the assignment. This is the criteria that will be used for peer grading. Please familiarize your... |
b53cf125a9cc22c43b9a61fb760fe9c237a2671e | simu217/AllCode | /Kohl'sContractual Notice.py | 4,917 | 3.546875 | 4 | #---------------------------------------------------#
# AUTHOR: Simarjit Kaur #
# CODE: RenewalPartners #
#---------------------------------------------------#
import os
import csv
import re
import time
def Searchdays(date3):
SearchdaysVar = ""
if ("refu... |
e3c20174ef965ece3cdbe5c2b441c875dd79dbf3 | simu217/AllCode | /EffectiveDateTypeTrial.py | 33,468 | 3.59375 | 4 | import sys
import csv
import re
import time
import datetime
def convert_month_to_num(mm):
if (mm == 'jan') or (mm == 'january'):
new_mm = '01'
elif (mm == 'feb') or (mm == 'february'):
new_mm = '02'
elif (mm == 'mar') or (mm == 'march'):
new_mm = '03'
elif (mm == 'apr') or (m... |
68cc4857dbfc4c21bc66afd0ff230bd449244db1 | 600613/Programs | /ZD 3.py | 546 | 3.90625 | 4 | import random
# Создание одномерного массива рандомных чисел
a_arr = [random.randint(1, 10) for _ in range(10)]
print(a_arr)
# Добавление в массив n рандомных чисел
N = int(input('Введите количество рандомных чисел для добавления в массив '))
A = 0;
while A < N:
a_arr.append(random.randint(1, 10))
A = A + 1
p... |
9e6789c6f08bfdd6b4ad5dc28166fa321843f6c4 | robbywalker/untemplate | /untemplate.py | 5,167 | 3.515625 | 4 | # Copyright 2010 The Untemplate Authors. All Rights Reserved.
"""Reverse engineers templates."""
def getData(*docs):
""" Takes docs and returns relevant data for each docs """
# split docs into list of words
split_docs = []
split_docs = map(lambda(doc): doc.split(), docs)
# make template
template = mak... |
3f8eb9bb40f626bcf68a7f94882ee36cb9cecf8c | mobarski/sandbox | /misc/firstlast.py | 251 | 3.515625 | 4 | class int_obj(int): pass
def indexed(iterable):
for i,x in enumerate(iterable):
idx = int_obj(i)
idx.first = i==0
idx.last = i+1==len(iterable)
yield idx,x
if __name__=="__main__":
for i,x in indexed("abcdef"):
print(i,i.first,i.last,x)
|
113acba3954da223bf206b2f3c61df537db7f878 | syedareehaquasar/Python_Interview_prepration | /Hashing_Questions/is_disjoint.py | 982 | 4.21875 | 4 | Problem Statement
You have to implement the bool isDisjoint(int* arr1, int* arr2, int size1, int size2) function, which checks whether two given arrays are disjoint or not.
Two arrays are disjoint if there are no common elements between them. The assumption is that there are no duplicate elements in each array.
Inp... |
20438d264471feb7fdd2ec8173c71a212b49af95 | daidaiJ/neo4jDemos | /2.py | 288 | 3.515625 | 4 | #给实体赋予属性
from py2neo import Node, Relationship
a = Node('Person', name='Alice')
b = Node('Person', name='Bob')
r = Relationship(a, 'KNOWS', b)
a['age'] = 20
a.setdefault('location', '北京')
# a['location'] = '上海'
b['age'] = 21
r['time'] = '2017/08/31'
print(a, b, r)
|
4eed721e0b9dfadbd1bcc1b53d9233f4fc1505e0 | daidaiJ/neo4jDemos | /1.py | 196 | 3.671875 | 4 | #简单的创建两个对象,并建立关系
from py2neo import Node, Relationship
a = Node('Person', name='Alice')
b = Node('Person', name='Bob')
r = Relationship(a, 'KNOWS', b)
print(a, b, r) |
0222bd5c1a4977c2072877049ca131251d39d711 | torggaman/monsterCapture | /monsters.py | 872 | 3.59375 | 4 | import random
import game
class Monster(object):
def __init__(self, name, level, health, attack, defense, mtype, abilities, item):
self.name = name
self.level = level
self.health = health
self.attack = attack
self.defense = defense
self.mtype = mtype
self.ab... |
f4b23e71cb3395d3f90a8f823407ddea41724000 | shreyasandal05/HelloWorld | /utils.py | 203 | 4.1875 | 4 | def find_max(numbers):
"""This prints maximum number within a list"""
maximum = numbers[0]
for number in numbers:
if maximum < number:
maximum = number
print(maximum)
|
706115c14b494d4cc59c1c70c0f05902cdd94db9 | drewfidel/AutomatingTheBoringStuff | /Dictionary.py | 337 | 3.671875 | 4 | myCat = {'size': 'fat', 'color': 'red'}
# print(myCat['size'])
# Dictionaries are unordered
# for k in myCat.keys():
# print(k)
#
# for k in myCat.items():
# print(k)
# print(myCat)for k in myCat.keys():
# print(k)
# print(myCat.get('size')) # returns fat
# print(myCat.keys())
myCat['size'] = 'skinny'... |
91ed401ac8c08f4b53936e144d7e40a9ec2f77ac | nahog/pico-tetris | /char_letters.py | 7,537 | 3.6875 | 4 | class Letters:
def __init__(self, display, fg_color):
self._display = display
self.fg_color = fg_color
def draw(self, word, x, y):
self.fg_color.enable_color()
next_y = y
for letter in word:
next_y = self._draw_letter(letter, x, next_y)
def _draw_letter... |
d8ff6e9500f28d77547b15d4550ad266d0632ded | yingrui/DeepLearningTutorials | /theano_demo/5_shared_variables.py | 1,552 | 3.71875 | 4 | from theano import function
from theano import shared
import theano.tensor as T
state = shared(0)
inc = T.iscalar('inc')
accumulator = function([inc], state, updates=[(state, state+inc)])
print(accumulator(1))
print(state.get_value())
'''
You might be wondering why the updates mechanism exists.
You can always achi... |
d3fb69009257e172dc91e8cf8d74e572253e4716 | vseslav666/Lessons_python | /Lesson_3/Sorted_list.py | 193 | 3.75 | 4 | def int_list(l):
for i in l:
if type(i) != int:
raise TypeError
sorted_list = sorted(l)
print(sorted_list)
return
unsort = [1, 1.2, 18]
int_list(unsort) |
ccb0b136a01caff6977a4ba75eb08321c9ba3969 | pspencil/cpy5python | /lab_practice_1/binarysearch_pansong.py | 231 | 3.71875 | 4 | def binary_search(A,target,low,high):
mid=(low+high)/2
if low>high:
return -1
if A[mid]==target:
return mid
elif A[mid]<target:
return binary_search(A,target,mid+1,high)
else:
return binary_search(A,target,low,mid-1)
|
36eca5d4ef10c2e372ca6bcccf57681a30cfbd0c | pspencil/cpy5python | /practical03/q6_determine_prime.py | 377 | 3.984375 | 4 | #Filename:q6_determine_prime.py
#Author:PS
#Created:20130221
#Description:determine whether a num is prime
import math
def is_prime(n):
if(n==1):
return True
for i in range(2,int(math.sqrt(n))+1):
if(n%i==0):
return False
return True
c=0
i=2
while c<=1000:
if(is_prime(i)):
print(i," ",end="")
i+=1
c... |
09aed2e7fc9574e2a5af26c9b2136faed7edbc53 | pspencil/cpy5python | /practical02/q06_kilograms_to_pounds.py | 239 | 4 | 4 | #Filename:q06_kilograms_to_pounds.py
#Author:PS
#Created:201302901
#Description:To convert from kg to pounds
print("{0:<10s}{1:<10s}".format("Kilograms","Pounds"))
for i in range(1,11):
print("{0:<10d}{0:<10.1f}".format(i,float(i)*2.2))
|
153e312f66e6b47a7ac72e883536b56c17204408 | pspencil/cpy5python | /lab_assessment_1.py | 1,115 | 3.6875 | 4 | #program to validate car plate number
import re
infile = open("INVALID.DAT" , "r")
outfile = open("INVALID.DAT" , "a")
invalid_nums=infile.readlines()
c='.'
def checksum(s):
mapping=['A', 'Y', 'U', 'S', 'P', 'L', 'J', 'G', 'D', 'B', 'Z', 'X', 'T', 'R', 'M', 'K', 'H', 'E', 'C']
if not s[2].isdigit():
s=s[1:]
if l... |
01d4b92425ebe77a583c5c6b7ea257deeac918ce | pspencil/cpy5python | /practical02/q04_determine_leap_year.py | 245 | 4.28125 | 4 | #Filename:q04_determine_leap_year.py
#Author:PS
#Created:201302901
#Description:To determine whether a year is a leap year
year=int(input("Enter a year: "))
if (year%4==0 and year%100!=0) or year%400==0:
print("Leap")
else:
print("Not leap")
|
2591d2b8e68e3d56433928a121b2482cee1d1e02 | pspencil/cpy5python | /practical04/q7_find_largest.py | 302 | 4.09375 | 4 | #Filename:q7_find_largest.py
#Author:Pan Song
#Created:20130225
#Description:find largest number in an array
def find_largest(alist):
if(len(alist)==1):
return alist[0]
Max=find_largest(alist[1:])
if(alist[0]>Max):
return alist[0]
else:
return Max
alist=[5,1,8,7,2]
print(find_largest(alist)) |
89462b9a6649efc43db5d2a81de708bd7a23053d | pspencil/cpy5python | /HBL/c.py | 3,373 | 3.546875 | 4 | # c
import random
class Player:
def __init__(self,username,score):
self.username = username
self.score = score
player_list = []
for i in range(5000):
score = random.randint(0,99999)
username = ''
length = random.randint(4,10)
number_length = random.randint(0,length-1)
for j in range(length - number_length):
... |
6ee12e0328ab239e63a23adc6856af79f9cf02ca | Yesid4Code/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 660 | 3.90625 | 4 | #!/usr/bin/python3
'''
d
'''
def text_indentation(text):
'''
This function automatically ident text
Args:
param1: text to ident.
Return:
Nothin.
Raises:
TypeError: if text is not a string.
'''
if not isinstance(text, str):
rai... |
21334ff4ca556f71bdba054c54693575d5d94bfc | Yesid4Code/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 2,921 | 4.5625 | 5 | #!/usr/bin/python3
""" A Square class definition """
class Square:
""" Initialization of the class """
def __init__(self, size=0, position=(0, 0)):
""" Initialization of the class """
self.size = size
self.position = position
def area(self):
... |
71b3d35512817229a6ea074a8c617a156639cd6f | Yesid4Code/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py | 193 | 3.875 | 4 | #!/usr/bin/python3
def multiply_by_2(a_dictionary):
my_dictionary = a_dictionary.copy()
for i in my_dictionary:
my_dictionary[i] = my_dictionary[i] * 2
return my_dictionary
|
7af84b5559f6993fbef07bce669e9812462b90a6 | Yesid4Code/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/10-best_score.py | 567 | 3.640625 | 4 | #!/usr/bin/python3
def best_score(a_dictionary):
if a_dictionary:
i = 0
for key, value in a_dictionary.items():
if i < value:
i = value
j = key
return j
return None
# return (max(a_dictionary, key=a_dictionary.get) if a_dictionary else None)
... |
0d440cc1edea22776345ed50ee48739b2e48f656 | Yesid4Code/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 193 | 4.09375 | 4 | #!/usr/bin/python3
def uppercase(str):
for x in str:
n = ord(x)
if (n > 96) and (n < 123):
n = n - 32
print("{:s}".format(chr(n)), end="")
print("")
|
409c555ee9c48ae9342390ac6e93dbaec5abcc4f | HDargo/Slime_python | /Old_maid/character/player.py | 1,819 | 3.546875 | 4 | class player:
def __init__(self):
self.deck = []
def card_append(self, card):
self.deck.append(card)
def card_select(self, next_list_len):
if next_list_len == 1:
return 0
while True:
try:
print("내 카드 ",self.deck)
prin... |
ec99440108d907204e4c0a9052a158162ca81f3a | BlazedEngima/CART | /src.py | 21,347 | 4.03125 | 4 | import os
def csvreader(dataset):
""" Function to read the csv file
returns:
raw_data = list() containing the data
features = the header of the dataset
"""
# assign 2 dummy variables
temporary = [] # store data temporarily
raw_data = [] # store the processed data
... |
b32fc61dc734271dd230a31f436ba74fe99e4b66 | bhchance/AdventOfCode | /src/adventofcode/year2019/day1/problem2.py | 517 | 3.75 | 4 | def calculate_fuel_requirement(mass):
if mass <= 0:
return 0
return mass + calculate_fuel_requirement(mass // 3 - 2)
def calculate_fuel_for_fuel(mass):
return calculate_fuel_requirement(mass) - mass
assert calculate_fuel_for_fuel(14) == 2
assert calculate_fuel_for_fuel(1969) == 966
assert calcul... |
e9dea7705359ecbd5566a88f8760a291ce1f50f5 | bhchance/AdventOfCode | /src/adventofcode/year2019/day2/problem1.py | 1,342 | 3.53125 | 4 | class IntcodeProgram:
def __init__(self, initial_state):
self.state = initial_state
self.current_position = 0
def handle_opcode_1(self):
self.state[self.state[self.current_position + 3]] = (
self.state[self.state[self.current_position + 1]]
+ self.state[self.stat... |
168d8066d57bbf9e622187a32f93bd123531092d | AJKemps/cs-module-project-recursive-sorting | /src/sorting/sorting.py | 1,320 | 4.3125 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(left, right):
# elements = len(left) + len(right)
# merged_arr = [0] * elements
merged_arr = []
# Your code here
left_point = right_point = 0
while left_point < len(left) and right_point < len(right):
if l... |
47806634fc94d95fe9e520f4175602550183ff54 | Z3-dan/Competitive-Programming | /Kattis/Iceland/Problems 2019/Python/Dagatal/main.py | 172 | 3.578125 | 4 | m = int(input())
def main():
if m == 2:
return 28
elif m in [4,6,9,11]:
return 30
elif m in [1,3,5,7,8,10,12]:
return 31
print(main()) |
daa49d32aeee93eb30cd622cd94807a0a56b1eaf | DeepikaSampangi/myPythonPackagesExploration | /asyncio/sync_prime_check.py | 605 | 3.859375 | 4 | from math import sqrt
import time
def is_prime(x):
duration = time.perf_counter() - start
print("%.4f" %(duration))
print(f'Processing {x}')
if x < 2 or x%2 == 0:
print(f"{x} is not a prime no.")
else:
limit = int(sqrt(x)) + 1
for i in range(3, limit, 2):
if x... |
6335f51c50be58cee3ff25a2f36b9faca940b42e | aasensio/ALMA-Zeeman | /lowerToSep.py | 215 | 3.75 | 4 | # Convert string to lower case up to the first occurrence of a separator
def lowerToSep(string, separator='='):
line=string.partition(separator)
string=str(line[0]).lower()+str(line[1])+str(line[2])
return string |
9029202ab0d9f4663a8aa7257ce21e92e036a1eb | zhbowei/Study20 | /Learn20/day1/buycar.py | 1,242 | 3.6875 | 4 | #coding=utf-8
#__author: bwzhang
#__date: 2018/6/4
product_list =[
('Mac',9000),
('kindle',800),
('tesla',900000),
('python book',105),
('bike',2000),
]
saving = input('please input your money:')
shopping_car = []
if saving.isdigit():
saving = int(saving)
while True:
for i,v ... |
0fce1b2cddaf06ba5e70fa2b23ee1706e6a84a9a | zhbowei/Study20 | /Learn20/cmp_understand/test.py | 200 | 3.75 | 4 | #__author: bwzhang
#__date: 2018/7/23
# s = ['1', '2', '3a']
# for i in range(len(s)-1):
# print(s[i])
s1 ,s2= input('请输入任意两个软件版本号大小:').split()
print(s1)
print(s2)
|
d3d69971fc4d54bd44f784131af42cff2df697a7 | zhbowei/Study20 | /Learn20/day3/生成器.py | 1,101 | 3.671875 | 4 | #__author: bwzhang
#__date: 2018/6/15
# l = [1,2,3]
# print(l[0])
# s = (x for x in range(10))
# # print(next(s)) #等价于,__next__() in Py2: s.next()
# print(type(s))
# # 生成器就是一个可迭代对象(interable)
# for i in s: #不断next打印下一个属,打印本次时上一次指向被隔断垃圾清理
# print(i)
# def foo():
# print('ok')
# yield 1
# print('ok... |
dd85ff753264f24b5e0e8759afee679705c90255 | yooq/PythonUp | /leetcode/1512.py | 933 | 3.65625 | 4 | '''
给你一个整数数组 nums 。
如果一组数字 (i,j) 满足 nums[i] == nums[j] 且 i < j ,就可以认为这是一组 好数对 。
返回好数对的数目。
示例 1:
输入:nums = [1,2,3,1,1,3]
输出:4
解释:有 4 组好数对,分别是 (0,3), (0,4), (3,4), (2,5) ,下标从 0 开始
示例 2:
输入:nums = [1,1,1,1]
输出:6
解释:数组中的每组数字都是好数对
示例 3:
输入:nums = [1,2,3]
输出:0
'''
class Solution:
def numIdenticalPairs(self, nums) -... |
e74b25ffecc87c66836a69e630c9b5ab333fecaa | yooq/PythonUp | /leetcode/1029.py | 794 | 3.6875 | 4 | '''
输入:[[10,20],[30,200],[400,50],[30,20]]
输出:110
解释:
第一个人去 A 市,费用为 10。
第二个人去 A 市,费用为 30。
第三个人去 B 市,费用为 50。
第四个人去 B 市,费用为 20。
最低总费用为 10 + 30 + 50 + 20 = 110,每个城市都有一半的人在面试。
'''
class Solution:
def twoCitySchedCost(self, costs) -> int:
costs.sort(key = lambda x : x[0] - x[1])#差值排序
print(costs)
... |
05485c3a576a14d074a6b7eb0407c65a8c53fc25 | yooq/PythonUp | /11盛水最多.py | 1,113 | 3.6875 | 4 | '''
给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water
输入:[1,8,6,2,5,4,8,3,7]
输出:49
'''
a= [1,8,6,2,5,4,8,3,7]
max_area =0
i=0
j=len(a)-1
pivot_area=0
while i<... |
c893fbcce2b06ab199e5a0eb522b62f6d64136ae | yooq/PythonUp | /leetcode/486.py | 1,741 | 3.75 | 4 | '''
给定一个表示分数的非负整数数组。 玩家 1 从数组任意一端拿取一个分数,随后玩家 2 继续从剩余数组任意一端拿取分数,然后玩家 1 拿,…… 。每次一个玩家只能拿取一个分数,分数被拿取之后不再可取。直到没有剩余分数可取时游戏结束。最终获得分数总和最多的玩家获胜。
给定一个表示分数的数组,预测玩家1是否会成为赢家。你可以假设每个玩家的玩法都会使他的分数最大化。
示例 1:
输入:[1, 5, 2]
输出:False
解释:一开始,玩家1可以从1和2中进行选择。
如果他选择 2(或者 1 ),那么玩家 2 可以从 1(或者 2 )和 5 中进行选择。如果玩家 2 选择了 5 ,那么玩家 1 则只剩下 1(或者 2 )可选。
所... |
33ba3150a7f174ab2bf7f6ef3c5027b792718fbb | yooq/PythonUp | /leetcode/回文串.py | 1,235 | 3.578125 | 4 | '''
给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
示例 1:
输入:"abc"
输出:3
解释:三个回文子串: "a", "b", "c"
示例 2:
输入:"aaa"
输出:6
解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
'''
class Solution:
def countSubstrings(self, s: str) -> int:
length = len(s)
dp1 = [[0]*length for i in rang... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.