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 |
|---|---|---|---|---|---|---|
c15014e022fb80ead4c363acfc690774e42f906f | Breachj71440/01_area_perimeter_assessment | /03_dimensions_input.py | 3,662 | 4.34375 | 4 | # asks user to only enter the following shapes
print("choose one of the following shapes: "
"square, rectangle, "
"circle, triangle, "
"parallelogram")
# what user is allowed to input after the questions
valid_shapes = ["square", "rectangle", "circle", "triangle", "parallelogram"]
valid_ap = ["... |
3054bead64ee9c307a075cd483a1b0eb1ec8dc8a | rohanwarange/Accentures | /program6.py | 1,379 | 4.1875 | 4 | # # # -*- coding: utf-8 -*-
# # """
# # Created on Sat Jun 26 07:19:47 2021
# # @author: ROHAN
# # """
# # Problem Statement
# # A carry is a digit that is transferred to left if sum of digits exceeds 9 while adding two numbers
# from right-to-left one digit at a time
# # You are required to implement the following ... |
5d623063e5a43caee25e23d9adba7895e212224c | alexssssalex/Longman | /Base.py | 1,237 | 3.609375 | 4 | from config import WORDS_IN_STUDY, WORDS_KNOWN, WORDS_IN_STUDY_BAK
def read_arrange(path: str) -> set:
"""
- read file by path;
- filter empty lines;
- made unique list;
- arrange list set and save word in the same file in alphabet order;
"""
with open(path, 'r') as f:
data = [w.s... |
d49a3de465224a2f238d09500289556e83c06d39 | GGreenBow/Python-Facul | /exercicios/aula 15 out/nao sie.py | 334 | 3.953125 | 4 | num=int(input('Digite um numero: '))
par=0
imp=0
while(num>0):
if num%2==0:
par=par+1
print('O número %d' %num, ' é par')
else:
imp=imp+1
print('O número %d' %num, ' é ímpar')
num=int(input('Digite um numero: '))
print('O total de números pares é %d' %par, ' e ímpares é %d' %... |
68a0e78c9d7fddeef33078c06156ead1ec265204 | HeapOfPackrats/AoC2017 | /day1b.py | 687 | 3.953125 | 4 | #http://adventofcode.com/2017/day/1
import sys
def main(argv):
#get input, otherwise prompt for input
if (len(argv) == 2):
inputStr = argv[1]
sum = 0
else:
print("Please specify an input argument (day1b.py [input])")
return
#find any char whose int value is equal to th... |
c4d4c614b9353e8d1508a909b14ed6b96a585185 | rogeriosilva-ifpi/teaching-tds-course | /programacao_estruturada/20192_166/Bimestral1_166_20192/JABES_166/jabeq04.py | 179 | 3.9375 | 4 | base = float(input('Digite o tamando da base do triâgulo: '))
h = float(input('Digite a altura do triâgulo: ' ))
area = base * h / 2
print(' A area do triâgulo é :' , area)
|
00cee42c2eca24a213590acc92a3af917233e6a2 | LuciaIng/TIC_20_21 | /ejercicio3.py | 513 | 4.0625 | 4 | '''Escriba una funcin que reciba
un nmero entero del 1 al 7 y
escriba en pantalla el correspondiente
da de la semana.'''
def ejercicio_3():
dias_semana=["Lunes","Martes","Miercoles","Jueves","Viernes","Sabado","Domingo"]
numero=input("Escribe un nmero: ")
while numero < 1 or numero > 7:
... |
b9d1457bfd8ac6e8135f5301d3a746b283a34ab2 | beatSpatial/isp | /isp_semi_auto/csv_xlsx_utils.py | 5,722 | 3.875 | 4 | import os
import csv
from openpyxl import load_workbook, Workbook
def _convert_csv_to_xlsx(list_loc):
# TODO: Test function with actual CSV as it would be provided
try:
csv_file = csv.reader(
open(list_loc, "r"),
quotechar='"',
delimiter=",", quoting=csv.QUOTE_ALL,
... |
a4313c9b45252f7171b6763301368c2b4a83e2ac | Akshata2704/APS-2020 | /121-convert_zeros_5.py | 316 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 10 22:42:51 2020
@author: AKSHATA
"""
def convertFive(n):
s=list(str(n))
for i in range(len(s)):
if(s[i]=='0'):
s[i]='5'
return ''.join(s)
for _ in range(int(input())):
print(convertFive(int(input()))) |
9503e2607ba4e738649fb72a729014a84b48ac53 | zygoh1986/FS104 | /Session6/writetofile.py | 173 | 3.578125 | 4 | file_string = str(input("Enter Text here:"))
def write(text):
file_object = open("testfile","w")
file_object.write(text)
file_object.close()
write(file_string) |
2c7d6d3c53e6ca094067f84842b29d4ee4beb886 | automata-studio/HackerRank-Solutions | /ProblemSolving/Python/Sorting/quicksort_2_sorting.py | 532 | 3.9375 | 4 | def partition(arr):
p = arr[0]
left, equal, right = [], [], []
for e in arr:
if e > p:
right.append(e)
elif e == p:
equal.append(e)
else:
left.append(e)
return left, equal, right
def quicksort(arr):
if len(arr) <= 1:
return a... |
83b6d19fe07d76888e2d98a4884a59bd95c91382 | oglebee/python.learning | /rec.py | 3,342 | 4.125 | 4 | import os
os.system("clear")
import math
pi = float(math.pi)
############################################
#Load in
############################################
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def get_perimeter(self):
return 2 * (self.width + self.h... |
6528887bb9d07d26056f53b32bea096d8378a41a | witkowskipiotr/Checkio | /code_2017_11_06/tickets.py | 2,240 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Task from
http://www.codewars.com/kata/555615a77ebc7c2c8a0000b8/train/python
"""
def sell_tickets_to_all_customers(*, people: list) -> str:
"""
Can you sell a ticket to each person and give the change
if you initially has no money and sells the tickets strictly
in the order... |
191d1cffc447494dd2960277262164ae88b01f9d | fatmanursaritemur/python-numpy-pandas-tutorial | /Python/Pandas/demo.py | 301 | 3.578125 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
notes=pd.read_csv("grades.csv")
notes.columns =["İsim","Soyisim","SSN","T1","T2","T3","T4","Final","Grade"]
print(notes)
print(type(notes))
print(notes.head())
print("*******************************")
print(notes["İsim"])
print(notes.iloc[2]) |
1f648d440c2306e012d044c7bb98d095c9a22419 | xiyuansun/Udacity_Machine_Learning_Engineer | /Numpy_Practice/np_prac_02.py | 2,443 | 4.53125 | 5 | import numpy as np
'''
The following code is to help you play with Numpy, which is a library that provides functions that are especiall useful when you have to work with
large arrays and matrices of numeric data.
Numpy is battled tested and optimized so that it runs fast, much faster than if you were working with Pyth... |
927e692401759567398ddd5edb5d5427f2dbe65e | yeboahd24/Python201 | /PYTHON LIBRARY/SUB_2/datetime_date_math.py | 385 | 3.859375 | 4 |
import datetime
today = datetime.date.today()
print('Today :', today)
one_day = datetime.timedelta(days=1)
print('One day :', one_day)
yesterday = today - one_day
print('Yesterday:', yesterday)
tomorrow = today + one_day
print('Tomorrow :', tomorrow)
print()
print('tomorrow - yesterday:', tomorrow -... |
edc7118c1b673353a737fb5e7dd8e65671e7b76a | cpd-central/inventor | /excel/read_write_excel.py | 963 | 3.671875 | 4 | #script to read data from mongodb, put into pandas dataframe and write to excel.
#will be similar to putting the data on the website, these may be combined at some point.
import pandas as pd
def mongo_to_dataframe(documents):
mongo_df = pd.DataFrame(documents)
#removes the mongodb id from the dataframe
#mongo_df... |
ed0e2ff55e63644321bdc7a4aff22a696d1746c6 | MiyabiTane/myLeetCode_ | /31_m_Next_Permutation.py | 646 | 3.5625 | 4 | def nextPermutation(nums):
list=[]
for i in range(len(nums)):
pointer=len(nums)-1-i
#print(pointer)
if pointer==0:
nums.sort()
return nums
list.append(nums[pointer])
if nums[pointer-1]<nums[pointer]:
list.append(nums[pointer-1])
... |
bda852dd871383e39613208b313f71f60edd3db0 | uniyalnitin/competetive_coding | /Hackerrank/hackerrank_(gena).py | 1,387 | 3.640625 | 4 | '''
Problem Url: https://www.hackerrank.com/challenges/gena/problem
Idea: Use BFS to get the minimum depth from current state to final state
'''
from collections import deque
def legal_moves(x):
'''
This function is used to get the valid moves from current state
'''
for i in range(len(x)):
if x[i]:
for j ... |
26c98f87fd2a3247a4c2f5274d2face8f25094e8 | valen2510/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 395 | 3.71875 | 4 | #!/usr/bin/python3
"""function that returns True
if the object is an instance of
a class that inherited from the
specified class; otherwise False
"""
def inherits_from(obj, a_class):
"""Returns True if the object is an instance
of a class or specific inherited class
"""
if (type(obj) is no... |
940a8ab3f2269fcbc7e5dd34aae86dca7d431d47 | Silentsoul04/my_software_study | /Algorithm/SWEA/6323_함수의_기초_4.py | 665 | 3.890625 | 4 | # 1. 10을 치면 10개의 피보나치 수열이 리스트 형식으로 나타나게 하자.
# 2. while문을 이용해서 지정한 숫자 횟수만큼 이전의 숫자와 합쳐지게 만들자.
# 3. 합쳐진 숫자를 append하여 리스트를 제작하자.
# 4. 다 했으면 return 값을 받을 수 있는 함수를 제작하고 함수를 만들고 출력하자.
def function():
number = int(input(''))
start_number = 1
lis = [1,1]
number_new= 0
while start_number < number-1:
... |
ea997879fddb718a7a1ea941b475934721edab75 | IamFive/note | /note/python/recipel.py | 1,313 | 3.6875 | 4 | class RomanNumeralConverter(object):
def __init__(self, roman_numeral):
self.roman_numeral = roman_numeral
self.digit_map = {
"M":1000,
"D":500,
"C":100,
"L":50,
... |
f503f4822f5b659b0d7487b723498da185e1a14b | zubie7a/Algorithms | /HackerRank/Algorithms/01_Warmup/07_Staircase.py | 211 | 3.953125 | 4 | # https://www.hackerrank.com/challenges/staircase
n = int(raw_input())
# Print a staircase like
'''
n = 6
#
##
###
####
#####
######
'''
for i in range(n):
print " "*(n - i - 1) + "#"*(i + 1)
|
570d97f8af9ef484a7b2fa761cd0563ad585ca65 | jongfranco/python-workshop-wac-5 | /day_2/list_comrehension.py | 369 | 3.625 | 4 | """
{1^2, 2^2 .....}
{x^2 | for all x in natural numbers}
{2x + 1 | for all x in integers}
{2n | n in (3, 10)}
[f(x) for x in iterable]
"""
# value = [x % 2 for x in range(1, 11)]
# print(value)
print(''.join([character.upper() for character in 'hello world']))
print(sum(n ** 2 for n in range(1, 4)))
val = min(x fo... |
6cd2f2676d43735a662606f8a8b7b6049346a270 | cfireborn/PrepCS | /backend/Database for PrepCS Courses/6 - Recursion and Dynamic Programming/Recursion and Dynamic Programming.py | 8,037 | 3.84375 | 4 | """
===================================================================================
EASY
===================================================================================
"""
#########################################
"""
A child is running up a staircase with n steps, and can... |
84446798522f7dba59ba5c6497d330983584fd28 | mandrakean/Estudo | /Python_Guan/ex056.py | 682 | 3.53125 | 4 | print('-=-'*20)
print('')
print('-=-'*20)
print('-=-')
soma_idade = 0
NH = ''
IV = 0
mul = 0
for c in range(1, 5):
print('----- {} PESSOA ------'.format(c))
nome = str(input('nome: '))
idade = int(input('idade: '))
sexo = str(input('Sexo (M/F): '))
soma_idade += idade
if c == 1 and sexo in 'Mm... |
a912818e829dac2f84bc7b9764dfd75140d58673 | banje/acmicpc | /2440.py | 83 | 3.71875 | 4 | a=int(input())
b="*"*(a+1)
for i in range(a):
b=b+" "
b=b[:-2]
print(b) |
da7a8fc01f7066430874c17e442c4290d313705c | Sionae/Stickmen_genetic_alg | /Functions.py | 2,770 | 3.5 | 4 | from time import time
from Classes import *
def StartPopulation(total):
population = []
for ind in range(0, total):
sword_length = random.randint(2, 5)
speed = random.randint(4, 15)
evade = random.random()
strength = random.randint(4, 15)
health = random.randint(10, 50)... |
aa70b6c5bd4d7acefb332c969ea3f13a9dbeb81a | mohamedsamyfoda/Code_Camp_Python | /Conditions/Conditions_6.py | 127 | 3.765625 | 4 | value1 = 10
value2 = 10
equal = value1 == value2
if equal == True :
print ('True')
if equal == False:
print('False')
|
3bbf813cf7de045952d9669a731f82a08af7627e | Himanshuma38966/furry-octo-goggles | /107.py | 353 | 3.59375 | 4 | import pandas as pd
import plotly.graph_objects as go
df=pd.read_csv("data.csv")
#to show how groupby works
'''
x=list(df.groupby("level"))
print(x)
'''
print(df.groupby("level")["attempt"].mean())
fig=go.Figure(go.Bar(x=df.groupby("level")["attempt"].mean(),y=["level 1","level 2","level 3","level 4"... |
60f6d99ac3be768e739cc93f15bd5747b30dacce | charan2108/pythonprojectsNew | /Dpython/datatypes/boolean.py | 93 | 3.625 | 4 | a = True
print(a)
print(type(a))
a = 10
b = 20
print(a>b)
print(a<b)
print(a>=b)
print(a<=b) |
46c54dc0dc2e3a8ef6a20a448e93139897da84d7 | EOppenrieder/HW070172 | /Homework5/Exercise6_8.py | 389 | 4.15625 | 4 | # A program to guess the square root of numbers
import math
def nextGuess(guess, x):
g = (guess + x / guess) / 2
return g
def main():
x = float(input("Enter the number of which you want to know the square root: "))
n = int(input("Enter the number of times to improve the guess: "))
g = x / 2
f... |
3daee9f5943b113cc004c49ebfa8102c5d42c98a | chandanadasarii/CrackingTheCodingInterview | /Heaps/heapsort.py | 345 | 3.765625 | 4 | from Heap import Heap
# Time complexity : O(nlogn)
def heapsort(data):
heap = Heap('maxheap')
heap.build_heap(data)
for i in range(len(data)-1, 0, -1):
heap.data[i], heap.data[0] = heap.data[0], heap.data[i]
heap.n -= 1
heap.precolate_down(0)
return heap.data
print(heapsort([... |
a5609f4bb31a16a8615c7f3ef7d8b37914fa90cc | Duvaragesh/hello-world | /hungry.py | 227 | 3.953125 | 4 | isHungry = input("Are you hungry?")
if isHungry == 'yes':
print('eat samosa!')
else:
print('do your work')
'sample change
'abcdef
'publicKeyToken=abcdef1234
'https://github.com/Duvaragesh/hello-world/edit/master/hungry.py
|
0521922fde3d4119b6d82948aee0e21e02bb2b89 | vigneshsrinivasan9/Disease-Named-Entity-Recognition | /utils/utils.py | 823 | 3.546875 | 4 | def get_tagged_sentences(data):
'''
Objective: To get list of sentences along with labelled tags.
Returns a list of lists of (word,tag) tuples.
Each inner list contains a words of a sentence along with tags.
'''
agg_func = lambda s: [(w, t) for w, t in zip(s["Word"].values.tolist(), s["t... |
31b952b6a68b87ca8795eb6d4dc5692a93002a71 | PedroVitor1995/Algoritmo-ADS-2016.1 | /Cadeias/resolvidos_momento/Questao02.py | 367 | 3.71875 | 4 | #__*__ encoding:utf8 __*__
"""2. Leia uma frase e mostre cada palavra da frase em uma linha separada."""
def main():
frase = raw_input('Digite uma frase: ')
frase = frase.split()
for i in range(len(frase)):
print frase[i]
# espaco = ' '
# for letra in espaco:
# frase = frase.replace(letra,'\n')
# p... |
86ac1f622127f98a4a0be2b2a6428571a8c0d206 | guoliangxd/interview | /huawei/Python/count.py | 476 | 3.8125 | 4 | while True:
try:
_str = input()
alpha = 0
space = 0
digit = 0
other = 0
for char in _str:
if char.isalpha():
alpha += 1
elif char.isspace():
space += 1
elif char.isdecimal():
digit += ... |
f65706ff6527e0cd146b8ede4d3d595b819a0dda | pensebien/intro_to_programming | /fib.py | 691 | 3.765625 | 4 | # Uses python3
import random
import time
st = time.clock()
def calc_fib(n):
a,b = 0,1
if n<=0:return a
for i in range(1,n):
a, b = b, a+b
return b
def fibMatrix(n):
ar = Array(n)
for i in range(2, n):
fib_num = ar[i-1] +ar[i-2]
return fib_num
if __name__ == ... |
7d3074e3078405bac74fff36372388e2033f6c6d | Abhi-1298/practice-1 | /inhertance.py | 2,107 | 4.21875 | 4 | '''You are given two classes, Person and Student, where Person is the base class and Student is the derived class. Completed code for Person and a declaration for Student are provided for you in the editor. Observe that Student inherits all the properties of Person.
Complete the Student class by writing the followin... |
acc3cccb9a89f0ea20e4ed9478bcdb67c83fa251 | rajaprerak/Algorithmic_Toolbox-Coursera-Python | /Week4/majority_element.py | 594 | 3.609375 | 4 | def majority_element(elements):
assert len(elements) <= 10 ** 5
track_count = {}
for each in elements:
if each in track_count:
track_count[each] += 1
else:
track_count[each] = 1
for value in track_count.values():
if value > len(elements) / 2:
... |
3339ecc89f97fe272fbd23fb57a2402a682441ba | yunfei-teng/PyTorch-Tutorial-Spring-2019 | /recitation1/classification/models.py | 1,501 | 3.578125 | 4 | # PyTorch tutorial codes for course EL-9133 Advanced Machine Learning, NYU, Spring 2018
# models.py: define model structures
# read: https://pytorch.org/docs/stable/nn.html
import torch.nn as nn
import torch.nn.functional as F
class ConvNet(nn.Module):
''' convolutional neural network '''
def __init__(self):
... |
c4f3800d63ee2ccbd8751587280c7b896736fde3 | tribadboy/algorithm-homework | /week4/括号生成.py | 533 | 3.59375 | 4 | # -*- coding:utf-8 -*-
from typing import List
class Solution:
def generate(self, left: int, right: int, n: int, chars: str, result: List[str]):
if left == n and right == n:
result.append(chars)
if left < n:
self.generate(left+1, right, n, chars+'(', result)
if right... |
8e88c367875f6cb78e4e93ef4fa07395e45bfaf3 | yamabook37/atcoder | /Library/my_sort.py | 445 | 3.84375 | 4 | # bubble
def bubble(num):
# 方針
# 後ろから順に隣り合う要素を比較する。
# 左が右の要素に比べ大きい場合交換。
# 走査範囲を前からひとつ狭める。
for i in range(len(num)-1):
for j in range(len(num)-1, i ,-1):
if num[j] > num[j-1]:
tmp = num[j-1]
num[j-1] = num[j]
num[j] = tmp
print(num)
return num
array = [2, 3, 5, 4, 1]... |
7a72b5d807c2314e2c656161d08f6ed3c3e64ca8 | MichelFeng/leetcode | /118.py | 937 | 3.734375 | 4 | # coding=utf8
# 118. 杨辉三角
# 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
# 在杨辉三角中,每个数是它左上方和右上方的数的和。
# 示例:
# 输入: 5
# 输出:
# [
# [1],
# [1, 1],
# [1, 2, 1],
# [1, 3, 3, 1],
# [1, 4, 6, 4, 1]
# ]
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: Li... |
93053cfa0b36987ceb64f9bd4c2884989fab1b87 | Sajan-Optimal-AI/self-landing-rocket-simulation | /simulator.py | 5,381 | 3.984375 | 4 | """Simple rocket simulator.
Some Physical Limits Due To My Unexperience in Physics Yet :
* The rocket is treated as point with only thrust and gravity acting on it.
* The rocket is perfectly stable with no horizontal forces acting on it.
* The rocket is indestructable.
* The rocket has infinite fuel and... |
0e39a0ac2bd6ef04d22247058fc1c7a3a1b7b0aa | tanyalevshina/decisionengine | /src/decisionengine/framework/util/tsort.py | 2,056 | 4.0625 | 4 | """
See:
https://en.wikipedia.org/wiki/Topological_sorting
Kahn's topological sorting algorithm
L Empty list that will contain the sorted elements
S Set of all nodes with no incoming edge
while S is non-empty do
remove a node n from S
add n to tail of L
for each node m with an edge e from n to m do
... |
e795bea0ba602aeecac5be55eadb7ecdfe156847 | arsamigullin/problem_solving_python | /leet/amazon/trees_and_graphs/1334_Find_the_City_With_the_Smallest_Number_of_Neighbors_at_a_Threshold_Distance.py | 3,641 | 3.609375 | 4 | import collections
import heapq
from typing import List
class SolutionWrong:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
# a deque is faster at removing elements from the front
graph = collections.defaultdict(dict)
for u, v, dist in edges:
... |
19c231cad39b0cee44f5264a3eaf78ac4294bfd6 | xuweixinxxx/HelloPython | /nowcoder/foroffer/Solution10.py | 1,449 | 3.578125 | 4 | '''
Created on 2018年1月30日
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
@author: minmin
'''
class Solution10:
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return None
if not pRootOfTree.left and not pRootOfTree.right:
retu... |
c507ff6dbf30213e74ff53cbf4cd8ffc635b900d | GabrielAbdul/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 2,530 | 4.5 | 4 | #!/usr/bin/python3
"""
class Square that defines a square based on 5-square.py
"""
class Square:
""" Class of square that has no size
Attributes:
__size (int): size of square
"""
def __init__(self, size=0, position=(0, 0)):
"""
Initialization of square size
Args:
... |
ea9ac4d8272067629e5bf89cbbd5f9e4feb694b0 | yareddada/CSC101 | /CH-06/Programming-Exercises/ex_6-3.py | 376 | 3.96875 | 4 | '''\
Rev: 1
Name: silentshadow
Description:
Reference: exercise 6.3
Page: 203 (PDF 223)
'''
def palindrome( n):
if ( n[ ::-1] ) == n :
print( "Found one!")
else:
print( "Sorry")
def main():
print( "Let's find us a Palindrome number!")
n = input( "Give a number: ")
pal... |
af634cb835cafe23a9f4b0fc908c0b64d5f7d197 | cmychina/Leetcode | /leetcode_剑指offer_65.矩阵中的路径.py | 912 | 3.765625 | 4 | # -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
M = len(matrix)
N = len(matrix[0])
d = [(0, 1), (0, -1), (1, 0), (-1, 0)]
self.visited = set()
def dfs(x, y, k):
if not (0 <= x < M and 0 <= y < N and matrix[x][y] == path[k] and ... |
d86cde7e61e0da90fd7bd945e844c7b49a773772 | Tanmay53/cohort_3 | /submissions/sm_026_rohit-kumar/week_14/day_3/evaluation/average_diff.py | 394 | 4 | 4 | num_list = [1,2,3,4,5,6]
def average_diff(arr):
even_sum = 0
odd_sum = 0
# sum of nums present at even index
for i in range(0, len(arr), 2):
even_sum = even_sum + arr[i]
# sum of nums present at odd index
for i in range(1, len(arr), 2):
odd_sum = odd_sum + arr[i]
ret... |
f9d2421622ee9395094068198a00bc86fb5f0bd1 | JeffersonKaioSouza/Exercicios-de-Python | /ex015.py | 217 | 3.609375 | 4 | dias = int(input('Digite a quantidade de dias: '))
km = float(input('Digite a quantida de km rodados: '))
cdias = dias * 60
ckm = km * 0.15
print('O valor a ser pago pelo aluguel é de R$:{:.2f}'.format(cdias + ckm)) |
60b8da3f24a2f2c1467986682e36994eb3218f33 | tathamitra/TathaPython | /tut12.py | 497 | 3.90625 | 4 | #for loops
#
# l1 = ["jack", "jill", "mark", "paul"]
#
# for name in l1:
# print(name)
# l1 = [["jack", 1], ["jill", 2], ["mark", 7], ["paul", 9]]
#
# for name, wife in l1:
# print(name, "number of wives", wife)
#
# d1 = dict(l1)
# for name in d1:
# print(name)
# for name, wives in d1.item... |
58eb5d25a58bb203ead30bf25e1cbddb6940840e | Smithmichaeltodd/Learning-Python | /Gregorian Epact.py | 359 | 3.65625 | 4 | #Tis program determines the vale of the epact
#By Michael Smith
import math
def main():
print('Gregorian epact calculator!')
print()
Y = eval(input('Please input a 4 digit year your would like to calculate for: '))
C = Y//100
epact = (8 + (C//4) - C + ((8*C + 13)//25) + 11*(Y%19))%30
... |
3e1c4963fa0f1a654975f3e41c4a489f81604f5e | ddiana/CellECT | /CellECT/seg_tool/seg_utils/union_find.py | 1,985 | 3.53125 | 4 | # Author: Diana Delibaltov
# Vision Research Lab, University of California Santa Barbara
# Imports
import pdb
"""
Implementation of union find.
This is used by the nuclei collection for merging segments.
"""
class UnionFind(object):
def __init__ (self, number_lements):
self.parents = range(number_lements)
sel... |
a0d2609ccac235d7813b02a7bae4998854cf69e1 | tuxlimr/sonu1 | /Beautifulsoup/Sports-firstpost.py | 636 | 3.53125 | 4 | from bs4 import BeautifulSoup as soup
from urllib.request import Request, urlopen
# req = Request('https://www.firstpost.com/firstcricket/', headers={'User-Agent': 'Mozilla/5.0'})
# webpage = urlopen(req).read()
# page_soup = soup(webpage, "html.parser")
# containers13 = page_soup.find("div", {"class": "first-story"})
... |
26953e85da92204fa396de840c4a76cc6b1a5cf7 | Makoto-Taguchi/kadai1 | /kadai1_4.py | 827 | 3.703125 | 4 | import csv
input_path = './csv_files/input_file.csv'
output_path = './csv_files/output_file.csv'
with open(input_path, 'r') as f :
reader = csv.reader(f)
for source in reader :
print(source)
# # 検索ソース
# source=["ねずこ","たんじろう","きょうじゅろう","ぎゆう","げんや","かなお","ぜんいつ"]
### 検索ツール
def search():
word =input("鬼滅の登場人... |
52995eba75dcc5c0564e0e5cfe585ba305d56d7c | poc7667/internal-training-python-course | /05-file_io/sort.py | 165 | 3.53125 | 4 | import pprint
people = [
["Apple", 500, 1000],
["Zebra", 5000,500],
["Carlos", 5, 3]
]
print sorted(people, key = lambda x : x[-1])
print sorted(people) |
edf61aab9e90a59b4b70b3eb24a16785b571f19e | bitromortac/plottoterminal | /plottoterminal/lib/utils.py | 364 | 3.734375 | 4 | PI = 3.14159265359
def linspace(start: float, end: float, steps: int = 100):
assert start < end
return [start + (end - start) * i / steps for i in range(steps + 1)]
def rint(f: float) -> int:
"""
Rounds to an int.
rint(-0.5) = 0
rint(0.5) = 0
rint(0.6) = 1
:param f: number
:retur... |
55982d0837bb9a8288fb9261c5ea7f00690f1327 | PROxZIMA/Python-Projects | /User_Packages/amult.py | 236 | 4.125 | 4 | def mult():
L=[]
b=1
num=int(input("Enter how many numbers you are multiplying : "))
for i in range(num):
n=float(input("Enter the numbers : "))
L.append(n)
b=b*n
print('Multiplication of the numbers is =',b) |
8c067bbb8ba826cb9fbde1fb58c737583f9f06e2 | AlexArango/PythonExercises | /ex6.py | 859 | 4.28125 | 4 | # Just trying things out
#print "%r print = 'does this work?' and again 'works?' "+'let us see'+' "no?"'
# Declaring variables in Python. It seems like there are not different types
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
... |
ac33a7a35c7e28a521d1f41838e9097687d887f3 | akcauser/Python | /PythonCharArrayMethods/index()&&rindex().py | 439 | 3.875 | 4 |
#index metodu bize 1. parametrede girdiğimiz değerin ilk hangi indexkste karşılaşıldığı bilgisini verir
#2. ve 3. parametreleri ise aralık belirtir
city = "alanya"
print(city.index("a")) # çok da iyi bir metod değildir , yerine aşağıdaki algoritma iş görüyor
counter = -1
for i in city:
counter += 1
if i =... |
210f281cb2c0dc5ea11841ad1b2ccfc028ae7dbd | jvano74/advent_of_code | /2015/day_05_test.py | 3,819 | 4.03125 | 4 | import re
def nice(word):
"""
--- Day 5: Doesn't He Have Intern-Elves For This? ---
Santa needs help figuring out which strings in his text file are
naughty or nice.
A nice string is one with all of the following properties:
It contains at least three vowels (aeiou only), like aei, xazegov,
... |
55dad0e3e2d982533beaddc6a6034b09737aa893 | celestialized/Machine-Learning | /Part 1 - Data Preprocessing/data preprocessing_missing_spliting_categorical_scaling_pythin.txt | 2,684 | 3.625 | 4 | #data preprocessing
"""
Spyder Editor
This is a temporary script file.
"""
import numpy
import matplotlib.pyplot
import pandas
dataset = pandas.read_csv('Data.csv')
x= dataset.iloc[:,:-1].values #.iloc[] is primarily integer position based selection
y= dataset.iloc[:,3].values
x= dataset.iloc[:,:-1].values
#take car... |
34ad0d747fbd3544130ffc39f6b01057937eadc0 | SneakBug8/Python-tasks | /num2.py | 277 | 3.65625 | 4 | x1=float(input())
y1=float(input())
x2=float(input())
y2=float(input())
x=float(input())
y=float(input())
res=""
if (y>y1) and (y>y2):
res=res+"N"
if (y<y1) and (y<y2):
res=res+"S"
if (x<x1) and (x<x2):
res=res+"W"
if (x>x1) and (x>x2):
res=res+"E"
print (res)
|
b89c831ce9f4a4e87f68b334f770b687e434a88d | yuzuponikemi/project_euler | /p32.py | 1,335 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 24 02:18:04 2018
@author: fiction
p32
We shall say that an n-digit number is pandigital if it makes use of all
the digits 1 to n exactly once; for example, the 5-digit number, 15234,
is 1 through 5 pandigital.
The product 7254 is unusual, as th... |
501eafb185dafd832d185e7d533a151ee217712f | 1949commander/training_apps | /testArray.py | 200 | 3.625 | 4 |
carMakes = ["Dodge", "Studebaker", "Packard", "Mercury", "Nash"]
for x in carMakes:
print(x)
carMakes.append("Nash")
y = carMakes.count("Nash")
print(y)
carMakes.sort()
print(carMakes)
|
50021fe072c5789e91ec0afc99913b536010b5fd | rowaishanna/Intro-Python-II | /src/player.py | 1,035 | 3.9375 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, current_room):
self.name = name
self.current_room = current_room
# day two code
self.inventory = []
def __str__(self):
items = []
for item... |
3e20cb941aa1fc3e9238cbc25ee267651c3c56d8 | kedar-shenoy9/PIP-1BM17CS041 | /Third-lab/2a_search.py | 147 | 3.765625 | 4 | def search(arr, n):
return n in arr
l = list(map(int, input("Enter the list ").split()))
n = int(input("Enter the number "))
print(search(l, n))
|
911762c29e544ff29dd1504772802d294eb3a8e7 | Ran-oops/python_notes2 | /9/认识爬虫-课件-v1/Py爬虫课件/1-09爬虫代码/spider_day6/2.bs4_demo.py | 2,316 | 3.8125 | 4 | from bs4 import BeautifulSoup
import re
html = """
<html><head><title><p>The Dormouse's <br> story</p></title></head>
<body>
<p class="title" name="dromouse" id="p1"><b class="title">The Dormouse's story</b></p>
<p class="story1">Once upon a time there were three little sisters; and their names were
<a href="http://ex... |
4a5fc30ac43c0f01ff80833787154dd2abf94c62 | haoxuez/python | /pythonxiangmu/study.py | 1,387 | 3.859375 | 4 | print('好友通讯录:')
a={'小明':(1,'广州'),'小红':('002','深圳'),'小王':('003','北京')}
print(a)
x="""""
请输入数字对好友通讯录进行增删改查操作,
请输入数字1进行好友添加,
输入数字2删除好友,
输入数字3修改好友,
输入数字4查询好友,
"""""
print(x)
while True:
b=int(input())
if b==1:
b1=input('请输入好友的姓名,电话,地址:(以逗号隔开)\n')
b2=tuple(b1.split(',',2))
a[b2[0]]=b2[1:3]
... |
1fa5d7b7f8616053be154a211554615630da7cab | sadhanabhandari/learn_python_hard_way | /weekend_assignments/ex4.py | 335 | 4.125 | 4 | #With a given list With a given list [12,24,35,24,88,120,155,88,120,155]
# write a program to print this list after removing all duplicate values with original order reserved.
given_list=[12,24,35,24,88,120,155,88,120,155]
new_list=[]
for i in given_list:
if i not in new_list:
new_list.append(i)
print ne... |
d8cb71cc11faa6e20f10b70063b4d56baca4ba03 | JobCollins/NanoDSA | /UnscrambleCS/Task1.py | 975 | 4.25 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
# def test(uniq):
# symmetric_diff = set... |
93e4b0a6c135f88b825aa9e689d0591ad8bf9969 | shreyasabharwal/Data-Structures-and-Algorithms | /LinkedList/2.5SumLists.py | 3,349 | 3.890625 | 4 | ''' 2.5 Sum Lists: You have two numbers represented by a linked list, where each node contains a single
digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a
function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
... |
adb32b7df8222a454606487870eac46753d13d4e | buptwxd2/leetcode | /Round_1/191. Number of 1 Bits/solution_2.py | 459 | 3.65625 | 4 | # naive solution
class Solution:
def hammingWeight(self, n: int) -> int:
num_bits = 0
mask = 1
for _ in range(32):
if (n & mask) != 0:
num_bits += 1
mask = mask << 1
return num_bits
"""
Results:
Runtime: 24 ms, faster than 92.07% of Python... |
115b82c08d69c9dba28635dad1d5de4563578b3d | viethien/misc | /random_x.py | 389 | 3.8125 | 4 | #!/usr/bin/python3
# Will keep print lines of x where each line contains random characters of x from 5 to 19 inclusive until a line is printed with 16 or more characters
from random import randint
def main():
rand_x()
def rand_x():
stringSize = 0
while (stringSize < 16):
stringSize = randint(5... |
c049d8e6f20dcd6e18f3da8b8aedd2cd8ef42790 | atnsf/Problems | /excercise_005/excercise_005.py | 213 | 4.03125 | 4 | # excercise_005
arr1 = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
arr3 = []
for index in arr1:
if index in arr2 and index not in arr1:
arr3.append(inndex)
print(arr3) |
c8b4dda3508e2ef3427578205e366c8a41fca139 | chetanpachpohe/Bookyourmovie_Project | /main.py | 651 | 3.796875 | 4 | from book import Movie
global row
global seats
row=int(input("Enter the number of rows: "))
seats=int(input("Enter the number of seats in each row: "))
while True:
print("*** Welcome to Bookyourmovies ***")
catlog=input("1. show seats\n2. Buy tickets\n3. view statistics\n4. show booked tickets customer... |
3dc1026bd3c5dd6da05dad74d8531fa0c2cadc0e | ojhaanshu87/LeetCode | /249_group_string_shift.py | 865 | 4.21875 | 4 | '''
Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
"abc" -> "bcd" -> ... -> "xyz"
Given a list of non-empty strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequ... |
4975171e2af8e32688bb9d170855b37e9af1df2d | NikBomb/2021-strategy-parameters | /exchange.py | 1,864 | 4.0625 | 4 | """
Simple module that simulates an exchange.
"""
class ExchangeConnectionError(Exception):
"""Custom error that is raised when an exchange is not connected."""
class Exchange:
"""Basic exchange simulator."""
def __init__(self) -> None:
self.connected = False
def connect(self) -> None:
... |
d9da9874a3bde340dd32f1798cb31fcf7c976741 | RowiSinghPXL/IT-Essentials | /6_strings/opgave3.py | 229 | 3.59375 | 4 | zin_1 = input("Zin1: ")
zin_2 = input("Zin2: ")
if len(zin_1) < len(zin_2):
kleinste = len(zin_1)
else:
kleinste = len(zin_2)
for i in range(kleinste):
if zin_2[i] == zin_1[i]:
print(zin_1[i], "op index", i) |
8a59c5107818e9b0408a051ef02ff07b4bf64c74 | awesometime/learn-git | /Data Structure and Algorithm/Data Structure/Tree/binary_heap.py | 4,884 | 3.5625 | 4 | # from pythonds.trees.binheap import BinHeap
#
# bh = BinHeap()
# bh.insert(5)
# bh.insert(7)
# bh.insert(3)
# bh.insert(11)
#
# print(bh.delMin())
#
# print(bh.delMin())
#
# print(bh.delMin())
#
# print(bh.delMin())
"""
堆顺序属性:
1.树的根是树中的最小(大)项 根节点比子节点小(大)
2.最大(最小)堆是一棵每一个节点的键值都大于(小于)其子节点键值的树,左右子节点大小没有顺序
3.父两子节点索引分别为 ... |
b5f9967782f0b81d836ae9de920fe5576c83ade9 | er-aditi/Learning-Python | /List Working Programs/List_Indenting Unnecessarily.py | 208 | 3.5 | 4 | magicians = ['david', 'aleen', 'tom']
for magician in magicians:
print("I Like to see magic: " + magician)
print("I am very Grateful to see: " + magician + "\n")
print("It is Best: " + magician) |
6fe61d45cdd4bd00bdb8b7a6dd574a322e19f70e | kedpak/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/100-weight_average.py | 271 | 3.6875 | 4 | #!/usr/bin/python3
def weight_average(my_list=[]):
if my_list is None or my_list == []:
return (0)
score = 0
weight = 0
for i, j in my_list:
score = score + i * j
weight = weight + j
average = score/weight
return (average)
|
090d943c4ddf3d3ae6b76ce165f6d2cb8d9e72cf | atshaya-anand/LeetCode-programs | /Easy/pathSum.py | 960 | 3.859375 | 4 | # https://leetcode.com/problems/path-sum/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
... |
6ced1797ded915215bc4082233910b3bbe9f9668 | t-yuhao/py | /控制流/if.py | 271 | 3.96875 | 4 | # 猜数字
number = 37
guess = int(input('Enter an integer : '))
if number == guess:
print('congratulations,you gussed it.')
elif guess < number :
print('No ,it\'s a little higher than that.')
else:
print ('No, it is alittle lower than that')
print('done') |
4c2527ebaf713ab8804cc314e06596a37693d927 | StanislavBubnov/Python | /Lesson7/Hometask_7.1.py | 825 | 3.625 | 4 | class Matrix:
def __init__(self, my_list = []):
self.my_list = my_list
def __str__(self):
str_1 = ' '.join(str(e) for e in self.my_list[0])
str_2 = ' '.join(str(e) for e in self.my_list[1])
str_3 = ' '.join(str(e) for e in self.my_list[2])
return '|{}|\n|{}|\n|{}|'.format... |
62e6790d4fbb7536c1d18899e2d3a7afcae254ce | yichuanma95/leetcode-solns | /python3/twoSum.py | 1,815 | 3.9375 | 4 | '''
Problem 1. Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such
that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the
same element twice.
You can return the answer in any order.
Example 1:
Input: nums... |
94a2319431d5a1836af583129c04d896ed455287 | CompetitiveCode/hackerrank-python | /Practice/Numpy/Concatenate.py | 983 | 4 | 4 | #Answer to Concatenate
import numpy
n,m,p=input().split()
a,b=[],[]
for i in range(int(n)):
a.append(list(map(int,input().split())))
for i in range(int(m)):
b.append(list(map(int,input().split())))
a,b=numpy.array(a),numpy.array(b)
print(numpy.concatenate((a,b),axis=0))
"""
Concatenate
Two or more arrays can... |
4935489703e8f8b6de9d08a700a6dca89993defb | kdragonkorea/TIL | /Bigdata_analysis_course_20201228/2_Python/Python_exam/day3(20210106)/whileTest1.py | 465 | 3.71875 | 4 | student = 1
while student <= 5:
print(student, "번 학생의 성적을 처리한다.")
student += 1
print("수행종료")
# 2021-01-09 복습
# 아래와 같이 출력된다.
# '1번 학생의 성적을 처리한다.'
# '2번 학생의 성적을 처리한다.'
# ...
# '5번 학생의 성적을 처리한다.' 를 출력한다.
# '수행종료'
for student in range(1, 6) :
print(student, "번 학생의 성적을 처리한다.")
print("수행종료") |
b4a2e3192b4732f68658d91688bd6ce449689efa | trimcao/intro-python-rice-university | /week-5/memory.py | 3,485 | 3.765625 | 4 |
"""
Name: Tri Minh Cao
Email: trimcao@gmail.com
Date: October 2015
implementation of card game - Memory
"""
import simplegui
import random
no_turn = 0
first_open = -1 # index of the card player opens first
second_open = -1 # index of the card player opens second
# initialize a deck of cards, with each card appearing... |
7633b1754d757f0f5c99617f7c1ad25464b3310b | mdaiyub/Codeforces | /1389A.py | 140 | 3.515625 | 4 | for _ in range(int(input())):
a,b = map(int,input().split())
if a*2 <= b:
print(a,a*2)
else:
print("-1 -1") |
74ab68d4b27c11034b666a4b0b5aee7db0c89822 | sfox1975/Udacity-I2P-Stage3 | /entertainment_center.py | 2,971 | 3.5625 | 4 | # Udacity Introdution to Programming Nanodegree
# Stage 3 Project: Movies Website
# By Stephen Fox (with heavy assistance from Udacity!)
# Movie storylines are courtesy of www.imdb.com
# import media tells the program to use the contents of media.py
import media
import fresh_tomatoes
# Media.Movie() implies the cl... |
181118291b209768b69767cfd1293294768ae3f8 | Man0j-kumar/python | /tup-dict.py | 107 | 4.125 | 4 | #Python program to convert a tuple to a dictionary
tup=((2,'w'),(3,'r'))
print(dict((x,y)for y,x in tup)) |
178e85c3f6c4652042c765568ff27a480417b307 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/ec6269b2b00444a2b493f8a9d756b49a.py | 812 | 3.8125 | 4 | RESPONSETO = {
'question': 'Sure.',
'shouting': 'Whoa, chill out!',
'nothing': 'Fine. Be that way!',
'other': 'Whatever.'
}
def main():
what_I_say = input('Say something to Bob:')
while not (what_I_say.lower() == 'exit'):
if (what_I_say.lower().startswith('exit') or
what_I_say.lower().startswit... |
0083d2fa8e4fb448a2cc825b8cb3925850f6ce68 | Elena-Zhao/Leetcode-Practice | /LeetCode/Best_Time_to_Buy_and_Sell_Stock.py | 1,297 | 4 | 4 | # Say you have an array for which the ith element is the price of a given stock on day i.
#
# If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock),
# design an algorithm to find the maximum profit.
class Solution(object):
def maxProfit(self, prices):
... |
af3c4cea15a354c0014d421632e099fd2b212afa | gokul-raghuraman/algorithms | /rotate-left.py | 191 | 3.828125 | 4 | def rotateLeft(string, k):
n = len(string)
k = k % n
string = string[k:] + string[:k]
return string
if __name__ == "__main__":
k = 4
string = "ABCDEFGHIJ"
print(rotateLeft(string, k)) |
93614a460d42a63c94f857372b10a50954e83ad7 | JannaKim/PS | /GRAPH/review/2056_작업_1125.py | 702 | 3.546875 | 4 | # 현재 작업을 위해 필요한 정보가 이전에 모두 주어지므로,
# 바로 연결돼있는 노드의 최대 시간만 가져와서 자신과 더하면 된다
N = int(input())
edge = [[]for _ in range(N+1)]
time = [0]*(N+1)
for i in range(1,N+1):
*L,=map(int, input().split())
time[i]=L[0]
for v2 in L[2:]:
edge[i].append(v2)
total = time[:]
total[1]=time[1]
for i in range(2,N+1):
... |
e98d1afa9218836cde50c13761aacaf26356b2da | Aasthaengg/IBMdataset | /Python_codes/p02862/s481582144.py | 1,032 | 3.59375 | 4 | import sys
from math import factorial
input = sys.stdin.readline
def log(*args):
print(*args, file=sys.stderr)
def main():
x, y = map(int, input().rstrip().split())
# 全部 i + 1, j + 2が最初だったとする
# a + 2b = x, 2a + b = y
# =>
# a = x - 2b
# b = y - 2a
# =>
# b = y - 2x + 4b
# 3b ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.