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 |
|---|---|---|---|---|---|---|
b9a7e97826c1f746c7ce528958f7320e671a9ab7 | yooni1903/DDIT | /workspace_python/HELLOPYTHON/day09/mynumpy03.py | 154 | 3.625 | 4 | import numpy as np
a = np.zeros((10, 10), dtype=int) # int형으로 넣어주는 명령어
print(a)
print(a.shape)
b = np.reshape(a,(20,5))
print(b)
|
e8e187817d66d03da0c37b5f2a8dff1ab8f4152a | ethanrweber/ProjectEulerPython | /Problems/1-100/11-20/Problem14.py | 648 | 4.09375 | 4 | def method():
print("Collatz Conjecture! which starting number < 1,000,000 produces the longest collatz chain?")
print("note: takes up to 15 seconds")
max = 0
max_chain = 0
for i in range(1, 1_000_000, 2):
# even numbers have shorter chains
chain = collatz(i)
if chain > max_c... |
0d9ce5c438818a59f7d3e81332c3bbf5ac6184a4 | markymauro13/CSIT104_05FA19 | /Exam-Review-11-6-19/exam2_review.py | 127 | 3.578125 | 4 | #1
# review asci
x = 'D'
ch = chr(ord(x)-3)
print(ch)
print("--")
print(ord(x))
print("--")
print(ord(x)-3)
|
bfb435bdf8e5fcced6b23b520bf1919e83027527 | techkids-c4e/c4e5 | /Lê Văn Dịnh/buoi3/bai tap 5.py | 169 | 3.75 | 4 | from turtle import*
d=360
speed(0)
for i in range (d) :
for i in range (360):
color("green","black")
forward(1)
left(360/d)
left(360/30)
|
ad1035e672761918cfab6722b9dc391faeb953a9 | yennanliu/CS_basics | /leetcode_python/Binary_Search/find-minimum-in-rotated-sorted-array.py | 5,948 | 3.75 | 4 | """
Suppose an array of length n sorted in ascending order is rotated between 1 and n times.
For example, the array nums = [0,1,2,4,5,6,7] might become:
[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results i... |
5c722e1a33d1b4fc35106174373d143fbd4b4bf0 | FicusCarica308/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/2-my_filter_states.py | 1,138 | 3.625 | 4 | #!/usr/bin/python3
"""
Description:
Here we have a program that opens a MySQL database from arguments
passed on exectution. Host name and port number are static
to local host system.
===================================================================
MySQL Execution:
Will print results from query in ascending order by ... |
89ac5173aaab8b4d9a028fcb7efcdf1b24eb7a2f | ptking/advent_of_code | /2018/1/1_1.py | 446 | 3.59375 | 4 | import os
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--input')
args = parser.parse_args()
frequency = 0
with open(args.input,'r') as file_in:
for line in file_in:
sign = line[:1]
length = len(line)
increment = int(line[1:])
if(sign == '-'):... |
7490138795056a76c91992104e7c0ebc6c60bd3d | starkcoffee/maths | /maths/pythagoras.py | 951 | 4.03125 | 4 | from math import sqrt
import cProfile
from numpy import gcd
#return number of triplets with c less than n
def num_triplets(n):
# generate the set of all squares less than n
all_squares_list = [i**2 for i in range(1,n)]
all_squares_set = set(all_squares_list)
n_squared = n**2
# for each pair of squares
co... |
971f2856606daafa3fd436eb861518b2f5055d4d | 200202iqbal/game-programming-a | /Paiza/D129.py | 276 | 3.53125 | 4 | #税率の変更
number = input().split()
z = int(number[0])
x = int(number[1])
y = int(number[2])
rule = z >= 100 and z<=2000 and z%100 == 0 and x,y >=1 and x,y<=100 and x < y
if(rule):
z1 = (z * x)/100
z2 = (z * y)/100
result =int(abs(z1-z2))
print(result)
|
e51fa04b3bcdd354f8828d0f815b9b2f057a5886 | AnnaShilova/structured-programming | /Лабораторная работа №4/базовый уровень.py | 322 | 3.78125 | 4 | str = input('Введите строку: ')
print('замена №1: ',str.replace('!', ' '))
#второй вариант решения
s = input('Введите строку: ')
i = 0
s2 = ''
while i < len(s):
if s[i] != '!':
s2 += s[i]
elif s[i] == '!':
s2 += ' '
i += 1
print('замена №2: ',s2)
|
49719364f7b1ee5cc1331fc6227c005a3a143c7b | Pedro-H-Castoldi/descobrindo_Python | /pphppe/sessao7/Módulo_Collections-Counter.py | 1,483 | 3.578125 | 4 | """
Collections -> high-performance Container Datetypes
Counter (Contador)
Recebe um interável como parâmetro e cria um objeto do tipo Collections Counter q é parecido com um dicionário,
contendo como chave o elemento da lista passado como parâmetro e como valor a quantidade de vezes q este elemento
se repete na lista... |
74355b4b8eca6c2a6bce299ed9ad73dedefd95e3 | wangyum/Anaconda | /lib/python2.7/site-packages/sympy/geometry/point.py | 28,721 | 3.671875 | 4 | """Geometrical Points.
Contains
========
Point
Point2D
Point3D
"""
from __future__ import division, print_function
from sympy.core import S, sympify
from sympy.core.compatibility import iterable
from sympy.core.containers import Tuple
from sympy.simplify import nsimplify, simplify
from sympy.geometry.exceptions imp... |
864e63284b52c827fccc278a2aa0cd449218b748 | tagonata/daily_programming | /daily_programming/200216_30.py | 177 | 3.625 | 4 | def bit_counter(number):
return bin(number)[2:].count('1')
Input_number = 6
print(f'Input: {Input_number}')
result = bit_counter(Input_number)
print(f'Output: {result}')
|
74d54cdb51c6911a001f2aaa23682b87d32141a9 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/496e2a18-374e-4aa4-b0f8-e38d8c16a018__problem057.py | 1,660 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# The Euler Project: problem 57
#
# It is possible to show that the square root of two can be expressed as an infinite continued fraction.
#
# √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + … ))) = 1.414213…
#
# By expanding this for the first four iterations, we get:
#
# 1 + 1/2 = 3/2 =... |
486e9403adea925f6443bd3817e3771cff20fc2e | kcalizadeh/tic-tac-toe_game | /tic-tac-toe.py | 6,067 | 3.96875 | 4 | import re
import random
# a function for switching from player to player
def switch_player(active_player):
if active_player == "X's Player":
return "O's Player", 'O'
else:
return "X's Player", 'X'
# a function for asking if people want to play against computers or human opponents
def ask_oppon... |
3e15f28106fe3c9ea091bac6f5cc129a73924776 | daniel-reich/ubiquitous-fiesta | /2nx4JCytABfczdYGt_12.py | 485 | 3.75 | 4 |
def conjugate(verb, pronoun):
rel = (0,
('Io', 'o'),
('Tu', 'i'),
('Egli', 'a'),
('Noi', 'iamo'),
('Voi', 'ate'),
('Essi', 'ano')
)
if verb[-4] == 'i' and pronoun in (2,4):
word = verb[:-4] + verb[-3:]
elif verb[-4] in 'cg... |
e8229df868c89f56a80a4aa5dae7eeb277fc97e1 | Touchfl0w/python_practices | /advanced_grammer/practice1-10/practice1/p2.py | 171 | 3.515625 | 4 | from random import randint
d = {x:randint(-10,10) for x in range(10)}
print(d)
#字典解析
result = {v:k for k,v in d.items() if v > 0}
print(result)
#不适合用filter |
9cc71dbd24757ead6afab1f1ef6bc92165f00a63 | tylerlaquinta/projects | /rock_paper_scissors.py | 1,683 | 4.25 | 4 | import random, sys
print("""Let's play Rock, Paper, Scissors
Choose (r)ock, (p)aper of (s)cissors
Type 'q' at any time to quit""")
wins = 0
ties = 0
loses = 0
while True:
score = f"Wins: {wins} Ties: {ties} Loses: {loses}"
print(score)
while True:
choice = input("Choose: ")
... |
6760db46c6dfda748bb5bc8b6826c7fa5dd87b89 | rohanmarwah/hello-world | /Python-Data Structures(course 2)/file_opening.py | 149 | 4.0625 | 4 | # Use words.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
for lx in fh:
ln=lx.strip()
l1=ln.upper()
print(l1)
|
349c21b83ebf8cf3dd6b8fa9f5106b660ff36db9 | idellang/Python_Learning_Corey | /WorkingWIthNumericData.py | 436 | 4.21875 | 4 | num = 3
float_num = 3.14
print(type(num))
print(type(float_num))
# floor division
print(3 // 2)
# exponent
print(3 ** 2)
# modulus
print(3 % 2)
# incrementing values
num = 1
num += 1
num *= 10
print(num)
# abs
negative_num = -3
print(abs(negative_num))
# round
# first argument is decimal.
print(round(3.75, 1))
... |
b111a6b21c2028c0a6cdf6f072407987aa4ee731 | Shaileshsachan/script | /Script.py | 94 | 3.5 | 4 | list2 = []
list1 = [2, 4]
for i in range(10):
if i == [x for x in list1]:
print(i) |
310e91b8d9278a1de7464036a9a3fb30bf091956 | sancheslz/basic_tdd | /lesson_24.py | 923 | 4.28125 | 4 | """LESSON 24
Goal: Create a class called "Area" that return the square and the cubic area of some number
"""
class Area:
def square(self, a: int, b: int) -> int:
return a * b
def cubic(self, a: int, b: int, c: int) -> int:
return a * b * c
def magic(self, *args):
total = 1
... |
3741b09e795d97b8720d44d18975abd0ba5140ea | abishekbalaji/hundred_days_of_code_python | /hangman/hangman2.py | 1,295 | 3.921875 | 4 | import random
import hangman_art
import hangman_words
words = hangman_words.word_list
stages = hangman_art.stages
count = len(stages)
def init(count):
temp_word = []
word = random.choice(words)
for _ in word:
temp_word.append("_")
count = min(count, len(word))
print(
f"The word is... |
edde9c805fd646eff219c00056976f6f12cf7d42 | ChuChuIgbokwe/Python-2.7-code | /truth_testing_ex1.py | 591 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Chukwunyere Igbokwe on March 10, 2016 by 2:55 AM
def getinput():
'''
0 is returned from getinput. Remember that both 0, None, empty sequences and some other forms all evaluate
to False in truth testing.
:return:
'''
print "0: start"
... |
91e224d56f113318258f0fc58288f5fcde38529b | KellyInnovation/TODO | /todo.py | 962 | 3.84375 | 4 | from sys import exit
class TODO():
MAIN_MENU = (
"1: Display Tasks",
"2: Add Tasks",
"3: Mark Tasks Completed",
"4: Remove Tasks",
"0: Exit Program",
)
def main_menu(self):
while True:
menu_selection = get_menu_selection(self.MAIN_MENU)
if menu_selection == "1":
pass
elif menu_selection =... |
39191938133e0900a37afd3055a3ee871af790f6 | veryflying/ltcd | /98-Validate-Binary-Search-Tree/solution.py | 977 | 3.71875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
... |
70686442c2a1b0d0ce49b4327ef5a7714a9da210 | chriswill88/holbertonschool-machine_learning | /math/0x04-convolutions_and_pooling/2-convolve_grayscale_padding.py | 1,867 | 3.84375 | 4 | #!/usr/bin/env python3
"""performs a valid convolution on grayscale images"""
import numpy as np
def convolve_grayscale_padding(images, kernel, padding):
"""
That performs a convolution on grayscale images with custom padding:
@images
a numpy.ndarray with shape (m, h, w, c) containing... |
5fa4758a1f6393ecc8a95b003d72bf1cdeed85a0 | HripsimeHome/python_lessons | /hw1and2_mod2.py | 287 | 4.1875 | 4 | from math import remainder
# 8.2 calculating remainder of some number divided to other number (inputted from console),
input_num1 = int(input("Please, enter first number: "))
input_num2 = int(input("Please, enter second number: "))
remainder_result = (remainder(input_num1,input_num2))
|
a1b4cde9f2b8a899feb36198e73077af6b4a61e9 | mariogen/curso_python | /dia_1/arquivos-python/1_intermediate/02_bench.py | 680 | 3.53125 | 4 |
import time
t0 = time.time()
# code_block
t1 = time.time()
total = t1-t0
from math import sqrt
def fib_v1(n):
if n == 0:return 0
elif n == 1: return 1
return fib_v1(n-1)+fib_v1(n-2)
def fib_v2(n):
return int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5)))
fibs = fib_v1, fib_v2 #, fib_v3
... |
ce5f280aa1b68f24481abaef4a5fcf8185d24c75 | imgourav/codigosProgramacion | /Python/Varios/ContadorInversoWhile.py | 123 | 3.953125 | 4 | contador=5
while contador:
print("Dentro del ciclo.", contador)
contador -= 1
print("Fuera del ciclo", contador) |
d31a53b4355bdd5da67cfe4a6c7501f2337bd08b | AdamZhouSE/pythonHomework | /Code/CodeRecords/2776/49361/278541.py | 1,056 | 3.890625 | 4 | class Solution:
def findAllConcatenatedWordsInADict(self, words):
words.sort(key = lambda x: len(x))
ans = []
tire = {}
for word in words:
if len(word) == 0:
continue
if is_concatenated_word(tire, word):
ans.append(word)
... |
97e48ff7b0e0866cb5850a331cee8a216b657cd4 | asselapathirana/pythonbootcamp | /2023/day2/debug.py | 107 | 4.0625 | 4 | a=5
b=6
c=a+b
print(c)
if c < 5:
print("c is less than 5")
else:
print("c is greater than 5")
|
e642b23578b3d2d375db92ea0be85270350ed239 | LucasMatuszewski/python-eduweb-course | /OOP/main.py | 1,582 | 3.78125 | 4 | # We have main.py in subfolder which is not a standard.
# For autocomplete we have to add extraPaths in .vscode/settings.json
from bill import Bill
import view
def main():
# now we can use Meal Constructor to create Object of our class:
# eggs = Meal("Eggs", 6.99)
# print(eggs.name)
# Create new inst... |
07402a473c399abef1d8cd0472d73d76354920d2 | Jason101616/LeetCode_Solution | /Backtracking_Depth First Search/77. Combinations.py | 1,145 | 3.84375 | 4 | # Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
# For example,
# If n = 4 and k = 2, a solution is:
# [
# [2,4],
# [3,4],
# [2,3],
# [1,2],
# [1,3],
# [1,4],
# ]
# idea: similar as permutation, but you can't choose number which index is smaller than the curren... |
bc6b92a02f40ca6919df3627bc6569c38969a4e3 | dlefcoe/daily-questions | /sumToTen.py | 674 | 4.15625 | 4 | '''
This problem was asked by Microsoft.
A number is considered perfect if its digits sum up to exactly 10.
Given a positive integer n, return the n-th perfect number.
For example, given 1, you should return 19. Given 2, you should return 28.
completed by d ross: 2009_09_09
works.
'''
def ten(number):... |
db269d36e8e791412a0fac7d7822f9a573ea3b72 | kaio358/Python | /Mundo3/Funções/Desafio#101.py | 395 | 3.875 | 4 |
def voto(anos):
from datetime import date
atual = date.today().year
idade = atual - anos
if idade < 16 :
return f'A idade {idade} insuficiente, NEGADO !!'
if 16 <= idade <18 or idade>69:
return f'A idade {idade} é OPICIONAL'
if 18 <= idade <= 69:
return f'A idade {idade}... |
b7835f24122cdf98556dedda41774f2dcebe127c | StudyForCoding/BEAKJOON | /16_DynamicProgramming1/Step07/wowo0709.py | 300 | 3.515625 | 4 | n = int(input())
step = [0]*(n+2);score = [0]*(n+2)
for i in range(n):
step[i] = int(input())
score[0] = step[0];score[1] = step[0] + step[1]
score[2] = max(step[0]+step[2],step[1]+step[2])
for i in range(3,n):
score[i] = max(score[i-3]+step[i-1]+step[i],score[i-2]+step[i])
print(score[n-1]) |
2910d6bc150cfb5cfc60e5b31f9910d546027eda | karthikwebdev/oops-infytq-prep | /2-feb.py | 1,943 | 4.375 | 4 | #strings
# str = "karthi"
# print(str[0])
# print(str[-1])
# print(str[-2:-5:-1])
# print(str[-2:-5:-1]+str[1:4])
#str[2] = "p" -- we cannot update string it gives error
#del str[2] -- this also gives error we cannot delete string
#print("i'm \"karthik\"") --escape sequencing
# print("C:\\Python\\Geeks\\")
# print(r"I... |
d587d195d51c67fd9a6d5c726db7d7f5557f5ac5 | yaobinwen/robin_on_rails | /Python/time/time_demo.py | 621 | 3.921875 | 4 | #!/usr/bin/env python3
"""This file contains examples of using `time`. For its documentation, see
https://docs.python.org/3/library/time.html
This document is referred to as `DOC` in the code.
"""
import time
import unittest
class TestTime(unittest.TestCase):
def test_time(self):
"""Demo for `time.tim... |
cdb3e2971c915461e7c8be9698ac2697077f9369 | agasca94/codesignal-exercises | /interview/trees-basic/isTreeSymmetric/isTreeSymmetric.py | 841 | 3.875 | 4 | #
# Binary trees are already defined with this interface:
# class Tree(object):
# def __init__(self, x):
# self.value = x
# self.left = None
# self.right = None
def isTreeSymmetric(t):
if t:
nodes = [t.left, t.right]
return check_nodes(nodes)
return True
def check_nodes(nodes):... |
0bf452c6eccdb5786990e7571324ed5b68161cd6 | tom0/bioinformatics1 | /reverse_complement/reverse_complement.py | 332 | 4.03125 | 4 | def reverse_complement(str_pattern):
complements = {
'G': 'C',
'A': 'T',
'C': 'G',
'T': 'A'
}
result = ""
for c in str_pattern:
result = complements[c] + result
return result
if __name__ == '__main__':
import sys
t = sys.argv[1]
print(reverse_com... |
92dc80930e15b566cc2d93cb580c85c5c30bc3a3 | olincollege/Processing-Pop | /get_audio_features.py | 4,327 | 3.984375 | 4 | """
Find the audio features for each song when provided its Spotify Track ID. The
ID is used to find the corresponding audio features for each song through the
Spotify API. Do this for all the relevant Billboard Hot 100 Songs to be
analyzed.
"""
# Import the required libraries.
import pandas as pd
import requests
from... |
ee69a1ea9e549d2da2403d3c5ffba3ab83b00cfa | Patrrickk/aprendendo_python | /ex013.py | 175 | 3.515625 | 4 | didin = float(input('Qual é seu salário: '))
new = didin + (didin * 15 / 100)
print(f'Parabéns! você acaba de receber um aumento de 15% que totaliza o valor R${new:.2f}')
|
c2270c77820ee99279165ee796bc59a832ece4ca | milanmenezes/python-tutorials | /solutions/unit2/lifo.py | 243 | 3.78125 | 4 | l=[]
while(True):
x=eval(raw_input("Enter 1 to insert, 2 to delete 0 to quit\n"))
if(x==1):
y=eval(raw_input("Enter the element to be inserted\n"))
l.append(y)
elif(x==2):
y=l.pop()
print y
elif(x==0):
break |
34b8377598796a71e07e6031d86f0ec9f5dcf4a1 | ken025/HelloWorld_Python | /car_game.py | 577 | 4.125 | 4 | print('''
Welcome to the Car Game!
Enter 'help' to begin!
''')
user_input = ""
while user_input != "quit":
user_input = input('> ').lower()
if user_input == "start":
print('Car started... Ready to go!')
elif user_input == "stop":
print('Car stopped.')
elif user_input == "quit":... |
6710b29ac7e56fa8e5928828ef640cd2302668a6 | karsevar/Code_Challenge_Practice | /combination_sum/combination_sum.py | 1,626 | 3.90625 | 4 | class Solution:
def combinationSum(self, candidates, target):
# create a recursion helper function that will be used to
# recursively step through the list and see what combinations
# create the target value
# base cases:
# if minus amount is less than the targ... |
b86a7387dba5d7ed311c789b3396e2dc8f38236c | GvidasKo/PythonEX | /python-advanced-features-master/11-multiprocessing/exercise-01.py | 1,862 | 4 | 4 | """
1. Create the following functions:
1. `generate_random(out_q, n)` which generates `n` random integers and puts them in `out_q` Queue
2. `square(in_q, out_q, n)` which takes numbers from the `in_q` Queue and puts their squares in the `out_q`.
3. `to_binary(in_q, out_q, n)` takes numbers from the `in_q` ... |
0582570e6a25e52e8a9f46ed6d37838c9f4fd100 | pdam/REST_API | /ParserUtils.py | 5,951 | 3.796875 | 4 | import json
import random
from pprint import pprint
import requests
def hyphen_range(s):
""" yield each integer from a complex range string like "1-9,12, 15-20,23"
>>> list(hyphen_range('1-9,12, 15-20,23'))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 19, 20, 23]
>>> list(hyphen_range('1-9,12, 1... |
d4ed39623cf130046a09bea59fdd1d4581d490cc | fmcarrasco/AguaUtil | /AguaUtil.py | 19,543 | 3.59375 | 4 | """
Funciones para trabajar con los archivos de porcentaje
de Agua Util por cultivo.
Tareas que hay que realizar:
- Lectura de TXT con los datos diarios
- Calculo de medias decadales (1-10; 11-20; 21-Fin de Mes)
- Union de estos datos con superficies por departamento y por cuartel
"""
import os
import pandas as pd
impo... |
b121700d89d5879702f518880887c930bc4bc45e | SeanyPollard/com404 | /99-practice-tca/03-2nd-tca-1/part_a.py | 1,852 | 3.90625 | 4 | from tkinter import *
class Gui(Tk):
# Window
def __init__(self):
super().__init__()
# Window attributes
self.title("Newsletter")
self.configure(background="#eee",
padx=10, pady=10)
# Add components
self.__add_main_frame()
self.... |
a73c1dc8ff898f5e04092f89c49d3641e1ad21c3 | yunhaeyoung/BaekJoon | /20210612.py | 3,406 | 3.8125 | 4 | #숫자 출력
# print(5)
# print(-10)
# print(3.14)
# print(5+3)
# print(8*8)
# print(3*(3+1))
#문자열 출력
# print('작은 따옴표')
# print("큰 따옴표")
# print("오에"*10)
#boolean
# print(5 > 10)
# print(5 < 10)
# print(True)
# print(False)
# print(not True)
# print(not (5 > 3))
#변수
# animal = "고양이"
# name = "땅콩스"
# age = 1.5
# hobby = "... |
9c2276242e50c13e996ab4f65f38323d1b872e35 | priya510/Python-codes | /19.09.2020 python/while_demo.py | 198 | 3.671875 | 4 | '''
Loop
while loop
for loop
WAP to print NIIT 10 times.
'''
i=10
while(i>=1):
print("NIIT")
i=i-1
|
34c7002b7a5ddeadd1f82d7eff1ea4ac24dd09c9 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/cfda6755abf642a39560ccfb11f84f5d.py | 569 | 3.6875 | 4 | # Initialize a class 'Bob'
class Bob:
# Bob hears you when you say 'hey'!
def hey(self,text):
# If you say nothing to bob...
if not len(text):
return 'Fine. Be that way.'
# If you ask bob a question...
# If text is BOTH a question AND shouted, response is based
... |
4f994d32a30b9782c1d15743150c0744c3aac133 | roblivesinottawa/studies_and_projects | /PYTHON_BOOTCAMP/LECTURES/bubble_sort.py | 987 | 4.125 | 4 | # create a unordered list and set it to a variable
data = [11,2,3,14,5,96,107,48,99]
# create a new list and make a copy of the original list
data_copy = data[:]
# the first for loop will iterate through the list and then will iterate through it again
for x in range(len(data_copy)):
# the -1 is added because we are co... |
3208321ef5ec30c0f2d733029636d4993c3bca8f | luandeomartins/Script-s-Python | /ex026.py | 546 | 4.03125 | 4 | from math import hypot
co = float(input('Comprimento do cateto oposto: '))
ca = float(input('Comprimento do cateto adjacente: '))
hi = hypot(ca, co)
print('A hipotenusa vai medir {:.2f}.'.format(hi))
# Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo. Calcule e
#... |
1d8510c1596740e1e7308764a83d82360c8ec937 | fcamilalima/exercicios-python | /group.py | 231 | 3.734375 | 4 | def group(x):
list=x[0]
size=x[1]
print(x[0])
print(x[1])
y=[]
y=[list[i:i+size] for i in range(0, len(list), size)]
return y
k=group([[1, 2, 3, 4, 5, 6, 7, 8, 9], 3])
print(k)
|
5c83b5e94ec58414096cac10bb29e37d94d0c64d | ameymahadik1997/amudi97 | /prime.py | 595 | 4.15625 | 4 | #WAP to check whether the nymber entered by the user is prime or not
while True:
a=int(input('Enter the number to be checked if prime or not=>'))
if a==0:
print('Number is a Zero')
elif 0<a<=2:
print('The Number entered=',a,'is a prime')
elif a>2:
for i in range(2,a):
... |
58fb47f97bb0b430ae988a55ca156614318fa7c5 | jdukosse/LOI_Python_course-SourceCode | /Chap15/lcsmemo.py | 7,209 | 3.8125 | 4 | from stopwatch import Stopwatch # Our Stopwatch class from before
from random import choice
from turtle import *
def LCS(X, Y):
""" Computes the longest common subsequence of strings X and Y. """
result = '' # No symbols in common unless determined otherwise
if len(X) > 0 and len(Y) > 0: # No symbols i... |
7e4b9c3843c4251db490394b94d03f230ed962de | magnuskonrad98/max_int | /FORRIT/python_verkefni/leika/test.py | 141 | 3.71875 | 4 | a = int(input("enter a nuber: "))
if a > 60:
print(a)
elif a > 50:
print(a)
elif a > 40:
print("cool",a)
else:
print("wow")
|
3f3b8dede7218f6ab313d989f7ce5079f31934df | GaoYu/zeroPython | /10_break.py | 220 | 3.9375 | 4 | i = 1
while i <= 6:
print("本次循环开始时:",i)
if i ==3:
break #break将打破包含它的while语句
print("本次循环结束时:",i)
i += 1
print("这是程序最后一条语句")
|
f599720e84ee28cd5effed0e58c91ac1edae35ed | baovu98/Homework-Python | /calculator.py | 711 | 4.125 | 4 | def calculator(number1, number2, operator):
if operator == '+':
return number1 + number2
elif operator == '-':
return number1 - number2
elif operator == '/':
if number2 == 0:
return False
return number1 / number2
elif operator == '//':
if number2 == ... |
32542515cf8728e5182e679ad820ca371133b121 | KamiKunDesu/RuneScape-HiScores-Getter | /scoreGetterFinal.py | 6,632 | 3.828125 | 4 | import http.client
"""
_getHTTPResponse is a function which handles making a request to the JaGex runescape hiscores api.
It also handles the csv format that it returns the data in, reads
it and processes so that it's in a useable format
It then returns the usable format (list) for use processing to make some
diction... |
f21a866f92f43972ece9fd59ba00544e495705c0 | gschen/sctu-ds-2020 | /1906101115-江汪霖/day0414/text03.py | 926 | 3.546875 | 4 | # 计算回退下标
def back_index(s):
lis=[-1] #代表第一个字符
k = -1 #最长公共前缀
for i in range(1,len(s)):
while s[i]!=s[k+1] and k>-1 : #不满足情况,需要不断往回退,同时避免退到-1
k = lis[k]
if s[i] == s[k+1]: #满足情况,最长公共前缀+1
k = k+1
lis.append(k)
return lis
print(back_index("ababaca"))
def kmp(... |
66209e3bde99f60f0a2b6f97df001ba20a55c8a7 | kagomesakura/consonants | /consonants.py | 625 | 3.78125 | 4 |
# purposely have 8 consonants, half upper, half lower. on run answer comes back 4, its counting only lowerself.
# need to understand how to .upper .lower case
c = "TH th dg DG"
numC = 0
for char in c:
if char == 'b' or char == 'c' or char == 'd' or char == 'f' or char == 'g' or char == 'h' \
or char == ... |
e52c47ba02f1a118b257ca40d616d827aa22c222 | beccaelenzil-teach/CS-Becca-1718 | /algorithms_data_structures/dateTest.py | 8,700 | 3.765625 | 4 | import cmath as math
import time
class Date:
def __init__(self, month, day, year):
self.month = month
self.day = day
self.year = year
def __repr__(self):
s = "%02d/%02d/%04d" % (self.month, self.day, self.year)
return s
def isLeapYear(self):
if self.year %... |
4bb0aa2966509cd3137d66d0819cf06980ccdd19 | Funk2256/Codewars | /Moving Zeros.py | 198 | 3.890625 | 4 | def move_zeros(array):
for find_zero in array:
list_zero = []
if find_zero == 0:
list_zero.append(find_zero)
print(list_zero)
move_zeros([1,1,1,1,1,0,0,1]) |
59a4c200bd80cf34b34417ad73668aca70babfb7 | leylairoyale/oop-hangman-wip | /main.py | 4,074 | 4.09375 | 4 | # remember to activate hangman-env
import random
# class HangmanGameSet does everything to set up the game.
# class CLPrint will print things to the command line
# class PlayGame will take instances of everything to get it set up and running and is the game logic.
# class UserInput will handle the user inputs.
# clas... |
536a68da5c2496c9aabe63cdbf7d9640efbb655c | officialtech/PYTHON | /list/Exercise/sumOf3.py | 270 | 3.90625 | 4 |
def sum3(_list):
if len(_list) < 3:
return "array length should be greater than or equall to 3"
else:
return sum(_list)
print("1.", sum3([1,2,3]))
print("2.", sum3([1,2,3,4,6]))
print("3.", sum3([1,2,-1,9]))
print("4.", sum3([1,2])) |
f7e3796fb50517225cd88c613b91d722d5bee85c | takamuio/DesafiosAulaYoutube | /venv/teste60.py | 462 | 4.15625 | 4 | from math import factorial
numero = int(input('Digite um numero inteiro: '))
f = factorial(numero)
print('O fator do numero {} é {}'.format(numero,f))
#usando while
contador = numero
fator = 1
print('Calculando {}! = '.format(numero), end='')
while contador > 0:
print('{}'.format(contador), end='')
if contado... |
5a6182c9442a55ed63cdcef5ad4cdcdc264cf203 | MihoKim/bioinfo-lecture-2021-07 | /pyBasic/test.py | 816 | 3.625 | 4 | #! /usr/bin/env python
d_table = {'fruit':'apple','color':'red','dia':10}
print('apple' in d_table)
print('fruit' in d_table)
print('color' in d_table)
print('red' in d_table)
print(d_table.keys()) #dict_keys(['fruit', 'color', 'dia'])
print(type(d_table.keys())) #<class 'dict_keys'>
pr... |
0a0e2f6835b43215b175839219918285367ec523 | yuehhanc/classler | /python/solution/solution_framework/test_utils_deserialization.py | 6,147 | 3.5625 | 4 |
import json
import re
def get_string_parser_for_type(typename):
"""
Constructs a string parser for the given type.
:param typename - string representation of a type from the test data header.
:return: a functor, that accepts a string and converts it to an instance of the given type.
"""
if t... |
309589ee7562b1da86f8dd3a4301c138a6e0d9bb | marthinmhpakpahan/onlinejudge | /uri/1035-SelectionTest1.py | 224 | 3.703125 | 4 | a = raw_input()
aR = a.split(" ")
A,B,C,D = int(aR[0]),int(aR[1]),int(aR[2]),int(aR[3])
if B > C and D > A and (C+D) > (A+B) and (C>0 and D>0) and A%2==0:
print "Valores aceitos"
else:
print "Valores nao aceitos"
|
b48b8757838ba34bfad0033ec8d285d2eb4c03b3 | Sneha-Singh09/python-others | /operators.py | 991 | 4.3125 | 4 | #arithmetic operators
#8+6- add
#8-6-sub
#8*6-mul
#8/6-div
#8//6-floor div- rounds off value removing decimal
#8%6-modulus
#8**6-exponent
#abs- removes negative sign
#round-round offs round(no.,how many places)
"""print(abs(-5))
print(round(5.789,2))
print(8/3)"""
#comparison operators
#< -- less than
#>... |
d8ed138ba95a8b042dca57a1e1f5883bac682954 | nkirkpatrick/google-python-crash-course | /lists_tuples/skip_elements.py | 524 | 3.796875 | 4 | def skip_elements(elements):
new_list = []
i = 0
y = 0
# Skip every other element in current list and write to new list
#
for i in elements:
if y % 2 == 0:
new_list.append(i)
y += 1
return new_list
print(skip_elements(["a", "b", "c", "d", "e", "f", "g... |
abe1acf8763d13d1d4ef95eb99244105018670e3 | jasonqwerty100987/DSA_21_group8 | /nqueen.py | 4,972 | 3.890625 | 4 | import random
import copy
import math
def get_random_state(n):
state = []
# Your code here
candidates = [0]*n
for i in range(1, n+1):
candidates[i-1] = i
for i in range(0, n):
choice = random.choice(candidates)
candidates.remove(choice)
state.append(choi... |
24c7e917f950aabb035f9a5d24b7792ff2638daa | dado3899/Coding-Challenge | /CodingChallenge4/Solution/Solution.py | 493 | 4.15625 | 4 | def LowestPosInt(IntList):
#Give the lowest possible positive int
Lowest=1
#Sort the List
SortedList = sorted(IntList)
#For every value in the sorted list, if it is equivilent to the lowest value that means that the lowest value exist, so we should bump up the lowest value by 1
for i in SortedLi... |
66d4307bf1378abffa78bb208388bf592c1bf871 | ShiJingChao/Python- | /PythonStart/一阶段查漏补缺/day1要求背的代码/demo3.py | 364 | 3.96875 | 4 | from datetime import datetime # 引用datetime 库
now = datetime.now() # 获得当前日期和时间信息
print(now)
now.strftime("%x") # 输出其中的日期部分
print(now.strftime("%x"))
# print("------------------")
print(now.strftime("%X")) # 输出其中的时间部分
print(now.strftime("%A"))
print(now.strftime("%x %X"))
print(now.strftime("%b %B")) |
9a52f7b370a8e787fb1f64946f0a7b059e3830ce | ktktkat/cs50-pset | /pset6/readability/readability.py | 681 | 4 | 4 | # Initialise variables
letters = 0
words = 1
sentences = 0
# Get text input
text = input("Text: ")
# Iterate over text and find markers for letters, words and sentences
for i in text:
if i.isalpha():
letters += 1
if i == " ":
words += 1
if i in {".", "!", "?"}:
sentences += 1
# ... |
6073de8000cce49a774169dbabc149cf3239de69 | Suri111200/ITI-1120 | /ITI 1120 Lab 6 - Tuples and Dictionaries/Exercise 2.py | 718 | 4 | 4 | def histo_n(x):
dictionary = {}
for val in x:
dictionary[val] = dictionary.get(val,0)+1 #adds 1 to dictionary val, creates entry if not present
return dictionary
#Main
raw_input = input('Enter a tuple : ') #Ask user to input tuple ie."(1,2,3,4,5,6)"
modified_input = raw_input.replace("(","").replac... |
20307c79d4bc28b22a167d3fd77c4c0656949b17 | 1quant/Microservices-Based-Algorithmic-Trading-System | /Storage/q_pack/db_pack/schema/risk_db_schema_builder.py | 6,855 | 3.59375 | 4 | import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import os
import q_credentials.db_risk_cred as db_risk_cred
def create_db(db_credential_info):
"""
create a new database if it does not exist in the PostgreSQL database
will use method 'check_db_exists' before creating a new dat... |
41c09b0ef1d1d9fd723ee6932aa06de04baad33b | swengeler/Autonomous-Quadcopter-Construction | /src/env/block.py | 1,870 | 3.546875 | 4 | import logging
from typing import List
from geom.shape import Geometry
class Block:
"""
A class representing a block used for construction. It could be extended to e.g. implement communicating blocks.
"""
COLORS_SEEDS = ["red"]
COLORS_BLOCKS = ["blue"]
SIZE = 15
def __init__(self,
... |
018212742ca082f2b7737c8d8b6d4e0efb97499f | maaaaaaaax/coding-dojo-python | /W1 | Fundamentals, OOP, Flask/Object Oriented Programming (OOP)/product.py | 2,067 | 4.03125 | 4 | # product.py
# declare a class and give it name User
class Product(object):
# the __init__ method is called every time a new object is created
# Price and Weight are integers; item_name, brand, and status are strings
def __init__(self, price, item_name, weight, brand):
# set some instance variables... |
d4a32be66e4e1e6f2f5a7d7a4e9a7355dfc33a03 | gsalgado2138/Module-7-Functions | /problem 2.py | 312 | 4.0625 | 4 | #giovanni salgado
#11/13/2021
#problem 2
# Write a Python function to check whether a number is in a given range. Use range(1,10).
# Print whether the number is in or not in the range.
def inrange(g):
if g in range(1,11):
print(g, 'is in the range')
else:
print(g, "is not in the range")
inrange(... |
606702cdaf6c291279f7db4b6ef6b901ffaca977 | subban358/Python | /magic_index_with_repetation.py | 647 | 3.59375 | 4 | def magic_index(lis, size):
return helper(l, 0, size-1)
def helper(l, start, end):
if end < start:
return -1
midIndex = (start + end) // 2
midValue = l[midIndex]
if midIndex == midValue:
return midIndex
leftIndex = min(midIndex - 1, midValue)
left = helper(l, ... |
4339dd9d86b44df2af5875d09d15bfa3c56f9576 | data-augur/ScrapingTablesWithBeautifulSoup | /ScrappingTablesWithBeautifulSoup.py | 1,584 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 12 14:51:53 2018
@author: sarfraz
"""
import requests
from bs4 import BeautifulSoup
#Set Headers for request to the website
header = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Sa... |
5d6af826c9b1b266abb1f7fcdb77662323fab5af | t0theheart/command-line-state | /tests/test_command_line_app.py | 5,105 | 3.65625 | 4 | import unittest
from command_line import CommandLine
from command_line.exception import CommandLineException
class TestCommandLine(unittest.TestCase):
def test_empty(self):
program = CommandLine()
program.parse_command_line('')
state = program.get_state()
self.assertEqual(state['s... |
015e6779debbe051f7421b675fc091b742bcf454 | yo16/tips_python | /文字列/SetDefault_prac.py | 594 | 3.984375 | 4 | # -*- coding:utf-8 -*-
# ディクショナリのsetdefault
# ディクショナリの参照で、
# 通常は存在しないキーを読むとエラーになるから
# 存在しないキーを読んだときにこれを返してねっていう値
# 'a'というキーが設定されていない場合は'*'を返すよう準備
dic1 = {}
dic1.setdefault('a', '*')
print( dic1['a'] )
# → *
# 設定した場合
dic2 = {}
dic2.setdefault('a', '*')
dic2['a'] = 'A'
print( dic2['a'] )
# → A
# 下記と同じ感じ
dic3 = ... |
25f58b3d905c37f7bf70435f23cb30a2aaa9ea5e | Shubham-Mate/Password-Manager | /gui.py | 7,602 | 3.515625 | 4 | import tkinter
from tkinter import Label, Entry, Button, StringVar, Listbox, ttk
import tkinter as tk
from tkinter.font import Font
# Colors
BG_COLOR = '#353b48'
BTN_COLOR = '#2f3542'
TEXT_COLOR = '#ffffff'
ERROR_BACKGROUND = '#e74c3c'
ERROR_MSG = '#d50000'
SUCCESS_BACKGROUND = '#689F38'
SUCESS_MSG = '#1... |
2a36fc0c3e8d9c51735401af277c807d716f3acb | mayelespino/code | /LEARN/python/read-file/readFileIntoList-py3.py | 116 | 3.625 | 4 | #
# This only works in python2
#
lines = [line.strip() for line in open('text.txt')]
for line in lines:
print(line) |
da1943e61ba5bf42a0c0af3aefaed55cb08e7b8b | karthik2146/karthik2146-s-repository | /pythontrail/basics/loopstatements.py | 195 | 3.953125 | 4 | def looptest():
list = [1, 2, 3, 4, 8]
for i in list:
print(i)
looptest()
def whilelooptest():
i=2
j=10
while i<=j:
print (i)
i=i+1;
whilelooptest() |
14704f99ae385af9fe68691e669426e7a9dd6f62 | Aasthaengg/IBMdataset | /Python_codes/p00001/s011215917.py | 115 | 3.828125 | 4 | m=[]
for i in range(10):
x = input()
m.append(x)
m.sort()
m.reverse()
for i in range(0,3):
print m[i]
|
41711cc207c2ebc6578ee43e3bcc8a362170b645 | analogpixel/adventOfCode2018 | /day8/code.py | 1,092 | 3.609375 | 4 | #!/usr/bin/env python
input_file = "input.txt"
input = open(input_file).readlines()[0].strip().split(' ')
total = 0
def parseData(d,i):
debug = False
global total
if len(d) == 0:
return
child_nodes = int(d[0])
meta_nodes = int(d[1])
if child_nodes == 0:
if debug: print... |
e07bb3c376f63b751c8364c8758c9524b732548a | heartnoxill/cpe213_algorithm | /dynamic_programming/warshall_4012.py | 1,480 | 3.859375 | 4 | # Warshall Algorithm
import random as r
import sys
__author__ = "Pattarapon Buathong 62070504012"
global vertices
def random_graph(vertices):
# Generate zero matrix (vertices x vertices)
matrix_random = [[0 for m in range(vertices)] for n in range(vertices)]
for i in range(vertices):
for j in ran... |
faaa8dd0a5c0784ace5052b4bbac47a1d3f64afc | Laxmivadekar/json | /saral6q.py | 411 | 3.75 | 4 | # Q6.Python object key unique key value ko access karne ka program likho?
# Example
import json
a='''{
"a": 1,
"a": 2,
"a": 3,
"a": 4,
"b": 1,
"b": 2
}'''
python_string=json.loads(a)
print(python_string)
# Output:-
# Original Python object:-
# {
# "a": 1,
# "a": 2,
# "a": 3,
# "a"... |
00225660b1a670d6eece4c9176563fbbe895327f | samkevich/Dip | /polynomial.py | 515 | 3.703125 | 4 |
class Polynomial:
def __init__(self, coeffs):
self.coeffs = coeffs
def __str__(self):
res = ""
plus = ""
i = len(self.coeffs) - 1
for i in xrange(len(self.coeffs)-1, 0, -1):
if self.coeffs[i] != 0:
res += plus + str(self.coeffs[i])+'*x^'+str... |
b4a0571a04df79031e359adfe42c516f5ef06e3b | vuamitom/Code-Exercises | /npl/SpellChecker/Sentence.py | 1,922 | 3.875 | 4 | class Sentence:
"""Contains a list of Datums."""
def __init__(self, sentence=[]):
if(type(sentence) == type([])):
self.data = list(sentence)
else:
self.data = list(sentence.data)
def getErrorSentence(self):
"""Returns a list of strings with the sentence containing all errors."""
e... |
80042b2bc8a8fdf4fcaeed863a726bf81a480b4a | bristy/HackYourself | /PE/PE105.py | 1,764 | 3.71875 | 4 | """
et S(A) represent the sum of elements in set A of size n.
We shall call it a special sum set if for any two non-empty disjoint subsets,
B and C, the following properties are true:
S(B) != S(C); that is, sums of subsets cannot be equal.
If B contains more elements than C then S(B) > S(C).
For example, {81, 88, 75, ... |
55ede2e96507e43a96f11034b8b9eefd3773f2c7 | sleepysloth17/advent-of-code-2020 | /day-03/03.py | 947 | 3.828125 | 4 | from typing import List, Generator, Tuple
from math import prod
INPUT_FILE_NAME = "day-03-input.txt"
def get_input_list() -> Generator[str, None, None]:
with open(INPUT_FILE_NAME) as input_file:
for line in input_file:
yield line.strip()
# 1 for tree, 0 for empty
def get_encountered(step: T... |
f5c0dbd69636d68340fe3fcae5a2a98a1adf09aa | shukla-abhinav/Turtle | /star.py | 184 | 3.6875 | 4 | import turtle
turtle.done()
'''
n = 20
pen = turtle.Turtle()
for i in range(n):
pen.forward(i*10)
#in clockwise
pen.right(144)
turtle.done()
'''
|
3327090e6768c994e8230747ca25519b969e6e3f | knparikh/IK | /LinkedLists/partition_linked_list.py | 296 | 3.625 | 4 | # Given a singly linked list, divide it so that for x, elements are ordered <x, =x, >x
# Dutch national flag/3 way split.
# But instead of rearranging, keep 3 lists, and keep appending node to each of them.
# Also keep head and tail of 2 lists, head of 3rd list. Stich them together at the end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.