blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a6c0324efd7588288b83d3e541bce695aa8fafa2 | easternpillar/AlgorithmTraining | /Programmers Level 1&2 완전 정복/신고 결과 받기.py | 781 | 3.546875 | 4 | # 링크: https://programmers.co.kr/learn/courses/30/lessons/92334?language=python3
# 문제 접근
# 1. 딕셔너리에 나를 신고한 사람의 이름을 담음
# 2. 딕셔너리 길이가 기준을 넘으면 딕셔너리 values에게 메일이 전송
# 3. 딕셔너리 value값은 중복되면 안되므로 set
from collections import defaultdict
def solution(id_list, report, k):
answer = []
report_dict = defaultdict(set)
... |
7961117c272b5935e03c6d61ae78c99632d9258d | jnguyen1991/Rosalind | /sset.py | 658 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 24 09:48:11 2018
@author: jnguyen3
"""
def sset(n, output):
for i in n:
temp = n.copy()
temp.remove(i)
if temp not in output:
output.append(temp)
output.append(sset(temp, output))
def main(n):
'''
Recursive sol... |
40d4aa7bfab318dac684558ad18adbe095f206ef | JohanGro/CSE | /DictionaryNotes.py | 2,283 | 3.546875 | 4 | states = {
"CA": "California",
"VA": "Virginia",
"MD": "Maryland",
"RI": "Rhode Island",
"NV": "Nevada"
}
'''
print(states["CA"])
print(states["NV"])
'''
nested_dictionary = {
"CA": {
"NAME": "California",
"POPULATION": 39557045 # 39,557,045
},
"VA": {
"NAME": ... |
7f362996aa4bd6fdd02d571c21ee41037c40bd78 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/web-dev-notes-resource-site/2-content/ciriculumn/week-17/python/my-intro-BG/2/Module3PersonalizedStorySolution.py | 1,316 | 4.40625 | 4 | # initialize the variables
girldescription = " "
boydescription = " "
walkdescription = " "
girlname = " "
boyname = " "
animal = " "
gift = " "
answer = " "
# Ask the user to specify values for the variables
girlname = input("Enter a girl's name: ")
boyname = input("Enter a boy's name: ")
animal = input("Name a type ... |
edfba19244397e3c444e910b9650de1a855633b3 | Allaye/Data-Structure-and-Algorithms | /Stacks/balancedParen.py | 2,399 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
from Stack import Stack # personal implementation of stack using python list
# In[12]:
def check_balance(string, opening='('):
'''
a function to check if parenthesis used in a statement is balanced
this solution used a custom implementation of a stack u... |
9841e35ff7828069dd6e31617549104603a1cb8b | marcuschiriboga/RPS-se-q3-oct-2021-class | /RPS.py | 400 | 4.09375 | 4 | # https://realpython.com/python-rock-paper-scissors/
import random
# pictures
user_action = input("enter a choice (rock, paper, scissors): ")
if user_action not in ["rock", "paper", "scissors"]:
print("you chose poorly")
quit()
possible_actions = ["rock", "paper", "scissors"]
computer_action = random.choice(po... |
92984714b31d0371d71ecf1b5199079e4954a089 | saetar/pyEuler | /not_done/py_not_started/euler_618.py | 768 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ~ Jesse Rubin ~ project Euler ~
"""
Numbers with a given prime factor sum
http://projecteuler.net/problem=618
Consider the numbers 15, 16 and 18:
15=3× 5 and 3+5=8.
16 = 2× 2× 2× 2 and 2+2+2+2=8.
18 = 2× 3× 3 and 2+3+3=8.
15, 16 and 18 are the only numbers that have 8 as ... |
105ae8f9f679e7152364420c391995e6cd32d9a1 | minus9d/python_exercise | /parallel_and_concurrent/multiprocessing_pool.py | 208 | 3.59375 | 4 | #!/usr/bin/python3
import multiprocessing
def pow2(n):
return n * n
before = list(range(100000000))
with multiprocessing.Pool(4) as p:
after = p.map(pow2, before)
print(before[:5])
print(after[:5])
|
f46a1a47e165d5b894de0b9877fb046f42017f1a | selenazhen/planetParasite | /movingSprites.py | 13,420 | 4.0625 | 4 |
TESTING CODE FOR FEATURES, IGNORE FILE
# """
# Sample Python/Pygame Programs
# Simpson College Computer Science
# http://programarcadegames.com/
# http://simpson.edu/computer-science/
#
# Explanation video: http://youtu.be/qbEEcQXw8aw
# """
#
# import pygame
# import random
#
# # Define some colors
# BLACK = (0... |
a3f5f074f54b27b21a1d257ab3688165a303beff | its-me-debk007/Simple-GUI-Calculator | /GUI_Calculator.py | 5,269 | 3.875 | 4 | from tkinter import *
from math import *
window=Tk()
window.title("Calculator")
window.configure(bg="black")
e = Entry(window, borderwidth=10, width=14, fg="white", bg="black", font=("Arial",20))
e.grid(row=0, column=0, columnspan=4, pady = 1)
flag=0
def click(n):
global flag
if flag:
e.delete(0,END... |
6bcb7aad9b7a23689eeed75a78fe1a1f154e0c00 | sharadsharmam/DataStructures-in-Python | /Queues.py | 2,116 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 15:07:21 2019
@author: sharad sharma
"""
class Queue:
def __init__(self, queueLimit):
self.head = None
self.tail = None
self.limit = queueLimit
def isEmpty(self):
if self.head == None:
retur... |
701b95d2a47ca261293e41a70a90a4641c7bacb7 | olopez15401/Python_Exercises | /favorite_number.py | 1,032 | 4.25 | 4 | """
Simple program that prompts a user's favorite number, stores it, and prints it out.
Author: Oscar Lopez
Date: Jan 11, 2019
"""
import json
class favorite_number():
def __init__(self):
self.number = 0
self.prompt_user()
self.save_number()
print("Your favorite number is : "... |
210037f1cb8e3cb64d8aabcf69258238307bb519 | aestriplet1279/cs109-osp | /hw3_with_hint_ArmaniEstriplet.py | 2,689 | 4.5 | 4 | ###############################
# Print Range
#
# Giving the following variables:
# start (number): The lower bound of the range.
# end (number): The upper bound of the range.
# stride (number): The amount to increment when counting.
#
#
# Print all numbers between `start` and `end` at
# intervals of `s... |
43bb7546c2030ed60cb3cec80e5649f582b20c7b | VictorRielly/bhk | /neuralnet.py | 67,060 | 3.53125 | 4 | # This python script will be used to implement a neural network.
# The neural network will be nested in a class so it may integrated
# more easily with other code later on.
import sklearn.metrics
from sklearn import svm
import numpy as np
import csv
import pandas as pd
import copy
import time
import math
np.random.seed... |
c7b7e889a0be44893d49b0aff09711340d7af055 | clevelandhighschoolcs/p4mawpup-DexterCarpenter | /Versions/WebScraper8.py | 4,232 | 3.53125 | 4 | #
# Web Scraper
# Version: 8
"""
cd C:\Users\Dexter Carpenter\Documents\GitHub\WebScraper\environment
c:\Python27\Scripts\virtualenv.exe -p C:\Python27\python.exe .lpvenv
.lpvenv\Scripts\activate
# on at home computer:
cd C:\Users\dexte\Documents\GitHub\WebScraper\environment
"""
# import libraries
import sys
im... |
9fe11203587e6965eef579ea703cb422698b8c42 | Jhangsy/ta_eval | /func.py | 501 | 3.59375 | 4 | # -*- coding: utf-8 -*-
character_dict = "E:/ta_eval/character_dict.txt"
kungfu_dict = "E:/ta_eval/kungfu_dict.txt"
def split_name(character_name,kungfu_name):
character = open(character_dict).read()
kungfu = open(kungfu_dict).read()
with open("name_dic.txt","wb") as outfile:
outfile.write(kungfu)... |
7cf3636502de6a1c38dab9a7dd890cdff3f35e1a | montlebalm/euler | /python/problems/problem4.py | 819 | 4.0625 | 4 | """
Question:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
Answer:
906609
"""
from helpers.timer import print_timing
def is_palindrome(num):
digits =... |
3fd212cf4b006b196aa8d5ff387b1d6295f491d2 | JaiminBhagat5021/CyberstormGriffin | /Binary.py | 1,367 | 3.953125 | 4 | ###########################################################################################
# Name: Jaimin Bhagat
# Date: 3/23/2020
# Description: Binary Decoder for Bits evenly divisible by 7 and 8(Done in Python 2.7.17)
###########################################################################################
from ... |
d922663c4e172e8bd321644ea934378a76541303 | navdeepbeniwal16/Daily-Coding-Problem | /Python Solutions/day2.py | 1,145 | 3.984375 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Uber.
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5... |
11c1b46b320c8c0ca2337654870c759456591a46 | liqima/Machine_Learning_books | /kaggle竞赛之路/classification/decisontree.py | 1,170 | 3.5 | 4 | # obtain the dataset
import pandas as pd
titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')
#titanic.info()
#print(titanic.head())
# preprocessing
x = titanic[['pclass', 'age', 'sex']]
y = titanic['survived']
x['age'].fillna(x['age'].mean(), inplace = True) ... |
570bf9388c854f5084b9d9c783314be0117433ee | deepikasr03/python-basic-examples | /hello.py | 295 | 3.65625 | 4 | #defining a function called say_hello .This function takes no parameters.and hence there are no variable
#declared in the parenthesis.
def say_hello():
print("hello world")
#calling the function twice.This means there is no neccesity to write the same code twice.
say_hello()
say_hello() |
9160bbad83029a80b5d5ee2e66c0ba3ab72d5cc1 | radomirbrkovic/algorithms | /matrices/row-wise-sorting-2d-array.py | 411 | 4.15625 | 4 | # Row wise sorting in 2D array https://www.geeksforgeeks.org/row-wise-sorting-2d-array/
def sortRowWise(matrix):
for i in range(len(matrix)):
matrix[i].sort()
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(matrix[i][j], end=" ")
print()
sortRowWise... |
046002906d814aa4229f3185b8fc9e5c666591b6 | veratsurkis/enjoy_sleeping | /ex1_2.py | 149 | 3.671875 | 4 | import turtle as tr
from random import *
tr.shape('turtle')
for i in range(100):
tr.forward(randint(10,100))
tr.right(randint(0,360))
|
8822bd05b3c007f28646074bcb20e8abe4eafe17 | Mehulagrawal710/learnings | /python/algorithms/merge_set_of_ranges.py | 341 | 3.84375 | 4 | def merge(l):
l.sort()
merged = [l[0]]
for x in l:
a = merged[-1][0]
b = merged[-1][1]
c = x[0]
d = x[1]
###########################
if d>b:
if c>b: merged.append(x)
else: merged[-1][1] = d
###########################
return merged
print(merge([[2, 4], [1, 2], [3, 5]]))
print(merge([[2,3],[1,3]... |
5506cb76e56bfcdcabe675561b41ff755e3736b3 | Lolita88/GenomeSequencing | /k_universal_circular_string_problem.py | 4,030 | 3.59375 | 4 | # Function finds a universal circular string in binary numbers
# example uses eight binary 3-mers (000, 001, 011, 111, 110, 101, 010, and 100) exactly once
# output is 00011101
from copy import deepcopy
from random import randint
import random, sys
import itertools
def k_universal_circular_string_problem(k):
# get... |
960225f77054ce48a9a52a3a2a550c91391dcfae | MPankajArun/Python-Proctice-Examples | /Day 4/RegexDemo-findall.py | 603 | 3.609375 | 4 | import re
patt =r"PSL"
s1 = "PSLaaa welcome to Pune. PSL PErsistyent ..."
s2 = "Welcome to PSL ... Good Morning PSL"
m = re.findall(patt,s1)
#print "m = ",m
if m != None: #match start search begining of line from first character
print patt ,"Occures " ,len(m) ,"time"
print "Match found as = ",m
else:
pri... |
fa9c0a49375e63526af795222ccd459e9c3bc3bd | AR123456/python-deep-dive | /work-from-100-days/Intermediate days 15-100/Day-32/Birthday-wisher-v2-datetime-module/main.py | 214 | 3.515625 | 4 | import datetime as dt
now = dt.datetime.now()
year = now.year
month = now.month
day_of_week = now.weekday()
print(day_of_week)
date_of_birth = dt.datetime(year=1995, month=12, day=15, hour=4)
print(date_of_birth) |
1fec54c7c2a05270e2656c481bf1b0c248219cea | cstrahan/python_practice | /coding_bat/warmup_1/pos_neg.py | 959 | 3.53125 | 4 | import pytest
# Given 2 int values, return True if one is negative and one is positive.
# Except if the parameter "negative" is True, then return True only if both are
# negative.
def pos_neg(a, b, negative):
pass
@pytest.mark.parametrize(
"a,b,negative,expected",
[
(1, -1, False, True),
... |
ddac4756f16e2c042f78e1ed6dcf4abe20a3c8e7 | dolomaniuk/FirstStepsInPython | /solution.py | 2,538 | 3.859375 | 4 | import math
y1 = int(input())
x1 = int(input())
y2 = int(input())
x2 = int(input())
res = 'y'
distance = y2 - y1 # макс разброс по X
isEvenY1 = y1 % 2 # четность Y1
isEvenY2 = y2 % 2 # четность Y2
minX = int(math.fabs(x1 - distance)) # миним значение X
if minX < 1:
if isEvenY2 == 0:
minX = 2
e... |
5a54812f2362e01abf23750d533eb8ced2727ae2 | spisheh/Udacity-ML-projects | /outliers/outlier_cleaner.py | 634 | 3.734375 | 4 | #!/usr/bin/python
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the f... |
e294cbebf9fb8a1a0d2e0eaf0799620e6d7d1ea3 | FrederikLehn/modpy | /modpy/plot/_tornado.py | 6,305 | 3.515625 | 4 | import numpy as np
from matplotlib import pyplot as plt
# ###############################################################################
# # The data (change all of this to your actual data, this is just a mockup)
# variables = [
# 'apple',
# 'juice',
# 'orange',
# 'peach',
# 'gum',
# ... |
e08e58d929f62044eb5e95bc43e69d9209de1a2b | Kai-log-93/python_modules_for_work | /pandas/filter.py | 1,335 | 3.609375 | 4 | import pandas as pd
from openpyxl.workbook import Workbook
df_csv = pd.read_csv('Names.csv', header=None)
# specify header for CSV
df_csv.columns = ['First', 'Last', 'Address', 'City', 'State', 'Area Code', 'Income']
# get City == 'Riverside'
print(df_csv.loc[df_csv['City'] == 'Riverside'])
print('----------------... |
da5a0302e4459f0246d2d500bdea981542387f02 | vesso8/Functions | /07. Chairs.py | 513 | 3.703125 | 4 | # from itertools import combinations
#
# result = list(combinations(input().split(", "), int(input())))
# for x , y in result:
# print(x, y , sep= ", ")
def combination(name, count, current_names=[]):
if len(current_names) == count:
print(', '.join(current_names))
return
for i in range(len(... |
c18e99603c2be1080538050092c07bf74c930a2e | anubhavsrivastava10/Python-ML | /DAY 20/prostate_cancer.py | 3,172 | 3.5625 | 4 | import pandas as pd
dataset = pd.read_csv("http://www.stat.cmu.edu/~ryantibs/statcomp/data/pros.dat", delimiter =' ')
features = dataset.iloc[:,:-1]
labels = dataset.iloc[:,-1]
#performing train test and spliy
from sklearn.model_selection import train_test_split
features_train, features_test, labels_train, ... |
2a6d9bdaae27a64cec7d6487ac55c370f3c343fd | bingyihua/bing | /help/py/jicheng_duo.py | 325 | 3.765625 | 4 | class Parent2():
print('我是第二个爹')
class Parent():
print('我是第一个爹')
class SubClass(Parent, Parent2):
print('我是子类')
#
# 结果:我是第二个爹
# 我是第一个爹
# 我是子类
#注意:类在定义的时候就执行类体代码,执行顺序是从上到下
|
4d9b5a16da2436ee293b1e88806c37ffd272c024 | nadiaguedess/SistemasDistribuidosEstruturaSequencialPython | /ListaSequencial/atividade_8.py | 232 | 3.875 | 4 | salarioHora = float(input("Digite quantos você ganha por hora:"))
horasTrabalhadas = int(input("Digite quantas horas você trabalhou no mês:"))
salarioFinal = salarioHora * horasTrabalhadas
print("Seu salário é:", salarioFinal)
|
6c3042b4dc5760ff78adaa38f1addc54968d8d36 | ianlai/Two-Circle-Intersection-Area | /two-circle-intersection-area.py | 3,026 | 3.828125 | 4 | #!/usr/local/bin/python3
# -*- coding: utf-8 -*-
import math
import numpy as np
import sys
PI = 3.14159265359
### Default Setting
x1 = 2.1
y1 = 1.8
r1 = 1.9
x2 = 5.3
y2 = 2.5
r2 = 3.2
numerical = False
def p(x):
return pow(x,2)
def s(x):
return pow(x,0.5)
def sin(x):
return math.sin(x)
def cos(x):
... |
eecdf56616975b28768a8c7b689ae28796cb5cda | SantaPoro/IT-Chalmers | /Contains.py | 1,252 | 4.4375 | 4 | #!/bin/python
def contains(list, e):
""" determines whether e is contained in the list """
for elem in list:
if elem == e:
return True
return False
integer_list = [0, 1, 2, 3]
print("")
print("Does the list contain 3?: %r" % contains(integer_list, 3))
print("Does the ... |
3ead2197c78a6414100389b2b2cde2f9df8e1760 | LizinczykKarolina/Python | /Practice Python/ListEx3.py | 312 | 3.875 | 4 | a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
z=[]
for i in a:
if i <= 5:
print "Adding element %d to the list" % i
z.append(i)
print z
print "Please enter the number: "
num = int(raw_input("> "))
x = [i for i in a if i < num]
c = []
for y in x:
c.append(y)
print c |
be47d91f72e229c20353485ff009d2fd02a7d22a | praveen5658/cspp1 | /cspp1_practise/cspp1-assignments/m8/GCD using Recursion/gcd_recr.py | 501 | 3.75 | 4 | '''
Author : Praveen
Date : 07-08-2018
'''
def gcd_recur(input_a, input_b):
'''
This function returns GCD of two numbers using Recursion
'''
if input_a < input_b:
input_a, input_b = input_b, input_a
if input_a % input_b == 0:
return input_b
return gcd_recur(input_b, input_a % inp... |
182d1b0c993b77213bbc353e0cae94e23754341f | abhilashmaddineni/Terraform_Abhi | /Challenge#3/Scenario1.py | 602 | 4.3125 | 4 | #Scenario 1: If some undefined variable is given in the dictionary which is not present, below code will skip the undefined Varibale and check for next variable.
#taking the dictionary into cont variable
cont = {"x":{"y":{"z":"a"}}}
#Validating with key
key = "john/x"
#using split function to separate the keys and usi... |
2e71e66d31a1cf9aa3f0d31dfff101c35395d08a | AdrianM20/Hangman---PracticalExam | /src/hangman/ui/console.py | 3,105 | 3.5 | 4 | """
console Module
Created on 30.01.2017
@author adiM
"""
from hangman.domain.validators import HangmanException
class Console(object):
def __init__(self, sentence_controller, game_controller):
self.__sentence_controller = sentence_controller
self.__game_controller = game_controller
def run_... |
7a3535e82cf7a851995070fefc6304def69b9537 | shebac22/remote | /check_number.py | 90 | 3.859375 | 4 | # check whether 4 is even
num = 4
if (num % 2) == 0:
print("{0} is Even".format(num))
|
f0c17fbe451f63d334ed57a1179095ea69c9faf2 | xavi-/random | /Euler/problem27.py | 649 | 3.703125 | 4 | def isPrime(n):
if n < 2: return False
if n == 2: return True
if n % 2 == 0: return False
i = 3
while(n / i >= i):
if(n % i == 0): return False
i += 2
return True
def testExpression(a, b):
for n in range(1, 900):
if not isPrime(n*n + a*n + b):
... |
2948a131295b9fecf0bcb71841e0d91cf3feb844 | joseangel-sc/CodeFights | /Arcade/BookMarket/ProperNounCorrection.py | 621 | 4.1875 | 4 | #Proper nouns always begin with a capital letter, followed by small letters.
#Correct a given proper noun so that it fits this statement.
#Example
#For noun = "pARiS", the output should be
#properNounCorrection(noun) = "Paris";
#For noun = "John", the output should be
#properNounCorrection(noun) = "John".
#Input/Out... |
f737a16017cb5f7eec8c58d5ba1b633eb482977f | renyi1314/Source-code | /basis/data/card.py | 2,697 | 3.984375 | 4 | '''
需求:1,显示用户菜单
'''
card_list = []
tmp_card = {} # 临时保存查找到的数据
tmp_name = "" # 临时保存查找的名字
tmp_index = int() # 临时保存查找到数据的索引,用于更新数据
def main():
print("欢迎进入名片管理系统")
print("请选择操作: ")
print("1.新增名片")
print("2.显示全部")
print("3.查找名片")
print("0.退出系统")
choice = input("请输入选择的操作")
if ... |
1dfc76b312eebcde9d3612b05eaad4af1d56b4c1 | vikky12343/python_basic-programs | /lab_6/lab6.9.py | 304 | 3.90625 | 4 | class power:
def __init__(self,a,b):
self.x=a
self.n=b
self.p=1
def pow(self):
while(self.n>0):
self.p=self.p*self.x
self.n=self.n-1
def display(self):
print self.p
a,b=input()
ob=power(a,b)
ob.pow()
ob.display()
|
c42cee88d2157af6428e11c11a5be8aa2fba83ca | noisebridge/PythonClass | /guest-talks/20171204-profiling/001-string-concat.py | 540 | 4.3125 | 4 | def lowercase(string):
return string.lower()
# Concatenate using a loop
def concat_loop(strings):
result = ''
for string in strings:
result += ','
result += lowercase(string) # !
return result
# Concatenate using string.join
def concat_join(strings):
return ','.join([lowercase(s... |
67c1d8262a87b233dfccbe0425be12b3b3f55f73 | Botany-Downs-Secondary-College/password_manager-joshua-saunders | /password_manager.py | 2,499 | 4.21875 | 4 | #password_manager.py
#Joshua Saunders 25/02/2021
#Lists
password_list = ["Pass1234"]
username_list = ["BDSC2021"]
#Functions
def line():
print(" ")
def age():
while True:
try:
age = int(float(input("What is you age: ")))
if age < 13:
print("Sorry you are not old enough")
... |
56d954ec2ab4773adb186ce9f240117e792507c7 | My-Students/Turtle_UDP_Server | /Turtle_Giavelli/Server.py | 1,105 | 3.640625 | 4 | import socket
import turtle
#TURTLE_KING=turtle.Turtle()
#TURTLE_KING.hideturtle()
MOVE=10
server_ip="127.0.0.1"
server_port=10000
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind((server_ip,server_port))
port_table=[]
turtle_dict={}
def turtle_create(address,movement):
turtle_dict[add... |
0c8b1fcc3b7d63371bd24a06c2d66b63fb4920f3 | hdantas/prog-puzzles | /codewars/python/5kyu/processes.py | 1,041 | 3.5625 | 4 | # http://www.codewars.com/kata/542ea700734f7daff80007fc
def processes(start, end, original_processes, solution_candidate=[]):
# uses recursion to greedily explore trees, then returns the shortest tree of those with the correct start and end node
if (start == end): return solution_candidate # found a possible s... |
408babae6f2e8b73ff56eaab659d421628c46cab | Aditya-A-Pardeshi/Coding-Hands-On | /4 Python_Programs/6 Problems on characters/2_CheckCapital/Demo.py | 408 | 4.15625 | 4 | '''
Accept Character from user and check whether it is capital or not
(A-Z).
Input : F
Output : TRUE
Input : d
Output : FALSE
'''
def CheckCapital(ch):
if((ch >= 'A') and (ch <= 'Z')):
return True;
else:
return False;
def main():
ch = input("Enter character:");
result = False... |
99541d9078f385475dfd6f0ccd5a1fac274b034a | justinta89/Work | /PythonProgramming/Chapter 8/Exercises/fibonacci.py | 487 | 4.28125 | 4 | # fibonacci.py
# Calculates the nth number in fibonacci sequence.
def fibonacci(n):
if n > 0:
if n == 1:
fn = 1
elif n == 0:
fn = 0
else:
fn = (n - 1) + (n - 2)
if n < 0:
if n == -1:
fn = 1
else:
fn = ((-1) ** ... |
e9c3ed5154d1bf0b35ed01a70634ad2eb1cbb290 | scolphew/leetcode_python | /leetcode/_043_MultiplyStrings.py | 877 | 3.59375 | 4 | class Solution(object):
def multiply(self, num1, num2):
"""
string乘法
:type num1: str
:type num2: str
:rtype: str
"""
len_1 = len(num1)
len_2 = len(num2)
result = [0 for _ in range(len_1 + len_2)]
print(result)
for i in range(le... |
06a0ea2f01878451b4abf17d2e930a62585d9f86 | IM-MC/LCsol | /49.py | 572 | 3.765625 | 4 | def groupAnagrams(strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
dic = dict()
res = []
for i in range(len(strs)):
checker = [0]*26
for char in strs[i]:
value = ord(char) - ord('a')
checker[value] += 1
key = tuple(checker)
... |
27432145ccb7d6656fabe18b41b3eb0124355d6b | ngchitrungkien/nguyenchitrungkien-fundamental-c4e20 | /Session01/homework01/Turtle exercise session01/turtle_equilateraltriangle.py | 243 | 3.625 | 4 | from turtle import *
speed(1)
shape("classic")
color("green")
pencolor("green")
fillcolor("yellow")
begin_fill()
for i in range (3):
forward(300)
left(120)
color("yellow")
end_fill()
pencolor("green")
fillcolor("yellow")
mainloop() |
be59f6e67e8ce78560b107c50280e38bbc976fab | SouzaCadu/guppe | /Secao_19_Manipulando_data_hora/19_138_Metodos_data_hora.py | 3,575 | 4 | 4 | """
Metodos
import datetime
from textblob import TextBlob
# aceita parâmetro de fuso horário (timezone)
agora = datetime.datetime.now()
print(type(agora), repr(agora), agora)
hoje = datetime.datetime.today()
print(type(hoje), repr(hoje), hoje)
# Mudanças acontecendo a meia noite
manutencao = datetime.datetime.com... |
0de34e7f84a0aff75af827cb56f12e3d3e6075f8 | astral-sh/ruff | /crates/ruff/resources/test/fixtures/tryceratops/TRY400.py | 1,283 | 3.703125 | 4 | """
Violation:
Use '.exception' over '.error' inside except blocks
"""
import logging
import sys
logger = logging.getLogger(__name__)
def bad():
try:
a = 1
except Exception:
logging.error("Context message here")
if True:
logging.error("Context message here")
def bad():... |
a7a9ec4067ff45625b0429831e01a175fc86a8a2 | southzyzy/FILAttack | /main_ui.py | 3,963 | 3.546875 | 4 | """
Python Version 3.8
Singapore Institute of Technology (SIT)
Information and Communications Technology (Information Security), BEng (Hons)
ICT-2203 Network Security Assignment 1
Author: @
Tan Zhao Yea / 1802992
Chin Clement / 1802951
Gerald Peh Wei Xiang / 1802959
Academic Year: 2020/2021
Lecturer: Woo Wing Ke... |
d4b17b8ee5a1a13e75bf1ea9f3100fdb31b83317 | dinhhuyminh03/C4T21 | /session3/turtle_intro.py | 342 | 3.859375 | 4 | from turtle import *
shape ("turtle")
speed(-1)
# forward(100)
# left(90)
# forward(100)
# left(90)
# forward(100)
# left(90)
# forward(100)
# left(30)
# forward(100)
# left(90)
# forward(100)
# left(90)
# forward(100)
# left(90)
# forward(100)
# left(30)
for i in range (10,200,5):
forward(10 + i)
left(90)
for ... |
cba3ef8acfa0a67b9d9718f968ecf2df4f3ff17c | DanielRrr/Algorithms-Studies | /gcd3.py | 184 | 3.84375 | 4 | def gcd3(a, b):
assert a >= 0 and b >= 0
if a == 0 or b == 0:
return max(a, b)
elif a >= b:
return gcd3(a % b, b)
else:
return gcd3(a, b % a)
|
8663b54614d6361def4d1b4605bad4a9d3c04a2c | Barbariansyah/pyjudge | /test/loop_2.py | 139 | 3.546875 | 4 | def loop_2(in1,in2):
if in1 > in2:
i = 0
while i < in1:
i = i+1
return i
else:
return 0 |
e9bf3e88f740d9d2f8f092d494b44a852fc4f5e0 | rochejohn/ATBS | /Projects/Character_Picture_Grid.py | 1,072 | 4.0625 | 4 | #! /usr/bin/env python3
'''
Chapter 4 Character Picture Grid
Basically take this grid below and print it so the image is shifted 90 degrees
to the right
You will need to use a loop in a loop in order to print grid[0][0],
then grid[1][0], then grid[2][0], and so on, up to grid[8][0].
This will finish the first row, ... |
b531b455550925271b011e4dd5ab1dc51bcee440 | rishikeshpuri/python-codes | /assignment-2 one complex number from user and display the greater number between real part and imaginary part.py | 281 | 4.4375 | 4 | #To accept one complex number from user and display the greater number between real part and imaginary part.
x=int(input("Enter one real number"))
y=complex(input("Enter one imaginary number"))
if x>y:
print("%d is greater number"%x)
else:
print("%d is greatest number"%y)
|
bf96ba839c7df2c0e5be37a3cebfa6fb3b83acf7 | shreya1sharma/Coding | /programming-puzzles/jump_game.py | 808 | 3.84375 | 4 | '''
Method 1: recursion
pseudo-code
1. read the first element
2. initialize a canJump variable to False
3. Check all possible jumps starting from maximum to 0 (reverse order)
4. For each jump repeat steps 1-3
5. if the jump leads to the end of the array (len(arr)=1):
Update canJump to True, else do not update
6. If w... |
8692211470383feed28dae0e008aa2a20194a513 | FrankJonasmoelle/Matrix-Library | /matrix/test_unittest.py | 423 | 3.546875 | 4 | import unittest
from matrix import *
class TestMatrix(unittest.TestCase):
def setUp(self):
self.m1 = Matrix([[1,2,3],[4,5,6]])
self.m2 = Matrix([[1,1,1],[1,1,1]])
self.m3 = Matrix([[1,2],[3,4],[5,6]])
def test_add(self):
out = self.m1 + self.m2
expected = Matrix([[2,3... |
86912d6585057f5618747f0ff5e43c36b0d35a8a | dan1el5/cs50-lectures | /lecture2/square.py | 187 | 3.8125 | 4 | from functions import square # could also use import functions
num = int(input("number: "))
print("The square is" , square(num)) # and then change square(num) to functions.square(num) |
ee11cd3dba463874062b05e9d15b89031fff7f5d | deep141997/web-scraping | /web scraping3 | 1,260 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 13 02:05:15 2018
@author: deepak
"""
import requests
from bs4 import BeautifulSoup
# when we run request.get it return a response object
page=requests.get("http://dataquestio.github.io/web-scraping-pages/simple.html")
print(page.status_code) #res... |
f61cedd2d260d3c74d9e1766d5b6508cbd0f5b71 | trevornagaba/Agile-project | /logic.py | 706 | 3.75 | 4 | user_name = raw_input('Please enter your username: ')
user_type = raw_input('Hello {}, what type of user are you? :'.format(user_name))
if user_type == user_type.lower('user'):
comment = raw_input('Enter new comment here: ')
add_comment()
edt_comment = raw_input('If you want to edit a comment, please the ... |
d4c5aba6f9e1ef97458bf3c50342b596a54a6e1e | meagles/advent-of-code-2020 | /app.py | 12,419 | 3.609375 | 4 | import re #regex
def open_puzzle_input(day):
with open('./Day{}/input.txt'.format(day), 'r') as file:
data = file.read()
splitData = data.splitlines()
return splitData
if __name__ == "__main__":
day = 10
puzzle = 2
input = open_puzzle_input(day)
if day == 10:
int_input = []
for ... |
a7b2aec62b5b7f1a8ebb4b5e3facfeaf3cea2aa9 | saitoshin45/AnimalTetris- | /tetris.py | 917 | 3.65625 | 4 | #saitoshin45 tetris game
import tkinter
#variables for the positions
mouseX = 0
mouseY = 0
mouseC = 0
cursorX = 0
cursorY = 0
#function to get the mouse's positions
def mouse_move(e):
global mouseX, mouseY
mouseX = e.x
mouseY = e.y
def mouse_press(e):
global mouseC
mouseC = 1
... |
2e85ac86faf369f94a100a6efdadc8cbb53500d1 | AndreiBratkovski/CodeFights-Solutions | /Interview Practice/Arrays/firstNotRepeatingCharacter.py | 818 | 4.25 | 4 | """
Note: Write a solution that only iterates over the string once and uses O(1) additional memory, since this is what you would be asked to do during a real interview.
Given a string s, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'.
Example
For s = ... |
dcfeb2cdbb6613c8be2925b9b61a08b696c17b15 | adamorhenner/Fundamentos-programacao | /vp2/objeto2.py | 460 | 3.8125 | 4 | class Pessoa:
def __init__(self, nome, cpf, email):
self.nome = nome
self.cpf = cpf
self.email = email
p1 = Pessoa("adamor","065054343", "adamorhenner2@outlook.com")
p2 = Pessoa("adamo","06505434", "adamohenner2@outlook.com")
p3 = Pessoa("adam","0650543", "adamhenner2@outlook.com")
p4 = Pes... |
fd7a9eab46b710503c991c10717b215617e08471 | sgrade/pytest | /leetcode/convert_sorted_array_to_binary_search_tree.py | 1,933 | 4.03125 | 4 | # https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
"""
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees
of every node... |
c19baa97e81bd46c5a9f662e3eb2cec86c621c3b | ICCV/coding | /others/of52.py | 466 | 3.578125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
L1,L2 = he... |
2841a3be0a2107c129223ca26d3d7954ffc79d48 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/NatalieRodriguez/Lesson08/test_Circle.py | 1,835 | 3.59375 | 4 | from Circle import *
import pytest
from math import *
a = Circle(10)
b = Circle(5)
c = Circle(2)
d = Circle(1)
def getter_test():
assert a.radius == 10
assert b.radius == 5
assert c.radius == 2
assert d.radius == 1
assert a.diameter == 20
assert b.diameter == 10
assert c.diameter == 4
... |
72c91389167bd08dd363dd1fe132e3c919aad4ea | xhimanshuz/time-pass | /Python/fileio_ui.py | 454 | 3.640625 | 4 | #Input Data by user in file
from sys import argv
from os.path import exists
source, filename = argv
print("Enter Data in %r" %filename)
print("Currently in %r \n" %filename)
ofile = open(filename, "r+w+")
print(ofile.read())
line1 = raw_input("Enter Text to Line 1: ")
line2 = raw_input("Enter Text to Line 2: ")
ofile.w... |
37b9acd8596877fb6d4ee7252ff124a5db16a09d | mstrzelczyk4/Exercism---python-track | /wordy/wordy.py | 983 | 3.796875 | 4 | import re
def answer(question):
operators = ["plus", "minus", "multiplied", "divided"]
tab = [word for word in question[:-1].split() if re.search("[0-9]+", word) or word in operators]
if len(tab) % 2 == 0 or not re.search("[0-9]+", question[-2]):
raise ValueError("Invalid question!")
for x in ... |
e75ca20199a09434371b6a9f6c5e797a5807a7a2 | SebastianAthul/pythonprog | /OOP/INHERITANCE/person_child.py | 735 | 4 | 4 | #MULTIPLE INHERITANCE
class Person:
def set(self,name,age,address):
self.name=name
self.age=age
self.address=address
print("Name=",self.name)
print("AGE=",self.age)
class Child:
def setvalue(self,school,std):
self.school=school
self.std=std
print("... |
dc9ae09a62ac884572a56bbd649c9c40e31da970 | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/06-Objects-and-Classes/02_Exercises/02-Weapon.py | 1,069 | 4.0625 | 4 | # 2. Weapon
# Create a class Weapon. The __init__ method should receive an amount of bullets (integer). Create an attribute called bullets, to store them.
# The class should also have the following methods:
# • shoot() - if there are bullets in the weapon, reduce them by 1 and return a message "shooting…".
# If there a... |
0eb02469796ba91bad5473c6f3f6c73f3b8be1db | praba230890/Simultaneity | /queue_threading.py | 558 | 3.53125 | 4 | import threading, queue
import time
q = queue.Queue()
def task(i):
d = 0
for v in range(100000):
d += 1
q.put(d)
print("Thread: %s" % (i))
time.sleep(1)
if __name__ == "__main__":
tasks = []
for i in range(100):
add_task = threading.Thread(target=task, args=(i,))
... |
23ed86aa27ee01da36c29b9f43575a81c7e296ea | Kushbak/python-tasks | /Neobis/Logic/#biggestDigit.py | 473 | 3.71875 | 4 | hundred = []
def setDig(n):
i = 0
while n > i:
i += 1
anyNum = int(input(str(i) + ' число: '))
hundred.append(anyNum)
showArr()
def showArr():
maxNum = max(hundred)
indexOfMax = hundred.index(maxNum)
print('Самое большое число: ' + str(maxNum))
print('Его индекс: ' + str(indexOfMax + 1))... |
e9e85d18792bf3175a691fdb3cff116435a645ef | JinzhuoYang/hogwarts | /class_pritice/class_pritice1.py | 682 | 3.65625 | 4 | class person:
def __init__(self,name,age,gender):
self.name = name
self.age = age
self.gender = gender
def set_att(self,value):
self.value = value
def eat(self):
print(f" name : {self.name}, age : {self.age}, gender : {self.gender} i'm eat")
def drink(self):
... |
56c2e62daffd1d133cbda5a484ddcf60f20c2d26 | dimitar-daskalov/SoftUni-Courses | /python_advanced/labs_and_homeworks/01_lists_as_stacks_and_queues_exercise/02_maximum_and_minimum_element.py | 623 | 3.5 | 4 | manipulation_stack = []
commands_number = int(input())
for _ in range(commands_number):
command = input()
if command.startswith("1"):
element = int(command.split()[1])
manipulation_stack.append(element)
elif command == "2":
if manipulation_stack:
manipulation_stack.pop(... |
a8f4d0a132e0fb22a367e067692ac81540537b7b | rafaelperazzo/programacao-web | /moodledata/vpl_data/380/usersdata/315/95895/submittedfiles/principal.py | 162 | 3.671875 | 4 | # -*- coding: utf-8 -*-
from minha_bib import *
#COMECE AQUI ABAIXO
for x in range(-10,10,1):
a = ((x**2)-(2*x)+1)
if a ==0:
print(i)
|
bdac19986e18ad413e11500c344aaf3df0b68ea6 | doPggy/py-try | /3-str.py | 1,562 | 4.21875 | 4 | # 单引双引号都可以创建字符串
s = "hello world"
print(s)
s = 'hello, world'
print(s)
# 简单操作
## 加法
s = 'h' + 'w'
print(s)
## 与数字相乘
print("echo" * 3)
# 字符串方法
## 分割
line = "1 2 3 \t 4 5"
print(line.split())
line = '1, 2, 3, 4, 5'
print(line.split(','))
## 连接
s = ','
'''以 s 为连接符连接成一个字符串'''
ss = s.join(['1', '2', '3']) # char list
prin... |
2018849a56da6195fd7b6734a90e5a7ef5830f43 | sjogleka/General_codes | /criticalRouters.py | 3,197 | 3.84375 | 4 | import collections
'''
def FindCriticalNodes(numEdges, numNodes, edges):
# Get all the node
nodes = []
for i in range(numEdges):
# Get nodes
if edges[i][0] not in nodes:
nodes.append(edges[i][0])
if edges[i][1] not in nodes:
nodes.append(edges[i][1])
# G... |
9bfa12055dc14833cc06613977ae83e784953612 | BarisAkkus/Main | /Sezon1/Ders10-Formatting.py | 571 | 4.25 | 4 | for i in range(1, 13):
print("No.{0:2} squared is {1:3} and cube is {2:4}".format(i,i**2,i**3))
print()
for i in range(1, 13):
print("No.{0:2} squared is {1:<3} and cube is {2:<4}".format(i,i**2,i**3))
#sola dayalı
print()
print("Pi is approximately {0:<12}".format(22 / 7 ))
print("Pi is approximately {0:<12f}... |
6c0188ab2a17ddb968f9476865101313531a5a98 | ErvinHRivasM/Python | /basicPython/conversor_mejorado_v_alfa.py | 990 | 4.09375 | 4 | """
Bienvenido al conversor de monedas
1 - Pesos Colombianos
2 - Pesos Argentinos
3 - Pesos Mexicanos
Elige una opción:
"""
opcion = input("¿Cuanto pesos colombiano tienes?")
if opcion == 1:
pesos = input("¿Cuanto pesos colombiano tienes?")
pesos = float(pesos)
valor_dolar = 3846.40
dolares = pesos ... |
a39e0196f034b1ea086a3d321beb605126acc78d | RobertaLara/BankAccount | /Bank.py | 2,931 | 4.0625 | 4 | # Consulta ao saldo na conta corrente e liberação do valor somente se for dentro do valor disponível na conta
# Programadora Roberta Lara
import os
def clear(): # Função para limpar console
os.system('clear')
clear()
print("\n\n\tBANCO 24 HORAS - Não aceite ajuda de estranhos\n")
auxiliar = ... |
5db87bbf83793956f96325a6baf8b13ff8f530aa | grand-mother/h5py-examples | /examples/units.py | 3,566 | 3.78125 | 4 | #! /usr/bin/env python3
# The following example illustrates how numerical data can be wrapped with
# units using the Pint package.
#
# Note that while using Physical units can prevent some type of bugs it can
# also create new ones. In particular when wrapping data with units one must
# take care if a copy or a refere... |
a986f208e42103ac976ee17b213e0711ac31745b | CNZedChou/python-web-crawl-learning | /spider/codes/37_variable_thread.py | 788 | 3.546875 | 4 | # !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author : Zed
@Version : V1.0.0
------------------------------------
@File : 37_variable_thread.py
@Description :
@CreateTime : 2020-5-8 14:21
------------------------------------
@ModifyTime :
"""
from threading import Thread
i... |
93b728a28fe8f3ffcf2926837ab97bdfe992d23e | Long0Amateur/Self-learnPython | /Chapter 6 Strings/Problem/16. A program asks user their name and generates offer.py | 428 | 3.640625 | 4 | #
s = input('Enter name:')
s1 = s.split()[0]
print('Dear',s+',\n')
print('I am pleased to offer you our new Platinum Plus Reward card at a special',end=' ')
print('introductory APR of 47.99%.',s1+',','an offer like this does not come along',end=' ')
print('every day, so I urge you to call now toll-free at 1... |
edd0fa92f5ee53fb114cb39361c00a0882cc12e6 | ARTIC-TTS-experiments/2021-ICASSP | /lib/densenet.py | 2,121 | 3.515625 | 4 | from keras.layers import BatchNormalization, Dropout, Flatten, Dense, Activation
import numpy as np
# Function for creating a dense layer(s)
def dense_block(layer, n_neurons, flatten=True, inner_activation='relu', last_activation='sigmoid', batch_norm=True,
batch_norm_after_activation=True, dropout=No... |
c5cc900c47e979eb91f96b4a206834925577f311 | jasoncsonic/CS313E | /Intervals.py | 3,703 | 4.40625 | 4 | # File: Intervals.py
# Description: A program that scans a list of tupples and sees if they are overlapping with one another. Whichever tuples are no
#longer overlapping with one another are sent to another list that will tell the user which tuples are no longer overapping.
# Student's Name: Peyton Breech
... |
3dd9201b0b228fecabb349efb0bd1903fc6bf09b | szabgab/slides | /python/examples/basics/calculator_argv.py | 454 | 3.5625 | 4 | import sys
def main():
if len(sys.argv) < 4:
exit("Usage: " + sys.argv[0] + " OPERAND OPERATOR OPERAND")
a = float(sys.argv[1])
b = float(sys.argv[3])
op = sys.argv[2]
if op == '+':
res = a + b
elif op == '-':
res = a - b
elif op == '*':
res = a * b
el... |
39d70e9babb3ef7ee258054893d5afc872b70e40 | wbshobhit1/Python3.7 | /finally_else.py | 251 | 3.703125 | 4 | f1 = open("eyes.txt")
try:
f = open("water.txt")
except Exception as e:
print(e)
else:
print("This will run only if except is not running")
finally:
print("Run this anyway...")
f.close()
f1.close()
print("Important to run")
|
07607c9b673d9a5145848e9cd607a1cd1111ea73 | sheng1993/coding-problems | /interview/04_tree_and_graphs/12_paths_with_sum.py | 1,236 | 3.546875 | 4 | # Paths with Sum: You are given a binary tree in which each node contains an integer value (which
# might be positive or negative). Design an algorithm to count the number of paths that sum to a
# given value. The path does not need to start or end at the root or a leaf, but it must go downwards
# (traveling only from ... |
3536d39f0c2ea49e6888a96ede54aa1be165896a | maygrey/RimeIce | /Codeeval/primepalindrome.py | 936 | 3.90625 | 4 | '''
Codeeval challenge 3
Created on 02/06/2014
@author: maygrey
'''
import sys
def search_primes(n):
"""Search all the primes from 2 to n"""
num = [2]
i = 3
while i < n:
for j in num[:]:
if i % j == 0:
i = i + 1
break
else:
num.a... |
3f01872b9ddb442b7f94b29ee9d026ee82e77735 | super3/PyDev | /Old Projects/ident/Helper.py | 615 | 3.65625 | 4 | # Name: Helper.py
# Author: Super3(super3.org)
import random
def FiletoArray(filename):
"""Converts a .txt file to list"""
try:
tmp = []
file = open(filename)
except:
print("Error Reading File:",filename)
else:
for line in file:
line = line.strip()
line = line.lower()
tmp.append(line)
file... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.