blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
376e6a065a1f94c7aad27775d2af2a80ad51e4da | MissBolin/CSE-Period3 | /procedures and functions.py | 1,844 | 4.4375 | 4 | # Procedures are abstractions. We can create a blueprint of steps
# for common actions that we can reference and use as often
# as we wish.
# Step 1: Create the blueprint / define the procedure
def speak():
print("Hello user!")
print("From your PC")
# Step 2: Use the blueprint / call the procedure
speak()
spe... |
d173d15d9f9783b689b447187a3b88cec904e437 | muondu/python-practise | /For loops/fruits_shop.py | 446 | 3.9375 | 4 |
fruits = {
"Apple" : 30,
"Banana" : 10,
"Pineaple" : 70
}
print(fruits)
input1 = input("How many times do you want to print it: ")
integer = int(input1)
constructor = list()
for b in range(integer):
input2 = fruits[input("Enter what you want: ")]
print("The price of the fruit is " + str(input2))... |
73b776ef58006f5fe7d266b21a7db248a615ad6d | Yuya-Furusawa/Self-Study | /choice.py | 237 | 3.578125 | 4 | import numpy as np
def sampling(coin, n):
"""
coin : array-like
Amount coin
n : scalar(int)
The number of lucky guys
"""
coin = np.asarray(coin)
m = len(coin)
prob = coin / sum(coin)
return np.random.choice(m, n, p=prob) |
fceb07c22ff3f423d86a57a957b18681c4bd3fd3 | BenjiKCF/Codewars | /day9.py | 347 | 3.75 | 4 | def remove_smallest(numbers):
l = [(index, value) for index, value in enumerate(numbers)]
n = sorted(numbers)
for i in range(len(numbers)):
if n[0] == l[i][1]:
numbers.pop(i)
break
return numbers
def remove_smallest(numbers):
if numbers:
numbers.remove(min(nu... |
826a613564bbd9d36a9d2ad5b03ebf9d8f6633e3 | MudretsovaSV/Python | /Циклич.ПросмотрСписка.py | 70 | 3.53125 | 4 | letters=["a","b","c","d","e"]
for letter in letters:
print letter
|
9c9c012afdc73ff9cb58836b46544e18f747b84a | mdmmsrhs/Learning_Python | /point.py | 1,091 | 4.25 | 4 | #!/bin/Python
"""define a class called Point and initialise it"""
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def printPoint(p):
print'(' + str(p.x) + ',' + str(p.y) + ')'
def samePoint(p1,p2):
return (p1.x == p2.x) and (p1.y == p2.y)
def distanceSquared(p):
retur... |
552fc7c286d46bf908d61eaa3dfa12cd5308ac67 | greenloper/Graph | /10-3 Kruskal.py | 688 | 3.8125 | 4 | def find_parent(parent, x):
if parent[x]!=x:
parent[x]=find_parent(parent, parent[x])
return parent[x]
def union_parent(parent, a, b):
a=find_parent(parent, a)
b=find_parent(parent, b)
if a<b:
parent[b]=a
else:
parent[a]=b
v, e=map(int, input().split())
... |
e8826c4345b73bc95b964f932460a9f1eaadd282 | georgeribeiro/dojouva | /convertion/convertion.py | 384 | 3.828125 | 4 |
def convert(numero, sistema1, sistema2):
if sistema1 == "numerico":
sobra = int(numero) % 5
inteiro = int(numero) / 5
return "/" * sobra + "\\" * inteiro
else:
i = 0
for barra in numero:
if barra == "/":
i += 1
else:
... |
90e4f5e2d35076b1f772053cb6d74061783dd43e | nhl4000/project-euler | /python2/11-20/015.py | 263 | 3.875 | 4 | def factorial(n):
sum = 1
for i in xrange(1,n+1):
sum *= i
return sum
def binomial_coefficient(n, k):
num = factorial(n)
dem = factorial(k) * factorial(n-k)
return num / dem
n = 20
k = 20
print (binomial_coefficient(n+k,k))
|
0b3904de4bf06c5e252bc075b2a54b17de918479 | sarik/Algo_DS | /powerSet.py | 1,104 | 3.640625 | 4 | def convertArrToString(arr):
st=""
for i in arr:
st = st + str(i)
return st
def powerSet(arr):
setall =set()
print(setall)
helper(setall,[],arr,0)
return setall
def helper(setall,prev,arr,index):
if len(prev) == 3 or index >2:
setall.add(conver... |
ce2b89dd15e27074e7de5d6ce175c8896b441070 | Sal2912/Python-Projects | /first_last_name_reverse.py | 172 | 4.3125 | 4 | first_name = input("Enter your First Name: ")
last_name = input("Enter your Last Name: ")
full_name = first_name + last_name
print(f'Reversed name is: {full_name[: :-1]}')
|
f1ee2409839ae1af398d5223b984c6fa5efae98b | chakid/NLPexp | /exp2/exp2_1.py | 454 | 4.125 | 4 | #字符串输出
str1 = "这是一个变量";
print("变量str1的值是:"+str1);
print("变量str1的地址是:%d" %(id(str1)));
str2 = str1;
print("变量str2的值是:"+str2);
print("变量str2的地址是:%d" %(id(str2)));
str1 = "这是另一个变量";
print("变量str1的值是:"+str1);
print("变量str1的地址是:%d" %(id(str1)));
print("变量str2的值是:"+str2);
print("变量str2的地址是:%d" %(id(str2)));
|
4f23672de689428004a125bcd8eedbb2d60669fb | gerrycfchang/leetcode-python | /tree/construct_BST_from_pre_inorder.py | 2,025 | 3.953125 | 4 | # 105. Construct Binary Tree from Preorder and Inorder Traversal
#
# Given preorder and inorder traversal of a tree, construct the binary tree.
#
# Note:
# You may assume that duplicates do not exist in the tree.
#
# For example, given
#
# preorder = [3,9,20,15,7]
# inorder = [9,3,15,20,7]
# Return the following bi... |
ccb38823f3781e6c058f59f0e0d90ec68f0ccad0 | quantumsnowball/AppleDaily20200907 | /sentiment.py | 2,567 | 3.703125 | 4 | from textblob import TextBlob
def tweet_sentiment(text, verbose=False):
"""
The sentiment function of textblob returns two properties, polarity, and subjectivity.
Polarity is float which lies in the range of [-1,1] where 1 means positive statement
and -1 means a negative statement.
Sub... |
7bd1bdcae31fce4687c48c2048ae36b40c288176 | Nitroto/SoftUni_Python_Open_Course | /Lecture_1/Problem-4.py | 294 | 4.3125 | 4 | import turtle
while True:
angle = input("Enter an angle: ")
length = input("Enter a length: ")
direction = input("Enter direction left/right: ")
if direction == 'left':
turtle.left(int(angle))
else:
turtle.right(int(angle))
turtle.forward(int(length))
|
6554ed99e35d54c348a2c6c7c52ba798298e62f4 | sudershan1903/Cricket-Scorecard-using-MongoDB | /DB Insertion/cleaning.py | 627 | 3.6875 | 4 | def headings(string):
diction = eval(string)
keys = list(diction.keys())
string = ""
for i in keys:
string = string + str(i).capitalize() + '\t\t\t'
return string
def process(string):
diction = eval(string)
#keys = list(diction.keys())
values = list(diction.values())
... |
6408ef20d0e8becb4f53e3934c24aadb5e3b10af | hjain5164/Linear-Search | /python-linear-search/python-linear-search.py | 382 | 4.25 | 4 | num_array = list() #Enter elements
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
n = raw_input("num :")
num_array.append(int(n))
element_to_find = raw_input("Element to find :")
for i in num_array: #searching through the list
if i==elemen... |
efd5b35c881d14427f89ee49f8fe4b0353f733ea | Nagalakshmi301994/Python-Essentials-Day-9-Assignment | /Day9 B7 Assignment.py | 1,700 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Write a python Function for finding is a given number prime or not and do Unit Testing on it using PyLint and Unittest Library.
# In[2]:
get_ipython().system(' pip install pylint')
# In[3]:
get_ipython().run_cell_magic('writefile', 'prime.py', "'''\nIt is a prime numbe... |
11ff925f1e812ce444af7666b2a61540902d85f7 | sashakrasnov/datacamp | /27-visualizing-time-series-data-in-python/2-summary-statistics-and-diagnostics/07-density-plots.py | 1,385 | 4.15625 | 4 | '''
Density plots
In practice, histograms can be a substandard method for assessing the distribution of your data because they can be strongly affected by the number of bins that have been specified. Instead, kernel density plots represent a more effective way to view the distribution of your data. An example of how t... |
08e9c46a6df3483f5aafae545761e8ea60af5443 | Vasiliy1982/repo24122020 | /praktika_urok5_2.py | 254 | 4.03125 | 4 | # практическое задание 2
число = int(input("Введите число:"))
число_крат7 = число % 7
if число_крат7 > 0:
print(число, "не кратно 7")
print(число, "кратно 7")
|
b418f1704484b48d5b7dc9bcfefa3e6d3643b523 | NagiLam/MIT-6.00.1x_2018 | /Week 1/PS1_Problem2.py | 506 | 3.96875 | 4 |
""" Probem Set 1 - Problem 2
Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
Number of times bob occurs is: 2"""
# s = 'azcbobobegghakl'
count = 0
n = 0
m = 3
temp = 0... |
3b6fb8e9ab34b5d114f0a817de8eef59b8cbd9ce | dipanjan44/Python-Projects | /ProgramPractise/numberofwaystoclimb.py | 676 | 4 | 4 |
def count_ways_recursive(n):
if n < 0:
return 0
if n==0:
return 1
else :
return count_ways_recursive(n-1) + count_ways_recursive(n-3) +count_ways_recursive(n-2)
def no_of_ways(n):
count = [0 for i in range(n + 1)]
count[0] = 1
count[1] = 1
count[2] = 2
for... |
a735458d0282ae51d62aed88b0cf0a7b0a61387c | kanyaandrea/Exercises | /Phyton_exercises/exercise_4.py | 519 | 3.609375 | 4 | import random
import math
a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]#list of number from 10 to 100 by 10
t = 0#t is zero now
if a[0] % 20:
t += a[0]
print(t)
if a[1] % 20:
t += a[1]
print(t)
if a[2] % 20:
t += a[2]
print(t)
if a[3] % 20:
t += a[3]
print(t)
if a[4] % 20:
t += a[4]
... |
944ba36690d9cb9dffa31ffb237486adf4f5b826 | CiesliixW/Cwiczenia_Repo | /Simple__calculator.py | 2,148 | 4.1875 | 4 |
def is_number(string):
try:
float(string)
return float(string)
except:
return None
def is_valid_operator(operator):
if operator == "+" or "-" or "*" or "/":
return True
else:
return False
def ask_for_a_number(force_valid_input):
while force_valid_inpu... |
6874444881d5cff2ae430bb0874336f1a1f16347 | sarn3792/Python_tutorial | /polimorfismo.py | 660 | 3.59375 | 4 | class Usuario:
def __new__(cls):
print("Este método es el primero que se ejecuta")
return super().__new__(cls)
def __init__(self):
print("Este método es el segundo que se ejecuta")
self.__password = "Es secreto"
def __str__(self): #ToString() del objeto
return "Esto se imprime cuando intento mostrar el o... |
d0bcf3fdfc6c0814207a188d1820247c7dc709bb | fidakhattak/PreciousServer | /grovepi/test.py | 513 | 3.734375 | 4 | import collections
class test:
def __init__(self):
window_size = 10
self.averaging_window = collections.deque(maxlen = window_size)
def test_queue(self):
string = "Hello Pakistan, How is the weather today"
l = list(string)
i = 0
while i < len(l):
... |
844a7b99c689759e5bb9ef4db213f4c4d6f5a5fb | jachin/AdventOfCodeSolutions | /2017/01_day/sum-half-way-round.py | 470 | 3.5 | 4 | #! /usr/bin/env python3
import fileinput
for line in fileinput.input():
line = line.strip()
if len(line) < 1:
continue
last_index = len(line)
half_length = int(last_index / 2)
print(last_index, half_length)
sum = 0
for i, n in enumerate(line):
half_index = (i + half_l... |
0be27f96e57c8014f679a02c32362274bcdf777c | JohnRal/fogstream_courses | /Practice_1/task_2.py | 858 | 3.828125 | 4 | '''
2.Длина Московской кольцевой автомобильной дороги —109 километров.
Стартуем с нулевого километра МКАД и едем со скоростью V километров в час.
На какой отметке остановимся через T часов? Программа получает на вход значение V и T.
Если V>0, то движемся в положительном направлении по МКАД, если же значение V<0, то в о... |
a58b3f37fdd02f5dbe5ed04659be43ca91004d0a | borisnorm/codeChallenge | /practiceSet/g4g/DP/game.py | 1,650 | 3.859375 | 4 | #Optimal strategy for a game
'''
Problem statement: Consider a row of n coins of values v1 . . . vn, where n is even. We play a game against an opponent by alternating turns. In each turn, a player selects either the first or last coin from the row, removes it from the row permanently, and receives the value of the co... |
4919f1c66d34e2a89882ea25b28402044d65fea2 | Aasthaengg/IBMdataset | /Python_codes/p02406/s004425808.py | 256 | 3.828125 | 4 | def inc3(i):
if i - (i // 10)*10 == 3:
return(True)
elif i//10==0:
return(False)
else:
return(inc3(i//10))
n = int(input())
for i in range(1,n+1):
if i%3==0 or inc3(i):
print(" " + str(i),end="")
print() |
591a90923a91076e2e07d64531c56baf881e9143 | larrywhy/learning | /Python/verify_num.py | 162 | 3.8125 | 4 | user_input = input("enter number:")
print(user_input)
try:
isNum = int(user_input)
print("yes, is number")
except ValueError:
print("No, is string.")
|
a5d0d812f48114e2150c223d482ede9208fa6efc | huisonice668/is218_project_02 | /Statistics/Mode.py | 753 | 3.5 | 4 | def mode(data):
temp_list = []
count = []
if len(data) == 0:
raise ValueError('Can not be an empty list')
# remove duplicate then store the elements into temp_list
for num in data:
if num not in temp_list:
temp_list.append(num)
# count the appearance of elements in ... |
b6703b3fb1b8f8e2830318635c3e82ad6b8dce23 | alexander-travov/algo | /InterviewBit/LinkedLists/KReverse.py | 1,289 | 3.890625 | 4 | # -*- coding: utf8 -*-
"""
K reverse linked list
=====================
Given a singly linked list and an integer K, reverses the nodes of the
list K at a time and returns modified linked list.
NOTE : The length of the list is divisible by K
Example :
Given linked list 1 -> 2 -> 3 -> 4 -> 5 -> 6 and K=2,
You shoul... |
586ec39746d54ea0f15f9da172742902f9c9d24c | brewersey/dsp | /python/q6_strings.py | 6,059 | 4.3125 | 4 | # Based on materials copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
def donuts(count):
"""
Given an int count of a number of donuts, return a string of the
form 'Number of donuts: <count>', where <count> is the number
passed in. However, if the count is 10 or more, then use... |
03d1cd338caf7339b72ad88cf9ff3e34adc6a438 | DavLivesey/algoritms_01 | /exercise_12.py | 781 | 3.6875 | 4 | '''
Васе очень понравилась задача про анаграммы и он придумал к ней модификацию.
Есть 2 строки s и t, состоящие только из строчных букв.
Строка t получена перемешиванием букв строки s и добавлением 1 буквы
в случайную позицию. Нужно найти добавленную букву.
'''
import collections
text_1 = collections.Counter(input())... |
c5342742af6e1229f22f4bd32db0269788067cb9 | betty29/code-1 | /recipes/Python/580639_Python2_keywordonly_argument_emulatidecorator/recipe-580639.py | 11,343 | 3.546875 | 4 | #!/usr/bin/env python
import inspect
import sys
# The @decorator syntax is available since python2.4 and we support even this old version. Unfortunately functools
# has been introduced only in python2.5 so we have to emulate functools.update_wrapper() under python2.4.
try:
from functools import update_wrapper
exce... |
61a18768a0df1d7cf52fc57b646a538bc1d8facd | kotaro0522/python | /procon20171205/kaiden.py | 265 | 3.65625 | 4 | import math
from decimal import *
numbers = [int(i) for i in input().split()]
diff = numbers[1] - numbers[2]
if numbers[0] <= numbers[1]:
print("1")
elif diff <= 0:
print("-1")
else:
print(math.ceil(Decimal(numbers[0] - numbers[1]) / diff) * 2 + 1)
|
cb7f77da43f54145314a5b85a5360846c982d4b9 | PranavSonar/Python-Scripting-And-Automation | /PowerCode/Pattern Print/STAR PATTERN/Done/Pattern Start Print Basic.py | 2,836 | 3.71875 | 4 | #%%
# code to print box/O
# *****
# * *
# * *
# * *
# * *
# * *
# *****
def boxPrint(symbol, width, hight):
print(symbol*width)
for i in range(hight-2):
print(symbol+(' '*(width-2))+symbol)
print(symbol*width)
boxPrint('*', 5, 7)
# code to prin I
# *****
# *
# *
# *
# *
# *****
... |
03152bef4c989f5472a6fa27244598d88b066d9d | Flavio-Varejao/Exercicios | /Python/EstruturaDeRepeticao/Q22.py | 649 | 4.125 | 4 | #!/usr/bin/env python3
#Altere o programa de cálculo dos números primos, informando, caso o número não seja primo, por quais número ele é divisível.
contador=0
divisores=[]
numero=int(input("Digite o número: "))
if numero!=-1 and numero!=0 and numero!=1:
for divisor in range(1,numero+1):
if numero%divisor... |
f55540fa11bf169fd2111036c569d407d4df0575 | jbelo-pro/NumericMatrixProcessor | /Numeric Matrix Processor/task/processor/processor.py | 8,596 | 3.6875 | 4 | from collections import deque
def sum_matrices():
rows_1, col_1 = input('Enter size of first matrix: ').split()
print('Enter first matrix:')
matrix_1 = []
for r in range(int(rows_1)):
row = []
for n in input().split():
t = int(n) if n.isdigit() else float(n)
row.... |
eb752ee9e8012e1014f0574fe0a6759256c7dcb6 | mickyscandal/word_count | /revamp.py | 4,024 | 3.75 | 4 | #!/usr/bin/python
# imports
import argparse
import time
from collections import Counter
class TextData(object):
def __init__(self, nfile):
self.nfile = nfile
def basic_count(self):
"""basic count of all words and unique words"""
with open(self.nfile) as f:
data = f.read()... |
1889331059fe2e0d78320aaa8160feb550cec294 | Uthaeus/practice_python | /guessing_game.py | 628 | 4.1875 | 4 | import time
import random
print("---------This is the guessing game----------")
time.sleep(1)
game = 'y'
while game == 'y':
turns = 0
for x in range(1):
num = random.randint(1, 10)
guess = int(input("Pick a number between 1 and 10 \n"))
while guess != num:
if guess < num:
print("Your guess i... |
bfe377861812e9be856d7912903105b53810126b | AdamZhouSE/pythonHomework | /Code/CodeRecords/2306/60696/261462.py | 1,486 | 3.546875 | 4 | lch = []
rch = []
res_pre_order = []
res_in_order = []
res_post_order = []
def print_pre_order(root):
if lch[root] == 0 and rch[root] == 0:
res_pre_order.append(root)
return
res_pre_order.append(root)
if lch[root]!=0:
print_pre_order(lch[root])
if rch[root]!=0:
print_pr... |
1181f3ddf197be347868826a2f274072d30b247b | edt-yxz-zzd/python3_src | /nn_ns/math_nn/Josephus_problem.py | 8,949 | 3.875 | 4 |
##Josephus problem
##From Wikipedia, the free encyclopedia
##In computer science and mathematics,
##the Josephus Problem (or Josephus permutation)
##is a theoretical problem related to a certain counting-out game.
##
##There are people standing in a circle waiting to be executed.
##The counting out begins at some po... |
f08b78b7c2e108bb366eeccefb9f6d1b7bc31a9f | yunfanLu/LeetCode | /leetcode/src/p026RemoveDuplicatesfromSortedArray/solution.py | 454 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/8/31 13:51
# @Author : yunfan
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums is None or len(nums) == 0:
return 0
l, r = 0, 1
while r < len(nums... |
ad73e0369c00a547c883e7b5b1c8c5c950a3635e | vanely/Python-Challenges | /KeepHydrated/liters.py | 175 | 3.5625 | 4 | import math;
def litres(time):
return math.floor(time / 2)
#for greater simplicity we could use python floor division
def liters(t):
return t // 2
print(litres(5)) |
ab8232f1cdf261107c85b4b5946196f3d1fca5b5 | lemishAn/prak_sem5 | /task2/program1.py | 519 | 3.890625 | 4 | '''
task 2, program 1
'''
if __name__ == '__main__':
LINE = input()
i, j, number_substrings = 1, 0, 1
S = LINE[0: i]
while number_substrings*S != LINE:
j = LINE.find(S, i)
if j == - 1:
break
S = LINE[0: j]
number_substrings = LINE.count(S)
if i == j:
... |
03c2b48c7245b6f57c655c61395cc9be48704395 | kidexp/91leetcode | /two_ponters/287FindtheDuplicateNumber.py | 670 | 3.765625 | 4 | from typing import List
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
slow = fast = 0
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = 0
while slow != fast:
slow = ... |
eb04a1adb1c67acb4477445ce4fdec33371dde4e | AMS347/PRACTICA | /Obtener promedios (diccionario).py | 1,954 | 3.734375 | 4 | def obtenerInfoestudiantes():
op=''
dic={}
while (op!='no'):
print('ingrese los datos del estudiante')
mat=int(input('Matriculas:'))
dic2={}
dic2['nombres']=input('nombres:')
dic2['apellidos']=input('apellidos:')
dic2['carrera']=input('carrera')
op2=''... |
65d5efa13cbf7f1f99eb09eb38d2bb929e4ff9ef | Autassist/pi_code | /websocket_server.py | 1,171 | 3.625 | 4 | #!/usr/bin/env python
import bluetooth
host = ""
port = 1 # Raspberry Pi uses port 1 for Bluetooth Communication
# Creaitng Socket Bluetooth RFCOMM communication
server = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
print('Bluetooth Socket Created')
try:
server.bind((host, port))
print("Bluetooth Binding Com... |
96b9409462f49e6aa93e7d82e7a652a0b48282e7 | aanantt/Python-DataStructure | /Tree/Binary Tree/BinaryTree_Rightmost_Element.py | 680 | 3.90625 | 4 | class Node:
def __init__(self, element):
self.element = element
self.right_node = None
self.left_node = None
class BinaryTree:
def __init__(self, root_Node):
self.root= root_Node
def rightMost(self,node):#Right Most Element in a BST
if node.right_node:
sel... |
5dad0b3c1b8fcd106d96a91d80991383e2a1413f | ikeshou/Kyoupuro_library_python | /src/mypkg/basic_algorithms/sliding_window_min.py | 3,243 | 3.8125 | 4 | """
スライド最小値
<algorithm>
長さ n の数列 L に対し、長さ k の連続部分数列を考える。L[i:i+k] (0<=i<=n-k) に対してこの連続部分数列の最小値を求めたい。
ナイーブに比較演算を行うと O(n * k) 、RMQ をさばくセグ木だと O(nlgn) だが、スライド最小値のアルゴリズムでは O(n) で計算可能。
"""
from collections import deque
from typing import List, Sequence, Union
Num = Union[int, float]
def sliding_minimum_query(L: Sequenc... |
b15547f6c896f19e2293ca2287ecc08cc18362f7 | 302Blue/CISC106 | /PYTHON/Final & Midterm/Midterm/Worksheet+-+while+loops.py | 2,314 | 4.28125 | 4 | # Make sure you understand why each loop creates the output that it does.
# Convert the following while loops to for loops.
# For example, exercise 12b would be:
product = 1
n = 2
for k in range(0, 9, 4):
product = product * n
print(product)
print("Exercise 1a")
x = 0
while x < 20:
x = x + 1
print(x)
pri... |
69cafd4bffccd6d13345df7d98de9f5479bf7459 | franky-codes/Py4E | /Ex3.2.py | 417 | 4.125 | 4 | hours = input('How many hours did you work?: ')
rate = input('What is your hourly rate?: ')
try:
fhours = float(hours)
frate = float(rate)
except:
print('Please enter a numeric')
quit()
if fhours > 40.0:
overtime_rate = frate * 1.5
pay = (fhours - 40) * overtime_rate + (frate * 40)
print(... |
3c6881f88d5c24a4dfdde1f2a31a865d9e7b3c1a | LeilaHuang/python_projects | /data_related_program/data_file_4/data_run_4.py | 2,149 | 3.53125 | 4 | # 题目描述:统计1-3月气温在-10℃~10℃的天数统计直方图
import os
import numpy as np
import matplotlib.pyplot as plt
data_path = './'
data_filename = 'temp2.csv'
month_temp_list = []
def get_data():
data_file = os.path.join(data_path, data_filename)
temp_data = np.loadtxt(data_file, delimiter=',',dtype='int',skiprows=1)
return... |
62815a3b55a40a6284c4e002ac849b3bf017d3b2 | KIMBOSEO/problems | /4522_palind.py | 439 | 3.578125 | 4 | for t in range(1, int(input())+1):
case = str(input())
if len(case) ==1:
ans =0
for i in range(len(case)//2):
if case[i] == case[-i-1]:
ans =0
else:
if '?' == case[i] or case[-i-1] == '?':
ans =0
else:
ans =1
... |
b5b8ebd1fab633ba09c6aaa555c6267c3dec5429 | e-valente/ISTA-421-521-ML-UofA | /hw/hw2/ista421ML-Homework2-release/code/scripts/exer5.old.py | 2,568 | 3.578125 | 4 | ## cv_demo.py
# Port of cv_demo.m
# From A First Course in Machine Learning, Chapter 1.
# Simon Rogers, 31/10/11 [simon.rogers@glasgow.ac.uk]
# Demonstration of cross-validation for model selection
# Translated to python by Ernesto Brau, 7 Sept 2012
# NOTE: In its released form, this script will NOT run
# You wi... |
a10d1535eb9bda35e4c3a31b7b97545e12047bfc | Apeoud/LeetCode | /25_ReverseKGroup.py | 1,870 | 3.828125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
return self.val
def __repr__(self):
return str(self.val)
class Solution(object):
def reverseKGroup(self, head, k):
"""
... |
fd5e864bacfb4f25a6151e8f2e5a1b43fc667fd1 | elpiniki/pythonista | /test3_1.py | 358 | 4.09375 | 4 | d1 = [1, 2, 3, 4, 5, 6]
def invert(param):
"""This function inverts the contents of the array"""
i = 1
l = len(param)
while i<l-3:
head = [param[0]]
tail = param[1:l]
param = tail + head
i = i + 1
if i == l:
break
return param
if __name__ == "__main__":
invert(d1)
print... |
030fa37760918ccee282bcae3336ae3f2644b8bb | TroutMaskReplica1/Grading | /grading.py | 457 | 3.984375 | 4 | num = int(input('enter grade '))
if num < 60:
print('\nF')
elif num < 65:
print('\nD-')
elif num < 68:
print('\nD')
elif num < 70:
print('\nD+')
elif num < 75:
print('\nC-')
elif num < 78:
print('\nC')
elif num < 80:
print('\nC+')
elif num < 85:
print('\nB-')
elif num < 88:
print('\... |
15b1f6ef7b0a25dd8299f5ae42fe949ebdb8c8dd | arturh85/projecteuler | /python/src/problem004.py | 2,735 | 4.09375 | 4 | '''
Problem 4
16 November 2001
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers.
----------------------------------------------------------
Created ... |
3cef378239c8f79e881d4f265e61802610fb0dfd | yamunaAsokan/guvizen | /loop/factorial.py | 207 | 3.984375 | 4 | n=int(input('enter the input'))
a=1
if(n<0):
print('not valid value')
elif(n==0):
print('factorial of 0 is 1')
if(n>0):
for i in range(1,n+1):
a=a*i
print('factorial of',n,'is',a)
|
9a9606fea9e9dfc86321e537f54b81611e01f007 | Michaelhuazhang/code_offer | /leetCode/longestPalindromeSubstring.py | 861 | 3.65625 | 4 | # -*- encoding:utf-8 -*-
# 查找字符串最长回文
# 依次遍历每一个字符,找到最长的回文
# 回文有奇回文和偶回文,abcba是奇回文,abccba是偶回文
# 回文都是中心对称,找到对称点后,同时向前后寻找回文的最长串即可
# 奇回文和偶回文可以归为同一种情况,即abcba以c为对称点,abccba以cc为对称点,
# 但为了代码可读性,可以分开讨论
class Solution:
def __find_palindrome(self, s, j, k):
while j >= 0 and k < len(s) and s[j] == s[k]:
j -= 1
k += 1
if s... |
c79e6f70a899e51f30fadb9e71d2a4d5fa8efbdb | wideglide/aoc | /2022/d04/solve.py | 994 | 3.515625 | 4 | #!/usr/bin/env python3
import re
import sys
RE_C = re.compile(r"(\d+)\-(\d+),(\d+)\-(\d+)")
input_file = 'input' if len(sys.argv) == 1 else sys.argv[1]
# part 1
data = list(open(input_file).read().strip().split('\n'))
overlap = 0
for pair in data:
p1, p2 = pair.split(',')
a, b = list(map(int, p1.split('-'))... |
5a558baadcd4946f246a874fc8fdf7868265e3f1 | chyjuls/Computing-in-Python-IV-Objects-Algorithms-GTx-CS1301xIV-Exercises | /Extra_Course_Practice_Problems/practice_problem_25.py | 1,440 | 4.40625 | 4 | #Write a function called delete_from_list. delete_from_list
#should have two parameters: a list of strings and a list of
#integers.
#
#The list of integers represents the indices of the items to
#delete from the list of strings. Delete the items from the
#list of strings, and return the resulting list.
#
#For example:
... |
e2fc9ec61ced0ea7d7db3b012ec7cde5125977ec | sfeng77/myleetcode | /countAndSay.py | 748 | 4.0625 | 4 | """
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represen... |
d1d560ba1d96b1d0b521a620d7a6acc57c0dd902 | Avenger98/Python-Programms | /List.py | 371 | 3.921875 | 4 | a = []
for i in range(4):
num = int(input("Enter the number: "))
a.append(num)
print()
print("This is list created: ",a)
max = a[0]
min = a[0]
for numbers in a:
if numbers > max:
max = numbers
if numbers < min:
min = numbers
print()
print('This is the maximum number: ... |
a05bae88c9748e5dc5acc75fad6a29a8bece0a59 | marikell/eve-platform | /containers/eve-api/api/utils/validate_fields.py | 455 | 3.546875 | 4 | def check_empty_string(string: str, field: str):
if not string:
raise Exception('Not allowed empty strings for {}.'.format(field))
return True
def check_if_key_exists(key: str, obj: dict):
if key not in obj:
raise Exception('Not allowed empty object for {}.'.format(key))
return True
de... |
6bfb15d12b92f78d776e92284038d659e00df9e2 | lsjroberts/codeclub | /python/lesson03/decode.py | 614 | 4.125 | 4 | # List of letters in alphabet
alphabet = "abcdefghijklmnopqrstuvwxyz"
# Secret letter to decode
letter = "r"
# Secret used to decode the letter
secret = 17
# Find the position of the secret letter, this will
# be a number between 0 and 25
secret_position = alphabet.find(letter)
# Count backward from this position
l... |
0197c2aed5d2f4cfe404824963a73edec5b050a4 | Juma01/Juma_DZ_5 | /juma_dz_3.py | 856 | 3.734375 | 4 | # 3. Создать текстовый файл (не программно),
# построчно записать фамилии сотрудников и величину их окладов.
# Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников.
# Выполнить подсчет средней величины дохода сотрудников.
my_f = open("salary.txt", "r")
content = my_f.read()
print(f... |
eb77549f297ff8a260f6092ca07492623b1187a2 | timprod13/python_lesson3 | /part2.py | 569 | 3.84375 | 4 | def my_info(name, surname, date, city, email, tel_num):
print("Привет,", name, "с фамилией", surname, "рождённый", date, "из города", city, "с e-mail", email,
"и номером телефона", tel_num)
my_info(name=input("Введите имя "), surname=input("Введите фамилию "), date=input("Введите дату рождения "),
... |
dd5bb715de5f40386a3c56cd1d3450d543721803 | ganeshiitr/CPP-Programs | /MyHashMap.py | 969 | 3.859375 | 4 |
print "Hello World!\n"
class MyHashMap:
def __init__(self):
self.size=10
self.map=[None]*self.size
def insertInToMap(self,key,val):
hash = 0
for char in str(key):
hash += ord(char)
keyHash = hash%self.size
keyvalList = [key... |
b7cb6814afbd2e8e968cc04c327f819467c1254e | faurehu/word_extractor | /reader.py | 1,383 | 3.53125 | 4 | import re
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
def is_time_stamp(l):
if l[:2].isnumeric() and l[2] == ':':
return True
return False
def has_letters(line):
if re.search('[a-zA-Z]', line):
return True
return False
def has_no_text(line):
l = line.stri... |
622740825644a7204844889d3cb41b0a19dbf75b | CS-NF/Intro-Python-II | /src/room.py | 1,480 | 3.75 | 4 | # Implement a class to hold room information. This should have name and
# description attributes.
class Room:
def __init__(self, room_name, description, items=[]):
self.room_name = room_name
self.description = description
self.n_to = None
self.s_to = None
self.e_to = None
... |
94e281628de3cddc19bc84292b1b0974f093ece3 | l0he1g/w2vExp | /common/util.py | 533 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from nltk.util import ngrams
def tokenize(text):
"""
:return list of tokens
"""
regex = r"[\u4e00-\ufaff]|[0-9_a-zA-Z\-]+\'*[a-z]*"
matches = re.findall(regex, text, re.UNICODE)
return matches
def ngram_tokenize(text, N):
"""
:return list of to... |
cbafa61177772e117390087eaba4af6132d52800 | aongenae/leetcode | /src/balanced_binary_tree.py | 1,186 | 4 | 4 | #!/usr/bin/env python3
################################################################################
#
# Filename: balanced_binary_tree.py
#
# Author: Arnaud Ongenae
#
# Leetcode.com: problem #110
#
# Problem description:
# https://leetcode.com/problems/balanced-binary-tree/
#
#... |
f2b9f094467e7e49232e168c61afc36f5166a125 | enfiskutensykkel/euler | /1-25/15/pascal.py | 324 | 3.75 | 4 | #!/usr/bin/env python
def pascal(n):
triangle = [[1], [1,1]]
for i in xrange(2,n):
row = []
for j in xrange(1, len(triangle[i-1])):
row.append(triangle[i-1][j-1] + triangle[i-1][j])
triangle.append([1] + row + [1])
return triangle
def grid(dim):
tri = pascal(2*dim+1)
return tri[2*dim][dim]
print grid(... |
8322b1d73f0e8919faafa2063a7ed34ff93666c5 | Rhysoshea/daily_coding_challenges | /daily_coding_problems/daily2.py | 683 | 4.28125 | 4 | '''
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], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected ... |
032cfcf9799622185d60f992a411a7f4548b750f | gabriellaec/desoft-analise-exercicios | /backup/user_054/ch25_2020_09_30_11_42_04_791479.py | 223 | 3.59375 | 4 | import math
v = int(input('qual a velocidade? '))
a = int(input('qual o angulo? '))
g = 9.8
d = v^2 * math.sin(2*a)/g
if d < 100:
print('Muito perto')
elif d > 100:
print ('Muito longe')
else:
print('Acertou!') |
99ee51281e4a9fc0eea496fb7b1fd3d1f5458f09 | CuongNgMan/alg | /sort/merge.py | 527 | 3.765625 | 4 | #!/usr/bin/env python3.6
import sys
sys.path.append('../')
def merge(L:list,R:list):
result = []
i = j = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
result.append(L[i])
i+=1
else:
result.append(R[j])
j+=1
result+=L[i:]
result+=... |
44fe0b3875c00cfbdc7e3f61667d6e7f47dde7af | oOZeqOo/Projects | /PersonalAssistant/common/weather.py | 1,175 | 3.640625 | 4 | import python_weather
import asyncio
def say_weather(say):
loop = asyncio.get_event_loop()
result = loop.run_until_complete(get_weather())
say(result)
async def get_weather():
try:
# declare the client. format defaults to metric system (celcius, km/h, etc.)
client = python_weather.Clie... |
7a01e7bd8664d8fd9c69dec6d30cadb796a5c6ae | goginenigvk/PythonSep_2019 | /Datatypes/tupledatatype.py | 509 | 3.765625 | 4 | person=('john',28,200.56)
print(person)
print(type(person))
names='Sachin','Dravid','Ganguly'
print(type(names))
print('-1 output',names[-1])
print(names[2])
print(names[1]) #Dravid
names2=('Yuvaraj','Dhoni',20,24,names,(50,29,30))
print(names2)
print(names2[4][1])
print(names2[0][2])
numbers=2,6,8,5,9,6,2,['a','b... |
873080634c04430329a9e847fb82ab0ba37da79c | C-CEM-TC1028-414-2113/02-decisiones-A01753493-tec | /assignments/09CmaKmMtCm/tests/input_data.py | 980 | 3.546875 | 4 | # List of tuples
# Each tuple contains a test:
# - the first element are the inputs,
# - the second are the output,
# - and the third is the message in case the test fails
# To test another case, add another tuple
input_values = [
# Test case 1
(
["100"],
["Introduce los cm:", "... |
2676434f0ad308402d1c90bb6e45c0355ec3bc69 | matthew-cheney/kattis-solutions | /solutions/weakvertices.py | 748 | 3.609375 | 4 | def getNeighbors(targ, matrix, excl=None):
if excl is None:
excl = set()
return {my_x for my_x in range(len(matrix[targ])) if matrix[targ][my_x] == '1' and my_x not in excl}
while True:
N = int(input())
if N == -1:
break
matr = []
for n in range(N):
matr.appen... |
91cbc6e5e0bcc5030d1c5a389d92f433489dd45d | mattnorris/tate | /src/find_scanned_docs.py | 2,715 | 3.75 | 4 | #! /usr/local/bin/python
# Title: find_scanned_docs.py
#
# Description: Traverses a source directory. If PDFs are found, copy them
# to the target directory. If no PDF is found, copy all files to
# the target directory.
#
# (This was the convention I used when
#... |
2f7dd02cdf9351e3d69002c51f1ac9acff0666b9 | sudhasr/Two-Pointers-2 | /mergesortedarrays.py | 727 | 3.8125 | 4 | #Leetcode - wrong answer
#Explanation - The idea is to have two pointers at end of each array to compare the values and put
#them in appropriate positions
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-... |
4771950a56172f32c004940927f520f9d08fbee9 | smoitra87/PythonChallenge | /challenge/p10.py | 1,061 | 3.578125 | 4 | #! /usr/bin/env python
import string
import urllib2 , bz2, re
import pdb
import Image, ImageDraw
""" solution to problem 10 in pythonchallenge http://www.pythonchallenge.com/pc/return/bull.html
The trick is to generate something known as Morris numbers
"""
def morris(last) :
if not last : return None
cu... |
b4e000b6e2fc02f4cbfcefe07ad8ebc3ae9c446c | sesliu/ULFTP | /ulftp/ulftp.py | 2,266 | 3.515625 | 4 | from ftplib import FTP
from Prompt import Prompt
import sys, getopt
def main(argv):
parametro = ' usage: ulftp.py -u <user> -p <password> -s <server> -r <port>[optional]'
diretorioAtual = ''
usuario = ''
senha = ''
servidor =''
porta = 21
ftpDados = FTP()
... |
a606e574eb7deba8ad0f9fcdd1f5b049dacee46a | shoroogAlghamdi/test | /Unit4/unit4-demo14.py | 87 | 3.703125 | 4 | # Slide 50
numl = 4
num2 = 3
if not(num2==3): print("True!")
else:
print("False!")
|
4ab712d12634fd657260d3c5083604ac0cade610 | nykh2010/python_note | /02pythonBase/day08/res/exercise/dict_season.py | 720 | 4.125 | 4 | # 练习:
# 1. 写程序,实现以下要求:
# 1) 将如下数据形成字典 seasons
# 键 值
# 1 '春季有1,2,3月'
# 2 '夏季有4,5,6月'
# 3 '秋季有7,8,9月'
# 4 '冬季有10,11,12月'
# 2) 让用户输入一个整数代表这个季度,打印这个季度的信息
# 如果用户输入的信息不存在,则提示用户您查找的信息不存在
seasons = {1: '春季有1,2,3月',
2: '夏季有4,5,6月',
... |
3cc5f1bbf8ccb5584b4196979f9ac24fd5138250 | DanielF1976/SolarCar | /Gui.py | 683 | 3.578125 | 4 | import tkinter as tk
from tkinter import *
from tkinter import ttk
ws = Tk()
Label(ws, text="ISU Solar Car").grid(row=0, column=2)
Label(ws, text="MPH").grid(row=1, column=0)
Label(ws, text="00000").grid(row=2, column=0)
Label(ws, text="RPM").grid(row=1, column=1)
Label(ws, text="00000").grid(row=2, column=1)
Label(ws... |
238c39995bd135c69fdea8caf9497898c8723c3f | hemangbehl/Data-Structures-Algorithms_practice | /session4/GroupMultipleOccurrenceInOrderArray.py | 334 | 3.6875 | 4 | def group(arr):
if len(arr) <= 2: return arr
dict1 = {}
for ele in arr:
dict1[ele] = dict1.get(ele, 0) + 1
ans = []
for key in dict1.keys():
for i in range(0, dict1[key] ):
ans.append(key)
return ans
arr = [4, 6, 9, 2, 3, 4, 9, 6, 10, 4]
print(arr)
print(g... |
99eacfab2d534b8d2176a80585abbf629ccacc6b | Hower/NCSS-2013 | /Week 1/Autobiographical_Numbers.py | 395 | 3.890625 | 4 | def addDigits():
total = 0
for char in num:
total += int(char)
return total
def check():
for pos, char in enumerate(num):
if num.count(str(pos)) != int(char):
return True
num = input("Number: ")
no = "is not autobiographical"
if len(num) != addDigits():
print(num, no)
eli... |
68b8dfe75df38b285f2dc53233246144a62c9cdf | FarzanaEva/Data-Structure-and-Algorithm-Practice | /InterviewBit Problems/Array/anti_diagonal.py | 662 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 6 02:58:36 2021
@author: Farzana Eva
"""
"""
PROBLEM STATEMENT:
Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details.
Example:
Input:
1 2 3
4 5 6
7 8 9
Return the following :
[
[1],
[2, 4],
[3, 5, 7],
[6, 8]... |
855cfeefe041f2f0f6b74216cca0668d305e0865 | ITT-21SS-UR/assignment6-modellinginteraction-sc2 | /calculator/config_parser.py | 1,646 | 3.59375 | 4 | import json
import os
import sys
from enum import Enum
"""
Responsible for parsing the json file for the config.
If the given config is invalid the system exists and prints out error messages.
"""
# Author: Claudia
# Reviewer: Sarah
class ConfigKeys(Enum):
PARTICIPANT_ID = "participant_id"
TASK = "task"
... |
29c96a0b21786f71005b2c79e10368f755d0f98f | YaserMarey/AI_for_Medicine_deeplearning.ai | /AI_for_Medical_Diagnosis/W_3/utf-8''AI4M_C1_W3_lecture_ex_03.py | 14,435 | 3.953125 | 4 |
# coding: utf-8
# # AI4M Course 1 week 3 lecture notebook
# ## U-Net model
# In this week's assignment, you'll be using a network architecture called "U-Net". The name of this network architecture comes from it's U-like shape when shown in a diagram like this (image from [U-net entry on wikipedia](https://en.wikiped... |
f964d8c26e7370c501a764e606bcebc6a6984dcf | SergioTA01229274/Python-Code | /Secondpartial/Game.py | 751 | 3.96875 | 4 | import random
def game(n1, n2):
lim1 = n1
lim2 = n2
answer = bool()
while answer:
number = random.randint(lim1, lim2)
print("The number I'm thinking is: ", number)
feedback = input("The number you're thinking is: ")
feedback = feedback.lower()
... |
a25a53f60fb3fa10e5cf7c261a193fe358c85a87 | dzampar/curso_python | /Exercicios/ex059.py | 1,509 | 4.125 | 4 | print("Insira dois valores abaixo")
valor1 = float(input("Primeiro Valor:"))
valor2 = float(input("Segundo Valor:"))
opcao = 0
while opcao != 5:
print(' [ 1 ]Somar\n'
' [ 2 ]Multiplicar\n'
' [ 3 ]Maior\n'
' [ 4 ]Novos numeros\n'
' [ 5 ]Sair')
opcao = int(input(">>>>>... |
cde08ebd614b81d65993f51a8a1618e6d2e9b300 | sonukrishna/Anandh_python | /chapter_2/q21_wrap.py | 200 | 3.609375 | 4 | ''' wrap the file as per the given length '''
def wrap(filename,n):
for i in open(filename):
if len(i)>n :
print i[0:n]
print i[n:len(i)]
else:
print i
wrap('she.txt',30)
|
e2a7694dfc492769306b9ce9227037edeb19e100 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_203/252.py | 1,998 | 3.875 | 4 | #!/usr/bin/python
def fill(cake):
r = len(cake)
if r == 0:
return cake
c = len(cake[0])
if c == 0:
return cake
chars = []
for i in range(0,r):
count = c
for j in range(0,c):
if cake[i][j] == '?':
count -= 1
chars.append(count)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.