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 |
|---|---|---|---|---|---|---|
4d6463478ed3d8fa7b7d3dbe7e0136db48efed0f | hatamleh12/htu-ictc5-webapps-using-python | /W2/S1/CA04-solutions/problem7.py | 443 | 4.34375 | 4 | # Create a function `sum_or_max(my_list)`, given a list, if the length of the list is even return the sum of the list. If the length is odd, return the maximum value in that list.
# sum_or_max(my_list)
def sum_or_max(my_list):
if len(my_list) % 2 == 0:
return sum(my_list)
return max(my_list)
# Call... |
d057c6883feded817ebe0fd8042e5da371d6116e | bpham2018/powerFunction | /powerFunctionMain.py | 1,214 | 4.40625 | 4 | # float_input function -------------------------------------------------------------------
def float_input( question ):
try:
baseNumber = float( raw_input( question ) ) # terminating case
return baseNumber
except ValueError: # if input is not a real number
float_input( "\nThats not a valid input,... |
97849d82edd698d6748423338e9f18ca7089d957 | Robooze/unittest_exe | /test_module.py | 1,143 | 3.8125 | 4 | import unittest
from functions import gen_to_list, division, int_division, dict_division
class TestFunctions(unittest.TestCase):
def setUp(self): # Initialized before every single test
self.number = 5
def test_gen_to_list(self):
self.number = 4 # overwrites the setup
self.assertEqu... |
79a5a1a485fd776e096cb59fee2d8d309517d36d | ra2003/Python-2 | /lecture8/fileread/add_numbers.py | 335 | 3.84375 | 4 | fileName = input("Enter the file name:")
total = 0
try:
with open(fileName) as f:
while(True):
l = f.readline()
if(not l):
break
total += int(l)
except ValueError:
print("Value error:", l.strip(), " is not a number")
except FileNotFoundError:
print("Could not find file:", fileName)
print("The tot... |
657e9916cc79752dd8ae95311d67a42c99b35bd2 | zs-horvath/chatbot | /scriptlets/mapping.py | 2,398 | 4.28125 | 4 | #! usr/bin/env python3
base = [1,2,3,4,5]
exponent = [5,4,3,2,1]
def power(x, y):
return(x**y)
# The mapping function gives an iterable, not a list
result = list(map(power, base, exponent))
print(result)
#Now for something completely different: mapping with lambda function
resultLambda = list(map(lambda x,y: x*... |
6bddc93d79b1f74fe13fedaa3b22fd8e793d1941 | yunbinni/CodeUp | /Python/1156.py | 45 | 3.84375 | 4 | print("odd" if int(input())%2!=0 else "even") |
c992bfc3c60dd0025220a001d8776d131f77f7b2 | yaoyaoding/lecture | /2017-09-05-nt-train/day1/data/kor/yyprod.py | 246 | 3.578125 | 4 | #!/usr/bin/python
from random import *
T = 5
print T
for t in range(T) :
n = randint(5,10)
U = (1<<randint(1,5)) - 1
s = randint(0,U)
print n, randint(1,n), s
for i in range(n - 1) :
print randint(0,U),
print s
|
8f237f1336de4491e98c85a8c62d9afb2d190ab0 | dongIhwa/Python_practice | /0715/conditionLab3_0715.py | 217 | 3.75 | 4 | # [실습 3]
import random
grade = random.randint(1,6)
if grade >= 1 and grade <= 3:
print(grade, "학년은 저학년입니다.")
elif grade>= 4 and grade<= 6:
print(grade, "학년은 고학년입니다.") |
a32f9b2238bc3dc9b3c4e7b115af4acd273950b6 | kyrsant34/exercises | /valid_braces.py | 1,087 | 4.34375 | 4 | # Write a function that takes a string of braces, and determines if the order of the braces is valid. It should
# return true if the string is valid, and false if it's invalid.
#
# This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {}.
# Thanks to @arnedag f... |
9fea95f7f7d3d3497c58bd157aaac22313de556c | GwenIves/Scripts | /src/hoi2_tech.py | 4,596 | 3.53125 | 4 | #!/bin/env python3
#
# Generate a report of different research teams performances for all available technologies
# in the Paradox Interactive's game Hearts of Iron 2
# usage: tech.py
# <country's research teams definition csv file>
# <list of all technology definition files>
#
import sys
def calc_research_time(t... |
bebdcad009f7e3d36b23dae37510ee05cf3f393c | alisonlauren/Catch-Charlie | /oldfile.py | 11,768 | 4.25 | 4 | #The import function down below uses time, random, and math.
#The import here goes into our library and uses those components to make our game work.
import pygame
import time
import random
import math
#The first thing is we have a parent class called Enemy, and it's going to have Monster and Goblins in here.
#Because... |
6eafaa8be33a4a9090e54c643c67e246bf778966 | TrellixVulnTeam/tic-tac-toe_P4BI | /controller.py | 3,788 | 3.609375 | 4 | from tkinter import *
from XO import XO
class Controller:
def __init__(self):
self.numOfClicks = 0
self.symbol = ""
self.root = Tk()
self.xo = XO()
self.root.title("tic tac toe")
self.symbolTexts = []
self.buttonList = []
for i in range(9):
... |
e25c390301c7f13870e52a1d06fa286b167f87d7 | Clint1080/databases | /process.py | 925 | 3.84375 | 4 | log_file = open("um-server-01.txt") # This line brings in the data to our python script so we can manipulate it
def sales_reports(log_file): # This is like creating a "View" or "Report" to view the data
for line in log_file: # Start of the for loop
line = line.rstrip() # rstrip is a methon that removes ... |
8d84e67c9da1e6986ae0bfca661633da7b9b06cc | clhansen24/GP_analysis | /clustering.py | 7,400 | 3.5 | 4 | '''
Clustering approach
- Particles of each size are separately
For each size:
- Particles within a specific x,y are grouped
- The spread in the z is determined for each group
- The median spred in the z is set as the z threshold for de-convolution
- Particles within the x,y,z, threshold are represented as just the cen... |
4a71eb3fffe4b73a2cf11b6daff09a7f11a610fa | chinchponkli/pyalgorithms | /search algorithms/linearSearch.py | 254 | 3.921875 | 4 | '''
Time Complexity : O(n)
Auxiliary Space : O(1)
'''
def linearSearch(arr, k):
for i in range(len(arr)):
if arr[i] == k:
return i
return -1
arr = [1, 2, 3, 4, 5, 6, 7, 8]
for i in range(10):
print (linearSearch(arr, i)) |
a5a5692aafe4bc822f59035e5fde620ca732f65f | jmseb3/bakjoon | /Prgrammers/lv2/배달.py | 829 | 3.515625 | 4 | from collections import defaultdict
import heapq
def solution(N, road, K):
INF = int(1e9)
graph = defaultdict(list)
road.sort()
for a, b, c in road:
graph[a].append((b, c))
graph[b].append((a, c))
distance =[INF] *(N+1)
def dijkstra(start):
distance[start] = 0
... |
8127db4038684ed69ffd210c64fcdcd54452c76d | archanakul/ThinkPython | /Chapter11-Dictionary/ReverserDict.py | 3,743 | 4.125 | 4 | #PROGRAM - 40
"""
creates a dictionary that maps from frequencies to letters
1. SINGLETON is a list that contains a single element
2. Lists can be values in a dictionary, as this example shows, but they
cannot be keys (TypeError: list objects are unhashable)
3. Basically have to be hashable/immu... |
6a1ecddd91818fa4e125d1eca5aada408b859dac | rajlath/rkl_codes | /Rosalind/algorithm_heights/sq.py | 937 | 3.5625 | 4 | def multiply(a, b):
lena = len(a)
c = [[0] * lena for _ in range(lena)]
for i in range(lena):
for j in range(lena):
for k in range(lena):
c[i][j] += a[i][k] * b[k][j]
return c
def has_sqr(adj):
mult_matrix = multiply(adj, adj)
print( any([i != j and mult_ma... |
88105fea79dbd54f6e5368e4f56ce5e997e1d0c8 | phsh/potential-computing-machine | /phshpy/roman-numerals.py | 1,783 | 4.1875 | 4 | #!/usr/bin/python
'''
Roman numerals come from the ancient Roman numbering system. They are based on specific letters of the alphabet which are combined to signify the sum (or, in some cases, the difference) of their values. The first ten Roman numerals are:
I, II, III, IV, V, VI, VII, VIII, IX, and X.
The Roman nume... |
e53546948c4ea0108a81ef46ee40861f95824db6 | GT-RAIL/derail-fetchit-public | /task_execution/task_executor/src/task_executor/ops.py | 4,645 | 3.71875 | 4 | #!/usr/bin/env python
# The operations that can be specified in the YAML
from __future__ import print_function, division
import rospy
# Private helper functions
def _get_heap_for_var_name(var_name, variables, params):
"""Given a variable name, return the 'heap' that contains it"""
if var_name in variables:... |
655c60af01012e532a9537bc8d147da6af6280ec | DKanyana/PythonProblems | /10_MinMaxDiff.py | 290 | 3.875 | 4 | def minmax_diff(nums):
min_num = nums[0]
max_num = nums[0]
for num in nums:
if num < min_num:
min_num = num
elif num >max_num:
max_num = num
return max_num - min_num
nums = [1,3,1,2,6,79,10]
print(minmax_diff(nums)) |
6d271e230658260af04899d5e7a783cf78a9c6ad | TarandeepSingh562/BasicTemperatureConverter | /TempConverter.py | 2,516 | 4.09375 | 4 | from tkinter import *
from tkinter import messagebox
#Creates a class
class MyGUI:
def __init__(self):
root = Tk()
root.geometry("400x200")
root.title("Temperature Conversion")
# creates a Frame
frame = Frame(root)
frame.pack(fill = BOTH, expand = True)
#cr... |
dc2c9eb1e4c9b42ceb4c90865431c831680d8a6d | DincerDogan/Python-2 | /Visualizing Geographic Data-223.py | 2,495 | 3.515625 | 4 | ## 1. Geographic Data ##
import pandas as pd
airlines=pd.read_csv("airlines.csv")
airports=pd.read_csv("airports.csv")
routes=pd.read_csv("routes.csv")
print(airlines.iloc[0])
print(airports.iloc[0])
print(routes.iloc[0])
## 4. Workflow With Basemap ##
import matplotlib.pyplot as plt
from mpl_toolk... |
4e5f4a2032485b12db03776de3ddca39a458a47a | KaterinaMutafova/SoftUni | /Python Advanced/10. Exam_preparation/Exam_ex1_24_10_2020.py | 1,032 | 3.703125 | 4 | from collections import deque
def get_the_shortest_job(list_j):
shortest_j = list_j[0]
index_shortest_j = 0
for index in range(len(list_j)):
if list_j[index] < shortest_j and list_j[index] != 0:
shortest_j = list_j[index]
index_shortest_j = index
elif list_j... |
92a6c3d77f6cc878dc0e3a873f149f9b473bf1d2 | AngelFA04/practice_python_excercises | /excercise_8/main.py | 1,149 | 4.09375 | 4 | def menu():
print("""
SELECT ONE CHOICE:
1 - Rock
2 - Paper
3 - Scissors
""")
def ask_player_moves():
menu()
choices = {'1': 'ROCK', '2': 'PAPER', '3': 'SCISSORS'}
move_p1 = choices.get(input('Turn player 1: '))
move_p2 = choices.get(... |
825b5e685b9e1336f43006a2478d217d01558a13 | staryjie/Full-Stack | /day9/auth.py | 192 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import getpass
username = input("Pls enter your username: ").strip()
passwd = getpass.getpass("Pls enter your password: ")
print(username,passwd) |
d6b14095db3c0502cb5cde47caad628e3f8085d4 | saharma/PythonExercises | /Lab2/lab2ex8.py | 157 | 3.53125 | 4 | grades = [9, 7, 7, 10, 3, 9, 6, 6, 2]
print(grades.count(7))
grades[len(grades)-1] = 4
print(max(grades))
grades.sort()
print(sum(grades)/float(len(grades))) |
1ddb0796dad90a69b7b63f020d46ce33627b7484 | Rodrigodebarros17/Livropython | /CAP11/11-1.py | 537 | 3.890625 | 4 | import sqlite3
conexao = sqlite3.connect("precos.db")
cursor = conexao.cursor()
cursor.execute('''
create table produtos(
produto text,
preco float
)
''')
while True:
produto = input("Favor, informe o nome do produto(enter para sair do programa):")
if produto == "":
break
... |
4c83baad4e6a8cbac220ec6fc12282313d779886 | michelle100320206/programming_for_big_data_MC10032026 | /CA1/calccode.py | 1,924 | 3.953125 | 4 | import math
#import python module to run calculations
class mathcalc(object): #setting up class for calculator. can reference this class in seperate file to access functions
def add(self,x,y):
number_types = (int, long, float, complex)
if isinstance(x, number_types) and isinstance(y, number_types):
return... |
e5bf6281a63f38d85efa563a4fb6489dc6baa13a | sanddragon2004/python | /menu1.py | 536 | 4.5 | 4 | print "Enter a selection here. This is where you choose what function you want"
selection = raw_input("what is your selection?")
# this is an if statement file
#create a menu that will look at 3 different options and 2 different sub options.
if selection is == "1":
print "do you want to do this function"
#do st... |
18c656d4e69e8c6ee881c0c9a4bd9af8908196c9 | GlenboLake/DailyProgrammer | /C204E_remembering_your_lines.py | 2,868 | 4.21875 | 4 | '''
I didn't always want to be a computer programmer, you know. I used to have
dreams, dreams of standing on the world stage, being one of the great actors
of my generation! Alas, my acting career was brief, lasting exactly as long as
one high-school production of Macbeth. I played old King Duncan, who gets
brutally mu... |
1deabf9dcc2a4f0b6a166c2b1b080249d0e95783 | upasek/python-learning | /string/sum_digit.py | 352 | 4.1875 | 4 | #Write a Python program to compute sum of digits of a given string.
#here x.isdidit() function also we can use
def char(string):
digit = "0123456789"
sum = 0
for m in string:
if m in digit:
sum = sum + int(m)
return sum
string = input("Input the string : ")
print("Sum of digits of ... |
63f0257b23344f3b8ea3ba5805cd562ba1c2edd5 | rk385/tathastu_week_of_code | /Day3/program1.py | 132 | 4.34375 | 4 | string=input('enter a string: ')
rev=''
for i in range(len(string)-1,-1,-1):
rev=rev+string[i]
print('reversed string is:',rev)
|
5b2d99e26438acf8182e97293011e245bbfd813e | AmandaCasagrande/Entra21 | /Aula 05/exercicio12.py | 689 | 4.21875 | 4 | # Exercicio 12
#
# Crie um programa que peça 2 números.
#
# Depois mostre um menu interativo contendo 5 operações matemáticas do python
# (adição, subtração, multiplicação, divisão e expoente)
#
# Peça para o usuário escolher uma destas opções e mostre o resultado da operação escolhida.
num1 = int(input("Digite um ... |
e7ce6373df103dfcdf397f00e41013eb36aeeacf | Hety06/SNEL | /SNEL/caesar.py | 1,646 | 3.796875 | 4 | def shift(letter, shift_amount):
unicode_value = ord(letter) + shift_amount
if unicode_value > 126:
new_letter = chr(unicode_value - 95)
else:
new_letter = chr(unicode_value)
return new_letter
def encrypt(message, shift_amount):
result = ""
for letter in message:... |
87ae3c79274a7121f93e8f8fc70048d18f301f5b | Haseebvp/Anand-python | /chapter 1&2/triplets.py | 151 | 3.859375 | 4 | #a function triplets
def triplets(a,b):
return [(x,y,x+y) for x in a for y in b if a.index(x)==b.index(y)]
a=range(4)
b=[4,3,2,1]
print triplets(a,b)
|
025ff862069d73033c8a0b965ecfd23d9d87e057 | 01-Jacky/Python-Things | /python_features/generator.py | 1,219 | 4.15625 | 4 | import time
def some_function():
i = 1
while True:
yield i*i
i += 1
x = some_function()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
''
def fibonacci_iterative(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a + b
return a
def fibonacci_generator():
"... |
dd6b10f0ce310c0ac70c32f5d473e1e263217259 | Anshnema/Programming-solutions | /balanced_binary_tree.py | 484 | 3.6875 | 4 | """
Ques. Balanced Binary Tree
T.C. = O(n)
S.C. = O(n)
"""
class Solution:
def isBalanced(self, root) -> bool:
def dfs(root):
if(root is None):
return [True, 0]
left = dfs(root.left)
right = dfs(root.right)
balanced =... |
9e54b27c51872589a0c48a8fd5c36a0ea0307e77 | kopchik/itasks | /round5/epi/18.9_word_stream.py | 397 | 3.953125 | 4 | #!/usr/bin/env python3
#find majority element
def find_majority_elem(stream):
candidate = None
count = 0
for w in stream:
if w == candidate:
count +=1
continue
else:
if count == 0:
count = 1
candidate = w
else:
count -= 1
return candidate
if __name__ =... |
7335c674baa2c28b0215714e058e8d29c6bb8eb2 | k0malSharma/Competitive-programming | /CHEALG.py | 295 | 3.546875 | 4 | for _ in range(int(input())):
s=input()
st=""
c=1
for i in range(len(s)-1):
if(s[i]==s[i+1]):
c+=1
else:
st+=s[i]+str(c)
c=1
st+=s[len(s)-1]+str(c)
if(len(st)<len(s)):
print("YES")
else:
print("NO")
|
ac5b65e6db3ca8e8ae96f9e411fc3eb542af96c1 | SeanM743/SmallProjects | /longest_pal.py | 1,019 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 16 19:26:50 2019
@author: snama
"""
def longest_subpalindrome_slice(text):
"Return (i, j) such that text[i:j] is the longest palindrome in text."
if text == '': return (0,0)
text = text.upper()
lens = [grow(text,start,end)
... |
aa35d19a5f16255708613b87af3c2c355fbf9066 | agnathomas/Python | /cycle5/rectangle.py | 1,436 | 4.21875 | 4 | class rectangle():
def __init__(self, breadth, length):
self.breadth = breadth
self.length = length
def area(self):
return self.breadth * self.length
def perimeter(self):
return 2 * (self.breadth + self.length)
print("Rectangle1")
a = int(input("Ent... |
a8f6de10660f6ce44972000773b564db14e470e8 | jjason/RayTracerChallenge | /ray_tracer/patterns/ring.py | 1,630 | 4.25 | 4 | import math
from patterns.pattern import Pattern
class Ring(Pattern):
"""
The ring pattern. A ring pattern has two colors and changes based upon
the x and z coordinates of the point. The color is determined based upon
the distance of the point from the point (x=0, y=?, z=0), i.e., circles
in th... |
bd37f4ea222b21e5b66738029501efd8269c47d3 | patchaiy/Python-1 | /pro40.py | 150 | 3.609375 | 4 | st1="dhoni"
st2=input()
val1=list(set(st1)-set(st2))
val2=list(set(st2)-set(st1))
val=len(val1)+len(val2)
if val==0:
print("yes")
else:
print("no")
|
62aba7dfc5a099a2915eaa1b00276f5f0adaf9be | weltonvaz/Primos | /fatorar1.py | 664 | 3.921875 | 4 | #!/usr/bin/python
import os
def cls():
os.system('cls' if os.name=='nt' else 'clear')
cls()
def get_prime_factors(number):
"""
Return prime factor list for a given number
number - an integer number
Example: get_prime_factors(8) --> [2, 2, 2].
"""
if number == 1:
return []... |
54ecc643c11545eaee3c64720cbd2a14f99e0527 | palathip/bbb_basic_python | /CH2-Condition/LAB 2-5 EX.py | 3,718 | 3.9375 | 4 |
print"Calculator"
def calculator():
input_1 = input("Enter Input 1 :")
switch = True
st_run = True
while switch:
#input_1 = input("Enter Input 1 :")
operand = raw_input("Enter Operator :")
input_2 = input("Enter Input 2 :")
if operand.lower() == "clear" or operand... |
79ca241b02a85248abc3d4f6335a252219edc1cf | alehatsman/pylearn | /py/lists/insert_sorted.py | 714 | 4.25 | 4 | from lists.linked_list import Node
def insert_sorted(ll, value):
"""
Insert element in sorted linked list.
Find position and replace pointers.
Time complexity: O(N)
Space complexity: O(1)
"""
insert_node = Node(value)
current_node = ll.head
if not current_node:
ll.head = ... |
3acd792dcf4d6510b5989e21ca9eae8d6b9daba8 | tnakaicode/jburkardt-python | /geometry/circles_intersect_area_2d.py | 2,376 | 4.28125 | 4 | #! /usr/bin/env python
#
def circles_intersect_area_2d ( r1, r2, d ):
#*****************************************************************************80
#
## CIRCLES_INTERSECT_AREA_2D: area of the intersection of two circles.
#
# Discussion:
#
# Circles of radius R1 and R2 are D units apart. What is the area of
# ... |
9ea208216835c0d35e1fe4677044a6cd4a9850b6 | vuminhph/randomCodes | /DataStructure/merge_sorted_linked_lists.py | 1,539 | 4.09375 | 4 | def main():
list1 = Node(1)
list1.insert_last(Node(2))
list1.insert_last(Node(4))
list2 = Node(1)
list2.insert_last(Node(3))
list2.insert_last(Node(4))
print(merge_sorted_lists(list1, list2))
class Node:
def __init__(self, val):
self.value = val
self.next = None
... |
e3df69fd0dff76dd7a73c26835902e1b97aeebaa | maze88/rubiks_shuffler_and_timer | /move_class.py | 2,192 | 4.3125 | 4 | """This module contains the class Move, for creating Rubik's cube moves.
For an explanation of Rubik's cube notation checkout the following article
in the Twisty puzzle wiki: https://ruwix.com/the-rubiks-cube/notation/
"""
import random
FACES = ('L', 'R', 'U', 'D', 'F', 'B')
CLOCKWISE_TURNS = (-1, 1, 2) # Negative me... |
59df46c65a8f6255d277025f885bed0d948fece0 | zedzijc/advent_2018 | /Day_9/Advent_9a.py | 2,102 | 3.671875 | 4 |
class Marble(object):
def __init__(self, value, previous_marble, next_marble):
self.marble_value = value
self.previous_marble = previous_marble
self.next_marble = next_marble
def set_next(self, next_marble):
self.next_marble = next_marble
def next(self):
return se... |
47768f5d799434f896b095d07c256c81cbc52501 | KrasilnikovNikita/python | /3-4/array14.py | 190 | 3.796875 | 4 | N = int(input())
a = []
b = []
for i in range(N):
a.append(int(input()))
for i in range(0,N,2):
b.append(a[i])
for i in range(1,N,2):
b.append(a[i])
print(b)
|
82b2d2d234d6eaf7ffb3d9b687286b374d807944 | ruselll1705/home | /home_work3_1.py | 109 | 3.640625 | 4 | import sys
x=int(sys.argv[1])
y=int(sys.argv[2])
if x>y:
s=x-y
elif x<y:
s=x+y
else:
s=x
print(s) |
7ef84646ae3a697a2d581e15770fde5e6e5c2435 | whiterabbitPL/Mateusz | /test.py | 1,616 | 4 | 4 | import unittest
from world import World
class TestWorld(unittest.TestCase):
def test_constructor(self):
# Non-argument constructor is working
w = World()
self.assertEqual(w.world, 'Earth')
# Argument constructor is working
sw = World("Mars")
self.assertEqual(sw.world, 'Mars')
# Wrong argu... |
fada9cb25504e9898b813dece5d97875a912dc80 | seddon-software/python3 | /Python3/src/_Exercises/src/Basic/ex3-1.py | 277 | 3.921875 | 4 | """
Write a program that prints out the sum, difference, product
and dividend of two complex numbers.
"""
x = 5 + 3j
y = 4 - 2j
print( "sum = ", x + y )
print( "difference = ", x - y )
print( "product = ", x * y )
print( "dividend = ", x / y )
|
85be20cecff931c2831034b14fe262222d069d53 | xiaoyongaa/ALL | /函数和常用模块/装饰器2.py | 413 | 3.921875 | 4 | def outer(fu):
def inner(*args,**kwargs): #原来函数传参几个,装饰器的函数就要要几个传参
print("bro")
R=fu(*args,**kwargs) #取得原函数的返回值
print("after")
return R #原函数的返回值返回给inner
return inner
@outer
def f1(a):
print(a)
return "1111111111"
@outer
def f2(a,b):
print("F2")
return "222... |
af8365520a99e9999d7c2e8422c958dfecce4a31 | wpyzik/motion | /Resizing etc/script1.py | 901 | 3.828125 | 4 | import cv2
#if color = 1, if black and white = 0,3rd parameter -1 = color image bt also alpha channel meaning you have transparency in the image
img=cv2.imread("galaxy.jpg",0)
print(type(img))
print(img)
print(img.shape)
#(1485 rows and 990 columns)
print(img.ndim)
#3 dimensions
cv2.imshow("Galaxy",img)
#it resized... |
80fb30a2a9319ca4ff8a0abfd734afa0afac7c5d | shubam-garg/Python-Beginner | /Conditional_Expressions/11_practice_test6.py | 244 | 3.953125 | 4 | # 7) Write a program to find out whether a given post is talking about "Shubam" or not
post="My Name iS ShUbaM"
p=(post.lower())
if("shubam" in p):
print("shubam is present in the post")
else:
print("shubam is not present in the post") |
0bf6fbcaa9b70ecd46b246bf2caa5bdf5fb8913b | xiaomengyu/test | /购物车.py | 1,576 | 3.890625 | 4 | # Time : 2018/3/19 17:35
# Author : Jack
# File : 购物车.py
# Software: PyCharm
product_list = [
('Mac',9000),
('kindle',800),
('tesla',30000),
('python book',110),
('bike',2000),
]
saving = input('please input your saving:')
shopping_car = []
if saving.isdigit():
saving = in... |
838b9c54436f93d1fe28701beb2eababb284f20e | morita657/Algorithms | /Leetcode_solutions/preorderTraversal.py | 1,685 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if root == None:
return []
output... |
63b4264d0465379c31487866eaefe2d88e1a5813 | donzpixelz/psychic | /cgi-bin/answer_census.py | 12,114 | 3.578125 | 4 | import pymc as pm
import numpy as np
import pandas as pd
import re
import xml.etree.ElementTree as ET
import urllib2
import sqlite3
import answer as ans
from StringIO import StringIO
from zipfile import ZipFile
#Some helpful functions
def hasNumbers(strings):
'''Returns true if any of the strings in the 'strings'... |
46d04e00b89e2417b35d2f86602f464acf0a2d12 | miguelex/Universidad-Python | /POO/lee_archivo.py | 527 | 3.515625 | 4 | archivo = open("prueba.txt", "r")
#print(archivo.read())
#Leer algunos caracteres
#print(archivo.read(5)) #Si no comento el print anterior no se me mostrara nada porque ya leyo el archivo
#print(archivo.read(3))
#Leer lienas completas. Tengo que comenbtar lo anterior
#print(archivo.readline())
#print(archivo.readlin... |
e7c8230bdfd5b25a563b9bdba2a9ca1ac4a33ec1 | BlakeERichey/University-Projects | /Python/Library Repo/BTree.py | 3,346 | 4.125 | 4 | ##Blake Richey
#Used to create a binary tree that is sorted
#when a value is added to the binary tree that already exists in the tree,
#that value is always added to the right of the corresponding node
class BTNode():
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def... |
2fde6515a4576929b0d26bf44695af803752f23e | lukasbasista/Daily-coding-problem | /012/main.py | 1,140 | 4.375 | 4 | """
This problem was asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function
that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1,... |
f267c1c2904f7d62803a7189c6d14da9f946190d | kenzzuli/hm_15 | /01-04_python基础/08_面向对象基础/hm_05_初始化方法.py | 261 | 3.703125 | 4 | class Cat:
def __init__(self):
print("调用初始化方法")
self.name = "Tom"
def eat(self):
print("%s eats fish" % self.name)
# 创建对象时,会自己调用初始化方法__init__
tom = Cat()
print(tom.name)
tom.eat()
|
7ddbdf6c2df16cbe246732592edef367fa162c47 | matheustxaguiar/Programming-Period-1 | /apnp23.py | 1,487 | 3.90625 | 4 | #C:\Users\mathe\PycharmProjects\exerciciosifes\venv
# -*- coding: utf-8 -*-
#
# apnp23.py
#
# Copyright 2021
# Autor: Matheus Teixeira de Aguiar
# Matricula: 20202BSI0322
#
# Este programa:
# a) Definir uma função em Python 3 que calcule o valor do máximo divisor comum (mdc) entre dois números inteiros
# positiv... |
99c73ffcaf830b9812f86b71899b9bf144d83423 | joelburton/bst-practice | /contains.py | 1,118 | 3.65625 | 4 | """Does binary search tree contain node?"""
from bst import bst
def contains(node, val):
"""Does tree starting at node contain node with val?
>>> contains(bst, 5)
True
>>> contains(bst, 1)
True
>>> contains(bst, 2)
False
>>> contains(bst, 6)
True... |
4fad63f4fabfcd86e643ab9d497ef25ee0599086 | dualfame/YZUpython | /0506 lesson 5/def 7.py | 232 | 3.796875 | 4 | # 高階函數 advenced function
def add(x):
return x + 1
def subs(x):
return x - 1
def adv_func(func, x):
return func(x)
x = 20
x = adv_func(add, x)
print(x)
z = [add, subs]
for z in func:
print(adv_func(z, x))
|
c65ba04bf422f4b174f3afd1541cf125a94ef03d | Aasthaengg/IBMdataset | /Python_codes/p02660/s248987384.py | 608 | 3.53125 | 4 | def prime_factorize(n):
a = []
while n % 2 == 0:
a.append(2)
n //= 2
f = 3
while f * f <= n:
if n % f == 0:
a.append(f)
n //= f
else:
f += 2
if n != 1:
a.append(n)
return a
dum = prime_factorize(int(input()))
dum_len = l... |
90d70a86e0d75329c0e2b784f779c84a0dd440f7 | VineeshaKasam/Leetcode | /isPalindromeLL.py | 667 | 3.96875 | 4 | '''
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def isPalindrome(self, head):
strs = []
... |
3c2ca7c14755331e1ea8b7eccb82a29db99daf07 | EricMontague/Leetcode-Solutions | /medium/problem_63_unique_paths_2.py | 3,648 | 3.890625 | 4 | """This file contains my solutions to Leetcode problem 63: Unique Paths 2."""
# Bottom Up Solution more space efficient
# time complexity: O(mn), where 'm' is the number of rows and 'n'
# is the number of columns
# space complexity: O(m)
class Solution:
def uniquePathsWithObstacles(self, grid: List[List[int]]) -... |
9447091ef7de3195b13ae90fa8bb0d02151ed219 | bitwoman/curso-em-video-python | /Curso de Python 3 - Mundo 3 - Estruturas Compostas/#078.py | 927 | 4.09375 | 4 | # Exercício Python 078: Faça um programa que leia 5 valores numéricos e guarde-os em uma lista.
# No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista.
randomNumbers = []
bigger = smaller = 0
for n in range(0,5):
number = int(input('Enter a number: '))
randomNumbers.... |
01fca0a0da3e619c8742e75be677835b6d9d0386 | GefestLAB/pyrex | /pyrex/earth_model.py | 3,676 | 3.546875 | 4 | """
Module containing earth model functions.
The earth model uses the Preliminary Earth Model (PREM) for density as a
function of radius and a simple integrator for calculation of the slant
depth along a straight path through the Earth.
"""
import logging
import numpy as np
logger = logging.getLogger(__name__)
EAR... |
69aea9de4c459e07655126c034f377972a2eb40b | Vanditg/Leetcode | /Best_Time_Buy_Sell_Stock_II/EfficientSolution.py | 1,721 | 3.984375 | 4 | ##==================================
## Leetcode
## Student: Vandit Jyotindra Gajjar
## Year: 2020
## Problem: 122
## Problem Name: Best Time to Buy and Sell Stock II
##===================================
#
#Say you have an array prices for which the ith element is the price of a given stock on day i.
#
#Desig... |
16fbb6af6eef35d2af3b8d192509546150d23750 | raf-espanol/pythonTest | /d2.py | 294 | 3.75 | 4 | import os
list=['dog','cat','frog','turtle','cat','frog','cat','dove']
def countwords(list):
dict={}
for i in range(len(list)):
if list[i] in dict.keys():
dict[list[i]]+=1
else:
dict[list[i]]=1
for k,v in dict.items():
print "%d,%s" % (v, k)
countwords(list)
|
4b6aed931e00a0f2d01433019df20ef6765e3626 | argysamo/InvertedIndex | /Map.py | 1,101 | 3.609375 | 4 | #!/usr/bin/python
"""This Map is written using Python iterators and generators for better performance."""
import sys, os
def read_input(file):
for line in file:
#delete spaces from line
line = line.strip()
# split the line into words
yield line.split()
def getFileName():
# I use con... |
810ef9c57dca05962762f386a2455ad576e70a92 | MarthaSamuel/foundation | /areacalculations.py | 524 | 4.125 | 4 | # Author: Dimgba Martha O
# @martha_samuel_
# 03 finding area of a rectangle
length = 10
width = 2
Area = length * width
print('The area of the rectangle is ' + str(Area))
# finding sum of two areas using definitions
def area_triangle(base, height):
return base * height / 2
area_a = area_triangle(5, 4)
area_b =... |
bc926b95d2e450f384c167a83bd0c78b3e42d4ab | OlegSudakov/Programming-Problems | /hackerrank/coding_interview/strings_anagrams.py | 733 | 3.765625 | 4 | # https://www.hackerrank.com/challenges/ctci-making-anagrams
def number_needed(a, b):
aLetters = {}
bLetters = {}
for char in a:
if char in aLetters:
aLetters[char] += 1
else:
aLetters[char] = 1
for char in b:
if char in bLetters:
bLetters[cha... |
5ee64f70940ee4abc0f91b68a4f5cd2edd161a03 | akimi-yano/algorithm-practice | /lc/review2_718.MaximumLengthOfRepeatedSubarr.py | 1,383 | 3.734375 | 4 | # 718. Maximum Length of Repeated Subarray
# Medium
# 4714
# 114
# Add to List
# Share
# Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.
# Example 1:
# Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
# Output: 3
# Explanation: The repeated subarray... |
3484c9805ea5cc1e06f9b3e2760064c36995503e | UB68DF/pythontrainings | /listcomprehension.py | 425 | 3.953125 | 4 | #list comprehension
list = []
for letter in 'word':
list.append(letter)
print(list)
print('\n')
list = [letter for letter in 'word']
print(list)
print('\n')
list1 = [x**3 for x in range(1,11)]
print(list1)
print('\n')
list2 = [number for number in range(1,11) if number%2 == 1]
print(list2)
celsius = [-10,-5,0... |
9d170cd340ce40b26668a11103b38355c8c93007 | eBetcel/contact-list-linked-list | /main.py | 1,319 | 3.953125 | 4 | from Contact import Contact
from LinkedList import LinkedList
from Node import Node
import os
if __name__ == "__main__":
aux = -1
new_list = LinkedList()
while(aux != 0):
aux = int(input("1 - Add contact\n2 - Delete contact by name\n3 - Delete contact by index\n4 - Show Phone Book\n0 - E... |
1b85739b38e89a682afbe13615220ca80c7d8937 | TerryLun/Code-Playground | /lcm_using_gcd.py | 166 | 3.5625 | 4 | """
https://en.wikipedia.org/wiki/Least_common_multiple
"""
from euclidean_gcd import gcd
def lcm(num1, num2):
return abs(int(num1 * num2 / gcd(num1, num2)))
|
c3247a8417cde1ff814bda09ee92aa2b45cecfd5 | Vinay-Harke/codemonk-solutions | /Monk and Suffix Sort.py | 183 | 3.84375 | 4 | # Write your code here
s1,pos=input().split()
pos = int(pos)
all_suffix = []
for i in range(len(s1)-1,-1,-1):
all_suffix.append(s1[i:])
all_suffix.sort()
print(all_suffix[pos-1])
|
632829d9fea1b4c434bb0ce6c60219a9715237fc | veronikakovalisko/classes | /main.py | 4,513 | 4.15625 | 4 | '''
Task 1
A Person class
Make a class called Person. Make the __init__() method take firstname, lastname,
and age as parameters and add them as attributes.
Make another method called talk() which makes prints a greeting from the person containing,
for example like this: “Hello, my name is Carl Johnson and I’m 2... |
e627b6178f654c35224ac16dc3b503a08036aa05 | amoghrajesh/Coding | /transpose_matrix.py | 226 | 3.859375 | 4 | matrix = [[1,2,3],[4,5,6]]
m = len(matrix)
n = len(matrix[0])
ans = []
for i in range(n):
temp = []
for j in range(m):
print(j,i,matrix[j][i])
temp.append(matrix[j][i])
ans.append(temp)
print(ans)
|
d68e0b39320b0b464169aa1be0244e18e317d87a | anudeike/CSCI_201-HelperFile | /CSCI_201_HW_helpers/HW-7/convertToIEEE.py | 3,833 | 4.21875 | 4 | import math
# goal is to convert a decimal to floating point
"""
[ISSUES]
1. Something weird and annoyingly recursive happens when you input anything with "0.3" [FIXED]
2. Right now, it rounds to 10 in the separate function. Be careful.
"""
def run():
decimal = input("Enter the base-10 decimal number: >>")
... |
35a64d7ea90d57c72d05c6050b17063f080db21a | ravi4all/PythonFebOnline_21 | /ExceptionHandling/05-example.py | 487 | 3.796875 | 4 | def atm():
total = 10000
pin = input("Enter PIN : ")
if (pin == "1234"):
print("Login Success")
else:
raise ValueError("Login Failed")
amount = int(input("Enter amount : "))
if (amount < total):
total -= amount
print("Remaining balance is",total)
... |
ff20347bd91795b337c687936798f0b75d353698 | wesenu/Project-Euler-1 | /python/Euler22.py | 897 | 3.546875 | 4 | #!/usr/bin/env python
# Project Euler - Problem 22
# Using names.txt, begin by sorting it into alphabetical order.
# Then working out the alphabetical value for each name, multiply
# this value by its alphabetical position in the list to obtain a name score.
#
# solution by nathan dotz
# nathan (period) dotz... |
1856f6053ead4251fd8b11255c0c714792b84cf1 | ideahitme/contest | /hackerrank/contest/world_codesprint_april/kmp_4/code.py | 1,161 | 3.609375 | 4 | def toString(xs):
result = []
col = [[el for _ in range(rep)] for (rep, el) in xs]
for arr in col:
result += arr
return result
def starting_point_of_char(xs, what_to_insert):
result = 0
for (rep, el) in xs:
if el == what_to_insert: break
result += rep
return result
def swap(mystring, pos1, pos2):
tmp = ... |
2ebd975f54007353cb043987b5e438accc6722c6 | SKPannem/PythonTraining | /Python/Chapter02/controlLoop.py | 521 | 4.0625 | 4 |
def main():
print("Hello")
msg = "WelcNomne to Nun the Python Cournse"
for c in msg:
if c == 'N' or c == 'n' :
continue #continue will continue for one iteration and skip one iteration of the loop
#break #break will simply... |
f5ded81c0a003cb0422e48411467855eacf3d09f | MatheusKlebson/Python-Course | /TERCEIRO MUNDO - THIRD WORLD/Funções para sortear e somar - 100.py | 694 | 4.15625 | 4 | # Exercício Python 100: Faça um programa que tenha uma lista chamada números
# duas funções chamadas sorteia() e somaPar(). A primeira função vai sortear 5 números
# vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre
# todos os valores pares sorteados pela função anterior.
def randomNumbers():... |
bf4d0232485244f01c9bebf511139a8af957dbb7 | Future-Aperture/Python | /exercícios_python/exercicios_theo/Exercicios 61-75/ex071.py | 597 | 3.90625 | 4 | print('='*30)
print('Banco do Xesque')
print('='*30)
valor = int(input('\nQual a quantidade que você quer sacar?\n> '))
cedula = 50
totalCedula = 0
while True:
if valor >= cedula:
valor -= cedula
totalCedula += 1
else:
if totalCedula > 0:
print(f'Total de {totalCedula} cé... |
707a50c0d4e9fe3e9a558b7decd7b18299666fe8 | TrinityChristiana/py-classes | /city.py | 588 | 4.125 | 4 | class City:
def __init__(self, name, mayor, year):
# Name of the city.
self.name = name
self.mayor = mayor
self.year = year
self.buildings = list()
def add_building(self, building):
self.buildings.append(building)
def print_building_details(self):
bu... |
fdb9916e1e0cd063c2db59a2a379653730097e50 | JesusGarcia23/PythonKatas | /SumOfStrings/sumOfStrings.py | 109 | 3.59375 | 4 | def sum_str(a, b):
if(a == ""):
a = 0
if(b == ""):
b = 0
return str(int(a) + int(b))
|
f1f490198e7fcd2322ae38a112aa65ae12733bb9 | shen-huang/selfteaching-python-camp | /exercises/1901050013/1001S02E03_calculator.py | 1,256 | 4.15625 | 4 | def COUNT(count_one,count_two,operation):
if operation == '+':
print(count_one, "+" ,count_two, "=" ,(count_one + count_two))
elif operation =="-":
print(count_one,"-",count_two,"=",(count_one - count_two))
elif operation =="*" or operation =='x':
print(count_one,'*',count_two,"=",(c... |
d7e7418339de09ef772f2c15b3752c44b1780b3a | hayeonk/algospot | /solong.py | 1,439 | 3.703125 | 4 | class TrieNode(object):
def __init__(self, chr):
self.chr = chr
self.first = -1
self.terminal = -1
self.children = [None for i in range (26)]
def insert(self, key, id):
if self.first == -1:
self.first = id
if key == "":
self.terminal = id
else:
next = ord(key[0]) - ord('A')
i... |
a84d90bfa5802e2f154cff73a4877177a15efa09 | whigon/Founder | /Check.py | 1,684 | 3.625 | 4 | def check(filePath, sel, SN='', BN=''):
with open(filePath, 'r', encoding='UTF-8') as read_file:
# 记录行数
lineCount = 0
# 记录检查的项的正确个数
count = 0
while 1:
line = read_file.readline()
# 文件结束
if not line:
break
... |
137119eb89e882493312de179e740bba6a3a236b | dusty736/DS_400 | /DustinBurnham-L09-AccuracyMeasures.py | 5,613 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Dustin Burnham
Data Science 400
3/5/19
Assignment 9: Accuracy Measures
Summary:
The goal was to classify/predict whether a car was made in Asia based on
other factors like mpg, cylinders, horsepower, etc.. I decided since the
asia column was one-hot-encod... |
188c344ff0db03b18222fa1a76758c20baf9e5cf | sreshna10/assignments | /L9-set of operations.py | 1,001 | 4.4375 | 4 | # set of operators allowed in expression
Operators=set(['','-','+','%','/','*'])
def evaluate_postfix(expression):
# empty stack for storing numbers
stack=[]
for i in expression:
if i not in Operators:
stack.append(i) #This will contain numbers
else:
a=stack... |
d893304a35ffc050e9925924b4a0cf212b005e41 | zed1025/coding | /coding-old/Codechef/long-challenge/NOV19B_HRDSEQ.py | 880 | 3.546875 | 4 | '''
https://www.codechef.com/NOV19B/problems/HRDSEQ
Accepted
'''
try:
t = int(input())
except:
pass
def util(nums):
'''
if the last element of the list does not occour anywhere previously, method returns -1
else method returns, diff between the positions of the last element and the firs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.