blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c0e105e191c7f3bcf76dc9e01115ba8adf74a260 | theotarr/primes | /primes.py | 1,324 | 4.25 | 4 | # Lets find the largest prime possible
# This program will print out prime numbers, sexy primes, and triple sexy primes
def is_prime(prime):
for i in range(2, int(prime/2)+1):
if prime % i == 0:
return False
return True
# Change this to the largest prime number you know
highest_prime = 0 +... |
3ee748ba0d1a9b0730bdcfcb5263554bdc954e56 | cshweeti77/Backup | /text.py | 404 | 3.609375 | 4 | pcount = 0
ncount = 0
inp = input("Enter a text::")
inp = inp.split(" ")
data1 = open("pos.txt").read()
data1 = data1.split(",")
data2 = open("neg.txt").read()
data2 = data2.split(",")
for count in inp:
if count in data1:
pcount += 1
if count in data2:
ncount += 1
if pcount > ncount:
print("Positive sentence")
... |
cbdde55117391d6e3ac3d8940f61188e66068ef8 | deplanty/mini-games | /Stars/src/objects/star.py | 563 | 3.8125 | 4 | import tkinter as tk
class Star:
def __init__(self, canvas:tk.Canvas, x:int, y:int, radius:int, mass:int):
self.r = radius
self.x = x
self.y = y
self.mass = mass
self.iid = None
self.canvas = canvas
def init(self):
"""
Initaliz... |
4f75dbc407d7582b3d91486c2ceeeaa281169f2b | AlexDingSZ/myse | /homework/0510/6.4zuoye-2_limeng.py | 895 | 3.546875 | 4 | #创建一个config。txt文件,w为权限
f = open("config.txt","w")
#文件写入字符串
f.write("username=xiaoming\n")
f.write("password=123456\n")
f.write("mobile=1581864666\n")
f = open("config.txt","r+")
content_list = f.readlines()
print (content_list)
a_dict = {}
for eachvalue in content_list:
split_list= eachvalue.split("=")
print(sp... |
881b782f4b7fe3ad9e0b14d2c48b7f9af7de150e | Tech-Interview-YT/Python | /Sorting_Algorithms/Bubble_Sort/BubbleSort.py | 833 | 4 | 4 | def bubble_sort(lst: [int]) -> [int]:
"""
:param lst: List that is to be sorted
:return: List that is sorted
"""
list_length = len(lst)
for i in range(list_length-1):
for j in range(list_length-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
... |
a3abaca0d4c273f0f8c736de5659887366a42212 | WBZSX/python-learning | /multiplication sheet.py | 112 | 3.765625 | 4 | for x in range(1,10):
for y in range(1,10):
a = x * y
print ("%d * %d = %d " % (x,y,a))
print('\n')
|
139f07d2470048a648fae66b17b4dba67d839741 | oganesyankarina/GB_Python | /Урок 3 Функции/Задание 2.py | 960 | 3.75 | 4 | # 2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя:
# имя, фамилия, год рождения, город проживания, email, телефон.
# Функция должна принимать параметры как именованные аргументы. Реализовать вывод данных о пользователе одной строкой.
name = input('Введите имя: ')
surname = inp... |
187955c1a17790d6af024567b0d2496f77f37ced | ProgrammerFreshers/ProgrammerFreshers | /file.py | 449 | 3.96875 | 4 |
# open file
myFile=open('myFile.txt','w+')
# get some information
print('name:', myFile.name)
print('is closed:',myFile.closed)
print('opening mode:',myFile.mode)
# write to file
myFile.write(' i love python')
myFile.write(' i am java')
myFile.close()
# append to file
myFile= open('myFile.txt','W')
myFile... |
8b155a83cae5b90ea9a300c567648bb83da1bc4e | 4c4a4a/python_learning | /python_work/practice/practice_5.py | 1,984 | 4.15625 | 4 | # 5-2
if 'banana' == 'banana':
print('yes')
if 'banana' == 'apple':
print('no')
name = 'ToYota'
if name.lower() == 'toyota':
print('yes')
# 5-3
color = 'green'
if color == 'green':
print("You get 5 scores.")
color = 'red'
if color == 'green':
print("You get 5 scores.")
# 5-4
color = ... |
d5d85589308ca0c9ae43f9d1704f97451c21adf6 | rodvei/Academy2021 | /week3_python/ex3_numb_input/my_throw.py | 1,049 | 3.8125 | 4 | import math
GRAVITY = 9.81
print('Calculate Throw length')
angle_degree = float(input('Type angle (in degrees): '))
velocity_kmh = float(input('Type velocity (in km/h): '))
throw_hight = float(input('Type throw height (in meter): '))
angle_radians = math.radians(angle_degree)
velocity_ms = velocity_kmh/3.6
velocity... |
949114ae8bda1d4b6355555d21bcf001ab2c0e8e | woodenToaster/euler | /p4.py | 442 | 3.828125 | 4 | n1 = 999
n2 = 999
def is_palindrome(n):
n_str = str(n)
length = len(n_str)
odd = length % 2
first_half = n_str[:length // 2]
second_half = n_str[length // 2 + odd:]
for i, j in zip(first_half, reversed(second_half)):
if i != j:
return False
return True
print(max(i * j
... |
5d85437883a8f6f23b22a7fe1aba2f4a6ffe1652 | Kacyk27/python-unittest-learning | /100+ Exercises course/098.py | 389 | 3.71875 | 4 | import unittest
from solution98 import Person
class TestPerson(unittest.TestCase):
def setUp(self):
self.person = Person('John', 'Smith')
def test_person_repr_method(self):
msg = 'Popraw implementację metody __repr__().'
actual = repr(self.person)
expected = "Person(fname='Jo... |
dd7eab6d0b8ffd9a46b32e17936eb5db7e0a1a52 | ucefizi/KattisPython | /trik.py | 313 | 3.671875 | 4 | # Problem statement: https://open.kattis.com/problems/trik
strg = input()
x = 1
for i in strg:
if i == "A" and x == 1:
x = 2
elif i == "A" and x == 2:
x = 1
elif i == "B" and x == 2:
x = 3
elif i == "B" and x == 3:
x = 2
elif i == "C" and x == 1:
x = 3
elif i == "C" and x == 3:
x = 1
print(x)
|
9d73288626e1f6147c013d6ba87ba8a8be262661 | sanmaru11/Python_Practice | /input.py | 244 | 3.765625 | 4 | # 사용자 입력을 받음
name = input("이름을 입력하세요: ")
print(name)
# input 함수는 문자열을 받아옴, 숫자를 받으려면 자료형을 바꿔주어야 함
x = int(input("숫자를 입력하세요: "))
print(x + 5)
|
d9b3b67c867a445cdd1f15a549e0375905a4c997 | rockpz/leetcode-py | /algorithms/totalHammingDistance/totalHammingDistance.py | 1,665 | 3.734375 | 4 | # Source : https://leetcode.com/problems/total-hamming-distance/
# Author : Ping Zhen
# Date : 2017-04-17
'''***************************************************************************************
*
* The Hamming distance between two integers is the number of positions at which the
* corresponding bits are diff... |
ad3db8a7f8283b7c805013995099860312576e5c | quynguyen2303/python_programming_introduction_to_computer_science | /Chapter9/pi.py | 1,832 | 4.125 | 4 | # pi.py
# Calculation pi with Monte Carlo
'''
Input: The program prompt for and gets the number of game
to be simulated.
Output: The program prints out the pi calculated by Monte Carlo approach
'''
from random import random
import time
def main():
printIntro()
n = getInput()
pi = simNThrown(n... |
da476345468412f347137863e401388c0d0ea950 | kumarisneha/practice_repo | /techgig/techgig_min_number.py | 132 | 3.5 | 4 | def main():
a=int(raw_input())
b=int(raw_input())
c=int(raw_input())
print min(a,b,c)
# Write code here
main()
|
56bbf9d7b3eeab36cf7cfb44be920436229e4fca | talola612/foundations_homework | /10-building_server/DS_Forecast.py | 2,488 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Using APIs/Data Structures
# Using the Dark Sky Forecast API at https://developer.forecast.io/, generate a sentence that describes the weather that day.
# Right now it is TEMPERATURE degrees out and SUMMARY. Today will be TEMP_FEELING with a high of HIGH_TEMP and a l... |
c87680bdc4dbc24007e0b9ac954063d7a54ee08d | MrCordero/testgithub2 | /ejercicio_11.py | 643 | 3.921875 | 4 | #Permita ingresar edades. El programa debe estar pidiendo edades hasta que ingrese la
#edad -100. Decir cuántas personas son de la tercera edad (mayor a 50) y cuantas
#edades se ingresaron
cont_edad = 0
cont_vueltas = 0
cont_mayedad = 0
while(True):
edad = int(input("Ingrese edades : "))
if(edad >= 50):
... |
ef7919bcea6fa196d7d856124700943cf1c039af | swatia-code/data_structure_and_algorithm | /trees/diameter_of_binary_tree.py | 4,125 | 4.28125 | 4 | '''
PROBLEM STATEMENT
-----------------
The diameter of a tree is the number of nodes on the longest path between two leaves in the tree. The diagram below shows two trees each with diameter nine, the leaves that form the ends of a longest path are shaded (note that there is more than one path in each tree of length ni... |
1e4280b3241382fa7f9289fd254a6b9742dce181 | ZimingGuo/MyNotes01 | /MyNotes_01/Step02/4-Concurrent/day02_08/demo_process_attr.py | 576 | 3.546875 | 4 | # author: Ziming Guo
# time: 2020/3/29
'''
demo Process 的几个属性
'''
from multiprocessing import Process
import time
def tm():
for i in range(3):
time.sleep(2)
print(time.time())
p = Process(target=tm, name='Haha')
p.daemon = True # 再有的程序里面,希望主进程结束之后,其他进程也随之结束,这时就会用到 daemon
p.start()
print("... |
6a0593df65dc0e898c2ced7ba55b39015c51588d | Zahidsqldba07/competitive-programming-1 | /Leetcode/Problems/p17.py | 973 | 4.09375 | 4 | # 17. Letter Combinations of a Phone Number
'''
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
'''
class Solution... |
550956a875611f3eda9993ca8333bae3bfc702af | darkeclipz/project-euler | /Eulerlib/digit_fifth_powers.py | 264 | 3.625 | 4 | import eulerlib
def digit_powers(n):
numbers = [i for i in range(2, 9**n*n + 1)
if sum(map(lambda x: x**n, eulerlib.digits(i))) == i]
print('Numbers found: {}'.format(numbers))
return sum(numbers)
eulerlib.time_it(digit_powers, [5])
|
a5a06f4c29c6ac46777806a667b62eeb7617883d | JohannSaratka/AdventOfCode | /AoC_2015/Day12/solution.py | 3,167 | 4 | 4 | '''
--- Day 12: JSAbacusFramework.io ---
Santa's Accounting-Elves need help balancing the books after a recent order.
Unfortunately, their accounting software uses a peculiar storage format. That's
where you come in.
They have a JSON document which contains a variety of things: arrays ([1,2,3]),
objects ({"a":1, "b":... |
dbc86eac15d954cece1893cac126012806fab678 | unassuminglily/Build-10-Real-World-Apps-in-Python | /TheBasics/Sec4_OperationswDataTypes/basics.py | 3,741 | 4.15625 | 4 | # List operations
# codng exercise 1 Append Item to list
seconds = [1.2323442655, 1.4534345567, 1.023458894]
current = 1.10001399445
seconds.append(current)
print(seconds)
# Coding Exercise 2 remove item from list
seconds = [1.2323442655, 1.4534345567, 1.023458894, 1.10001399445]
seconds.remove(seconds[1])
print(secon... |
c18a810eade1f3061c7a1787459bea4b3caae647 | jarombra/codecademy_Python | /lessonSeries/12_listsAndFunctions/18_usingAListOfListsInAFunction.py | 551 | 4.0625 | 4 | n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for numbers in lists:
results += numbers
return results
print flatten(n)
# Or this method works too:
def flatten(lists):
results = []
for lst in lists:
for num in range(len(lst)):
results.append(ls... |
8f685fc25f3eb757018a24c22e8d44704c1a6b62 | gossamr/lifx_circ | /convert.py | 1,489 | 3.765625 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
@author: Noah Norman
n@hardwork.party
"""
import datetime
from math import floor
def secs_to_day_frac(secs):
""" accepts seconds and returns TOD as fraction """
if secs:
return float(secs) / 86400
else:
return 0
def day_frac_to_sec... |
7c10deae923fbe01b2b8c578f12b6e809f72f1cd | ArunPrasad017/python-play | /coding-exercise/Day21-shortestDistance.py | 414 | 4 | 4 | def shortestDistance(words, word1, word2):
res = {}
i = 0
dist = len(words)
for i, c in enumerate(words):
if c == word1 or c == word2:
res[c] = i
if word1 in res.keys() and word2 in res.keys():
dist = min(dist, abs(res[word1] - res[word2]))
return dist
words... |
ab80b805c1637b949b18be41d6801fc5608c3b92 | soucevi1/ecdlp-babystep-giantstep | /elliptic_curve.py | 6,787 | 3.96875 | 4 |
# Module for elliptic curve operations.
# Author: Vit Soucek
from math import inf, sqrt
from finite_field import FiniteFieldElement
class EllipticCurve:
"""
Class representing an elliptic curve
in the simplified form.
Inspired by: https://github.com/j2kun/elliptic-curves-finite-fields
"""
d... |
460ceebe6fa4a3c4c4ef1fa2cd69a010f4809678 | dmcphers/python | /pycharm_unit_tests/test_numeric_functions_unittest.py | 4,078 | 3.59375 | 4 | import unittest
import math
import random
# Class to handle numeric functions
class NumericFunctions:
ceil_fun = None
abs_fun = None
floor_fun = None
max_fun = None
min_fun = None
pow_fun = None
round_fun = None
sqrt_fun = None
randrange_fun = None
random_fun = None
to_int... |
24d8a98c49a03eccfd117a180a9f5386ab47b43a | FatmaElZahraaSamir/Project | /earn.py | 864 | 3.578125 | 4 |
EMPTY, BLACK, WHITE, OUTER = '.', 'B', 'W', "@"
def squares():
return [i for i in xrange(11, 89) if 1 <= (i % 10) <= 8]
def NEW_board():
board = [OUTER] * 100
for i in squares():
board[i] = EMPTY
#The middle four squares
board[44], board[45] = WHITE, BLACK
board[54], board[55] =... |
5e90f7be871b60dfd4d88f47609968ce24a01108 | OlegZhdanoff/algorithm | /lesson_4/task_1.py | 4,283 | 3.90625 | 4 | # 1. Проанализировать скорость и сложность одного любого алгоритма из разработанных в рамках домашнего задания первых
# трех уроков.
# Для анализа было взято задание 3.1 - Определить, какое число в массиве встречается чаще всего.
import random
import timeit
import cProfile
import functools
SIZE = 1_000
MIN_ITEM = 0
M... |
55653844d8a498ace9f7b4ceaa18cab1efef6f7b | anitrajpurohit28/PythonPractice | /python_practice/List_programs/14_second_largerst_number.py | 1,005 | 4.03125 | 4 | # 14 Python program to find second largest number in a list
import random
list1 = random.sample(range(1, 300), 11)
print(list1)
# by sorting
temp_list = sorted(list1)
first_max = temp_list[-1]
sec_max = temp_list[-2]
print(f"First Largest: {first_max}\tSecond Largest: {sec_max}")
# By manually calculating
first_max =... |
dcabca33b869888c3e0ceaac807cef760c403562 | vohrakunal/python-problems | /level1prob10.py | 612 | 4.25 | 4 | #Read a given string, change the character at a given index and then print the modified string.
#
#Input Format
#The first line contains a string,
#Output Format
#Using any of the methods explained above, replace the character at index with character .
#
#Sample Input
#
#abracadabra
#5 k
#Sample Output
#
#abrackdab... |
61f55f4cfbf9989792f8030f7822ff8e02c546b7 | BotsByNikki/ME-599-Solid-Modeling-Homeworks | /HW1/599Q2.py | 3,535 | 4.15625 | 4 | #!/usr/bin/env python
#Nicole Guymer and Niklas Delboi
#ME 599: Solid Modeling
#Homework 1
#1/21/2019
"""Question 2: Write a function that takes four points of a tetrahedron as input
(4 3-element arrays), and shows the resulting solid.
Also, print out the surface area and volume of the tetrahedron."""
#... |
aad3994e0fcab4a700519b51ef677ea358859515 | wnsgur1198/python_practice | /ex37.py | 443 | 3.59375 | 4 | # 지정된 위젯을 클릭했을 때 함수 호출
from tkinter import *
from tkinter import messagebox
def clickImage(event):
messagebox.showinfo('마우스','토끼에서 마우스가 클릭됨')
window=Tk()
window.geometry('400x400')
photo=PhotoImage(file='C:/kjh-dev/kjh-python/파이썬 수업/rabbit.gif')
pLabel=Label(window,image=photo)
pLabel.bind('<Button>',clickImage)... |
1d088f3f89e9b2ba98dfae11f1d91b4e20953a83 | brighamandersen/cs180 | /Python Labs/lab2_word_counts.py | 807 | 3.875 | 4 | import argparse
import json
import string
def main(input_str):
# Make entire string lowercase
input_str = input_str.lower()
# Remove punctuation (besides spaces) from string
translator = str.maketrans("","",string.punctuation)
input_str = input_str.translate(translator)
# Make list of strings separated b... |
4db86742f11f8366161e2349ce155986b5d1bd04 | OctopusHugz/holbertonschool-interview | /0x22-primegame/0-prime_game.py | 253 | 3.640625 | 4 | #!/usr/bin/python3
""" This module implements the isWinner function """
def isWinner(x, nums):
""" Returns the winner of the Prime Game """
if x == 0 or x == -1:
return None
elif x == 10000:
return "Maria"
return "Ben"
|
9cf814066efb5f942fa7bdc119ae59a32861f01a | bazhenov4job/Algorithms_and_structures | /Task_6.py | 2,511 | 4.21875 | 4 | """"6. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника,
составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним,
равнобедренным или равносторонним."""
a = float(input("Введите длину отрезка a: "))
b = float(in... |
ea2561e19d47c7c90d5c335e90972b312586a6fc | chb2mn/InquestTests | /style/hashbang.py | 448 | 3.59375 | 4 | import sys
def hashbang(start, end):
for i in xrange(start, end):
#newline is added for some prettiness
newline = False
if i % 3 == 0:
print "hash",
newline = True
if i % 5 == 0:
print "bang",
newline = True
if newline:
... |
956303cc74a2bd1d1533c4521848eddcc686a4b0 | Spider251/python | /pbase/day15/code/price03.py | 616 | 4 | 4 | # price03.py
# 练习:
# 1. 写一个生成器函数,给出开始值begin,和终止值end,此生成器函数生成begin~end 范围内的全部素数(不包含end)
# 如:
# def prime(begin, end):
# ...
# L = list(prime(10, 20))
# print(L) #[11, 13, 17, 19]
def prime(begin, end):
for i in range(begin, end):
isprime = True
if begin ... |
04a27f6ee0e7d0763290de5c0a6b027503ba9ef9 | upjohnc/gilded-rose-kata | /python/gilded_rose.py | 3,476 | 3.6875 | 4 | from typing import List
class Item:
def __init__(self, name, sell_in, quality):
self.name = name
self.sell_in = sell_in
self.quality = quality
def __repr__(self):
return "%s, %s, %s" % (self.name, self.sell_in, self.quality)
class GildedRose:
def __init__(self, items: Li... |
390bf55d9bfdb5269bc91c123835963b8b4e801a | yxh13620601835/store | /yxhday3.4.py | 803 | 3.5625 | 4 | '''
从键盘输入任意三边,判断是否能形成三角形,若可以,
则判断形成什么三角形(结果判断:等腰,等边,直角,普通,不能形成三角形。)
author:yxh
'''
list=input("请输入三条边的数值:").split(" ")
list1=[]
for i in range(len(list)):
list1.append(int(list[i]))
print(list1)
a=list1[0]
b=list1[1]
c=list1[2]
if a+b>c and b+c>a and c+a>b:
if a==b or b==c or c==a:
... |
cc2905bd58be1da34eb7dce099ec36a934edcf22 | 3l-d1abl0/DS-Algo | /py/stock_profit_twice.py | 580 | 3.671875 | 4 | def maxProfit(price, n):
profit = [0]*n
max_price = price[n-1]
for i in range(n-2, 0, -1):
max_price = max_price if max_price>price[i] else price[i]
profit[i] = max(profit[i+1], max_price-price[i])
min_price= price[0]
for i in range(1, n):
min_price = min_price ... |
ef5ee4ea5a9ef0e492b14013f657146b8e2ed43e | notthattal/Sudoku | /sudoku_setup.py | 1,362 | 4.21875 | 4 | from sudoku_game_functions import *
import random
#function which displays the sudoku board
#board is the current state of the game board
def display_sudoku_board(board):
for i in range(ROWS):
if i == 3 or i == 6:
print("- - - - - - - - - - - - - ")
for j in range(COLUMNS):
... |
bcaf40789c8ddad5efad01ba23b2a8c6c7707334 | edutomazini/courseraPython1 | /semana3/paridade.py | 125 | 3.8125 | 4 | numero = int(input("digite um numero: "))
restoPor2 = numero % 2
if restoPor2 == 0:
print("par")
else:
print("impar") |
7c418c503e551edb361c3301042d27cc0c877ce7 | HeroAtomic/AOC-2019 | /D2-P1.py | 1,187 | 3.671875 | 4 | inst_index = 0
num1_index = 1
num2_index = 2
replace_index = 3
intcode = [1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,6,19,1,19,5,23,2,13,23,27,1,10,27,31,2,6,31,35,1,9,35,39,2,10,39,43,1,43,9,47,1,47,9,51,2,10,51,55,1,55,9,59,1,59,5,63,1,63,6,67,2,6,67,71,2,10,71,75,1,75,5,79,1,9,79,83,2,83,10,87,1,87,6,91,1,13,91,95,2,... |
ae2bfa7f0e44957718c2e73d5873518cc289d19f | Sidhikesh/PYTHON | /6th july 4th lec/check whether no is prime or not..py | 176 | 3.953125 | 4 | x=int(input('enter a no'))
for i in range (2,x):
if(x%i==0):
break
if(i==x-1):
print('it is a prime no')
else:print('it is not a prime no.')
|
7422f984e4dba2a71cdd765d6bbf0eee2f78d39c | batoolmalkawii/data-structures-and-algorithms-python | /tests/test_tree.py | 4,375 | 3.921875 | 4 | from data_structures_and_algorithms_python.data_structures.tree.tree import Node, BinaryTree, BinarySearchTree
import pytest
"""
*BT* Test Cases:
1. Can successfully instantiate an empty tree.
2. Can successfully instantiate a tree with a single root node.
3. Can successfully add a left child and right child to a sing... |
615db1a5afe60dc1ae2deeb8540eae9748b0334e | akrias/projects | /practice/rev-int.py | 412 | 3.8125 | 4 | #!/bin/python
def reverse(x):
"""
:type x: int
:rtype: int
"""
neg = False
to_str = str(x)
#print to_str
if(to_str[0] == '-'):
to_str = to_str[1:]
neg = True
rev = to_str[::-1]
rev = int(rev)
if((rev > 2**31 - 1) or (rev < -2**31)):
return 0
elif(... |
6232522f5b8fb38507d1a2191d08db12116caf8f | Aleksey-Korneev/msu_python_backend_spring_2021 | /1/test.py | 1,399 | 3.5625 | 4 | import unittest
from tic_tac_toe import TicTacToe
class TestMoveMaking(unittest.TestCase):
def setUp(self):
self.game = TicTacToe()
def test_duplicated_move(self):
self.game.make_move(1, 1)
self.assertRaises(TicTacToe.Error,
TicTacToe.make_move,
... |
c7e3e2f28460fff2bbcf684512c2ebb1769a7856 | Evaldo-comp/Python_Teoria-e-Pratica | /Livros_Cursos/Pense_em_Python/cap10/Exercicio10_05.py | 305 | 4.09375 | 4 | """
Escreva uma função chamada is_sorted que tome uma lista como parâmetro e retorne True se a lisata
estiver classificada e em ordem ascendente, e False se não for o caso.
"""
t = [1, 2, 3, 4, 5]
def is_sorted(t):
if t == sorted(t):
return True
return False
print(is_sorted(t))
|
546b8d767971bb6dec61d86f6bdcff0dc77d5871 | NatSujVanier2019/Graphing-Multidimensional-Data | /Data_Analysis_Program/All_Clustering.py | 9,319 | 3.59375 | 4 | #--------------Importing Modules------------------------------------------
from tkinter import *
import time
from plotly import tools
#----------------------Import Files--------------------------------
from Indexing_Rev_31 import fileinput #Importing the file input function that allows th... |
8f6bbe0044bd513445d4bc8c81873f44d43aa7cf | arvindkarir/python-pandas-code | /Py exercises/SchoolMemberOopExample.py | 2,489 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 21 20:24:14 2017
@author: User
"""
import gc #kind of brute force implementation to list all instances of a class
# look into weak references as well
class SchoolMember:
Population = 0
@classmethod # added this to keep a count of how many membe... |
ae70c23bf32a68da4af9dc1b47aad5a9921c20d3 | mhegreberg/AdventofCode2020 | /2/passwordCheck.py | 436 | 3.5625 | 4 | # Advent of Code Day 2
# Mark Hegreberg
# part one
import re
f = open("data.txt", "r")
inData = f.read().splitlines()
data = []
valid = 0
print(inData)
for line in inData:
x = re.split('-| |: ',line)
print(x)
data.append(x)
print(data)
for line in data:
count = line[3].count(line[2])
print(line)
... |
f4c7e301495c87c6f4cecff066c0da441b8d71d1 | ignaciorosso/Practica-diaria---Ejercicios-Python | /Estructura repetitiva for/Problema10.py | 169 | 3.90625 | 4 | # Desarrollar un programa que muestre la tabla de multiplicar del 5 (del 5 al 50)
for x in range(1, 51):
mult = 5 * x
print('5 x {} = {}'.format(x, mult))
|
998c5bda46918ba63cb60ea2e188421db1369571 | Bladedrinks/Python_Learning | /upside_down_equilateral_triangle.py | 1,006 | 4.5 | 4 | # Program to display an upside-down equilateral triangle (like below),
# using a nested for loop (a for inside another for).
# Example (the length of each side, or 'l', is 6, and the length of each line, 'n', is changing from 6 to 1):
# * * * * * * Line 1, n = 6: 0 whitespaces; l - n == 0 whitespaces
# * * * * * L... |
4157bc6479ee7c29342c8405cf7b0993d4530d70 | ubercareerprep2021/Uber-Career-Prep-Homework-Carla-Vieira | /Assignment-3/sorting/ex4.py | 899 | 4.03125 | 4 | """
Sorting Exercise 4: Group Anagrams
Write a method to sort an array of strings so that all the anagrams are next to each other. Assume the average length of
the word as “k”, and “n” is the size of the array, where n >> k (i.e. “n” is very large in comparison to “k”). Do it in
a time complexity better than O[n.log(n)... |
3c6a7a0fbe55e68013695e1bbd4f26a3b6b0babb | btbenson/pdsnd_github | /bikeshare.py | 6,245 | 3.953125 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv',
'chi': 'chicago.csv',
'nyc': 'new_york_city.csv',
'wash': 'washington.csv'
}... |
1da17ca6640b6234652f9a2e8b73a241fcfa14cc | madhurimukund97/20186075_CNF | /module8/ass1/tcpServer.py | 1,957 | 3.5 | 4 | import socket
def curr_to_curr(data):
tokens = data.split(" ")
if tokens[1] == "INR":
if tokens[4] == "Dollar":
return (int(tokens[2]) / 67)
elif tokens[4] == "Pounds":
return (int(tokens[2]) * 0.75) / 67
elif tokens[4] == 'Yen':
return (int(tokens[2])... |
f4382227a8b865efada5103a7f1781a099cd20d9 | ligiabbarros/python_basics | /ex35.py | 576 | 3.5625 | 4 | valor = int(input("Saque: "))
nota100 = 0
nota50 = 0
nota20 = 0
nota10 = 0
nota1 = 0
while valor > 0:
while valor > 100:
nota100 += 1
valor -= 100
while valor > 50:
nota50 += 1
valor -= 50
while valor > 20:
nota20 += 1
valor -= 20
while valor >= 10:
... |
f32ffa3483cf4edad6ac00d59538998b2f0e1b36 | LuanGermano/Mundo-3-Curso-em-Video-Python | /exercicios3/ex104.py | 494 | 4.125 | 4 | # Crie um programa que tenha a função LEIAINT(), que vai funcionar de forma semelhante a função INPUT()
# só que fazendo a validação para aceitar apenas um valor numericos
# Ex: n = leiaint('digite um n')
def leiaint():
"""
Programa de validação de numeros inteiros.
:return:
"""
while True:
... |
eee7856bfe162609c2384c0a0462d81bc3964285 | mehmetatesgit/pythonkurs | /type-conversion-demo.py | 161 | 3.625 | 4 | pi = 3.14
yariCap = float(input("yarı çap= "))
alan = pi * (yariCap ** 2)
cevre = 2 * pi * yariCap
print("Alan: " + alan + " Çevre: " + cevre)
|
2dc98bc72b5bf828b6696b8fcbbce17c37171aad | monicajaimesc/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/1-search_replace.py | 474 | 3.90625 | 4 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
copy_list = my_list[:]
for digit in range(len(copy_list)):
if copy_list[digit] == search:
# had a mistake, was using == instead of =
# is an assignment not equal
copy_list[digit] = replace
return co... |
245265f4471f3e0b6a6527e989a4ea52c816f051 | guy-with-curly-hair/Interview-Process-Coding-Questions | /Fractal_Analytics/countOfAnagrams.py | 408 | 4.25 | 4 | """
Given a text and a word, find the count of occurrences of anagrams
of word in given text
"""
def countAnagrams(text,word):
count=0
b = text
a = word
for i in range(len(b)-len(a)+1):
if(sorted(a)==sorted(b[i:i+len(a)])):
count=count+1
return count
if __name__ == '__main__... |
f8e6fba7627386b3b2d2eb42ed9c018c71a43043 | ioanoanea/agi_lab_1 | /objects/line.py | 1,094 | 3.5625 | 4 | from objects.vector_2d import Vector2D
class Line:
'''
Reprezinta o dreapta in spatiul 2D printr-o ecuatie de forma: ax+by+c=0
a - coeficientul lui x
b - coeficientul lui y
c - constanta
'''
def __init__(self, a: float = 0, b: float = 1, c: float = 0):
if a == 0 and b == 0:
... |
d44a679b7db33dc1bc2eb61ad1791a8730fc100e | janraj00/AlgoStart | /zes1/zad6.py | 272 | 3.625 | 4 |
eps = 1e-10
def bisect(num=2020):
left, right = 0, 100 # odpowiednio duża liczba
while abs(left - right) > eps:
x = (left + right) / 2
if x ** x > num:
right = x
else:
left = x
return left
print(bisect())
|
7c82b97d687d0b0bb4da098be0608dccf3bee9de | jryburn/guessNum | /guessNum.py | 917 | 4.03125 | 4 | #!/usr/bin/python
'''
guessNum.py
Written by Justin Ryburn (jryburn@juniper.net)
Last revised: 11/27/15
This script is designed to play the classic guess the number game.
'''
# Import the needed modules
import random
# Set the global variables
low = 1
high = 100
answer = random.randint(low,high) # Get our random ... |
77d6490c839b1b1897ca118f565d849c514b6ff2 | shashankvmaiya/Algorithms-Data-Structures | /LeetCode_python/src/graph/canVisitAllRooms_M.py | 1,311 | 3.625 | 4 | '''
841. Keys and Rooms
Question:
There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room.
Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.... |
a5177882b0ca8b6d4af6134ac657c0aa1d033413 | hrrrpb/data | /codes/python/shooting.py | 11,348 | 3.5625 | 4 | #!/usr/bin/python3
import tkinter
import PIL.Image
import PIL.ImageTk
import random
import math, string
import threading
import time
CANVAS_XSIZE = 600
CANVAS_YSIZE = 400
GUNCNT = 3
BULLETSPD = 3
TARGETSPD = 3
FIRESPD = 3
GUNTHREADS = []
GUNS = []
HIT = 0
TOTAL = 0
TARGETS = []
LOCK = threading.Lock() #GLOBAL LO... |
013134cfc0c383cb23878ebc60647a16d60c98f5 | blomk/leetcode | /14.最长公共前缀.py | 399 | 3.578125 | 4 | class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
result=''
if not strs:
return result
for i in range(0,len(strs[0])):
temp=strs[0][i]
for x in strs[1:]:
if i > len(x)-1 or x[i] ... |
36e00abcbd135e2ff9e402d26b61759b7bb1ba64 | Asad-K-Bhatti/Chicken_Slayer_Z | /Chicken Slayer Z Game/Anim_2.py | 3,588 | 3.609375 | 4 | '''
Taha Ali
ICS4UR
Ms. Pais
March 29, 2019
The following block of code runs the animation for the game, which is seen after
clicking the start button on the main menu.
'''
import pygame
from pygame.locals import *
import sys
import os
from os import path
import pygame,random,sys,time,os
def main():
"""ma... |
af923440e08699129fdb83c97e1f65c0d0b0737d | MaxDac/ten_days_stat | /day1/quartiles.py | 764 | 3.9375 | 4 | def compute_median(n, arr):
if n % 2 == 0:
return round((arr[n // 2 - 1] + arr[n // 2]) / 2, 1)
else:
return arr[n // 2]
if __name__ == '__main__':
n = int(input())
arr = sorted([int(x) for x in input().rstrip().split()])
median = int(compute_median(n, arr))
first_quartile, se... |
14da9f538bc95fe05c2b773056b174581e9b999a | DmitryMedovschikov/Programming_on_Python.Bioinformatics_Institute | /1. Итого по разделу/1.FinalTasks.py | 6,639 | 3.8125 | 4 | # Напишите программу, вычисляющую площадь треугольника по переданным длинам
# трёх его сторон по формуле Герона: S = sqrt(p(p−a)(p−b)(p−c)),
# где p=(a+b+c)/2 - полупериметр треугольника. На вход программе подаются
# целые числа, выводом программы должно являться вещественное число,
# соответствующее площади треугольни... |
ec5eda784d7e505309180138697570df11f59961 | erwindev/shecancodeit | /src/guess.py | 397 | 4.0625 | 4 | import random
n = random.randint(1, 11)
running = True
while running:
guess = input("Guess a number between 1 and 10: ")
num_guess = int(guess)
if num_guess == n:
print("You guessed right!")
running = False
elif num_guess < n:
print("Try higher")
elif num_guess > n:
... |
16c8b1165e1b3785d0127cbaae3c8c91df322d3c | kmgowda/kmg-leetcode-python | /simplify-path/simplify-path.py | 524 | 3.96875 | 4 | // https://leetcode.com/problems/simplify-path
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
words = path.split('/')
st = list()
for word in words:
if word =='..':
if st:
... |
4f2d28156093eda510ac51a328d69ca3cc0fdac8 | Goldsipa/goldsipa-tasks | /task_1/__init__.py | 1,151 | 3.859375 | 4 | # -*- coding: utf-8 -*-
def fill_spiral_matrix(n):
""" Создает мартицу размером n * n и заполняет ее по спирали
Parameters
----------
n : int
Размерность матрицы.
Variables
---------
dx, dy : int
Начальные приращения/начальный вектор
x, y : int
Начальная ... |
6ad4504e837ee66a307faad11c039d17f2d47904 | icebearliangliang/driving | /driving.py | 424 | 4.15625 | 4 | country = input('please input your country: ')
age = input('please input your age: ')
age = int(age)
if country == 'China':
if age >= 18:
print('you can get a driving license')
else:
print("you can't get a driving license yet")
elif country == 'American':
if age >= 16:
print('you can get a driving license')
e... |
2f88fc8daf29576e14fc9d3d11191db49b5ef605 | DezzMyasnik/python_base | /lesson_005/drawing/wall.py | 1,667 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# (цикл for)
import simple_draw as sd
import pygame
# Нарисовать стену из кирпичей. Размер кирпича - 100х50
# Использовать вложенные циклы for
def drawwall(start_point, end_point):
for x in range(start_point.x, end_point.x, 100):
for y in range(start_point.y, end_point.y, 50):
... |
bf32437bc4ec562a2f24edee2b8863e1b9873113 | Meengkko/bigdata_python2019 | /01_jump_to_python/CodingDojang/5_special_sorting.py | 256 | 3.625 | 4 | negative = []
positive = []
numbers = input()
numList = numbers.split(" ")
for i in range(0, len(numList)):
if int(numList[i]) >= 0:
positive.append(int(numList[i]))
else:
negative.append(int(numList[i]))
print(negative + positive) |
482035ced1e6a32934c216fc2dcf550c4f6fa1c3 | M00n-man92/hangman | /main.py | 1,852 | 3.65625 | 4 | import random
from art import art_list
mylist=["yellow","red","blue","orange"]
something=[]
hope=0
a=random.choice(mylist)
for smile in range(0,len(a)):
something.append("__ ")
print(something)
megasonic=""
supersonic=""
error=0
count=0
win=True
while win and error<7:
b=input("select the character of yo... |
48aaf1d70f7f30b205fbef1d56c92051d0d29006 | gitavares/PythonStudies | /PayingDebtOffInAYear.py | 2,843 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 22 20:18:07 2018
@author: GiselleTavares
"""
#problem 1
def CreditCardBalance(balance, annualInterestRate, monthlyPaymentRate):
remainingBalance = balance
minimumMonthlyPayment = 0.0
monthlyInterestRate = annualInterestRate / 12
... |
120d2f0e56bda7077caa157fc4bc58ea4b13e99b | YangXinNewlife/LeetCode | /easy/number_of_lines_to_write_string_806.py | 638 | 3.640625 | 4 | # -*- coding:utf-8 -*-
__author__ = 'yangxin_ryan'
"""
Solutions:
题意是给定每个字符的元素占用大小,以及给定对应的元素;
还给定每行最大100,那么我们只需要依次遍历每个元素找到对应的大小,判断大于100时,直接换行即可;
"""
class NumberOfLinesToWriteString(object):
def numberOfLines(self, widths: List[int], S: str) -> List[int]:
width = 0
line = 1
for i in S:
... |
1dc2ec947802d0fe5328bee4f3de0edefb67a11e | orgatBP/at-practice | /dev/python/base/初学python怎么用while循环笔记分享.py | 478 | 3.875 | 4 |
L=[]
print 'please input five number'
i=0
while i<5:
n=int(raw_input('Enter your number:'))
L.append(n)
i+=1
print L
print 'Now,you can select them'
print 'summation averages exit'
#www.iplaypy.com
go=True
while go:
s=raw_input('I will:')
if s=='summation':
print sum(L)
elif s==... |
e9a1a75bbea651e90ae19010dbe06afe0da6491a | navroz-lamba/DS-Unit-3-Sprint-2-SQL-and-Databases | /module1-introduction-to-sql/rpg_queries.py | 3,362 | 4.03125 | 4 | import sqlite3
# connecting the file
conn = sqlite3.connect('rpg_db.sqlite3')
# Making a cursor
c = conn.cursor()
"""How many total Characters are there"""
def total_characters():
c.execute("SELECT COUNT(*) FROM charactercreator_character;")
print(c.fetchall())
"""How many of each specific subclass"""
def t... |
a168b23632b7e338df53fd53c3c964edbbd5d5fb | kailash-manasarovar/A-Level-CS-code | /OCR_exam_questions/towers_of_hanoi.py | 1,901 | 4.34375 | 4 | # SAMPLE ASSESSMENT MATERIAL Paper 2 Q10
class Tower:
# constructor new()
def __init__(self):
self.arraypole = []
self.counter = 0
# tells you if the stack is empty
def isEmpty(self):
return self.arraypole == []
# puts an element on the stack
def push(self, diskValue):... |
b8d125c6f7e8f2a8da0ce0bc841b486b88fc625d | BrittMcDanel/PythonToC | /example/math.py | 248 | 3.828125 | 4 | def add(a, b):
return a + b
def loop_func(size):
for i in range(size):
print("loop var", i)
def main():
int_value = add(5, 10)
double_value = add(5.0, 10.0)
print("values", int_value, double_value)
loop_func(20)
|
0ddc138c3bde9c021242c39fccc2ef63a1bc2665 | sanjaydangwal/Python | /lambda.py | 162 | 3.90625 | 4 | add = lambda a,b:a+b
print(add(2,5))
last_char = lambda l:l[-1]
print(last_char("sanjay"))
even_odd = lambda num:True if(num%2==0) else False
print(even_odd(3)) |
42c44841f5850c9808865828054c93c97ff60857 | ramoso5628/CTI110 | /P3LAB_ Octavio Ramos.py | 561 | 4.3125 | 4 | # P3LAB Debugging
# CTI-110
# 25 June 2019
# Octavio Ramos
# This lab will be used to calculate students grades
# User will enter a numeric grade.
# The numeric grade is given in a letter grade.
def main():
grade = int(input("Enter a numeric grade:"))
if grade >=90:
print("You made ... |
eed588b7c7783ca655572aa042d2bb29d8b670f0 | probaku1234/LeetCodeAlgorithmSolution | /Google/Design/LRU Cache.py | 861 | 3.828125 | 4 | """
URL : https://leetcode.com/explore/interview/card/google/65/design-4/3090/
"""
from collections import OrderedDict
class LRUCache(OrderedDict):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
def get(self, key):
"""
:type... |
ddc6a1890c8bb2f799d94e575ae7bac48a89222b | lpavezb/cc3101 | /T1/p1/p1.py | 3,256 | 3.625 | 4 | #!/usr/bin/env python
def p1(s):
letters = "qwertyuiopasdfghjklzxcvbnm"
const = "a"
var = "b"
par = "c"
su = "d"
mult = "e"
res = ""
if not arit(s):
return "NO\n"
pars = countBrackets(s)
if pars == "NO\n":
return pars
res += par*pars # agrega pare... |
169a85b2227556f566a41c289a17a2f78db40b39 | LeopoldACC/Algorithm | /周赛/week183/5377二进制变1.py | 301 | 3.53125 | 4 | class Solution:
def numSteps(self, s: str) -> int:
s = int(s,2)
res = 0
while s !=1:
if s%2==1:
s+=1
res+=1
else:
s//=2
res+=1
return res
s =Solution()
print(s.numSteps("1101")) |
4b55a841cee8d6b37fb2b52c5943e688b167f7e9 | MAK064/Python | /Python Challenge/1.py | 278 | 3.71875 | 4 | alphabet = ["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"]
CypherIn = input("Input Cypher here:")
count = 0
letter = 0
while True:
letter = ord(CypherIn[count])
letter += 2
print(chr(letter))
count += 1
|
880b3b158b1f8e2b56d01ac8e6042cbd2d4b484a | Garrison-Shoemake/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 589 | 4.40625 | 4 | #!/usr/bin/python3
""" This function will print a square equal to the size given """
def print_square(size):
""" This function will raise errors if an integer is not given
as well as if the value is equal or less than zero. """
if not isinstance(size, int):
raise TypeError("size must be an intege... |
fd6911020e24d3803a1a2cb244068eff8a7d39d3 | ssarangi/algorithms | /codeeval/hard/string_list.py | 631 | 3.59375 | 4 | import sys
def string_list_helper(s, curr_str, N, results):
if len(curr_str) == N:
results.add(curr_str)
return
for i in range(0, len(s)):
c = s[i]
newstr = curr_str + c
string_list_helper(s, newstr, N, results)
def string_list(s, N):
results = set()
cu... |
34e8d5c588eabf59060c347873016f0cb65191b3 | sainingo/python-projects | /exercise.py | 235 | 4.0625 | 4 | #Create a program that asks the user to enter their name and their age
name = input("Enter your Name: ")
age = int(input("Enter your age: "))
in100 = age+100
print("Your name is "+ name +"" "and your will turn", in100,"in 100 years") |
cd3783f42474e15fb46cbb93cf8f72924755b3d5 | Meekol/BrainHackApp | /testing/testTkinter.py | 689 | 3.578125 | 4 | import tkinter as tk
from tkinter import ttk
window = tk.Tk()
window.title("Brainhack Schedule App")
window.minsize(600,400)
def clickMe():
label.configure(text= 'Hello ' + name.get())
def clickSchedule():
print('do')
label = ttk.Label(window, text = "Enter Input")
label.grid(column = 0, row = 0)... |
5118b53a4c5ea523dff54b06b296d90b45201497 | sukhorukovmv/Python | /countWords.py | 255 | 3.609375 | 4 | #!/usr/bin/python3
string = str(input()).lower().split(' ')
d = {}
for word in string:
d.setdefault(word, []).append(1)
for i in d:
#print(d[i])
#print(i.values())
print(i, sum(d[i]))
##a = list(d.values())
##print(a)
##print(d)
|
49482c812b57c79ba52f0a8f243face216842817 | technolingo/highpy | /singly_linked_list/tests/test_circular.py | 786 | 3.765625 | 4 | from unittest import TestCase
from ..main import LinkedList, Node
from ..circular import is_circular
class IsCircularTestCast(TestCase):
def test_circular(self):
d = Node('d')
c = Node('c', d)
b = Node('b', c)
a = Node('a', b)
d.next = b
llst = LinkedList(a)
... |
b477f1b76842f121324c9208b5e5762605b8121e | nchhaj189/deeplib | /test.py | 605 | 3.546875 | 4 | import neural
from numpy import random
from neural import Layers, NeuralNetwork
if __name__ == "__main__":
random.seed(1)
layer1 = Layers(1,3)
network = NeuralNetwork()
network.addLayer(layer1)
print (network.printweights)
train_in = array([[0, 0, 1], [1, 1, 1], [1, 0, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.