blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9ef3e7f62f753112d3a52053fa58ac8bb8a2d13d | dchandrie/Python | /inheritance.py | 634 | 3.875 | 4 | class pet:
def __init__(self, name, age):
self.name=name
self.age=age
def show(self):
print("I am "+ str(self.name)+" and I am "+str(self.age)+" years old!")
def speak(self):
print("Hi!")
class cat(pet):
def __init__(self, name, age, color):
super().__init__(name,... |
fc1ba6d87024fa57eb85b0bd1601eb1fe1507132 | IvTema/Python-Programming | /lesson1.12_step6.py | 458 | 3.90625 | 4 | # https://stepik.org/lesson/5047/step/6?unit=1086
a = int(input())
t=("программист")
ta=("программиста")
tov=("программистов")
if 11<=a<=14 or (a-11)%100==0 or (a-12)%100==0 or (a-13)%100==0 or (a-14)%100==0:
print(a, tov)
elif (a-1)%10==0 or a==1:
print(a, t)
elif (a-2)%10==0 or a==2:
print(a, ta)
elif (a-... |
9df8f31fab565fbccea395cff93136e545c40c41 | vmms16/MonitoriaIP | /Dicionarios/lista_dicionarios_02.py | 526 | 4.03125 | 4 | linhas=int(input("Numero de linhas: "))
colunas=int(input("Numero de colunas: "))
matriz={}
for i in range(1,linhas+1,1):
for j in range(1, colunas+1,1):
matriz[i,j]=input("Insira um valor: ")
matriz_transposta={}
for i in range(1,linhas+1,1):
for j in range(1, colunas+1,1):
... |
a68e315033e7231eee39411763c7d5f2f94b21d6 | JonesCD/P-E-Problems | /pe011.py | 2,045 | 3.546875 | 4 | """
What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20x20 grid?
"""
import time
start = time.clock()
import winsound
Freq = 200 # Set Frequency To 2500 Hertz
Dur = 250 # Set Duration To 1000 ms == 1 second
############################
import csv... |
5ac44d446284a88b7382a166fcdea58c6db67b16 | richnakasato/interviews | /reverse_ll_with_k.0.py | 1,501 | 3.75 | 4 | class Node(object):
def __init__(self, data, next_=None):
self.data = data
self.next = next_
def reverse_ll(head):
curr = head
prev = None
while curr:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev
def reverse_ll_with_k(head,... |
a890dc9d5cb9a3344fabd3f6bcef8d49d129df02 | BinXiaoEr/Target_to-Offer | /64.求1+2+n.py | 324 | 3.53125 | 4 | # -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
return sum(list(range(1,n+1)))
class Solution:
def Sum_Solution(self, n):
# write code here
result=n
temp=n>0 and self.Sum_Solution(n-1)
result+=temp
return re... |
7f19bff1d0ca20cf98b6081e70d8dfb523a20845 | keisuke-isobe/Magic8Ball | /isquestion.py | 630 | 4.15625 | 4 | """
Function which returns if the input text is a question or not. This is
determined by checking first if the sentence ends with a question mark.
If it does, it is assumed that the statement is a question. If it doesn't
end with a question mark, the function then checks if the statement
contains any of the words that ... |
0d27c8874549c8930eec5588f37da379bd67ab8a | sdetcoding/Python_Basics | /basic/datatype/setbasic.py | 872 | 3.921875 | 4 | # --------- Lets Play with Set -------------------------------------
st = {1, 2, 3}
print(st)
# empty set
est = {}
print(est)
# adding value to set
st.add(4)
st.add(40)
st.add(64)
st.add(42)
print(st)
# removing value from set
st.pop()
st.remove(42)
st.discard(42) # will not throw error if element is not present
pr... |
a148c63e4631c16a5575f6258162b835496aaf44 | Akanksha-Verma31/Python-Practice-Problems | /Problem14.py | 220 | 4.09375 | 4 | # print the square of first 10 numbers
i = 1
while (i<=10):
print(f"Square of {i} is :" ,i**2)
i+=1
# print the square of first 10 numbers
x = 1
while (x<=10):
print(f"Square of {x} is :" ,x*x)
x+=1
|
b9f77525940724fdc33c559573a487fec20c4d10 | Vickybilla/PRACTICA-PHYTON | /EjerciciosPython/ejercicio2-1.py | 908 | 4.34375 | 4 | """Ejercicio 1: Pedir al usuario que ingrese un mensaje cualquiera, si el mensaje tiene
más de 100 caracteres imprimirlo por pantalla, si tiene entre 50 y 100 caracteres imprimirlo al revés,
si no se cumple ninguna de las opciones anteriores,
por pantalla devolver un mensaje que diga "su mensaje es demasiado corto"."""... |
23a58c2a73fefb1e66a57faa02e44603a4c18626 | capnhawkbill/simple-game | /randomfunctions.py | 1,636 | 3.8125 | 4 | import os
def valid_input():
"""Gets valid input from user"""
while "true":
output = int(input("> "))
if output > 10 or output < 1:
print("input needs to be between 1 and 10")
else:
break
return output
def y_or_n():
"""gets y or n from user"""
while "true":
output = input("> ")
if output == "... |
0a9dc0e80a2c71609520cafc6774127100e100f7 | manufactured/Youtube_Scraper_mod1 | /src/get_api_key.py | 1,687 | 3.5 | 4 | from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from httplib2 import ServerNotFoundError
from google.auth.exceptions import DefaultCredentialsError
'''
Get the API key and save it in a text file named, key.txt in parent folder.
The method to get a youtube API key is well illustr... |
1891ca42f5cdb9f4f7f73119fed178d0a71fffe4 | lbedoyas/Python | /Clase 1/if_else.py | 307 | 3.875 | 4 | sueldo1=int(input("Introduce el sueldo 1: "))
sueldo2=int(input("Introduce el sueldo 2: "))
#condicional if / else
if sueldo1>sueldo2:
print("El sueldo 1: " + str(sueldo1) + " Es mayor que sueldo2 " + str(sueldo2))
else:
print("El sueldo 1: " + str(sueldo1) + " Es menor que sueldo2 " + str(sueldo2)) |
4aa92163cb1bd33f09aec4de69259308cebf6296 | WenboTien/python_assignment_test | /firewall.py | 2,455 | 3.5 | 4 | import csv
from IPy import IP
"""
input: the string of the port range
output: The list consists of all qualified port number
"""
def port_range(port_str):
if port_str.find('-') < 0:
return [int(port_str)]
port_list = port_str.split('-')
return [i for i in range(int(port_list[0]), int(port_list[1]... |
c7406591b4511b69e6c8b28e6c096497e89d34f0 | gustavo-zsilva/exercicios-python-cev | /PythonExercicios/ex054.py | 873 | 3.921875 | 4 | from datetime import date
data = date.today().year
maiores = 0
menores = 0
for c in range(1,8):
ano = int(input('Digite o ano que a {}ª pessoa nasceu: '.format(c)))
if data - ano >= 18:
maiores += 1
else:
menores += 1
if ano >= data:
print('\033[31mValor Inválido.\033[m')
... |
58baef245b36eb2e74e6e10e63accd38ce724d78 | trew13690/CSC101Code | /Work/Exam/app.py | 3,763 | 3.5 | 4 | """
App.py ~ This App build Meh Faces !!! 0.0 -_-
by Alex Trew ~ 03/21/19
"""
from graphics import *
import math
class App():
"""
App - Contains all high level objects
"""
def __init__(self, faceR=50,eyeR=10, facecolor='blue', eyeColor='red', noseColor='green', noseWidth=10):
sel... |
2541b58048a273a757541d64790f30504eeaa9a6 | devdo-eu/zombreak | /logic/city_card.py | 464 | 3.703125 | 4 | from enums.zombie import ZombieType
class CityCard:
def __init__(self, zombie: ZombieType = ZombieType.ZOMBIE):
if zombie == ZombieType.SURVIVOR:
raise Exception('Card cannot be init with survivor on top!')
self.active = True
self.top = ZombieType.SURVIVOR
self.bottom =... |
462f98f9352fea25e34ed30e0f5832781f848948 | anthonywww/CSIS-9 | /lockers.py | 1,692 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Program Name: lockers.py
# Anthony Waldsmith
# 7/6/2016
# Python Version 3.4
# Description: Show how many lockers are open/close after a alternating loop run for each value instance 1000 times.
# Optional import for versions of python <= 2
from __future__ import print_f... |
bced22f69c020ef81941798b781f50c20dd89805 | kavitshah8/PythonSandBox | /tutoring/hello1.py | 232 | 3.984375 | 4 | def con():
grade = int(input("Enter your final grade"))
if grade >= 90 :
print ("A")
elif grade >=80:
print ("B")
elif grade >= 70:
print ("C")
else :
print ("Avg")
|
6c6c7643baaaf284e739ee3f0bd6a2964b2c0474 | mahoep/ME-499 | /Lab5/complex.py | 4,569 | 3.875 | 4 | #!usr/bin/env python3
'''
@author Matthew Hoeper
'''
import math
class Complex:
def __init__(self, re=0, im=0):
if isinstance(re, int) or isinstance(re, float):
self.re = re
else:
raise TypeError('Real part must be an integer or float')
if isinstance(im, int) o... |
a01da818cdc80f09e1fd08ce587ba28b0ec5795b | makennamartin97/python-algorithms | /loweruppermap.py | 424 | 4.25 | 4 | # Write a function that creates a dictionary with each (key, value) pair
# being the (lower case, upper case) versions of a letter, respectively.
# mapping(["p", "s"]) ➞ { "p": "P", "s": "S" }
# mapping(["a", "b", "c"]) ➞ { "a": "A", "b": "B", "c": "C" }
# mapping(["a", "v", "y", "z"]) ➞ { "a": "A", "v": "V", "y": ... |
73a1f13ddb50eb74c88fa151bf7ff7ebceb5299f | Eunjuni/Indoor-Tracking | /Server/localization.py | 7,971 | 3.515625 | 4 | import math
import re
import sys
import csv
import localizationTrilateration
'''
BSSID: Basic Service Set Identifier
SS: signal strength
RSSI: Received signal strength indicator
AP location: access point location
The basic service set (BSS) provides the basic building block of an 802.11 wireless LAN.
Each BSS is uni... |
3e69933b6a38d3ac73f36cfab2769c32f95a5077 | rkandekar/python | /DurgaSir/ob_input_eval.py | 347 | 4.4375 | 4 | #automatically it will evaluate, eval() takes string and evaluate
print(eval("1+2+3"))
expression=input("Enter some expression:")
result=eval(expression)
print(result)
#eval is smart will determine the variable type
x=eval(input("Enter one variable int or float or sting or any type:"))
print(type(x))
print(x)
... |
38cc1e8ff475ce4a1ad0ece56aca429ed3c372c2 | panditprogrammer/python3 | /python97.py | 338 | 4.25 | 4 | # isupper and is lower function in python
print("This is isupper function")
x="This is paragraph."
print(x.isupper())
print(x.islower())
print(x.istitle())
print("This is uppercase")
n=x.upper()
print(n.isupper())
print("This is lowercase.")
m=x.lower()
print(m)
print("This is checking title is lower or uppercase.")
o=... |
48d48b33f00df1a5cb7e1e06c8637e99a09481d0 | rahulmitra-kgp/cnn_build_stepwise | /cnn_build_stepwise.py | 7,858 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import cv2
import matplotlib.pyplot as plt
# we will visualize the below mentioned image later on
# change the path and provide the path from your file system
img = cv2.imread('C:\\Users\\rmitra\\Desktop\\photograph\\fruits\\fruits-360\\Training\\Mango\\13_100.jpg')
... |
50ecd379d52625e8e3824acda131a82a833ad78e | KevinDeNotariis/self-replicating-virus | /03-recursive-encryption/recursively_encrypt_decryption.py | 929 | 4.0625 | 4 | import encrypt_decryption
number_of_encryption = 1
original_filename = ""
def level_of_encryption():
global number_of_encryption
print("Number of encryption: ")
number_of_encryption = input()
def ask_for_filename():
global original_filename
encrypt_decryption.ask_for_filename()
original_filename = encry... |
c9a12c8e0ec7c37df0309bea55df7bf7c0a6dedd | jagrvargen/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/8-simple_delete.py | 206 | 3.71875 | 4 | #!/usr/bin/python3
def simple_delete(my_dict, key=""):
if my_dict:
newDict = my_dict
if key in newDict.keys():
del newDict[key]
return newDict
return my_dict
|
e3151a93661c2f8a805c94a7ddf93139f766a396 | rafaelperazzo/programacao-web | /moodledata/vpl_data/359/usersdata/287/109647/submittedfiles/lecker.py | 411 | 3.703125 | 4 | # -*- coding: utf-8 -*-
q1=int(input('digite os elementos da primeira lista: '))
q2=int(input('digite os elementos da segunda lista: '))
lista1=[]
lista2=[]
for i in range (0,q1):
lista1.append(int(input('digite o valor')))
for i in range (0,q2):
lista2.append(int(input('digite os valores da lista 2')))
print... |
428737aad901bf7ff52c5563e57a7387f5313f95 | Mumulhy/LeetCode | /954-二倍数对数组/CanReorderDoubled.py | 671 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# LeetCode 954-二倍数对数组
"""
Created on Fri Apr 1 10:30 2022
@author: _Mumu
Environment: py38
"""
from collections import Counter
from typing import List
class Solution:
def canReorderDoubled(self, arr: List[int]) -> bool:
cnt = Counter(arr)
for num in sorted(cnt.keys(), ke... |
e93ec3e522c93b2042f5ec120f85bdedabc74569 | hwangboksil/algorithm | /programmers/python_ex/level-1/divisibleArrayNums.py | 1,050 | 3.59375 | 4 | # 나누어 떨어지는 숫자 배열
# array의 각 element 중 divisor로 나누어 떨어지는 값을 오름차순으로 정렬한 배열을 반환하는 함수, solution을 작성해주세요.
# divisor로 나누어 떨어지는 element가 하나도 없다면 배열에 -1을 담아 반환하세요.
def solution(arr, divisor):
return sorted([i for i in arr if i % divisor == 0]) or [-1]
print(solution([2, 36, 1, 3], 10))
# 1. if문을 사용하지 않고 or를 사용하면 값이 없는 경... |
cd888ce6401f27cfee3e998b2f00633efba831a7 | ltadeu6/python-numeric-optimization | /pynumoptimizer/point.py | 704 | 3.6875 | 4 | #! /usr/bin/env python3
import numpy as np
class Point(object):
def __init__(self, dim):
self.p = np.zeros(dim)
self.v = 0
def __str__(self):
return "Params: {}, ObjValue: {}".format(", ".join(["{:>10.5f}".format(p) for p in self.p]),
s... |
e3d4a5a907375143172a21dd8ddf27f2e3c1d126 | wffeige/algorithm015 | /Week_02/350_两个数组的交集.py | 523 | 3.671875 | 4 | #!coding:utf-8
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
# 存放共同元素
lst_set = list()
for i in nums1:
if not nums2:
break
i... |
66a053938230fd90cc957e6ce973849ed476c96d | liyinging/leetcode | /Python/Binary_Tree_Inorder_Traversal.py | 862 | 3.671875 | 4 | from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def inorderTraversalRecursion(self, root: TreeNode) -> List[int]:
ans = []
def traverse(node):
non... |
46e0585bcfab64ac677ad3576c28f2b3cc798f7e | JGuymont/ift2015 | /3_tree/Tree.py | 3,536 | 3.5625 | 4 | from ListQueue import ListQueue
#ADT Tree (Classe de base)
class Tree:
#inner class Position
class Position:
def element( self ):
pass
def __eq__( self, other ):
pass
def __ne__( self, other):
return not( self == other )
# retourne la rac... |
a64b6576f6e2bf1abe0ffd5b9f1e31ced2656050 | anuragsingh7700/FITC_anurag_singh | /q1.py | 62 | 3.546875 | 4 | t=int(input())
for i in range(t):
print(input().count('5')) |
954ed1406bb3308d6bc1eafbcff31a43a0201d3f | IamJenver/mytasksPython | /asimptotic.py | 336 | 3.78125 | 4 | # На вход программе подается натуральное число n. Напишите программу,
# которая вычисляет значение выражения
n = int(input())
counter = 0
from math import log
for i in range(1, n + 1):
counter = counter + 1 / i
counter -= log(n)
print(counter) |
1bf95b285168d5e332de9f082227a89833161fde | Ernestbengula/python | /kim/Payroll.py | 448 | 3.859375 | 4 | # create a payroll
#Gross_Pay
salary =float(input("Enter salary"))
wa =float(input("Enter wa"))
ha=float(input("Enter ha"))
ta =float(input("Enter ta"))
Gross_Pay =(salary+wa+ha+ta)
print("Gross Pay ", Gross_Pay)
#Deduction
NSSF =float(input("Enter NSSF"))
Tax =float(input("Enter Tax"))
Deductions=(NSSF+Tax)
print(... |
9e2c874da0bfd4df1e818ee9d333f75c304b4a8d | mintheon/Practice-Algorithm | /Minseo-Kim/leetcode/5_Longest_palindromic_substring.py | 769 | 3.671875 | 4 | # two pointer solution O(n^2)
# Middle can be any index from 0 to (n-1) in the loop.
# Two pointers depart from middle point and expand to left and right.
class Solution:
def expand(self, left: int, right: int, s: str) -> str:
result = ""
while 0 <= left and right <= len(s) - 1:
if s[le... |
79da11b8d911fc21de9d192f398aa2c076dc0e72 | wujjpp/tensorflow-starter | /py/l2.py | 2,213 | 3.84375 | 4 | # 关键字参数
def person(name, age, **kw):
if 'city' in kw:
# 有city参数
pass
if 'job' in kw:
# 有job参数
pass
print('name:', name, 'age:', age, 'other:', kw)
person('Jane', 20)
person('Jack', 20, city='Suzhou', job='Test')
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack'... |
e02903be1a5a2039f3e8d5ff08d88599ff5e00c4 | aimdarx/data-structures-and-algorithms | /solutions/Strings/validate_ip_address.py | 3,167 | 4.09375 | 4 | """
Validate IP Address
Given a string IP, return "IPv4" if IP is a valid IPv4 address, "IPv6" if IP is a valid IPv6 address or "Neither" if IP is not a correct IP of any type.
A valid IPv4 address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and xi cannot contain leading zeros.
For example, "192.168.1.1... |
748ce036df96aaac0e975c76a4b042799e92c1a0 | princess0307/PythonExercises | /ex36.py | 158 | 3.671875 | 4 | class Add(object):
def __init__(self,name,age):
self.name=name
self.age=age
print self.name
obj=Add("chanchal",20)
|
5e36933b188437cb16cfe741886e9fcc97d8abdd | fjaschneider/Course_Python | /Exercise/ex044.py | 807 | 3.671875 | 4 | print('{:=^50}'.format(' Schneider Store '))
p = float(input('Preço das compras: R$ '))
print('''Formas de pagamento:
[ 1 ] à vista dinheiro/ cheque
[ 2 ] à vista no cartão
[ 3 ] 2x no cartão
[ 4 ] 3x ou mais no cartão''')
op = int(input('Qual é a opção? '))
if op == 1:
print('O valor das compras ficou R$ {:.2f} co... |
be0f88fea248bb9d8954b2e00396bbf164a94cac | fadymedhat/TMIXT | /HOCRParser/autocorrect/word.py | 3,092 | 3.53125 | 4 | # Python 3 Spelling Corrector
#
# Copyright 2014 Jonas McCallum.
# Updated for Python 3, based on Peter Norvig's
# 2007 version: http://norvig.com/spell-correct.html
#
# Open source, MIT license
# http://www.opensource.org/licenses/mit-license.php
"""
Word based methods and functions
Author: Jonas McCallum
https://git... |
94ce4dfb752d2056cab38cfc2f58f6bac71f29bb | gordol/CrossHair | /crosshair/examples/PEP316/bugs_detected/hash_consistent_with_equals.py | 769 | 3.515625 | 4 | class HasConsistentHash:
"""
A mixin to enforce that classes have hash methods that are consistent
with their equality checks.
"""
def __eq__(self, other: object) -> bool:
"""
post: implies(__return__, hash(self) == hash(other))
"""
raise NotImplementedError
class ... |
b72a990b4a437c771b1993855d180178a1276a40 | iankatzman/CS112-Spring2012 | /hw08/math_funcs.py | 404 | 3.984375 | 4 | #!/usr/bin/env python
import math
def ptop((x1, y1), (x2, y2)):
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
return distance
x1 = int(raw_input("enter a number for x1: "))
y1 = int(raw_input("enter a number for y1: "))
x2 = int(raw_input("enter a number for x2: "))
y2 = int(raw_input("enter a number for... |
5c15a640c5f20e1035e7927112631a69ae88c433 | xaowoodenfish/Chapter2 | /Chapter2_eig8.py | 417 | 3.921875 | 4 | # Time Oct.20 2015
# A simple input to judge whether prime number
from math import *
a = raw_input('Input an integer:')
while True:
if not a.isdigit():
print 'Error: try again.'
a = raw_input('Input an integer:')
else:
print 'The integer is:%s'%a
break
b = int(a)
N = int(sqrt(b))... |
0083fd2066590e429270f2980662573d0c13a620 | sungillee90/python-exercise | /FromJClass/MazeProject.py | 1,630 | 3.921875 | 4 | # Backtracking
maze = [[".", ".", ".", "."],
[".", "X", "X", "X"],
[".", ".", ".", "X"],
["X", "X", ".", "."]]
def print_maze(maze):
for row in maze:
row_print = ""
for value in row:
row_print += value + " "
print(row_print)
print(maze)
print_maze(maze)... |
1e7e8fd1718883a228730b96cbdcaa664735d188 | peterlaraia/DailyProgrammerChallenges | /e282/Instruction.py | 291 | 3.609375 | 4 | class Instruction:
def __init__(self, base, value):
self.base = base
self.val = value
def getBase(self):
return self.base
def getVal(self):
return self.val
def __str__(self):
return "base: {}, value: {}".format(self.base, self.val)
|
33ef4ce59f3e15963c924b68fbc4d1d082bea34d | Austin-Bell/PCC-Exercises | /Chapter_2/famous_quotes.py | 379 | 3.859375 | 4 | #find a quote from a famous person. Print the quote adn the name of its author.
famous_quote = ' once said, "A person who never made a mistake never tried anything new."'
#print(famous_quote)
#repeat exericies above, but this time store the famous person's name iin a variable called famous_person.
famous_person = "Al... |
5c1a906241a975a7e113ad7d6ae73b679ad194cf | fenglihanxiao/Python | /Module01_CZ/day9_reference/04-代码/day9/151_引用(数值、布尔、字符串).py | 440 | 3.78125 | 4 | """
演示引用(数值型、布尔型、字符串型)
"""
# a = 1
# b = 1
# print(id(1))
# print(id(a))
# print(id(b))
# print((id(2)))
# a = 2
# print("-------")
# print(id(a))
# flag1 = True
# flag2 = False
# print(id(flag1))
# print(id(flag2))
# flag1 = False
# print("-------------")
# print(id(flag1))
# print(id(flag2))
str1 = "a"
str2 = "a"
p... |
2c87771069c9fe8c8c74793ba31fd14fba114a1f | sy850811/Python_DSA | /Kth_largest_element.py | 461 | 3.671875 | 4 | import heapq
def kthLargest(lst, k):
######################
#PLEASE ADD CODE HERE#
######################
heap=lst[:k]
heapq.heapify(heap)
n1=len(lst)
for i in range(k,n1):
if lst[i]>heap[0]:
heapq.heappop(heap)
heapq.heappush(heap,lst[i])
... |
ca96d354feb59f7757802609165696583e4c7ab2 | abdularifb/Pythonprograms | /SimpleInterest.py | 180 | 3.859375 | 4 | P = input("Enter the Principle Amount:")
R = input("Rate of Interest:")
N = input("No Of Years:")
si = float(P * N * R)/100
print "Simple Interest is {}".format(si)
|
524c5da8f7997bd7c67b19a84a105a712991d083 | ikhvastun/deepLearning | /randomizer/shuffle.py | 658 | 4.03125 | 4 | """
Tools for shuffling arrays
"""
import numpy as np
def randomIndices( length ):
random_indices = np.arange( length )
np.random.shuffle( random_indices )
return random_indices
#shuffle several arrays consistencly
def shuffleSimulataneously( *arrays ):
#check that all input arrays have the same l... |
e4e1e1ec13126d4766104aa8d40825bcaf1abc5b | CharlyWelch/data-structures | /dll.py | 3,252 | 4.15625 | 4 | class Node(object):
""" Class object for instantiating nodes to add to the doubly-linked list """
_value = None
_next = None
_prev = None
def __init__(self, value):
self._value = value
def value(self):
return self._value
def next(self, next):
self._next = next
... |
8a50f197003450d2661257d387cd15ed25a3679f | ParkChangJin-coder/pythonProject | /random_tutorial.py | 1,311 | 3.78125 | 4 | import random
#randint : 시작 숫자부터 끝 숫자 사이에 임의 숫자
print(random.randint(1,100))
#random : 0 ~ 1 사이의 임의 플롯
print("random.random() : ", random.random())
#uniform(시작 소숫점, 끝 소숫점) : 시작 소숫점 ~ 끝 소숫점 사이의 임의 플롯
print("random.uniform() : ", random.uniform(0.1,0.02))
#randrange(정수) : 0부터 정수 미만의 수 사이에서 임의수
#randrange(시작숫자, ... |
dc9be2de5f8367600809aa2ce8ba8608cf1119c7 | yunjung-lee/class_python_data | /test1.py | 225 | 3.6875 | 4 | ###CSV 안에 comma를 포함한 문자열이 있을 때 문자열은 상관없이 분리하는 방법
import csv
a='1234,John Smith,100-0014,"$1,350.00",3/4/14'
for a in csv.reader([a],skipinitialspace=True):
print(a)
|
a4e3fb8f436a801576f0a4d15c0b5ebd6d733606 | DeepLearningSky/qandabot | /utils/generate_txt_from_csv.py | 406 | 3.765625 | 4 | import sys
def generate_txt_from_csv(filename, q = True, a = False):
for l in open(filename):
sentences = l.strip().split('\t')
if(len(sentences) >= 3):
question = sentences[1]
answer = sentences[2]
if q and a:
print question
print answer
elif a:
print answer
else:
print question
... |
25227aed6439091c15bb1a5fc6babd6fd29df103 | abhijitdey/coding-practice | /trees_graphs/trie.py | 1,147 | 4.03125 | 4 | class Node:
def __init__(self):
# Each node can have a max of 26 children (if we consider only lower-case chars)
# print('Initializing Node')
self.children = [None]*26
self.is_word = False
class Trie:
def __init__(self):
# print('Initializing Trie')
self.root ... |
11c3aba4ec50bd58f01459251036a325bce5dddf | MarineChap/Machine_Learning | /Classification/Section 15 - K-Nearest Neighbors (K-NN)/K_NN_algorithme.py | 2,745 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Part 3 : K-Nearest Neighbors in following the course "Machine learning A-Z" at Udemy
The dataset can be found here https://www.superdatascience.com/machine-learning/
Objective : Predict the likelihood for a person to buy an SUV in function of his age
... |
8514278a72cd0ae0b04dd2013be27ce4275a39d1 | jadhaddad01/SudokuSolver | /solver.py | 3,694 | 3.859375 | 4 | ## Author: Jad Haddad
import puzzleAPI
import time
"""
#manually entered puzzle
puzzle = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3... |
22ee0a4db1572243ab763a560ce389120f3aa7f7 | routdh2/100daysofcodingchallenge | /Day5/find_distance_value.py | 428 | 3.65625 | 4 | #Problem Statement: https://leetcode.com/problems/find-the-distance-value-between-two-arrays
class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
count=0
for i in arr1:
flag=False
for j in arr2:
if abs(i-j)<=d:
... |
35acc68784cc7c656abbd7315b4d14b3d1ffdb27 | kadirkoyici/pythonkursu | /karalamalar_src_idi/sayial.py | 391 | 3.5625 | 4 | # -*- coding: utf-8 -*-
sayi = input("Bir Sayi Giriniz:")
if sayi==5:
print "Girdiginiz sayi 5 tir"
else:
print "girdiginiz ssayi 5 degildir %s dir " %sayi
kelime = raw_input("Bir kelime giriniz")
if kelime=="kadir":
print "girdiginiz kelime kadirdir"
print "dogru kelime bu"
else:
print "girdgin... |
f2c748bc52b971e1d29e377a87985b2082864338 | b01lers/b01lers-library | /2019tuctf/Crypto/Something in Common [405 pts]/solve.py | 1,700 | 3.5625 | 4 | '''
Explanation
The given information shows two ciphertext, two public keys, and a single common modulus. With this information we can apply bezout's identity using the extended euclidean algorithm. Which states that there are two coefficients, which we can call a and b, such that a * e1 + b * e2 = gcd(e1,e2). We also ... |
aa47a251564828ce69662bd835cbc68c32cbcfc3 | nicholasrokosz/python-crash-course | /Ch. 6/favorite_places.py | 284 | 3.734375 | 4 | favorite_places = {
'nick': ['tucson', 'milwaukee'],
'nicole': ['bend', 'sedona'],
'al': ['madrid', 'barcelona', 'rome'],
}
for person, places in favorite_places.items():
print(f"{person.title()}'s favorite places are:")
for place in places:
print(place.title())
print("\n") |
c265190d0c1775a52dc143c8f4fa6bde09ce5784 | maCucyrt07/Birthday-quiz | /birthday.py | 1,935 | 4.75 | 5 | """
birthday.py
Author: MaCucyrt07
Credit: Ella, Kyle
Assignment: Birthday Quiz
Your program will ask the user the following questions, in this order:
1. Their name.
2. The name of the month they were born in (e.g. "September").
3. The year they were born in (e.g. "1962").
4. The day they were born on (e.g. "11").
... |
efed965bb69f8a371ef7da6960aa9bf7f870b2c7 | emrahselli/python_challenge | /PyBank/main_csv.py | 1,629 | 3.515625 | 4 | import os
import csv
csvpath = os.path.join('Resources', 'budget_data.csv')
with open(csvpath, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
next(csvreader, None)
row = next(csvreader, None)
max_m = row[0]
min_m = row[0]
profit = float(row[1])
row_counter = 1... |
f039b8695207daa2fea92fdd2528f268d5420475 | BazzalSeed/LeetCoding | /counting_bits/counting_bits.py | 702 | 3.6875 | 4 | """
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate
the number of 1's in their binary representation and return them as an array.
Atacched pic to see the core concept
"""
class Solution(object):
def countBits(self, num):
"""
:type num: int
... |
32ed9e077843e51d9fc514d6cc7b13af66226566 | rm-hull/luma.examples | /examples/game_of_life.py | 2,319 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014-2023 Richard Hull and contributors
# See LICENSE.rst for details.
# PYTHON_ARGCOMPLETE_OK
"""
Conway's game of life.
Adapted from:
http://codereview.stackexchange.com/a/108121
"""
import time
from random import randint
from demo_opts import get_devic... |
eaf31902187cdd442bb3619fce76f1186917a004 | FionaT/Digital-Image-Processing_Proj | /proj_2/0201/proj_02-01-a.py | 1,969 | 3.890625 | 4 | # Write a halftoning computer program for printing gray-scale images
# based on the dot patterns just discussed. Your program must be able
# to scale the size of an input image so that it does not exceed the
# area available in a sheet of size 8.5 x 11 inches (21.6 x 27.9 cm).
# Your program must also scale the gra... |
dce6b989352a096fbd97ad55adc7b17b07f93047 | MartinMa28/Algorithms_review | /backtracking/knight_tour.py | 1,768 | 3.75 | 4 | class Solution():
def __init__(self, n):
self.size = n
self.board = [[-1 for _ in range(self.size)] for _ in range(self.size)]
self.directions = ((2, 1), (-2, 1), (2, -1), (-2, -1),
(1, 2), (-1, 2), (1, -2), (-1, -2))
def _is_safe(self, row, col):
... |
534b93d7e10626cb00a52c95a75686569f0673f3 | mario21ic/abstract-data-structures | /python/tree/Arbol.py | 2,805 | 3.796875 | 4 | class Node:
def __init__(self, label, parent=None):
self.label = label
self.parent = parent
def __str__(self):
return self.label
def __repr__(self):
return self.label
def have_parent(self):
return self.parent == None
class Tree:
def __init__(self):
self.root = None
self.no... |
4206cb3d60e1bf4623268ead41d19d4a5080ab5a | hyuueee/Python-Crash-Course | /aliens.py | 957 | 3.859375 | 4 | #字典列表
alien_0={'color':'green','points':5}
alien_1={'color':'yellow','points':10}
alien_2={'color':'red','points':15}
aliens=[alien_0,alien_1,alien_2]
print(aliens)
#使用range
aliens=[]
for alien_number in range(30):#创建30个外星人,range的作用是告诉python循环多少次
new_alien={'color':'green','point':5,'speed':'slow'}
aliens.appen... |
629fabece847eb52995bf752bc4caed0b59fc171 | PravinSelva5/LeetCode_Grind | /Linked_Lists/LinkedList.py | 6,191 | 4.1875 | 4 | '''
- A linked list is a linear data strucutre where its elements are not stored in contiguous order in memory unlike an array.
- Two types:
- Singly Linked List
- Doubly Linked List
- Singly Linked List:
- nodes only have a pointer to the NEXT ELEMENT
- first node in the linked list is called the HEA... |
93aed7ebf886ad31f7b2b2c8d0fbdd9ec9705b80 | yccdesign/Python-for-Everybody | /ex_7_2/ex_7_2_avgnum.py | 449 | 3.515625 | 4 | fname = input('Enter file name:')
fileopen = open(fname)
count = 0
totalnum = 0
for line in fileopen:
if line.startswith('X-DSPAM-Confidence:'):
locate = line.find(':')
aftercolon = line[locate+1:]
num = aftercolon.strip()
floatnum = float(num)
totalnum = totalnum + floatnum
... |
a9a8c3ca0a588d4ac82576bea0af27c1e2b0b75a | magnuskonrad98/max_int | /FORRIT/timaverkefni/29.08.19/greatest_common_divisor.py | 259 | 3.765625 | 4 | m = int(input("Input the first integer: ")) # Do not change this line
n = int(input("Input the second integer: ")) # Do not change this line
gdc = 0
for i in range(1, m):
if m % i == 0 and n % i == 0:
if i > gdc:
gdc = i
print(gdc)
|
92664a01a546facdcbe63e2d77e85e91c4ee9d81 | amberrevans/pythonclass | /chapter 4 and 5 programs/commissions.py | 679 | 4.09375 | 4 | #amber evans
#9/15/20
#program 4-1
#This program calculates sales commissions.
#create a variable to control the loop.
keep_going= 'y'
#Calculate a series of commissions.
while keep_going=='y':
#get a salespersons sales and commission rate.
sales = float(input('Enter the amount of sales: '))
comm_rate= fl... |
5cccfde3492de3a8f7b9ac59c1ea953d4b00aaff | jiatongw/notes | /code/queue_stack/reverse_polish_notation.py | 1,028 | 3.9375 | 4 | ## LC 150
## Input: ["2", "1", "+", "3", "*"]
## Output: 9
## Explanation: ((2 + 1) * 3) = 9
def reverse_polish_notation(tokens):
stack = []
for num in tokens:
if num == "+":
num2 = stack.pop()
num1 = stack.pop()
result = num1 + num2
stack.append(result... |
81edb0d2dde52930b1dfcf67d710c4c867daf2cc | MariaNazari/Introduction-to-Python-Class | /cs131ahw4Final.py | 1,311 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
The purpose of this program is to calculate how many times bigger the Alaskan district
is from an average Wisconsin district
Background:
Wisconsin has eight congressional districts covering its land area of 169,790
square kilometers, while Alaska has just on... |
69557ae4b9f07fc95ebb551c39a8008e7949e6c2 | q36762000/280201102 | /lab7/example4.py | 378 | 4.03125 | 4 | password = input("enter a password:")
valid = True
if len(password) != 8:
valid = False
if password.lower() == password:
valid = False
if password.upper() == password:
valid = False
count = 0
for i in range(10):
if str(i) in password:
count += 1
if count == 0:
valid = False
if valid:
print("Your passwor... |
8de00655ec55cdd75ef84b31f327c19bfd00509a | sky7sea/KDD_Daily_LeetCoding_Challenge | /0329-0404 (Week_1)/RobertHan/039.Length of a Linked List/solution.py | 766 | 3.96875 | 4 | #https://binarysearch.com/problems/Length-of-a-Linked-List
'''
Given a singly linked list node, return its length. The linked list has fields next and val.
Example
- Input
node = [5,4,3,]
- Output
3
'''
# class LLNode:
# def __init__(self, val, next=None):
# self.val = val
# self.next = next
... |
357b3df77357f9739d458ce94fdb0f3559621b32 | xucaimao/python | /kid/e1201.py | 263 | 4.09375 | 4 | names=[]
print("Enter 5 names:")
for i in range(5):
names.append(input())
print("The names are",end=" ")
for na in names:
print(na,end=" ")
print()
names.sort()
print("After sorted,The names are",end=" ")
for na in names:
print(na,end=" ")
print()
|
f97ea3cb395a68753b9797484d4bf88996f8d533 | gonzaloquiroga/neptunescripts | /lation2.py | 799 | 3.703125 | 4 | #! /usr/bin/env python
import re #It creates an object where the package of Regular expressions are in Python
InFileName = 'Marrus_claudanielis.txt'
InFile = open (InFileName, 'r') #opening the file to read it!
LineNumber = 0
for Line in InFile:
Line = Line.strip()
if LineNumber > 0:
#print (LineNumber)
#... |
54128716fa095b91e0a5dc4c95678332b47af24c | TrickFF/helloworld | /task3.2.py | 974 | 3.859375 | 4 | # 3:
import random
player = {
'name': '',
'health': 100,
'min_damage': 30,
'max_damage': 50,
'armor': 1.2
}
enemy = {
'name': 'COVID-19',
'health': 100,
'min_damage': 10,
'max_damage': 50
}
player['name'] = input('Введите свое имя - ')
def attack(player, enemy):
dmg_player =... |
714bf09379b5017d6778bdd862e9758fec9a470e | sqw3Egl/TSTP | /TSTP_Scripts/chapt4_examples/def_variable_example2.py | 210 | 4.34375 | 4 | #save the result the function returns in a variable for use later in the program.
def f(x):
return x + 1
z = f(5)
if z == 5:
print("z is 5")
else:
print("z is not 5, its something else!")
|
a1452e7cfc087e81d2437e59c07315770b4d1dfa | sevenhe716/LeetCode | /Heap/q855_exam_room.py | 16,782 | 3.53125 | 4 | # Time: seat O(n) leave O(log(n))
# Space: O(n)
# 解题思路:
# 多次调用,需要维护当前座位信息的数据结构,当数据稀疏时,维护座位索引即可
# 对于相邻的座位i,j,离相邻学习的最大距离为d = (j-i)//2,新的位置为i+d,但需要保证i+1<j,或者说保证存在座位,则不会取到这种情况(我的计算方式太复杂)
# 特殊情况:左右两端需要单独判断,d = seat_index[0], d = self.N-1-seat_index[-1],从左至右选择第一个满足条件的解
# O(n)并非效率最高的解法,用最大堆或者优先队列来维护下一个最优位置,可以把seat的时间复杂度降为O(... |
48361c4f4904145d397db0376b0773f79d43518a | bujars/csc113 | /Chapter9prac.py | 2,250 | 4.34375 | 4 | class Dog():
#A simple attempt to model a dog.
def __init__(self, name, age): #NOTE init function is constructor, def means define a function,
#this is a "self" function because it accepts self, or an instance as a paramter
# "Initialzie name and age attributes"
self.name=name
s... |
1e81f1ad64af88917fd409183b061626ef141577 | silvafj/BBK-MSCCS-2017-19 | /POP1/mocks/practical-one/question1a.py | 164 | 3.6875 | 4 | def fib(n):
terms = [0, 1, 1]
for i in range(3, n):
terms.append(terms[i-1] + terms[i-2])
return terms
for v in fib(20):
print(v, end=" ")
|
40f35423f3a6f923157756592a77993fbeaf94ef | KevenGe/LeetCode-Solutions | /books/《剑指offer》/剑指 Offer 41. 数据流中的中位数.py | 875 | 3.59375 | 4 | # 剑指 Offer 41. 数据流中的中位数
# https://leetcode-cn.com/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof/
import heapq
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.A = []
self.B = []
def addNum(self, num: int) -> None:
if ... |
c87850a7d419ff0a10a2d24c5950b51baeced6a1 | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/scrsha001/util.py | 2,733 | 3.796875 | 4 | # Shaaheen Sacoor SCRSHA001
#30 April 2014
# Programs that to be utilized for 2048 game
#Creating grid
def create_grid(grid):
height =4
for i in range(4):
grid.append([0]*4)
return grid
#Printing Grid
def print_grid(grid):
print("+--------------------+")
for y in range(4):
... |
e499cfcd27e72aeccc08228d3497b03d67b95b77 | blackbogdan/interviewcake | /task1_stocks.py | 5,473 | 4.34375 | 4 | # coding=utf-8
# Suppose we could access yesterday's stock prices as a list, where:
#
# The indices are the time in minutes past trade opening time, which was 9:30am local time.
# The values are the price in dollars of Apple stock at that time.
# So if the stock cost $500 at 10:30am, stock_prices_yesterday[60] = 5... |
50a5f662940e4e9c9589abd4f87ff3e4d8444484 | adebray/adebray.github.io | /python/mandelbrot.py | 917 | 3.609375 | 4 | #Draws a Mandelbrot set.
from Tkinter import *
def main():
master = Tk()
w = Canvas(master,width=750,height=675)
w.pack()
a = -2.0
while a < 1.75:
b = -1.25 #Unfortunately this skips over zero
while b < 1.25:
if in_set(a,b):
create_point(give_x(a),give_y(b),w)
b = b + 0.001 #This tak... |
6fb3874538b010fa6367cfd1ef6ed6fd392e91c3 | TheJoeCollier/cpsc128 | /code/python2/tmpcnvrt.py | 1,242 | 4.5 | 4 | ###########################################################
## tmpcnvrt.py -- allows the user to convert a temperature
## in Fahrenheit to Celsius or vice versa.
##
## CPSC 128 Example program: a simple usage of 'if' statement
##
## S. Bulut Spring 2018-19
## Tim Topper, Winter 2013
#############################... |
9158a9d71afe231d29baa78e499900f78458650d | ZGingko/algorithm008-class02 | /Week_08/242.valid-anagram.py | 599 | 3.546875 | 4 | class Solution:
"""
242.有效的字母异位词 https://leetcode-cn.com/problems/valid-anagram/
"""
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
base = ord('a')
counter = [0] * 26
for i in range(len(s)):
counter[ord(s[i]) - base]... |
f45619416d5d80444b45d288dc54089b4c577add | marleneargenton/Python-Ipea | /Interaction.py | 2,798 | 3.78125 | 4 | # Python4ABMIpea - Exercício 2
#
# Professor: Bernardo Furtado
#
# Autora: Marlene Aparecida Argenton
#
# Outro módulo, import as classes e contém algumas funções:
# Uma para criar os agentes e as lojas, a partir de um número n e controla o id específico i
# Criam-se listas
# Faz-se um loop utilizando n, i, a... |
b295affe0a0ad0ce0754b4e57eb09b68e5c6df13 | larikova/python-practice | /lacey-book/109.py | 642 | 4.15625 | 4 | print("1) Create a new file")
print("2) Display the file")
print("3) Add a new item to the file")
selection = int(input("Make a selection 1, 2 or 3: "))
if selection == 1:
file = open("Subjects.txt", "w")
subject = input("Enter a school subject: ")
file.write(subject + "\n")
file.close()
elif selection ... |
9218271e4fb907b966c079fe1d0ec1a4f185e263 | Yoyoshix/random | /tilde_expression.py | 1,122 | 3.984375 | 4 | def is_prime(number):
if number == 1 or number%2 == 0:
return 0
for i in range(3, int(number**0.5)+1, 2):
if number%i == 0:
return 0
return 1
def prime_factor(number):
prime_list = []
while number % 2 == 0:
prime_list.append(2)
number = number // 2
di... |
a81799e19c04debcb218c689387e353ad2230390 | Haris-Noori/algoassignment2 | /i150013_Sabkat/q6.py | 557 | 3.5 | 4 | #q6
def count( S, m, n ):
table=[[0 for x in range(m+1)] for x in range(n+1)]
for i in range(1,m):
table[0][i] = 1;
for i in range(1,m):
for j in range(1,n):
if(S[i-1]>j):
table[i][j]=table[i-1][j]
else:
table[i][j]=table[i-1... |
a6fb79df3858935d9307e87da861c3fb5acf2cdd | draganmoo/trypython | /pandas_notes/Song_Tian_Pandas/s1_Series.py | 273 | 3.671875 | 4 | import pandas as pd
# 生成一个20行的series
d = pd.Series(range(5))
print(d)
"""
0 0
1 1
2 2
3 3
4 4
dtype: int64
"""
"""对d进行前n项累加"""
print(d.cumsum())
"""
0 0
1 1
2 3
3 6
4 10
dtype: int64
""" |
8238b59030b1874ae2f2e532a2f07a6c2ffcbf50 | PC-coding/Exercises | /data_structures/linked_lists/1_insert_start/solution/solution.py | 329 | 3.734375 | 4 | # Write your solution here
class Node:
def __init__(self, data):
self.data = data
self.next = None
class linkedList:
def __init__(self, head=None):
self.head = head
def insert_at_start(self, data):
Node1 = Node(data)
Node1.next = self.head
self.head = Node1
... |
4e1e17d8336917f19eb92ddb8d2d61c44ab9af75 | SmischenkoB/campus_2018_python | /Oleksandr_Mykhailovskyi/2/MapFunctions.py | 414 | 4.28125 | 4 | import math
def map_functions(arg, *functions):
"""
Given object arg and functions - subsequently use those functions on arg.
Args:
arg (obj): any object.
*functions: functions which can take arg.
Returns:
arg.
"""
for func in functions:
arg = func(arg)
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.