blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4fb087fd599813b8a13554b1530a04edd96a8103 | freddieaviator/my_python_excercises | /ex042/ex02.py | 303 | 3.890625 | 4 |
first_name = "fredrik"
last_name = "hårberg"
course = "Data Engineer"
candidates = 11
print(f"""My name is {first_name.capitalize()} with last name {last_name.capitalize()}.
I am participating in the course {course.lower()}.
There are {candidates} candidates taking the {course.lower()} course.""")
|
dff2db36e5f3cf6b30bd9266221f77f039469301 | CharlesJonah/andela_ex_d1 | /fizz_buzz.py | 365 | 4.1875 | 4 | def fizz_buzz(num):
#Return FizzBuzz if num is divisible by both 3 and 5
if num % 3 == 0 and num % 5 == 0:
return 'FizzBuzz'
#Returns Buzz if num is divisible by 5
elif num % 5 == 0:
return 'Buzz'
#Returns Fizz if num is divisible by 3
elif num % 3 == 0:
return 'Fizz'
#Returns num itself if it is not di... |
55221d27a289720d001a5e6b612cb6534e8e470a | shubham-dixit-au7/test | /coding-challenges/Week03/Day01_(03-02-2020)/Ques3.py | 585 | 4.28125 | 4 | # Question- Write a Python program to create a dictionary from a string.
# Note: Track the count of the letters from the string.
# Sample string : 'w3resource'
# Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
# Answer-
# first method-
# user_input = input("Enter a String ... |
449cc995d85aceb7296751501136209c535dec42 | maksim-shaidulin/CodeSignalTasks | /LeetCode/plusOne.py | 446 | 3.53125 | 4 | from typing import List
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
num = int("".join([str(x) for x in digits])) + 1
return [int(x) for x in str(num)]
def test_plusOne():
assert Solution().plusOne([0]) == [1]
assert Solution().plusOne([1]) == [2]
assert Solutio... |
43dd7834732752e8c4215516f9fab5c775e5afb4 | Iliaromanov/classroom-examples_gr11 | /arcade/11_lists_motion_01.py | 1,234 | 4 | 4 | """
1. Create parallel lists of rain x and y values.
2. In the draw function, use a for loop with zip() to draw
rain at the x, y co-ordinates.
"""
import arcade
WIDTH = 640
HEIGHT = 480
# Parallel lists to store x and y values for each rain drop
rain_x_positions = [100, 200, 300]
rain_y_positions = [480, 480, 480]
... |
01406dca128ecd3caf10f7f3c59b81ec94a1bb27 | tektutor/DevOpsJuly2018 | /Day6/Python/inheritance.py | 965 | 4.0625 | 4 | #!/usr/bin/python
class Parent:
def __init__(self):
print ( 'Parent constructor' )
self.x = 0
self.y = 0
def setValues(self, a, b):
self.x = a
self.y = b
def printValues(self):
print ('The value of x is' , self.x )
print ('The value of y is' , self... |
38c4f4d57a469bc6575bc82c77ef83eae3529b48 | tuftsceeo/EDL2020 | /student_notebook_root_folder/archive/image_processing/python_scripts/apply_face_detection.py | 2,309 | 3.640625 | 4 |
import cv2
import argparse
def detect_face(img, faceCascade, eyeCascade):
"""
Name: detect_face
Input: image(numpy 3d array), face classifier, eye classifier
Return: n/a
What it does: draws red box around face, draws green box around eye
"""
gray = cv2.cvtColor(img, cv2.COL... |
006fb1c33f5bf0649de9c7da3a761f3a892e3d0f | dark-polar/tech-test | /programmer.py | 483 | 3.890625 | 4 | words = ["pro", "gram", "merit", "program", "it", "programmer"]
patterns = "program"
matching = [s for s in words if patterns in s]
def check(n):
array = ['pro', 'gram', 'merit', 'program', 'it', 'programmer']
result = ''
cut = False
for i in array:
if i in n:
result +=... |
be2970af9bcb6736ce21f3009bbc1108cbe8d0da | gcrowder/currency_converter | /currency_test.py | 2,051 | 3.578125 | 4 | import unittest
import currency
first_currency_object = currency.Currency('£5.25')
second_currency_object = currency.Currency(currency_code='GBP', amount=5.25)
third_currency_object = currency.Currency(amount=5.25, currency_code='EUR')
fourth_currency_object = currency.Currency('£10.50')
class TestCurrency(unittest.T... |
9382a54fbddb47a1500e6b4e3f1729b72a24a9f3 | KenOasis/LeetCode | /LeetCode/Algorithm/Longest Palindromic Substring/main.py | 1,748 | 3.671875 | 4 | class Solution:
def palindrome(self , start , end , s ):
while True:
if(start < 0 or end > len(s) - 1 ):
break
if(s[start] != s[end]):
break
start -= 1
end += 1
return end - start - 1
de... |
e5649d2b70a4c7a3e4683d58e11b9a975dad9a3f | hatsem78/practica_python | /ejercicios.py | 601 | 3.828125 | 4 | import math
def anagrama(word, word2):
word = sorted(word)
word2 = sorted(word2[::-1])
if word == word2:
return True
else:
return False
print(print(anagrama('fresa', 'frase')))
def es_polidromo(word):
polidromo = word[::-1]
if word == polidromo:
return True
e... |
14db37534f2757c428b5d99eb638d845c077fc01 | harshalms/python | /basics/minimum_difference.py | 743 | 4.1875 | 4 | '''GeeksForGeeks
Find minimum difference between any two elements
Given an unsorted array, find the minimum difference between any pair in given array.
Examples :
Input : {1, 5, 3, 19, 18, 25};
Output : 1
Minimum difference is between 18 and 19
Input : {30, 5, 20, 9};
Output : 4
Minimum difference is between 5 and ... |
699b703705e6717dd00c0abb1603fceeb8643d73 | biocatalytic-coatings/pythonScripts | /millis.py | 323 | 3.546875 | 4 | import time
from datetime import datetime, timedelta
interval=1
start_time=datetime.now()
future_time=start_time + timedelta(seconds=60)
dt=datetime.now()
print("Started @",dt)
while (dt < future_time):
#time.sleep(interval)
#print("Millis = ",dt)
dt=datetime.now()
print ("Finished @", datetime.now(... |
5a6c664bc424dd41516b94535695105b1e3a9ec6 | codeAligned/coding-practice | /practicepython.org/exercise20.py | 930 | 3.640625 | 4 | #!/usr/bin/env python3
import random
def binarySearch(value, sample, start, end):
if start > end:
return -1
midIndex = int((start+end) / 2)
if value == sample[midIndex]:
return midIndex
elif value < sample[midIndex]:
return binarySearch(value, sample, start, midIndex - 1)
... |
3e3f213b14d53a92f3f32a04a2913419b9a7e590 | mantripat/python_programs | /palindrome.py | 402 | 3.90625 | 4 |
#s1=input("enter any string to check if it is palindrome:")
"""
s1="maddsam"
print("reverse string=",s1[::-1])
if s1[0:]==s1[::-1]:
print("String is palindrome")
else:
print("Its not plaindrome")
"""
s="hi ! my name is Alpha ..... u can write it like @lph@ 123%%%6&8^%$#"
s2=""
for i in range(len(s)):... |
db13bfc35fdca90f2f7d1021fae1de47fca651e2 | Zahidsqldba07/competitive-programming-1 | /Leetcode/August Leetcoding Challenge/vertical_order.py | 1,569 | 4.0625 | 4 | # Vertical Order Traversal of a Binary Tree
'''
Given a binary tree, return the vertical order traversal of its nodes values.
For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1).
Running a vertical line from X = -infinity to X = +infinity, whene... |
4bdc92c7596158a48862c14f9cced649638575ab | dhootha/nGramBabbler | /Babbler.py | 4,282 | 3.828125 | 4 | # Babbler: reads in a corpus and uses conditional probabilities to
# write out a string of words, with each word generated based off of
# the probability that it occurred after the previous n words in the corpus.
#
# Boyang Niu
# boyang.niu@gmail.com
# 11-13-2013
#
#
import random
import collections
class Babbler(ob... |
2f992cfead04dfcddcd717a63c9eb512b4617d31 | daniel-reich/turbo-robot | /QN4RMpAnktNvMCWwg_12.py | 961 | 4.375 | 4 | """
An identity matrix is defined as a square matrix with **1s** running from the
top left of the square to the bottom right. The rest are **0s**. The identity
matrix has applications ranging from machine learning to the general theory of
relativity.
Create a function that takes an integer `n` and returns the ident... |
3b5f2c02635ce0a3f0a9bf38ae5d2cea625e475a | gabriellaec/desoft-analise-exercicios | /backup/user_035/ch37_2020_03_23_23_14_07_056409.py | 168 | 3.890625 | 4 | Senha = False
resposta = input("Qual é a senha")
while Senha:
if resposta!="desisto":
print("tenta denovo")
else:
Senha = True
print("Você acertou a senha!") |
cfd1bf81e1e7b6c0e8c8c5c8845627f963bd3e15 | jakehoare/leetcode | /python_1_to_1000/812_Largest_Triangle_Area.py | 961 | 3.9375 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/largest-triangle-area/
# You have a list of points in the plane. Return the area of the largest triangle that can be formed by any
# 3 of the points.
# For each 3 points, use shoelace formula as per https://en.wikipedia.org/wiki/Shoelace_formula... |
9eba62f84d960868a5b699765b204f4f0047eb64 | passion4energy/Elyane | /losses/multi_class_cross_entropy.py | 972 | 3.671875 | 4 | """ The Multi-Class Cross-Entropy Loss Function """
import numpy as np
from .loss import Loss
class MultiClassCrossEntropy(Loss):
""" The Multi-class CrossEntropy that contains everything needed to calculate the loss. """
def fct(self, labels, preds):
""" The loss function formula.
Args:
... |
6bf953d8ba77379b13fd0162be89c54d3ac31e56 | dingshuangdian/lsqPython | /day2/format.py | 601 | 3.96875 | 4 | # 格式化输出
# %s d
name = input('请输入姓名:')
age = input('请输入年龄:')
height = input('请输入身高:')
job = input('请输入工作:')
hobbie = input('你的爱好:')
# msg = "我叫%s,今年%s 身高%s" % (name, age, height)
msg = '''-------------info of %s --------------
Name:%s
age:%s
height:%s
job:%s
hobbie:%s
学习进度为:3%%
''' % (name, name, age, height, job, ho... |
d8f3de21f3aa99da8c9d894ba048342db39dd486 | ThompsonHe/LeetCode-Python | /Leetcode0111.py | 1,680 | 4 | 4 | """
111. 二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例:
给定二叉树[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
import collections
cla... |
fa1bc157d60353f35b17187d63444fafd026bd29 | jeach27/IPC2_Proyecto1_201903873 | /lista.py | 2,467 | 3.90625 | 4 |
class Lista:
def __init__(self, codigo, nombre, n, m, g):
self.codigo = codigo
self.nombre = nombre
self.n = n
self.m = m
class Nodo:
def __init__(self, Lista=None, next = None):
self.Lista = Lista
self.next = next
class ListaCircular:
def __init__(... |
7c5b6f7faa46e2c99e469729e22227e0b9104227 | kimgy0/Python_Practice | /CLASS/10_7_Polymorphism.py | 535 | 4.1875 | 4 | class Animal:
def __init__(self,name):
self.name=name
def talk(self):
raise NotImplementedError("Subclass must implement abstract method")
#해당 자식 객체를 제외한 다른 클래스가 이 메서드를 쓰지 못하게 함.
class Dog(Animal):
def talk(self):
return "woof! woof!"
class Cat(Animal):
def ta... |
2f4642e62b7b9739a119763968ef0e5a1acab35e | guoweifeng216/python | /python_design/pythonprogram_design/Ch5/5-1-E35.py | 436 | 3.96875 | 4 | def main():
## Display the largest number in the file Numbers.txt
max = getMax("Numbers.txt")
print("The largest number in the \nfile Numbers.txt is",
str(max) + ".")
def getMax(fileName):
infile = open("Numbers.txt", 'r')
max = int(infile.readline())
for line in infile:
... |
89e2eb44c6a27362d91c2b349f35f3b781891f42 | Django-Lessons/lesson-41-argparse-module | /draw.py | 1,620 | 3.921875 | 4 | import argparse
CIRCLE = 'circle'
SQUARE = 'square'
class Square:
def __init__(self, p1, p2):
print("Square")
class Circle:
def __init__(self, p1, radius):
print(f"Circle center=({p1[0]}, {p1[1]}) radius={radius}")
def circle_func(args):
Circle(args.center, args.radius)
def square_... |
34007ec1cc22bbc359d08c5d553c45e1d55f80a6 | logan-lach/Algos | /max_contiguous_sum/kadanes.py | 2,740 | 3.84375 | 4 | def kadanes_1(A):
# Whoohoo! this is the alt branch!
total = gcs_value = A[0]
total_list = [A[0]]
gcs = [A[0]]
for i in range(1, len(A)):
'''
The opening step. Our combination between everything we seen this far and our new item
We will check if this contributes something t... |
cebb81f80c0a4f307b9e752723001df4b7a0055d | GKPSingh/Functions-Practice | /siminterest.py | 173 | 3.625 | 4 | # Python Program for simple interest
def si(p, r, t):
simple_interest = (p * r * t)/100
print(f'The value of simple interest is {simple_interest}')
si(100, 10, 1) |
f42e5e6e0a1ea2789493606a517180446e6c6d9f | Nirali0029/Algorithms-in-python | /Algorithms/Sorting/selection_sort.py | 216 | 3.578125 | 4 | def selection(a):
n=len(a)
for i in range(n):
min=i
for j in range(i,n):
if a[j]<a[min]:
min=j
if i!=min:
a[i],a[min]=a[min],a[i]
return a
a=[2,7,4,6,1,8,5]
print(selection(a))
|
f553a41fac58e9cca0b4dccbf7317b29df55ce00 | RohanDeySarkar/DSA | /linked_lists/linked_list_palindrome/linkedListPalindrome.py | 965 | 3.828125 | 4 | # This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
# Recursion
def linkedListPalindrome(head):
isEqual, _ = isPalindrome(head, head)
return isEqual
def isPalindrome(leftNode, rightNode):
if rightNode is None:
return (Tru... |
1a72ce540701c897939e3a1339dcdf4de0adf631 | amiraHag/python-basic-course2 | /database/database3.py | 1,165 | 3.71875 | 4 | # ------------------------------------------------------
# -- Databases => SQLite => Insert Data Into Database --
# ------------------------------------------------------
# - cursor => All Operation in SQL Done By Cursor Not The Connection Itself
# - commit => Save All Changes
# ----------------------------------------... |
927122669494c4c749257820ff4f0ae734eb1b4a | WebDevExpertise/Notes_For_Python | /unit_4/lecture_4.py | 1,865 | 4.59375 | 5 | # Unit 4: For Loops, Working with Lists & Other Ways of Storing Mutliple Pieces of Information
# 4.1 - 4.2 - Using For Loops on Lists
movies = ['Avengers: End Game', 'Ralph Breaks the Internet']
for movie in movies:
print(movie) # prints "Avengers: End Game", and "Ralph Breaks the Internet" in seperate lines... |
9c48662077fcc74d7382c74f218cea427d110f10 | moeburney/2040 | /scripts/classes/colors.py | 1,172 | 3.6875 | 4 | '''
Created on Jul 14, 2011
@file: colors.py
@author: jake bolton
Usage:
Feel free to use code as you want!
functions:
random_color(search=None):
search_color(name)
'''
import pygame
from pygame.locals import *
from pygame.color import THECOLORS
from random import choice
VERSION = '0... |
e12db07f662918cc36ac39f7f006448fd56e1558 | JoMOlsson/neural_playground | /ANNet.py | 39,935 | 3.609375 | 4 | import numpy as np
from math import e
import matplotlib.pyplot as plt
import mnist
import math
from colour import Color
from PIL import Image
import copy
import os
import glob
import random
def sigmoid(z):
""" Calculates the output of the sigmoid function from the provided z-data
:param z: (float, int, npArr... |
f95a3729fcc7e2e5476081156a8f1d3a2378eb4d | Saneter/Education | /assignment_5_travis_jarratt.py | 4,287 | 4.15625 | 4 | """
author: Travis Jarratt
CIS 1600 - Assignment 5
Saint Louis University
"""
def get_data():
fileObj = open("./exam-scores.csv")
lines = fileObj.readlines()
dict_scores = {}
for line in lines[1:]:
lst_items = line.strip().split(",")
dict_scores[lst_items[0]] = (float(lst_items[1]), f... |
cf4a38a0e60330d84e3de39e55d45cde94bf8486 | Tusharsampang/LabProject2 | /One.py | 331 | 4.40625 | 4 | '''
1.Write a program that takes numbers and print theirs sum.Every number is given on a separate line.
'''
num1 = int(input("enter the first value: "))
num2 = int(input("enter the second value: "))
num3 = int(input("enter the third value: "))
sum = num1 + num2 + num3
print(sum)
print(f"The sum of given three numbers ... |
8e0400fa1f3956b2e70cb5084fab4abac5982b13 | sevdaghalarova/Donguler | /List_comprehension.py | 417 | 4.28125 | 4 | # List Comrehension listeler uzerinde for dongusunu daha kisa yazmak icin kullanilir
liste=[1,2,3,4,5]
liste1=list()
for i in liste:
liste1.append(i)
#print(liste1)
# yukaridaki kodu list comprehension ile yazarsak
liste1=[i for i in liste]
liste1=[i*2 for i in liste] # her bir elemani 2-3 carpip liste1-e ekleye... |
f2db23034447104787549f69b7c5c44f528fe044 | saadz-khan/SpotDown | /SpotDown/spotipy_api/client.py | 2,341 | 3.578125 | 4 | from spotipy.oauth2 import SpotifyClientCredentials
from spotipy import Spotify
import json
from sys import argv
def spotify_authentication(client_id, client_secret, playlist_id):
"""
This part verifies the credentials for the spotify-api usage
Args:
client_id:
client_secret:
playlist_id: Playlist i... |
1ac326f8a1aadb038ce4ce4502afa9a9de07640b | bhaavanmerchant/challenge-problems | /skycompany/Tree.py | 826 | 3.765625 | 4 | class Tree:
root = {
'value': None,
'children': []
}
def __init__(self, val):
self.root = self._create_node(val)
return self.root
def _create_node(self, val):
return {
'value': val,
'children': []
}
def create_... |
5c30c871d1372ec6d61ff1b195ed2877972bdc42 | hellokena/goorm | /1단계/홀짝 판별.py | 61 | 3.921875 | 4 | n = int(input())
if n%2==0: print('even')
else: print('odd')
|
f0e6b2ace850a92b0771dc2844ca6a2b1bfdcc8b | aliKatlabi/Python_tut | /tutorial/DataStructure.py | 937 | 3.546875 | 4 | vec = [-4, -2, 0, 2, 4]
# create a new list with the values doubled
[x*2 for x in vec]
#[-8, -4, 0, 4, 8]
# filter the list to exclude negative numbers
[x for x in vec if x >= 0]
#[0, 2, 4]
# apply a function to all the elements
[abs(x) for x in vec]
#[4, 2, 0, 2, 4]
# call a method on each element
freshfruit = [' ban... |
b9d2cd65a38cf0cbc57508d5c71d8553973d77e0 | joaovbs96/Logistic-Regression-Neural-Networks-MC886-2018s2 | /nnOneHiddenLayer.py | 6,437 | 3.765625 | 4 | # coding: utf-8
# MC886/MO444 - 2018s2 - Assignment 02 - Neural Network with One Hidden Layer
# Tamara Campos - RA 157324
# João Vítor B. Silva - RA 155951
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import itertools
from sklearn.preprocessing import MinMaxScaler
from sklearn.dec... |
feccaf38a397e46c4d1c0d0ffa3de9501d278d11 | edD9m/codingground | /New Project/main.py | 2,412 | 4.28125 | 4 | print "Hi, my name is Python! I'm a programming language that's intelligent but simple! Enjoy your stay!"
print "Soo, please answer my questions."
myname=raw_input("What's your name? >>> ")
print "Nice to meet you, " + " " + myname
if myname == "myname" :
print "Oh, by the way, don't enter the name of the variable,... |
7436a98a489b0a0f39242ad99b0b83b170171145 | Rapid1898-code/codesignal | /arcade/level54.py | 367 | 3.734375 | 4 | def sumUpNumbers(inputString):
listString = list(inputString)
newString = ""
countSum = 0
for char in listString:
if char.isdigit():
newString += char
else:
newString += " "
newList = newString.split(" ")
for elem in newList:
if elem != "":
... |
38231e47076d65f330d68dd5a4f47ef8843cd8de | kat0h/timetable_bot | /get_timetable.py | 1,128 | 3.59375 | 4 | import csv
import sys
def get_timetable(filepath: str):
# 時間割の読み取り
with open(filepath) as f:
reader = csv.reader(f)
tt = [row for row in reader]
timetable = {}
for i in tt:
timetable[i[0]] = i[1:7]
return timetable
def get_schedule(filepath: str):
# 時間割の読み取り
with ... |
5e0d0f760ac4bda396a4bb8ba9f408d5af7598e0 | jigonzalez124/morseCode | /morseCode.py | 1,195 | 3.984375 | 4 | # Name: Jesus Ivan Gonzalez
# Date: July 20th 2015
# Description: Simple morse code program. Note: / indicates whitespace
def morse(code):
morseCode = {
'.-': 'a', '-...': 'b', '-.-.': 'c', '-..': 'd', '.': 'e',
'..-.': 'f', '--.': 'g', '....': 'h', '..':... |
7900a6d984ef3a63b380fd528a411acbf43ec52d | Ragav-Subramanian/My-LeetCode-Submissions | /923. 3Sum With Multiplicity Python Solution.py | 323 | 3.5 | 4 | class Solution:
def threeSumMulti(self, arr: List[int], target: int) -> int:
twosums={}
ans=0
for i in range(len(arr)):
ans+=twosums.get(target-arr[i],0)
for j in range(i):
twosums[arr[i]+arr[j]]=twosums.get(arr[i]+arr[j],0)+1
return ans%(10**9... |
663e0b6ffc2069637d90ca4cba24cc7b676c8930 | GiantSweetroll/Program-Design-Methods-and-ITP | /Exercises/Lists and Dictionaries/Student.py | 1,536 | 3.875 | 4 | eren = {
"name": "Eren",
"homework": [90.0,97.0,75.0,92.0],
"quizzes": [88.0,40.0,94.0],
"tests": [75.0,90.0]
}
mikasa = {
"name": "Mikasa",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
armin = {
"name": "Armin",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0,... |
efee6903cd41bc93ee9afee9a354a26182eee9d9 | chaofan-zheng/tedu-python-demo | /month01/all_code/day17/demo09.py | 1,938 | 3.546875 | 4 | """
需求:
定义函数,在员工列表中查找最富的员工
定义函数,在员工列表中查找xxx的员工
步骤:
1. 根据需求,写出函数。
2. 因为主体逻辑相同,核心算法不同.
所以使用函数式编程思想(分、隔、做)
创建通用函数get_max(定义到单独模块中)
3. 在当前模块中调用(使用lambda)
"""
from common.iterable_tools import IterableHelper
class Employee:
def __init__(self, eid, d... |
c837c5f673c0a18aa7b17b01bfec37a84e397a23 | Khananashvili/WEB | /LR2/Code_2.2.py | 145 | 3.65625 | 4 | s=str(input("Введите строку: "))
k=s.split(' ')
for i in range (len(k)):
if (k[i][len(k[i])-1:])=='r':
print(k[i])
|
39567f773e1395b4bf94da9fe4505cff5621f350 | df413/leetcode | /maximum_subarray/solution.py | 780 | 4 | 4 |
class Solution(object):
"""
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
"""
def find_maximum_subarray(self, nums):
... |
33bfd882d31d1b3114a2a0cb23557b020cfdce0d | DylanDu123/leetcode | /142.环形链表-ii.py | 873 | 3.5625 | 4 | #
# @lc app=leetcode.cn id=142 lang=python3
#
# [142] 环形链表 II
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def fetchPoint(self, head: ListNode):
fast, slow = head, head
whi... |
2e44f6334967d048fd634fd71bfbfaacb97a0ef5 | kavithacm/MITx-6.00.1x- | /Week 4- Good Programming Practices/7. Testing and Debugging/Exercise- Integer Division | 1,080 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 22 14:27:13 2018
@author: Kavitha
"""
'''
Exercise: integer division
5.0/5.0 points (graded)
ESTIMATED TIME TO COMPLETE: 4 minutes
Consider the following function definition:
def integerDivision(x, a):
"""
x: a non-negative integer argume... |
2926b14261b2c450b0d29d34f802ea63b40e592c | edadasko/coursera_algorithms | /graphs/dijkstra.py | 917 | 3.53125 | 4 | from queue import PriorityQueue
INF = float('inf')
def distance(adj, cost, s, t):
q = PriorityQueue()
n = len(adj)
min_costs = [INF] * n
for i in range(n - 1):
q.put((INF, i))
q.put((0, s))
min_costs[s] = 0
for _ in range(len(adj) - 1):
min_node = q.get()
from_cost, ... |
1e904e2bc98bb6a16844b1c9146de7f6d3af21ff | Ivanochko/lab-works-python | /Topic 07. Strings, Bytes, Bytearray/lab7_11.py | 203 | 3.71875 | 4 | arr = [(i, len(i)) for i in input('Введіть речення на сорт.: ').split(' ')]
arr = sorted(arr, key=lambda x: x[1], reverse=True)
print()
for x, i in arr:
print(x, end=' ')
print()
|
114be0800d32d9221ec5c4c290612e0828b72c7e | haekyu/python_tutoring_ys | /1029/hw_sol/mk_csv.py | 608 | 4.03125 | 4 | """
2. 파일 출력 연습
어떠한 리스트를 csv (comma-separated values) 포맷으로 텍스트파일에 저장해보세요.
예)
[[1, 2, 3, 5], [3, 5, 2, 1], [5, 3, 1, 5]]
라는 리스트가 주어져 있으면
1,2,3,5
3,5,2,1
5,3,1,5
로 텍스트파일(파일 이름 맘대로)에 저장해 보세요.
"""
def save_mat_csv(filename, mat):
f = open(filename, 'w')
for rows in mat:
for th, element in enumerate(rows):
f.write(... |
dcc50569d07ca76d99b486295fa0f9e15ed6d4c6 | paige0701/rockpaperscissors | /main.py | 1,570 | 3.953125 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from enum import IntEnum
class Action(IntEnum):
Rock = 0
Paper = 1
Scissors = 2
def get_user_selection():
... |
08b9b45752de1a0cf21337ff86d3f92ec0400b9d | spencerstock/Sprint-Challenge--Computer-Architecture | /ls8/cpu.py | 4,432 | 3.5625 | 4 | """CPU functionality."""
import sys
class CPU:
"""Main CPU class."""
def __init__(self):
"""Construct a new CPU."""
self.ram = [0] * 256
self.registers = [0] * 8
self.registers[7] = 0xF4
self.fl = 0b00000000
self.pc = 0
def load(self, path):
"""Loa... |
426777904ce7f66b904c4bd97386bb34ee8aebb7 | anrom7/Array | /multiset/multiset.py | 1,827 | 3.734375 | 4 | from multiset.array_list import MyArray
class Multiset:
def __init__(self):
"""
Produces a newly constructed empty Multiset.
"""
self.data = MyArray(100)
self.firstempty = 0
def empty(self):
"""
Checks emptiness of Multiset.
:retur... |
4ed7d7ac539651da3b4be4da47f0f0cfb3e572a3 | dlaevskiy/arhirepo | /fluent_python/2_sequence_array/1_listcomp_and_genexp.py | 576 | 3.578125 | 4 | # list comprehensive
import array
colors = ['black', 'white', ]
sizes = ['S', 'M', 'L']
tshirts = [(color, size) for color in colors for size in sizes]
print(tshirts)
# generators
symbols = '@#$%^7'
gen = tuple(ord(symbol) for symbol in symbols)
print(gen)
ar = array.array('I', (ord(symbol) for symbol in symbols))
... |
0a1385c2e0ad0c6be68f336ba9ef6588b3e4bd8f | koskot77/leetcode | /1448treePath.py | 924 | 3.640625 | 4 | # https://leetcode.com/problems/count-good-nodes-in-binary-tree/submissions/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def helper(self... |
a5ef8d78f80fa0c4c07fe039408c5b1a56baf800 | Zoogster/python-class | /Project 1/admin.py | 3,802 | 4.25 | 4 | """Lets an admin look at the roster and change max class size
show_roster -- Displays roster of a course.
change_max_size -- Allows admin to change max class size
"""
def show_roster(r_list):
"""Displays the roster for a chosen course
Checks to make sure the course entered is valid.
If valid desplays st... |
1c312af821a9253a41a9a87ff566b41daebba346 | kunweiTAN/techgym_ai | /0LTh.py | 652 | 3.765625 | 4 | #AI-TECHGYM-3-2-Q-2
#回帰問題と分類問題
#インポート
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
#データを作成
#0〜1までの乱数を100個つくる
x = np.random.rand(100, 1)
#値の範囲を-2~2に調整
x = x * 4 - 2
#yの値をつくる
#標準正規分布(平均0,標準偏差1)の乱数を加える
y += np.random.randn(100, 1)
#モデル
model = linear_mode... |
2f2e90c195fdd811873c904f23aab19308ee83f4 | ESE205/fl_19_mod_9 | /mod9_func.py | 341 | 3.640625 | 4 | def movingAvg(array_list, numvals_for_average, size_of_array, position):
sumvals = 0
for i in range(numvals_for_average):
if (position - i >= 0):
sumvals = sumvals + array_list[position - i]
else:
sumvals = sumvals + array_list[size_of_array + (position - i)]
return sumvals... |
30c73b09c79b659ce6cae69377e313c37ea69809 | jarroba/Curso-Python | /Casos Prácticos/4.17-bucle_condicional_salida.py | 309 | 3.921875 | 4 | # 1
continua = True
# 2
uno = False
dos = False
tres = False
# 3
while continua:
# 4
print("uno: {}, dos: {}, tres: {}".format(uno, dos, tres))
# 5
if not uno:
uno = True
elif not dos:
dos = True
elif not tres:
tres = True
else:
continua = False
|
f9e37d84a0b00ab191270c8a582c5d8449866edf | letoshelby/codewars-tasks | /6 kyu/IQ test.py | 683 | 4.3125 | 4 | # Description:
# Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of
# the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness.
# Help Bob — to check his answers, he needs a program that among the given numbers ... |
8be15612b4c3fcd38b642474c9f0ad165a0ea386 | gdh756462786/Leetcode_by_python | /Array/Find All Duplicates in an Array.py | 706 | 4.03125 | 4 | # coding: utf-8
'''
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array),
some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
'''
class Solution(object)... |
d63792db1c43815b7dbc63ad65e2ae789a6bd4bc | tp00012x/Hacker-Rank | /Python/Strings/Text Wrap.py | 337 | 3.625 | 4 | # Textwrap
#
# The textwrap module provides two convenient functions: wrap() and fill().
#
# textwrap.wrap()
# The wrap() function wraps a single paragraph in text (a string) so that every line is width characters long at most.
# It returns a list of output lines.
def wrap(string, max_width):
return textwrap.fill(... |
0957e8a5213196a6c5d35606fb3603890ba717e7 | bwhitaker10/Python | /python/fundamentals/funcint1.py | 754 | 3.921875 | 4 | import random
def randInt(min='', max=''):
a = random.random() * ((randInt(max='')) - (randInt(min='')) + (randInt(min=''))
b = random.random() * (100 - (randInt(min='')) + (randInt(min=''))
c = random.random() * (randInt(max=''))
d = random.random()
if randInt(min='', max=''):
return a
... |
7428bdd3d23700f96945cac313223efe189182f1 | SEU-CodingTogether/Daily-Python | /Level-00-Elementary/solutions/s19.py | 665 | 4.0625 | 4 | def most_frequent(data: list) -> str:
"""
determines the most frequently occurring string in the sequence.
"""
# your code here
d = dict(zip(list(set(data)), map(data.count, list(set(data)))))
return sorted(d, key=lambda x:d[x])[-1]
if __name__ == '__main__':
#These "asserts" using only... |
651b022796c0c1de8fb27df38ae5b7adfac1930c | maypel/docstring_exercices | /jeux_aleatoire.py | 1,119 | 3.78125 | 4 | from random import randint
nombre = randint(1, 101) # sélection du chiffre
# intro et paramètres du jeux
print("***Le jeu du nombre mystère***")
essais = 5
print(f"Il te reste {essais} essais")
# boucle du jeux
while True:
num = input('Devine le nombre :') # choix du joueur
if num.isdigit() == True: # on v... |
10790df43ef3b4b0df78aed9fbb6e4ae787fcf20 | clickpn/final_proj | /UpdatedProject1207/general_functions.py | 1,178 | 3.546875 | 4 | import pickle
'''to merge with other teammates'''
def get_dictionary(filename):
'''The function takes a dictionray.p file as input and returns a dictionary.'''
dictionary = pickle.load(open(filename, 'rb'))
return dictionary
def data_extract(data, startyear, startmonth, endyear, endmonth):
data_by_yea... |
3ea97ed39eed4821ff05ff5a92e46dd5e9ed826d | flame4ost/Python-projects | /§4(77-119)/z89.py | 562 | 3.890625 | 4 | import math
print("Задание 88 а ")
a = input("Введите число a ")
a = int(a)
b = input("Введите число b ")
b = int(b)
print("a = ", a)
print("b = ", b)
while (a and b):
if a>=b:
a = a-b
elif(b>=a):
b = b-a
print("Результат",b)
print("Задание 88 б")
def gcd(a,b):
while(b>0):
a,b=b... |
b20766dfda3dc01f17aa2750330a0567325345db | shubhamkanade/Niyander-Python | /Multiplication.py | 107 | 3.765625 | 4 | def multiply(b,c):
mul=b*c;
return mul
result=multiply(4,5)
print("the multiplication is "+str(result))
|
0e7da2ec5944235ea6b5b8b811127f7237254e6f | LZY2006/A-poker-small-game-emulator | /Poker1.py | 2,371 | 3.53125 | 4 | # A 2 3 4 5 6 7 8 9 10 J Q K JOKER JOKER
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
import random
import time
def step(x, _list):
global desktop, one, another
desktop.append(x)
if _list == "one":
if x in desktop[:-1]:
pos = desktop[:-1].index(x)
for i in desktop[p... |
3539f9a0704c66f35e82730a38ec7fbf5dfe0673 | MihailSolomnikov/Mihail | /main.py | 1,098 | 3.6875 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
class Abiturient(ABC):
@abstractmethod
def factory_method(self):
pass
def some_operation(self) -> str:
# Вызываем фабричный метод, чтобы получить объект-продукт.
product = self.factory_method()
... |
e638bb9170ef377411bdcaba3f82d17d3fda0485 | cmonnom/Ped_Endocrine_Risk_Assessment | /date_helper.py | 720 | 3.84375 | 4 | from datetime import datetime
from datetime import timedelta
# split dates
month, day, year = [int(s) for s in "7/2/2014".split("/")]
print(month, day, year)
# testing dates
f_date = datetime(year, month, day)
l_date = datetime(2014, 7, 11)
# difference between dates
diff_date = l_date - f_date
print(diff_date)
# addin... |
3169ff3ba355164dff2955e06d9d5fe0114e7c7a | Harshad06/Python_programs | /Higher complexity programs/sumofTwoNums01.py | 416 | 3.734375 | 4 |
# sum 10 for adjacent 2 numbers??
x = [3, 2, 4, 6, 5, 9, 1, 12, 10]
for i in range(len(x)-1):
if x[i] + x[i+1] == 10:
print(f'Numbers are: {x[i]} & {x[i+1]}')
'''
output:-
# Numbers are: 4 & 6
# Numbers are: 9 & 1
-------------------------------
error if :-
if x[i] + x[i+1] == 10:
IndexEr... |
b53a0ac42858a7acab8f3920688a39993c6e0b6c | ynXiang/LeetCode | /563.BinaryTreeTilt/solution.py | 1,069 | 3.71875 | 4 | #https://discuss.leetcode.com/topic/87208/python-simple-with-explanation
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findTilt(self, root):
"""
:... |
00b65f36fd04c3bdcdd7fc59064e232f8dbdd50a | Renmusxd/PerturbationLib | /PerturbationLib/Symmetries.py | 5,271 | 4 | 4 | from abc import ABCMeta, abstractmethod
from typing import Sequence, Tuple
class Symmetry(metaclass=ABCMeta):
"""
A class containing information as to how to
combine and calculate representations.
Multiplets are stored in (a,b,c...) notation to
remove ambiguity. A conversion method will be impleme... |
3107407ba493e28a9d9b9ac4a6eec8c851a7d2e9 | auntaru/mypycharms | /importcsv7function.py | 951 | 3.59375 | 4 | # https://pythonspot.com/reading-csv-files-in-python/
# https://pythonspot.com/category/database/
# https://pythonspot.com/en/mysql-with-python
# https://pythonspot.com/en/python-database-postgresql/
# https://jakevdp.github.io/PythonDataScienceHandbook/03.10-working-with-strings.html
import csv
import pandas as pd
... |
c6492bd31d9d28f50ebc3a5d8b7e0aaed0eae436 | vijama1/codevita | /automorphic.py | 327 | 3.59375 | 4 | inp=input("Enter the number")
intinp=int(inp)
list=[]
list1=[]
list2=[]
for i in inp:
list.append(i)
length=len(list)
square=intinp*intinp
strsquare=str(square)
for j in strsquare:
list1.append(j)
list2=list1[-length:]
num=int(''.join(list2))
if num==intinp:
print("Automorphic")
else:
print("Not automor... |
ed5a0b99588888098db4ef762dd864c568f73b2a | SleepwalkerCh/Leetcode- | /77.py | 674 | 3.5 | 4 | #77. Combinations
#简单的全排列
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
result=[]
self.result=result
nums=[x+1 for x in range(n-1)]
self.Combination(nums,k,[])
return self.result
def Combination(self,nums,num,res):
if num==0:
s... |
6aeef53d6112d30af0fc7609a257fc54c16bfdf9 | michelman2/RigolDS1000Z | /code/Rigol_Lib/__init__.py | 646 | 3.59375 | 4 | import sys
import os
from pathlib import Path
"""
The file makes paths avaiable to python interpreter
has to be added before using a project hierarchy
"""
def add_subfolder_to_path( project_base_folder):
"""
Function iterates over all folders and subfolders of
current folder and ... |
5e6892111a1e6da698b0b00b6b6f6988d51c8a14 | jes5918/TIL | /Algorithm/SWEA/파이썬SW문제해결 String/범/4861.py | 803 | 3.5 | 4 | import numpy as np
def horizontal(x, n, m):
result = ''
for i in x:
for j in range(n-m+1):
a = i[j:j+m]
for k in range(m//2):
if a[k] != a[-(k+1)]:
break
else:
result += a
return result
def vertical(a, n, m):
... |
5987a40144dce5447965eae0975aa77251b49a1c | AnshulDasyam/python | /syntax/Summation.py | 125 | 3.984375 | 4 | """Sum of first n natural numbers"""
n = int(input("Summation of "))
a = 0
b = 0
while a < n :
a +=1
b += a
print(b)
|
108e5fd5e69e22f430c198b47e6ad18e961843be | permCoding/elective-course | /py/meeting-4-task-27/task-21.py | 107 | 3.578125 | 4 | def f(x):
return 2*x*x+3*x+2
k = int(input())
i = 15
while (i > 0 and f(i) > k):
i -= 1
print(i)
|
f4f71572de30c2c6091b0f985bb2b1526c6ca390 | aman-singh7/training.computerscience.algorithms-datastructures | /09-problems/lc_150_evaluate_reverse_polish_notation.py | 798 | 3.90625 | 4 | """
1. Problem Summary / Clarifications / TDD:
["2", "1", "+", "3", "*"]
9
5
-208
"""
class Solution:
def __init__(self):
self.operators = {
"+": lambda b, a: a + b,
"-": lambda b, a: a - b,
... |
951cb94db2bb676ea0c05bc72ce316f5c103ac7b | Raymond-Zhu/CSC113_Project_1 | /battle.py | 2,000 | 3.765625 | 4 | from status import player_status, battle_status #battle_status checks the status of everyone after someone makes a turn. If all enemy hp is 0 or player's hp is 0, it returns false to break the loop ending the battle
import random
import textwrap
def battle(player,enemies,inventory):
for enemy in enemies:
p... |
eaf64c5ce602b2c608de00f3eb1d9f3ed05d3b24 | EdwinSantos/EECS-4088 | /flask/games/__game.py | 5,082 | 3.578125 | 4 | #!/usr/bin/python3
from copy import deepcopy, copy
from abc import ABC, abstractmethod
from queue import Queue, PriorityQueue
from collections import OrderedDict, deque
class Game(ABC):
class Ranks():
'''
The ranks object is used by the display_game class to display standings.
... |
09ff4026527f0c110fa969ae08996c64df0ae69b | SpencerBurt/Minesweeper-game | /functions.py | 5,611 | 4.0625 | 4 | import board
class Functions:
"""
Provides some of the utility functions for printing and interacting with the gameboard.
"""
@staticmethod
def print_board(board:board.Board):
"""
Prints the gameboard
:param board: The gameboard that will be printed
:type board: ... |
f98979ada41ef6011297582c15c1e07c97a497be | xiao812/code | /temperature/world_population.py | 632 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 22:25:21 2020
@author: w
"""
import json
from test import get_country_code
# 将数据加载到一个列表中
filename = 'population_data.json'
with open(filename) as f:
pop_data = json.load(f)
# 打印每个国家2010年的人口
for pop_dict in pop_data:
if pop_dict['Year'] == '2010':
... |
275c38a2a98831592c7e04dc2185f44119f7ae78 | sdvacap/Python--Spring2020 | /Restriction_enzyme.py | 1,547 | 3.953125 | 4 | #Restriction Enzyme
#Sarah Vaca
#March 02,2020
#ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT
#The sequence contains a recognition site for the EcoRI restriction enzyme, which cuts at the motif G*AATTC (the position of the cut is indicated by an asterisk)
#Write a program which will calculate the size of th... |
d3b4ada695a2b2369fd0d96d5f5ef36c0d9c5a66 | AlexanderRagnarsson/M | /Assignments/Assignment 10/Stringtolist.py | 818 | 4.4375 | 4 | def word_splitter(word):
"""
Takes a string and splits is up into words which it appends to a list
when there is a space or comma and then returns the list
"""
return_list = []
append_word = ''
#Appends word to list whenever there is a space or comma next
for char in word:
if cha... |
26c32a657118a20adf804da60ecd7992af48a29e | me-and/project-euler | /pe050.py | 1,467 | 3.640625 | 4 | #!/usr/bin/env python3
'''
Consecutive prime sum
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below
one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime,
co... |
7ccd87484275fa2b0d0d180da871a7cbe7bb4099 | ovidubya/Coursework | /Python/Programs/assign5part2.py | 879 | 3.734375 | 4 | a = [] # The array with all positive numbers not including zero
b = [] # The array with all negative numbers including zeros
c = [] # The array with all numbers
isDone = True
while(isDone):
x = int(input("Enter a num"))
if(x == -9999):
break
if(x > 0):
a.append(x)
if(x <= 0):
... |
5c507cfc5582665dd273d8b91b712f46803cc8e5 | massey-high-school/2020-91896-7-assessment-zionapril | /2020-91896-7-assessment-zionapril-master/01_String_Checker.py | 606 | 4.09375 | 4 | # Functions goes here
def string_checker(question, to_check):
valid = False
while not valid:
response = input(question).lower()
for item in to_check:
if response == item:
return response
elif response == item[0]:
return item
pr... |
2bcdb5d533b002d8f61510073a0eb07458d72b6d | gdincu/py_thw | /4_File_Handling.py | 2,098 | 4.34375 | 4 | #Ex15
import sys
filename = sys.argv[1]
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Read a File
'r' is the default mode. It opens a file for reading and reads the entire content of the file.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
f=open(filenam... |
77046d8e99bf5b4d3c1b78f9d92a30d2cc2d34b0 | stephnec/ExerciciosLista01-Python | /Ex05.py | 284 | 3.671875 | 4 | precoCombustivel = float(input("Digite o preço do litro do combustível: "))
valorDinheiro = float(input("Digite o valor em dinheiro que deseja pagar: "))
litrosTotal = valorDinheiro / precoCombustivel
print("O total de litros a ser comprado é de " + str(litrosTotal) + " litros") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.