blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
1cdb8b5bc45783cb17c1365884d9f5a18db94e2f | raghuprasadks/sindhi-python-aug-2021 | /day7/3-assignment.py | 379 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
1. Create a class called Product
having attributes
code,name,desc,manu,price
having following methods
addProduct(self,code,name,desc,manu,price)
displayProduct(self)
return product attributes
2. show the product having maximum price
3. show all products of a spe... |
211301423c62e1082b0bc261be6f7fcca5e9189d | raghuprasadks/sindhi-python-aug-2021 | /day9/1-createtable.py | 303 | 3.59375 | 4 | import sqlite3
conn = sqlite3.connect('olympicsdb.db')
conn.execute('''
CREATE TABLE if not exists olympics (
location TEXT,
year INTEGER,
country TEXT,
gold INTEGER,
silver INTEGER,
bronze INTEGER,
total INTEGER
)
'''
)
print('table created successfully')
conn.close()
|
839946a7d28885e51edacabbd322e58eef806004 | raghuprasadks/sindhi-python-aug-2021 | /day8/2-filemanagement.py | 714 | 4.09375 | 4 | """
File management
Modes
w - write mode - existing content will be deleted
a - content gets added to the existing file
r - read content of a file
"""
file=open("olympics.txt","w")
file.write("Olympics 2020 was held in japan \n")
file.write("More than 170 countries participated in it")
file.close()
file=open("olympic... |
7823d45c55eedbfeda27499fb09e0a528313165b | raghuprasadks/sindhi-python-aug-2021 | /day4/1-listdemo.py | 615 | 4.0625 | 4 | """
List -
Dynamic array
It allows duplicate values
It maintains the order of insertion
Elements can be accessed using index
"""
runs =[10,40,50,60]
print('runs -list ',runs)
print('runs -list - data type ',type(runs))
#<class 'list'>
print("list length ",len(runs))
'''
Adding an element
'''
runs.append(35)
print("aft... |
517b57af6476e831869f798356ab0e7c57c0be3d | Nav-31/Zest-to-Conquer | /Hackerrank/Problem Solving/DiagonalDiff.py | 416 | 3.671875 | 4 |
def diff(n,ar):
s1=0;s2=0
for i in range(n):
s1=s1+ar[i][i]
s2=s2+ar[i][n-1-i]
d=abs(s1-s2)
return d
n=int(input("Enter the size of matrix:"))
ar=[]
for i in range(n):
a=map(int,input().split()) ... |
f7e5eeb733fe6521f57a9e47bf2fd96e87e1494c | Nav-31/Zest-to-Conquer | /Hackerrank/Problem Solving/UthopianTree.py | 254 | 3.75 | 4 | def uthopianTree(n):
h=1
for i in range(1,n+1):
if(i%2!=0):
h=h*2
else:
h=h+1
return h
tc=int(input("Enter d no. of TestCases:"))
for i in range(tc):
n=int(input())
print(uthopianTree(n))
|
4d9e426e1ff609fb3dd95fb8f42df70221da55e4 | neelitummala/swarmrouting | /Point.py | 730 | 3.640625 | 4 | import math
import numpy as np
class Point:
def __init__(self, x, y):
# x and y are integers
self.__x = x
self.__y = y
def getX(self):
return self.__x
def getY(self):
return self.__y
def distanceToPoint(self, other_point):
dx = sel... |
6c0e983ee912c4df1cd54aba6d832f74b1b46d88 | suliemanmeq/MCSA | /regression.py | 2,460 | 3.65625 | 4 | print(__doc__)
# Code source: Jaques Grobler
# License: BSD 3 clause
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
# Load the diabetes dataset
diabetes = datasets.load_diabetes()
# Use only one feature
diabet... |
b320d9d84c7377bd3d2ac6b959b8b8798016da69 | asaidomar/euler-project | /problem_27.py | 2,992 | 3.546875 | 4 | # -*- coding: utf-8; -*-
#
# 2019-05-31
def primes_formula(a, b, n):
return n ** 2 + a * n + b
def get_primes(limit):
candidates = set(range(2, limit))
for i in range(2, limit):
candidates.difference_update({i * n for n in range(i, limit)})
return candidates
def primes_below(end):
if e... |
27d96e595a2cb0560c0c22c075244e3dbd61ef88 | asaidomar/euler-project | /problem_31.py | 989 | 3.796875 | 4 | # -*- coding: utf-8; -*-
#
# 2019-06-02
tree = [1, 2, 5, 10, 20, 50, 100]
count = 0
# credit https://medium.com/@jschapir/coinsum-algorithm-for-dummies-e3f73394bc11
def coinsum(total):
count = 0
def make_change(current_total):
nonlocal count
if current_total == total:
count += 1
... |
c16a82ce52dada89b2470f62bdd9d5ec3fab42e1 | asaidomar/euler-project | /problem_14.py | 755 | 3.75 | 4 | import math
memoize_dict = {}
def step(start):
if start % 2 == 0:
start = int(start / 2)
else:
start = 3 * start + 1
return start
def is_power_of_two(number):
value = math.log(number, 2)
return math.floor(value) == math.ceil(value)
def cycle_len(start):
c = 1
while st... |
9bc6d0914b96d338ebfb8436fec4d9561968b1c0 | Pogorelov-Y/python-project-lvl1 | /brain_games/games/brain_gcd.py | 946 | 3.890625 | 4 | import random
from fractions import gcd
def make_data():
"""Make two random natural numbers"""
number1 = random.randint(1, 100)
number2 = random.randint(1, 100)
return {
"number1": number1,
"number2": number2,
}
def get_number1(data):
"""Return random natural numbers"""
r... |
3df5b1c94a03d38aa3313e0e118dbfc6176afa28 | babint/AoC-2020 | /05/part2.py | 1,303 | 3.671875 | 4 | #!/usr/bin/env python3
import sys
import re
seats = []
rows = 128
cols = 8
def caluate_id(row, col):
return (row) * 8 + (col)
def calculate_seat(instructions, rows, cols):
# Seat set
plane_rows = list(range(0, rows))
plane_cols = list(range(0, cols))
# halve the seat set based on instruction
for instr in ... |
0be5483f9dc0a3a9b03dacd612fa84a2786449be | babint/AoC-2020 | /01/part1.py | 636 | 3.921875 | 4 | #!/usr/bin/env python3
import sys
numbers = []
found = -1
# Usage
if len(sys.argv) != 2:
print("usage: part1.py input.txt")
exit(1)
# Read File + Get Numbers
with open(sys.argv[1]) as f:
data = f.read().splitlines()
for num in data:
numbers.append(int(num))
# Start
for i, num1 in enumerate(numbers):
if (fo... |
5b2e58bb92df6134906050ca74148d5c52f893de | ArturSargsyans/Trees | /BST.py | 1,845 | 3.90625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.right = None
self.left = None
class BST:
def __init__(self):
self.root = None
def __str__(self):
if self.root == None:
return "empty"
else:
return str(self.root... |
c5333727d54b5cb7edff94608ffb009a29e6b5f4 | nikita5119/python-experiments | /cw1/robot.py | 1,125 | 4.625 | 5 | # A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# The numbers after the direction are steps. Please write a program to compute the distance ... |
6e468bf7c8d0d37233ee7577645e1d8712b83474 | TameImp/compound_interest_app | /test_calc.py | 929 | 4.125 | 4 | '''
this programme test the compound interest calculator
'''
from calc import monthly_compounding
def test_tautology():
assert 3 == 3
#test that investing no money generates no returns
def test_zeros():
#initialise some user inputs
initial = 0
monthly = 0
years = 0
annual_rate = 0
#calcu... |
908b570380df3572cb18391937b7a8cdfc733dff | vurpo/e-resepti | /models.py | 2,218 | 3.890625 | 4 | """
This module contains the classes that represent the recipe book and recipe, used in the application.
"""
class RecipeBook:
"""
Represents a recipe book (collection of recipes)
"""
def __init__(self, recipes):
self.recipes = recipes
@classmethod
def from_json_list(cls, recipebook):
... |
2325c94dd4abf0c95ab0b4cc39dc1fb80156eaa4 | eliezeravihail/heap | /simple_use_heapsort.py | 306 | 3.765625 | 4 | import heap as H
def heapSort(arr):
heap = H.heap()
for i in arr:
heap.push(i)
for i in range(len(arr)):
arr[len(arr)-1-i] = heap.popMax()
"""#use:
x= [23,2,454,6,8787,3]
heapSort(x)
print(x)
#======== output: =============
[2, 3, 6, 23, 454, 8787]
"""
|
1f7e272130cff2ed0494cde01bd77119fef2164a | xjtushilei/python_dots_game | /factory.py | 4,605 | 3.875 | 4 | """Factory classes for Dots & Co game
While quite concise, the purpose of these classes is to manage creation of instances (of dots, etc.). By having a
class managing this process, hooking into and extending this process becomes quite simple (through inheritance). This
allows for interesting things to be done, such as... |
5c6905ae0f3d93a0f4f21be897c926faa79f275e | ocaballeror/AdventOfCode2018 | /6/sol1.py | 1,138 | 3.796875 | 4 | from collections import defaultdict
from common import manhattan
from common import all_points
from common import start_x, end_x, start_y, end_y
def nearest_point(coord):
nearest = None
smallest = float('inf')
duplicate = False
for point in all_points:
distance = manhattan(point, coord)
... |
4ee50f47fa7f3ecdb44b1e62be1bc645df218490 | ocaballeror/AdventOfCode2018 | /13/sol1.py | 1,368 | 3.921875 | 4 | """
DAY 13
The map is represented as an array, containing all the track pieces, using
their original character representation, with a few exceptions:
1. The carts are removed from the map and stored in a separate array.
# 2. Empty space is replace by an empty string for easier conversion to bool.
3. Empty ... |
615539c38a067d3e739360dd6b4c1e8241281286 | timush-a/praxise | /test_regexp.py | 1,127 | 3.5625 | 4 | from regexp import SimpleMathematicalOperationsCalculator as Calculator
one_variable = 'a-=1a+=1a+=10a+=a'
three_variables = 'a=1a=+1a=-1a=ba=b+100a=b-100b+=10b+=+10b+=-10b+=bb+=b+100' \
'b+=b-100c-=101c-=+101c-=-101c-=bc-=b+101c-=b-101'
raw_data = 'saf nahu haou fhj sf,aa134%...jfbak fa sd fb+=as... |
b78774d35a8f939c8ef3ea6511adb463a1a5996b | zhaoyang6943/Python_JiChu | /day06/01 可变不可变类型.py | 1,191 | 3.6875 | 4 | # 可变不可变类型,进行区分
"""
整形、浮点型、字符串、列表、字典、布尔
"""
# 可变类型:值改变、id不变,证明改的是原汁,证明原值是可以被改变的
# 不可变类型:值改变,id不变,证明是产生的是新的值,压根没有改变原值,证明原值是不可以被修改的
# 2. 验证
# 2.1 int是不可变类型
x=10
print(id(x))
x=11 # 产生新增
print(id(x))
# 2.2 float是不可变类型
y=10.5
print(id(y))
y=11.5 # 产生新增
print(id(y))
# 2.3 str是不可变类型
z="123asd"
print(id(z))
z="456... |
3cd051bbb49fc8bed3359a5c4bfedb2b8d8d5667 | DMfananddu/Kristina-s | /courser.py | 3,117 | 3.671875 | 4 | from random import randint, random, choice
class Course(object):
"""
Курс - набор уроков (от 4 до 16) по определенной Тематике;
Тематика - одна из списка тематик
Урок - объект, имеющий след. характеристики:
Номер в курсе
Тип урока:
Видео (долгое, среднее, короткое)
... |
a39844f0165749d52821e3ce256af15dc90f833c | gruve-p/haitech | /programming/python/combinatorics/bellnumber/bell.py | 799 | 3.5625 | 4 | #!/usr/bin/env python
#binomial coefficient
def ksub(n,k):
if k<=0 or k==n:
return 1
elif k<0 or n<0 or k>n:
return 1
else:
return (ksub(n-1,k-1)+ksub(n-1,k))
#how many ways to partition [n] into k cells
#each cell are mutex and their union is [n]
def stirling(n,k):
if n==k:
... |
490a659e150f79c7557abe84b440425ba81ca395 | Sbeir/Python_SQLite_Exam | /esame_ufs01/Biblio/create_table.py | 4,110 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 19 16:45:19 2021
@author: RobertoFormenti
"""
import sqlite3
from sqlite3 import Error
#connette al file biblio.sqlite se esiste se no lo crea
conn = sqlite3.Connection('file:biblio.sqlite?mode=rwc', uri=True)
def create_table(conn, create_table_sql): #f... |
e0ee6d13b199a167c7cf72672876ff5d4b6e1b99 | LuisPereda/Learning_Python | /Chapter03/excercise1.py | 420 | 4.1875 | 4 | # This program parses a url
url = "http://www.flyingbear.co/our-story.html#:~:text=Flying%20Bear%20is%20a%20NYC,best%20rate%20in%20the%20city."
url_list = url.split("/") # Parsing begins at character (/)
domain_name = url_list[2] # Dictates at which character number parsing begins
print (domain_name.replace("www.",... |
78b34f6a6d9a9048ee5a35146749f9a6c4440875 | LuisPereda/Learning_Python | /Chapter10/default_dict_example4.py | 206 | 3.515625 | 4 | from collections import defaultdict
game = defaultdict(int)
list1 = ['cricket', 'badminton', 'hockey' 'rugby', 'golf', 'baseball' , 'football']
for each in list1:
game[each]= game[each]+1
print game |
40a6ece982e5369eaed63f84061c204f53023ce4 | stoneape314/AdventOfCode2019 | /2019_day2_pt2_intcode.py | 5,469 | 3.546875 | 4 | '''
Advent of Code 2019, Day 2, Pt2
An encoding problem with list input of ints that's an analogy for
assembly language.
Intcode programs work in blocks of 4 numbers at a time, with 3 commands
1: tells you to take the numbers at the indices of the next two numbers,
add them, then place the result at the 3rd... |
1c33398ed7c5a35041c81e9ba808d38fb603ef25 | pombreda/anacrolix | /various/project-euler/problem1.py | 116 | 3.75 | 4 | #!/usr/bin/env python
sum = 0
for n in xrange(1, 1000):
if not n % 3 or not n % 5:
print n
sum += n
print sum
|
796d95af7e23bc1727f7e0ae171d7dbf559f825d | pombreda/anacrolix | /university/pymd/demos/tictac.py | 3,756 | 3.84375 | 4 | ## 3-D tictactoe Ruth Chabay 2000/05
from visual import *
from tictacdat import *
scene.width=600
scene.height=600
scene.title="3D TicTacToe: 4 in a row"
# draw board
yo=2.
base=grid (n=4, ds=1, gridcolor=(1,1,1))
base.pos=base.pos+vector(-0.5, -2., -0.5)
base.radius=0.02
second=grid(n=4, ds=1... |
c592d1c17eb39b646b8a144249a27e521f86b56a | ColeB2/Snake | /snakeObject.py | 4,776 | 3.75 | 4 | '''
snakeObject.py - Main class for snake and food objects
'''
import math
import pygame as pg
from pygame.locals import *
from pyVariables import *
import random
'''SNAKE CLASS'''
class Snake():
def __init__(self, x=START_X, y=START_Y):
self.x = x
self.y = y
self.eaten = 0
self.po... |
52062e9097e26c678d957bf732615e1138d08de2 | OsnovaDT/Grokking-Algorithms | /k_nearest_neighbours_algorithm.py | 2,888 | 3.796875 | 4 | '''Code for task in chapter 10'''
from collections import namedtuple
from math import sqrt
def get_the_most_similar_parameter(
parameter, other_parameters):
'''Get the most similar parameter'''
# The most similar parameter and his difference with parameter's values
the_most_similar_parameter = ... |
b412d0a61cf0122d340d79c6ea076c61c814549e | OsnovaDT/Grokking-Algorithms | /chapter_9.py | 4,136 | 4.21875 | 4 | '''Code for tasks from chapter 9'''
from collections import namedtuple
ThingForGrab = namedtuple(
'Thing_for_grab',
['weight', 'price']
)
def print_prices_matrix(prices, subjects_names):
'''Prints prices in a beautiful way with their string's names'''
max_len_for_name_in_string_names = len(max(
... |
06863f77ce80ac75a5c43e30b31efd91b81fefd8 | FernnandoSussmann/PyCalculator | /Operation.py | 1,879 | 3.953125 | 4 | class Operation(object):
def __init__(self,operation_type, value1, value2, result):
self.operation_type = operation_type
self.value1 = value1
self.value2 = value2
self.result = result
def get_operation_type(self):
return self.operation_type
def get_value1(self):
return self.value1
def... |
9448f1cc26fecc85c8b5f39ac8b029e66021f394 | popposs/ProjectEuler | /q36/q36.py | 702 | 3.671875 | 4 | import timeit
def to_binary(n):
return "{0:b}".format(n)
def digits(n):
return map(int, str(n))
def is_palindromic(n):
d = digits(n)
length = len(d)
end = int(length / 2) + (length % 2 == 0)
for i in xrange(end):
if d[i] != d[length - i - 1]:
return False
d = digits(t... |
43cfed3d199b536a9450f4021ddc18b15e2bbdfa | itisdhiraj/Simple-Chatty-Bot | /Problems/Very odd/task.py | 110 | 3.71875 | 4 | a = int(input())
b = int(input())
result = a // b
if result % 2 == 0:
print(False)
else:
print(True)
|
5663034bdb0f71931aeb1112d91972beb8442bb2 | mannaf/Python_docs | /Chapter 9/Object_Methods.py | 204 | 3.6875 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfun(self):
print("Hello my Name is " + self.name)
p1 = Person("Johan", 36)
p1.myfun()
|
e1934bcda23f7563d1cb6e220901682f0ce7c881 | mannaf/Python_docs | /Chapter 9/inheritance_add_prop.py | 391 | 3.828125 | 4 | class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.greaduationyear... |
9aa73c6303a6ea7fe63841bc56352f020b73be05 | SuperCowPowers/zat | /zat/utils/file_storage.py | 5,197 | 3.640625 | 4 | """FileStorage class for storing/retrieving bytes to/from persistant storage
Methods:
- store(key, bytes): Takes a bytes object as input
- get(key): Returns a bytes object
"""
import os
try:
import pyarrow # noqa F401
_HAVE_PYARROW = True
except ImportError:
print('pyarrow not found... |
7230c582168abaff0ca797c95cf8c5a5cb7756be | saunders-jake/EaglePing | /eagleping.py | 2,703 | 3.546875 | 4 | from pythonping import ping
from time import sleep, localtime, strftime
import sys, time
print("##########################")
print("........EAGLE PING........")
print("##########################")
print(" Made by: Jake Saunders ")
print("##########################\n")
logpath = "output.txt" #Path to your desired out... |
4efdb253e77e395072a91db9407b4896a5121edb | chintanvijan/Data-Structures | /python/stack.py | 1,028 | 4.09375 | 4 | class node:
def __init__(self,dataval):
self.dataval=dataval
self.nextval = None
class stack:
def __init__(self):
self.headval = None
def push(self,dataval):
if self.headval == None:
self.headval = node(dataval)
else :
t = self.headval
self.headval = node(dataval)
self.headval.... |
6ea1039b8aabd3cf03922cbd6cbb81c9eb7fbbe5 | ordros/Euler | /problem12.py | 573 | 3.640625 | 4 | from math import sqrt, ceil
def count_divisors(N):
fact = 1
j = 0
max = ceil(sqrt(N))
if N >= 3:
while N!=1 and N%2==0:
j += 1
N /= 2
i = 3
fact *=(j+1)
j = 0
while N!=1 and i<=max:
while N!=1 and N%i==0:
j += 1... |
3fedb6049e642132bc3d056ff6c1631bbcd282fe | CA2528357431/python-note-re | /07/main.py | 902 | 3.78125 | 4 | import re
#零宽断言
#即可修饰匹配内容前后的内容,又可以修饰要匹配的内容
a='word wow woawo wo w wasting aworow walling arrrw'
x=re.compile(r'\b\w+(?=ing\b)')#匹配 \b\w+ 此\w+后方必须是ing\b
xx=x.findall(a)
print(xx)
#正预测零宽断言,对后续部分的要求
# 形式为(?=结构)
x=re.compile(r'(?<=\bwo)\w+\b')#匹配 \w+\b 而且\w+前方必须是\bwo
xx=x.findall(a)
print(xx)
#正回顾零宽断言,对之前部分的修饰
# 形式为(... |
cca792b806acb6de02f602c55746873161c513b3 | witters9516/CSC-221 | /Examples/m2_vowel_finder.py | 648 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 25 12:16:24 2017
@author: norrisa
"""
def findVowels(word):
vowels = ['a', 'e', 'i', 'o', 'u']
found = []
for letter in word:
if letter in vowels:
print(letter)
def findVowelsV2(word):
vowels = ['a', 'e', 'i', 'o', 'u']
found = []... |
57ca2c5a050d5194c1ba7e935c81ccd0a888d501 | witters9516/CSC-221 | /test.py | 1,562 | 3.78125 | 4 | def main():
title = 'a clash of KINGS'
minor_words = 'a an the of'
officialTitle = title_case(title, minor_words)
print(officialTitle)
def title_case(title, minor_words):
# print(title)
titleWordList = list()
minorWordList = list()
officialTitle = ""
if title != '':
pr... |
260d5caa5d4ea343e7d356ab693761dd99f0677f | zilongxuan001/LearnPythonhandbook | /ex201012_20201012.py | 244 | 3.859375 | 4 | number = int(input())
num = len("Hello World")
HW =("Hello World")
j = 0
if number == 0:
print("Hello World")
elif number > 0:
while j < num:
print(HW[j:j+2])
j +=2
else:
for i in "Hello World":
print(i)
|
7e38dc101f8ef9007499f15cc251ce89984123f3 | zilongxuan001/LearnPythonhandbook | /single_20201106.py | 3,781 | 3.609375 | 4 | import turtle,time
def drawGap():
turtle.penup()
turtle.fd(5)
def drawLine(draw): # 处理单个行
drawGap()
turtle.pendown() if draw else turtle.penup()
turtle.fd(40)
drawGap()
turtle.right(90)
def drawDigit(digit): # 处理单个字符
drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False)
... |
274f872cd115a67a51d260296ba6f97189b23d10 | zilongxuan001/LearnPythonhandbook | /forElse_20200922.py | 115 | 3.703125 | 4 | # forElse
for c in "PYTHON":
if c == "T":
continue
print(c, end="")
else:
print("正常退出") |
c7f9d7a7c4f6a8343014e75a01570c46ed2e32eb | zilongxuan001/LearnPythonhandbook | /circles_20200917.py | 333 | 3.671875 | 4 | # circles
import turtle as t
t.pencolor("pink")
t.left(90)
def main():
for i in range(10):
t.circle(10,360)
t.penup()
t.fd(20)
t.pendown()
t.penup()
t.right(180)
t.fd(200)
t.left(90)
t.fd(20)
t.left(90)
t.pendown()
for i in range(10):
main... |
dba14cc9b716dcedab90012a8b47257f05fe47e7 | zilongxuan001/LearnPythonhandbook | /ex16_01_20200902.py | 613 | 3.765625 | 4 | from sys import argv
script, filename = argv
print("Let's open the file:")
target= open(filename, 'r+')
print("Let's erase the content.")
target.truncate()
print("Let's write something")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
target.write(line1)
target.write("\n")
target... |
0f59c8d732fd9bedc415c135a372acc743d5d961 | zilongxuan001/LearnPythonhandbook | /ex13_02_20200831.py | 156 | 3.65625 | 4 | from sys import argv
a,x,y,z = argv
print(f"the first is {x}")
print(f"the second is {y}")
print(f"the third is {z}")
print(input("What you want is ")) |
fdad515316880c87f37637b0c1d7ff37a4e833da | L200170122/prak_ASD_D | /Modul_6/partisi.py | 1,033 | 3.734375 | 4 | def partisi(A, awal, akhir):
nilaiPivot = A[awal]
penandaKiri = awal
penandaKanan = akhir
selesai = False
while not selesai:
while penandaKiri <= penandaKanan and A[penandaKiri] <= nilaiPivot:
pendanaKiri = penandaKiri + 1
while A[penandaKanan] >= nilaiPivot... |
82a1ab1412c029fe3b789e1b67909ed731cf910e | NickLuGithub/school_homework | /Python/期中考/b10702057-期中考2.py | 930 | 3.515625 | 4 | import time
import random
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
op = input("請輸入Y開始遊戲")
print(list1)
t0 = time.time()
while op == 'y' or op == 'Y':
for i in range(0, 10):
k = random.randrange(0, 26)
... |
61e27a466ee3a9d70062faf23f32d2a5ec427c7c | NickLuGithub/school_homework | /Python/課堂練習/b10702057-課堂練習3-1-1.py | 1,755 | 4.15625 | 4 | print("第一題");
print(1 == True);
print(1 == False);
print();
print(0 == True);
print(0 == False);
print();
print(0.01 == True);
print(0.01 == False);
print();
print((1, 2) == True);
print((1, 2) == False);
print();
print((0, 0) == True);
print((0, 0) == False);
print();
print('string' == True);
print('s... |
d6aead41f21280a466324b5ec51c9c86a57c35e6 | NickLuGithub/school_homework | /Python/課堂練習/b10702057-課堂練習7-1.py | 802 | 4.15625 | 4 | print("1")
list1 = [1,2,3,4]
a = [5, 6, 7, 8]
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("2")
list1 = [1,2,3,4]
a = 'test'
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("3")
list1 = [1,2,3,4]
a = ['a', 'b', 'c']
... |
2e424f94449de9f18669616d112303960228afe4 | NickLuGithub/school_homework | /Python/課堂練習/b10702057-課堂練習6-1.py | 138 | 3.59375 | 4 | a = "天增歲月人增肉,春滿乾坤福滿身"
for i in a:
if ( i == ","):
print(' ');
else:
print(i); |
9aff0ff67604c76da2cec2fe4ea16c7ac7f889d9 | kaushik246/python-concepts | /src/arg_parse.py | 658 | 3.578125 | 4 | # arg_parse.py
import argparse
def get_args():
""""""
parser = argparse.ArgumentParser(
description="A simple argument parser",
epilog="This is where you might put example usage"
)
parser.add_argument('-arg1', '--argument1' , action="store", required=True, help='Help for o... |
8a3dde8254a203250f68e450a793fc43f8b9ccad | JaredQR/CruceroPorElCaribe-Programacion2 | /modulo.py | 6,568 | 3.5625 | 4 | #PUERTOS#
def anadirpuertos():
import sys, os, sqlite3
con = sqlite3.connect('DISENHO.s3db')
puer=input("Ingrese el puerto :" )
pai=input("Ingrese el pais : ")
os.system('cls')
cursor=con.cursor()
cursor.execute("insert into TABPUERTOS(puertos, pais) values ('"+puer+"','"+pai+"')")... |
b17b98417dd5426278864a106cb22b7f7b2ba0ec | JNewberry/Lists | /List Rev 2.py | 351 | 3.953125 | 4 | #John Newberry
#
#List Rev 2
name_list = []
order = 0
for count in range(6):
order + 1
name = input("Please input a name: ")
name_list.append(name)
print(name_list)
while 1:
print("Please input the names you wish to view")
view = int(input("From: "))
end_view = int(input("To: "))
... |
b6cb4e5b3387f132abd793de8a7c79d719bef2e2 | aspcodenet/iot_StefanIfLabbar | /PythonLabbarIf/Labb6.py | 239 | 3.828125 | 4 |
age = int(input("Ange ålder"))
if age >=1980 and age < 1990:
print("Du är född på 1980-talet")
elif age >=1990 and age < 2000:
print("Du är född på 1990-talet")
else:
print("Du är inte född på 1990 eller 1980-talen") |
58de770241c64ab5294eac22884c104814b61bd4 | mfligiel/Capstone_Text_Mining | /capstone_text_mining/graph_viz.py | 1,043 | 3.75 | 4 |
import networkx as nx
from matplotlib import pyplot as plt
def graphviz(graph, edgecolor='grey', nodecolor='purple'):
"""
Parameters
----------
graph : graph object
A graph object prepared by the graphprep function
edgecolor : string
Optional color selection for visualization
nod... |
a898631d48a06defcbdad0a66c6d9cd4d6f96e3b | jwon/adventofcode | /2021/12/p1.py | 1,062 | 3.75 | 4 | from pprint import pprint
caves = {}
with open('input.txt') as f:
for line in f:
cave, connected_to = line.strip().split('-')
if cave in caves:
caves[cave].add(connected_to)
else:
caves[cave] = {connected_to}
if connected_to in caves:
caves[conne... |
3edc431c6167d5f8715dccc885d4cb5ba81e4e9b | iubica/tickerscrape | /scrape/web.py | 2,654 | 3.515625 | 4 | """
Routines for caching web queries
"""
import requests
from bs4 import BeautifulSoup
import pandas as pd
import six
_web_cache = dict()
def get_web_page(url, force):
"""
Gets a web page from the web, or from the local cache, in case it is cached.
Arguments:
url - the URL to retrieve
force - if ... |
13e937ebfdb6866b60dc3aa4f3b96b8d4744e07c | confar/algorithms_stepik | /course_1_algorithms/dynamic/calculator.py | 1,067 | 3.796875 | 4 | import math
from collections import deque
def calculate_steps_from_number_to_one(number):
operation_list = deque([number])
step_list = [0] + [math.inf for _ in range(number)]
prev_list = [math.inf for _ in range(number)]
if number != 1:
for num in range(1, number):
for value in (nu... |
9c645cb9fc290a59f8cf438c7e96deb994303992 | confar/algorithms_stepik | /course_2_data_structures/hash_tables/chaining_hashmap.py | 4,172 | 3.625 | 4 | import io
from functools import partial
from typing import List
class NotFound(Exception):
pass
class ListElem:
def __init__(self, value: str) -> None:
self.value = value
self.next = None
class LinkedList:
def __init__(self) -> None:
self.head = None
self.size = 0
... |
a4e06672b939e6fe8c2769c5fcc1e8670f774b1e | confar/algorithms_stepik | /course_1_algorithms/dynamic/editing_distance.py | 1,255 | 3.5 | 4 | import math
def diff(char1, char2):
return 1 if char1 != char2 else 0
def _edit_distance(distance, i, j, str1, str2):
if distance[i][j] == math.inf:
if i == 0:
distance[i][j] = j
elif j == 0:
distance[i][j] = i
else:
insert = _edit_distance(distanc... |
2e9b857a824c9da9b12923a39882047606052698 | cristhianfdx/console-crud-python | /console-crud.py | 10,958 | 3.515625 | 4 | # -*- coding=utf-8 -*-
'''
@author: Cristhian Alexander Forero
'''
import sqlite3
import os
import re
db_name = 'students.db'
def print_menu():
print('''
OPERACIONES BÁSICAS CON SQLITE
1. Crear Base de Datos.
2. Crear tabla.
3. Insertar datos en la tabla.
4. Consultar to... |
64ab234863beaabbd6ca3b5ae30c84256c109736 | pmjonesg/FaceTracker | /Algorithms/webcam.py | 1,150 | 3.734375 | 4 | # This script performs face recognition and draws a green box around a detected face.
import cv2
import sys
# The argument this script takes is a haarcascade.xml file which contains face parameters to be recognized.
cascPath = sys.argv[1]
faceCascade = cv2.CascadeClassifier(cascPath)
# Start the capture
video_capture... |
652e5bd306bdaceec9f79d87234d5e74a08fa232 | Fir-lat/Fir-lat.github.io | /caidingke.py | 2,018 | 3.953125 | 4 | #猜丁壳
#导入库
from random import randint
#游戏介绍
def introduce():
print("这是一个石头剪刀布的游戏")
print("请点击开始进行游戏")
print("每赢一局分数加一,采取五局三胜制")
#获取输入
def got():
f = True
print("请输入“石头”或“剪刀”或“布”")
while f:
x = 0
n = str(input())
if n in ["石头"]:
x = 1
f = False
... |
8d9d4c73894c0a436707cfc316938de3c8805f78 | Fir-lat/Fir-lat.github.io | /chengji.py | 154 | 3.703125 | 4 | print('小明上学期成绩:')
a = int(input())
print('小明这学期成绩:')
b = int(input())
c = (a/b+1.0)*10
print('成绩提升百分点=%.1f%%'%c) |
db8073a8a852d31b0f7536dd9061b36416b689f2 | BursacPetar/GIS_programiranje_Domaci_zadatak | /GIS_programiranje_Vezba_br_2/GISP_Vezba_br_2_Zadatak_br_1_PetarBursac1540-16.py | 370 | 3.703125 | 4 | # Kodiranje skripta
# -*- coding: utf-8 -*-
# Zadatak br. 1
# niz = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# napisati program koji racuna sumu parnih elemenata niza
niz = input("Unesite niz u obliku: [x,x1,x2,...]")
suma_parnih = 0
for i in niz:
if i % 2 == 0:
suma_parnih = suma_parnih + i
print "Suma ... |
2fb46cfcde3579f8c17dad8ece07131a06ae8391 | Rekahani/tugas-praktikum5-6 | /lab2.py | 486 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 4 19:09:11 2020
@author: LENOVO i5
"""
a = eval (input("masukan nilai a: "))
b = eval (input("masukan nilai b: "))
hasil = a+b
print ("variable a = ",a)
print ("variable b = ",b)
print ("hasil penggabungan %d & %d = %d" % (a, b, hasil))
#konversi nilai variable
print (... |
d080eeac24b1847b2d0725a3175dce9ce2329680 | MaxHills/demo-git-conflict | /uobioinfo/main.py | 728 | 3.515625 | 4 | import argparse
def say_something(phrase): # ... I'm giving up on you.
"""Change this however you'd like!"""
print("testphrase1")
print(phrase)
print("testphrase2")
# --- Don't change anything below this line -------
def cli():
"""Command line interface"""
parser = argparse.ArgumentParser... |
11c90dbbfebfaaf74e1296a9378a1c40083e2f08 | orbital23/tensorflow-example | /playground-1/data_generator.py | 406 | 3.75 | 4 | import random
import math
def generate(numPoints):
result = []
for i in range(0, numPoints):
x = random.uniform(-6,6)
y = random.uniform(-6,6)
color = 1 if distance((0,0), (x,y)) < 3 else 0
result.append((x,y,color))
return result
def distance(pointFrom, pointTo):
diff = (pointTo[0] - pointFro... |
5e2c3645f39f57c882205c19014fe1142e836716 | Orenjonas/school_projects | /python/python_scripts/test_complex.py | 1,887 | 3.890625 | 4 | import math as m
from complex import *
def test_add():
"""
Test addition for Complex with Complex, complex, int and float
"""
z = Complex(1, -2)
w = Complex(1, 1)
assert (z + w) == Complex(2, -1)
assert (z + (1+1j)) == Complex(2, -1)
assert (z + 2) == Complex(3, -2)
asser... |
cd45d4f6b4705211c862908dfdc2256cf5380237 | smkell/adventofcode | /2016/day3/day3py/day3.py | 1,455 | 3.953125 | 4 | """Python Solution of Day 3 of the `Advent of Code <http://adventofcode.com/2016/day/3>`
"""
import sys
def valid_triangle(sides):
"""Return true if the given sides specify a valid triangle."""
return ((sides[0] + sides[1] > sides[2]) and
(sides[1] + sides[2] > sides[0]) and
(sides[0] ... |
8c90dd545d83437d8dc4be1a985779827851b7d2 | ydPro-G/Flask | /4_request,session,cookie,response/requrst_2.py | 889 | 3.578125 | 4 |
# 一个完整的HTTP请求,包含客户端的Request,服务端的Response,会话Session等
# 在Flask中使用这些内建对象:request,session,cookie
# 请求对象Request
from flask import request
from flask import Flask
app = Flask(__name__)
@ app.route('/login',methods=['POST','GET'])
def login():
if request.method == 'POST': # request中的method变量可以获取当前请求的方法
if re... |
510bb83032b4a31bb0e78773f72ba4f18a86f6b2 | NIshant-Hegde/Data-Science | /Spam_classifier_using _naive_bayes/Spam_classifier_using_Naive_Bayes.py | 3,469 | 3.875 | 4 | #Importing libraries
import os #To navigate between directories and files
import io #For file manipulation and management
from pandas import DataFrame #To create dataframes ... |
a51e999f87254fb12a0dbb2b84184fa6de6260a9 | MrComputingHound/pylot_python_belt_exam | /app/models/User.py | 3,683 | 3.546875 | 4 | """
Sample Model File
A Model should be in charge of communicating with the Database.
Define specific model method that query the database for information.
Then call upon these model method in your controller.
Create a model using this template.
"""
from system.core.model import Model
import re
... |
f8b8f879cccda263a09997fb5132ab52fa827e4a | liuduanyang/Python | /廖大python教程笔记/jichu.py | 1,733 | 4.3125 | 4 | # python编程基础
a = 100
if a >= 0:
print(a)
else:
print(-a)
# 当语句以冒号:结尾时,缩进的语句视为代码块(相当于{}内的语句)
# Python程序是大小写敏感的
# 数据类型和变量
'''
数据类型:整数
浮点数
字符串('' 或 ""括起来的文本)
"I'm OK"包含的字符是I,',m,空格,O,K这6个字符
'I\'m \"OK\"!' 表示的字符串内容是:I'm "OK"!
布尔值(在Python中,可以直接用True、False表示布尔值(请注意大小写),也可以通过布尔... |
1d6cafab3bfee249b8ab0ab04ab0cd94e5b5d506 | liuduanyang/Python | /廖大python教程笔记/fanhuihanshu.py | 3,364 | 3.703125 | 4 | # 返回函数
# 把函数作为结果值返回
# 返回一个求和函数
def lazy_sum(*args):
def sum():
ax=0
for i in args:
ax=ax+i
return ax
return sum
f=lazy_sum(1,3,5,7,9)
print(f())
# 25
# 解析:当我们调用lazy_sum(1,3,5,7,9)时 返回的sum sum指向具体的函数 赋值给f的也就是sum
# 当我们调用f 即f() 时也就是调用sum得到25 也就是说返回一个函数 并不立即执行这个
# 函数,只有调用时才执行
'''
f是函数(指向函数变量)
>>> f = lazy... |
ff6f55f92091a43f543d07553876fde61b780da8 | liuduanyang/Python | /廖大python教程笔记/diedai.py | 1,360 | 4.3125 | 4 | # 迭代 (Iteration)
# 如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代
# Python的for循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上 比如dict、字符串、
# 或者一些我们自定义的数据类型
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
# b
# a
# c
# 因为字典存储是无序的 所以每次得到的顺序可能会不同
# for key in d 迭代key-value的key
# for value in d.values() ... |
57cf0f1364b7d4d2c0c3f3b8a8c869be4f7a261a | liuduanyang/Python | /廖大python教程笔记/dict.py | 2,204 | 4.28125 | 4 | # 字典
# Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)
# 存储,具有极快的查找速度。这种查找速度都非常快,不会随着字典大小的增加而变慢
d={'Michael':95,'Bob':75,'Tracy':85}
print(d['Michael'])
# 95
# 除了上述初始化方法外,还可以通过key来放入数据
d['Adam']=67
print(d['Adam'])
print(d)
# 67
# {'Adam': 67, 'Michael': 95, 'Bob': 75, 'Tracy': 85}
# 一个key只能对应一个v... |
7b8b186ef4337434ab97a55d9687452f909add16 | nbtvu/Data-Structure---Python-Implementation | /BinarySearchTrees/SplayTree.py | 4,908 | 3.796875 | 4 | from collections import deque
class Node(object):
def __init__(self, val):
self.val = val
self.parents = None
self.left = None
self.right = None
def __str__(self):
return str(self.val)
def __repr__(self):
return str(self.val)
class SplayTree(object):
def __init__(self):
self.root = None
def find... |
b5bfd66f6760cb0cfd08db20638eeb4e2e1965cb | nbtvu/Data-Structure---Python-Implementation | /how_to_read_a_matrix_from_console.py | 374 | 3.796875 | 4 | #read matrix of size MxN
m, n = map(int, raw_input("Input the matrix size (row, column): ").split())
print "Input the matrix elements (row by row): "
a = [None] * m
for i in range(m):
a[i] = map(int, raw_input().split())
#print out the matrix
print "Print out the matrix:"
for i in range(m):
line = ""
for j in range... |
21b2c42a45579c3481867264ac4493c9e7f13e10 | tor1414/python_programs | /131_h1_validate_sudoku_solutions.py | 2,353 | 3.96875 | 4 | """
Victoria Lynn Hagan
Victoria014
1/30/2014
Homework 1 - CSC 131
Program that uses 2D lists to verify whether or not a Sudoku solution is valid
"""
def checkLst(lst):
"""returns True if lst (may represent row, column or a block) has the values 1 to 9"""
#replace pass by the necessary code
a =... |
900588802461bb57362293cb8118e4710704ee4c | IbroCalculus/Python-Tkinter-Codes-Snippets | /x/window_Size.py | 593 | 3.53125 | 4 | import tkinter as tk
root = tk.Tk()
root.title("This is my template")
root.config(bg='#123456')
root.resizable(width=True, height=True)
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
#x+y offset
#root.geometry("400x200+800+200")
root.geometry("%dx%d+%d+%d" % (screen_width, screen_... |
3a305255401e86963c00825ded481ca48ed93084 | sonyashkapa/Sonya-Shkapa | /gener.py | 7,012 | 4.21875 | 4 | """ This module contains methods and a function for tokenizing a string of characters
"""
import unicodedata
def making_array(str):
""" This function divides a string in a list of alphabetical substrings."""
i = 0
# set the array, in which each element will be the alphabetical chain
data = []
... |
36cacd0e4052782976eca85781b5fda9a4894256 | alexwaweru/graduate_algotithms | /dynamic_programming/change_maker.py | 986 | 3.828125 | 4 | """
@Author: Alex Waweru
"""
import timeit
def dynamic_programming_change_maker(coin_value_list, change, min_coins, coins_used):
for cents in range(change+1):
coin_count = cents
new_coin = 1
for j in [c for c in coin_value_list if c <= cents]:
if min_coins[cents-j] + 1 < coin_count:
... |
b3862bd1d09ec45f919afbd45d1ef61b1abb6d41 | yyj7647261/gittest | /day02-2-zuoye.py | 630 | 3.5625 | 4 | # 递归函数列出所有文件 使用os.listdir 列出目录内容 os.isfile 检测是否是文件
# 练习找出单个目录中的最大文件
# 练习找出目录树中的最大文件
import os
file=os.listdir() #列出所有文件
# print (type(file))
# print ("当前目录所有文件:"+str(file)) #累出当前目录中的全部文件
# #os.path.getsize(name) 获取文件大小
maxV = -float('inf') #正无穷:float("inf"); 负无穷:float("-inf")
for a in file:
f=os.path.gets... |
eac14658b397d716e836dc38952b6fad36039e36 | azh4r/online-sorting-algorithms | /LargestValues/DataFile.py | 1,520 | 3.75 | 4 | # Class with functions to get handle to a file and
# to read in a file.
# Update: This should also take in number of lines to read
# and return also that file has ended.
class DataFile:
def get_handle(file_location):
in_file = open(file_location, "r")
return in_file
# method to convert a ... |
76f4172c5d391106c5ac528a89aa84fc1f8cfab0 | dkaniu/Denis-Kaniu-Dojo-Project | /room.py | 1,850 | 3.640625 | 4 | """
Room Allocation System
Usage:
room.py create_room <room_name> <room_type>...
room.py add_person <person_name> <emp_type>...
room.py print_room <room_name>
room.py print_allocations [-o=filename]
room.py print_unallocated [-o=filename]
room.py reallocate_person <person_identifier> <new_room_name
room.p... |
d8fd909cb070443842cf901dd363efa7b0dda23d | prachichouksey/Array-1 | /238_Product_Except_Self.py | 2,634 | 3.75 | 4 | # Leetcode problem link : https://leetcode.com/problems/product-of-array-except-self
# Time Complexity : O(n)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach
'''
Basic appr... |
9a915e306d84c786fd2290dc3180535c5773cafb | schase15/cs-module-project-iterative-sorting | /src/searching/searching.py | 1,967 | 4.375 | 4 | # Linear and Binary Search assignment
def linear_search(arr, target):
# Go through each value starting at the front
# Check to see if it is equal to the target
# Return index value if it is
# Return -1 if not found in the array`
for i in range(len(arr)):
if arr[i] == target:
... |
24b9e0ca714e29c6bc0dc6e6ffff1b3204b877d7 | kthvg5/CS5200 | /Knights_Tour/dfs.py | 1,505 | 3.6875 | 4 | # Don't use odd libraries
# Open tour gets partial credit
# Not testing anything bigger than 8x8
import sys
import copy
import stack
class Node(object):
def __init__(self, neighbors, used):
self.neighbors = neighbors
self.used = used
def dfs(graph, path):
parent = path.top()
# print "pa... |
6d8c58321442d9390bb3b8a0e7beaa39621906b6 | dolevp/prime_numbers | /utils.py | 205 | 3.90625 | 4 | def two_or_odd_numbers_between(start, end):
if start == 2:
return [2, *range(3, end + 1, 2)]
range_start = start + 1 if start % 2 == 0 else start
return range(range_start, end + 1, 2)
|
f1679bebaaf3107cc013a30839c45746444bc44b | nzsnapshot/MyTimeLine | /1-2 Months/tutorial/Test Discord Code.py | 854 | 3.5625 | 4 | import importlib
def get_all_candidates(ballots):
'''(list)->list
Given a list of strings, a list of lists, a list of dictionaries, or a
mix of all three, this function returns all the unique strings in this
list and its nested contents.
([{'GREEN':3, 'NDP':5}, {'NDP':2, 'LIBERAL':4},['CPC', 'NDP'... |
34d610751d4a8d69513f394ae0f53ed178f4fb95 | nzsnapshot/MyTimeLine | /2-3 Months/non-tutorial projects/rockpaperscissors.py | 5,096 | 3.875 | 4 | import random
import time
SLEEP_BETWEEN_ACTIONS = 0.5
def checkRules(user):
print('This is a game of Rock, Paper and Scissors')
print('')
userRules = input('Do you know the rules of the game? ')
time.sleep(SLEEP_BETWEEN_ACTIONS)
var = userRules.lower()
if var == 'yes':
straightinto = p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.