blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c0a28104532f473f5aa69b00e9fbe995e1a26a53 | lirixiang123/algorithm | /src/笔试面试/quick.py | 570 | 3.59375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/10/11 20:57
# @Author : lirixiang
# @Email : 565539277@qq.com
# @File : quick.py
l = input()
i = 0
j = len(l)-1
def quick(l,i,j):
if i >= j:
return l
mid = l[i]
low = i
high = j
while i < j:
while i < j and mid <= l... |
202c25b36c6f831f4e4d63039423a9fe8a6414a0 | Vk-Demon/vk-code | /ckbegs219.py | 85 | 3.546875 | 4 | fnum=int(input())
facnum=1
for i in range(1,fnum+1):
facnum=facnum*i
print(facnum)
|
e72916a7e2c630124b07c03bdd88d019445cc0f8 | ajayrot/Python7to8am | /Datatypes/Demo16.py | 309 | 3.828125 | 4 |
l1 = [10,20,30,40,50,60,70,10,5,30,50]
print(l1) # [10,20,30,40,50,60,70,10,5,30,50]
print(type(l1)) # <class 'list'>
print(len(l1)) # 11
print("==========================")
s1 = set(l1) # list is converting into set
print(s1) # {20,10,5,40,30,50,60,70}
print(type(s1)) # <class 'set'>
print(len(s1)) # 8
|
a400662561905e6b4d250328986bca173f3c8159 | maykjony90/py3_projects | /learning_python/test_pys/student.py | 817 | 4.21875 | 4 | # structure dosyasindan Student yapisini(kavramini)
# yukluyorum. Boylece ogrenci kavrami bu baglamda
# bilinen bir kavram haline geliyor.
from structure import Student
# ogrenci kayitlarini tutmak icin bir liste olusturuyorum
students = []
# kullanicidan kac tane kayit alcagimi belirliyorum
for i in range(2):
na... |
9298e544281269ac71f8d7d9a27c1d3ced529179 | lyh71709/00_Skill_Building | /02_input_math.py | 528 | 4.15625 | 4 | # get input
# ask user for name
username = input("What is your name? ")
# ask user for two numbers
integer_1 = int(input("What is your favourite number? "))
integer_2 = int(input("What is your second favourite number? "))
# add numbers together
addition = integer_1 + integer_2
# multiply numbers together
multiply =... |
c0b95b7a2d57a21e96c370c9a26f70849b29f919 | cupofteaandcake/CMEECourseWork | /Week2/Code/dictionary.py | 1,834 | 3.53125 | 4 | #!/usr/bin/env python3
"""This script creates a dictionary called taxa_dic,
in which the species in taxa are organised into sets based on their taxa"""
__appname__ = 'dictionary.py'
__author__ = 'Talia Al-Mushadani (ta1915@ic.ac.uk)'
__version__ = '0.0.1'
__license__ = "License for this code"
taxa = [ ('Myotis luci... |
6e55b13ad93090eb58f9f071bfeaa3be3cc2cb2f | TD0401/pythonsamples | /src/io/myacademy/pythontut/64.py | 322 | 4.09375 | 4 | #The following prints Hello, checks if 2 is greater than 1 and then breaks. Therefore hi is not printed.
#please replace break with something so that both Hello and Hi is printed repeatedly
while True:
print("Hello")
if 2 > 1:
#break
pass
print("Hi")
#pass allows to move on to next stateme... |
001584034d2785d6c5426a999956d79e3850260f | stlachman/Sprint-Challenge--Data-Structures-Python | /names/names.py | 7,886 | 4.3125 | 4 | import time
import sys
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
"""Wrap the given value in a ListNode and insert it
after this node. Note that this node could already
have a next node it is point to."""
def insert_after(... |
302a8cc2d380f4b582ef0294dabb0011e99a2f64 | zjuzpz/Algorithms | /LargestNumber.py | 765 | 4.03125 | 4 | """
179. Largest Number
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
"""
from functools import cmp_to_key... |
f751255e8ee91dee0935edc4b0c0ef84a6c93521 | shankar7791/MI-10-DevOps | /Personel/Sandesh/Python/Practice/10march/1prog.py | 2,578 | 4.40625 | 4 | #Program 1 : write a menu driven Program to
# Perform following operations
# 1. Length of String
# 2. Reverse String
# 3. Check Palindrome or not
# 4. Check Symmetrical or not
# 5. Check Permutations and combination
# 6. Check two strings are anagram or not
# 6. Exit
# str = input("Enter a string : ")
def lenth(str... |
6cd1cb13bab20d8994b08c7675ddb565c832782e | ursu1964/algorithms-data_structures-python | /algorithms/binary_search/contains.py | 432 | 3.8125 | 4 | def contains(target, source):
if len(source) == 0:
return False
mid_idx = (len(source) - 1) // 2
if source[mid_idx] == target:
return True
elif source[mid_idx] > target:
return contains(target, source[ :mid_idx])
else:
return contains(target, source[mid_idx + 1:])
... |
73fad4071d7ae108133c3512796f392ddd3881ca | rheee5/practice | /practice_1.py | 6,649 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 4 13:12:36 2017
@author: Edwin
"""
hand = {'c': 1, 'o': 1, 'f': 2, 'e': 2}
wordList = ['coffee', 'cat', 'rhee', 'rapture', 'rap', 'chayote']
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that h... |
fc81510f61a48004f71721e40d08ffb2a43f5a98 | paulkaefer/vigenere.py | /vigenere.py | 2,788 | 4 | 4 | #
# vigenere.py
#
# Paul Kaefer
# 2/23/2012
#
# Python implementation of the Vigenere Cipher.
#
# Information on the Vigenere Cipher may be found at
# http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher
#
# lowercase: a=97; z=122
# uppercase: A=65; Z=90
def number_value(letter):
#
# INPUT: a s... |
3eb8ddf8e665b67b8e43cbc9a0088db6fc8093a2 | cvsnraju/LeetcodePython | /70ClimbingStairs.py | 831 | 3.953125 | 4 | # 70. Climbing Stairs
# Easy
# You are climbing a stair case. It takes n steps to reach to the top.
# Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
# Note: Given n will be a positive integer.
# Example 1:
# Input: 2
# Output: 2
# Explanation: There are two ways to... |
0adad9cf7a15d51140adfb007fb9f4c4bce12392 | AuwoFu/Compiler_MINI-Lisp | /main.py | 8,330 | 3.984375 | 4 | import math
import operator as op
## type
Symbol = str # A Scheme Symbol is implemented as a Python str
Number = (int, float) # A Scheme Number is implemented as a Python int or float
List = list # A Scheme List is implemented as a Python list
Boolean = bool
## parser
def parse(program: str):
# read input &... |
da3cb9488ce9f776581090692fcebda0d0334351 | pistolilla/jupyter | /sklearnvarios/gradient_descent.py | 1,886 | 3.671875 | 4 | # %%
import numpy as np
import matplotlib.pyplot as plt
# %%
X = np.random.rand(100, 1)
X.shape
# %%
y = 4 + 3 * X + np.random.randn(100, 1) / 10
y.shape
# %%
plt.plot(X, y, 'b.')
## Matrix approach
# %% adding a bias unit to X that is 1 for every vector in X
# like zip(ones, X)
def prepend_bias(X):
return np.c_... |
6661aa0d3c0883b1781a7ecc31486d17036cf72a | Karan191099/Decimal2binary-octal-hex- | /Conversion2.py | 1,343 | 3.828125 | 4 | #***********************Vice-Versa of above program***********
def binary():
n = input('Enter binary number: ')
a = 0
r = 0
t = int(n)
while n!=0:
q = int(n)%10
n = int(n)//10
a += 1
print(f'number of digits in {t}: ', a)
a = a
a1 = 0
while a1 < a... |
cb80401a0444bc27753b55576bef0fd559480542 | oscillot/reddit-scraper | /src/reddit_scraper/data_types.py | 2,823 | 3.546875 | 4 | class CandidatesList(object):
"""
A set made up of `class` Download objects with a specific implementation
of __contains__ to make `keyword` in work properly. Used for set of
candidates returned from `class` RedditConnect
"""
def __init__(self, candidates):
self.candidates = candidates
... |
2060876207bb1ceeb7158840bb0660082d168be5 | JSisques/Python-Toolbox | /Seccion 02 - Control de flujo/01-Condicionales.py | 2,508 | 4.3125 | 4 | '''
Una sentencia condicional es aquella que dependiendo de una variable o de un dato escogerá ejecutar un trozo de codigo u otro
En Python existen 3 tipos diferentes de condicionales pero dos de ellas solo existen si una tercera presente en el codigo
Las diferentes sentencias son:
1. If --> La sentencia if comprue... |
0ac923e73ef544c4c6bb4219dcb66e55d8b879fc | cravo123/LeetCode | /Algorithms/0993 Cousins in Binary Tree.py | 2,215 | 3.609375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Solution 1, Recursion
# Cache parent and level info
class Solution:
def dfs(self, node, level, d, x, y):
if node is None:
return
... |
1192838341cefe412da5bc980be169e92285ad2e | CarverFan/PythonStudyNotes | /1.py | 521 | 3.6875 | 4 | if __name__ == '__main__':
python_students = []
for _ in range(int(input())):
name = input()
score = float(input())
tmp = []
tmp.append(name)
tmp.append(score)
python_students.append(tmp)
scores = []
for i in python_students:
scores.append(i[1])
... |
9a8837cd752026c36603163b6ac25d58678ff8d0 | rifanarasheed/PythonDjangoLuminar | /PYTHON_COLLECTIONS/List/sumoflist.py | 172 | 3.640625 | 4 | lst = [2,5,6,7]
# 20-2=18
# 20-5=15
# 20-6=14
# 20-7=13
out=list() # empty list
total=sum(lst) # total =20
for num in lst: # 5
out.append((total-num))
print(out)
|
be4e951c5047b7c785d610570992ff8c13ef952b | charlieRode/data-structures | /doublinked.py | 1,805 | 4 | 4 | #!/usr/bin/env python
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
self.last = None
class Double_Linked(object):
def __init__(self):
self.head = None
def insert(self, data):
self.head, self.head.last = Node(data), self.head
... |
46c3b019ca5f9f7143c046aa8134e31462d7195d | mariellewalet/DCP | /problem_168.py | 597 | 4.5 | 4 | """ Given an N by N matrix, rotate it by 90 degrees clockwise.
For example, given the following matrix:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
you should return:
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]
"""
# with extra space
def rotate(matrix):
n = len(matrix)
rotated = []
for column in range(0,n):
ne... |
06708fc3d17a4a42a5cd01a80bd28f79adf65fdf | daniel-reich/ubiquitous-fiesta | /Bb9PaM4B87L39SdAo_6.py | 219 | 3.796875 | 4 |
def intersection_union(l1, l2):
l1 = sorted(list(set(l1)))
l2 = sorted(list(set(l2)))
union = sorted(list(set(l1+l2)))
intersection = sorted([i for i in l1 if i in l2])
return [intersection, union]
|
01ba1900449d882162f7d096db77e4c1e8a933fa | Viniciusmgm/aula_processamento_info | /Projeto/biblioteca.py | 3,615 | 3.859375 | 4 | #Biblioteca
#Módulos: adicionar livros, retirar livros, apresentar livros, ranking melhores livros, pesquisa por categoria, sugestão aleatória
import random
def imprimir(estante, pos): #Imprime os dados do livro
print("=======================================")
print("Nome: {} ".format(estante[pos][0]))
print("Ca... |
bc99dba0e34ba0abe4c738d0c6a6e9e7a8b6b351 | aflashfish/python_codes | /算法/柱状图中最大的矩形.py | 1,252 | 3.796875 | 4 | """
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。
每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
"""
from typing import List
rectangle_list = [2, 1, 5, 6, 2, 3]
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
_heard = 0
area_list = []
max_value = 0
for i in range(len(heights))... |
7c6e90a6090f49121bab036ce726dcadc63193ed | michaelfbagheri/CodingNomads | /labs/03_more_datatypes/2_lists/04_11_split.py | 364 | 4.375 | 4 | '''
Write a script that takes in a string from the user. Using the split() method,
create a list of all the words in the string and print the word with the most
occurrences.
'''
my_string = input('please type your string: ')
my_string = my_string.split()
print(my_string)
for i in my_string:
print(i, ' appear... |
3a7888a0d115a4fa3510719dbb6f1d7497bb8314 | danielTeniente/codeForces | /entregables/sin_categoria/705A/Hulk.py | 239 | 3.84375 | 4 | n =int(input())
hate = 'I hate '
love = 'I love '
midd = 'that '
end ='it'
expression = hate
for i in range(1,n):
expression+=midd
if(i%2==0):
expression+=hate
else:
expression+=love
print(expression+end) |
e2d9f80e33421b4a3559cac1c81221b4f3fb00cf | maxtilford/Miscellaneous | /TripRouting/main.py | 3,531 | 4.15625 | 4 | #!/usr/bin/python
# I believe that this would count as my very first Python program.
# Given that, I've probably missed some idioms. Corrections are welcome.
# Overall I'd say I like Python. The syntax is nice and clear, if a
# bit verbose at times. I did miss the rich list and enumerable functions
# that I'm used to... |
d3c2b20e9625a637ab6250ce6356c8787213c5eb | JaehoonKang/Final_project_CS110 | /work/Guessing_game/GuessingGUI.py | 2,424 | 3.90625 | 4 | from tkinter import *
from guessingLogic import *
class GuessingGUI:
def __init__(self):
self.__window = Tk()
self.guessingLogic = guessingLogic()
print(self.guessingLogic.answer)
self.__upper_frame = Frame(self.__window, width=500, height = 400)
self.__upper_frame.grid(... |
23b6af3be762a94b4988bf1d31cd220f83dd9e43 | Park-Yegi/CS206-DataStructure | /HW/HW2/Problem2(c).py | 2,536 | 4 | 4 | import time
# the form of input(item) is tuple(data, priority)
# Let small number has high priority
# index 0 is front of queue
# Make Priority Queue class
class PriorityQueue(object):
# Create Priority Queue
def __init__(self, max_pq_size):
self.pq = []
self.max_pq_size = max_pq_si... |
39add725cfd9ab9a703b5d7131f729c04ad63e5e | evoisec/clusterFramework | /core/check_wf_schedule.py | 1,482 | 3.921875 | 4 | from datetime import datetime
from calendar import monthrange
def isScheduledDate(specificDate=None):
"""Returns whether the date passed in meets the criteria"""
if specificDate:
if "-" in specificDate and ":" not in specificDate:
# Just date passed in
specificDate += "-09:00... |
5291a0e7dcc36515f4abd9778639a3aa4d4f1d68 | carlosDevPinheiro/Python | /src/Unisa/Exemplos de programas em Python/ataque_estrutural.py | 762 | 3.546875 | 4 | # coding: utf-8
import os
import zipfile
def ataque_estrutural(img1, img2):
# Armazena o tamanho das imagens comprimidas;
tam = []
for img in (img1, img2):
# Comprime a imagem
zip = zipfile.ZipFile('imagem.zip', 'w')
zip.write(img, img, zipfile.ZIP_DEFLATED)
... |
355048adf7a6c6a7a90df25f9b01402e8122d8ea | lludu/100DaysOfCode-Python | /Day 16 - Coffee Machine OOP/main.py | 1,023 | 3.578125 | 4 | from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
# TODO 1. Print Report (Completed)
#TODO 2. Check Resources
#TODO 3. Process Coins
#TODO 4. Check transaction successful
#TODO 5. Make Coffee
#Make Objects using Classes
#Coffee Maker Object
coffee_maker = Cof... |
aac1f0ae8997d71382e3da53849dbcaf34b29bb2 | rafaelperazzo/programacao-web | /moodledata/vpl_data/16/usersdata/71/6506/submittedfiles/triangulo.py | 210 | 3.9375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
a = input("Insira o valor de a: ")
b = input("Insira o valor de b: ")
c = input("Insira o valor de c: ")
if a<b+c:
else:
print("N") |
901fa609e8d8eda2abeed25320e536c907f92656 | geetharamson/problemset-pands | /p9.py | 613 | 4.09375 | 4 | # Geetha Karthikesan , 2019
# p9.py moby-txt
# Import sys
import sys
# Input value of fileName as sys.argv[1]
fileName =sys.argv[1]
#print fileName
print (fileName)
# Opening fileName and reading
fileObject = open (fileName, 'r')
#Initialising index as 1
index = 1
# Using for loop to print alt... |
e7e209fdfd9d21ed81f534b9ccabd574976ca3a0 | lummish/cmsi282 | /homework2/majority_elem.py | 1,114 | 3.875 | 4 | # majority_elem.py
def majority_element(numbers):
mid = len(numbers) / 2
first_half = numbers[:mid + 1]
last_half = numbers[mid + 1:]
if (len(numbers) > 1):
first_majority = majority_element(first_half)
last_majority = majority_element(last_half)
else:
if len(numbers) == 1:
return numbers[0]
elif numb... |
d966eba1b7c9eabbc78209f55c9e798c598da027 | ene9/Study_Python | /practice.py | 313 | 3.8125 | 4 | # print를 이용해서 수식이 가능하다.
number = 2 + 3 * 4 # number라는 변수 생성
print(number)
number = number + 2
print(number) # 16
number -= 4
print(number) # 12
number *= 4
print(number) # 48
number /= 8
print(number) # 6
number %= 5 # 나머지 연산도 가능
print(number) |
d1afd4b62dc2c258931ca2eff4416c99787f3f4f | sreeraj7sm/Python-Games | /guessingnumber.py | 433 | 3.921875 | 4 | from random import randrange
print('\n Now start guessing the number, its between 0 and 20')
a=randrange(0,20)
b=int(input('\n Enter the number:'))
while True:
if b==a:
break
elif b<a:
print("Your guess is too low")
b=int(input('\n Enter the number:'))
elif b>a:
print("Your g... |
92d0f4d50c61ccad2c89f70811a4ca6aff3dc56c | hariharanRadhakrishnan/Python_Exercises | /cube_4/cube.py | 1,916 | 4.34375 | 4 |
####################
## EXAMPLE: perfect cube
####################
cube = 27
#cube = 8120601
for guess in range(cube+1):
if guess**3 == cube:
print("Cube root of", cube, "is", guess)
# loops keeps going even after found the cube root
####################
## EXAMPLE: guess and check cube root
#####... |
41835dfdb3874a8e0256b906e0e8811e76852434 | tonight-halfmoon/slv-n-python | /data.structure/linked.lists/find/merge_point.py | 657 | 3.859375 | 4 |
"""
Problem Statement: Find out the node at which both lists merge and return the data of that node
[Linked-List #1] a --> b --> c
\
x --> y --> z --> END
/
[Linked-List #2] p --> q
"""
class Node(object):
def __i... |
3c3f654ca489619c21be904a08aa258923273ffd | ascentman/pythonCourse | /card_game/durak.py | 505 | 3.5 | 4 | import random
class Card(object):
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def value(self):
return 0
def is_joker(self):
return False
class Deck(object):
def __init__(self):
self.cards = []
def draw(self):
return self.car... |
9915940674cc6340d723cff2fbcec29c8b200701 | oghusky/DV_Study_Hall_Monday | /rps_js_py/app.py | 2,406 | 4.0625 | 4 | import random
print("Let's Play Rock Paper Scissors")
options = ["r", "p", "s"]
computer_choice = random.choice(options)
user_choice = input("Make your choice: (r)ock, (p)aper, (s)cissors")
# if (user_choice == 'r' and computer_choice == 'p'):
# print(
# f'You chose {user_choice} and the computer chose ... |
5e94f34b7b19dfccc1b3bb0e04cf9ab297873c83 | lyucu/books | /python3.5/1.py | 413 | 3.921875 | 4 | #!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
# name=input('Please enter your name\n')
# print('Hellow World',name);
print('123+333=',123+333)
print('123"123"')
print(r'\\\\\\\\\\')
print('''123
dasfs
fsaf
''')
if(True):
print('dd')
if (1>0 and 2>1) :
print('true')
print(ord('a'))
print(chr(66))
x=b'abc'
pri... |
4f3368e0559e9f96b584f6c2ed4735d4cb53580f | lukasz40005/Python-lekcje-2 | /zadanie12.py | 385 | 3.859375 | 4 | """n=int(input("Podaj liczbę: "))
a=1
b=1
if n==1:
print(1)
elif n==2:
print(1)
print(1)
else:
print(1)
print(1)
for i in range(3,n+1):
c=a+b
print(c)
a=b
b=c"""
def fib(n):
if n==1 or n==2:
return 1
else:
return fib(n-1)+fib(n-2)
n=int(inp... |
a5f4028f0d6ab4d4cb588592d32fb916dd6a7f4a | BingfanWang/Introduction-to-Algorithms--Python | /BinaryTree/Tree.py | 14,045 | 3.96875 | 4 | # 实现的二叉树操作有:
# 寻找, 插入, 删除, 最大, 最小, 前驱, 后继, 中序遍历, 前序遍历, 后序遍历, 高度, 层
# 为了方便看二叉树, 加入了draw, 用来绘制简单的二叉树
from turtle import *
import math
import random
class TreeNode(object):
__slots__ = ('val', 'parent', 'left', 'right') # 用来限制属性只能是这几个
def __init__(self, value=None):
self.val = value
self.parent... |
00a9fa82b8125b74c74c050e3b7a9b44e6e800dd | VivianLiu108/python-basic-skills | /openFile.py | 1,982 | 3.640625 | 4 | #read()
infile = open("doc.txt", "r") #開啟檔案doc.txt r為讀檔案模式 (ex. with open("doc.txt", "r") as infile : print(infile.read)
s = infile.read() #This is a book. 讀取檔案所有內容
#Today is Friday.
wordList = s.split() #['This', 'is', 'a', 'book.', 'Today', 'is', 'Friday.'] 將以空白分隔的字... |
d62e711879923afbf163a8c198a4c200bb0bbb2e | sandhiya97/Guvi | /Home_task23.py | 132 | 4 | 4 | #program to count the number of digits in a number
n=(int(input()))
count=0
while(n>0):
n=n//10
count=count+1
print(count) |
b3c92738fb5edd8698d2b89b8690b7ab30a882de | Sarah1108/HW070172 | /hw_4/exercise_7.py | 569 | 4.21875 | 4 | # exercise 7
# geometrie, distance between points
import math
def main():
print("This program calculates the distance between two points: ")
print()
x1 = float(input("Enter the x coordinate of the first point: "))
y1 = float(input("Enter the y coordinate of the first point: "))
x2 = float(input... |
a3a8d7b5dd8e5a392bcd93669075eb62f24914d8 | Brunox117/Mision_03 | /Boletos.py | 554 | 3.78125 | 4 | #Bruno Omar Jiméenz Mancilla
#Programa que calcula csotos de boletos
def calcularPago(boletosA, boletosB, boletosC) :
A = boletosA*3250.00
B = boletosB*1730.00
C = boletosC*850.00
totalPago = A+B+C
return totalPago
def main() :
ba = int(input("¿Cuántos boletos quieres para la zona A?:... |
8b1c093b068bc94456b92a4493cf9014f4a24a77 | zhao907219202/python-1st | /python-base/108-exception/802-excet.py | 780 | 4 | 4 | try:
x = int(input("Enter the first number"))
y = int(input("Enter the second number"))
print(x / y)
except:
print("Something wrong happened...")
# 像这样捕捉所有异常是危险的,因为它会隐藏所有程序员未想到并且未做好准备处理的错误。
# 它同样会捕捉用户终止执行的Ctrl+C企图,以及用sys.exit函数终止程序的企图
# 这时用except Exception as e: 会更好一些,或者对异常对象e进行一些检查
while True:
t... |
e74f5edfc352abb5197c3da77d492f4b2f153e40 | LordMussta/greetingsApp | /greetings.py | 1,291 | 3.921875 | 4 | import tkinter as tk
from tkinter import ttk
def EnterName():
user_result.set("Hello " + user_name.get() + "!")
print(f"Hello {user_name.get() or 'World'}!")
if len(user_name.get()) == 0:
pass
else:
namesList.append(user_name.get())
print("passed else test")
user_name.set(""... |
abbf209295f1609b610b937b279da46808bacdd7 | Nishi216/PYTHON-CODES | /STRINGS/prog2.py | 786 | 4.1875 | 4 | #to check if teh string is a palindrome or not
#method 1
def isplaindrome(st):
return st==st[::-1]
st="malayalam"
result=isplaindrome(st)
if result:
print("yes")
else:
print("no")
#method2
def ispalindrome(st):
for i in range(0,int(len(str)/2)):
if str[i] != str[len(str)... |
e41c7aebf61d459aaab1fb0096c7beb3c6be6c98 | Daniel98p/Codewars | /weight_for_weight.py | 1,715 | 3.53125 | 4 | import collections
# def order_weight(strng):
# print(strng.split(" "))
# sum = 0
# new_dict = {}
# c = 0
# for counter, value in enumerate(strng):
# if value == ' ':
# new_dict[strng[c:counter]] = sum
# c = counter + 1
# sum = 0
# continue
#... |
8fed3258ae2a8b5ef77159cdf83f8f6a210981a2 | ktwoo111/MazeProject | /mazeTest.py | 1,097 | 3.515625 | 4 | import networkx as nx
import matplotlib.pyplot as plt
g=nx.DiGraph()
#name of node then position
g.add_node("(1,1)", message="HELLO")
g.add_node("(2,1)", message= "HI")
g.add_node("(3,1)", message="WHAT")
g.add_node("(4,1)", message="HI2")
g.add_edge("(1,1)","(2,1)",color='b')
g.add_edge("(2,1)","(3,1)",color='r')
g... |
5d8c96142390f1a9d85cb901e462fdea60857cf7 | manuelbrihuega/crossfit | /wsgi/reservas/reservas/aux/strings.py | 611 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import re
import unidecode
def string_to_compare(string):
string=string.replace("-"," ")
string=string.replace("_"," ")
string=string.replace("."," ")
string=string.upper()
string=string.strip()
return string
def slugify(str):
str = unidecode.unidecode(str).lower()... |
1d4f460c279ef00873a5a0c4432cbb196148e04b | michaelvitucci1/TicTacToe | /StartGame.py | 4,476 | 4.15625 | 4 | import numpy
import pygame
HEIGHT = 3
WIDTH = 3
RED = (255,0,0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
YELLOW = (255, 255, 0)
BLACK = (0, 0, 0)
SQUARE_SIZE = 200
MARGIN = 10
WEIGHT = 5
PLAYER_1 = 1
PLAYER_2 = 2
pygame.font.init()
win_font = pygame.font.SysFont('monospace', 75)
def create_board():
board = numpy.z... |
e000cd05d043f0b9df3064cd5760f472fc549277 | Xiristian/Linguagem-de-Programacao | /Exercícios aula4/Exercicio29.py | 342 | 3.765625 | 4 | notaUm = float(input("Digite a primeira nota: "))
notaDois = float(input("Digite a segunda nota: "))
notaTres = float(input("Digite a terceira nota: "))
notaQuatro = float(input("Digite a quarta nota: "))
mediaFinal = (notaUm + notaDois + notaTres + notaQuatro) / 4
print("A média aritmética das notas é:", "%.... |
95d8b0614dfa6dd7ccd1d59038d97798c1ddaab0 | Mahdi-Adeli/Atomic-Nature | /luminance.py | 433 | 3.53125 | 4 | from picture import Picture
from color import Color
def check_luminance(c):
red = c.getRed()
green = c.getGreen()
blue = c.getBlue()
return (.114 * blue) + (.299 * red) + (.587 * green)
# we use this 3 function when we are changing the picture color.
def change_to_black(c):
return Color( 0 , 0 , 0)
def ... |
2be590f6b316c330104cad04e55999f57b8da59f | chacal88/iniciando-com-python | /for.py | 230 | 3.984375 | 4 | list = [2,4,6,8,10]
for item in list:
if item > 2:
print('granter than 2')
print(item)
list2 = ["kaue","rodrigues","dos","santos"]
for name in list2:
if name == "kaue":
print(name)
if not name == "kaue":
print(name) |
970cf9b4c011ebb0d1b3abb8506dfd3a23c8b3ef | CristicRibeiro/Coisas_que_Usei_Python | /Input.py | 218 | 3.9375 | 4 | '''
Autor: Cristina Ribeiro
Codigo: como funciona metodo input (mostrar na tela)
'''
nome = input ('qual eh o seu nome?')
idade = input ('qual eh a sua idade?')
peso = input ('qual eh o seu peso?')
print (nome, idade, peso)
|
450552056a0f5e86b811017f201ec2fbd9982b0d | CatalinaMoralesCardenas/An-lisis-Num-rico- | /Talleres/Taller1/ejercicio_8.py | 1,854 | 3.546875 | 4 | from matplotlib import pyplot
import sympy as sy
import math
def f1(t):
return math.cos(3*t)
def f2(t):
return math.exp(t)
def graficar():
t = range(-2,2)
pyplot.plot(t, [f1(i) for i in t])
pyplot.plot(t, [-f2(i) for i in t])
pyplot.axhline(0, color="black")
pyplot.ax... |
6442165c0753cfa788dbb5903862a48aee56ed34 | rndAdn/LS4 | /TP6/compte.py | 663 | 3.796875 | 4 | #! /usr/bin/python3
class CompteEpargneTemps():
nombre_employes = 0
def __init__(self, nom, solde=0):
self.nom = nom
self.solde = solde
CompteEpargneTemps.nombre_employes +=1
def __del__(self):
print("Le Compte de {0} est supprimé".format(self.nom))
CompteEpargneTe... |
e7e76acb88439be18b7492b139f479df22a5aaf0 | AcrobatAHA/URI-Problem-Solving | /URI 1016 Distance in python.py | 69 | 3.53125 | 4 | distance = int(input())
Time =distance*2
print("%d minutos"%Time)
|
aa7dc690b24588add617267a594b508f165381c3 | claraj/web-autograder | /grading_module/notes/was_the_original_ag/repo_cloner.py | 1,487 | 3.53125 | 4 | import os
import shutil
# For each student, download the appropriate repository to a given location
# Each repo for each student/week has unique name
# example: student_code/student_github/test_set
# example student_code/clara-mctc/week_1
# minneapolis-edu JAG_2 student_code
# bobStudent ... |
2512774ebe77b2e523b3352a242f1437ee2970cb | hamzini99/aqaSchoolAssignmentTwo | /Game.py | 935 | 3.75 | 4 | from random import randint
def fileOpener():
fileName = str(input("\nPlease enter the file you wish to be Encrypted: ")).upper()
if fileName == "SAMPLE.TXT":
fN = open(fileName)
global fileContents
fileContents = fN.read()
fileName.close
def offsetCharacter():
ran... |
d45c743b599dec4fabb446fda96a76fb8ec6d535 | SandeepKumarShaw/python_tutorial | /new folder/excersize_12.py | 168 | 3.796875 | 4 | def reverese_order(a):
value = []
for i in a:
value.append(i[::-1])
return value
num = ["hhvccv","vcvcbc","hsvhvx"]
print(reverese_order(num)) |
8b157a98423d7446ad1055d8045e984b1fcad935 | chiachi921719/Age | /Age.py | 438 | 3.953125 | 4 | driving = input("你有沒有開過車? ")
if driving != "有" and driving != "沒有":
input("只能輸入 有/沒有")
raise SystemExit
age = input("你的年紀是? ")
age = int(age)
if driving == "有":
if age >= 18:
print("你通過測驗了")
else:
print("奇怪你怎麼開過車?")
elif driving == "沒有":
if age >= 18:
print("趕快去考駕照吧!")
else:
print("很好,18歲以後就可以考囉!") |
f2a1001ad501f2b730be19f44384de8da453041d | bhristovski/Python-Battleship | /Python Battleship Game/Main.py | 22,926 | 4.1875 | 4 | # Place.py
#
# @ author: Anthony. Danial
# date: November 2018
#Import needed as a method to exit the program
import sys
#Import Documents
from Ships import Ships
from Coordinates import Coordinates
from Place import Place
from Shoot import Shoot
from ShotLocation import ShotLocation
#Welcome message with instructio... |
18c95ad98dd2425042d8995b54890495fc098934 | khadak-bogati/python_project | /Selection_model.py | 305 | 3.53125 | 4 | def Selection_model(a_list):
for i in range(len(a_list)):
minIndex = i
for j in range(i + 1, len(a_list)):
if a_list[minIndex] > a_list[j]:
minIndex = j
minValue = a_list[minIndex]
del a_list[minIndex]
a_list.insert(i, minValue)
return a_list
print(Selection_model([6, 5, 4, 3, 2, 1]))
|
7bcd122dc00f5c0d4c0e1f596defd8fcbde9b6c0 | orbitz/ca-ocaml-platform | /igs/utils/core.py | 476 | 3.53125 | 4 | ##
# Really core tiny functions
class StringNotFoundError(Exception):
pass
def getStrBetween(haystack, start, end):
sidx = haystack.find(start)
if sidx < 0:
raise StringNotFoundError('start: %s not found in %s' % (start, haystack))
sidx += len(start)
eidx = haystack[sidx:].find(end)... |
48f9b042883d7ca46da2580794ce63a6419aadc0 | rubythonode/algorithm-king | /codewars/5-kyu/can-you-get-the-loop.py | 278 | 3.53125 | 4 | def loop_size(node):
visit = {}
while 1:
if node not in visit:
visit[node] = 0
elif node in visit:
if visit[node] > 1:
return sum(int(bool(i)) for i in visit.values())
else:
visit[node] += 1
node = node.next
|
879b0920a2fbea133f2be0c7c6bef168a79393e1 | deep2612/Python | /Functions.py | 206 | 3.578125 | 4 | import math
import random
#Built in Functions
print(max("Hello World"))
print(len("Hello World'"))
radian = 0.8
height = math.sin(radian)
print(height)
print(math.sqrt(64))
print(random.randrange(0,10))
|
f8bd0fdfa7981819ff7282f094051c4e8c4c37ed | jerdra/Suffix_Tree | /suffix_tree_builder.py | 7,834 | 3.765625 | 4 | #Tree builder class
class SuffixNode():
'''Suffix Node object of Suffix Tree'''
leaf_pos = 0
_curr_ind = 0
def __init__(self):
#Key node variables
self.children = {}
self._s_link = []
self._start, self._end = 0, 0
#Keep track of leaf nodes for visualization
... |
e0ba7c9b7bbf0ca94073489fce5bc2e650d6c33e | yycang/Bucciarat | /剑指offer/fourteen.py | 1,104 | 3.5625 | 4 | # 剪绳子问题,给长度为n的绳子,要求剪m段,每段都为整数,如何剪出每段绳子的最大乘积
def max_count(length):
if length < 2:
return 0
if length == 2:
return 1
if length == 3:
return 2
# 创建长度为length的数组存储子问题的最优解
f = [None for _ in range(length + 1)]
f[0], f[1], f[2], f[3] = 0, 1, 2, 3
res = 0
for i in rang... |
9ca03847647f9a73550543cdac08d9c345e31bcc | AnshumaJain/recruiting-exercises | /inventory-allocator/src/inventory_allocator.py | 2,933 | 4.09375 | 4 | # Anshuma Jain
# Problem: Compute the best way an order can be shipped (called shipments) given inventory across a set of warehouses (called inventory distribution).
def update_shipment_distribution(shipment_distribution, warehouse_name, fruit, order_qty):
""" Updates the shipment distribution using the given war... |
13738f6019a0de9a6f7a9d5b0fd7edd3f22106f1 | forklady42/algorithms | /graphs/shortest_path.py | 2,227 | 3.90625 | 4 | """Shortest path algorithms for both weighted and unweighted graphs"""
import pylab
import networkx as nx
from Queue import Queue, PriorityQueue
def BFS(G, s, t):
"""Shortest path for unweighted graph"""
for u in G.nodes():
G.node[u]['dist'] = float('inf')
G.node[s]['dist'] = 0
... |
84c655acc227222e4f6e141c97949be2aac1e22a | mori-c/cs106a | /sandbox/sandcastles.py | 1,495 | 4.3125 | 4 | """
File: sandcastles.py
-------------------------
Practice of control flow, variable and function concepts using the following files:
1 - subtract_numbers.py
2 - random_numbers.py
3 - liftoff.py
"""
import random
import array
def main():
"""
Part 1
- user inputs numbers, py separates numbers with substract... |
347d5fda48d3dc1e39d1e906e61b6ab64d5c640b | AyaHusseinAly/practicing_python | /problem3.py | 548 | 3.890625 | 4 |
def comparehalves(input_string):
str_len = len(input_string)
global front
global back
if (str_len % 2 != 0):
front = input_string[0:int(str_len / 2)+1]
back = input_string[(int(str_len / 2)) + 1:]
else:
front = input_string[0:int(str_len / 2)]
back = input_string[int(str_len / 2)... |
64e85bf33dfbceb40f27f197638dd1f2942f445e | zgudasha/python | /pygame/moving.py | 878 | 3.53125 | 4 | import pygame
pygame.init()
screen = pygame.display.set_mode((300, 300))
screen.fill(pygame.Color('black'))
pygame.draw.rect(screen, pygame.Color('red'), [0, 0, 50, 50])
running = True
x1, y1 = 0, 0
contains = False
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
... |
7cf150f441c29ea7637d2950969ab5dfa64050b9 | xiao-li0220/data_structure | /指针/对撞指针/最接近的三数之和.py | 754 | 3.625 | 4 | from typing import List
def threeSumCloest(nums: List[int],target: int) -> int:
nums.sort()
min = abs(nums[0] + nums[1] + nums[2] - target)
sums = nums[0] + nums[1] + nums[2]
for i in range(len(nums)-2):
left = i + 1
right = len(nums)-1
while left < right:
sum = nums[... |
7af37bc44edec018da894d96400d9bee6a6e422a | JennyTrac/Unit-3-10 | /mark_calculator.py | 1,095 | 3.59375 | 4 | # Created by Jenny Trac
# Created on Oct 26 2017
# Program calculates a students final average
# learned how to do arrays from:
# http://www.i-programmer.info/programming/python/3942-arrays-in-python.html
import ui
# constants and variables
average = 0
marks_sum = 0
number_of_marks = 0
def calculate_touch_up_inside(... |
581e26dca32ffa41ef8e42009360a0b2f9fe2f79 | PhurpaSherpa16/Python2.0 | /OOP/inheritance.py | 725 | 3.796875 | 4 | class GrandParents:
def name1(self):
print("GrandParents is Kami")
def cast1(self):
print("Cast is Sherpa")
class Fathername:
def name2(self):
print("Father is Kami")
def cast2(self):
print("Cast is Sherpa")
def location(self):
print("Living in Dhading")
cla... |
586954e4623a95577ff79e51863cf64a095d8893 | coder-dipesh/Basic_Python | /labwork1/bmi_calculation.py | 523 | 4.4375 | 4 |
"""Solve each of the following problems using Python Scripts. Make sure you use appropriate variable names and comments. When there is a final answer have Python print it to the screen.
A person’s body mass index(BMI) is defined as:
BMI = mass in kg / (height in m)2.
"""
# Raw data collected
person_mass = float(input... |
f7ef8af2359fa49f09f473cde198542cea993cb9 | evangordo/ca278 | /01numbers.py | 151 | 3.921875 | 4 | #!/usr/bin/env python
n = input("Enter a number:")
total = 0
print "\n" + str(n)
while n > 0:
total += n
n -= 1
print n
print "\n" + str(total)
|
8a3c104778a29b71ef895efee756a5fa7605531c | FaizaTanveer/Assignment16Apr2017 | /Assignment16Apr2017.py | 4,597 | 3.796875 | 4 | # Chapter 8 , Question no.8-3. T-shirts:
def make_shirt(size,message):
print("Well Done ! You Proved\n'"+message.title()+"'.")
print("I hope shirt size '"+size.title()+"' fit you.\n")
make_shirt('medium',"dreams don't work unless you do")
#make_shirt(message='a goal without a plan is just a wish',size=... |
00ad8fc2b564fd5da75f9b4023802bda08bfe419 | aly50n/Python-Algoritmos-2019.2 | /lista02ex14.py | 794 | 3.890625 | 4 | print("Lhe farei 5 perguntas sobre o crime, me responda apenas com sim ou não:")
p1 = input("Telefonou para a vítima? ")
if p1 == "sim":
r1 = 1
elif p1 == "não":
r1 = 0
p2 = input("Esteve no local do crime? ")
if p2 == "sim":
r2 = 1
elif p2 == "não":
r2 = 0
p3 = input("Mora perto da vítima? ")
if p3 == ... |
9cb28d3f25ff0bf3240cf320568046e3d3c74e1d | himanshutyagi36/AlgorithmPractice | /CTCI/python/BFSHackerrank.py | 1,407 | 3.671875 | 4 | ## QUESTION: https://www.hackerrank.com/challenges/ctci-bfs-shortest-reach/problem
from collections import defaultdict
class Graph:
def __init__(self,n):
self.graph = defaultdict(list)
self.numNodes = n
def connect(self,x,y):
self.graph[x].append(y)
self.graph[y].append(x)
... |
1375aa23159002e3845fe0f0eb693512513d9e83 | rushikmaniar/RushikPython | /collegeExercise/exe4.py | 177 | 4.25 | 4 | '''
Positive Negative Or zero
'''
a = int(input("Enter no: "))
if(a == 0):
print(a," is Zero")
elif(a > 0):
print(a,"A is Positive")
else:
print(a,"A is Negative") |
7179685b392a18abe77561b94d7fafd10018f7df | anhmvc/CS30 | /hw3_turtle.py | 986 | 4.1875 | 4 | '''
Description: A program that implements the Python turtle library to draw a tree.
(I did not discuss this assignment with anyone.)
Written By: Anh Mac
Date: 11/6/2018
'''
from turtle import *
# I've implemented this function for you; do not edit it.
def tree( trunkLength, angle, levels ):
left(90)
sideways... |
478ed1b0685ac4fda3e3630472b2c05155986d50 | girishsj11/Python_Programs_Storehouse | /codesignal/Miss_Rosy.py | 2,510 | 4.15625 | 4 | '''
Miss Rosy teaches Mathematics in the college FALTU and is noticing for last few lectures that the turn around in class is not equal to the number of attendance.
The fest is going on in college and the students are not interested in attending classes.
The friendship is at its peak and students are taking turns fo... |
910a09668634d802c863197d94214174d89fc816 | anupama-sri/My-First-Repository | /file.py | 59 | 3.5 | 4 | a = 10
b = 20
if a==10:
print("Hello World")
else
print(b)
|
42c94f5036c139de4a15233b041f91f20f145763 | najpodge/AdventOfCode2020 | /src/day7.py | 1,330 | 3.71875 | 4 | import re
def contains_gold(bag, bags):
found_gold = False
if bags[bag] == []:
return False
for (quantity, sub_bag) in bags[bag]:
if sub_bag == 'shiny gold':
found_gold = True
found_gold = found_gold or contains_gold(sub_bag, bags)
return found_gold
def num_bags_in... |
75fb3c5b8ed9987fc2ef63d7dc3770792e9b2ea7 | yenicelik/neuralarchitecturesearch | /src/child/rnn/Base.py | 1,539 | 3.578125 | 4 | """
This class defines the abse elements that our neural network need to incorporate.
This neural network incorporates only the model logic, which includes:
- generating the network
- forward step
- backward step
One should notice that torch does not have a "building" and one "compu... |
5fdae073d0ebd353ffec97a2d7e30373cd234e42 | Alex-Iskar/learning_repository | /lesson_3/hw_3_1.py | 530 | 3.84375 | 4 | # Реализовать функцию, принимающую два числа и выполняющую их деление
def del_1(arg_1, arg_2):
return arg_1 / arg_2
a = int(input("Введите число а : "))
b = int(input("Введите число b : "))
try:
del_1(a, b)
except ZeroDivisionError as err:
print("Error! Для параметра b использовано значение '0'. Введите к... |
8f52c072a440a2008bfeebba4c0e8a702403d69f | acesknust/Learn-to-Code-Python | /functions/function.py | 581 | 4.3125 | 4 | #to create a function the keyword is def
def my_function1 () :
print("hello world ! ")
#to add arguments put them between parentheses seperated by ","
def my_function2 (msg) :
print(msg)
#to return a value we use the key word return
def my_function3 (a,b) :
som=a+b
return(som)
#to call a functio... |
7823158ca96689861643d448e0a785e30d66710f | huettenhain/mistletoe | /mistletoe/span_tokenizer.py | 1,332 | 3.65625 | 4 | """
Inline tokenizer for mistletoe.
"""
def tokenize(content, token_types):
"""
Searches for token_types in content, and applies fallback_token
to texts in between.
Args:
content (str): user input string to be parsed.
token_types (list): a list of span-level token constructors.
... |
91569ee6503ea46f5da3d6a874dbe959f53b1bd4 | Mathesh099/Arithmetic-Exam-Application | /Arithmetic Exam Application/Stage-1.py | 171 | 3.71875 | 4 | Inputs = input()
a, b, c = Inputs.split(" ")
if b == "+":
print(int(a) + int(c))
elif b == "-":
print(int(a) - int(c))
elif b == '*':
print(int(a) * int(c))
|
d70d2fe8ee72724461584894e11239525c42352e | TheSentinel36/DFS-Scraper | /lib/make_db_stats.py | 10,794 | 3.8125 | 4 |
"""
Add something to check that player ID is in ID list.
"""
class Player(object):
def __init__(self, date, game_record):
"""
See specific sport subclasses for game_record format.
"""
self.date = date
self.name = game_record[1]
self.fd_position = None
self.f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.