blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
8e65e9c2183bec0cbddbd250605204fd6a28bf0d | phibzy/InterviewQPractice | /Solutions/RemoveElement/removeElement.py | 485 | 3.5 | 4 | #!/usr/bin/python3
"""
@author : Chris Phibbs
@created : Wednesday Sep 02, 2020 10:42:57 AEST
@file : removeElement
"""
class Solution:
def removeElement(self, nums, val):
if not nums: return 0
nums.sort()
i = 0
while i < len(nums):
if nu... |
d5656aea38fb85f2cc8fbbe4532fa89fcfbd0de1 | briann-paull/DATA-SCIENCE-PROJECTS_3 | /kMeans.salary.ore/K Means.py | 1,990 | 3.890625 | 4 | #importing packages
from sklearn.cluster import KMeans
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from matplotlib import pyplot as plt
#iporting data
df = pd.read_csv("income.csv")
df.head()
#cisualizing data
plt.scatter(df.Age,df['Income($)'])
plt.xlabel('Age')
plt.ylabel('Income($)')
#kme... |
ffa506b90bee59239e1d9a499e615ed94fde07b7 | noors312/ex.py | /ex.py | 485 | 3.609375 | 4 | from random import *
list_ = ['up','down','left','right']
random_list = [choice(list_) for i in range(20)]
def step(list):
str_ = ''.join(list)
if str_.count('left') == str_.count('right') and str_.count('up') == str_.count('down'):
print(str_.count('right'), str_.count('left'), str_.count('up'). str_.... |
8d8ab8150896f6ddbd2e311b30718ea719cab10a | DomomLLL/newpy | /jiaoben/yxwd/yxwd.py | 526 | 3.5 | 4 | from HERO import Hero
from HERO import monster
import unittest
class TestHero(unittest.TestCase):
def test_init_hero(self):
lisy = Hero(name = 'lisy', hp =100, ack = 10)
self.assertEqual(lisy.hp, 100)
self.assertEqual(lisy.ack, 10)
def test_hero_ack(self):
if lisy.ack > monster()... |
83b4baf77bc53e42fb4e2b5d87acb0ec7441f58b | snebotcifpfbmoll/ED | /P06E14.py | 1,270 | 4.0625 | 4 | # P06E14:
# Desarrolla un programa junto con tu compañero, apoyándote en la “metodología pair programming” que tenga las siguientes características:
# While
print("Calculadora Fibonacci")
iteraciones = int(input("Introduce el numero de valores que quieres: "))
num_1 = 0
num_2 = 1
print("%d, %d, " % (num_1, num_2), end... |
91c9a1d7e3c26281ea45eb13339a707b9bc76cd5 | huangqingyi-code/ai | /代码/PythonStudy/tuple操作.py | 267 | 3.9375 | 4 | print(" ============ tuple 操作 ============")
a = (1, 2, 3, 4)
print(len(a)) # 计算包含元素的个数
print(a[2]) # 获取集合第2个元素
# 查看元素4的索引
print(a.index(4))
# tuple不能修改,所以任何修改性操作都会报错
#a[2]=5
|
0ab07f8a9ccd99a37fbb8a05a4c13d8564d686f4 | MauGarrido/hyperblog | /codigo Python/alan.py | 815 | 3.78125 | 4 | import pandas as pd
# Aquí va el código para confirmar si quiere visualizar la información, y en ese caso si quiere cambiarla o simplemente guardarla
def run():
mi_info = {
'tarea': input("Hola, bienvenido, guardaremos la tarea quieres registrar, cuál es el nombre de la tarea:"),
'descripción': inp... |
3355a14fc2596e5a8135571cb6ff17ab42835c72 | emmaliden/thePythonWorkbook | /E23.py | 363 | 4.46875 | 4 |
# Calculate and display the area of a polygon with length of side is s and number of sides is n
from math import tan, pi
n = int(input("How many sides does the polygon have?: "))
s = float(input("What is the length of each side in centimeters?: "))
area = round(((n*s**2)/(4*tan(pi/n))),2)
print("The area of the p... |
b1201874749db182097bc203e4c6f053daedaa64 | ivoryspren/basic_data_structures | /binary_tree_recursive.py | 1,680 | 3.828125 | 4 | class Node(object):
def __init__(self, d, n = None):
self.data = d
self.next_node = n
def get_next (self):
return self.next_node
def set_next (self, n):
self.next_node = n
def get_data (self):
return self.data
def set_data (self, d):
self.data = d
clas... |
ec2795019fe974000648ad2542e4dea12e3f270f | manne05/Konzepte | /scope.py | 421 | 3.765625 | 4 | # Zugriff auf die globale Variable x in der Funktion foo1() muss mit
# global x erfolgen.
x = 5
def foo1():
global x
x += 1
print(x)
print("global x")
foo1()
# Zugriff auf die lokale Variable x der Funktion foo2() in der lokalen Funktion
# bar() muss mit nonlocal x erfolgen.
def foo2():
x = 5
d... |
455467d7f5a67ee58d377d2804a9514e68c81d6b | wyaadarsh/LeetCode-Solutions | /Python3/0211-Add-and-Search-Word-Data-Structure-Design/soln-1.py | 1,555 | 3.9375 | 4 | class TrieNode:
def __init__(self):
self.is_word = False
self.children = collections.defaultdict(TrieNode)
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word: str) ->... |
d44147469464185ce57f90868a3eb02bbeac0b75 | rohithprem/Python-Lessons | /HomeWork/HW9.py | 3,224 | 3.671875 | 4 | class Vehicle():
def __init__(self, make, model, year, weight, needsMaintenance = False, tripSinceMaintenance = 0):
self.make = make
self.model = model
self.year = year
self.weight = weight
self.needsMaintenance = needsMaintenance
self.tripSinceMaintenance = tripSinceMaintenance
def setMak... |
26e6982d518244c16418a290f1f49586667cace3 | BilalMubarakIdris/Nanos | /projects/capstone/thecrew_full_stack/thecrew-app-backend-api-python/app/date.py | 1,335 | 3.671875 | 4 | """Utilities for using date objects.
now(): the main function exported by this module.
"""
__author__ = "Filipe Bezerra de Sousa"
from datetime import datetime, timezone
from flask import current_app
def date_to_str(date):
"""Convert a date object to a string representation using the application
date ... |
96b9bb5987559351a0233cfa54db607085b562ee | RyanCoplien/Dijkstras-Algorithm-in-Python | /LinkState.py | 3,044 | 3.921875 | 4 | #-----------------------------------------------------------------------
# Name: Ryan Coplien
# Project: LinkState Dijkstra Algorithm
# Course: 3830 Data Communications and Computer Networking
#-----------------------------------------------------------------------
import csv
import sys
import heapq as hq
from ... |
77c6d78f63c76c6dc8e449df5acbad5c091a7e73 | scvalencia/algorist | /03. Arrays and ADT's/examples/CreditCard.py | 1,285 | 4 | 4 | class CreditCard(object):
def __init__(self, customer, bank, acnt, limit):
''' Creates a new credit card instance.
The initial balance is zero
args:
customer (string): name of the customer (e.g. 'John Lynch')
bank (string) : name of thr bank (e.g 'Bank of San Serriffe')
acnt (strign) : account i... |
afdbdd370f09ae63aa0360fc629bbfe929b94995 | fishedee/PythonSample | /basic/control.py | 548 | 3.515625 | 4 | #if 控制
age = int(input("请输入你家狗狗的年龄: "))
if age == 1:
print("相当于 14 岁的人。")
elif age == 2:
print("相当于 22 岁的人。")
elif age > 2:
human = 22 + (age -2)*5
print("对应人类年龄: ", human)
else:
print("你是在逗我吧!")
# while控制
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 到 %d 之和为:... |
dde6f5886f6992c15f1e0810a7e220956a5ba6d4 | dustinvo17/DS-Algo | /divide_and_conquer/sorted_arr_frequency_counter.py | 979 | 3.5 | 4 | # Given a sorted array and a number, write a function that counts the occurences of the number in the array
def count_num(arr,num):
start = 0
end = len(arr) - 1
i = None
j = None
while True:
if arr[start] == num:
start +=1
if arr[start+1] != num:
return start + 1
break
... |
9ad1501004df57c55fcb69645dccd4bc4f6d0823 | lshinkuro/praxis-academy | /novice/minggu_1/hari-1/kasus algoritma sorting/shellsort.py | 765 | 3.953125 | 4 | def shellsort(alist):
sublistcount = len(alist)//2
while sublistcount >0:
for star_position in range(sublistcount):
gap_insertionsort(alist,star_position,sublistcount)
print ("after increment of size",sublistcount,"the list is",nlist)
sublistcount = subl... |
eb6d86e3066c0193276948004f7486454e310a07 | rkoch7/Learning-Python | /chaining_and_teeing.py | 1,166 | 3.921875 | 4 | l1 = (i**2 for i in range(4))
l2 = (i**2 for i in range(4, 8))
l3 = (i**2 for i in range(8, 12))
# for gen in l1, l2, l3:
# for item in gen:
# print(item)
def chain_iterables(*l):
for iterable in l:
yield from iterable
l1 = (i**2 for i in range(4))
l2 = (i**2 for i in range(4, 8))
l3 = (i**2 ... |
f16484a84f4f1a172d1a26e675b8da8a9918291b | bharathmanvas/codes | /prefix.py | 219 | 3.71875 | 4 | def common(s1, s2):
out = ''
for i, j in zip(s1, s2):
if i != j:
break
out += i
return out
s1=input("enter")
s2=input("enter")
common(s1,s2)
print(common)
|
0fddd7ee03356083b9f3006cc730cd818b489676 | Subramanian11/word-game | /wordgame.py | 853 | 3.921875 | 4 | import random
system=['laptop','desktop','smart TV','Mobile']
print("Guess the word: {}".format(system))
store=random.choice(system)
# print(store)answer
j=2
def chance():
global j
if j>=1:
print("Still %d chances" %j)
else:
print("Game Over................")
j-=1
#let check... |
f730e69f3c38129b18b22ad7df790a11f819f6e9 | jxvo/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 128 | 3.625 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
return list(list(map(lambda num: num ** 2, row)) for row in matrix)
|
f9a3bd589bc5ab2ac51507a0a6c7e923734b49a8 | Arsentiiiii/prac3 | /prac3.py | 1,454 | 3.703125 | 4 | """
#1. whitespace before '('
def f ():
print("Hello")
f()
#2. missing whitespace arount operator
print(5+ 4)
#3. missing whitespace after ','
print([2,3,4])
#4. unexpected spaces around keyword / parameter equals
def f(arg=0):
return 2**arg
f(arg = 2)
#5. expected 2 blank lines, found 1
def f1():
retur... |
021ebe910d2ca68fe55d4517b5fea8d9eee0a887 | Barnsa/python-Instructional-Code | /welcomeChat.py | 3,438 | 4.0625 | 4 | ##################################################################################################################################
## Written by: Adam Barns ##
## Contact: adambarns83@gmail.com ... |
bb4c2dd02b9cf38fc1e290835e8d30ca5118ac79 | JoshTheBlack/Project-Euler-Solutions | /060.py | 1,781 | 3.765625 | 4 | # coding=utf-8
# The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime.
# For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four
# primes wit... |
5b38c66512eadbe6185363bc188e1a53da6d837c | Luorinz/courses | /NEU/cs5001/lab/lab01_Anda_Luo/name.py | 83 | 3.703125 | 4 | print("Please input your name:\t")
name = input()
print("Hello, there, %s!"%(name)) |
8aecc9e1e16bd83a8e36f01d1f85906b00cd5477 | timsergor/StillPython | /324.py | 1,077 | 3.59375 | 4 | # 788. Rotated Digits. Easy. 55.6%.
# X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone.
# A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to t... |
e8a0a6bebd27e308d09b206b6f29828be08b9316 | xiepfgit/PythonLearn | /MyFunctools.py | 564 | 3.953125 | 4 | # -*- coding: utf-8 -*-
'''
Created on 2019年7月13号
偏函数
@author: XPF
'''
def int2(x, base1=2):
return int(x, base1)
import functools
if __name__ == '__main__':
#以十进制转换为int
i= int('12345')
print(i)
#以8进制转换为int
i = int('12345', base=8)
print(i)
#以2进制转换为int
i = int2('10... |
79aec694dbb473c5e7d708704c6cc93dabfad411 | puneet29/algos | /GeeksForGeeks/SortingElementsOfAnArrayByFreq.py | 551 | 3.90625 | 4 | # Problem Description: https://practice.geeksforgeeks.org/problems/sorting-elements-of-an-array-by-frequency/
t = int(input())
for _ in range(t):
n = int(input())
a = [int(x) for x in input().split()]
freq = {}
for num in a:
if(num in freq):
freq[num] += 1
else:
... |
bb5a0e5d76b420620364b1d0af30e437e63483c4 | xiashuo/tedu_execises | /month01/day13/homework1.py | 1,305 | 4.1875 | 4 | '''
内置可重写函数练习1
(1). 创建父子类,添加实例变量
创建父类:人(姓名,年龄)
创建子类:学生(成绩)
(2). 创建父子对象,直接打印.
格式: 我是xx,今年xx.
我是xx,今年xx,成绩是xx.
(3). 通过eval + __repr__拷贝对象,体会修改拷贝前的对象名称,不影响拷贝后的对象.
'''
class Person:
def __init__(self, name, age):
self.name = name
self.ag... |
e846de9341a0fbd85a5b91be1b81c4ab25b83951 | adubois85/python_projects | /head_first/chapter2/marvin.py | 170 | 4.25 | 4 |
# You can iterate over a list as-is (and other data structures?)
paranoid_android = 'Marvin'
letters = list(paranoid_android)
for char in letters:
print('\t', char)
|
e7db56e6891fdee536f1523b991ae00ee63eabfc | ManojKrishnaAK/python-codes | /FUNCTIONS/aop.py | 524 | 3.6875 | 4 | #aop.py
def operations():
x1=float(input("Enter First Value:"))
x2=float(input("Enter Second Value:"))
sum=x1+x2
sub=x1-x2
mul=x1*x2
div=x1/x2
fdiv=x1//x2
mod=x1%x2
print("sum of {0} and {1} = {2}".format(x1,x2,sum))
print("sub of {0} and {1} = {2}".format(x1,x2,sub))
print("mul of {0} and {1} = {2}".format(... |
4466f1366b91499b6a1573b045b57aceb43d95ba | hurtnotbad/pythonStudy | /studyNotes/method/keywordTest.py | 768 | 4.0625 | 4 | import keyword
"""
关键字是python内置的、具有特殊意义的标识符,可通过print(keyword.kwlist) 查看所有关键字有如下:
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',
'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise',... |
5ea1421668175b183465d929afe2cf0352f02f6c | DanielSwags/erp | /interview 3.py | 609 | 3.921875 | 4 | def palindrome_chain_length(n):
num = str(n)
rev_num = ""
x = len(num) - 1
for i in range(x, -1, -1):
digit = num[i]
rev_num = rev_num + digit
return rev_num
def is_palindrome(n):
num = str(n)
rev_num = palindrome_chain_length(n)
return num == rev_num
numb = input("Pl... |
fdb89e86595f0685d3223f782b0b11ca558225b1 | velicu92/python-basics | /03_Import&Export.py | 2,437 | 3.734375 | 4 |
### Data import without Pandas can be difficult
### You would need to use Excel before that, to format the tables.
### Only numbers can be imported. Dates should be transformed to specific formats
##############################################################################
### Import data using Pandas
####... |
094dfcbda3d43e09fb3c1b50660b9db2bb9cf29d | MinnowBoard-Projects/max-opencv-demos | /screens/mazegame/gameplay.py | 7,574 | 4.25 | 4 | from .include import *
import random
# The maze generation is an implementation of the unmodified randomized Prim's
# algorithm from http://en.wikipedia.org/wiki/Maze_generation_algorithm
class Maze:
def __init__ (self, w, h, seed = None):
self.w, self.h = w, h
self.area = w * h
... |
69038065d926af82722cd28be4f5dddec59ee0a2 | Fantendo2001/FORKERD---University-Stuffs | /CSC1001/hw/hw_2/q3.py | 3,160 | 3.78125 | 4 | # !/bin/env python
# -*- coding:utf-8 -*-
import random
size = 139
fishes = 20
bears = 5
rounds = 100
class Ecosystem:
def __init__(self, size, fishes, bears):
creatures = fishes + bears
creatureLocs = random.sample(
range(size), creatures
)
fishLoc = random.sample(cr... |
4970125bab36291185457216732961f66556bbef | marti157/codewars | /2019/Problem2/Problem2.py | 95 | 3.703125 | 4 | num = input()
append = "s" if num != "1" else ""
print("{} lemonade jar{}".format(num, append)) |
56a4615b31b72d0babf238540c9dc18424962c5b | SophieGarden/cs_algorithm-structure | /15_3sum.py | 3,458 | 3.5625 | 4 | 15. 3Sum
Medium
5790
706
Add to List
Share
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -... |
81fe1bcef0e0e908befa995d2a8e5509427dfb9b | SheetanshKumar/smart-interviews-problems | /Contest/B/Range of Primes.py | 614 | 3.703125 | 4 | '''
https://www.hackerrank.com/contests/smart-interviews-16b/challenges/si-range-of-primes
Given a range A to B, both inclusive, you have to find the number of prime numbers in the given range.
Input Format
First line of input contains T - number of test cases. Its followed by T lines, each line contains 2 numbers - ... |
e64006c4eabae45aa356d7a1a6767577908d085b | ApexMaister/Python-2k18 | /ejercicio-mayor.py | 301 | 4.09375 | 4 | #coding: utf8
numero1= input("Introduce numero1: ")
numero2= input("Introduce numero2: ")
if (numero1 == numero2 ):
print "Son iguales"
else:
if (numero1 > numero2):
print numero1 , "Es mes gran que" , numero2
else:
print numero2 , " Es mes gran que " , numero1
|
701ff2f4b3a116233b9c5fed85946f770fa5c1de | RIMPOFUNK/FirstLyceumCourse | /Lesson 32 (Введение в ООП)/Homework/2. Самые короткие и самые длинные слова.py | 603 | 3.53125 | 4 | class MinMaxWordFinder:
def __init__(self):
self.sentence = []
def shortest_words(self):
if not self.sentence:
return []
mmin = min([len(i) for i in self.sentence])
return sorted([i for i in self.sentence if len(i) <= mmin])
def longest_wo... |
2b1f23bde2dba152fac95b4bd800240733a8acdf | pavstar619/HackerRank | /Python/Python Functionals/Map and Lambda Function.py | 250 | 4.03125 | 4 | cube = lambda x: x ** 3
def fibonacci(n):
List = [0, 1]
for i in range(2, n):
List.append(List[i-1] + List[i-2])
return(List[0:n])
if __name__ == '__main__':
n = int(raw_input())
print map(cube, fibonacci(n))
|
2ecdb840c85be34844476304d5235576dccf7beb | DonalMcGahon/Problems---Python | /Sorted list.Q8/SortedList.py | 497 | 4.125 | 4 | # Adapted from - https://stackoverflow.com/questions/29615274/user-input-integer-list
# Ask user to enter a list of numbers
list1 = input("Please enter a list of numbers separated by a single space only: ")
list1 = list1.split(' ')
# Ask user to enter a list of numbers
list2 = input("Please enter a list of numbers se... |
6365dda38eafc54c8ebedf87c0ef921d6ca3a752 | Adomkay/python-object-oriented-cash-register-lab-nyc-career-ds-062518 | /shopping_cart.py | 2,536 | 3.609375 | 4 | class ShoppingCart:
def __init__(self, employee_discount = None):
self._total = 0
self._items = []
self._employee_discount = employee_discount
def mean_item_price_list(self):
price_list = []
for item in self._items:
price_list.append(item['price'])
r... |
919198161bf8b4c66fbf8d67bd3da8aa0d07b890 | sw30637/assignment8 | /tl1759/distribution.py | 1,584 | 4.03125 | 4 | ####Liwen Tian
#####Assignment8
import pandas as pd
import numpy as np
from pandas import DataFrame as Df
import matplotlib.pyplot as plt
import math
import sys
def distributionpcincome():
"this function is to explore the per person distribution"
incomevalue = []
countries = pd.read_csv('countries.csv')
income ... |
93fb32ce0864da5e02aaf44c76ddf10942048ebe | Chandan-CV/school-lab-programs | /Program22.py | 619 | 4.21875 | 4 | #Program 22
#Write a program to create a tuple of Fibonacci series
#Name : Adeesh Devanand
#Date of Execution: September 16, 2020
#Class 11
n = int(input("Enter the length of the Fibonacci series"))
a = 0
b = 1
l = []
if n <= 0:
print("Invalid input")
elif n >= 1:
l.append(a)
if n >= 2:
l.append(b)... |
6c0b0d9147ed40187e586b74567caa1c7b3d5c8b | ejmaster/python-proj | /python-7.py | 1,956 | 4.15625 | 4 | """
Ask user for username and password
class customers
usernanmne, password, money
ask user withdraw or deposit money
modify the money
k = 203
if ( k == 203):
k += 123
k == 326
"""
class BankUser():
#This line tells the name and password.
def __init__(self):
s... |
987b2bac969d7be2de4801ed8534b5b34921e84d | wan-catherine/Leetcode | /test/test_1775_equal_sum_arrays_with_minimum_number_of_operations.py | 531 | 3.5 | 4 | from unittest import TestCase
from problems.N1775_Equal_Sum_Arrays_With_Minimum_Number_Of_Operations import Solution
class TestSolution(TestCase):
def test_minOperations(self):
self.assertEqual(3, Solution().minOperations(nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]))
def test_minOperations_1(self):
... |
c3d4009c9ddda5f3ea427d39213c278fc9790321 | Darnster/ManualAmend | /CryptProcess.py | 1,216 | 3.984375 | 4 | """
Module to encrypt/decrypt passwords to store in the config file
"""
from cryptography.fernet import Fernet
import sys
def encrypt(message: bytes, key: bytes) -> bytes:
return Fernet(key).encrypt(message)
def decrypt(token: bytes, key: bytes) -> bytes:
return Fernet(key).decrypt(token)
def generateKey():... |
5eeb0d2e63d72df91232b1ea19bee120a3fa69b2 | taoing/python_code | /4.0 gui/tkinter/calculate.py | 2,573 | 3.921875 | 4 | # -*- coding: utf-8 -*-
# 计算3场比赛的平均成绩
from tkinter import Tk, Frame, Label, Button, Menu, Entry, END
class Application(Frame):
'''创建框架模板'''
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
me... |
1ec3dd47f082fc78d6343f149b7384005e37cb35 | raahool007/CoffeeMachine | /Topics/Loop control statements/The mean/main.py | 155 | 3.65625 | 4 | total = 0
counter = 0
while True:
bucket = input()
if bucket == '.':
break
total += int(bucket)
counter += 1
print(total / counter) |
285a9572d229fbed2436a23ea367b29849a365a5 | BhargavReddy461/Coding | /Binary Tree/replace_eachNode_with_sum_of_previousAndNextEle_in_Inorder.py | 1,531 | 3.9375 | 4 | class getNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder(root, arr):
if not root:
return
inorder(root.left, arr)
arr.append(root.data)
inorder(root.right, arr)
def inordersum(root, arr, i):
... |
2feb3a433c6a39a1e74070e689b992d8979b61f0 | niepengfeiisgood/crn-lung-nodule | /src/crn_lung_nodule/nlp/base_sentence_splitter.py | 13,640 | 3.53125 | 4 | """
# <p>Title: Sentence Boundary program </p>
# <p>Create Date: 16:00:49 03/21/11</p>
# <p>Copyright: Copyright (c) Department of Biomedical Informatics </p>
# <p>Company: Vanderbilt University </p>
# @author Yonghui Wu
# @version 1.2
# <p>Description: This program is used to detect sentence boundary and format... |
7b6067622701b366b71be9343495f76051ed7e50 | ARSK-11/calculatorpy | /calculator01.py | 2,195 | 3.671875 | 4 | print(" ========= ========= ==== ")
print(" ===== == == ==== ")
print("== == == ==== culator python3")
print("== =========== ==== ")
print(" ===== == == ==========")
print(" ========= == ==... |
bd92c04905218e57a4f05db61e9299493797eaf2 | Txiaobin/thoughtwork | /python基础/第六节:如何操作文件/student_io.py | 521 | 3.625 | 4 | import csv
import json
def convert_file_format(input_file_path: str, output_file_path: str,
input_format: str = 'csv', output_format: str = 'json'):
csvfile = open(input_file_path,'r', encoding='utf-8')
jsonfile = open(output_file_path, 'w',encoding='utf-8')
fieldnames = ('name... |
fd0fc5cb9286653244ecb43b825cf9e3bcaabf2f | anmuer/pystudy | /tkinter/tk4.py | 3,192 | 3.890625 | 4 | # coding: UTF-8
from tkinter import *
# pack 布局
"""
root = Tk()
e = Entry(root)
e.pack(padx=10, pady=10)
e.delete(0, END)
e.insert(0, "default string...")
mainloop()
"""
# grid 布局
"""
root = Tk()
Label(root, text="作品:").grid(row=0, column=0)
Label(root, text="作者:").grid(row=1, column=0)
e1 = Entry(root)
e1.g... |
98b62b32098fbc5b30ab91a4adcfa83381fd50a8 | shashank31mar/DSAlgo | /Algorithms_DS/isBST.py | 825 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 25 12:32:14 2018
@author: shagupta
"""
import math
class Node:
def __init__(self,data,left=None,right=None):
self.data = data
self.left = left
self.right = right
def isBST(root):
return isBSTUtil(root,-math.inf,ma... |
bcd0b4986878958286eae020c0852276d2df37a2 | hamza-yusuff/CP-algo | /new upper lower.py | 290 | 3.671875 | 4 | test=int(input())
for i in range(test):
string=input()
ucount=0
lcount=0
digit=0
for w in string:
if w.isupper()==True:
ucount=ucount+1
elif w.islower()==True:
lcount=lcount+1
elif w.isdigit()==True:
digit=digit+1
print('Case {}:'.format(i+1),min(ucount,lcount)+digit)
|
e1e41401194db9ec89b3e2e8cb9d2530f4a717d6 | mooja/dailyprogrammer | /challenge310easy.py | 736 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Daily Programmer Challenge 310 Easy
#
# https://www.reddit.com/r/dailyprogrammer/comments/64jesw/20170410_challenge_310_easy_kids_lotto/
#
# 14 April 2017
from random import shuffle
def randomized_lists(names, lotto_len):
for idx, name in enumerate(names):
... |
b4e8f53921a146eb0cf98efe51508988ded6cb3e | sharkfinsid/LearnPython | /OOP2.py | 1,689 | 4.3125 | 4 | # Object Orientated Programming in Python Part 2
# Inheritance
class Pet: # Contains all the methods and attributes that all pet classes have
number_of_pets = 0 # Class variable (Not specific to any one instance)
def __init__(self, name, age):
self.name = name
self.age = age
Pe... |
6ee1b86d6c1e16457153bcd0b83ca0fb44286529 | PengfeiLv/LeetCode | /Level1/Sort/75. Sort Colors.py | 355 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/1/11 15:40
# @Author : Lvpengfei
# 荷兰国旗问题:快排思想
def sortColors(nums):
lo, hi = -1, len(nums)
i = 0
while i<hi:
if nums[i]<1:
nums[i], nums[lo+1] = nums[lo+1], nums[i]
lo += 1
i += 1
elif nums[i]>1:
nums[i], nums[hi-1] = nums[hi-1], nums[i]
hi -= 1
else:... |
044d258b07f9e0241ce15c246cc2e8f2b9ab1849 | Olegs-Adventures/MyRandomCodingAdventures | /LambdaCalculator.py | 3,774 | 3.65625 | 4 | """
Needs more work. But at least I kinda understand how it is supposed to work.
"""
from tkinter import *
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_input.set(operator)
def btnClearOperations():
global operator
operator = ""
text_input.set(""... |
456d2f3127fc58c9f11b35303db6bb720fd62390 | jkvilladiego/FOR-THE-WOMEN | /exercise7.py | 716 | 4.09375 | 4 | # EXERCISE 7
# Challenge - Classes Exercise
# Add a method to the Car class called age
# that returns how old the car is (2019 - year)
# *Be sure to return the age, not print it
import datetime
class Cars:
def __init__(self, yearmade, make, model):
self.yearmade = yearmade
self.make = make
... |
1ff76f92999b5ec98404d1a2cd519278702d35f7 | emdre/first-steps | /starting out with python/ch13t2 latin-english dict.py | 1,313 | 3.59375 | 4 | import tkinter
class DictionaryGUI:
def __init__(self):
self.main_window = tkinter.Tk()
self.word1_frame = tkinter.Frame(self.main_window)
self.word2_frame = tkinter.Frame(self.main_window)
self.word3_frame = tkinter.Frame(self.main_window)
self.word_button1 = tkinter.But... |
0ba98ef88fabe43e633796618b749c371879ab44 | hsuanwen0114/sharon8811437 | /HW5/BFS_06170226.py | 901 | 3.609375 | 4 |
# coding: utf-8
# In[18]:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def BFS(self, s):
s2 = []
queue = [s]
while queu... |
37e263b0ef2df549a385cfa723b2216c6bc55445 | MandeepKaurJS/The-Tech-Academy-Basic-Python-Projects | /mySimpleprograms in python/exx.py | 198 | 3.875 | 4 | from datetime import datetime
my_date = raw_input("Enter B'date in mmi/dd/yyyy format:")
b_date = datetime.strptime(my_date, '%m/%d/%Y')
print "Age : %d" % ((datetime.today() - b_date).days/365)
|
8c8f00deba08d1da622680855849b9f84707b2a5 | zmalpq/CodeWars | /moving zeros to the end.py | 403 | 4.0625 | 4 | #Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
#move_zeros([1, 0, 1, 2, 0, 1, 3]) # returns [1, 1, 2, 1, 3, 0, 0]
#solution
def move_zeros(array):
zeroLst = []
numLst = []
for i in array:
if int(i) == 0:
zeroLs... |
40c62a8d77fbc6c00bde1510cd8e45ad15b959fd | elliotjr/CSSE1001 | /Assignments/Assignment 1/assign1.py | 5,159 | 3.6875 | 4 |
###################################################################
#
# CSSE1001/7030 - Assignment 1
#
# Student Number: s4356917
#
# Student Name: Elliot Randall
#
###################################################################
#####################################
# Support given below - DO NOT CHANGE
###... |
61d6e9c89d71e0db32edd71c79c1a1a486f190e9 | Gaurav-Pande/DataStructures | /leetcode/arrays/sort_string_freq.py | 492 | 3.5 | 4 | # link:https://leetcode.com/problems/sort-characters-by-frequency/submissions/
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
counter = collections.Counter(s)
sorted_counter = sorted(counter.items(), key=lambda item: item[1], re... |
465a969cf307179ca1892072a567be63f6503cb7 | deang2021/PythonTrainingCourse | /app23.py | 300 | 3.96875 | 4 | # Working with Return Statements
# Create a function to square times a number via a placeholder 'number' and return statement
def square(number):
return number * number
# Return a value by passing an argument of 5
print(square(5))
# NOTE: by default python functions returns NONE.
|
344cb9b60bb328ab382a82422e4ffcc149efdd7e | cubomx/BlackJack | /Game.py | 8,677 | 3.609375 | 4 | from random import randint
class Card:
def __init__(self, name, value):
self.__name = name
self.__value = value
self.__hidden = False
@property
def hidden(self):
return self.__hidden
@hidden.setter
def hidden(self, value):
self.__hidden = value
@prope... |
e4163395699eb7a8018344bdd2dd25134f744754 | TGlove/AlgorithmLearning | /pyHundredTraining/1-10/T007.py | 137 | 3.5 | 4 | #-*- coding: UTF-8 -*-
# 将一个列表的数据复制到另一个列表中。
l = [1,2,3,4,5,6,7,8,9,11,15,17,19]
b = l[:]
print(b) |
c5722f5bbf81838e640a318850a0e01c6702ed3d | Veron-star/space-turtle-chomp | /game2.py | 618 | 3.8125 | 4 | #Turtle Graphic Game - Space Turtle Chomp
import turtle
#set up screen
turtle.setup(650,650)
wn = turtle.Screen()
wn.bgcolor('navy')
#create player turtle
player = turtle.Turtle()
player.color('darkorange')
player.shape('turtle')
player.penup()
player.speed(0)
#set speed variable
speed = 1
#define functions
def turn_l... |
ac7b2f8cce4d033c78c796dc78f58bb746a98a40 | jul-star/Stepik_BasicUse | /03/UTest/tst_3_3_07.py | 1,163 | 3.515625 | 4 | import unittest
from ex_3_3_07 import *
class TestCase_3_3_07(unittest.TestCase):
def test_cat3_1(self):
_lines = ['cat',
'catapult and cat',
'catcat',
'concat',
'Cat',
'"cat"',
'!cat?', ]
_... |
f35c43a18a823c7a45e8e94bc679ddd6862719b6 | nzh1992/Interview | /py_language/builtin_structure/p14.py | 563 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Author: niziheng
Created Date: 2021/6/4
Last Modified: 2021/6/4
Description:
"""
# 问题:
# 了解functools模块么?请介绍一下reduce的用法
# reduce函数将一个序列中,前一次调用的结果和sequence的下一个元素传递给function。
# recude函数共三个参数,function(自定义函数),sequence(序列),initial(初始值)
# initial默认值为0
from functools import reduce
if __name__ ... |
38a849612401790b883113ee3af608b0e989ab8e | swilliams0520/hello_git | /quantify.py | 946 | 3.734375 | 4 | import re
import string
import sys
from collections import OrderedDict
STRIP_PUNCT = str()
for i in string.punctuation:
STRIP_PUNCT += "\\" + i + "|"
def quantify_words(text_file):
word_count = dict()
with open(text_file, "r") as f:
words = f.read().casefold()
clean = re... |
3487a9828cf685fb41583a5d3f4ee2acaed4d77b | RRedwards/coursework | /05-Principles-Python/a5_WordWrangler.py | 4,003 | 3.9375 | 4 | """
Student code for Word Wrangler game
"""
import urllib2
import codeskulptor
import poc_wrangler_provided as provided
WORDFILE = "assets_scrabble_words3.txt"
# Functions to manipulate ordered word lists
def remove_duplicates(list1):
"""
Eliminate duplicates in a sorted list.
Returns a new sorted lis... |
946a45dc4c382ec460038628d7e1f265c5445ed2 | itsdj20/python_practise | /pyth/loop/l5.py | 138 | 3.734375 | 4 | list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
for num in list1:
if num<=150 and num%5==0 :
print(num)
|
8e92179c62e832a778302f80e404373bda220989 | s2t2/trumpmeter-py | /test/helper_text_test.py | 694 | 3.5 | 4 |
import string
from app.helper_text import main_clean, clean
def test_clean():
# it removes stopwords and punctuation, and lowercases the results:
assert clean("Hello world! is a message from me and us") == "hello world message us"
def test_main_clean():
# it converts text into a vector:
results = ma... |
fd7866956b72194886c1a3ebdd1102186fce7fea | causztic/digital-world | /mini_projects/guiwithkivy/raspberry.py | 916 | 3.625 | 4 | import RPi.GPIO as GPIO
from time import sleep
from firebase import firebase
url = "https://rasbpi-9b253.firebaseio.com/"
token = "tlXOUKslj8JwDSc1ymJ1lbh8n2tkfUIZb5090xlC"
# Create a firebase object by specifying the URL of the database and its secret token.
# The firebase object has functions put and get, that allo... |
7f56c30efdd9f360e714f6997c936e5b429a48dc | deadpyxel/simple-roguelike | /map_objects/tile.py | 741 | 3.640625 | 4 | class Tile:
"""Generic Tile class.
A tile may or may not be blocked and may or may not block sight
"""
def __init__(self, blocked: bool, block_sight: bool = None):
"""Tile initializer.
Arguments:
blocked {bool} -- blocking status of tile
Keyword Ar... |
48a23f9eef8297edd673e85c43d292f66b8547da | tanaymeh/nadl-new | /nadl/utils/other.py | 1,467 | 3.671875 | 4 | import numpy as np
from typing import List
class validateMatrixOp:
"""
Bunch of functions to validation matrix operations
"""
def matmulSizeCheck(tensor1: 'Tensor', tensor2: 'Tensor'):
"""Checks if given 2 tensors can be multiplied or not.
Args:
tensor1 (Tensor): First... |
9a69d154177969910238e224d872edcd1f5db899 | JimWeisman/PRG105 | /3.4 nested ifs.py | 1,192 | 3.859375 | 4 | #jim weisman
# Spring 2019
# RPG 105
# project 3.4 nested ifs
package_selected = input("Which package did you purchase?: ")
minutes_used = 0
if package_selected == "A" or package_selected == "a" \
or package_selected == "B" or package_selected == "b" \
or package_selected == "C" or package_selected ==... |
b2c85fb4f7df529d212495c3188e6d0110da4059 | ash/amazing_python3 | /tasks/t-009.py | 255 | 3.765625 | 4 | # Find all local maxima
data = [3, 6, 1, 2, 5, 4, 9, 5, 7, 2, 4]
# Scan data except edge elements:
print('List of found local maxima:')
for i in range(1, len(data) - 1):
if data[i-1] < data[i] > data[i+1]:
print(f'{data[i]} at position {i}')
|
04289a1cb1176ed59a7c3dbd4d4611082f6aa06c | awaisakram64/Statistic_operat | /operation.py | 1,178 | 3.5 | 4 | class Functions:
def Median(self,data):
ln=len(data) #length of data set
data=sorted(data)
if ln%2==0:
return (data[ln//2]+data[(ln//2)+1])/2
else:
return data[(ln//2)+1]
print('Hello')
def Mode(self,data):
dic={}
for i i... |
20a272df1d7776188ed3923b9bb496e134f531e3 | bwilson753/Workout-Updater | /workout.py | 2,735 | 3.609375 | 4 | #!/usr/bin/python
import sys
def modify(func, s):
input = open(sys.argv[1], 'r')
output = open(sys.argv[2], 'w')#creates a new text file
for x in input:
l = x.split(' ')
num = int(l[1])
r = func
result = r(num)
if((l[0] == 'walkLunge') | (l[0] == 'stepUp')):
... |
4fdac71e49e52a377c52a7f095199f0b94a243bd | zilongxuan001/benpython | /ex08.py | 1,590 | 3.9375 | 4 | #--coding: utf-8 --
#Date:20170815
#Title:ex08 打印,打印
#把 ’%r %r %r %r‘赋值给formatter.%r的意思是无论什么都打印出来,不限制格式。
formatter = '%r %r %r %r'
#打印1,2,3,4
print( formatter % (1, 2, 3, 4))
#打印‘one’,‘two’,‘three’,‘four’
print( formatter % ('one', 'two', 'three', 'four'))
#打印‘True’,‘False’,‘False’,‘True’
print( formatter % (True, ... |
857ad96a247c692da0ff37bcd7ea7fa93711bd53 | ViacheslavBor/PythonOOP | /car.py | 845 | 3.828125 | 4 | class Car(object):
def __init__(self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if self.price > 10000:
self.tax = 0.15
else:
self.tax = 0.12
def display_all(self):
print "Price:", self.price
print "Speed:", self.speed
print "Fu... |
e5ec7fdd82fb42fe59bf7955cfbf5f1c417c0cd2 | alejandromarroquin/functionsandalgorithmswithpython | /Diccionarios.py | 1,289 | 4.03125 | 4 | from os import system
system("cls")
my_dic={
'David':35,
'Fanny':22,
'Valeria':21,
'Iridian':23
}
print(my_dic)
print(my_dic['David'])
print('-----Acceder a un elemento si no sabemos si existe en el diccionario----')
print('El elemento no se encuentra en el diccionario')
print(my_dic.get('Ju... |
c8f3e1d85532c6069e65a8ae1d198b42bc4c7789 | jweissenberger/Google-Developers-Machine-Learning-Recipes | /Recipe#1/Machine Learning Recipes #1.py | 754 | 4.28125 | 4 | # This is a simple learning algorithm that predicts if an input item is an apple or an orange based on its weight and if
# it is considered bumpy or smooth
from sklearn import tree
# training set
features = [[140, 1], [130, 1], [150, 0], [170, 1]]
# the first feature is the weight of the fruit and in the secon... |
dd4c78fbc51c608be9a1520aa0d16364172ea30a | gabiks318/mission-manager | /Try.py | 400 | 3.671875 | 4 | from tkinter import *
def printt():
print(square.get(1.0,END))
def main(root):
root.mainloop()
root=Tk()
root.title("Mission Control")
root.geometry("580x450")
app=Frame(root)
app.grid()
square=Text(app,width=15,height=1,wrap=WORD)
square.grid(row=0,column=0)
square.insert(0.0,'meeeeeir')
b= Button(app,... |
74d8457f41b3e69cea700c0b844ea7561dad2a50 | greenfox-velox/szemannp | /week-05/day-3/todo_app/todo.py | 2,908 | 3.546875 | 4 | import sys
class ToDo():
def sort_user_input(self):
if len(sys.argv) == 1:
self.get_usage_info()
if len(sys.argv) >= 2:
self.handle_user_input()
def handle_user_input(self):
if sys.argv[1] == '-l':
self.get_todo_list()
elif sys.argv[1] == '-... |
e3e697b6aabe7e1bfe5f3ed3a45c785482c0f001 | heysushil/full-python-course-2020 | /2.7.operatores_excercise.py | 1,024 | 3.828125 | 4 | # 1. Arithmatic Op (Math ke sare signs):
a = 5
b = 15
print('\nAdd: ', a + b)
print('\nSUb: ', a - b)
print('\nMul: ', a * b)
print('\nDiv: ', b / a)
print('\nModules: ', a % b)
print('\nFloor: ', 50 // 5)
print('\nExponent: ', 10 ** 2)
# 2. Assigment Op (=):
a = 10
b = 20
# b = b + a
b += 5
print('\nB: ', b)
... |
50fed2831d0b0bde391b5e0726df18c91af7d7b7 | gitkenan/Data_Structures_and_Algorithms | /4.py | 444 | 4.1875 | 4 | # How do you find all pairs of an integer array whose sum is equal to a given number?
def pairs_which_sum_to(Arr, num):
pairs = []
for i in range(len(Arr)):
for j in range(len(Arr[i:])):
if Arr[i] + Arr[i + j] == num:
pairs.append([Arr[i], Arr[i + j]])
else:
... |
a34bff9000965069571596f7f68b91b0003cbec1 | akshays-repo/learn.py | /files.py/Artificial intelligence/opencv/intro/circle1.py | 322 | 3.5625 | 4 | import numpy as np
import cv2
# Create a black image
img = np.zeros((512,512,3))
# Draw a diagonal red line with thickness of 5 px and starting and ending point
img = cv2.circle(img,(447,347), 100, (123,0,255), -1) #center radius color thickness
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()... |
108d340169c6a2110d2719a236fcd6d09025a1b6 | SinCatGit/leetcode | /00244/shortest_word_distance_ii.py | 1,111 | 4.0625 | 4 | from collections import defaultdict
from typing import List
class WordDistance:
def __init__(self, words: List[str]):
self.locations = defaultdict(list)
for i, word in enumerate(words):
self.locations[word].append(i)
def shortest(self, word1: str, word2: str):
"""
... |
290fe745710662a4185714de320d89c9de328864 | srekan/pyLearn | /77_multiplication_table_while.py | 120 | 3.765625 | 4 | # 77_multiplication_table_while.py
n = 2
i = 1
while(i <= 10):
print(f"{n} * {i} = {n*i}")
i += 1 # i = i + 1
|
15cf3da491f5980f53a84b2b04edcff5bbfc9e40 | RadkaValkova/SoftUni-Web-Developer | /Programming Basics Python/Exam problems/Suitcases Load.py | 521 | 3.921875 | 4 | trunk_volume = float(input())
counter = 0
sum_suitcase_volume = 0
while True:
line = input()
if line == 'End':
print('Congratulations! All suitcases are loaded!')
break
suitcase_volume = float(line)
sum_suitcase_volume += suitcase_volume
if trunk_volume <= sum_suitcase_volume:
... |
b431fe4854aa80757509d2c671db4f99b6d7dee7 | singyuKang/school | /lab4.py | 1,963 | 4.09375 | 4 | ##201614792 컴퓨터공학과 강신규
##이프로그램은 그림을 그리는 프로그램입니다
from turtle import *
def drawStar():
for i in range(0,5):
forward(150)
right(144)
def drawRectangle():
for i in range(0,4):
forward(150)
right(90)
def drawTriangle():
for i in range(0,3):
forward(150)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.