blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
52a56109f4722563cc92f33f9c7fcf07f1b7db79 | HarrisonMS/JsChallenges | /Python/codesignal/test3.py | 309 | 3.53125 | 4 | def uncover_spy(n, trust):
trust_counter = [0] * (n + 1)
for a, b in trust:
trust_counter[a] -= 1
trust_counter[b] += 1
for i in range(1, n + 1):
if trust_counter[i] == n - 1:
return i
return -1
uncover_spy(3, [[1, 3], [2, 3]]) |
6f28f1a2e7dadc615e2bff5a743946a418d8731c | momentum-team-6/house-hunting-with-python-jesseyproctor | /house_hunting.py | 1,570 | 4.5 | 4 | # variables I can give a value to
portion_down_payment = 0.25
r = 0.04
current_savings = 0
months = 0
# variables the user will give a value to
total_cost = float(input('What is the cost of your home? '))
annual_salary = float(input('What is your anual salary? '))
portion_saved = float(input('How much money will you ... |
8408ee02815b1d30107f30ee0e19b7c9ff1626ba | namsoojang/Play_with_Data_2nd | /5. 딥러닝/ch5/pd-test-sort.py | 410 | 3.765625 | 4 | import pandas as pd
# 키, 몸무게, 유형 데이터프레임 생성하기
tbl = pd.DataFrame({
"weight": [ 80.0, 70.4, 65.5, 45.9, 51.2, 72.5 ],
"height": [ 170, 180, 155, 143, 154, 160 ],
"gender": [ "f", "m", "m", "f", "f", "m" ]
})
print("--- 키로 정렬")
print(tbl.sort_values(by="height"))
print("--- 몸무게로 정렬")
print(tbl.sort... |
720a7a12f76cdaa6d3deb5893a4bb1f789ba297b | Baton-Bread/startup | /Second lesson/main.py | 770 | 3.984375 | 4 | def get_imt(weight, height):
imt = weight / (height * height)
if imt < 19:
print("У вас недовес :(")
elif imt > 25:
print ("У вас перевес :(")
else:
print("Ваш вес в норме :3")
def calc():
command = input("Введите команду: ")
num1 = float(input("Введите 1-e число: "))
num2 ... |
00ba476cbde4d720e9dfddae625caaf713a8fab3 | NamorNiradnug/physicslib | /physicslib/vector.py | 2,678 | 4.0625 | 4 | from math import acos
class Vector:
"""3D Vector. Could be used as 2D."""
def __init__(self, x: float = 0, y: float = 0, z: float = 0):
self.data = [x, y, z]
def __add__(self, other):
return Vector(*(self.data[i] + other.data[i] for i in range(3)))
def __iadd__(self, other):
... |
059baac992a5c546f8903bbb0be086bc033c2b33 | joonion/Project-Euler | /Python/052.py | 354 | 3.609375 | 4 | def permutable(n, m):
if sorted(str(n)) == sorted(str(n * m)):
return True
return False
def permutable_all(n):
for m in range(2, 7):
if not permutable(n, m):
return False
return True
def solve():
n = 1
while True:
if permutable_all(n):
return... |
19ad5853de61ad86fa7ad3b80ce09f5b0095ec6d | joonion/Project-Euler | /Python/036.py | 303 | 3.640625 | 4 | def double_palindrome(n):
s = str(n)
b = str(bin(n))[2:]
if s == s[::-1] and b == b[::-1]:
return True
return False
def solve(n):
s = 0
for i in range(1, n):
if double_palindrome(i):
s += i
return s
n = 1000000
answer = solve(n)
print(answer)
|
3136e4ce2ee18d824b3121c3a332b72fa378aad5 | LosGnidoS/Algorithms | /Binary_search.py | 362 | 3.96875 | 4 | #!/usr/bin/python3
#created by KIRILL SHVEDOV
'''BINARY SEARCH ALGORITHM'''
def binary_search(list, item):
low = 0
high = len(list)-1
while low <= high:
mid = (low + high)//2
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
my_lis... |
5a99145e864374e87f1476afe88811acf161d766 | burcekrbrk/GlobalAIHubPythonCourse_Burce-Karabork | /HW1.py | 252 | 3.796875 | 4 | #1. ödevin a şıkkı
liste = [1, 2, 3, 4, 5, 6]
a = len(liste)
liste1= liste[int(a/2):]
liste2= liste[:int(a/2)]
print(liste1 + liste2)
#1. ödevin b şıkkı
n = int(input("Tek basamaklı bir sayı giriniz"))
for i in range(0,n+1,2):
print(i)
|
bf39a2cf1aace8ff87a9e059ae9a2e2941389143 | csbailey5t/aoc2020 | /python/day2.py | 1,332 | 3.546875 | 4 | from collections import namedtuple
PasswordEntry = namedtuple("PasswordEntry", "min, max, letter, password")
def parse_line(line):
chunks = line.split(":")
password = chunks[1].strip()
rule_chunk = chunks[0].split(" ")
letter = rule_chunk[1]
rules = rule_chunk[0].split("-")
r1 = int(rules[0]... |
34daa102a91e79d84d65ad2eb8e9a25efaf305c5 | SaiRithvik/Python_mycaptain | /classes.py | 190 | 3.875 | 4 | class rectangle:
length = float(input())
width = float(input())
Area = length*width
def area(self):
print(self.Area)
return
rectangle1 = rectangle();
rectangle1.area();
|
8696e7dfd6d4b394a3dfb6bd48ee1bc74205068b | OttmarV/DataStructuresWithPython | /Built-In-DataStructures/list.py | 821 | 3.984375 | 4 | """
Mutable
Indexing
Not homogeneous
Allows duplicates
"""
hello=[1,20,0.5,10]
# Adding Elements(append,insert,extend)
# Deleting Elements(remove,pop,clear)
# Other Functions(index,count,sort)
print(hello.index(10))
hello.append([10,29]) #agrega como tal la lista proporcionada
print(hello)
hello.in... |
46e663130f8664513b88acd8cd2ae95743512a18 | samson-93/Minesweeper | /_coordObj.py | 1,059 | 4 | 4 | class Coord():
def __init__(self, x, y = None):
# Handles casting x-y coords in a string to Coord()
if(y == None):
if(isinstance(x, str)):
ln = x.split(', ')
newX = int(ln[0][1:])
newY = int(ln[1][:-1])
self.x = newX
... |
8f2118606711941786e68335bd87433d797c4aae | loongchan/geocoder_service | /apps/geocoders/base_geocoder.py | 1,861 | 3.515625 | 4 | from abc import ABC, abstractmethod
from urllib import request
from urllib.parse import quote_plus
import json
class BaseGeocoder(ABC):
"""Base class to get geocoder info from website"""
def __init__(self, param_config, param_request: request, param_address: str) -> None:
"""init class"""
sel... |
263777f538709a5521c78673d07720abe4faa278 | MikolajUl/TikTacToe | /main.py | 3,157 | 3.9375 | 4 | # Function changing char at given index of string
def replace(old_string, new_char, char_index):
return old_string[: char_index] + new_char + old_string[char_index + 1:]
# Win detector function
def check_win(modified_possible_wins, player_move, player):
counter = -1
# Modifying possible_wins lis... |
509793011140bf5e5057467a90b22ead0c3d8d27 | MechaMask/TicTacToeRL | /TicTacToe.py | 6,952 | 3.71875 | 4 |
class Game:
def __init__(self, player1, player2):
if(not(isinstance(player1, Player) or isinstance(player2, Player))):
raise TypeError("player 1 and player2 must be of type \"Player\"")
if(player1.type == player2.type):
raise TypeError("player 1 and player2 can't have the s... |
501dc134ff00e80ae6d68f4172b5dd76a6c8b384 | MisterZhouZhou/python3demo | /python2.7/class/Parent.py | 519 | 3.546875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
class Parent:
'定义父类'
parentAttr = 100
def __init__(self):
print('调用父类构造函数')
def parentMethod(self):
print '调用父类方法'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "父类属性 :", Parent.parentAttr
... |
2b7c924bbd75924c367c974c7280476daabeb7f9 | MisterZhouZhou/python3demo | /python3.6/re/re1.py | 145 | 4 | 4 | #! /usr/bin/python3
import re
str = 'Anna is {age} years old,Bob is {age} years old too';
content = str.replace('/{.*}/g', '13')
print(content) |
8ccfdca155b6736b2f75f8ec5082456cb296305a | njhughesSAS/zybooks_python | /Unit 11/11.8 LAB Words in a range (lists).py | 1,183 | 4.125 | 4 | """ Write a program that first reads in the name of an input file, followed by two strings representing the lower and upper bounds of a search range. The file should be read using the file.readlines() method. The input file contains a list of alphabetical, ten-letter strings, each on a separate line. Your program shoul... |
1ec89445ad498f7c7b766550eee346a2449aaba4 | njhughesSAS/zybooks_python | /Unit 12/12.7 LAB Pet information (derived classes).py | 1,599 | 4.59375 | 5 | """ The base class Pet has attributes name and age. The derived class Dog inherits attributes from the base class Pet class and includes a breed attribute. Complete the program to:
Create a generic pet, and print the pet's information using print_info().
Create a Dog pet, use print_info() to print the dog's informatio... |
33a3d95b1a0034b23d3817142662a2a8155a1677 | celine-m-s/python-test-101-pyconfr | /code/main.py | 649 | 3.9375 | 4 | class Number(object):
def __init__(self, number):
self.number = number
def is_odd(self):
""" Return True is the number is odd
"""
return self.number % 2 == 1
def ceil(self):
""" Returns the largest integer value less than or equal to
current number.
... |
19d35c11fbc83b115387ecba61ffc5abfc88c668 | vpiserchia/CTI-Toolbox | /compare.py | 654 | 3.703125 | 4 | import sys
if len(sys.argv) < 3:
print("Usage: compare.py file1 file2")
exit(0)
f1file = open(sys.argv[1], "rb")
f2file = open(sys.argv[2], "rb")
result = 0
lcount = 0
for line in f1file.readlines():
lcount +=1
count = 0
split = line.split(" ")
for f2line in f2file.readlines():
count = 0
for word in split:... |
c9317c3cf51d5a7f40cebed79f4f5f7fdbe4aa1a | iswetha522/Project_Euler | /ProjectEulerProblems/Exercise2.py | 353 | 4.15625 | 4 | items = [1,2,4543,0,-1]
# new_list = []
# for item in items:
# new_list.append(item)
# print(new_list.sort())
smallest = items[0]
largest = items[0]
for item in items:
if smallest > item:
smallest = item
if largest < item:
largest = item
print(f"Smallest element is {smallest}")
print(f"... |
ae57b2923cbd209be2ba5345218006cdc4d0d504 | keijak/hikidashi-py | /src/sieve.py | 331 | 3.65625 | 4 | def sieve(n):
is_prime = [True] * n
is_prime[0] = False
is_prime[1] = False
for i in range(4, n, 2):
is_prime[i] = False
for i in range(3, n, 2):
if i*i > n:
break
if is_prime[i]:
for j in range(2*i, n, i):
is_prime[j] = False
retur... |
78f23af8bdabbb8060a20bc5ebbb475383a4e783 | Dj4salsas/DS_PT_ENE21 | /0-Ramp_Up/1-Python/6- Módulos/primer_script.py | 1,522 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Ejemplo de un módulo Python. Contiene una variable llamada pi,
una función para calcular el área de un círculo de radio r
y una clase llamada Punto.
Created on Thu Feb 11 20:25:42 2021
@author: rzambrano
"""
import math
pi = math.pi
def area_circulo(radio):
"""
Función que devue... |
1ad9dc3ee3b0eea393e6d0e1761471f5bd55d5a2 | upassby/nexusPHP_scraper_based_adoption_system | /convert_to_GB.py | 578 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 10 00:15:14 2019
@author: asus
"""
def convert_to_GB(size):
# intake a str of size and output in MB
if 'KB' in size:
size = round(float(size.replace('KB', '')) / (1024 * 1024), 3)
elif 'MB' in size:
size = float(size.replace('MB', '')) / 1024
... |
8f4400c4b54fd457ded44ce9f6a2b41f50c485df | fxfabre/Algos | /Distribution_uniform_to_uniform/main.py | 2,205 | 3.890625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import math
import random
import numpy as np
import matplotlib
A = 7
B = 87
NB_TIRAGES = 100*1000
"""
Suppose we can generate a uniform density in [[0, A-1]].
From it, generate a uniform density in [[0, B-1]]
"""
def getUniformA( n ):
return random.randint(0, n-1)
d... |
eee38745fa542ea6a808f0e6e6af2dcafb571882 | Jmarkaba/wikipedia-CQG | /combine_data.py | 1,518 | 3.6875 | 4 | import argparse
import pandas as pd
def combine_data(args):
with open(args.ctx_ans_file, encoding="utf-8") as fin:
input_lines = [x.strip().split(" [SEP] ") for x in fin.readlines()]
with open(args.q_file, encoding="utf-8") as fin:
q_lines = [x.strip() for x in fin.readlines()]
assert ... |
9060deb571e451b376e042d0a0da5e36d037ac3e | echigawa0921/python-dl-test | /tutorial/test.py | 1,167 | 3.796875 | 4 | #Comment
# print("Hello World!")
# print("海賊王に俺はなる")
# print("モテたい")
#演算
# print(1+1)
# print(1-1)
# print(2*2)
# print(10/2)
# print(5%3)
#変数
# unko = 'l_size'
# unko_length = 0
# unko_times = 5.5
# print(unko_length + unko_times)
#条件分岐と関係演算子
# if else elif
# ==, !=, <, >, >=, <=
# if unko_length > 6:
# print(... |
501b516ba1ac63309bc240deb6381815ad048302 | cegraris/pythontutorial | /t_03_funciton.py | 4,681 | 3.890625 | 4 | # if False:
# def func():
# print('func1')
# else:
# def func():
# print('func2')
# func()
# othername = func
# othername()
# global variable and function ========================
# X = 23
# def func2():
# global X
# X += 1
# func2()
# print(X)
# factory function
# def maker(N):
# ... |
92aafd66ee605eeefd72485020010a58408958e7 | tholden92/uit-inf-1400-2020.github.io | /lectures/oop-07-oop-shortcuts/code/code.py | 979 | 3.890625 | 4 | #!/usr/bin/env python3
# reversed
normal_list = [1, 2, 3, 4, 5]
class CustomSequence():
def __len__(self):
return 5
def __getitem__(self, index):
return "x{0}".format(index)
class FunkyBackwards(CustomSequence):
def __reversed__(self):
return "BACKWARDS!"
for seq in normal_l... |
d80dd63e649cc99c60629cc7e7406b5c14da417d | anish531213/Interesting-Python-problems | /test0001.py | 117 | 3.671875 | 4 | def gcd(a, b):
if b == 0:
return a
else:
r = a%b
return gcd(b, r)
print(gcd(18, 12))
|
5393dbc2d3213aea5c70bc90145a61f42860c11d | anish531213/Interesting-Python-problems | /BinarySearch.py | 406 | 3.796875 | 4 | def BinarySearch(lst, key, midpoint):
if key == lst[0]:
return 0
if key == lst[midpoint]:
return midpoint
else:
if key < lst[midpoint]:
return BinarySearch(lst, key, midpoint - len(lst[:midpoint])//2)
else:
return BinarySearch(lst, key, midpoint + len(... |
8d9ebd19771b39b0e9a5f381c445dd88d57df84a | anish531213/Interesting-Python-problems | /myfirstobjectorientedprogram.py | 646 | 3.625 | 4 | import turtle
def make_line():
wdow = turtle.Screen()
anish = turtle.Turtle()
wdow.bgcolor("red")
anish.color("white")
anish.speed(10)
n = 24
while n>0:
i = 4
for i in range(i, 0, -1):
anish.forward(100)
anish.right(90)
anish.right(... |
f071939cf1f2997ec7b66e832cebf0dc8f339dca | anish531213/Interesting-Python-problems | /is reversible.py | 241 | 3.734375 | 4 | def reverse(n):
n = str(n)
n = n[::-1]
n = int(n)
return(n)
def find_age():
m = 0
z = 0
for n in range(36, 120):
if (n - 36) == reverse(n):
print(n)
z += 1
print(find_age())
|
990297985c3ec2ac181400cad39471fb61c13a90 | anish531213/Interesting-Python-problems | /RemoveSubstring.py | 376 | 3.546875 | 4 | def RemoveSub(string, sub):
new = ''
i = 0
while i < len(string):
if string[i] == sub[0]:
if string[i: (i+len(sub))] == sub:
i += len(sub)
else:
new += string[i]
i += 1
else:
new += string[i]
i +=... |
e514af48b6a480cd1befd326db456a453f0f3156 | anish531213/Interesting-Python-problems | /temporaryforproject.py | 2,436 | 4.3125 | 4 | '''
Exercise 4:
When playing Hangman, a user should be guessing one unique
letter at a time: let's call those 'legal guesses'. When a
user guesses a number, symbol, or two-letter guess, let's
call those 'illegal guesses'. Based on the newly guessed
letter and a string of all previously guessed letters,
write a function... |
02e5b85348e3aecd2c2268bc57194a01e3fc723b | anish531213/Interesting-Python-problems | /Stack.py | 344 | 3.734375 | 4 |
class Stack:
def __init__(self):
self.item = []
def push(self, element):
self.item.append(element)
def peek(self):
return self.item[len(self.item)-1]
def size(self):
return len(self.item)
def is_empty(self):
return (self.item == [])
def pop(self):
... |
4a7b5cb05ac045454abfeaac8e3cc99059c03e18 | anish531213/Interesting-Python-problems | /sorte.py | 312 | 3.828125 | 4 | def sort(list1):
pivot = list1[0]
new_list = []
for g in list1:
k = [g]
print(k)
if g <= pivot:
new_list = new_list + k
else:
new_list = k + new_list
k.pop(0)
print(k)
return new_list
z = sort([1, -2, 6, 100, 5])
print (z)
|
db40bd43f8abeb5fcfaeaebd5db6cb5931dd9a15 | anish531213/Interesting-Python-problems | /sad.py | 210 | 3.796875 | 4 | import turtle
def draw_circle():
window = turtle.Screen()
window.bgcolor("green")
brad = turtle.Turtle()
brad.forward(100)
window.exitonclick()
print("exit on click")
draw_circle()
|
6d4ce80ffa1282fe045d6accbc6892298e31a231 | anish531213/Interesting-Python-problems | /arrangeinwave.py | 175 | 3.78125 | 4 | def ArrangeWave(lst):
lst.sort()
for i in range(0, len(lst)-1, 2):
lst[i], lst[i+1] = lst[i+1], lst[i]
lst = [3, 5, 7, 9, 10, 13]
ArrangeWave(lst)
print(lst)
|
7b03b8622b976084e2076a95efacc053e968b4f6 | anish531213/Interesting-Python-problems | /Binarysearchalgorithm.py | 626 | 3.9375 | 4 | def BinarySearch(arr, num):
start = 0
end = len(arr)-1
result1 = Findindex(arr, num, True)
result2 = Findindex(arr, num, False)
return result2-result1+1
def Findindex(arr, num, bol):
start = 0
end = len(arr)-1
while start <= end:
mid = (start+end)//2
if arr[mid] < n... |
8cee0b1f6ddccf8251cdf32a8427472e217f077d | anish531213/Interesting-Python-problems | /sumwithoutint.py | 291 | 3.703125 | 4 | def sum_without_int(s1, s2):
int_s1 = 0
int_s2 = 0
for i in range(len(s1)):
int_s1 += int(s1[i])* (10 **(len(s1)-1-i))
for j in range(len(s2)):
int_s2 += int(s2[j])* (10 **(len(s2)-1-j))
return (int_s1 + int_s2)
z = sum_without_int('34', '34')
print(z)
|
0f829d5199a5a2811c531fdbe92ea50887174d07 | anish531213/Interesting-Python-problems | /has_duplicates.py | 199 | 3.671875 | 4 | def has_duplicates(l):
d = dict()
for i in l:
if i in d:
return False
else:
d[i] = 1
return True
z = has_duplicates([1, 2, 3, 'a', 'a'])
print(z)
|
6cc99f8081172b1cb75610ecf1642bb3f0cce51f | JDonMc/BCI-1 | /OtherUnused/discrete_fourier_transform.py | 756 | 3.515625 | 4 |
read(file)
def discrete_fourier_transform(xn):
N = length(xn)
K = N
fourier[0::K] = 0
for k in K:
cissum = 0
for n in N:
cissum += xn[n]*(cos(-2*pi()*k*n/N)+i*sin(2*pi()*k*n/N))
fourier[k] = cissum
return fourier
def inverse_discrete_fouri... |
36fc107c877d14d547a5e7f97c320c67ba843a8c | alex-schaaf/adventofcode2020 | /day10/main.py | 2,241 | 3.625 | 4 | # python 3.9
from collections import Counter
def parse_input(filepath: str, split: str = "\n") -> list[str]:
with open(filepath, "r") as file:
content = file.read()
return content.split(split)
if __name__ == "__main__":
lines = parse_input("./input")
joltages = [int(l) for l in lines]
g... |
b2e88a9a0fdde2f74cd2de50f33e8a862dc5281e | xiaochuanjiejie/python_exercise | /Exercise/15-18/10.py | 593 | 3.859375 | 4 | #-*- coding: utf-8 -*-
class Foo(object):
'''类属性'''
jishu = 100
my_list = []
def testJishu(self,number):
'''定义实例属性'''
self.jishu = number
def print_jishu(self):
print 'jishu,我是实例变量:',self.jishu
mytest = Foo()
mytest.testJishu(20)
mytest.print_jishu()
mytest.jishu += 1
my... |
70758815cee385cb9434f87898df24529a7dac3e | xiaochuanjiejie/python_exercise | /Exercise/19-22/8.py | 340 | 4 | 4 | >>> x = 'abc'
>>> x1 = 'abc'
>>> x2 = repr(x1)
>>> x1
'abc'
>>> x2
"'abc'"
>>> eval(x2)
'abc'
>>> print type(x2)
<type 'str'>
>>> print type(x1)
<type 'str'>
>>> x3 = str(x1)
>>> eval(x3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'abc... |
6135be1d309b5d332c865e83085a3386d0a1fcca | xiaochuanjiejie/python_exercise | /Exercise/27/re_14.py | 117 | 3.75 | 4 | #coding: utf-8
import re
month = raw_input('输入月份:')
ss = re.search(r'^(0|1)?[0-9]?',month)
print ss.group() |
014163cc1c9cfc70eeb9e5e8aeb41004d35049a0 | xiaochuanjiejie/python_exercise | /Exercise/15_module/t.py | 150 | 3.765625 | 4 | #coding: utf-8
def f(n):
if n == 0 or n == 1:
return 1
else:
return (n * f(n-1))
print f(0)
print f(1)
print f(2)
print f(5) |
c81862a58442906c8f3caf5f59620528d402bde2 | xiaochuanjiejie/python_exercise | /Exercise/dict_1.py | 344 | 3.8125 | 4 | # -*- coding: utf-8 -*-
__author__ = 'chuan'
dict1 = {1:"a",2:"b","c":3}
#字典排序方法一
def sort1(adict):
a = adict.items()
a.sort()
return [value1 for key1,value1 in a]
print sort1(dict1)
#字典排序方法二
def sort2(bdict):
b = bdict.keys()
b.sort()
return [bdict[key2] for key2 in b]
print sort2(dict1) |
974fc7c85ed8f6cfa8c4510b915a9d539d43dc88 | xiaochuanjiejie/python_exercise | /Exercise/9-14/zhongweishu.py | 563 | 3.6875 | 4 | #-*- coding:utf-8 -*-
__author__ = 'xujunchuan'
import re
t_list = []
num = raw_input('input number: ')
t_list = re.split(',',num)
length = t_list.__len__()
print length
#python浮点数list排序(http://blog.csdn.net/pirage/article/details/9282717)
t_list.sort(cmp=lambda x,y: cmp(float(x), float(y)), reverse = False)
#3.0,2.1,1... |
e0eb851be52b5e977c22cd4dd158fec25d1673fe | xiaochuanjiejie/python_exercise | /Exercise/15-18/14.py | 537 | 3.953125 | 4 | #-*- coding: utf-8 -*-
class Foo(object):
def __init__(self,x,y):
self.x = x
self.y = y
def test(self):
print 'in 父类'
class Foo2(Foo):
def __init__(self,x,y,z):
print '调用子类自己的构造函数'
# Foo.__init__(self,x,y) //缺陷是若父类名称变化,调用失效,可用下行方法
super(Foo2,self).__ini... |
1e8c913c8f72cbc1f1b021b58d7db42c9500bade | xiaochuanjiejie/python_exercise | /123/ShuangChongXunHuan.py | 438 | 3.578125 | 4 | #-*- coding: utf-8 -*-
__author__ = 'chuan'
'''
要求:
输出:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
思路:双重循环,外层循环管行数(从第一行到第六行),内层循环管横向输出(1 2 3...)
'''
line = 7
i = 1
# j = 1
while i < 7:
i += 1
# 保证每行第一个数字是1,不然的话在内层循环后,j就会变值
j = 1
while j < i:
print j,
j += 1
print |
9d29f83658ef1740490fa80010859ef50dbd9b4b | xiaochuanjiejie/python_exercise | /EG/9x9.py | 278 | 3.59375 | 4 | # -*- coding: UTF-8 -*-
__author__ = 'chuan'
# for i in range(1,10):
# for j in range(1,10):
# a = i * j
# print '%s x %s = %s' % (i,j,a)
#此方法效果更佳
for i in range(1,10):
for j in range(1,i+1):
print i,'*',j,'=',i*j,
print '' |
50bde459573b04ea423ebe994fd81888bd5b7d7c | xiaochuanjiejie/python_exercise | /123/score.py | 256 | 3.5625 | 4 | #-*- coding: utf-8 -*-
__author__ = 'chuan'
scroe = int(raw_input('请输入分数:\n'))
if scroe >= 90:
print 'A'
elif scroe >= 80 and scroe < 90:
print 'B'
elif scroe >= 60 and scroe < 80:
print 'C'
else:
print '不及格,加油。' |
53982e6f29af3e1a92d1389a4c69210e0326c0af | xiaochuanjiejie/python_exercise | /Exercise/19-22/3.py | 545 | 4 | 4 | #-*- coding: utf-8 -*-
class Foo(object):
#静态变量
num = 5
def __init__(self,x,y):
self.x = x
self.y = y
p = Foo(5,6)
print getattr(p,'x')
print getattr(Foo,'num')
print hasattr(p,'x')
print hasattr(Foo,'num')
setattr(p,'z',8)
print getattr(p,'z')
print hasattr(p,'z')
print hasattr(Foo,'z')
d... |
f0d63131cf5a10b683ad33633a056dd4f91fc7b2 | kylestremdev/DojoAssignments | /Python/Python_Fundamentals/coinToss.py | 365 | 3.671875 | 4 | import random
heads = 0
tails = 0
for i in range(1, 5001):
rando = round(random.random())
coin = ""
if rando == 0:
coin = "tails"
tails += 1
else:
coin = "heads"
heads += 1
print "Attempt #{}: Throwing... Coin landed {}\n{} total head(s), {} total tail(s)".format(i,... |
b5262a0e7e9f00226d10866dae162d365ccf992f | kylestremdev/DojoAssignments | /Python/Python_Fundamentals/averageList.py | 155 | 3.65625 | 4 | from __future__ import division
def averageList(arr):
sum = 0
for num in arr:
sum += num
print sum/len(arr)
averageList([1,2,3,4,4])
|
8d33cc2c9e96617931be8da4dddc9cc42c6c81aa | smithcb88/Titan-FTPFileDownloader | /ftpfiledownloader.py | 9,956 | 3.5625 | 4 | """Download file(s) from FTP and upload directly to Titan's blob storage.
For more help, please execute the following at the command prompt:
ftpfiledownloader --help
"""
import datetime
import ftplib
import posixpath # Unix separators needed for FTP despite code potentially running on windows so use this over os.p... |
a8a1bbe3c5e5caec5388ca7de7bd5e789fbe8e90 | nkrish19/Weather-Web-Service | /a1.py | 6,325 | 4.125 | 4 | # function to get weather response
def weather_response(location, API_key):
"""This function takes in location and an API key as input.
The location must be in the city list document available at openweathermap.org .
Don't generate an API key more than once in ten minutes for good a response.
A json string is ... |
b9aab0fd8ba396ec80379c02b495e84a1f4b37e8 | YourM0mm/week-9-Final | /Kellogg final.py | 2,408 | 3.9375 | 4 | import requests
#make a call to website and retrieve data. reference openweathermap.org
def get_web_data(zip=None, city=None):
baseUrl = "http://api.openweathermap.org/data/2.5/weather?units=imperial"
#add API id
apiid= "5cea5abaf21b5253ae99a8bda30bb09e"
#check is user provides zip code or city
if z... |
c100c79b90394b0d59c8976565e736b7b12f8805 | dbkusumawardhana/el5203_advanced_programming | /homework_3/insertion_sort.py | 1,463 | 3.84375 | 4 | # source of bubble sort and insertion sort algorithm
# https://www.tutorialspoint.com/python_data_structure/python_sorting_algorithms.htm
import csv
import array
import time
import os
import numpy as np
def main():
filename = '../datasets/10integer.csv'
list_unsorted = read_file(filename)
list_to_sort = np.copy(li... |
513ca05bedc8aad71c8eaacb1737b625aae80323 | dbkusumawardhana/el5203_advanced_programming | /homework_3/bubble_sort.py | 1,409 | 3.828125 | 4 | # source of bubble sort and insertion sort algorithm
# https://www.tutorialspoint.com/python_data_structure/python_sorting_algorithms.htm
import csv
import array
import time
import os
import numpy as np
def main():
filename = '../datasets/10integer.csv'
list_unsorted = read_file(filename)
list_to_sort = np.copy(li... |
43d5900b94d6cfa2452a010e738000bdafc1552c | konlrie/coding-practice | /Programmers/practice.py | 66 | 3.671875 | 4 | a = [1,2,3]
b = [1]
for i in a:
if i in b:
print(i-1) |
181d0d64db9844cb1533432d2f6f24a0dfd776fd | yushujun0629/PythonProject | /MyProject/Lesson1/1.py | 198 | 3.578125 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
# set_test = set("hello")
# print(set_test)
name = 'yushujun'
age = {'k1': 'v1', 'k2': 'v2'}
print('My name is %s, and my age is %s' % (name, age))
|
2f8795c32e74c6dd3980bf6e0709f7f29da020cf | ryanitto/aoc2020 | /day8/part2.py | 7,775 | 3.671875 | 4 | """
--- Day 8: Handheld Halting ---
Your flight to the major airline hub reaches cruising altitude without incident. While you consider checking the
in-flight menu for one of those drinks that come with a little umbrella, you are interrupted by the kid sitting next
to you.
Their handheld game console won't turn on! T... |
acc32262866d42ac87af240959c0bc337c7af014 | ryanitto/aoc2020 | /day8/part1.py | 4,900 | 3.671875 | 4 | """
--- Day 8: Handheld Halting ---
Your flight to the major airline hub reaches cruising altitude without incident. While you consider checking the
in-flight menu for one of those drinks that come with a little umbrella, you are interrupted by the kid sitting next
to you.
Their handheld game console won't turn on! T... |
23a5d23ff48a0d53af6881dbde41d944b3fde325 | toyotathon/leetcode_problems | /strings/anagrams/anagrams.py | 840 | 3.53125 | 4 | class Solution(object):
def createDict(self, s):
returnDict = dict()
for char in s:
if char in returnDict:
returnDict[char] += 1
else:
returnDict[char] = 1
return returnDict
def anagramMatch(self, s, t):
for char, count... |
7d71a97687da817c62b265fd72f0254333ba975b | SathishKumarA2001/Sockets_Collections | /Socket_example/getServByPort.py | 243 | 3.625 | 4 | import socket
#Get internet service protocol name using service protocol...
ports = [443,80,21,22]
proto = "tcp"
for port in ports:
name = socket.getservbyport(port,proto)
print("The service name {} got by port {}".format(name,port)) |
5934ab36c542eefb09f1ce0fb82b3a576a8b253d | SathishKumarA2001/Sockets_Collections | /Socket_example/getServbyName.py | 392 | 3.5 | 4 | import socket
## Get port Number of the internet service protocol using service name...
serviceList = ["daytime","ftp","gopher","http","https","imap","pop3","ssh","smtp"]
UnderLying_proto = "tcp"
UnderLying_proto_2 = "udp"
for service in serviceList:
port = socket.getservbyname(service,UnderLying_proto)
pri... |
ac58677ba3c640cb2b9293e84e5370d8702c3d2c | JeremyRawlings/nfl | /Overtime/OvertimeAnalysis.py | 9,528 | 3.59375 | 4 | #!/usr/bin/env python
# coding: utf-8
from bs4 import BeautifulSoup as bs
import requests
import re
import pandas as pd
from matplotlib import pyplot as plt
def get_abbreviations():
"""
Returns
-------
Prints a list of acceptable team abbreviations
"""
play_df = pd.read_csv('plays.csv')
... |
fe9c8cce45a5295f533517682657382ef385ab44 | aqurilla/data-structures-and-algorithms | /python/integer_replacement.py | 444 | 3.65625 | 4 | # https://leetcode.com/problems/integer-replacement/
class Solution:
def integerReplacement(self, n: int) -> int:
if n <= 1:
return 0
div2 = n//2
if (n%2 == 0):
return self.integerReplacement(n/2) + 1
else:
if (div2 == 1) or (div2%2 == 0):
... |
e9a585d0ab4c11bdd9de0138b06b939f5525d1ca | aqurilla/data-structures-and-algorithms | /python/LinkedList_lvl2.py | 1,514 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
num1 = 0
num2 = 0
ptr1 = l1
ptr2 = l2
factor = 1
... |
d983d704cfef486798905c2ee10e64213e76f9bb | S-Lam/PFB_problemsets | /pset4-shuffled_sequence.py | 1,100 | 4.0625 | 4 | #!/usr/bin/env python3
#creating a shuffled sequence
import random
import sys
#get sequence as input
sequence = sys.argv[1]
#need to convert sequence to list to make it mutable
seq_list = list(sequence)
#randomize the sequence
for num in range(len(sequence)):
#choose two random positions within given sequence
rand... |
909cee9e90f0a1dfa4fef9f02e4add37f0ad981d | S-Lam/PFB_problemsets | /pset9-part2.py | 781 | 3.84375 | 4 | #!/usr/bin/env python3
# calculate gc_content
def gc_content(dna):
upperdna = dna.upper()
g_content = dna.count("G")
c_content = dna.count("C")
gc_content = (g_content+c_content)/len(dna)
percentage_gc = '{:.2%}'.format(gc_content)
# print (gc_content)
print("Percent GC content:", str(percentage_gc))
#gives rev... |
d51f7e0fe7a5b96c776534306b6b7ca80264a1e1 | judyhuang209/000alg | /hw7/hw7origami.py | 682 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 1 20:05:18 2019
@author: 105502506
"""
def maxwid(a, b):
if a > b:
a, b = b, a
wid = b/4
if a < wid:
return a
elif a == wid:
return wid
else:
if wid < a/2:
return a/2
else:
return wid
de... |
b0b1e9660d0933bb655f7daa29c1065b3ca0ca1f | kolyann/adventofcode | /2017/day_09/day_09.py | 949 | 3.53125 | 4 | import re
data = open('data.txt').read().strip('\n')
#print(data)
def escape(data):
accumulate = []
trash = False
skip = 0
garbage = 0
for i in range(len(data)):
if skip:
skip -= 1
continue
l = data[i]
if l == '!':
skip = 1
... |
00e569900c8567c7a997fd116b360a58fa9f47bc | abosma/Miniproject | /Miniproject2/SetTweets.py | 1,071 | 3.796875 | 4 | from tkinter import *
from tkinter import messagebox
root = Tk()
filename = None
def Tweet():
global filename
tweet = text.get(0.0, END) # read tweet
if (len(tweet) > 140): # check on tweet
messagebox.showerror('Error',
"Meer dan 140 characters ingevoerd, typ minder ... |
028c47f3bcbbda53e497eb0c345976441288c534 | JosephPolaski/eight_puzzle | /verify_puzzle.py | 5,548 | 4.3125 | 4 | """
verify_puzzle.py
This module contains the verification algorithim to determine the decision problem for 8-puzzle.
This decision problem asks, if given an 8-puzzle, can it be solved in k moves. In this case the
k value will be provided by the user. The user may also play the game and see if they are
able to solv... |
02f388ed5cad12592f02eb151f981881da180cd2 | saipramodkudapa/practise-dsa | /oas/maxKOccurences.py | 1,073 | 3.53125 | 4 |
# def maxRepeating(sequence: str, word: str) -> int:
# if len(sequence) < len(word):
# return 0
# ans = 0
# k = 1
# while word * k in sequence:
# ans += 1
# k += 1
# return ans
def maxRepeating(sequence: str, word: str) -> int:
s, w = len(sequence), len(word)
max_r... |
5d9e06e515284f622b0373d8e317e4028bc3e7ef | hunaif/leetcode_assignment | /src/binary_tree_max_path_sum/max_sum_path.py | 1,237 | 3.96875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# from sys import maxint
# minimum_int = -maxint - 2
class Solution:
def __init__(self):
self.sum = -1000 #Not a good initialization
def m... |
7d975dd7d85d7b41d189e83af9388f6e3ac9ca12 | ZrcLeibniz/PythonTest | /Recall/TestTuple02.py | 433 | 4.15625 | 4 | # 元组元素的访问和计数
a = (20, 30, 40, 50)
print(a[2])
print(a[0:2:1])
# 对于元组而言内部没有排序方法,只能使用内部函数sorted(tupleObj),并且产生新的列表对象
a = (10, 20, 30, 9, 8)
b = sorted(a)
print(b)
# 可以通过zip函数,将多个列表组合成元组,并且返回这个zip对象
a = [10, 20, 30]
b = [40, 50, 60]
c = [70, 80, 90]
d = zip(a, b, c)
print(d)
e = list(d)
print(e) |
03804e524c49bf8ab2f1cbbd80299b96685a6632 | ZrcLeibniz/PythonTest | /mypro01/mypy06.py | 600 | 3.75 | 4 | # for循环的学习
for x in (10, 20, 30):
print(x * 30)
for x in 'abcdefg':
print(x)
a = ['姓名', '年龄', '薪资']
b = ['rich', 18, 200000]
z = dict(zip(a, b))
for x in z.keys():
print(x)
for x in z.values():
print(x)
for x in z.items():
print(x)
print("#################################")
sum_all = 0
sum_eve... |
59b39a23dbd891e5fe29069457bdd018d2cb89e8 | ZrcLeibniz/PythonTest | /mypro01/mypy12.py | 286 | 3.609375 | 4 | import turtle
my_colors = ['red', 'yellow', 'green', 'blue', 'pink', 'red', 'yellow', 'green', 'blue', 'pink']
t = turtle.Pen()
t.width(5)
for x in range(10, 101, 10):
t.penup()
t.color(my_colors[x // 10 - 1])
t.goto(0, 5 - x)
t.pendown()
t.circle(x)
turtle.done()
|
5e2fb22c56b2b54614f33acb9506c871bcaffccb | osHamad/car_prices | /setup.py | 1,141 | 3.859375 | 4 | import statistics as stat
# we will setup the data to ensure we get optimal results
# for our regression algorithm, we must skip over all attributes with string values
# we should remove any instances with no Price attribute, since it is our y var
# we should check to see if any other instances are empty
# if th... |
19c7c1ac9181292a9145228c0db02675b5ec616d | Leocodefocus/project | /Python/LottoNumbers.py | 458 | 3.90625 | 4 | isCovered=99*[False]
endOfInput=False
while not endOfInput:
s=raw_input("Please enter a line of numbers separated by spaces:")
items=s.split()
lst=[eval(x) for x in items]
for number in lst:
if number==0:
endOfInput=True
else:
isCovered[number-1]=True
allCovered=True
for i in range(99):
if not isCovered[... |
e419e91651a8d871bc00e4df10705bfc002741d6 | chromakey/advent2018 | /day1/part2/solution.py | 741 | 3.625 | 4 | from argparse import ArgumentParser
def get_first_repeat_frequency(file_path):
with open(file_path, 'r') as freqfile:
change_list = [int(freq) for freq in freqfile.read().splitlines()]
frequency = 0
freq_list = []
idx = 0
while frequency not in freq_list:
freq_list.append(frequen... |
b80b018e6d2613effd8074d09b8a9c8206210a1d | sarthakarora1208/pythonbasics | /tic_tac_toe.py | 2,232 | 3.828125 | 4 | # Making a board and assigning row column pair
board = {}
for i in range(1, 4):
for j in range(1, 4):
board.setdefault(str(i) + str(j), ' ')
# pluging values to the board and appearence
def BoardImage():
print(board['11'] + '|' + board['12'] + '|' + board['13'])
print('-+-+-')
print(board['21'... |
d29a96b2b887362c2347f79b653d296ea4775bdc | AnmolTalwar/Automating-Boring-Stuff-with-Python-Solutions | /Dictionaries and Structuring Data/List to Dictionary Function for Fantasy Game Inventory.py | 580 | 3.859375 | 4 | def displayInventory(inventory):
n=0
print("Inventory:")
for i in inventory:
n+=inventory[i]
print(i,inventory[i])
print("Total number of items:" + " " + str(n))
def addToInventory(inventory, addedItems):
for new in addedItems:
if new in inventory:
inv... |
c168b939e6ec3bfe0196154c0b6f4a0a7761ffc2 | AnmolTalwar/Automating-Boring-Stuff-with-Python-Solutions | /Organizing Files/Filling in the Gaps.py | 1,469 | 3.6875 | 4 | import re
import os
import shutil
a = input("Please Enter what type of File to copy:\n")
b = input("Please Enter the Base Name of the series file:\n")
c=input("Input the full directory path you want to check for file sequence:\n")
os.chdir(c)
path1 = os.getcwd()
regex = re.compile('(^(%s)(\d{1,})\.%s$)'%(b,a))
e = [... |
aea71ee136cfdf46c0ac57bbf77cc5dc318cffd4 | AnmolTalwar/Automating-Boring-Stuff-with-Python-Solutions | /Organizing Files/Selective Copy.py | 386 | 3.5625 | 4 | import re
import os
import shutil
a = input("Please Enter what type of File to copy:\n")
regex = re.compile('^.*\.%s$'%a)
for folderName, subfolders, filenames in os.walk('C:\\MA'):
for filename in filenames:
if regex.search(filename):
print(filename+ " is being copied.")
path = ... |
6918761016db3a74c55164761e5f1e960df0b44e | IIC2115/Syllabus-2019-2 | /Material de clases/Capítulo 3/Clase.py | 961 | 3.765625 | 4 | from copy import deepcopy as dp
def isPrime(n):
if n <= 1:
return False
for i in range(2, n):
if (n % i == 0):
return False
return True
def getPrimes(P,S):
primes = []
for i in range(P+1,S+1):
if isPrime(i):
primes.append(i)
return primes
... |
bd7520b944a4e5b3140c444322e478b14958e0e4 | AliAbdelaal/Mwaslaty | /python codes/cleaning the data/merging matching stations/mege.py | 3,031 | 3.5625 | 4 | # this code to find the matched stations
from difflib import SequenceMatcher
import csv
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
# the source file of the buses and it's stations
source_file = open("bus_and_stations.csv","r")
accepted_file = open("accepted.txt","r+")
rejected_file = open(... |
fcb504892d3fa7832dfca7f6689ec9d94086d625 | TheGrateSalmon/Side-Projects | /Word Finder.py | 349 | 4.125 | 4 | def main():
text = input("Enter a string or 'done' to quit: ")
while text != "done":
print()
text_list = text.split()
index = int(input("Which word place? ")) - 1
print("The word is:", text_list[index])
print()
text = input("Enter a string or '... |
9daaef13d5a842215165b4e744d0357f856f1ffe | uisandeep/ML-Journey | /Numpy/Numpy.py | 3,064 | 4.46875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 2 10:33:42 2020
@author: sandeepthakur
"""
#Array Creation
import numpy as np
#from a regular Python list or tuple using the array function
a = np.array([2,3,4])
print(a)
print(a.dtype)
b = np.array([1.2, 3.5, 5.1])
print(b.dtype)
print("-----... |
fac2d17a79f63eb6dc28db15f89e4e7ec9ea8345 | uisandeep/ML-Journey | /python/regex.py | 980 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 10 17:14:30 2020
@author: sandeepthakur
"""
import re
str1 = "Python is awesome used for scientific data manipulations"
if(re.search("awesome", str1)):
print("search found")
else:
print("search not found")
str1 = "Python is awesome. P... |
8b5228200cc0bf5b91734bcda66e5cac6e853194 | mauropappaterra/ML-Home-Exam | /sampleMean.py | 708 | 3.53125 | 4 | # Home Exam Machine Learning
# sampleMean.py
# Created by Mauro J. Pappaterra on 19 of May 2019.
def sampleMean (data):
"""A non-recursive solution approach"""
total = 0
for n in data:
total += n
return total / len(data)
def sampleMeanRecursive (data, x):
"""A recursive solution approach"... |
e76185b27e99408125916f218f9b68c69e86e05b | sokeyo/AI-Programming- | /Grad_descent_final.py | 653 | 3.765625 | 4 | import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
import pandas as pd
df = pd.read_csv('C:\School\Yr2-1-Semester\AI-Programming\python\Assignment\population_vs_profit.txt', names=['x','y'])
x = pd.DataFrame(df, columns=['x... |
14573b30a65f6a9d15852cce14f8d8854ab2342a | MartijnPY033/Opdrachten-Python | /Les 4/Final_Assignment NS-functies.py | 1,235 | 3.71875 | 4 | print ('Dames en Heren, Welkom bij de kostenberekener van de NS')
print('Om u zo goed mogelijk van dienst te zijn hebben wij deze rijskosten berekener gemaakt.')
input('Druk op enter om door te gaan: ')
input()
afstand = eval(input('Dien hier het aantal KM in dat je gaat reizen: '))
def standaardprijs(afstandKM):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.