blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
05708062fd83c6c3c742e1cf5d3beb80b9f5ab56 | Zjx01/IBI1_2018-19 | /Practical4/power of 2.py | 817 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 16 17:08:11 2019
@author: Jessi
"""
n=eval(input("input a integer:",))
n0=n
sign=0 #to store whether the number input is an odd or even
answer=str(n) + "="
l1= []
if n%2 != 0:
n = n-1
#to change the odd number into even, and the minused 1 will be added by sign a the ... |
61aa806beb82a52d92319bb1fb2c5e03dce09eb4 | mx2013713828/leetcodeTest | /Middle.py | 539 | 3.65625 | 4 |
class Node(object):
def __init__(self,elem= -1,lchild=None,rchild = None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild
class middle(object):
def __init__(self):
self.root = Node()
def front_digui(self,root):
if root == None:
return
... |
09063b6b8c585c741335003592b115be76edbd6b | pdturney/open-ended-immigration-games | /immigration-rules/rule_generator.py | 6,705 | 3.703125 | 4 | #
# Rule Generator
#
# Peter Turney, October 30, 2019
#
# Read in a list of totalistic life-like rules of the
# form "B37/S236" and generate Golly rule files for
# playing the Immmigration Game with the given rules.
# The Immigration Game requires odd numbers for birth
# (for example, "B37" but not "B47"), in... |
21f10cbab8ebb5c699b63212e5f3174a81ee6555 | marmotmarsh/euler-project | /python/completed/euler0019.py | 395 | 4.1875 | 4 | ###
#
# Created by Holden on 12/18/2015
#
# SOLVED on 12/18/2015
#
# Problem 19 - Counting Sundays
#
###
import datetime
def counting_sundays(start, end):
count = 0
for year in range(start, end + 1):
for month in range(1, 13):
date = datetime.date(year, month, 1)
if date.w... |
f322ab867fe80a7ba1e948d64adf712e20dc62db | krishnajaV/luminarPythonpgm- | /oops/ExceptionHandling/addition.py | 244 | 3.796875 | 4 |
try:
a = int(input("enter the number"))
b = int(input("enter the number"))
sum= a+b
print(sum)
except:
print("please enter the integer")
finally:
print("finally")
#in this case try and except and finally work at a time. |
11c00fcb70018a8f5b03c4c6c61af0a4037d454f | michaelhuo/pcp | /653_2.py | 1,134 | 3.828125 | 4 | # 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 findTarget(self, root: TreeNode, k: int) -> bool:
def recursive(root: TreeNode, nums:List[int]) ... |
9a60d1950251c4c15010a1651c921d6e387cc317 | michelleferns/python | /school.py | 290 | 3.859375 | 4 | my_name=input("enter your name>")
my_age=input("enter your age>")
my_class=input("enter your class>")
my_mark=input("enter your marks>")
print("My name is ",my_name,"fernandes")
print("My age is ",my_age,"years")
print("My class is ",my_class,"A")
print("My marks is ",my_mark,"%")
|
37fff59e31bd213786d385be5bed493d7c9fa366 | Alexander-Stanley/Programming-II | /Prac 4/quick_pick_lotto.py | 774 | 4.09375 | 4 | import random
NUMBERS_PER_LINE = 6
MIN_NUM = 1
MAX_NUM = 45
def main():
num_of_picks = int(input("How many Quick Picks(TM):"))
while num_of_picks <0 :
print("Come on now, give in to the capitalist game to keep lining our pockets, forget about feeding your kids.")
num_of_picks = int(input("Now... |
779e4d74c545936c268b0f92b7a41fc8297ad34b | shahid31202/expert-system | /project9.py | 9,069 | 3.515625 | 4 | print('--------------------------------------------------------')
print('--------WELCOME TO HOMEOPATHIC EXPERT SYSTEM---------- |')
print('enter which category do you want diagnosis |')
print('1.children |')
print('2.digestive ... |
1602836a9a261b23e89369798e7d462c6c672949 | kajal1301/python | /ifElse.py | 391 | 4 | 4 | #if Else and Elif in python
var= 4
var1= 44
var2= int(input()) #takes user input
if var2>var1 :
print("Greater than",var1)
elif var2== var1:
print("Equal")
else:
print("Lesser")
#to check if the element is present in a list or not
list1= [5,6,7]
if 5 in list1:
print("Yes it is in the Li... |
db3eef5c222c469ea296bd13d77dabd63d4d9050 | magikitty/GetPythonBookPractice | /25.Lists/AddingItems25.4.py | 731 | 4.4375 | 4 | """
This is Lesson 25: Working with lists
Get Programming: Learn to Code With Python
There are three ways to add items to lists: append, insert, and extend
"""
# Append adds one item to the end of the list (last index position)
grocery_list = ["boinky beans", "milk"]
grocery_list.append("bananas")
print(grocery_list)
... |
df0db37b7b9eb3d02b3b3de5dbd92c01b1509569 | Yozi47/Data-Structure-and-Algorithms-Class | /Final Exam/Question no 4.py | 668 | 3.546875 | 4 | '''
Let us consider the base case as H = 0.
Here a binary tree has height 0 which has single node.
so we get, 1=2^(0+1) -1
Therefore, the base case is satisfied as of the induction hypothesis.
Using Induction
Suppose the max modes in a binary tree of height h is
2**(h+1) -1 where h = 1, 2, .... , k
Assuming,... |
00e2b99fedecde6ebc45b719e626eaa4d3c98100 | jeancharlles/orientacao-objeto | /modificadores_de_acesso/classe_BaseDeDados.py | 1,381 | 3.640625 | 4 |
class BaseDeDados:
def __init__(self):
self._dados = {}
def inserir_cliente(self, id, nome):
if 'clientes' in self._dados:
self._dados['clientes'].update({id: nome})
else:
self._dados['clientes'] = {id: nome}
def lista_clientes(self):
for id, nome i... |
9b8a4ee54b0c3c29224594f3ea16239c2a22e6af | asoonyii/python-challenge | /PyPoll/main.py | 2,090 | 3.90625 | 4 | #Onyinyechi Asoluka
#Python homework2- PyPoll
#8th September 2018
import os
import csv
#Collect data
csvpath= os.path.join("election_data.csv")
# Set initial counters, candidates, and winners
total_votes = 0
unique_candidate_list = []
candidate_vote = {}
count_winner= 0
# Read the csv and account for header
with open... |
e6643ba272fe8514fdb32368e9cdd2d2fad53a78 | yejinee/Algorithm | /Solve Algorithm/1523_startriangle1.py | 1,341 | 3.671875 | 4 | """
삼각형의 높이 n과 종류 m을 입력받은 후 다음과 같은 삼각형 형태로 출력하는 프로그램을 작성.
INPUT
삼각형의 크기 n(n의 범위는 100 이하의 자연수)과 종류 m(m은 1부터 3사이의 자연수)을 입력받는다.
OUTPUT
위에서 언급한 3가지 종류를 입력에서 들어온 높이 n과 종류 m에 맞춰서 출력한다.
입력된 데이터가 주어진 범위를 벗어나면 "INPUT ERROR!"을 출력한다.
EXAMPLE
type1) type2) type3) ... |
8873d6570cba92896418f8cef3fa1a8ebf39ac9f | zz-zhang/some_leetcode_question | /Mock Interview/6/Critical Connections in a Network.py | 3,450 | 3.859375 | 4 | '''
There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network.
A critical connection is a connection... |
bbc2190d5f7c22df9112331fb0bfb0ed9ddd3344 | ShaneRich5/fti-programming-training | /solutions/labs/lab2.1/indexing.py | 303 | 3.828125 | 4 | a = 'New York'
b = 'Grand Rapids'
c = 'San Francisco'
d = 'Houston'
e = 'Atlanta'
f = 'Boston'
#print the word 'Chicago' by only concatenating indexes from the variables above
result = c[c.find('c')].upper() + d[0].lower() + b[b.find('i')] + c[c.find('c')] + e[-1] + b[0].lower() + f[1]
print(result) |
9e8a000a85c65879900155aae6870a5385d5e218 | dlara10/DanielLara_hw13 | /DL_MontyHall.py | 1,274 | 3.84375 | 4 |
# coding: utf-8
# In[1]:
import numpy as num
import random
# In[6]:
#Funcion que definira lo que hay dentro de las puertas
def sort_doors():
a = ['goat', 'goat', 'car']
#Se usa la funcion random.shuffle para desordenar la lista
return random.shuffle(a)
print (sort_doors())
# In[10]:
#Funcion p... |
9ce17714f2dbdfd1e2f4209b2e267bd18ce16252 | swiggins83/codeeval | /prime.py | 576 | 3.765625 | 4 | import sys
def primes(pathname):
dontuse = []
for line in open(pathname,'r').readlines():
n = int(line.split("\n")[0])
for i in range(1,n):
if i in dontuse:
print 'dont'
else:
if isprime(i, dontuse):
print i
def isp... |
2f210d2c95c9691de97826edc6deae7092877758 | danilodelucio/Exercicios_Curso_em_Video | /ex058.py | 606 | 3.84375 | 4 | from random import randint
print(('-' * 10) + ' JOGO DE ADIVINHAÇÃO ' + ('-' * 10))
n = int(randint(0, 5))
palpites = 0
user = int(input('Qual número que estou pensando? '))
done = False
while not done:
user = int(input('Que pena, você errou sonso!\nTente outra vez: '))
palpites += 1
if user == n:
... |
f41d9c423ead3ab6fd4fda15e8479fde85b78648 | saulo-lir/processamento-de-imagens-com-python-e-opencv | /processamento-de-imagens/01-introducao.py | 1,082 | 3.5625 | 4 | import cv2
'''
- Uma imagem colorida é formada por 3 canais de cores: Red, Green, Blue (RGB)
- Cada canal possui de 0 a 255 valores
- Ex.: Uma imagem que possui os canais: [255, 0, 0], terá a cor vermelha,
pois 255 na primeira posição equivale a cor máxima do vermelho, enquanto que
0 nas outras posições indica o valo... |
a1ef6e8c35ea2f9d1856de592b698f5e79228e15 | curiousguy13/project_euler | /pe14.py | 644 | 3.515625 | 4 |
def collatz(x):
'''brute force method '''
l=[]
while x!=1:
l.append(x)
if x%2==0:
x=x/2
else:
x=3*x+1
l.append(x)
return l
#print collatz(7)
l={1:1}
def collatz2(x):
'''dp method'''
count=0
if x in l :
return count+int(l[x])
... |
d09eb268c07099a82139981151793f539ea81272 | nemishzalavadiya/fake-news-predictor-NLP-Scikit-learn | /DataPreprocessing_with_countvectorizer.py | 869 | 3.734375 | 4 | # Import the necessary modules
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
# Print the head of df
print(df.head())
# Create a series to store the labels: y
y = df.label
# Create training and test sets
X_train, X_test, y_train, y_test = t... |
b18923b3488d1c1f9838949e4a66cfe6f5e63672 | toberge/python-exercises | /exams/actual/tee.py | 1,602 | 3.609375 | 4 | #!/usr/bin/env python3
import sys # for args and stdin
import argparse
def print_usage():
print('Usage: tee [-a] [FILE]\n-a: Append to file\nIf -a is set FILE must be present')
def read_and_output(outfile=None):
"""Read from stdin and write to stdout + file if any"""
for line in sys.stdin:
# Using... |
074660b121de73f1b2450bc2eb34849d49e798c8 | sherryxiata/zcyNowcoder | /lucky.py | 3,609 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/18 11:23
# @Author : wenlei
# 队列和栈(collections包中的deque双向队列,性能最好)
import collections
deque = collections.deque() # 创建双向队列/栈
deque.append(x) # 插入元素到队尾(队列)
deque.appendleft(x) # 插入元素到队头(栈)
# deque.pop() # 弹出队尾元素
deque.popleft() # 从队头弹出元素(√)
deque[0]... |
1de49b4cdfe20e30d5f223e3a0e355d56003a158 | tkqlzz/baekjoon | /1197.py | 1,079 | 3.609375 | 4 | parent = dict()
rank = dict()
def make_set(v):
parent[v] = v
rank[v] = 0
def find(v):
if parent[v] != v:
parent[v] = find(parent[v])
return parent[v]
def union(v1, v2):
root1 = find(v1)
root2 = find(v2)
if root1 != root2:
if rank[root1] > rank[root2]:
parent... |
6777724ebd2e33d497df8b5ed4ebb2bd488f9b5c | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_37/153.py | 922 | 3.546875 | 4 | #!/usr/bin/env python
import sys
import pdb
def base10toN(num, n):
s = ''
while 1:
remainder = num % n
s = str(remainder) + s
num = num / n
if num == 0:
break
return s
def happytest(num, base, numlist=[]):
if num == 1:
return True
else:
i... |
6363867f69aa003b838c0c64e726ef00abb06a69 | abdul8117/igcse-cs | /Programming Challenges/N4-Q10.py | 378 | 3.890625 | 4 | par3 = int(input("How many par 3 holes are there?\n"))
par4 = int(input("How many par 4 holes are there?\n"))
par5 = int(input("How many par 5 holes are there?\n"))
par3 = par3 * 3
par4 = par4 * 4
par5 = par5 * 5
difficulty = int(input("What is the difficulty adjustment for the course?\n"))
print(f"The Standard Scra... |
6ce561986eb820cb01e4a4b6708387233c18f5df | AndrewFendrich/Mandelbrot | /gradient4.py | 2,313 | 3.6875 | 4 | #def gradient_list((R1,G1,B1),(R2,G2,B2),steps):
#import sys,os
def gradient_list(Color1,Color2,steps):
gradientList = []
if Color2[0] > Color1[0]:
rinterval = (Color2[0]-Color1[0])/steps*6
else:
rinterval = (Color1[0]-Color2[0])/steps*6
if Color2[1] > Color1[1]:
gin... |
88e8668381f49943898eb7f2ca10056479ed3d0d | ChikusMOC/Exercicios-Capitulo-5 | /cap5_ex2.py | 138 | 4.09375 | 4 | """
Exercicio 2
"""
numero = float(input("Digite um numero:"))
if numero >= 0:
print(numero**0.5)
else:
print('numero invalido') |
21a9bfcb8a6c41e72bfea1d538fd2cf3360f9651 | sarahvestal/ifsc-1202 | /Unit 2/02.10 First Digit After Decimal.py | 294 | 4.21875 | 4 | #Prompt for a positive real number
#Print the first digit to the right of the decimal point.
#Enter Number: 1.79
#Tenths Value: 7
number = float(input("Enter a positive real number: "))
onedigitright = int(number % 1 * 10)
print ("First digit to right of decimal: {}".format (onedigitright,1)) |
5613367aed64de5744756afec88e8f010125a21c | dsli208/CSE-307-Programming | /simplecalc/SimpleCalc/calcparser.py | 1,667 | 3.6875 | 4 | # -----------------------------------------------------------------------------
# calcparser.py
#
# A simple calculator with variables.
# The example from http://www.dabeaz.com/ply/example.html
# broken down into separate lexer, parser, and main (top-level) files
#
# This is the parser
#
# ----------------------------... |
c818a88b124ee3ec277d628aca09819c3a7be742 | BryantHall/Enigma | /analysis.py | 2,310 | 3.625 | 4 | #Attempt to decrpyt the cipher using frequency based probability
import csv
#List of character frequency
alphabetTable = [' ','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
conversionTable = [' ','e','t','a','o','n','r','i','s','h','d','l','f','c','m','u','g'... |
a1c3160d5d04457d0ec97610f5680403c3d8ee80 | MichelleZ/leetcode | /algorithms/python/binaryTreePaths/binaryTreePaths.py | 873 | 4.0625 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/binary-tree-paths/
# Author: Miao Zhang
# Date: 2021-01-29
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# ... |
91bf845015a139150522d63df93a2d3aae3f05e0 | Matheus654/ifpi_ads_2020 | /Q13_F2b_crime.py | 749 | 3.875 | 4 | def main():
a = input("Telefonou para a vítima?")
b = input("Esteve no local do crime?")
c = input("Mora perto da vítima?")
d = input("Devia para a vítima?")
e = input("Já trabalhou com a vítima?")
verifica_crime(a, b, c, d, e)
def verifica_crime(a, b, c, d, e):
x = 0
... |
ff94cc873510e1e7de440adcdbe16507ce9b51fe | sethi-bhumika/RISC-V-Simulator | /Phase1/src/MachineCodeParser.py | 2,001 | 3.828125 | 4 | # module to parse instructions in machine code and store them in PC_INST
import sys
PC_INST={} # dictionary with key as PC, value as instruction
# function to parse the instructions
# comments start with #
# comment feature is just for ease to paste code from venus
def parser(FileName):
instructions=open(FileName... |
118e671fa96bc010cb1dcef83a6faf7b74eaba02 | ariscon/DataCamp_Files | /22-introduction-to-time-series-analysis-in-python/03-autoregressive-ar-models/02-compare-the-acf-for-serval-ar-time-series.py | 1,411 | 3.53125 | 4 | '''
Compare the ACF for Several AR Time Series
The autocorrelation function decays exponentially for an AR time series at a rate of the AR parameter. For example, if the AR parameter, ϕ=+0.9
ϕ
=
+
0.9
, the first-lag autocorrelation will be 0.9, the second-lag will be (0.9)2=0.81
(
0.9
)
2
=
0.81
, the third-lag will ... |
4e564ab3ca5dbe4e45ffc8cc3c2afcfe072f11ca | rjamadar/python | /lab 3.2.py | 623 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 29 16:23:49 2020
@author: Russell
"""
#read the number from user input
userInput = float(input("Enter a number:"))
#nested condition
if userInput == 0.0 :
print("zero")
else :
#display positive or negative
if userInput > 0:
prin... |
cab24c0eeb9632efdcc718ab9f388483f8941a6a | tomhel/AoC | /2022/day18/1.py | 432 | 3.734375 | 4 | def load():
with open("input") as f:
for row in f:
yield tuple(int(x) for x in row.strip().split(","))
def surface_area():
cubes = set(load())
count = 0
for x, y, z in cubes:
for dx, dy, dz in ((0, 0, 1), (0, 0, -1), (0, 1, 0), (0, -1, 0), (1, 0, 0), (-1, 0, 0)):
... |
3ce0163059f9ae725371954b061f1b9ad217acde | pb593/cam | /II/BioInf/lcs.py | 708 | 3.734375 | 4 | #!/usr/bin/python
# Longest Common Subsequence using dynamic programming
import pprint, time, os
pp = pprint.PrettyPrinter()
if __name__ == "__main__":
s1 = "abdce"
s2 = "abecdx"
l1 = len(s1)
l2 = len(s2)
mtx = [[0 for x in range(l2 + 1)] for x in range(l1 + 1)]
for i in rang... |
a909f8cf80fba0e5e1a72abe28f6e75f00b7faa6 | alexandredorais/project-euler-solutions | /Pb 6 - Sum square difference/main.py | 1,826 | 3.921875 | 4 | """
From : https://projecteuler.net/problem=6
Context : The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of... |
ab73dd5665004c86af1f878613c333fc2a2a499b | mKleinCreative/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/6-print_comb3.py | 188 | 3.5625 | 4 | #!/usr/bin/python3
for value in range(1, 80):
if (int(str(value).zfill(2)[1]) - int(str(value).zfill(2)[0])) > 0:
print('{}'.format(str(value)).zfill(2), end=', ')
print('89')
|
5ba5b8428a7de0d0c617cb0c5097dcfa1d382db0 | murdock07/raspi | /keypassing.py | 786 | 4.28125 | 4 | #!/usr/bin/python3
#keypassing.py
import encryptdecrypt as ENC
KEY1 = 20
KEY2 = 50
print ("Please enter text to scramble:")
#Get user input
user_input = input()
#Send message out
encodeKEY1 = ENC.encryptText(user_input,KEY1)
print ("USER1: Send message encrypted with KEY1 (KEY1): " + encodeKEY1)
#Reciever encrypts th... |
f60123efd3e4a66196f80638a8fcbfe9ea3806fa | sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions | /ex11_2.py | 670 | 4.1875 | 4 | # Chapter 11
# Exercise 2: Write a program to look for lines of the form
# `New Revision: 39772`
# and extract the number from each of the lines using a regular expression and
# the findall() method. Compute the average of the numbers and print out the
# average.
# Enter file:mbox.txt
# 38549.7949721
# Enter fi... |
5c1d605dc760b118213f7fe38045938bb6d8da1c | Aayuayushi/python-codes | /practice.py | 159 | 3.8125 | 4 |
list1 = [11, 5, 17, 18, 23]
print("Sum of all elements in given list: ")
def add():
return(+)
def total(list1):
return(add(list1))
y=total(list1)
print(y)
|
8ea627a29aff928a515e60e98137b5066c6c8ecd | kristen-schneider/friendship_algorithm | /kate_bubar.py | 2,905 | 4.21875 | 4 | import sys
## Function to play friendship algorithm game
def play_game():
## START GAME
# initialize the user input to 0
user_entry = 0
# ask the user to make their own input (1 to play or 2 to exit):
while user_entry != 1 and user_entry != 2:
user_entry = int(input('Select Option!\n1. P... |
0c293e479c533185fe79401556a2fd3105e6a907 | Aasthaengg/IBMdataset | /Python_codes/p03252/s955553615.py | 426 | 3.78125 | 4 | def main():
dic1 = {}
dic2 = {}
S = list(input().rstrip())
T = list(input().rstrip())
for s, t in zip(S, T):
if s not in dic1:
dic1[s] = t
elif dic1[s] != t:
print('No')
exit()
if t not in dic2:
dic2[t] = s
elif dic2[t] ... |
18b4adf9fe34cfe7b1881222db2e567256480eb8 | mehlj/challenges | /reduce_to_zero/reduce_to_zero.py | 656 | 4.21875 | 4 | def numberOfSteps(num):
"""
Determines the amount of iterations needed to reach zero starting from num
Ex: numberOfSteps(16) --> 5
@param num: Integer that needs to reach zero
@return: Number of iterations needed to reach zero
"""
counter = 0
while num != 0:
if num % 2 == 0:
... |
434a92e1dd8b91569caf3240524845ec061fa275 | rajlath/rkl_codes | /LeetCode_Top_100/max_dept_BT_133.py | 1,149 | 4.21875 | 4 | '''
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest
leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
'''
# -... |
d15b16b6302cd426d7c1ad4d935bb9304c160974 | MadhuriSarode/Python | /ICP1/Source Code/Replace.py | 478 | 4.65625 | 5 | # Write a program that accepts a sentence and replace each occurrence of ‘python’ with ‘pythons’ without using regex
string_a = input("Enter the string to be replaced: ") # Accept the string from user
string_b = string_a.replace("python", "pythons") # replace the python word with pythons
print("Origin... |
48c01674c092c13209e109ce99bd91f1015220e4 | qhuydtvt/C4E3 | /Assignment_Submission/hant/7.2.py | 615 | 3.71875 | 4 | n = [int(x) for x in input('input point one and point two:').split()]
m= input('operation:')
def calculate(number1,number2,operation):
if m=='add':
a=n[0]+n[1]
print(str.format('{0} + {1} = {2}',n[0],n[1],a))
return a
if m=='subtract':
a=n[0]-n[1]
print(str.format('{0} - ... |
fd96ad5f776c0c010dddd6e42da93e3ae19f9e8c | HANEESH-TANNERU/CS-5590-PYTHON | /ICP 1/first.py | 101 | 3.53125 | 4 | h = input("enter the string:")
g= h[::-1]
n = g[:2] + g[3:]
w=n[:1] + n[2:]
print ("",g)
print("",w)
|
c34dc6299063eb6ba425a7ce3a16e710f9411dbd | StefiOs/Python_Shapes | /rectangle.py | 755 | 3.96875 | 4 | name = input('What is the name of the customer? ')
address = input('What is the address of the customer? ')
length = eval(input('What is the length of the room (in feet)? '))
width = eval(input('What is the width of the room (in feet)?'))
area = length*width
flooring = (2)
installation = (1.5)
print('Estimate fo... |
fb691d6b6e44a03b64c14c27d465cd7025fbe2b6 | The-Mad-Pirate/Clyther | /doc/perfpy/core.py | 2,153 | 3.59375 | 4 | '''
Created on Dec 22, 2011
@author: sean
'''
class Grid(object):
"""A simple grid class that stores the details and solution of the
computational grid."""
def __init__(self, np, nx=10, ny=10, xmin=0.0, xmax=1.0,
ymin=0.0, ymax=1.0):
self.np = np
self.xmin, self.... |
08d7206c4f2848babd17ec330bea8895e06d0076 | isabellahenriques/Python_Estudos | /ex070.py | 1,172 | 4.0625 | 4 | '''Crie um programa que leia o nome e o preço de vários produtos.
O programa deverá perguntar se o usuário vai continuar ou não.
No final, mostre:
A) qual é o total gasto na compra.
B) quantos produtos custam mais de R$1000.
C) qual é o nome do produto mais barato
'''
print("-" * 32)
print("LOJA SUPER BARATÃO")
print("... |
8ef3756c10763eb16f373099f6238de90210657a | Chencheng78/python-learning | /checkio/robot-sort.py | 331 | 4.03125 | 4 | def swapsort(sequence):
seq = list(sequence)
count = []
while seq != sorted(seq):
for i in range(0,len(seq)-1):
a,b = seq[i],seq[i+1]
if a > b :
seq[i],seq[i+1] = b,a
count.append(str(i) + str(i+1))
return ','.join(count)
print(swapsort((6, 4, 2)))
print(swapsort((1,2,3,4,5)))
print(swapsort((1, 2,... |
f68e476cf1e344cb0e10e3080ac7c7f19cb74d8c | eth-ait/ComputationalInteraction17 | /Andrew/Thrid/code.py | 9,068 | 3.765625 | 4 | # PLEASE NOTE THAT THIS IS NOT ALL THE CODE USED WITHIN THE THIRD TUTORIAL, SEE TUTORIAL FOR FULL CODE.
import numpy as np
import random
import matplotlib.pyplot as plt
np.set_printoptions(suppress=True)
def __init__(self):
# array for storing reward values
self.r = np.array([[-1, -10, -30, -1], # State... |
98283b4290d8ecdf2d0a0991af78844ece7488a0 | Anithakm/study | /list1.8.py | 292 | 3.796875 | 4 | #Find largest and smallest elements of a list.
a=[777,34,333,234]
i=0
largest=a[0]
while i<len(a):
if a[i]>largest:
largest=a[i]
i=i+1
print(largest)
j=0
smallest=a[0]
while j<len(a):
if a[j]<smallest:
smallest=a[j]
j=j+1
print(smallest)
|
a159d6db7738b70d1e7be005380f1b4b87ac7b5a | jojox6/Python3_URI | /URI 1117 - Validação de Nota.py | 213 | 3.859375 | 4 |
A=float(input())
while(A<0 or A>10):
print("nota invalida")
A=float(input())
B=float(input())
while(B<0 or B>10):
print("nota invalida")
B=float(input())
print("media = %.2f"%((A+B)/2))
|
212e8f951b9d452d0ef57559cb3314aaa3a1b50c | RODRIGOKTK/Python-exercicios | /EX 16numero aredondado.py | 502 | 4.0625 | 4 | #resolução #1
import math
num = float(input('Qual um valor: '))
print('O valor digitado foi {} e a sua porção inteira é {}'.format(num, math.trunc(num)))
#resolução #2
import math import trunc
num = float(input('Qual um valor: '))
print('O valor digitado foi {} e a sua porção inteira é {}'.format(num, trun... |
385ea025598fe6a9c833d54050a70bed5ed5a1e7 | slahmar/advent-of-code-2018 | /09-02.py | 1,009 | 3.640625 | 4 | from collections import deque
with open('09.txt', 'r') as file:
parameters = file.read()
players = int(parameters[:parameters.index('players')-1])
last_marble = int(parameters[parameters.index('worth')+6:parameters.index('points')-1])*100
print(f'{players} players, last marble: {last_marble}')
pl... |
09b05ca636407d5df2261bae14752c7a1756f09f | sumeetmishra199189/Applied-Algorithms | /Brute Force vs Divide and Conquer/Assignment2.py | 5,185 | 3.515625 | 4 | #reading inputs and initializing variables
input=open('/Users/sumeetmishra/Desktop/Applied_Algorithms/Assignment/Programing Assignment-2/input.txt','r+')
input1=input.read()
input2=input1.strip().split()
input2= list(map(int, input2))
#test_3=[]
test_1=input2[:60] #taking 1000 elements from input2 which can be modi... |
cc08dc0ba575971a118b7847d61700d1b3a892fc | Akshay-jain22/Mini-Python-Projects | /Calculator_GUI.py | 4,529 | 4.21875 | 4 | from tkinter import *
# Creating Basic Window
window = Tk()
window.geometry('312x324')
# window.resizable(0,0) # This prevents from resizing the window
window.title("Calculator")
########################## Functions ##########################
# btn_click Function will continuously update the input fiel... |
e2b76213912f4f7eeaf48f06f0629b1672544015 | saimadhu-polamuri/CodeevalSolutions | /Lowercase/lowercase.py | 651 | 3.890625 | 4 | # Solution for codeeval lowercase problem
__autor__ = 'Saimadhu Polamuri'
__website__ = 'www.dataaspirant.com'
__createdon__ = '27-Feb-2015'
import sys
class Lowercase():
""" Solution for codeeval lowercase problem """
def __init__(self,filename):
""" Initial function in Lowercase class """
self.filenam... |
035b354d06bc23257f54b1e64a60e31b4b8b4ce7 | SebasRaveg/Introduccion_a_la_Programacion_con_Python_Universidad_Austral | /Trabajo_Curso_1/suma_dados.py | 664 | 3.8125 | 4 | import random
def suma_dados():
preguntar = input('¿Desea tirar los dados? (s/n): ')
while preguntar!= 's' and preguntar!= 'n':
preguntar = input('Por favor, teclee "s" o "n": ')
dado = [1, 2, 3, 4, 5, 6]
while preguntar == 's':
num1 = random.choice(dado)
num2 = random.choice(d... |
10009f65d1e1c67732076eea969b8a3beadeb7f2 | Adityanagraj/infytq-previous-year-solutions | /Prefix and Suffix.py | 493 | 3.890625 | 4 | """
A non empty string containing only alphabets. Print length of longest prefix in the string
which is same as suffix without overlapping.Else print -1 if no prefix or suffix exists.
>>Input 1
Racecar
>>Output 1
-1
>>Input 2
aaaa
>>Output 2
2
"""
string=input()
length=len(string)
mid=int(lengt... |
076991188de6809d7e108686b35eb3edba6dde47 | mooyeon-choi/TIL | /problemSolving/swExpertAcademy/python/sw_4047_카드카운팅.py | 844 | 3.53125 | 4 | from collections import deque
t = int(input())
for tc in range(1, t + 1):
answer = []
s = input()
deck = deque([])
string = ''
dic = {'S':[], 'D':[], 'H':[], 'C':[]}
for i in range(len(s) + 1):
if i == len(s):
deck.append(string)
elif not i % 3:
deck.appen... |
9bb278ee41858f4c9e550545042f88508d554218 | jackandsnow/LeetCodeCompetition | /hot100/78subsets.py | 706 | 4.28125 | 4 | """
78. 子集
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
"""
def subsets(nums):
"""
递归法
:type nums: List[int]
:rtype: List[List[int]]
"""
... |
c67b04edef3ca83450a0cec7dda79a67799e7ac7 | dualfame/YZUpython | /0429 lesson04/forloop demo4.py | 403 | 3.75 | 4 | em1 = {'name': 'John', 'salary': 60000, 'program': ['Python', 'Java']}
em2 = {'name': 'Mark', 'salary': 70000, 'program': ['C++', 'Java', 'R']}
em3 = {'name': 'Dan', 'salary': 50000, 'program': ['Python']}
emps = [em1, em2, em3]
#求會Python的員工?
language= 'Python'
names = []
for n in emps :
for p in n['program'] :
... |
799e907d8890bc5851426ba46d358fe9f5adc31d | imsaksham-c/Udacity-DataStructuresAndAglorithms | /Project-2/Problem2.py | 1,659 | 4.25 | 4 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffi... |
066dcb0b4a3dd070b677c7bf4a92c54c217480a0 | smwelisson/Exercicio_CeV | /18 - Listas 2 - 84 a 89/88.py | 306 | 3.828125 | 4 | from random import randint
jogos = 5
for quantidade_jogos in range(1, jogos+1):
mega = []
while len(mega) < 6:
num_aleatorios = randint(1, 60)
if num_aleatorios not in mega:
mega.append(num_aleatorios)
mega.sort()
print(f"Jogos {quantidade_jogos}: {mega}")
|
5dfa9cdc508f5994b6fcd16ad938c8a0f890877a | ElsieBL/STP-Portfolio | /Objective_Programming.py | 461 | 3.9375 | 4 | class Rectangle:
def __init__(self, w, l):
self.width = w
self.length = l
def calculate_perimeter(self):
return 2 *(self.width + self.length)
class Square:
def __init__(self, s):
self.s1 = s
def calculate_perimeter(self):
return 4 * self.s1
... |
a649c22ed1a9b1958147bc1c14954ab75a5e2600 | steveding1/CS-1 | /task2.2-exer2.py | 98 | 3.84375 | 4 | #CS-1 Task 2.2 - Exercise 2 from Steve Ding
name = input('Enter your name:')
print ('Hello '+name)
|
f5297ce2110544c443235a7c989e33b27b8b3d9c | arpandhakal/python_powerworkshop | /jan 19/string/17.py | 112 | 4.0625 | 4 | a=input("enter a string")
count=0
for i in a:
count += 1
print ("the length of the string is ",count)
|
5410c409558f08ad06cf09763026fa9d91eee821 | RettPop/csvexcerptor | /csvexcerptor.py | 1,493 | 3.75 | 4 | import argparse
# <input file>
# <output file>
# series of <column_name:value> parameters,
# series of <source_column:new_column_name>
# [dst_id_column_name:dst_id_value]
# reads input file looking for a row with given columns value
# takes value of the source_column of the row
# open/create output_file
# ad... |
87cb8f7a4c02ce4fd94140e39416c06ea623100f | Imranabdi/Training101 | /cardExample.py | 625 | 3.78125 | 4 | class Card:
balance = 0
# created a constructor
def __init__(self,bal):
self.balance = bal
#create a method for withdrawal
def withdraw(self,amount):
if self.balance >= amount:
self.balance -= amount + (0.2 * amount)
return self.printReceipt(self.balance,amo... |
142eaa246ccacbacdbfae5bab04ae30e26fb67f8 | ecjuncal/stats-project-dataset | /predict.py | 1,031 | 3.515625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, plot_confusion_matrix
df = pd.read_csv(r'C:\Users\Jujin\Desktop\stats-project-dataset\data\heart_failure_clinical_recor... |
5faa783c075b34d65548f4d8cbe2397e6888049e | jakubchudon/Matura | /rozne/tablice 2d.py | 295 | 3.640625 | 4 | def print2d(lista):
for i in range(len(lista)):
for j in range(len(lista)):
print(lista[i][j], end=' ')
print(' ')
tablica2d=[]
tab=[]
for i in range(1,11):
for j in range(1,11):
tab.append(i*j)
tablica2d.append(tab)
tab=[]
print2d(tablica2d)
|
e508d569ccc02071ce01530f2017f9ea0d14f8fb | w2116o2115/FirstScrip | /best/day03/课上练习.py | 1,171 | 3.59375 | 4 | __author__ = 'zw'
#注册,死循环
#账号、密码、密码确认
#非空
#已经存在的不能注册
# all_user = {'lily':123,'zhaosi':123}
# while True:
# username = input('username:').strip()
# pwd = input('pwd:').strip()
# cpwd = input('cpwd').strip()
# if username and pwd and cpwd:
# if username in all_user:
# print('用户名已经存在... |
ce31701aeed72025bfc2e4b8262297f4d93ab9c5 | Furgololoo/PythonZadania | /zad1.py | 335 | 3.71875 | 4 |
def Second(arr):
arr.sort()
for second in arr:
if second != arr[0]:
break
a = arr.index(second)
foo = []
for i in arr:
if i == arr[a]:
foo.append(i)
return foo
arr = [5,234,54,23,213,54,76,346,98,23,5,5,23,65,342]
secondmin = Second(arr)
pr... |
f3c684fe349a0e6db21f11d7c67f73e435a6c611 | zftan0709/DL_HW | /HW1/CPSC8810_HW1-3 Parameters vs Generalization.py | 25,497 | 3.703125 | 4 |
# coding: utf-8
# # ** CPSC 8810 Deep Learning - HW1-3 **
# ---
#
# ## Introduction
# _**Note:** This assignment makes use of the MNIST dataset_
#
# The main objective of this assignments:
# * Fit network with random labels
# * Compare number of parameters vs generalization
# * Compare flatness vs generalization
#... |
ec78b41416ee5bdccdab0c342ea4b6c49f841694 | C-SON-TC1028-001-2113/listas---tarea-6-Diego0103 | /assignments/17MenoresANumero/src/exercise.py | 598 | 3.625 | 4 | def resultado(m):
listafinal=[]
for i in range (len(m)):
if m[i]<10:
listafinal.append(m[i])
return listafinal
def datos(r,c):
valores=[]
matriz=[]
listacompleta=[]
for i in range(r):
for i in range (c):
valor=int(input())
valores.append(val... |
4cd78138720e58bed49c4c7cc18411edd8363fd5 | houhailun/data_struct_alrhorithm | /data_struct/BinaryTree.py | 9,516 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Time : 2019/6/28 13:08
@Author : Hou hailun
@File : BinaryTree.py
"""
print(__doc__)
"""
节点的高度:节点到叶子节点的最长路径(边数)
节点的深度:根节点到叶子节点所经历的边的个数
节点的层数:节点的深度 + 1
树的高度:根节点的高度
"""
class TNode(object):
"""二叉树节点类"""
def __init__(self, data=None, left=None, right=Non... |
e21672469f7cae4648e349b22855e6e33229faaa | jonasluz/mia-cana | /Playground/radix_sort.py | 1,082 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 20 15:52:57 2017
@author: Jonas de A. Luz Jr <unifor@jonasluz.com>
"""
import array
def findK(A):
"""
Determina o valor de k, caso não seja conhecido (em geral, o é).
"""
assert len(A) > 0
k = A[0]
for i in range(0, len(A)):
if A[i] > k:
... |
b7500140246800cc60a4abd6dc39d4801e6e872d | jedzej/tietopythontraining-basic | /students/serek_wojciech/lesson_03_functions/fibonacci_numbers.py | 294 | 3.8125 | 4 | #!/usr/bin/env python3
"""Fibonacci numbers"""
def fib(value):
"""Fibonacci numbers"""
if value == 1 or value == 2:
return 1
return fib(value - 1) + fib(value - 2)
def main():
"""Main function"""
print(fib(int(input())))
if __name__ == '__main__':
main()
|
3679b632cdafaac2d55d2dd377d498e80e8dbfc8 | kennyfrc/pybasics | /codewars/phone_number2.py | 159 | 3.671875 | 4 |
def phone_number(num):
num_str = ''.join(map(str,num))
return '(%s) %s-%s'%(num_str[:3],num_str[3:6],num_str[6:])
print(phone_number([1,2,3,4,5,6,7,8,9])) |
20bb6d298aa025b38641983432afa2937481e376 | fredichisar/p3-OC-MacGyver | /classes.py | 5,470 | 4.03125 | 4 | #!/usr/bin/python3
# -*- coding: Utf-8 -*
"""Classes of MacGyver maze"""
import pygame
from pygame.locals import *
from constants import *
from random import sample, choice
class Level:
"""Class to create a level (map)"""
def __init__(self, file):
self.file = file
self.structure = 0
de... |
354924dc3d6950e4e623d9b8d6575bec19373fe7 | someoneb100/my_termux_env | /python_modules/timer.py | 530 | 3.53125 | 4 | from time import process_time as pt
#has 4 keyword parameters
#pre - function to be called before timing
#func - timed function
#post - called after timing
#n - number of execution for averaging time
def timer(pre = None, func = None, post = None, n = 1):
suma, t = 0.0, 0
a = lambda x: (la... |
2004c168f87c1e1d4bb401fcb5bc6216a7305c98 | S-C-U-B-E/CodeChef-Practise-Beginner-Python | /Tickets.py | 358 | 3.75 | 4 | for _ in range(int(input())):
"""s=input().upper()
if s[0]!=s[1]:
if (s.count(s[0]+s[1]))*2<=len(s):
print("YES")
continue
print("NO")"""
s=set(input())
if len(s)==2:
print("YES")
else:
print("NO")
#WRONG QUESTION/TEST CASES BRO.. LOL.. ABBABA SHOU... |
9e3f1329d9d28770488ff772039f466956e29894 | mouraa0/python-exercises | /exercises/ex070.py | 762 | 3.703125 | 4 | def ex070():
preco_total = 0
maior = 0
mais_barato = None
condicao = 'S'
while condicao == 'S':
nome = input('Nome do produto: ')
preco = float(input('Valor do produto: R$'))
preco_total += preco
if mais_barato is None:
mais_barato = nome
... |
b29fc02bb1aac85072cd6cb47b0fb97734409404 | Rob174/detection_nappe_hydrocarbures_IMT_cefrem | /main/src/data/balance_classes/BalanceClassesNoOther.py | 1,496 | 3.703125 | 4 | """Balance classes by excluding patches where there is only the other class"""
import numpy as np
from main.src.data.balance_classes.AbstractBalance import AbstractBalance
from main.src.param_savers.BaseClass import BaseClass
class BalanceClassesNoOther(BaseClass, AbstractBalance):
def __init__(self, other_inde... |
a81c0672c4a0af43b5778417e4c026ba39489dcb | 4ar0n/fifthtutorial | /homework2.1_a2_day.py | 5,304 | 3.546875 | 4 |
import csv
from pprint import pprint
from datetime import datetime
from collections import OrderedDict
def get_csv_dict(file):
data = []
with open(file) as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=',')
for row in csv_reader:
data.append(dict(row))
# ppri... |
8e6e3387704b63262edbf3d44949a2e3e7d1e804 | RobinsonTran/rt-django-repo | /lpthw/ex6.py | 892 | 4.28125 | 4 | types_of_people = 10 # variable for x
x = f"There are {types_of_people} types of people." # 1st verison of string formatting
binary = "binary" # variable for f-stringing stuff
do_not = "don't" # variable for f-stringing stuff
y = f"Those who know {binary} and those who {do_not}." # both previous variables used for y s... |
f341989002cfa56c43b94b5d294d107c6329b03d | PDXCodeGuildJan/CourseAssignments | /merge_sort.py | 853 | 3.71875 | 4 | __author__ = "Tiffany Caires"
"""Implements the merge sort algorithm, recursively, in Python."""
def main():
"""Take a random list and use merge_sort to sort it"""
unsorted = [4, 7, 14, 2, 94, 38, 2]
sorted = merge_sort(unsorted)
print(sorted)
def merge_sort(unsorted):
"""Implement the merge sort al... |
d088308e4527bb250fdedffbb9eb50819a8b8e44 | MrunalPuram/gamma-ai | /pairidentification/heptrkx-gnn-tracking/models/cnn_classifier.py | 1,581 | 3.515625 | 4 | """
This module defines a generic CNN classifier model.
"""
# Externals
import torch.nn as nn
class CNNClassifier(nn.Module):
"""
Generic CNN classifier model with convolutions, max-pooling,
fully connected layers, and a multi-class linear output (logits) layer.
"""
def __init__(self, input_shape,... |
5f68ce5a34d7aee154428d6fdd3dafc2b3830fbd | MaxLavrinenko/Python_okten | /hw4.py | 4,434 | 4.40625 | 4 | # Создать класс Rectangle:
# -конструктор принимает две стороны x,y
# -описать арифметические методы:
# + сума площадей двух экземпляров класса
# - разница площадей
# == или площади равны
# != не равны
# >, < меньше или больше
# при вызове метода len() подсчитывать сумму сторон
# class Rectangle:
# def ... |
052af12e6487a076f1d71ec4c76c2553a18a73e9 | ImaniNgugi50/Data-Science-projects | /p1.py | 141 | 3.6875 | 4 | import pandas as pd
d = {'col1': [1, 2, 3, 4, 7], 'col2': [4, 5, 6, 9,5], 'col3': [7, 8, 12, 1, 11]}
df = pd.DataFrame(data=d)
print(df)
|
fe4823fc78f1d7aba084f79ccbc1dde4baccd40a | Siyuan-Liu-233/Python-exercises | /python小练习/017田忌赛马.py | 924 | 3.90625 | 4 | # 这题也是华为面试时候的机试题:
# “ 广义田忌赛马:每匹马都有一个能力指数,齐威王先选马(按能力从大到小排列),田忌后选,马的能力大的一方获胜,若马的能力相同,也是齐威王胜(东道主优势)。”
# 例如:
# 齐威王的马的列表 a = [15,11,9,8,6,5,1]
# 田忌的马的候选表 b = [10,8,7,6,5,3,2]
# 如果你是田忌,如何在劣势很明显的情况下,扭转战局呢?
# 请用python写出解法,输出田忌的对阵列表 c及最终胜败的结果
# 评分
a = [8,15,1,11,6,5,9]
b = [2,8,6,7,5,3,10]
import numpy as np
a,b=np.array(n... |
1dcc11ab5a82fce16aed96854ac5dc5862b8777f | HandeulLy/CodingTest | /Programmers/짝수와홀수.py | 190 | 3.828125 | 4 | # Solution 1
def solution1(num):
if num%2==0 : return "Even"
else : return "Odd"
############
# Solution 2
def solution2(num):
return "Even" if num%2 == 0 else "Odd" |
ef9be9e92e1ded6a556a4a0b663d1cac3b510fe3 | ledbagholberton/holbertonschool-higher_level_programming | /0x08-python-more_classes/chess.py | 1,899 | 4.15625 | 4 | #!/usr/bin/python3
"""Queen Chess challenge
"""
def printSolution(board, n):
for i in range(n):
for j in range(n):
print(board[i][j]),
print()
def isSafe(board, row, col, n):
""" Found if a position is safe or atacked by other Queen
Arguments:
board: Position of other quee... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.