blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
de99e1d9b18b48be0ea4c09e9b42418efd368682 | pdst-lccs/lccs-python | /Section 7 - Dictionaries/mean result v1.py | 544 | 3.984375 | 4 | # Event: LCCS Python Fundamental Skills Workshop
# Date: Dec 2018
# Author: Joe English, PDST
# eMail: computerscience@pdst.ie
# Purpose: A program to demonstrate the use of dictionaries to calculate the mean result
#A dictionary to store results for multiple students
results = {
'Joe': 67,
'Mary' : 7... |
62386c074957d2fab9a85ea17e967e3b27cdb759 | gxsoft/SkillShare---Python-3--Programming-in-Py-for-Beginners | /Jucu 01.py | 247 | 3.5 | 4 | print('-Jucu-'*50)
a = 10
print(a)
b = 'Hola 123456789-z'
print(a,b[0:2])
a = [1,2,3,4,5,6,7]
b = [8,9]
c = a + b
print(b+a,sum(c))
# a = 'Hola como te va'
if a>b:
print('a es mayor que b')
|
32bb910e9e8a0e047e4c01e823e6e1dbf0e11af6 | Naxthephantom/Python_Learning | /Binary Search Algorithm.py | 902 | 4.25 | 4 |
#Binary search algorithm
def binary_search(number, item):
left = 0
right = len(number) - 1
while left <= right:
middle = int((left + right) / 2) # middle tile
if item < number[middle]:
right = middle - 1
elif item > number [middle]:
left = middle +... |
c25a4216a7e75366a77fb5f8090d81dd75f8446c | basvasilich/leet-code | /264.py | 563 | 3.546875 | 4 | # https://leetcode.com/problems/ugly-number-ii/
from heapq import heappop, heappush
class Solution:
def nthUglyNumber(self, n: int) -> int:
h = []
d = set()
heappush(h, 1)
count = 0
next_num = 1
while count < n:
next_num = heappop(h)
heappu... |
3a70d48b3b3687f2a1cc64a54f21f1738bfb5b26 | meenapandey500/Python_program | /program/ex1.py | 539 | 3.890625 | 4 | #WAP to find the sum of 2 nos.
while(True):
try:
a=float(input("Enter Number a : "))
break #exit from loop
except ValueError:
print("Data Type Mismatch Error, Please Re-Enter numeric value of variable a : ")
print("Value of a : ",a)
while(True):
try:
b=int(input("... |
f51c2f594ac165224c40496383dbe8f6e0fbbc71 | CardinisCode/learning-python | /extra-course-practice-problems/delete_from_list.py | 3,231 | 4.25 | 4 | #Write a function called delete_from_list. delete_from_list
#should have two parameters: a list of strings and a list of
#integers.
#
#The list of integers represents the indices of the items to
#delete from the list of strings. Delete the items from the
#list of strings, and return the resulting list.
#
#For example:
... |
65b62cb43ae3445dade943da03cc789f0dd83a5f | sideroff/Softuni | /00_Other_Courses/01_Python/05_Exam_Preparation/15_Unique_Sales_By_City.py | 1,754 | 3.625 | 4 | import sys
import os
import iso8601
def file_check(file_path):
if (not os.path.isfile(file_path) or not os.access(file_path, os.R_OK)):
raise FileExistsError('Path is either a dir or cannot be accessed for reading')
def file_to_dict_of_cities(file_path):
dict_of_items = dict()
with open(file_path,... |
7fd3e9736f90af6cfe287b70cecfed99c8b15c36 | PaulWendt96/Markov_Visualize | /tempdir.py | 1,193 | 3.90625 | 4 | from contextlib import contextmanager
import os
import shutil
@contextmanager
def make_temporary_directory(path, dir_name, remove_if_already_exists=False):
''' create a temporary directory, do stuff with it, and remove it '''
assert os.path.isdir(path), "Error -- '{}' is not a directory".format(path)
... |
5ee303b8cd9171b7e5ea594af8628a54ad876377 | SmartCityLabs/Licence-Plate-Detection | /Licenceplate_identification/Logistic_regression/a_HOG_computation.py | 1,464 | 3.578125 | 4 | #-------------------------------------------------------------------------------
# Name: module2
# Purpose:
#
# Author: Sardhendu_Mishra
#
# Created: 04/03/2015
# Copyright: (c) Sardhendu_Mishra 2015
# Licence: <your licence>
#-----------------------------------------------------------------------... |
5a245698a46e3046f617c30fc4150707de41c22e | avik94/The-Whether | /run.py | 1,046 | 3.78125 | 4 | def x():
file = open("temp.txt",'w+')
file.write('city,country,month ave: highest high,month ave: lowest low\n\
Beijing,China,30.9,-8.4\nCairo,Egypt,34.7,1.2\nLondon,UK,23.5,2.1\
\nNairobi,Kenya,26.3,10.5\nNew York City,USA,28.9,-2.8\nSydney,Australia,26.5,8.7\nTokyo,Japan,30.8,0.9\n')
file.close()
... |
42fc258d24a33048771307150459357e29d03d14 | shellygr/Zookathon | /dbconnection.py | 1,426 | 3.515625 | 4 | import sqlite3
def initDB():
try:
conn = sqlite3.connect('photos.db')
c = conn.cursor()
c.execute('''CREATE TABLE photo
(photopath text,latitude number, longitude number, lables text, dateTaken text,endangeredStatus number)''')
conn.commit()
conn.close()
exce... |
401ebe39c1a84852792cd56972ad59b9529b69d2 | renlei-great/git_window- | /python数据结构/和刘亮讨论/快速排序.py | 759 | 3.546875 | 4 | lista = [12, 4, 5, 6, 22, 3, 43, 654, 765, 7, 234]
# lista = [78, 45, 984, 42, 5, 6, 22, 3 , 2]
def quick_sort(alist, start=None, end=None):
"""快速排序"""
if start is None and end is None:
start = 0
end= len(alist) - 1
if end - start <= 0:
return
l_cur = start
r_cur = end
... |
5f3b32d1809318284e670fa004f9870061cec906 | dukeofducttape/code-combat | /cloudrip-volcano-fighters.py | 1,072 | 3.59375 | 4 | # Complete the paladin rectangle to protect the village.
# This function finds the left-most unit.
def findMostLeft(units):
if len(units) == 0:
return None
mostLeft = units[0]
for unit in units:
if unit.pos.x < mostLeft.pos.x:
mostLeft = unit
return mostLeft
# This function... |
d725d2b54e95b43ee68ca08974caefdd72f2bc61 | bidahor13/Python_projects | /P3/Q1.py | 1,195 | 4.3125 | 4 | #AUTHOR: BABATUNDE IDAHOR
#COURSE: CS133
#TERM : FALL 2015
#DATE : 11/3/2015
#This program checks if two user input strings are anagrams of each other.
print('Project_3: Q1')
print('----------------------------------------------')
print('----------------------------------------------')
#Input values
word1 = str... |
16d74f0baf29cc997770b5dbb18314793161f3bb | patovala/ecuador-django-jquery | /validator.py | 1,713 | 3.828125 | 4 | #-*- coding: utf8 -*-
#------------------------------------------------------------------------------#
#---- ----#
#---- Validator testing functions ----#
#---- ... |
3b5bb7113c3a848ebdf2b90c1245789cf530a9ac | jakipatryk/aoc-2020 | /12/solution.py | 2,221 | 3.5625 | 4 | import fileinput
instructions = list(
map(lambda x: (x[0], int(x.rstrip()[1:])), fileinput.input()))
def manhattan_distance(x, y):
return abs(x) + abs(y)
def process_instructions_1(instructions):
facing = 0
x = 0
y = 0
move_forward = {
0: lambda v: (x + value, y),
1: lambda ... |
3ffbe91af56fcd941a0bfaa243d64eeb44e5f1d3 | YingXie24/Python | /Fundamental-Python/2-DNA-Processing/DnaProcessing.py | 3,133 | 4.28125 | 4 | def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1... |
797dea886c57ac0febaaade4e8f63162223a2496 | ZU3AIR/DCU | /Year1/prog2_python3/w10l2/maximum_102.py | 146 | 3.578125 | 4 | def maximum(x):
if len(x) == 1:
return x[0]
m = maximum(x[:-1])
if x[-1] > m:
return x[-1]
else:
return m
|
9c15acec8f598fcaeaa6f953399ff4e408ce12f7 | sandeepkumar8713/pythonapps | /03_linkedList/26_delete_greater_value_on_right.py | 2,006 | 4.0625 | 4 | # https://www.geeksforgeeks.org/delete-nodes-which-have-a-greater-value-on-right-side/
# Question : Given a singly linked list, remove all the nodes which have a greater value on right side.
#
# Question Type : Generic
# Used : removeNextGreater(self):
# temp = self.head, prev = None
# while temp.next:
# ... |
0fe2afb514cc7e595e1dc3c4362c05e48ad99d50 | choiking/LeetCode | /tree/EricD/235. Lowest Common Ancestor of a Binary Search Tree - EricD.py | 294 | 3.53125 | 4 | # Binary Search Tree!
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
while (root.val-p.val)*(root.val-q.val)>0:
root = root.left if root.val>q.val else root.right
return root |
576499034a57a30a45fed2769bc801cc7a32aded | izlatkin/euler-project | /interview/sorting/13_h_citation.py | 856 | 3.578125 | 4 | import collections
import heapq
def h_citation(citations: list[int]):
citations.sort() # O(n*log(n))
n = len(citations)
for i, c in enumerate(citations): # O(n)
if c >= n - i:
return n - i
return 0
def h_citation_heap(citations: list[int]):
n = len(citations)
count_citati... |
3f9fb68543fbcb81d5bb4ba4b951266690561e81 | thmbob/TIPE-MPSI | /denombrement.py | 2,164 | 3.53125 | 4 | ### Objectif : mettre au point une formule qui calcule la proba théorique qu'un graphe soit connexe on procède par dénombrement via une formule récursive
### Pour limiter le nombre d'appel on a recours à la programmation dynamique. Les nombres en jeu sont rapidement très gros
### On dénombre le nombre de graphe à n s... |
d88456f5ef26533b2d29c2c5d7d118cf45b8e95d | kimtaehyeong/Algorithm | /solution/beakjoon_2750.py | 215 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 22:26:30 2020
@author: Taehyung
"""
N = int(input())
a = []
for i in range(N):
b = int(input())
a.append(b)
a.sort()
for i in a:
print(i) |
f8ab57d4b8e6f28cb9956278e8d200bba736ffd0 | jingyiZhang123/leetcode_practice | /searching_problem/four_sum_18.py | 2,126 | 3.6875 | 4 | """
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
... |
a64feae59f170151834409fc9a84fc0ee84d9865 | ReethP/Kattis-Solutions | /anothercandies.py | 387 | 3.671875 | 4 | iterations = int(input())
candies = []
for i in range(0,iterations):
input()
children = int(input())
candies.clear()
for j in range(0,children):
userinp = int(input())
candies.append(userinp)
kids = len(candies)
totalcandies = 0
for candy in candies:
totalcandies = totalcandies + candy
possible = totalc... |
b690b0dc696a95aa8a6ffcb7f8a77cdb613cd8be | gkdmssidhd/Python | /Python_day03/Day03Ex02.py | 714 | 3.71875 | 4 |
# 함수를 사용하는 이유
# 함수를 선언 해 두면 여러지점에서 재활용(반복호출) 가능
# input(), print() 도 역시 함수
def my_func(size) :
print(">>> 함수 호출")
print(">>> 이것은 함수 입니다")
print("-"* size)
print(">>> 1 함수를 외부에서 호출 하였다.")
my_func(5)
print(">>> 2 함수를 외부에서 호출 하였다.")
my_func(30)
print(">>> 3 함수를 외부에서 호출 하였다.")
my_func(5)
print(">>> 4 함수를 외부에... |
1e041001d8847572413077b2ca8303b4bb7c10d5 | darian200205/FP-python | /lab7/Domain/Subject.py | 328 | 3.53125 | 4 | class Subject:
def __init__(self, subject_id, subject_name, teacher):
self.subject_id = subject_id.upper()
self.subject_name = subject_name.upper()
self.teacher = teacher.upper()
def show_subjects(self):
print('ID:' + str(self.subject_id) + ':' + self.subject_name + '-' + self.t... |
9d718c1457da85bb8d871b2024a6902c6888132e | vnpavlukov/Study | /Coursera/1_Specializations/2_Programming_on_Python/1_Dive_into_Python/Week_3/2_Inheritance/Lect_1_1.py | 417 | 3.53125 | 4 | class Pet:
def __init__(self, name=None):
self.name = name
class Dog(Pet):
def __init__(self, name, breed=None):
super().__init__(name)
self.breed = breed
def say(self):
return '{0}: waw'.format(self.name)
Doberman_Sharik = Dog('Шарик', 'Доберман')
print(Doberman_Sharik.... |
046d62a9e843ab3f475213273b01fa967ddcc2ba | Elena-Zhao/gf | /utils.py | 559 | 3.6875 | 4 | import datetime as dt
from re import sub
import numpy as np
def parse_currency(string):
"""Preprocess string and get currency number
>>> parse_currency('$2,000')
2000.0
"""
return float(sub(r'[^\d.]', '', string))
def parse_date(string):
"""Get datetime
>>> parse_date('08/22/2... |
3518c1e2d91c271c0f8b98df5fa9a686eec251ef | OtchereDev/Python-workbook-solution-projects- | /python_workbook_3.py | 7,829 | 4.0625 | 4 | """
This is the third chapter of The Python Workbook
the solution to the exercise
'Loop Exercise'
"""
#Exercise 61
# print('Let calculate the average of your collection of values')
# print('Please enter "0" if you dont have any more input')
# input_=True
# value=0
# n=0
# while input_:
# user_=int(input('What i... |
0f1324da10e312bb9dcad0ccf1e726692fe1f20b | joeguerrero735/AlgoritmosSistemas | /ene-jun-2020/joe tareas y parciales/segundo parcial/segundo examen parcial.py | 1,931 | 3.875 | 4 | def quick_sort(arr,primero,ultimo):
pivote = arr[(primero+ultimo)//2]
min =primero
max =ultimo
while min <= max:
nom = arr[min]
while nom[0] < pivote[0]:
min +=1
nom = arr[min]
pass
nom2 = arr[max]
while nom2[0] > pivote[0]:
max -=1
nom2 = arr[max]
pass
if min <= max :
temp = arr[... |
dbf5d871c992a586c4f09838f9c9b7dd1e034e5a | iSaluki/python | /testing/string_repeater.py | 194 | 3.9375 | 4 | string = input("String:")
stringSuffix = " "
string = string + stringSuffix
times = input("Amount:")
while not times.isdigit():
times= input("Amount")
times = int(times)
print (string * times)
|
cd4c8bdb642c0124fc9eb85b40812fece852fbe5 | MorisGoldshtein/2020DivHacks | /Map.py | 3,133 | 3.859375 | 4 | # Description: This program creates a map of the trains within the NYC Transit System based on data from
# NYC Open Data. Each station will have a heatmap, marker, station name, and track letter(s).
# The map is accessible through Jupyter with Map.ipynb
#Required Libraries: gmaps (includes Jupyter and other dependenci... |
337a3404f62a25506ee85ef439720c58cad435cf | himu999/Python_Basic | /F.list/#H#list_comprehension.py | 396 | 4.09375 | 4 | a = ["apple", "kiwi", "cherry", "banana", "mango"]
b = []
c = []
for x in a:
if "a" in x:
b.append(x)
else:
c.append(x)
print("Element of list a : ", a)
print("Element of list b : ", b)
print("Element of list c : ", c)
# With short hand
k = [x for x in a if "a" in x]
print("Element of list k ... |
da6052993b3c1119dee46966a57b3cde20a2d63a | horada1991/DerpSnake | /piton.py | 1,491 | 3.734375 | 4 | import curses
screen = curses.initscr()
dims = screen.getmaxyx()
curses.start_color()
# Moving Snake's parts' coordinates
def moving_coords(coord_list, y, x):
global dims
for element in range(len(coord_list)-1, 1, -1):
coord_list[element] = coord_list[element-2]
coord_list[0] = y
coord_list[1]... |
74dd49a4d7167b79c9801ca42a0000faf14b118f | chefkasperson/Cracking_the_Interview | /chp1/python/multiples_3_and_5.py | 256 | 4.09375 | 4 | def solution(number):
total = 0
i = 0
while i < number:
if i % 3 == 0 or i % 5 == 0:
total += i
i += 1
return total
# def solution(number):
# return sum(x for x in range(number) if x % 3 == 0 or x % 5 == 0)
|
e8395bd96993d23694ef61c1475182610aa52e36 | Qing8/Assignments-for-Data-Structure | /1/Python template files/question5.py | 1,249 | 3.859375 | 4 | import math # need math.pi
class Shape:
# No need to modify this class.
def __init__(self, name):
self.name = name
def compute_area(self):
pass
def compute_perimeter(self):
pass
class Circle(Shape):
def __init__(self, name, radius):
# TO DO
# Call super f... |
cf7dc2ee2073db26b2279f584171b905e1805e04 | yanoshercohen/virtual-mouse | /mouse_controller.py | 867 | 3.625 | 4 | import mouse
from pynput.keyboard import Key, Listener
#Pixels amount per any mouse step
step = 15
#configuring the mouse control keys
direction_keys = {
Key.right: (step, 0),
Key.left: (-step, 0),
Key.up: (0, -step),
Key.down: (0, step)
}
#configuring the mouse click keys
click_keys = {Key.f9: "left... |
ee29c5df4e434674beae2edf8d32a800c3ac9344 | brooky56/SSD_Assignment_1 | /src_assignemnt_2/bc_printer.py | 1,733 | 3.640625 | 4 | """Opcodes printing
Takes .py files and yield opcodes (and their arguments) for ordinary python programs.
This file can also be imported as a module and contains the following
functions:
* expand_bytecode - function find and extends bytecode result
* bc_print - function print instructions names and human re... |
5fdc983681dcddc1d6bee594da5b455bdfd8186d | avinash516/python-problem-solving-skills-programmes | /2.Interest rates calculator.py | 218 | 3.84375 | 4 | basic = float(input('Amount :'))
rate = float(input('Rate :'))
months = float(input('No.of Months :'))
y =float( input("Enter No. of Years: "))
m=(basic*rate*months)/100
print("intrest rate for year wise",m*y)
|
68be34cee896c61ef2e1f6e2c57de42053834d0b | tlima1011/python3-curso-em-video | /ex067.py | 345 | 3.921875 | 4 | titulo = 'TABUADA VS 3.0'
print(f'{titulo:=^30}')
while True:
tab = int(input('Informe a tabuada: '))
if tab < 0:
break
print('-=' * 10)
print(f'TABUADA DE {tab}')
print('-=' * 10)
for i in range(1, 11):
print(f'{tab} x {i} = {tab * i}')
print('-=' * 10)
print('PR... |
235e66a39ed8285fe8f074d04b4e88986ed239e9 | andreagaietto/Learning-Projects | /Python/Small exercises/functions/star_args.py | 218 | 3.640625 | 4 | def sum_all_nums(*args):
print(sum(args))
#returns a tuple
sum_all_nums(1, 2, 3, 4)
sum_all_nums(1, 2)
# can also do something like (num1, *args)
# also doesn't have to be named args, can be something else |
8b9b43bb859b4a6adb5874e9f4db3c398a797bff | vasudevk/python | /lists.py | 2,366 | 4.25 | 4 | s = "Show how to index into sequences".split()
print(s)
print(s[4])
# indexing from the end
print(s[-5])
# slicing a list using index, negative indexing and including
gunga = "Though I’ve belted you and flayed you, " \
"By the livin’ Gawd that made you, " \
"You’re a better man than I am, Gunga Din!".... |
6d7221c46962a6ca326aceb2a33ecab084d9f5fa | sdnProjectAqsa/SDN-Simulation-with-OpenFlow | /FatTree_6.py | 2,694 | 3.875 | 4 | """Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value
pair to generate our newly defined topology enables one to pass
in '--topo=mytopo' from the command line"""
from mininet.topo import Topo
class MyTopo(... |
47dad38657dad04ccdf1d51ed3757139a36eb1cb | ysk1026/data_science | /chp4/vector.py | 3,216 | 3.921875 | 4 | from typing import List
import math
'''
벡터를 리스트로 표현해서 개념 정리, 원리를 설명하는데 굉장히 편리하지만 성능면에서는 최악이다.
실제 사용할 땐 NumPy를 사용함
'''
Vector = List[float]
height_weight_age = [70, # 인치,
170, # 파운드,
40 ] # 나이
grades = [95, # 시험 1 점수
80, # 시험 2 점수
75, # 시험 3 점수
6... |
25b582d7ec8e282e890f000daceb7b716ef7d261 | smartinsert/CodingProblem | /equal_string_backspace.py | 1,091 | 3.765625 | 4 |
def backspace_compare(str1, str2):
if str1 == str2:
return True
left_idx, right_idx = len(str1) - 1, len(str2) - 1
while left_idx >= 0 or right_idx >= 0:
valid_left_idx = next_valid_character_index(str1, left_idx)
valid_right_idx = next_valid_character_index(str2, right_idx)
... |
18db09159f1d5f56a84e1be119d2b0819de145ec | thenu97/mathworld | /Calculator.py | 478 | 4.125 | 4 | #!/usr/bin/env python3.8
print("Hello World")
x = float(input("What is your x: " ))
y = float(input("What is your y: "))
Ops = input("addition, subtraction, multiplication, division?: ")
def cal(x, y):
if Ops == "addition":
return x + y
if Ops == "subtraction":
return x - y
if Ops == "mult... |
4a5d2461d230e6d46b000b0c5b223d7ad1801a7e | ManuBedoya/AirBnB_clone_v2 | /web_flask/6-number_odd_or_even.py | 1,541 | 3.5 | 4 | #!/usr/bin/python3
"""Modulo to find the flask
"""
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/', strict_slashes=False)
def index():
"""The root of the page or index/default
"""
return 'Hello HBNB!'
@app.route('/c/<text>', strict_slashes=False)
def c_is(text):
"""Pa... |
611cd300cf57e64d24ad1c3dae7502ef3db48bab | dhananjayharel/mark_trego_python_beginners | /numpy_basic/basic.py | 369 | 3.546875 | 4 | import numpy as np
x=np.random.random()
print("Random number: ", x)
x_square_root=np.sqrt(x)
print("Number square root: ", x_square_root)
print("x^sqrt(x): ", np.power(x, x_square_root))
matrix = np.random.random(3)
print("Random matrix: ", matrix)
matrix = np.append(matrix, np.random.random(2))
print("New matrix: ", ... |
92e443de47064165bfe64761c480290e619e2589 | eno2050/python-study-note | /base/task10.py | 269 | 3.78125 | 4 | #-*- coding:utf-8 -*-
# 面向对象编程
class Person(object):
def __init__(self,name,skin = "yellow"):
self.name = name
self.__dict__.skin = skin
xiaoming = Person('xiaoming')
hahha = Person('hahha')
print xiaoming.name
print xiaoming.skin
print hahha.name |
28f731a0edd85ced317ea990fbce0302831f81a4 | m4nasi/UCL-Coding-Summer-School | /snakes.py | 2,359 | 3.515625 | 4 | ###### 1. Initialising the game ################################################
#### 1.1 Import libraries
import sys
sys.path.insert(1,'/home/pi/Go4Code/g4cSense/skeleton')
from sense_hat import SenseHat
from snake_lib import Snake
import random
from senselib import *
#### 1.2 Initialisation
sense = SenseHat() # ... |
fcfc6601c4c68b2397f8bda1982b1f7713245083 | tasotasoso/statistics | /NLP/myparse.py | 800 | 3.75 | 4 | #Copyright (c) <2017> Suzuki N. All rights reserved.
#inspired by "http://www.phontron.com/teaching.php?lang=ja"
# -*- coding: utf-8 -*-
import MeCab
from collections import Counter
def Wordcount(text):
def myparse(text):
mc = MeCab.Tagger("-Owakati")
ptext = mc.parse(text)
words = ptext.... |
cd2eb70ddd06efb445b9dffd8124dcc82fb5bfc8 | vharvey80/PythonExercises | /LightYearCalculator.py | 1,032 | 3.703125 | 4 | # Calcul la distance en année lumière
def CalculSeconde(annees):
n_j = (float(str(annees.replace(",", "."))) * 365.26)
n_h = n_j * 24
n_m = n_h * 60
n_s = n_m * 60
return n_s
n_secondes = CalculSeconde(input("Entrez un nombre d'année(s) lumière : "))
print(format(n_secondes, ".2f") + " secondes")
... |
6d8522c061838774fcd10c28be7a1ce81c8978e1 | Ethics123/python_a | /level2-1.py | 208 | 3.828125 | 4 | # バグを修正し全ての名前を一度ずつ順番に出力できるようにしてください
name_list = ["太郎", "次郎", "三郎", "四郎", "五郎"]
for i in range(1, 5):
print(name_list)
|
94709ec80dd95d1ee3e6ca9aed83aac7f5fe0b0a | zongzake/Homework- | /work 27-09-2562.py | 8,272 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#ข้อที่ 1 ให้นักศึกษากำหนดค่าตัวเลขมา 1 จำนวน ตั้งแต่ 15-60 เป็นตัวแปร A จากนั้นให้เลือกตัวเลขตั้งแต่ 2-15 มา 1 จำนวน เป็นตัวแปร B แล้วให้หาว่า ตัวแปร B สามารถหารจำนวนในช่วงที่ 15-A ใดแล้วมีเศษเป็น 0 บ้าง จงแสดงจำนวนทั้งหมดนั้น
A = int(input("Enter A in range 15-60 : ... |
921a62fee651c6cc5ce3bf0e08928d0b725c03b8 | dubugun/big_data_web | /python/0131/두수비트연산.py | 792 | 3.578125 | 4 | sel = int(input("진수(2/8/10/16)를 선택하시오"))
num1 = input("첫 번째 수를 입력하시오. ")
num2 = input("두 번째 수를 입력하시오. ")
num11 = int(num1, sel)
num22 = int(num2, sel)
print("두 수의 & 연산 결과")
print("16진수 ==> ",hex(num11&num22))
print("8진수 ==> ",oct(num11&num22))
print("10진수 ==> ",num11&num22)
print("2진수 ==> ",bin(num11&num22),'\n')... |
188ebc1523e59cface7df486908fddfe1237c58d | gisselleroldan/Digital-Crafts | /Python/Homework/phonebook.py | 1,530 | 4.125 | 4 | # CRUD - create, read, update, delete
phonebook = {}
import pickle
with open('phonebook.pickle', 'rb') as fh:
phonebook = pickle.load(fh)
keep_going = True
def lookup():
name = input("Enter whose number would you like to look up: ")
if name in phonebook:
print(f'Number for {name} is: {phonebook... |
505f712290f0db9911709fd231891cced65d3921 | WampiFlampi/Temporary-Python | /Tutorial2.py | 229 | 4.25 | 4 | number = input("Place your number here!")
check = int(number) % 2
number = int(number)
if number == 0:
print("neither even nor odd")
else:
if check == 1:
print("the number is odd")
else:
print("the number is even")
|
4e3225e0cf2f649d1562b67173a3745f723ef1ac | NavneetChoudry/DataScience-Python | /Matplotlib/LINE GRAPH.py | 234 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 8 09:44:33 2018
@author: Navneet Choudry
LINE GRAPH
"""
from matplotlib import pyplot as plt
x = [5,8,10]
y = [12,16,6]
plt.plot(x,y)
plt.title("info")
plt.ylable("Yaxis")
plt.xlabel("Xaxis")
|
b4f09f3550ad06c9b464bfcd70e11ad2a5c9fe10 | Ismazgz14/TIC_20-21 | /ululador.py | 347 | 3.921875 | 4 | '''Haz un programa que lea una cadena y sustituya
las vocales por la letra u. palabra de 10, For'''
def ululador():
palabra=raw_input("Introduce una palabra para ulular. ")
for cont in range (0,11):
if(palabra [cont]=='a'):
print 'u'
else:
print palabra[cont]
... |
f4405340f5885e2b0ee45ab4212a369146a5852a | DT211C-2019/programming | /Year 2/Saul Burgess/Labs/2020-10-15/Lab10(1).py | 267 | 3.90625 | 4 | def list_adder(list):
'''When passed a list, will return an intiger containing the total
of the list'''
ans=0
for i in range(len(list)):
ans+=list[i]
return ans
sample_list = [1,2,3,4,5,6]
print("The answer is", list_adder(sample_list)) |
9a3abe8fd5b06350a888ca5c9dfe9da554c5f303 | qqqlllyyyy/LintCode-Python | /09-High-Frequency/12 Maximum Subarray.py | 990 | 4.15625 | 4 | # Maximum Subarray
# Given an array of integers, find a contiguous subarray which has
# the largest sum.
#
# Example
# Given the array [-2,2,-3,4,-1,2,1,-5,3], the contiguous
# subarray [4,-1,2,1] has the largest sum = 6
#
# Challenge
# Can you do it in time complexity O(n)?
#
class Solution:
"""
@param nums:... |
58b2906855bd2203296f657bc39fea8eca5263ca | LXwolf123/python-2021-7 | /Ui_Joseph/user_case/reader.py | 2,090 | 3.515625 | 4 | import csv
import zipfile
import xlrd
import os #pandas 这个库好用
import pandas as pd
class Reader(object):
def __init__(self, filePath):
self.filePath = filePath
def read(self): #父类先实现该方法
pass
class CsvReader(Reader):
def __init__(self, filePath):
assert f... |
3f6ca19176ab49037380bb96756153c668ebd430 | asatav/Python-All-Example | /RegularExpression/Demo1.py | 220 | 3.984375 | 4 | import re
count=0
pattern=re.compile("ab")
matcher=pattern.finditer("abaababa")
for match in matcher:
count+=1
print(match.start(),"...",match.end(),"...",match.group())
print("The number of occurrences:",count) |
840060bb21bb1384384a71d5e8934cf45c0edd9b | syedshameersarwar/pandas_init | /data_handling.py | 2,203 | 3.875 | 4 | import pandas as pd
import numpy as np
string_data = pd.Series(['aardvark', 'artichoke', np.nan, 'avocado'])
print(string_data)
print(string_data.isnull())
# The built-in Python None value is also
# treated as NA in object arrays
string_data[0] = None
print(string_data.isnull())
# filtering out missing data
print('... |
384f64b575ed819dc569d6b3db4ba4ed9e20f3ba | sachinbiradar9/Autograder | /src/gradient descent/linear.py | 4,173 | 3.671875 | 4 | """
Implementation of *regularized* linear classification/regression by
plug-and-play loss functions
"""
from numpy import *
from gd import *
from binary import *
class LossFunction:
def loss(self, Y, Yhat):
"""
The true values are in the vector Y; the predicted values are
in Yhat; comput... |
e84ae46c564ee191533f7c02738d33f1be511880 | phhm/thefruitflygang | /Breakpoint_function.py | 1,714 | 3.796875 | 4 | Melanogaster = [23,1,2,11,24,22,19,6,10,7,25,20,5,8,18,12,13,14,15,16,17,21,3,4,9]
def breakpoint_search(List):
'''
Function to determine Breakpoint positions.
Breakpoints are returned in a list containing each Breakpoint.
'''
# Creating borders to check for Breakpoints before the first, and behind the last elem... |
74aec538ae2308f6d5fe0322dab27630072b76e1 | quixoteji/Leetcode | /solutions/261.graph-valid-tree.py | 1,048 | 3.65625 | 4 | #
# @lc app=leetcode id=261 lang=python3
#
# [261] Graph Valid Tree
#
# @lc code=start
class Solution:
# topological sort
# 0 : unknown 1 : visiting 2 : visited
def validTree(self, n: int, edges: List[List[int]]) -> bool:
return self.sol1(n, edges)
# Solution 1 : dfs
def sol1(self... |
40fae480f5b34757c7ebd1fe8c83e47068d9adce | JT4life/PythonRevisePractice | /inheritancePractice.py | 671 | 3.734375 | 4 | class A():
def __init__(self):
self.name = 'joshua'
def view(self):
print("My name in A is ",self.name)
def sayHello(self):
print("Hello there")
class B(A):
def __init__(self):
self.name = "JayZ"
A.__init__(self) #because this is declared after 'joshua' would be ... |
12f82c423e43a0dc2802c7b6bf7f752372f1d06d | WeilieChen/data-engineer-interview | /facebook/screening/python/highest_neighbor.py | 640 | 3.546875 | 4 | """
Find the alphabet with highest neighbors
"""
def solution(data):
count = {}
for group in data:
if len(group) == 1:
count[group[0]] = count.get(group[0], 0) + 0
else:
for node in group:
count[node] = count.get(node, 0) + 1
highest = max(count.va... |
36abab3b6da56105277743d1b5d70be728edff80 | mudit2103/courserapython | /pong.py | 5,361 | 3.5 | 4 | # Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 4
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
LEFT = False
RIGHT... |
5b23f87d82b4596860ca67e2d6232e4207f053a9 | kanosaki/picbot | /picbot/utils/__init__.py | 824 | 3.5 | 4 |
import itertools
def uniq(*iters):
"""Make unique iterator with preserving orders. """
return UniqueIterator(itertools.chain(*iters))
class UniqueIterator(object):
def __init__(self, source):
self.source = source
self._history = set()
def __iter__(self):
return self
def ... |
8af333cb4512847777511f653fce1921a1085846 | r25ta/USP_python_2 | /semana4/exercicio_busca_binaria_recursiva.py | 1,368 | 4.1875 | 4 | """ ALGORITIMO DE BUSCA BINARIA RECURSIVA
O SISTEMA RECEBE UMA LISTA ORDENADA E O ELEMENTO A SER PROCURADO
"""
def search_binary_recursive(list,element):
'''CONSISTE SE A LISTA ESTÁ VAZIA GERALMENTE PARA CASOS ONDE A LISTA FOI TOTALMENTE
EXPLORADA E O ELEMENTO NÃO ENCONTRADO'''
if(len(list)==0):
r... |
6990fd4b69f9f5235c85f720ae1fea76b2625bf4 | knysna/POTD | /potd.py | 2,521 | 3.734375 | 4 | __author__ = 'admin'
""" potd (Password of The Day)
Calculates the passwords for today based on the well known formula. The purpose is to save a few minutes work each day.
Writes the passwords into html and sets up a little http daemon for access. The listening port can be specified.
Browse to <IP>:PORT
The html page i... |
64b6cdc27b4fff2bf7f587b48a37bd9b8ce15062 | w40141/atcoder | /abc_247/c.py | 143 | 3.5 | 4 | n = int(input())
def s(n):
if n == 1:
return "1 "
else:
return s(n - 1) + str(n) + " " + s(n - 1)
print(s(n)[:-1])
|
45b08d586d1f072a685d4fb7f09b7c8fa8645074 | Elly-bang/python | /chap06_Class_Module_lecture/step01_class_basic.py | 2,761 | 3.796875 | 4 | '''
클래스(class)
-함수의 모임
-역할: 다수의 함수와 공유 자료를 묶어서 객체(object) 생성
-유형 : 사용자 정의 클래스, 라이브러리 클래스 (python)
-구성 요소: 멤버(member)+생성자
-멤버(member): 변수(자료 저장) + 메서드(자료 처리)
-생성자 : 객체 생성
#####################
형식)
class 클래스명 :
멤버변수 = 자료
def 멤버메서드() :
자료 처리
생성자 : 객체 생성
#####################
'''
#... |
bea1fd4f88652d01c59f6cf56b7888f3ee30a9cd | hks73/project | /weather.py | 2,152 | 3.640625 | 4 | # import pyowm
# import requests
# from datetime import date
# from dateutil.rrule import rrule, DAILY
# API_KEY="68897584b12c57a6f018081baac462c2"
# ################### GET CUURENT WEATHER DETAILS ############################
# x=raw_input("Enter any place to get current weather :")
# owm = pyowm.OWM(API_KEY)
# ob... |
bcb1da2ae519e5b94601070cd56e69aa058b37b3 | OleksandrMakeiev/python_hw | /def gen_primes.py | 370 | 3.609375 | 4 | #30
def gen_primes():
list_of_ints = []
for x in range(1, 101):
if x == 1:
pass
else:
for y in list_of_ints:
if x % y == 0:
break
else:
list_of_ints.append(x)
return list_of_ints
print("Все простые числа... |
2a7e3c2f143789b5a09c7f1cf8d1353874639de9 | EmersonDantas/SI-UFPB-IP-P1 | /Exercícios-Lista3-Estrutura sequencial-IP-Python/Lista3-Sld-Pag28-Alg-9.py | 253 | 3.546875 | 4 | #Emerson Dantas S.I IP-P1
#02/08/2017 16:06
print('Para saber sua média, diga suas notas:')
N1= float(input('Nota 1:'))
N2= float(input('Nota 2:'))
N3= float(input('Nota 3:'))
N1F= (N1*2)
N2F= (N2*3)
N3F= (N3*5)
NF= ((N1F+N2F+N3F)/10)
print('Sua média:',NF)
|
6cc02658076f1b458e0c981741f56a10a1c3a18c | sowmiyavelu17/geet | /cancatenate.py | 132 | 4.03125 | 4 | s1=input('Please enter the first string:\n')
s2=input('Please enter the second string:\n')
print('Concatenated String =', s1 + s2)
|
3f69a86216b5ec08c7135fdd889bd5136b1a5760 | manojach87/ludo | /src/game.py | 3,044 | 3.65625 | 4 | colors = {0: "red", 1: "green", 2: "yellow", 3: "blue"}
## This class is for the gatti
class gatti:
loc = -1
MAXMOVES = 56
inSafeZone = True
SAFEZONES = [-1, 0, 8, 13, 21, 26, 34, 39, 47]
HOMEZONES = [51, 52, 53, 54, 55, 56]
def __init__ (self,color):
self.color = color
self.loc... |
c197f98dffe24c60a2876d694734ffc5dc7c7b6b | kongtianyi/cabbird | /leetcode/find_bottom_left_tree_value.py | 402 | 3.75 | 4 | from structure.treenode import *
def largestValues(root):
res=[0,root.val]
dfs(root,0,res)
return res[1]
def dfs(root,level,res):
if root:
if level>res[0]:
res[0],res[1]=level,root.val
dfs(root.left,level+1,res)
dfs(root.right,level+1,res)
if __name__=="__ma... |
a17970fac69726143fa1d73a8d53004336f1fdf1 | ecdegroot/replace_characters | /replace_characters.py | 669 | 4.40625 | 4 | # https://github.com/ecdegroot/replace_characters
# This python program replaces multiple characters in a word or sentence, example:
# text_input = "Intelligence is the ability to adapt to change"
# text_output = "1N73LL1G3NC3 15 7H3 4B1L17Y 70 4D4P7 70 CH4NG3"
# enter a word or sentence
input_str = input("Type someti... |
166798ef28aec224c1a5e52eab49109db501e1d3 | weekenlee/pythoncode | /pra/counter_test.py | 590 | 3.578125 | 4 | import collections
print(collections.Counter(['a', 'b', 'c', 'a']))
print(collections.Counter({'a': 2, 'b': 3, 'c': 1}))
print(collections.Counter(a=2, b=3, c=1))
c = collections.Counter()
print('Initial:', c)
c.update('abcdaab')
print('Sequence:', c)
c.update({'a': 1, 'd': 5})
print('Dict :', c)
for letter in 'ab... |
3d012edc643328f4aac480a022458eacdd888175 | Zahidsqldba07/HackerRank-Solutions-1 | /python/epeated-string.py | 825 | 3.78125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the repeatedString function below.
def repeatedString(s, n):
acounter = 0
for c in range(len(s)):
if s[c] == 'a':
acounter += 1
acounter = math.floor(n/len(s))*acounter
g = math.floor(n/len... |
b6d502bb47035a59b9ca9ab79f7c571b404b4fe7 | mattheww22/COOP2018 | /Chapter06/U06_Ex_03_Sphere.py | 1,098 | 4.375 | 4 | # U06_Ex_03_MacDonald.py
#
# Author: Matthew Wiggans
# Course: Coding for OOP
# Section: A3
# Date: 14 Dec 2019
# IDE: PyCharm
#
# Assignment Info
# Exercise: 03
# Source: Python Programming
# Chapter: 06
#
# Program Description
#
# This program prints the surface area and volume of a sphere using a... |
3e46559534cc40ed2a0e86f442517d07eb7efe60 | khromov-heaven/pyBursaGit | /L2/dz2_5.py | 298 | 3.71875 | 4 | def separator(l):
even = []
uneven = []
res = []
for i in l:
if i%2 != 0:
uneven.append(i)
else: even.append(i)
uneven.sort()
even.sort()
even.reverse()
res = uneven + even
print res
print l is res
s = list(input())
separator(s)
|
77603e4a09bf35d2c1354c7d299ef9e3a59a74b5 | yordanovagabriela/HackBulgaria | /week7/website-crawler/histogram.py | 318 | 3.5 | 4 | class Histogram:
def __init__(self):
self.items = {}
def add(self, word):
if word not in self.items:
self.items[word] = 1
else:
self.items[word] += 1
def count(self, word):
return self.items[word]
def get_dict(self):
return self.items
|
3daf851111dd097c7a0d967e5e7b8d4206eb57be | usako1124/teach-yourself-python | /chap11/reserve_call.py | 354 | 3.8125 | 4 | import math
class Coordinate:
def __init__(self, x, y):
self.x = x
self.y = y
# c(x, y)形式で呼び出せ、距離を求める
def __call__(self, o_x, o_y):
return math.sqrt(
(o_x - self.x) ** 2 + (o_y - self.y) ** 2
)
if __name__ == '__main__':
c = Coordinate(10, 20)
print(c(5... |
9002befb024258a18d693bcf477d404963b02594 | DanielPramatarov/Python-Data-Structures-Implementation | /Stack/Stack.py | 555 | 3.796875 | 4 | class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return self.stack == []
def push(self, data):
self.stack.append(data)
def pop(self):
if self.size_stack() < 1:
return None
data = self.stack[-1]
del self.stack[-1]
... |
428e353b8584dc61b1d78eb29be138ebc6d75cc0 | xc21/Leetcode-Practice | /Python/283. Move Zeroes.py | 1,212 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 12 23:18:44 2018
@author: Xun Cao
"""
"""
283. Move Zeroes
Given an array nums, write a function to move all 0's to the end of it
while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your f... |
408ba40227c45debbffc114b3c9cf04ebfc61376 | ietuday/python-notes | /variable-ex.py | 721 | 3.78125 | 4 | a = 2
print(a)
b = 9223372036854775807
print(b)
pi = 3.14
print(pi)
c = 'A'
print(c)
name = 'John Doe'
print(name)
q = True
print(q)
x = None
print(x)
print(type(a))
# a, b, c = 1, 2
# print(a, b, c)
# dummy variable can have any name, but it is conventional to use the underscore ( _ ) for assigning unwanted... |
b3857a281b98c9fc779661174a034d14f7ed32e1 | xodhx4/webcam_image_recognizer | /train.py | 6,097 | 3.78125 | 4 | """Make CNN model with your dataset
Make your CNN model with your dataset.
This automatically load dataset from directory './train/'.
This model is multi class classification and each folder would be onde class with dir name.
And this automatically augument the dataset with shift, flip, etc.
*Pretrained model is recom... |
474bb9e8defc88c9b1888a1fcd93e4e203702314 | max644/advent_of_code | /2018/2.py | 396 | 3.53125 | 4 | from collections import Counter
if __name__ == "__main__":
with open("2.txt", "r") as file:
lines = file.readlines()
lines = [line[:-1] for line in lines]
count2 = 0
count3 = 0
for line in lines:
if len(filter(lambda x: x[1] == 2, Counter(line).items())) > 0:
count2 += 1
if len(filter(lambda x: x[1] ... |
3e075402bc0190ee5664d2b3e4d19b889b6409ff | kaiwolff/Eng88-cybercourse | /Week_3/Python_OOP/functional_calculator.py | 1,150 | 3.578125 | 4 | from oop_calculator import SimpleCalculator
class FunctionalCalculator(SimpleCalculator):
#add mroe functionality compared to the simple calculator
def __init__(self):
super().__init__()
def inchtocm(self, value1):
return value1 * 2.54
def triangle_area(self, height, width):
... |
a3dcbf1cfbe44f9a2d6930d13f83de124a020da4 | huimeizhex/leetcode | /BestTimetoBuyandSellStock.py | 425 | 3.796875 | 4 | #!/usr/bin/env python
# coding=utf-8
class Solution(object):
def max_profit(self, prices):
if len(prices) == 0:
return 0
min_price = prices[0]
res = 0
for price in prices:
res = max(res, price-min_price)
min_price = min(min_price, price)
re... |
78177a2068792738a8f2969f63ccf71ecea694d2 | vivekiitm/IC272-MiniProject | /Batch06/main.py | 204 | 3.859375 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
data = pd.read_csv("group6.csv")
#Checking whether there is any missing value in any column.
print(data.isna().sum())
'''No Missing Values Found'''
|
d57888085c0faae2778b9d3c586dd764946f3156 | kho903/Flask_Oracle | /oracleTest.py | 887 | 3.609375 | 4 | import cx_Oracle as o
def insertTest(name, age, birth):
try:
# sql = "insert into student values('이순신',30,'1999/02/11')"
sql = "insert into student values(:name,:age,:birth)"
dsn = o.makedsn('localhost', '1521', 'xe')
conn = o.connect(user='scott', password='tiger', dsn=dsn)
... |
6d1bd469108801a6ab43f34ebd5f2084b636ffdb | brianpattie/byz-generals | /byzgen.py | 6,340 | 3.609375 | 4 | import sys
import threading
import queue
# Nodes of the OrderTree. Implemented as recursive dictionaries.
class OrderNode():
def __init__(self):
self.value = None
self.dict = {}
# Returns the order (a string)
def majority(self):
# Perform majority on all child nodes
for ... |
1436e0e3899ba21b67be2f00be2024c6b9f437ac | rabinshrestha2055/python-training | /week2/factorial.py | 118 | 3.96875 | 4 | def factorial(n):
i = 1
f = 1
while i<=n:
f *= i
i += 1
return f
print(factorial(3))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.