blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
928b5dff4ec62b05392a631621827969339d1c52 | choijaehoon1/programmers_level | /src/test18.py | 558 | 3.59375 | 4 | def solution(a, b):
answer = ''
num = 0
weeks = ["FRI","SAT","SUN","MON","TUE","WED","THU"]
for i in range(1,a):
if i == 1 or i == 3 or i == 5 or i == 7 or i == 8 or i == 10 or i == 12:
num += 31
elif i == 4 or i == 6 or i == 9 or i == 11:
num += 30
e... |
88f281e6043d7fe2100e2ccdbebb43216bca31f3 | esierra8/website_blocker | /website_blocker.py | 2,017 | 3.703125 | 4 | #This is a website blocker, what it does is it goes to your conf files in your system
# in this case in windows. You will have to schedule a task in the background that
# will check the time and depending on the time (working hours) it will edit the file
# and will add the specify websites in the list of links to... |
3f30367856c26d1630674216d03c8bf153c3225f | zzylydx/source | /面向过程_02_01/小练习1.py | 765 | 3.984375 | 4 | #!/usr/bin/env python3
# coding utf-8
'''
练习1 编写一个 学生类,产生一堆学生对象
要求
有一个计算器(属性),统计总共实例了多少对象
'''
class Student:
school = 'luffycity'
count = 0
def __init__(self,name,age,sex):
self.Name = name
self.Age = age
self.Sex = sex
# self.count = self.count + 1
Student.cou... |
403e807b8ddee54bdbcf64a7106fb61acde48cd7 | K-G-1/python-practice | /function+file/function.py | 548 | 3.9375 | 4 | #coding=UTF_8
##函数与文件操作例程
#
from sys import argv
script , input_file=argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_one_line(line,f):
for line in range(1,line):
f.readline()
line = line + 1
print line,f.readline()
print "Now,we will print the whole file:"
txt = open(input_file... |
5843c7ecd033183c91625c70db76f79030eacd34 | EduardoAlbert/python-for-data-analysis | /Dictionaries/Dictionary.py | 1,146 | 4.125 | 4 | """filme = {'titulo': 'Star Wars',
'ano': 1977,
'diretor': 'George Lucas'}
print(filme.values())
print(filme.keys())
print(filme.items())
for value in filme.values():
print(value)
for key, value in filme.items():
print(f'O {key} é {value}')
"""
"""locadora = [{'titulo': 'Star Wars', 'ano':... |
1a6cc4175a4e0a04f7c55ef7558bfb0865f8a309 | junyaoshi/iGibson | /igibson/scenes/scene_base.py | 2,220 | 3.578125 | 4 | class Scene(object):
"""
Base class for all Scene objects
Contains the base functionalities and the functions that all derived classes need to implement
"""
def __init__(self):
self.build_graph = False # Indicates if a graph for shortest path has been built
self.floor_body_ids = []... |
479013b825b71c328d9ed7b5773ea6a08f78d412 | CarlosGiovannyG/Curso_Python | /Calcular_Poblacion.py | 1,770 | 3.6875 | 4 |
year = 2022
a = 25
b = 18.9
while a > b:
a = a+(a*0.02)
b = b+(b*0.03)
year += 1
print("El pais B superara a A en el año: " + str(year))
"""def poblacion(pA, pB):
anio = 2022
while pA > pB:
pA += pA*0.02
pB += pB*0.03
anio += 1
return print("Año: ", anio, "\nTotal población A: ", pA, "\n... |
72776a6633e80fcc4e69d79889f4c91ebaca39d3 | lo1gr/medical_document_clustering | /embeddings/TFIDF.py | 1,694 | 3.75 | 4 | from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
import numpy as np
# website to look @ for potential info: https://www.freecodecamp.org/news/how-to-process-textual-data-using-tf-idf-in-python-cd2bbc0a94a3/
# what does tokenizer do and do we need it?
# on processing nouns
def perform_... |
6ad6e49a50d8e9051095c42179c27b18131f316b | odora/CodesNotes | /Python_100_examples/example3.py | 1,294 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/1/26 22:29
@Author : cai
examples come from http://www.runoob.com/python/python-exercise-example3.html
"""
# ============== Example 3 ======================================
# 一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
# ==============... |
ebb9529c30a0e7f84ca40222f52ff4e97ff9fd4b | TheAkshrCompany/Python | /Fibonacci.py | 461 | 4.21875 | 4 | ##############################################
# code By Harsh Tiwari
# code for Fibonacci in python
##################################################
def Fibonacci(p):
fab=[0,1]
a=0
b=1
if p<=0:
return print("Enter the valid number")
if p==1:
return fab.pop(0)
for i in range(p-... |
5980f2ce5a05ade82d0c2c80692a32ce6b3bc55c | whiz-Tuhin/Competitve | /Hackerrank/University Codesprint/seperate_numbers.py | 984 | 3.796875 | 4 | def check_forward(prev,remain):
if(len(remain) == 0):
return 1
if(len(remain) >= 1 and remain[0] == '0'):
return 0
a = -1 # taking -1 as intializing value
pos = -1
flag = -1
for i in range(1,(len(remain)+1)):
a = int(str(remain[:i]))
if(a == prev+1):
... |
f673da68371d83e5c5a7fa95004eccfd3a6c2a93 | martinjakopec/euler | /eul10.py | 267 | 3.59375 | 4 | import math
zbroj = 0
def is_prime(x):
output = True
for i in range(2, int(math.sqrt(x) + 1)):
if x % i == 0:
output = False
return output
for i in range(2,2000001):
if is_prime(i):
zbroj += i
print(zbroj)
|
29826ebc9ff45905e7dc57200e34694f04732a0e | rejithry/class | /algo2_misc/optimize.py | 12,857 | 3.6875 | 4 | # Do Not Repeat Repeated Work
#
# Focus: Units 5 and 6: Interpreting and Optimization
#
#
# In class we studied many approaches to optimizing away redundant
# computation. For example, "X * 0" can be replaced with "0", because we
# know in advance that the result will always be 0. However, even if we do
# not k... |
484ac1f17bfaff13f0c0543c124b208e222a9548 | ashar-sarwar/python-works | /python_assignment/practice 1.py | 105 | 3.71875 | 4 | dict = {'Name': 'Zabra'}
print ("Value :" ,dict.get('Age',8)+1)
print ("Value :" ,dict.get('Age',8)+1)
|
f0e27f5e5e5e409a19dfbfe931e0125932a8f678 | thakursc1-zz/IMDB-Movie-DataBase | /Btree.py | 6,688 | 3.796875 | 4 | ### Class movie make a set of storage options as below
class movie:
def __init__(self,title,ID,year,rating):
self.title=title
self.id=ID
self.year=year
self.rating=rating
def printmovie(self):
print self.title ,"(",self.year,")"
print "imdb id :",self.id
p... |
8c9dabece40f2b10a4b539b2dc281e06afc12cc9 | daisyang/data_structure_and_algorithm | /Findstring.py | 1,626 | 4.28125 | 4 | # Given a sorted array of valings which is interspersed with empty valings, write a method to find the location of a given valing.
# Example: find 'ball' in ['at', '', '', '', 'ball', '', '', 'car', '', '', 'dad', '', ''] will return 4
# Example: find 'ballcar' in ['at', '', '', '', '', 'ball', 'car', '', '', 'dad', ''... |
3dd7dad24bc72f6550bcbb693891a2d0825d5f0a | yuangaonyc/project_euler | /problem_10.py | 200 | 3.703125 | 4 | num = 2
sm =0
def is_prime(num):
for i in range(2, int(num ** 0.5)+1):
if num % i == 0:
return False
return True
while num < 2000000:
if is_prime(num):
sm += num
print(num, sm)
num += 1 |
d63ea9d2621c86e359e529485f33dbf1ce56903b | cosmunsoftwares/django-boilerplate | /project_name/core/utils.py | 4,918 | 3.765625 | 4 | class CPF(object):
INVALID_CPFS = ['00000000000', '11111111111', '22222222222', '33333333333', '44444444444',
'55555555555', '66666666666', '77777777777', '88888888888', '99999999999']
def __init__(self, cpf):
self.cpf = cpf
def validate_size(self):
cpf = self.cleaning... |
630dd6b75782bdf5917ecd82ccc77bbfd472aabe | KimTaeHyun-GIT/Study | /응용해서 만든거/if문.py | 541 | 3.9375 | 4 | case = int(input('password : '))
if case==3102:
print("Password Correct")
select = int(input('Enter the number : '))
if select == 1: print("You Enter the 1")
elif select == 2: print("You Enter the 2")
elif select == 1023: print("New Password Detected")
new_password = int(input('Enter the... |
882252c363a58130788252a86cda11106a9b4e58 | gnramos/CIC-APC | /src/exemplos/03_Fluxo/02_Repeticao/04-do-while.py | 580 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# @package: 04-do-while.py
# @author: Guilherme N. Ramos (gnramos@unb.br)
# @disciplina: Algoritmos e Programação de Computadores
#
# Em Python, não há o laço de repetição DO-WHILE. Mas o
# comportamento pode ser replicado da seguinte forma:
#
# while True:
# # iteração
#
# if cr... |
f00d55a500396e25fa3c9a09e50dca32cd556476 | 4roses41/COM404 | /PracticeTCA/Question1/Q1.py | 138 | 3.84375 | 4 | Question = input("What happens when the last petal falls? ")
print(Question)
print("My dear Bella when the last petal falls " + Question)
|
213b337206746cd05b2ef42c4d743ee122bcc710 | rmcclorey/pythonTest | /Text.py | 790 | 4.09375 | 4 | #enter string returns reversed string
def reverseString(str):
return str [::-1]
print reverseString("Hello World")
#enter single word string returns pig latin form
def pigLatin(str):
return str[1:]+str[0]+"ay"
print pigLatin("Hello")
#enter string returns how many vowels present
def vowelCounter(str):
vowels = [... |
f97fff24bd34a40427c0edd48673aaf254af6106 | zzy1120716/my-nine-chapter | /catagory/BinaryTree/0072-construct-binary-tree-from-inorder-and-postorder-traversal.py | 1,109 | 4.21875 | 4 | """
72. 中序遍历和后序遍历树构造二叉树
根据中序遍历和后序遍历树构造二叉树
样例
给出树的中序遍历: [1,2,3] 和后序遍历: [1,3,2]
返回如下的树:
2
/ \
1 3
注意事项
你可以假设树中不存在相同数值的节点
"""
# Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param inorder:... |
3ed312280bd16c883d4ce7391cb92b61cc935d62 | rafaelperazzo/programacao-web | /moodledata/vpl_data/139/usersdata/237/61911/submittedfiles/diagonaldominante.py | 274 | 3.6875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
a=int(imput("Digite o numero de linhas: "))
b=int(imput("Digite o numero de colunas: "))
n=np.zeros((a,b))
for i in range(0,n.shape[0],1):
for j in range(0,n.shape[1],1):
n[i,j]=float(imput("Digite o termo: "))
print(n) |
d0a3fadf4f55ef02ce05658661bfba397ba8d15e | sirdaybat/aoc | /2016/16.py | 389 | 3.5 | 4 | import sys
def invert(s):
return "".join("0" if c == "1" else "1" for c in s)
state = sys.argv[1].strip()
target_length = int(sys.argv[2])
while len(state) < target_length:
state = state + "0" + invert(reversed(state))
state = state[:target_length]
while len(state) % 2 == 0:
cs = ""
for i in range(0, len(state... |
2bd989281d719d81e4e6844db156cc4820ebc8a0 | gudbrandsc/RSA-Public-Key-Cryptosystem | /rsa-homework.py | 2,965 | 4.28125 | 4 |
import random
# src: https://www.rookieslab.com/posts/how-to-find-multiplicative-inverse-of-a-number-modulo-m-in-python-cpp
def multiplicative_inverse(e, phi):
for i in range(0, phi):
if (e*i) % phi == 1:
return i
return -1
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
# Check if a num... |
c05864e31397d9eea7f7d31a86e1b6be07055627 | cmosguy/kaggle-hash-code-traffic-signal | /traffic/street.py | 1,466 | 3.703125 | 4 |
# Define class of street for keeping properties and methods
class Street:
def __init__(self, start_int, end_int, name, time_used):
self.start_int = start_int
self.end_int = end_int
self.name = name
self.time_used = time_used
self.queue = []
# Append new car drivi... |
b0255ae776c0a82e42aefe7afa9c88b631d0f50b | kmustyxl/DSA_final_fighting | /NowCoder/Array_Sort/HeapSort_EXAM_Mid_number.py | 3,643 | 4.0625 | 4 | def Mid_number(arr):
'''
随时获取数据流中的中位数
首先,需要建立一个大根堆和一个小根堆。 实时保证大根堆和小根堆的平衡,数量差值不能大于1
大根堆存放数组中较小的部分,则堆顶就是较小部分的最大值
小根堆存放数组中较大的部分,则堆顶就是较大部分的最小值
:param arr:
:return:
'''
if arr is None:
return
Big_heap = [] #建立大根堆
Small_heap = [] #建立小根堆
mid_num_arr = []
Big_heap.ap... |
903a96a00dae3cce6ebe2eeba508da57b38f4a0a | darkblaro/Python-code-samples | /myPower.py | 99 | 3.609375 | 4 | def myPow(a,b):
while b-1>0:
a=a<<1
b=b-1
return a
print(myPow(2,8)) |
14760827f09dfb12f8e2f894000367c1b2ee2577 | radhikagarg03/Python-project | /Assignment/Assignment8.py | 1,912 | 3.6875 | 4 | #Q1.
class Circle():
def __init__(self,radius):
self.radius = radius
def getArea(self):
return 3.14*self.radius*self.radius
def getCircumference(self):
return self.radius*2*3.14
obj1=Circle(10)
print(obj1.getArea())
print(obj2.getCircumference())
#Q2.
class Student():
def __init__(se... |
5c3db748af8f46ed2921b79889d8e4106c7b4f46 | Farazzaidi22/CG_lab02 | /image_histo_rgb.py | 669 | 3.875 | 4 | import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
#uint8 is an unsigned 8-bit integer that can represent values 0..255
#numpy uint8 will wrap. For example, 235+30 = 9
#img = np.zeros((200,200), np.uint8)
img =cv.imread("lena.jpg")
cv.imshow("img", img)
#splitting img in RGB
b,r,g = cv.split(... |
cef4204c3131566960b2cffb00031012c9cfab5a | marshallhumble/Coding_Challenges | /Code_Eval/Moderate/RemoveCharacters/RemoveCharacters.py3 | 320 | 3.796875 | 4 | #!/usr/bin/env python
from sys import argv
with open(argv[1], 'r') as f:
cases = f.read().strip().splitlines()
for item in cases:
text, letters = item.split(',')
text = text.split()
for c in letters:
for t in text:
text[text.index(t)] = t.replace(c, '')
print(' '.join(text))
|
d3c9556ac2879c7afdffd951708bc6089b45d36a | chang-1/BrownUniversity | /CSCI1420/hw02/models.py | 3,519 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This file contains the Linear Regression Regressor
Brown CS142, Spring 2020
'''
import random
import numpy as np
def l2_loss(predictions, Y):
'''
Computes L2 loss (sum squared loss) between true values, Y, and predictions.
@params:
Y: A 1D ... |
f5feda0c8976345dc5e11b6e67b76692f8e443ff | ojhaanshu87/LeetCode | /39_combination_sum.py | 1,787 | 3.953125 | 4 | '''
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target.
You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are ... |
556f8101ee3f1be7137d02d807ad4a86d3cd1827 | jwhite007/python-practice | /practice_modules/string_compression.py | 638 | 3.890625 | 4 | #! /usr/bin/env python
def compr_str(string):
compr_str = ''
count = 0
# import pdb; pdb.set_trace()
for i in string:
if compr_str == '':
compr_str = i
count += 1
elif compr_str[len(compr_str) - 1] == i:
count += 1
else:
compr_str... |
2e02823e4c94a2c272c70d9a428f2ed7c93b1bbc | machevera/pytest | /parametros2.py | 1,254 | 3.640625 | 4 | #sys.argv is the list of command-line arguments.
#sys.argv ES UNA LISTA
#uso de la libreria getopt (get options)
#python parametros2.py -i archivo1.xls -o archivo1.sql
#python parametros2.py --ifile=archivo1.xls --ofile=archivo1.sql
#imports
import sys
import getopt
#funciones
def p(mensaje):
print("\n-... |
5e14397a2248c2ecfd54df6cd5834798645ee385 | cantseemy/py | /Project_5_4.py | 503 | 3.921875 | 4 | #! /usr/bin/env python3
import math
print("a * x^2 + b * x + c = 0 ")
a = int(input("a = "))
if a == 0:
while a == 0:
a = int(input("a = "))
continue
b = int(input("b = "))
c = int(input("c = "))
d = b**2-4*a*c
if d == 0:
x = -1*b/2*a
print("D = 0, Коренем рівняня є : ",x)
elif d < 0:
print("D < 0, Корені... |
6bc6c76ccb57b66e093bf27de8c978151f7510b4 | DouglasCarvalhoPereira/Interact-OS-PYTHON | /M7/csv_to_html.py | 2,568 | 3.765625 | 4 | #!/usr/bin/env python3
import sys
import csv
import os
def process_csv(csv_file):
"""#Transforma o CSV em uma lista de listas"""
print("Processando {}".format(csv_file))
with open(csv_file, "r") as datafile:
data = list(csv.reader(datafile))
return data
def data_to_html(title, data):
... |
7a9d5f6c20d34fe36f7a3ad9db70f9ebff1d80d8 | jaruwitteng/6230401856-oop-labs | /jaruwit-6230401856-lab3/Problem 1.py | 127 | 3.9375 | 4 | total = 0
digit = 0
while total <= 200:
digit = digit + 1
total += digit ** 2
print("the final total is", total)
|
c58130d67d4734cdc1bbb1d25dd83f244c699d62 | tinasoady/detect_error | /PARITE.py | 535 | 3.578125 | 4 | #!/usr/bin/env python3
def getParity(n):
parity = 0
while n:
parity = ~parity
n = n & (n - 1)
return parity
def parityimp(binArray):
res=[]
for i in binArray:
if getParity(i):
b = bin(i)
b = b[2:]
res.append("1" + b)
else:
b = bin(i)
b = b[2:]
res.append("0" + b)
re... |
d51a9d75672357869c8afa8f637fe9394cf76cb7 | 13548029769/Aline-game-python- | /code/alien.py | 1,196 | 3.515625 | 4 | import pygame
from pygame.sprite import Sprite
class Aline(Sprite):
"""a class representative aline"""
def __init__(self,ai_settings,screen):
"""init aline setting and initialization"""
super().__init__()
self.screen = screen
self.ai_settings = ai_settings
#loading ali... |
c8ce2b31c7ee91626c1f2ea3a863be8ea9101b85 | 3chrisprosise/pythonUtil | /Util1.py | 6,897 | 3.890625 | 4 | # -*- encoding:utf-8 -*-
from math import pi
import string
# # 整数除法 //
# print(3//2) # 结果为 1
# #序列相加
# list1 = [1, 2, 3]
# list2 = [4, 5, 6]
# print(list1+list2)
# #创建空列表
# squence = [None]*10
# print(squence)
# 判断成员
# date = ['Mon', 'Tue', 'Ths', 'Wen']
# print('Mon' in date) # True
# print('Wen' in date) # Fa... |
4d363fcd447d53d36f9cfd4d2c6f851a69f94aa2 | simranbarve/Queue | /CircularQueue.py | 1,419 | 3.96875 | 4 | class CircularQueue:
def __init__(self, queue_size = 7):
self.queue_size = queue_size
self.queue = [None] * queue_size
self.front = -1
self.rear = -1
'''checks if the stack is empty (used in enqueue and dequeue methods)'''
def isempty(self):
'''if the rear pointer a... |
0cc98572b5f49820af23e97891796e033515bb62 | SusmoyBarman1/Python-OOP | /3. updateData.py | 767 | 4.0625 | 4 | class Human():
def __init__(self):
self.name = 'susmoy'
self.age = 24
def updateName(self, name):
self.name = name
def updateAge(self, age):
self.age = age
man1 = Human()
man2 = Human()
'''
print(f'\nName of 1st person: {man1.name}')
print(f'Age of 1st person: {man1.... |
9cf1f63c0387d1241ff810d847e5b64624fdf5c4 | ash-xyz/CompetitiveProgramming | /Kattis/Datum/date.py | 255 | 3.9375 | 4 | from datetime import date
days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
]
day, month = map(int, input().split())
day_of_week = date(2009, month, day)
print(days[day_of_week.weekday()])
|
b1ad89ac90fb83bc0be425247240d132e6650996 | thebazman1998/School-Projects | /Grade 10/Unit 1/Bp_U1_Assignment5/Bp_U1_Assignment5_V4.py | 1,795 | 4.1875 | 4 | """
Name: Basil
Class: ICS201-01
Date: 10/02/14
Assignment 5
"""
#Imports libraries
import math, random
#Asks user for a number and saves it to variable a
a = input("Enter a number")
print "Rounded down integer", math.floor(a)
print "Rounded up integer", math.ceil(a)
"""
1. The math.floor() command tells it to roun... |
e959cdde65daf61cd19e655fec9b7ddd65ffbe6a | annechen112995/ShakespeareSonnet | /src/dictionaries.py | 3,955 | 3.71875 | 4 | from shakespeare_processing import *
BORDER = "==============================================================="
def load_file(filename):
'''
Given a filename, load the file and return list of sentences
deliminated by '\n'
'''
raw_text = open(filename).read()
return raw_text
def import_sylla... |
119985c0fb5b36a51360003131436ae029d50346 | Akash-kakkar/Python-DS | /Day9/PyDS_Day9.py | 1,012 | 4.09375 | 4 | #When does operation between two uneven ndarray support in numpy and how?
#
'''If the arrays have different shapes, then the element-by-element operation is not possible. But, in real-world applications, you will rarely come across arrays that have the same shape. So Numpy also provides the ability to do arithmetic op... |
c62db5dc47eb08c3ffd5eedc616aec6158e21abc | gabrielajachs/courses | /Python Developer/Lesson120.py | 493 | 3.546875 | 4 | class PlayerCharacter:
membership = True
def __init__(self, name, age):
self.name = name
self.age = age
def shout(self):
print(f"My name is {self.name}")
@classmethod
def adding_things(cls, num1, num2):
return cls('Teddy', num1 + num2)
@staticmethod
def add... |
5c6dc02a8e551831b04c88e664c6e0e1b2e0596e | thewchan/python_oneliner | /ch3/numpy_assoc2.py | 693 | 3.890625 | 4 | """NumPy association analysis example.
Here we would like to find the two items that were purchased most often
together.
"""
import numpy as np
# Row is customer shopping basket
# row = [course 1, course 2, ebook 1, ebook 2]
# value 1 indicates that an item was bought.
basket = np.array([[0, 1, 1, 0],
... |
34e44753e83b11bf76982057445277012dd1b3ba | akshat14714/IT-Practice | /labs/lab-7/gibberish.py | 347 | 3.640625 | 4 | inputfile = open("encrypted.txt","r")
file = open("decrypted.txt","w")
def decrypt():
string = inputfile.read()
string = "".join(string.split('#'))
string = "".join(string.split('\n'))
string = "".join(string.split(' '))
ans = ""
for i in string:
ans += chr(ord(i) - 20)
file.write(a... |
c77d4a0c8ce00e0d7d83844e7092c69c0be08020 | captainmoha/MITx-6.00.1x | /Week 3/Objects/applyToEach.py | 628 | 3.984375 | 4 | # using functions as first class objects
# apply to each function takes a function and applies
# it to a list
lista = [1,2,3,4,5]
listb = [6,1,2,7,9]
def applyToEach(L,recurFact):
for i in range(len(L)):
L[i] = recurFact(L[i])
return L
# factorial with recursion
def recurFact(n):
... |
ceb29017310ac5582c500582312dd40a42f29b0d | mukeshk/python-learning | /hacker-rank/Strings/find-a-string.py | 798 | 4.1875 | 4 | """
In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left.
Output Format
Output the integer number indicating the total number of occurrences of the su... |
835ccc9a5580665c8b950b0b205e97b5cb0a5320 | katesolovei/python | /numbers.py | 708 | 3.75 | 4 | #Дано целое, положительное, трёхзначное число. Например: 123, 867, 374. Необходимо его перевернуть.
#Например, если ввели число 123, то должно получиться на выходе ЧИСЛО 321. ВАЖНО! Работать только с числами.
#Строки, оператор IF и циклы использовать НЕЛЬЗЯ!
number = int(input("Input *** number\n"))
res = lis... |
352e9aacde6bd81540203ef3a9917ab4f0661361 | caicono/PythonStartUp | /ex1.py | 615 | 4 | 4 | # -*- coding: utf-8 -*-
## ex1
print "Hello, world!"
print "Hello again"
print "你好!"
## ex2
print "I will count my chickens:"
print "hens:", 25+ 30/6
print "Roosters:",100-25*3%4
print "is it true that 3+2<5-7?", 3+2<5-7
#print 3+2<5-7
## ex3 varibles
cars = 100
space_in_a_car = 4.0
drivers = 30
... |
1d27acceacc19bc44d5b71216e3cf5da20b55205 | Ahmed-AG/python_tricks | /14-iterables.py | 907 | 3.953125 | 4 | def treat_as_iterable(iterable_var):
print(iterable_var)
first_pass = []
for v in iterable_var:
first_pass.append(v)
print("\tFirst Pass", first_pass)
print("\tSecond pass", [v for v in iterable_var])
print()
#lists_exist = [1, 2, 3]
#treat_as_iterable(lists_exist)
#range_generates = range(5)
#treat_... |
9726003d9e990bfcf4d657b0e557c351f8056267 | theByteCoder/CorePython | /List_Comprehension.py | 570 | 3.890625 | 4 | word = "coding is great"
# old method
my_list = []
for letter in word:
my_list.append(letter)
print(my_list)
# comprehension method
my_list = [letter for letter in word]
print(my_list)
# comprehension method
my_list = [num for num in range(1, 100)]
print(my_list)
# comprehension method - add con... |
6405b712be71faf4dbd9b6215aca6787a800a4d0 | dodecatheon/UW-Python | /winter2012/week04/print_time.py | 230 | 3.59375 | 4 | #!/usr/bin/env python
import time
import datetime
def date_time():
return datetime.datetime.now()
if __name__ == "__main__":
print "Here is the time: %s" % time.time()
print "and again: %s" % datetime.datetime.now()
|
9dac90a81abe3269786a86052cfb246a79ed98e0 | JZillifro/python-projects | /A5/assignment5.py | 5,718 | 3.921875 | 4 | """Implement a class called TreeDict that supports operators the same
way as a dict.
TreeDict should be implemented using the binarysearchtree module I
have provided (you can download it from canvas in the same folder as
this file).
You need to make sure you support the following operations with the
same semantics a... |
f5f36950d2cf34fb2b5e4d03f64b40a3226102bc | nitinworkshere/algos | /algos/tree/BST/SymmetricTree.py | 556 | 3.90625 | 4 | class Node:
def __init__(self, val):
self.val = val
self.right = None
self.left = None
def symetric_tree(root1, root2):
if not root1 and not root2:
return True
if root1 and root2:
return root1.val == root2.val and symetric_tree(root1.left, root2.right) and symetric_... |
b075c9a8b26b25603439618a88bef44eaac6a43b | itwasntzak/game_helper | /dice.py | 225 | 3.6875 | 4 | import random
def dice():
diceRoll = random.randrange(1, 7, 1)
return(diceRoll)
def diceRoll():
userChoice = int(input())
rollResult = [dice() for value in range(userChoice)]
print(rollResult)
|
3120f9b6ffe60e4676082d187f95259b27fad0f8 | junaidwahid/Implementation-of-UNET-Convolutional-Networks-for-Biomedical-Image-Segmentation | /helper_functions.py | 1,318 | 3.703125 | 4 | from torchvision.utils import make_grid
import matplotlib.pyplot as plt
def show_tensor_images(image_tensor, num_images=25, size=(1, 28, 28)):
'''
Function for visualizing images: Given a tensor of images, number of images, and
size per image, plots and prints the images in an uniform grid.
'''
# ... |
95fad8bdfd32aa98bcdf6c7ee62b0e4fff7bbe0c | spunos/project_euler | /problem12.py | 1,104 | 3.75 | 4 | # The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# Let us list the factors of the first seven triangle numbers:
# 1: 1
# 3: 1, 3
... |
2a3afe09c8e5a1386fb691ad6eabece6fbf901f5 | Jcabanas268/PRG105 | /chapter_practice/chapter7/ch_7_7.1_students_grades/student_grades_program.py | 2,004 | 4.125 | 4 | # Program to input student name & grade, print two dimensional list, write list to grade.txt
def main(): # define main() function
try: # try statement
num_students = int(input('E... |
6b91af2520471f23ef8afdbbfca301fd7126830a | marciocg/arvore_digital | /arvore_digital.py | 2,293 | 3.5625 | 4 | import time, string
# Define uma classe com a estrutura de nó da árvore digital, usando dicionário
class ArvNode:
filho = {}
fimpalavra = False
def __init__(self):
self.filho = {}
self.fimpalavra = False
self.contador = 0
raiz = ArvNode() # cria nó raiz vazio
def insere(palavra):
... |
3cfafaaa65660adae97b6df7e0fc9959c3386a28 | ChristineKarimi/Project-euler | /square.py | 256 | 3.796875 | 4 | #sum square difference
def main():
# finding sum of the squares.
a = sum([i**2 for i in range(101)]) # finding the square of the sum.
b = sum(range(101))**2 # Results.
print(b - a)
if __name__ == '__main__':
main() |
20b4e82ed2829dddae66d36a6ce911f589c2f239 | moontree/leetcode | /version1/483_Smallest_Good_Base.py | 1,223 | 4.15625 | 4 | """
For an integer n, we call k>=2 a good base of n, if all digits of n base k are 1.
Now given a string representing n, you should return the smallest good base of n in string format.
Example 1:
Input: "13"
Output: "3"
Explanation: 13 base 3 is 111.
Example 2:
Input: "4681"
Output: "8"
Explanation: 4681 base 8 is 11... |
c7812d94c29ca1363f279584bddb20a916491cb1 | quintanaesc/CYPRobertoQE | /python/libro/problemasresueltos/capitulo2/problema2_1.py | 169 | 3.75 | 4 | N=int(input("Ingrese el numero de sonidos emitidos por el grillo "))
if N>0:
T=(N/4)+40
print(f"La temperatura es de {T} grados fahrenheit")
print("Fin del programa")
|
a8a12087a7ae2ecf6d6d5ca1cd0896364d8f4494 | pankajdahilkar/RPi_tutorials | /LED interfacing/blinky2.py | 605 | 4 | 4 | import RPi.GPIO as GPIO
import time
LED = 40 # pin40
print(" ******** LED Blinking using Raspberry Pi 3 ********* ")
print(" **** Designed by pankajdahilkar.github.io **** ")
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) # We are accessing GPIOs according to their physical location
GPIO.setup(LED, GPIO.OUT) # We h... |
43224c9b38afade96060132180545248e4d84d94 | xarchived/patrix | /patrix/patrix.py | 2,118 | 3.546875 | 4 | def matrix(r, c):
return [[0 for _ in range(c)] for _ in range(r)]
def shape(mat):
r = len(mat)
c = len(mat[0])
return r, c
def main_diagonal(mat):
dia = []
col = 0
for row in mat:
dia.append(row[col])
col += 1
return dia
def anti_diagonal(mat):
dia = []
co... |
0e6f54dbbf8e8e5f561f2495c5a76eaaed3dc0f8 | Gokhulnath/Algorithm_lab | /Ex 6/ex6.py | 1,012 | 3.78125 | 4 | def trace_lcs(tab,a,b):
i=len(a)
j=len(b)
lcs=[]
while(i>0):
if(tab[i][j]==tab[i-1][j]):
i=i-1
elif(tab[i][j-1]==tab[i][j]):
j=j-1
else:
lcs.append(a[i-1])
i=i-1
j=j-1
print("Longest subsequence:",lcs)
def l... |
becbefa76ebf883d5d913c4a7c95ddd750867cbc | ernybugi/ACM_ICPC_DOT_NET_PS | /p1011/p1011.py | 589 | 3.53125 | 4 |
for test in range(input()):
startEnd = map(int, raw_input("").split(" "))
distance = startEnd[1] - startEnd[0]
maxStep = 2
result = 2
if distance == 1:
print 1
elif distance == 2:
print 2
else:
distance -= 2 # except first and last 1 step
while distance... |
3164b94d26a9dcd9940e5cb259830ed9772fc603 | Jansonboss/LeetCoding_Practice | /DepthFirstSearch/LintCode90_K_SumII.py | 954 | 3.5625 | 4 | # https://github.com/princeton-nlp/SimCSE
def kSumII(A, k, target):
A = sorted(A)
subsets = []
dfs(A, 0, k, target, [], subsets)
return subsets
def dfs(A, index, k, target, subset, subsets):
if len(subset) == k and target == 0:
subsets.append(list(subset))
return
if k == 0 or target <= 0:
return
for... |
8763b7f391a155078b065d7f227e10a73f67e357 | jakegerard18/Python-Datastructures-and-Algs | /Stack.py | 437 | 3.828125 | 4 | from LinkedList import LinkedList
class Stack:
def __init__(self, startingNode):
self.size = 0
self.stack = LinkedList(startingNode)
def push(self, node):
self.stack.addToHead(node)
self.size += 1
def pop(self):
self.size -= 1
return self.stack.removeHead()... |
72f019884e5b5efc5f07e17d2b7556ade1cdc884 | newbabyknow/python_practice | /longest_substring.py | 454 | 3.78125 | 4 | # 滑动窗口方法,计算字符串的最长不重复子字符串
def window(s):
begin_index = 0
max_long = 0
for i in range(1, len(s)):
if s[i] in s[begin_index:i]:
max_long = max(max_long, len(s[begin_index:i]))
begin_index += s[begin_index:i].index(s[i]) + 1
if max_long == 0:
max_long = len(s)
r... |
620b07938c9c4e9d25586de86c4c53f8589b07ba | shikhashah2627/LeetCodePractice | /ArrayImpQuestions.py | 3,401 | 3.65625 | 4 | def countTriplets(nums):
# nums.sort()
n = len(nums)
# count = 0
# for i in range(0, n-2):
# j = i+1
# while j < n:
# if nums[i] + nums[j] in nums:
# count += 1
# j += 1
# return count
max_val = 0
for i in range(n):
max_val =... |
da992604e15bf93e45d5ec9f3546b6bf337d705f | herllyc/Leetcode_Daily | /电话号码组合/index.py | 332 | 3.78125 | 4 |
def index(digits):
tel_dic = {2:'abc',3:'def',4:'ghi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'}
print(tel_dic[2])
if digits=='':
return['']
ls = ['']
for i in digits:
ls = [x+y for x in ls for y in tel_dic[int(i)]]
return ls
if __name__ == '__main__':
str = '23'
print... |
d9ff2b47d4918e770318b705b239c4f7cb14566c | hyun98/python | /알고리즘/수학/소수1.py | 477 | 3.984375 | 4 | def prime_checker(n):
if n==1:
return 0
else:
d=2
while(n!=d):
if n%d != 0:
d+=1
else:
return 0
if n==d:
return 1
def the_number_of_prime(arr):
count=0
for i in arr:
count+=prime_checker(i)
p... |
adee8a69e12f792fc87935562548473902b26750 | Zander-M/ICS-Exercise | /state_machine.py | 738 | 3.78125 | 4 | # ope = [ '+', '-', '*', "/"]
# while input != "q":
# a = input()
# if not a.isdigit():
# if a == 'q':
# break
# elif a == 'c':
# a = input()
# else:
# a = input()
# b = input()
# if not b.isdigit():
# if b == 'q':
# break
# elif b == 'c':
# b = input()
# else:
# b = input()
# ... |
9d72e153c2f20e8ac8ce55946b4e9d72907bfd6b | jianantian/misc | /_exercises/the_pragmatic_programmers/python/6.py | 663 | 3.765625 | 4 | import arrow
def get_input(message=""):
while True:
raw = input(message)
try:
res = int(raw)
except ValueError:
print("Please check your input.")
else:
break
return res
age = get_input("What is your current age? ")
retire_age = get_input("At ... |
e57d0a0b857bccfcfa8c209accb3f20e9ff3e03d | splaiser/newbie | /Class/user/user.py | 793 | 3.53125 | 4 | class User():
def __init__(self,first_name,last_name,age,location):
self.first = first_name
self.last = last_name
self.age = age
self.location = location
self.login_attempts = 0
def describe_user(self):
print(f"First name : {self.first.title()}")
print(f"... |
812afb47347144d757f17e3f5e94104067b65f94 | sammorrell/space-exe-python | /code/pythonic/enumerate.py | 342 | 4.1875 | 4 | # Zip combines the two or more arrys into a single
# for loop, leting you easily iterate over the values
list1 = ['a1', 'a2', 'a3', 'a4', 'a5']
list2 = ['b1', 'b2', 'b3', 'b4', 'b5']
for i, l1 in enumerate(list1):
l2 = list2[i]
print('{}, {}'.format(l1, l2))
# Will print:
# a1, b1
# a2, b2
# a3, b3
... |
d3d674d52977eb8577ab092266565fd9f1cec22f | arch123A/luoye | /Tony_study/whiel99乘法表.py | 197 | 3.5 | 4 | def 打印99表():
j=1
while j<=9:
i=1
while i<=j:
print ( "%d×%d=%d" % (i, j, i * j), end="\t" )
i+=1
j=j+1
print()
打印99表()
|
607310fa9e365d31019f82dd98750f7f66c54440 | Redoxfox/python_algoritmos | /funcion.py | 800 | 4.1875 | 4 | '''Programa para calcular valores de funcion f(x) = x²-13x+30 en intervalo [3,10]'''
'''Esta funcion puede ser representada como y = x²-13x+30 '''
#Definicion de variables
yi = 0 #Resultado de la funcion en cada punto del intervalo (iniciacion a cero)
xi = 3 #Valor de cada punto del intervalo (iniciacion en 3)
'''... |
0d7ecbaa57a82fe2cbb476f280271c1a8f10cbf9 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/kmsnyde/lesson04/mailroom2.py | 2,397 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 11 17:38:02 2018
@author: Karl M. Snyder
"""
#[[fill]align][sign][#][0][minimumwidth][.precision][type]
from collections import defaultdict
donor_dict = defaultdict(list, {'Karl Stick': [10, 20, 30],
'Kate Stam': [5, 30],
'Christine Goose': ... |
e024d268bfe95db8a4a9f339c870f84a4e7663c5 | dvdgitman/DevOPS-Project | /SiteChecker.py | 533 | 3.9375 | 4 | import requests
def get_url_status(urls): # checks status for each url in list urls
# for url in urls:
try:
r = requests.get(urls)
print(urls + "\tStatus: " + str(r.status_code)) # Prints the url and status of the site(Up/Down)
except Exception as e:
print(urls + " - The url is pr... |
70a17a5e43e6c56302c95e65482557cda4a4678a | geethaninge/PythonCoding | /PythonPgm/SearchUsingDivideAndConqure.py | 622 | 4.15625 | 4 | '''
Divide and conqre approach has log n time complexity
for binary search string should be in sorted order
'''
def binarySearch(list1,key):
if len(list1)==0 :
return False
mid = (len(list1))//2
if key == list1[mid] :
return True
elif key < list1[mid]:
return binarySearch(list1[:mid-1],key)
... |
0d6ec1badb5b143d658e8c150062063c349d5486 | srujanprophet/PythonPractice | /Class XII CBSE/1.1.32.py | 184 | 4 | 4 | l = []
n = int(raw_input("Enter n :"))
for i in range(n):
x = int(raw_input("Enter number : "))
l.append(x)
print "Set of Numbers :",l
print "Reversed set of Numbers",l[::-1]
|
a32799b09aa55d659d2af9bb7edbe35bd19e5460 | sujal100/sujal100-Probability_and_Random_variable | /exercise_2/code/exercise_2.py | 774 | 3.703125 | 4 | # problem
''' A box contains 4 white balls and 3 red balls.
In succession, two balls are randomly selected
and removed from the box. Given that the first
removed ball is white, the probability that the
second removed ball is red is _____
(A) 1/3
(B) 3/7
(C) 1/2
(D) 4/7'''
# solution
import random
def ... |
a678eaf1e3f07032d2eaf15e5810d2868d8c0256 | jsearfoo/beginner-project-solutions | /Pythagorean Triples Checker.py | 1,086 | 4.25 | 4 | '''
Pythagorean Triples
A "Pythagorean Triple" is a set of positive integers, a, b and c that fits the rule:
a*a + b*b = c*c
Here is a list of the first few Pythagorean Triples
(3,4,5)
(5,12,13)
Example: scale 3,4,5 by 2 gives 6,8,10 which should be Pythagorean Triples
'''
def PyTriples(a,b,c):... |
0c288b3da6dab5a1d9b670253e9093a20cc12099 | jonatanjmissora/PRACTICE_PYTHON | /PRACTICE_21_AL_25.py | 4,008 | 3.765625 | 4 | """# escribir un archivo
open_file = open('test.txt', 'w')
open_file.write('testprimer renglon\n')
open_file.write('segundo renglon\n')
open_file.write('tercer renglon\n')
open_file.close()
#otra forma de escribir, mejor syntaxis
with open('names.txt', 'w') as open_file:
open_file.write('cuarto renglon\n')
#leer ... |
4be3a56e8cac0e8e1aafea827a6cbf3769be6b05 | sankar-vs/Python-and-MySQL | /Numpy/8_Convert_list_tuple_to_array.py | 399 | 4.4375 | 4 | '''
@Author: Sankar
@Date: 2021-04-14 08:19:25
@Last Modified by: Sankar
@Last Modified time: 2021-04-14 08:35:09
@Title : Numpy_Python-8
'''
'''
Write a Python program to convert a list and tuple into arrays.
List to array:
[1 2 3 4 5 6 7 8]
Tuple to array:
[[8 4 6]
[1 2 3]]
'''
import numpy as np
list = [1,2,3,4,5,6,... |
cef88cde497da1e8bade740a872f630a72500589 | Pedro0901/python3-curso-em-video | /Python 3 - Mundo 2/Scripts Python - Mundo 2/Aula13.py | 1,011 | 4.0625 | 4 | for c in range(0, 6): #Primeiro numero dentro do parentese é onde a contagem começa, o 2º é onde PARA. (Para e nao mostra o numero)
print(c)
print('-------------DIVISÓRIA-------------')
for c in range(6, 0, -1): #O -1 informa que você quer contar do maior para o menor. (De traz pra frente)
print(c)
print('\nFIM')
... |
58d8564f83024fdb740fe9a4510b4671b0a97738 | ayoubabounakif/HackerRank-Python | /03. Strings/006. String Validators.py | 802 | 4.09375 | 4 | # Problem: https://www.hackerrank.com/challenges/string-validators/problem
if __name__ == '__main__':
s = input()
result = ["False", "False", "False", "False", "False"]
for i in s:
if i.isalnum():
result[0] = "True"
if i.isalpha():
result[1] = "True"
... |
d17839f31e383648f27b00beacb09fb379efdb6f | esau91/Python | /Problems/leetcode/avg_word_len.py | 565 | 4.125 | 4 | #Author: esau91
#Date: 03/04/2021
#Source: leetcode
#Description: return the average word len from string
def solution(test):
words_len = []
test = test.split()
if len(test) == 0:
print(0)
return 0
for word in test:
words_len.append(len(word))
print(sum(words_len)/len(... |
cb50e54c2018b4b9b22f33240cf6f8b8827e9086 | naveenramees/py-program | /52.py | 90 | 3.859375 | 4 | y = int(input("Enter the num:"))
if y%2 == 0:
print "\nEven"
if y%2 != 0:
print "\nOdd"
|
5640b6b0d3666f1579b231651d6634b554ae1f46 | EachenKuang/LeetCode | /code/674#Longest Continuous Increasing Subsequence.py | 517 | 3.546875 | 4 | # https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/
class Solution:
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 1:
return 0
temp = 1
sum = 1
for i in range(1,... |
afcba87fdca54e36cb4756286e14bf4af7ac6f1b | KanthetiManojSanjay/PythonProjects | /python_tips/operator_overloading_examples.py | 1,704 | 3.828125 | 4 | from functools import total_ordering
@total_ordering # to reduce redudancy
class Money:
def __init__(self, currency, amount):
self.currency = currency
self.amount = amount
def __add__(self, other):
return Money(self.currency, self.amount + other.amount)
def __sub__(self, other):... |
371f3ba9f41608e0a4cc4b1ae976defc94cc9f68 | jeff-lund/CS199 | /Python/Lists/binary.py | 566 | 4.125 | 4 | # Converting a decimal number to a binary number with a divide by 2 algorithm
n = int(input("Enter a positve number: "))
if n < 0:
print("Invalid number")
elif n == 0:
print(0)
else:
binary = []
count = 0
while n > 0:
q = n // 2 # quotient is to be carried on to the next iteration
... |
76644f45c6147d982e67856c627be3c93efe685e | MohammedGhafri/data-structures-and-algorithms-python | /data_structures_and_algorithms/challenges/quick_sort/quick_sort.py | 745 | 3.953125 | 4 | def QuickSort(arr,left,right):
if left < right:
pi = Partition(arr,left,right)
QuickSort(arr, left, pi-1)
QuickSort(arr, pi+1, right)
return arr
def Partition(arr,left,right):
i = ( left-1 )
pivot = arr[right]
for j in range(left , r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.