blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
17ebae8e211b8434bf67885727780f0f49786a7b | parulsharma-121/CodingQuestions | /day_42_DIStringMatch.py | 712 | 3.6875 | 4 | '''
Given a string S that only contains "I" (increase) or "D" (decrease), let N = S.length.
Return any permutation A of [0, 1, ..., N] such that for all i = 0, ..., N-1:
If S[i] == "I", then A[i] < A[i+1]
If S[i] == "D", then A[i] > A[i+1]
Example 1:
Input: "IDID"
Output: [0,4,1,3,2]
Example 2:
Input: "III"
Outp... |
1c94db7e17fb5664f206afb59880e3016ea8c7c1 | fwparkercode/Programming2Notes-2017 | /Searching A.py | 2,212 | 3.859375 | 4 | # Searching
file = open('data/villains.txt', 'r')
for line in file:
# strip method removes spaces and \t \n from a string
print(line.strip())
file.close()
file = open('data/villains.txt', 'r')
for line in file:
print("Hello", line.strip())
file.close()
# We can also write to a file.
''''
file = open... |
a4c5f9dd8b5495cc9de6519bad0161124ec30a1b | chendamowang/lianxi | /Data Structures and Algorithms/LList.py | 2,952 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
单链表python实现
"""
class LNode:
def __init__(self, elem, next_=None):
self.elem = elem
self.next = next_
class LinkedListUnderflow(ValueError):
pass
class LList:
def __init__(self):
self._head = None
def is_empty(self):
return self._head is N... |
17e64d72f8d4bc11cc1abc73cde526b597827304 | yinhuax/leet_code | /datastructure/hash_table/Intersect.py | 1,892 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Mike
# @Contact : 597290963@qq.com
# @Time : 2021/2/2 22:38
# @File : Intersect.py
"""
给定两个数组,编写一个函数来计算它们的交集。
"""
from typing import List
class Intersect(object):
def __init__(self):
pass
def intersect(self, nums1: List[int], nums2: Li... |
565d00d577357a5e03be893e6b3b8b08189ad695 | jbhennes/CSCI-220-Programming-1 | /Chapter 7 Decisions/letterGradeSection1.py | 292 | 3.953125 | 4 | def main():
for i in range(5):
grade = eval(input("Enter grade: "))
if grade >= 90:
print("A")
elif (grade >= 80 and grade < 90):
print("B")
elif (grade >=70 and grade < 80):
print("C")
else:
print("F")
|
8f8c540c0ee7d7ad24b158ca10cd883630da82a5 | pavangabani/DAA_Lab | /lab4.py | 1,108 | 3.734375 | 4 | def countingSort(a,b):
size = len(a)
output = [0] * size
count = [0] * (b+1)
for i in range(0, size):
count[a[i]] += 1
for i in range(1, b+1):
count[i] += count[i - 1]
i=size-1
while i >= 0:
output[count[a[i]] - 1] = a[i]
count[a[i]] -= 1
i -= 1
fo... |
d26e80c10a818a11241e2052bc54a2a83d0afc0b | MrRuban/lectures_devops2 | /Python/samples3/types/6lists1/1.6.9.py | 341 | 3.875 | 4 | #!/usr/bin/python3
"""
Удаление элемента
"""
li = ["a", "b", "new", "mpilgrim", "z", "example", "new", "two", "elements"]
print(li.remove("z")) # Does not return a value
print(li)
li.remove("new")
print(li)
x = li.pop()
print(x, li)
x = li.pop(-1)
print(x, li)
x = li.pop(3)
print(x, li)
li.remove("z") # ValueE... |
2aed13792acaae055a416aaa936388b4ba750567 | borntoburnyo/AlgorithmInPython | /medium/71_simplify_path.py | 519 | 3.78125 | 4 | class Solution:
def simplifyPath(self, path):
# Initialize a stack
res = []
# Split the path by '/'
splitPath = path.split('/')
for i in range(len(splitPath)):
# Pop to previous directory
if splitPath[i] == '..' and res:
res.pop()
... |
1fa73d85fcb3fe8271985fb874229137bbdfd580 | lingsitu1290/Data-Science-Exercises | /multi.py | 1,354 | 3.703125 | 4 | ''' Load the Lending Club Statistics.
Use income (annual_inc) to model interest rates (int_rate).
Add home ownership (home_ownership) to the model.
Does that affect the significance of the
coefficients in the original model? + Try to add the
interaction of home ownership and incomes as a term.
How does this impac... |
9c2a91885a8e8e674347f9ac2f2f8c177837ebff | johncornflake/dailyinterview | /imported-from-gmail/2020-01-09-compare-version-numbers.py | 1,426 | 4.3125 | 4 | Hi, here's your problem today. This problem was recently asked by Amazon:
Version numbers are strings that are used to identify unique states of software products. A version number is in the format a.b.c.d. and so on where a, b, etc. are numeric strings separated by dots. These generally represent a hierarchy from ... |
8c2c5166890511650b2ed517db1593b0d791785f | jeffreygray/alexa_topsite_grabber | /alexa_topsite_grabber.py | 1,570 | 3.5 | 4 | # Jeffrey Gray
# alexa_topsite_grabber.py
# takes user input to determine number of sites to rip from Alexa website [http://www.alexa.com/topsites/global]
import urllib.request
import re
from math import ceil
# relevant data determined by user input
n = int(input('Number of sites to load: '))
pages_to_load = int(ceil... |
d453e7a94efeed6e190d1a77bf44c8202ebcee15 | eastmountyxz/Book1-Python-DataCrawl | /第2章-Python基础知识/chapter02_02.py | 130 | 3.578125 | 4 | str1 = input("input:")
print(str1)
#input:"I am a teacher"
age = input("input:")
print(age,type(age))
#25 <class 'str'>
|
733c9de262faa2f342887900278e1d2bf4025680 | oneshan/Leetcode | /accepted/044.wildcard-matching.py | 1,876 | 3.953125 | 4 | #
# [44] Wildcard Matching
#
# https://leetcode.com/problems/wildcard-matching
#
# Hard (19.82%)
# Total Accepted:
# Total Submissions:
# Testcase Example: '"aa"\n"a"'
#
# Implement wildcard pattern matching with support for '?' and '*'.
#
#
# '?' Matches any single character.
# '*' Matches any sequ... |
924344252451e4a7cd34fa77ecad98e42e82b611 | bdaubry/crypto | /vigenere.py | 630 | 3.9375 | 4 | from helpers import alphabet_position, rotate_character
def encrypt(text, key):
new_text = ''
keyind = 0
for i in range(len(text)):
if text[i].isalpha():
new_text = new_text + rotate_character(text[i], alphabet_position(key[keyind % len(key)]))
keyind += 1
else:
... |
eb182743cab193897fe431ce67a2b78427300143 | ycooper/hse_python | /3.5.py | 105 | 3.609375 | 4 | from math import ceil
n = float(input())
if n % 0.5 == 0:
print(ceil(n))
else:
print(round(n))
|
040a4cc63755e165c04bb323a41c778c33899df0 | gmnvh/udacity | /AI for Robotics/Exercices/Lesson 5 - PID Control/PID_01_Proportional - Copy.py | 5,105 | 4.09375 | 4 | # -----------
# User Instructions
#
# Implement a P controller by running 100 iterations
# of robot motion. The desired trajectory for the
# robot is the x-axis. The steering angle should be set
# by the parameter tau so that:
#
# steering = -tau * crosstrack_error
#
# You'll only need to modify the `run` function at ... |
adfecf92911507b0e45be4af80a4565009138c07 | terceroswil/python | /numero.py | 70 | 3.53125 | 4 | #vamos a conocer while :
i=0
while i<10:
print"numero"+ str(i)
i=i+1 |
22568cba36e153bfafd50f5086da6ecc71b7971a | kevinhalliday/ProjectEuler | /python/p005.py | 534 | 4.03125 | 4 | '''
What is the smallest positive number that is evenly divisible by all of
the numbers from 1 to 20?
'''
from functools import reduce
from math import gcd
def lcm(a,b):
''' Returns least common multiple of a and b '''
return a*b // gcd(a,b)
def smallest_multiple(l):
''' Returns the smallest positive num... |
d7f03d410d5e1920aeb83e3887853ac8d3896f17 | giriquelme/Nivelacion-Python | /20082019/000435.py | 335 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 20 18:52:11 2019
@author: rique
"""
#Para escribir una función se utiliza el comando def
def funcion1():
print ("funcion numero 1") # Lo que ejecutara la funcion creada.
funcion1() #Como la funcion ya fue creada, solo hace falta escribirla para arrojar su res... |
27436f5d2223d6935b3defedc82eea76567323c6 | AIMads/Mnist | /finalmnist.py | 4,496 | 4.0625 | 4 | import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
#Gets the dataset from tensorflow
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
#Puts all the data on the gpu for training this is an optimaztion for bigger da... |
2ae1bf7118a0e407bcfd215da6c9f87518f22f02 | chunweiliu/leetcode2 | /serialize_and_deserialize_binary_tree.py | 1,884 | 3.953125 | 4 | """Preorder traversal for serializing all nodes (including None) in a binary tree.
Use preorder because then the first node is always the root.
1
2 3
4 5 # #
# ## #
=> 1,2,4,#,#,5,#,#,3,#,#
How many # in the serialized data?
A. n + 1, n is the number of node.
T... |
7893b7dd517f95279367549ebbd72a1fc5092a5d | cbovalis/reverse-number | /reverse_number.py | 334 | 4.15625 | 4 | #
# A simple fun program that reverses the number
# that is given as input.
#
# Example:
# Input Output
# 345 543
# 123 321
# 67 76
n = int(input("Enter a number: "))
rev = 0
while(n > 0):
dig = n % 10
rev = (rev * 10) + dig
n = n // 10
print("Reverse of the number ... |
3764ba56e3bd6dc3e7fd90aff0bd2dee640ee8b1 | nicolas-git-hub/python-sololearn | /5_More_Types/list_comprehensions.py | 837 | 4.4375 | 4 | # List comprehensions are a useful way of quickly creating lists
# whose contents obey a simple rule.
#
# List comprehensions are inpired by set-builder notation in mathematics.
#
# Example:
cubes = [i**3 for i in range(5)]
print(cubes)
#
# A list comprehension can also contain an if statement to enforce a condition
... |
22b0e96b8a31be528e8f0a6a7ec1cb12c5700b2b | nurshahjalal/python_exercise | /collections/defult_dict.py | 369 | 4.28125 | 4 | from collections import defaultdict
# this is an empty dictionary , no key and value
d = defaultdict(object)
print(d)
# Since Key1 was never assigned as key in dictionary d, hence it will not throw error
print(d['key1'])
# assigning a default value, always return 0 unless assigned
d = defaultdict(lambda: 0)
# will... |
fd2b65ee29c9ab5f6c808f9223d88694bfe434fb | josephbakarji/Gluvn | /gluvn_python/musicFun/MusicFunction.py | 648 | 3.53125 | 4 | '''
Created on May 21, 2016
@author: josephbakarji
'''
def accid(notename):
ac = len(notename[1:-1]) # first letter is a note and last a number
if '#' in notename:
return ac
elif 'b' in notename:
return -ac
else:
return 0
# replace this bulky function by a dictionary.
de... |
829efd8f2a3291d05a40d729ecefce22d7db049e | MatFarias/Projeto-Trabalho-Grau-A---Prog-1 | /InserirPeca.py | 666 | 3.765625 | 4 | class inserir():
codigo = 0
nome = ''
categoria = 0
preco = 0
quant = 0
def inserir_peca(self):
self.codigo = int(input("Digite o código da peça:"))
self.nome = input("Digite o nome da peça:")
self.categoria = int(input("Digite a categoria:"))
self... |
c4c3c64b00e0f33c2edb116922901b49c6117f8e | AltumSpatium/Labs | /4 semester/TS/Lab1/Var 1/text.py | 2,293 | 4.03125 | 4 | # lab 1, task 1
def repeats(file):
words = file.read().replace('!','').replace('?','').replace('.','').replace(',','').split()
repeated_words = {}
for word in words:
if repeated_words.get(word):
repeated_words[word] += 1
else:
repeated_words[word] = 1
print "Repeated words:\n"
for word in repeated_words... |
d0aee758eff41ce487f826bf291462b1d3b56bfb | haraldyy/semana_8_atividade_1 | /segunda.py | 510 | 3.734375 | 4 | def listas():
t=int(input())
lista=[]
for w in range(t):
lista.append(0)
print(lista)
lista=[]
numero=1
while numero<=t:
lista.append(numero)
numero+=1
print(lista)
lista=[]
for w in range(t):
n=int(input())
lista.append(n)
... |
47fd163fb9a178f3c9349517f6a580f28655ed8d | wangbiao92/leetcode | /2. linked/find_entry_node_of_loop.py | 540 | 3.6875 | 4 | # -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# 存在环,找到环的入口, 需要三个指针
class Solution:
def EntryNodeOfLoop(self, pHead):
slow1 = slow2 = fast = pHead
while fast and fast.next:
fast = fast.next.next
slow1 = ... |
0284b375c2c6c299a3f83b8d2f1708018394014a | Ryccass/PycharmProjects | /Fibonacci (kinda)/main.py | 442 | 3.875 | 4 | def fibo(rang):
nums = []
for i in range(0, rang):
nums.append(i)
newNums = []
for i in nums:
if i == 0:
newNums.append(0)
elif i == 1:
newNums.append(1)
elif i == 2:
newNums.append(1)
else:
newNums.append(newNums[i... |
414c2994391fc33fa25804f64df7cb11fbdd80ea | ramyasaimullapudi/WolfTrackPlus | /auto-doc/code/Controller/user_controller.py | 1,697 | 3.53125 | 4 | class User:
"""
This class is a controller for the user database. It inherits properties from flask_restful.Resource
"""
def get(self, email, password):
"""
gets defails of the specific user
:param email: email of the user
:param password: Password on user
:retur... |
530bcfd95fe459a330e520ff78175f8d4118a6a6 | dot-Sean/Ehseesi | /_site/workspace/extracredit1.py | 322 | 3.625 | 4 | import string
searchfile = open("file.txt", "r")
s = "GRAffiti!!@&, sWAAAAAg DURrrrrp^$$#@$#@ ZaCHARy **!@#!WiLLiams "
for line in searchfile:
words = s.split(" ")
for word in words:
xord = word.strip()
yord = xord.lower()
zord = yord.translate(yord, None, string.punctuation)
print(zord)
close... |
1a76faa960b2babe4b53da2b4d9f9058a25de95c | Neelam-Vishvakarma/NeelamProject | /Atbash_encryption.py | 2,248 | 4.125 | 4 | # Python program to implement Atbash Cipher Encryption
# This script uses dictionaries to lookup various alphabets
from threading import *
import time
lookup_table = {'A': 'Z', 'B': 'Y', 'C': 'X', 'D': 'W', 'E': 'V',
'F': 'U', 'G': 'T', 'H': 'S', 'I': 'R', 'J': 'Q',
'K': 'P', 'L': 'O',... |
952e9a533af9b4935596dc5f5ff8406609b34c2a | PyETLT/etlt | /test/helper/AllenTest.py | 2,762 | 3.6875 | 4 | import unittest
from etlt.helper.Allen import Allen
class AllenTest(unittest.TestCase):
"""
Test cases for class Allen algebra.
"""
# ------------------------------------------------------------------------------------------------------------------
def _test1(self, expected, x, y):
relat... |
1be3995cb8fb0504b25e093a90f486b70ac4f154 | ximenshaoshao/Learn_python | /one_in_three.py | 291 | 4.28125 | 4 | ##to find the biggest number in three numbers
import math
def main():
x1, x2, x3 = eval(input("Please enter three random number, seperated by comma, e.g. 1,2,3:"))
max = x1
if x2 > max:
max = x2
elif x3 > max:
max = x3
print("The largest number is:", max) |
555e54f3e59f5405b343af263899683dc78b74f7 | yz5308/Python_Leetcode | /Algorithm-Easy/67_Add_Binary.py | 922 | 3.921875 | 4 | class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
result, carry, val = "", 0, 0
for i in range(max(len(a), len(b))):
val = carry
if i < len(a):
val += int(a[-(i + 1)])
i... |
696c1dedbb448a5e6c3f6152d95bdd8e5f6733cd | karthik4h1/karthikpython | /42beg.py | 102 | 3.8125 | 4 | str1,str2=input().split()
if str1>str2:
print(str1)
elif str1==str2:
print(str1)
else:
print(str2)
|
3d7aa05a338935d19f1a1575047de0a2eb367999 | ErnestoGuevara/Tarea_03 | /Pago de trabajador.py | 1,397 | 3.90625 | 4 | #encoding: UTF-8
#Especificaciones del programa: Programa que Calcula el pago normal, pago extra y pago total de un trabajdor a la semana.
#Autor: Ernesto Ibhar Guevara Gomez
#Matricua: A01746121
def Leerhorasnormales():
horasnormales=int(input("Teclea las horas normales trabajadas: "))
return horasnormales
def... |
daf90102ab376053019da4a031b2dce852651892 | s-gulzar/python | /strings1.py | 1,313 | 4.15625 | 4 | ''' String Methods '''
a = "Gulzar"
print(a[3])
print(len(a))
for x in a:
print(x)
''' Check String '''
txt = "This is my sample test"
print('is' in txt)
''' OR '''
if "is" in txt:
print('Found')
else:
print('Not Found')
if "is " not in txt:
print('Not Found')
else:
print('... |
c48161c8c4099f1967960467a2a3442020a191ba | JayChenFE/python | /fundamental/python_crash_course/exercise/ch04/4-5.py | 568 | 3.65625 | 4 | # 4-5 计算1~1 000 000的总和 :创建一个列表,其中包含数字1~1 000 000,再使用min() 和max()
# 核实该列表确实是从1开始,到1 000 000结束的。另外,对这个列表
# 调用函数sum() ,看看Python将一百万个数字相加需要多长时间。
import time
nums = list(range(1, 1000001))
print("max is {:d}".format(max(nums)))
print('min is {:d}'.format(min(nums)))
start_time = time.time()
sum = sum(nums)
end_time =... |
d19500147154885e23754fbc23cdc3d34c5b2927 | yuliang123456/p1804ll | /于亮/小猫.py | 425 | 3.5 | 4 | class Cat:
def eat(self):
print('%s 在吃鱼,'%self.name)
def drink(self):
print('%s 在喝酒,'%self.name)
def introduce(self):
print('我的名字%s,我今年%d岁了'%(self.name,self.age))
tom = Cat()
tom.age = 60
tom.color='black'
tom.name ='tom'
tom.introduce()
tom.eat()
lanmao = Cat()
lanmao.name = '蓝猫'
... |
e2a8ec40d0b7a79effd774edeb1dbbd9d2dfc79e | crzysab/Learn-Python-for-Beginners | /019-Loops/Range_Loop.py | 176 | 3.5625 | 4 | # 1 parameter
for i in range(10):
print("Line -",i)
# 2 parameter
for i in range(5,15):
print("Value -",i)
# 3 parameter
for i in range(1,20,4):
print("line -",i) |
45e9b3a5047ed882d77676885cc95ecedc27242c | pedroriosg/IIC2233 | /pedroriosg-iic2233-2020-2/Actividades/AF05/servidor/jugadores.py | 2,644 | 3.5625 | 4 | """
Este módulo contiene la clase Jugador y funciones para su creación
"""
from threading import Lock
from random import shuffle
N_JUGADORES = 8
class Jugador:
"""
Representa a un jugador, que puede ser humano o bot.
Todos los jugadores parten como bots, y se asignan a humanos a medida
que se establez... |
3533f2dfd189003e4b83a32159ce00bf9b9b5ffd | AdamZhouSE/pythonHomework | /Code/CodeRecords/2476/8317/301690.py | 355 | 3.625 | 4 | def solve():
num = int(input())
for _ in range(num):
input()
calc([int(i) for i in input().split(' ')])
def calc(nums):
nums.sort()
if(len(nums) == 1):
print(nums[0])
return
res = nums.pop(0) * len(nums)
while len(nums)>0:
res = res + len(nums)*nu... |
6c1f5f36c4a0f226bdb74d077df1f97c3e8fa354 | vinuv296/luminar_python_programs | /Advanced_python/test/pgm9.py | 177 | 3.921875 | 4 | import re
x="[A-Z]+[a-z]+$" # check ending with a
r="Indian Is World of Culture"
#r="abc"
mat=re.finditer(x,r)
if mat is not None:
print("valid")
else:
print("invalid")
|
9d78e22f7d7fc5c1967a8cc79da4cf15e81df6a4 | sequoiap/cookiecutter-controlshw | /{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/utils/control.py | 714 | 3.75 | 4 | import control as ctrl
import numpy as np
def bode(*args, **kwargs):
"""
Wraps the control library's ``bode`` function and passes all the parameters
straight through. Acts more like MATLAB's ``bode`` function; it converts
magnitude to dB and phase to degrees after every function call. Returns the
s... |
8738aa2e038f7dc53a30ae1df911295da10face7 | mrwang33/python | /循环/homeWork.py | 83 | 3.703125 | 4 | nameList = ["wang",'zhao','qian','sun']
for name in nameList:
print("hello,"+name) |
cd41a4424df09d3e48660d3a7b216ac90df3800f | rajeshchinthanippu/upgraded-doodle | /credit_card.py | 1,163 | 4.09375 | 4 | import re
import argparse
PATTERN='^([456][0-9]{3})-?([0-9]{4})-?([0-9]{4})-?([0-9]{4})$'
def is_valid_card_number(sequence):
"""Returns `True' if the sequence is a valid credit card number.
A valid credit card number
- must contain exactly 16 digits,
- must start with a 4, 5 or 6
- m... |
5b9c99376076c0652125373e993e2fe783d82bd6 | nagask/leetcode-1 | /24 Swap Nodes in Pairs/sol.py | 1,072 | 4.0625 | 4 | """
We need to swap a node with its successor, and then repeat again, only if the node has a successor.
Given the current node, we check if it has a successor: in case it has, we swap them and we move to the third node.
The corner case is the first swap, when we have to change the head of the list
O(N) time, O(1) space... |
7387701e9011f7f2859e04c189cb55e26d5e3c5b | ejaytc/Python_Programs | /fizz_buzz-J19-18.py | 481 | 3.75 | 4 | #fizz buzz
while True:
try:
userInput = int(input("Input an integer: "))
for num in list(range(userInput)):
if num % 15 == 0:
print("{} fizz buzz".format(num))
elif num % 3 == 0:
print("{} fizz".format(num))
elif num ... |
2409454b2f20ff38574a4a95d1d5345b4c13fe2f | clarkjoypesco/pythonprog1 | /prog1.py | 189 | 3.859375 | 4 | # Write Python code that prints out the number of hours in 7 weeks.
hours_in_day = 24
days_in_week = 7
weeks = 7
hours_in_weeks = hours_in_day * days_in_week * weeks
print hours_in_weeks |
0542fe54b7e3ee15926f71fcf72d32cd9a3ca106 | BhuvanaChandraP/Spider_Task_1 | /Question Number 1.py | 336 | 3.65625 | 4 | num = int(input());
str = input();
decnum = int(str,2);
x = bin(decnum-1).replace("0b"," ");
y = bin(decnum+1).replace("0b"," ");
if(len(x) != len(y)) :
print(-1)
exit(0);
else:
print(int(x),int(y))
# def binarytodecimal(str)
# return int(str,2)
# def decimaltobinary(n)
# return bin(n).r... |
8eb9b33fb7c699d21d913d342e39bbb5c4460eaa | abijr/master-python101 | /101/cars.py | 1,073 | 3.9375 | 4 | command = ""
running = False
false = False
while false == False:
print("\nHello, your car is ready, ")
false == True
while True:
command = input(str("\nPlease select your option: "))
if command.lower() in "help":
print(
"""
Your Car Instructions:
- help: for ... |
350c425eb56b624af68d332ae429c25bcbec215c | sumit123sharma/skillsanta-python | /list_task2.py | 346 | 4.4375 | 4 | #python program to find the second largest no. in a list
list2=[]
num=int(input("enter the no. of elements:"))
for i in range(1,num+1):
numbers=int(input("enter numbers"))
list2.append(numbers)
#now sort the list
list2.sort()
#print the second largest by negative indexing method
print("second lar... |
17afb0cfb11d98f5996a855547e1305bbc2aeb92 | LiliGuimaraes/100-days-of-code | /CURSO-EM-VIDEO-PYTHON3/MANIPULANDO-TEXTOS/exerc_27.py | 201 | 3.6875 | 4 | nome_completo = str(input('Digite o nome e o sobrenome de uma pessoa: \n'))
nome_completo.split()
print(f'O seu primeiro nome é {nome_completo[1]}')
print(f'O seu segundo nome é {nome_completo[2]}') |
aab72255723f5b1eca2c8520a7f1931db3df9134 | 4925k/cs50_2021 | /pset6/credit/credit.py | 1,415 | 3.734375 | 4 | def luhnsAlgorithm(card):
# different sums for the positions
sum1 = 0
sum2 = 0
place = True # keep track of the digit from last
# start fromt the last digit
for i in reversed(card):
if place:
sum1 += int(i)
place = False
else:
temp = int(i) ... |
1ddb30f9f2158563f768543d3f361add4193fea5 | QueenSachi/QueenSachi.github.io | /functest.py | 2,433 | 4.03125 | 4 | import random
def hi():
print ("hi!")
def hello():
print("hello!")
def Hey():
print("Hey")
def joke():
jokeNum = random.randint(0,3)
if (jokeNum ==0):
print("What do you call an alligator detective?")
input()
print("An investi-gator!")
elif(jokeNum == 1):
prin... |
668d277fd63b6e7dba13a16e7140dd7315bc542f | SvetlanaIvanova10/python_netoogy | /classes/zadanie.py | 1,971 | 3.578125 | 4 | from python_netology.classes.Animals import Cow, Chicken, Duck, Goat, Sheep, Goose
cow = Cow('Манька', 100)
sheep1 = Sheep('Барашек', 20)
sheep2 = Sheep('Кудрявый', 19)
goat1 = Goat('Рога', 17)
goat2 = Goat('Копыта', 15)
goose1 = Goose('Серый', 5)
goose2 = Goose('Белый', 7)
chicken1 = Chicken('Ко-Ко', 2)
chicken2 = C... |
52112479f69537f4a9487569b36208fd7864f710 | likangwei/leetcode | /py/013_Roman-to-Integer.py | 913 | 3.59375 | 4 | __author__ = 'likangwei'
# https://leetcode.com/problems/roman-to-integer/
# Given a roman numeral, convert it to an integer.
#
# Input is guaranteed to be within the range from 1 to 3999.
class Solution:
# @param {string} s
# @return {integer}
def romanToInt(self, s):
x = {'I': 1, 'V': 5, 'X': 10... |
d989eaa6d3c84434ef0eaa5b7b8fa5fcfd8c41a4 | DanielHry/Python | /23 - Collatz Conjecture/CollatzConjecture.py | 1,323 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 2020
@author: Daniel Hryniewski
Collatz Conjecture - Start with a number n > 1. Find the number of steps it takes to reach one using the following process:
If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1.
"""
def choice():
i = 0
... |
1c5bbcc8202b4f1d7471e43f92634b5b72d24c11 | misrapk/Basic-Python-Codes | /fromkeys_get_copy_clear_dict.py | 745 | 4.375 | 4 | # "fromkeys is use to creat dictionary"
# dict_name = dict.fromkeys(['key1', 'key2'], 'vlaue')
# this value is common to alll the keys
d = dict.fromkeys(['name', 'age'], 'peeyush')
print(d) #it will assign 'peeyush' to both keys
#"get method"
#it is use to access the keys in dictionary
# dictNam... |
ba7f9c1286f0e85719aadf0d8ae1c78c36207f55 | PatrickPLG/GUI_aflevering | /Opgaver/gui.py | 7,380 | 3.546875 | 4 | '''
- Pet game, where you can feed and walk your pet
- Made by PatrickPLG og Klint02
- version 2.0 Public Release
'''
# Library and file imports
import tkinter as tk
import date
import pet
import TidTest
import os
from tkinter import simpledialog
from tkinter import PhotoImage, messagebox
import pygame
from pygame... |
5abc6dc2570a0aa17876c30b2293de61b8351b46 | legmartini/python-def | /ex099.py | 568 | 4.03125 | 4 | # Funções
def linha():
print('-' * 30)
def maior(* num):
cont = maior = 0
print('Analisando os valores...')
for valor in num:
print(f'{valor}', end=' ')
if cont == 0:
maior = valor
elif valor > maior:
maior = valor
cont += 1
... |
80d557ed10b19831ab39b699469ce5a5f077d63d | iyngr/PyIntro | /oops_demo.py | 689 | 3.65625 | 4 | # Classes and Objects
import random
class Enemy:
def __init__(self, atkl, atkh):
self.atkl = atkl
self.atkh = atkh
def getAtk(self):
print(self.atkl)
enemy1 = Enemy(40, 60)
enemy1.getAtk()
enemy2 = Enemy(75, 90)
enemy2.getAtk()
'''
playerhp = 260
enemyatkl = 60
enemyatkh = 80
whil... |
34de385876a74aeb6b29a3fec6c487ea96a4dfcf | ahtornado/study-python | /day18/myiter.py | 381 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author :Alvin.Xie
# @Time :2018/7/1 16:51
# @File :myiter.py
alist = ["hello", "world"]
for item in alist:
print item
for i in range(len(alist)):
print "%s: %s" % (i, alist[i])
for element in enumerate(alist):
print "%s: %s" % (element[0], element[1... |
1ee7dedf027b833a2004df2503c82927d3896356 | mihirsam/Data-Structure-And-Algorithm-Python | /DoublyInsertBegin.py | 1,205 | 4.1875 | 4 | # Insert node at begining of doubly linked list
class Node:
def __init__(self, data = None):
self.prev = None
self.next = None
self.data = data
class LinkedList:
def __init__(self):
self.head = None
def display(self):
if self.head.data is None:
print(... |
120b34b3602555a9c9041ecba0e88219fec0ddd8 | abdullahsumbal/Interview | /CTCI/ArrayList/one_two.py | 483 | 3.765625 | 4 |
def checkPermutation(s1, s2):
s1Array = [0] * 128
s1Length = len(s1)
s2Length = len(s2)
if s1Length != s2Length:
return False
for i in range(s1Length):
s1Array[ord(s1[i])] += 1
for i in range(s2Length):
s1Array[ord(s2[i])] -= 1
if(s1Array[ord(s2[i])] < 0):... |
9cc7801666294f158cb1eb4cd791856d9324b64c | github/codeql | /python/ql/src/Expressions/CompareIdenticalValuesMissingSelf.py | 393 | 3.515625 | 4 |
class Customer:
def __init__(self, data):
self.data = data
def check_data(self, data):
if data != data: # Forgotten 'self'
raise Exception("Invalid data!")
#Fixed version
class Customer:
def __init__(self, data):
self.data = data
def check_data(self, data):
... |
1f2c6eb5610ff3cec20b91f6c73aadf146b6c5ca | codeguru132/pythoning-python | /for_And_else.py | 207 | 4.09375 | 4 | for i in range(5):
print(i)
else:
# i retains its last value
print("else:", i)
# here the for is not even executed
j = 111
for j in range(2,1):
print(j)
else:
print("else:", j)
|
40bce346acf5b939f2f086ec18557355936ec1d0 | Meenu-github/uplift-python-Resources-Meenu | /my_function.py | 433 | 3.921875 | 4 | def swapUsingLenFunction(arr):
lelement= len(arr)-1
arr[0],arr[lelement] = arr[lelement],arr[0]
return arr
def swapUsingNegativeIndex(arr):
arr[0],arr[-1] = arr[-1],arr[0]
return arr
def swapUsingStarOperand(arr):
a,*b,c = arr
return [c,*b,a]
print(swapUsingLenFunction([1,2,3,4,5,6]))
p... |
fd99acba102b7997b89e311c72ae95511cc59d8b | jzx0614/example_code | /111_minimun_depth.py | 710 | 3.53125 | 4 | class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.min_depth = None
def dfs(node, depth):
if not node: return
if self.min_depth and depth > self.min_depth:
return
if not ... |
c01c3f2c1329a0673dffe2b6800f03220b93d326 | maximilianogomez/Progra1 | /Practica 4/4.15.py | 2,652 | 4.125 | 4 | # Muchas aplicaciones financieras requieren que los números sean expresados también
# en letras. Por ejemplo, el número 2153 puede escribirse como "dos mil ciento
# cincuenta y tres". Escribir un programa que utilice una función para convertir un
# número entero entre 0 y 1 billón (1.000.000.000.000) a letras. ¿En q... |
5c308983f122d936fc1625112e81a0a8b4b16dba | lixiangwang/SEU---Data-structure-and-algorithm-design | /树和图/图/6.py | 691 | 3.5625 | 4 | # encoding: utf-8
import numpy as np
def find_path(array):
m = 1
n = 4
med = np.zeros(shape=(4, 4))
while m:
for i in range(n):
for j in range(n):
for k in range(n):
med[i][j] += array[i][k] * array[k][j]
for i in range(n):
f... |
c13551b597dad105915df04d7687c1912c7004e8 | GourabRoy551/Python_Codes_2 | /Python Ex/Reverse_Order.py | 321 | 4.09375 | 4 | """
Python has two functions designed for accepting data directly from the user:
1.Python 2.x. -> raw_input()
2.Python 3.x. -> input()
"""
fname = input("Input your First Name : ")
lname = input("Input your Last Name : ")
print ("Hello {0} {1}".format(lname, fname))
str="Welcome"
x=str[::-1]
print(x... |
11d5f0def1db4a9c7be96dc45e759cf50908b749 | sloppyDev/ctf | /OverTheWire/Krypton/getSimpleCipher.py | 2,579 | 3.5625 | 4 | #!/usr/bin/python3
import sys
## Getting frequency files
singleLetterPath = '/home/slop/Documents/misc/singleLetterFreq.txt'
twoLetterPath = '/home/slop/Documents/misc/twoLetterFreq.txt'
threeLetterPath = '/home/slop/Documents/misc/threeLetterFreq.txt'
singleLetterList = open(singleLetterPath, 'r').read(-1).split... |
dd92fa5e50dfdb84964a677664bf609d5121ae74 | SayanDutta001/Competitive-Programming-Codes | /Google Kickstart April/Robot_Path_Decoding.py | 880 | 3.625 | 4 | def rec(s, z, a, b):
count = int(s[z-2])
while(s[z]!=')'):
for p in range(count):
if(s[z]=='N'):
a-=1
elif(s[z]=='S'):
a+=1
#print(a)
elif(s[z]=='E'):
b+=1
#print(b)
elif(s[z]=='W'):
b-=1
elif(s[z]=='('):
h = rec(s, z+1, a, b)... |
2f1c6a28d5957c5f3fffa30cad2d23dab1c626ed | hrubert/digitalCrafts | /python-exercises/Monday/practice.py | 677 | 4.0625 | 4 | # create a class and call its method
# class MyClass:
# def SayHello():
# print("Hello there!")
# MyClass.SayHello()
# create an instance of a class and call its method -- note you have to use self
# class Person:
# def greet(self):
# print("Hello")
# me = Person()
# me.greet()
# working wi... |
9b8e685d95fe08133b6876ee12bc3f03467f6b04 | xavierliang-XL/git-geek | /geekprogramming/oop/oop1.py | 359 | 3.90625 | 4 | class Washer():
def __init__(self,width,height):
self.width = width
self.height = height
def wash(self):
print("wash clothes")
print(self.width)
print(self.height)
washer = Washer(10,100)
#washer.width=200
#washer.height=1000
print(f'washer width is {washer.width}')
pri... |
ea3fbee1a13d59c20df78533b93da8964bfb0af5 | roni-kemp/python_programming_curricula | /CS1/0340_lists/investigation3.py | 2,650 | 4.5 | 4 |
#For 35 points, read this and answer the questions.
#1. What does the following program print? Try to answer without
#running the code, then check your answer.
for i in range(3,7):
print(i)
#2. What does the following program print? Try to answer without
#running the code, then check your answer.
numbers = [... |
983283e6aef3e05c649884a72cd4368ee85c9534 | krish0raj0vaiskiyar/krish-assignment-3.py | /find who is youngest one.py | 658 | 4.0625 | 4 | print (" this program is made by KRISH Raj ")
print ("this program is made for tell who is youngest one")
a = int(input("enter the age of Ram : "))
b = int(input("enter the age of Shyam : "))
c = int(input("enter the age of Ajay : "))
if a<b and a<c :
print ("Ram is youngest one ")
if b<c and b<a :
... |
e5a495f54966fdad90daf0cd44cad14792c120ee | reductus/reductus | /dataflow/deps.py | 3,681 | 3.578125 | 4 | # This program is public domain
# Author: Paul Kienzle
"""
Dependency calculator.
"""
from __future__ import print_function
def processing_order(pairs, n=0):
"""
Order the work in a workflow.
Given a set of n items to evaluate numbered from zero through n-1,
and dependency pairs
:Parameters:
... |
6c4bf232c420e1047dce8ccdaf594a1ff3266f44 | shacker/hikes.guru | /apps/base/utils.py | 934 | 3.546875 | 4 | import string
import random
def meters_to_dist(meters, pref, format="long"):
'''
Takes args `meters` (int) and `pref` ('mi' or 'km') and `type` ("short" or "long")
If type=="short" returns float value in feet or meters.
If type=="long" returns float value in miles or kilometers.
'''
if meters... |
970cf1079ee795d38e7984ed2e3c36c4515a2e8c | FurHound/turtle | /race homework.py | 1,310 | 4.03125 | 4 | import turtle
import random
numTurtles = int(turtle.numinput('race', 'How many turtles?'))
colors = ['red', 'blue', 'yellow', 'green', 'purple', 'black', 'magenta', 'cyan', 'brown']
position = [-400, -300 , -200 , -100, 0, 100, 200, 300, 400]
turtleplayers = ['turtle 1', 'turtle 2', 'turtle 3', 'turtle 4', 'turtle 5',... |
b2ef46075eb4b758b2d1ef07d2dc97d02f005eaa | blackox626/python_learn | /leetcode/top100/longestPalindrome.py | 2,211 | 3.78125 | 4 | """
最长回文子串
"""
class Solution(object):
"""
暴力
"""
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
longestStr = ''
if len(s) == 1:
return s
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
... |
49457cce6328885f6cebfb37b1c854f91c89e5c6 | lijun7141880/python-practice | /计时.py | 1,176 | 3.71875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# todo Python中有一个time模块,它提供了一些与时间相关的方法。利用time,可以简单地计算出程序运行的时间。对于一些比较复杂、耗时较多的程序,可以通过这种方法了解程序中哪里是效率的瓶颈,从而有针对性地进行优化。
# todo 在计算机领域有一个特殊的时间,叫做epoch,它表示的时间是1970-01-01 00:00:00 UTC。
# todo Python中time模块的一个方法
# todo time.time()
# todo 返回的就是从epoch到当前的秒数(不考虑闰秒)。这个值被称为unix时间戳。
import t... |
a0dbc2132fe800228b0dd55e7465944949ff6b04 | RayanAbri/DenseNN | /ANN-Dense.py | 3,156 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 29 13:32:22 2019
@author: rahem
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#load csv bank dataset to dataset variable
dataset = pd.read_csv('data.csv')
#split desire colums to x and y variables
x = dataset.iloc[:, 3... |
8b6c8c4905fef9c94f74f0fbe7cf5aa98268e60b | noahw345/city-map | /map1.py | 1,084 | 3.8125 | 4 | import folium
import pandas
#read csv file containing data about major world cities
data = pandas.read_csv("worldcities.csv")
#create lists containing data
lat = list(data["lat"])
lon = list(data["lng"])
names = list(data["city"])
population = list(data["population"])
#create map and feature group
map = folium.Map(... |
f0e7e21f2d31e8be8b4a104967d8604118f791c7 | jyoon1421/py202002 | /test1128.py | 600 | 3.640625 | 4 | # import csv
# import time
# from random import *
#
# with open("추천도서리스트.csv") as file:
# reader = csv.reader(file)
# booklist = list(reader)
#
# def recomment_book():
# print("3초 뒤 책을 추천해드립니다.\n")
# time.sleep(1)
# print("당신에게 추천해드릴 도서는")
# time.sleep(1)
# print("바로")
# time.sleep(1)
# ... |
81112d9424cec5e2afd9097456178013182e0626 | Neckmus/itea_python_basics_3 | /iassirskyi_stanislav/02/HW_2_3.py | 402 | 4 | 4 | array = list(input('Enter the array: '))
for i in range(len(array)):
check_array = []
for j in range(len(array)):
if array[i] == array[j]:
check_array.append(array[i])
if len(check_array) % 2 != 0 and len(check_array) > 1:
n = check_array[0]
print... |
c9478dc419b7a23596cedbee9696da5e5074d7c5 | silaslenz/TDDD95 | /Exercise 1/Superman/main.py | 1,769 | 3.640625 | 4 | # Author: Silas Lenz
if __name__ == '__main__':
N = int(input())
for testcase in range(N):
M = int(input())
jumps = [int(jump) for jump in input().split()]
alternatives = [[None] * 501]
alternatives[0][0] = {"visited": "", "highest": 0}
for jump in jumps:
... |
7fc8618bcd316b1997dc88ff8adf3f143db89b1e | Hu-Wenchao/leetcode | /prob002_addtwonumbers.py | 1,686 | 3.765625 | 4 | """
You are given two linked lists representing two non-negative
numbers. The digits are stored in reverse order and each of
their nodes contain a single digit. Add the two numbers and
return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
"""
# Definition for singly-linked list.
class... |
7f42dde72c39668cea5f40416132595eb011519b | aroberge/py-fun | /docpicture/src/svg.py | 4,756 | 3.546875 | 4 | '''
This module contains all the classes required to easily create an xml
document containing svg diagrams.
'''
class XmlElement(object):
'''Prototype from which all the xml elements are derived.
By design, this enables all elements to automatically give a
text representation of themselves.'''
... |
d45b83a09517c26af9de9604bb43c8f612621c6c | sagarrjadhav/Problem-Solving-in-Data-Structures-Algorithms-using-Python | /IntroductoryChapters/ForDemo.py | 1,196 | 3.875 | 4 | #!/usr/bin/env python
""" generated source for module ForDemo """
class ForDemo(object):
""" generated source for class ForDemo """
text = "Hello, World!"
PI = 3.141592653589793
@classmethod
def main1(cls):
""" generated source for method main1 """
numbers = [1, 2, 3, 4, 5... |
80a132ae6b13665bb4b11392ed5588ae9b10c346 | HminiL/flask-madird-titanic-docker | /test/palindrome.py | 357 | 3.5 | 4 | import unittest
from basic.palindrome import Palindrome
class PalindromeTest(unittest.TestCase):
mock = Palindrome()
def test_str_to_list(self):
print(self.mock.str_to_list("race car"))
def test_isPalindrome(self):
print(self.mock.isPalindrome(self.mock.str_to_list("hello")))
if __nam... |
070f97bdb45048b93878024cc297136fe320bb8c | pangfeiyo/PythonLearn | /【MOOC】Python语言程序设计/第2周 Python基本图形绘制/2.2 实例2:Python蟒蛇绘制/练习.py | 1,781 | 3.828125 | 4 | import turtle
# 方法一:使用海龟相对坐标 left 或 right
def 相对坐标正方形():
turtle.setup(650,350)
turtle.penup()
turtle.fd(-250)
turtle.pendown()
turtle.fd(100)
turtle.right(90)
turtle.fd(100)
turtle.right(90)
turtle.fd(100)
turtle.right(90)
turtle.fd(100)
turtle.done()
# 方法二:使用屏幕绝对坐标 ... |
28f53fa81515a80b204bdaab47e09078acf8a7cd | iliailmer/advent_of_code_2019 | /day10/day10.py | 10,135 | 3.6875 | 4 | """Solution to day 10."""
from typing import List
from collections import defaultdict
from typing import Tuple, NamedTuple
class Asteroid(NamedTuple):
x: int
y: int
asteroids = []
with open("input.txt") as f:
asteroids = [list(x.strip('\n')) for x in f.readlines()]
def display(layers):
"""Output ... |
a6e3bca644ba044a20ee3697cda4477fa0c9da8e | brunodantascg/listaExercicioPythonBR | /3estruturaDeRepeticao/31_caixa.py | 1,115 | 4.25 | 4 | # Questão 31
# O Sr. Manoel Joaquim expandiu seus negócios para além dos negócios de 1,99 e agora possui uma loja de conveniências. Faça um programa que implemente uma caixa registradora rudimentar. O programa deverá receber um número desconhecido de valores referentes aos preços das mercadorias. Um valor zero deve ser... |
6069e6ddf70fed52e0fd07859cabe40c80166424 | ganhan999/ForLeetcode | /122、 买卖股票的最佳时机II.py | 2,072 | 3.734375 | 4 | """
给定一个数组,它的第i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入: [7,1,5,3,6,4]
输出: 7
解释:
在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出,
这笔交易所能获得利润 = 5-1 = 4 。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,
这笔交易所能获得利润 = 6-3 = 3 。
示例 2:
输入: [1,2,3,4,5]
输出: 4
... |
9e0bd15c3f7a2e572618ffc85fdffde3d8579b0a | MicheSi/cs-bw-unit2 | /balanced_brackets.py | 2,142 | 4.125 | 4 | '''
Write function that take string as input. String can contain {}, [], (), ||
Function return boolean indicating whether or not string is balance
'''
table = { ')': '(', ']':'[', '}':'{' }
for _ in range(int(input())):
stack = []
for x in input():
if stack and table.get(x) == stack[-1]:
... |
965c53395014f8e12e34037f6f60c131ed01a301 | livexia/algorithm | /blind_75_leetcode/python/s0079_word_search.py | 2,109 | 3.78125 | 4 | from typing import List
import unittest
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
m = len(board)
n = len(board[0])
visited = [[False for _ in range(n)] for _ in range(m)]
def dfs(x: int, y: int, matched: int) -> bool:
if board[x][y] !=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.