blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
68043bd6a5099c622a478bb5977c69129ae6faea
tree3205/Projects
/cs636/parity_inclass.py
1,961
3.546875
4
import sys class Parity(object): def __init__(self, file): self.file = file def get_parity(self, c): s = "{0:08b}".format(ord(c)) sum = 0 for b in s: if b == '1': sum += 1 return sum % 2 def encode(self, outfile): """Return enco...
f0363b56f458b3d0a4a993588b5ea624ac70e2bc
UsmanovTimur/Rock-Paper-Scissors
/localization/ru.py
1,557
3.59375
4
# coding:utf-8 from .localization import BaseLanguage class RuLanguage(BaseLanguage): """Русский язык""" @classmethod def get_name(cls) -> str: return "Русский" def hello(self) -> str: return """Добрового времени суток! Приятной игры)\nВыберите вариант:\n{}""" def get_rock(self)...
103db903d0cc102fe683fc5cc1a10959621d2bca
Timothy-Davis/NameSort
/Sorting.py
2,651
4.375
4
import sys def sort_names(unsorted_names, sort_ption): # This list will contain all the names whose first character falls outside of the English alphabet. nonsortable_name_list = [] index = 0 while index < len(unsorted_names): # First, strip extra characters (such as \n and spaces)...
7da632e0af9a1429dcfc3d43d63b3c29a433c070
plawanrath/Leetcode_Python
/wordBreakToGetAllCombos.py
5,524
3.78125
4
from typing import List """ s = "catsanddog" wordDict = ["cat", "cats", "and", "sand", "dog"] wordBreak(s, wordDict) return: ['cats and dog', 'cat sand dog'] Approach: This can be done with DFS. We start with the entire string s. Then we go word by word in the wordDict to see if we can find one of the dordDict wo...
6fadc2a655e605c8f2a2905c99a6fd73f872992d
chenxu0602/LeetCode
/2552.count-increasing-quadruplets.py
835
3.5
4
# # @lc app=leetcode id=2552 lang=python3 # # [2552] Count Increasing Quadruplets # # @lc code=start class Solution: def countQuadruplets(self, nums: List[int]) -> int: # Specifically, We use dp[j] stores the count of all valid triplets (i, j, k) that satisfies i < j < k and nums[i] < nums[k] < nums[j] an...
8e066f76ac7506e112574510f617327927e0fc24
lldenisll/learn_python
/aulas/bubblesort1.py
642
3.609375
4
class ordenador: def bolha(self, lista): fim = len(lista) for i in range(fim-1, 0, 1): for j in range(i): if lista[j]>lista[j+1]: lista[j], lista[j+1] = lista[j+1], lista[j] return lista print(lista) def ordenada(self,...
5174b45a4744d830fe4e5d7938ef951208a06be2
Sulorg/Python
/Self-taught-programmer-Althoff/ООП2.py
1,112
4.03125
4
#Задание1 class Shape(): def what_am_i(self): print("Я - фигура.") class Square(Shape): square_list = [] def __init__(self, s1): self.s1 = s1 self.square_list.append(self) def calculate_perimeter(self): return self.s1 * 4 def what_am_i(self): super().what...
13e0c7bd4f2f5c00f3797ee473c20d0fa3933bf7
LeiShi1313/leetcode
/leetcode_py/109_convert_sorted_list_to_binary_search_tree.py
1,098
3.875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def build_list(l): if not l: return None p = head = ListNode(l[0]) for val in l[1:]: node = ListNode(val) p.next = node p = p.next return head #...
ec05db60745e84bc30d6e822ad36867d0e42fb6b
Vlas7528/Tensor-Homework
/lesson-1/Циклический светофор.py
535
3.984375
4
while True: print('Введите код сигнала светофора, где:\n\n 1 - Красный\n 2 - Жёлтый\n 3 - Зелёный\n\nДля выхода из программы введите 5') color=int(input()) if color == 1: print('Стой') elif color == 2: print('Ожидай смены сигнала') elif color == 3: print('Иди') elif color...
2e372442369383963cc25059d2e83e25874168ee
wisteria2gp/my_reinfo
/DP/environment_demo.py
1,857
3.546875
4
import random import numpy as np from environment import Environment class Agent(): def __init__(self, env): self.actions = env.actions def policy(self, state): return random.choice(self.actions) def main(): # Make grid environment. grid = [ [0, 0, 0, 1], [0, 9, 0, ...
fb3b4528e47e29dd0eadf29668544dbcafedaf05
cmok1996/helpme
/Python/tutorial/inheritance.py
649
3.796875
4
class Pet : def __init__(self, name, age): self.name = name self.age = age def show(self): print(f"I am {self.name} and I am {self.age} years old") def speak(self): print("I dont know how to speak") class Cat(Pet): def __init__(self, name, age, color): super()._...
0694a4b9cb9ca4227ce79b7fc13613beb4ebeec6
furu8/fizzbuzz
/test.py
677
3.8125
4
""" このファイルに解答コードを書いてください """ import pandas as pd def read_text(path): df = pd.read_table(path, sep=':', names=['num', 'str']) return df def main(df, m): df = df.dropna() df['num'] = df['num'].astype(int) df['rem'] = m % df['num'] ans_df = df.loc[df['rem']==0] ans_df = ans_df.sort_values('...
19010144e413b86b91a81310bc075f411e171cc1
qkreltms/problem-solvings
/기반알고리즘모음/버블정렬/직접구현.py
184
3.84375
4
def bubble(a): for i in range(len(a)): for j in range(len(a)-1): if a[j] > a[j+1]: a[j],a[j+1]=a[j+1],a[j] print(a) bubble([8,5,3,2,7,1])
bc5505841e734e2fdc1ea7eb232b9a01c9dbb9f8
pythonmentor/webinaire-python-mvc-juin-2021
/mynotes/models.py
1,613
3.65625
4
from datetime import datetime class Note: """Représente une note prise par l'utilisateur.""" def __init__(self, title, content=None, notebook=None, tags=[]): self.updated_datetime = None self.title = title self.content = content self.created_datetime = datetime.now() s...
3fb4affcdc587d509aac886641c5005d6c39a7ae
tanisha03/Sem5-ISE
/SLL-finals/SEE/1a.py
440
3.953125
4
print("enter integers separated by space") a=input().split() #separate elements by space arr=[int(i) for i in a] #convert each to integer print("Max :", max(arr)) print("Min :", min(arr)) print("enter element to be inserted") i=int(input()) arr.append(i) print("enter element to be deleted") i=int(input()) arr.remove(i)...
f3f53439628ba0e2998b0ad6bed0d703dc249894
FlavioFMBorges/exercicios_Python_Brasil
/leet code/1-two_sum.py
1,186
3.984375
4
"""class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You...
8153ae422acf80c01f70d900daf5e9504e81844b
riverszxc/riverplum
/pkm/lbld/141.环形链表.py
2,054
3.53125
4
# # @lc app=leetcode.cn id=141 lang=python3 # # [141] 环形链表 # # https://leetcode.cn/problems/linked-list-cycle/description/ # # algorithms # Easy (51.49%) # Likes: 1634 # Dislikes: 0 # Total Accepted: 857.9K # Total Submissions: 1.7M # Testcase Example: '[3,2,0,-4]\n1' # # 给你一个链表的头节点 head ,判断链表中是否有...
d91c53a7c51168dcbe16df8900ffe667e84586ad
vnetserg/algorithms
/greedy/task3.py
859
3.890625
4
#!/usr/bin/env python3 ''' https://www.hackerrank.com/challenges/luck-balance ''' def max_luck(max_loses, contests): ''' Вернуть максимальное количество удачи, которое Лена может иметь после окончания всех контестов. Параметры: max_loses - максимальнок число важных контесто...
9e113bf9dc7282ef12eec70e90df0b95fd30313b
mkirwa/Triangles
/triangle1.py
129
3.65625
4
#!usr/bin/python from __future__ import print_function for i in range(1,10): for j in range(1,i): print('#', end='') print()
02c5db64c0443842315bd182d92dd1d95bac0dfe
ivopascal/Epistemic_Kwartet
/brain.py
9,904
4.03125
4
import deck class Known_player: ''' The Known_player class is distinctly different from the Player class. A Known_player here is the representation of a participant that exists in the brain. You can therefore not interact with a Known_player, but you can store your knowledge about that pla...
75d26236f7a0f532b4ae996d75ad6703de19543c
ji0859/Algorithm
/programmers/level1/서울에서 김서방 찾기.py
168
3.5
4
def solution(seoul): answer = '' for i in seoul: if i == "Kim": answer = "김서방은 "+str(seoul.index(i))+"에 있다" return answer
7065171cd6b55d9db273c61d40ed34fc949943c8
cjduffett/Python-Projects
/Always Turn Left/Boundaries.py
712
3.734375
4
import sys # ---------------------------------------------- # Boundaries of the maze; min/max x and y vals # ---------------------------------------------- class Boundaries: def __init__(self): self.xmin = 0 self.ymin = 0 self.xmax = 0 self.ymax = 0 def getSize(self): ...
713e1f55f41ba169363ec5290320c98aaa7ab5f9
r87007541/270201026
/lab4/example5.py
106
4.125
4
n = int(input("Enter a Number :")) factorial = 1 for x in range(1,n+1) : factorial *= x print(factorial)
c96a63821c2542257ee4cb1ce548823b7be141cb
Theneaaaaaa/unit_seven
/d2_unit_seven_warmups.py
183
3.84375
4
name = "Guido van Rossum" lowercase_name = name.lower() print(lowercase_name) index = name.index("v") print(index) print(name[10]) split_name = lowercase_name.split() print(split_name)
086a9e15549e67a605196af485c36d6d0a3c874b
TuckerFerguson/py_DataScience
/numpy_methods/multiDimensionXOR_NumPy.py
962
4.40625
4
""" @author Tucker Ferguson 1/9/2020 Simulating 'XOR' on a 3D array, using the numpy library (array,shape,ones) """ import numpy as np #3D array to preform 'XOR' operation on my3dArray = np.array([ [[0,1,0], [0,1,0], [0,1,0]], ...
7c64176782af6f0b7d43ea061a21cfd5c02ff4bb
programmicon/teknowledge
/curriculum/07_game_02_circle_clash_2_DAYS/07_game_02_circle_clash_day_1/07_02_02_circle_clash_advanced.py
3,641
4
4
from tkinter import * # the game data for the initial game state def init(): data.playerX = 250 data.playerY = 550 data.circleX = 250 data.circleY = 0 data.gameOver = False # events updating the game data def keyPressed(event): if event.keysym == "Right" and data.playerX < 550:...
1992ba39499260d7b985a333d364e9cf7672c334
ricknigel/machineLearningCookbook
/chapter1/recipe1-10.py
550
3.9375
4
# 1.10 ベクトル、行列の転置 # 問題 # ベクトルもしくは行列を転置したい。 import numpy as np # 行列を作成 matrix = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]) # 行列を転置 print(matrix.T) # 転置とは、 # 行列の各要素に対する列インデックスと行インデックスを入れ替えること。 # ベクトルの転置 以下の場合、転置できない。 print(np.array([1, 2, 3, 4, 5, 6]).T) # 行ベクトルの転置 print(np.array([[1, 2,...
8ca2ea1de6c297cfc06513a07bd18c14e4322c87
mehransadeghi/Python_Stocks_2
/stock.py
6,551
3.5625
4
import requests from pyquery import PyQuery from iex import Stock from selenium import webdriver MAX_TICKERS=110 class Tickers: """ A class to fetch all tickers and store them in a file tickers.txt :type ticker_count: int :param ticker_count: The number of tickers to get """ def __init__(self, n): """ Cre...
13cd84bc6498985615b191fe1eb977f007e6bf9a
serimj98/fundprog
/serimj@andrew.cmu.edu_hw9_4_handin.py
10,382
3.59375
4
# 15-112 # Name: Serim Jang # Andrew ID: serimj ################################################# # Hw9 # # No iteration! no 'for' or 'while'. Also, no 'zip' or 'join'. # You may add optional parameters # You may use wrapper functions # ################################################# import cs112_f17_week9_linter ...
aa58d5137d030325b36ca1cfe2657e9672bb6b7b
RWaiti/URI
/1146.py
228
3.71875
4
# -*- coding: utf-8 -*- N = 1 while N != 0: N = int(input()) if N != 0: for i in range(N): print (str(i+1),end="") if i+1 != N: print(' ',end="") print()
9e68055784aa55e5aa1ab50588d21fd16ede704c
Mumulhy/LeetCode
/面试题04.06-后继者/InorderSuccessor.py
767
3.6875
4
# -*- coding: utf-8 -*- # LeetCode 面试题04.06-后继者 """ Created on Mon May 16 10:28 2022 @author: _Mumu Environment: py38 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def inorderSuccessor...
8a91c59d1fc909dca53cd0a05e3861c66040adce
lrj1197/Python
/Analytics/Bullshit_project.py
5,949
3.671875
4
''' This Program allows one to input data in the form of 'source of bs # date gathered # type of bs(political, eduacational, social) # kind of bs(plots, tweet, etc)' Then sift through the input and add the data to their lists. when finished enter 'end' to terminate the program and then put the data into a pd.datafr...
c3d6967017f9d43cb4b54d23533d2b747faaf2bc
jonathanrhyslow/mytrix
/mytrix/vector.py
9,183
3.6875
4
"""Module for general matrix class.""" from random import randrange from math import sqrt import mytrix.exceptions as exc import mytrix.matrix as mat class Vector: """A class to represent a general matrix.""" def __init__(self, m, data): """Initalise vector dimensions and contents.""" self....
753944fbe3f0d194450510aec6c740900c6db7f0
Paper-SSheets/PositivityBot
/positive_sayings.py
6,298
3.640625
4
# Create a list and just append whatever you want to it! positive_sayings = list() positive_sayings.append("You are a unique child of this world.") positive_sayings.append("You have as much brightness to offer the world as the next person.") positive_sayings.append("You matter and what you have to this world also...
afac4f7ef191d6912c7e22e424be4d1f75521099
poojataksande9211/python_data
/python_tutorial/excercise/ip_char_count_full_string.py
183
3.671875
4
name=input("enter name") temp_var ="" i=0 while i< len(name): if name[i] not in temp_var: temp_var += name[i] print(f"{name[i]}:{name.count(name[i])}") i += 1
6cdf8bd3910c26fa9da98dadf612eb4da4b90067
arpit0891/Project-Euler
/problem_01/sol7.py
536
4.25
4
""" Problem Statement: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below N. """ def solution(n): """Returns the sum of all the multiples of 3 or 5 below n. """ //Solution r...
0ee606574fd3760b22f6c4220320aa6e0fcfb6f5
Fenmaz/connect4
/minimax/src/minimax_tentative_solver_fail.py
6,879
3.515625
4
''' Aim is to create a solver that outputs how many steps are left to end up with a win/lose/draw for the current player. I am assuming that it's player 1's turn given the current configuration of the board. I referred to an example of the Negamax solver: http://blog.gamesolver.org/solving-connect-four/03-minmax/ I ...
a5c05491a9937db3090b9d4ecf45a11d04382bc2
SandyHuang0305/python
/階乘練習.py
529
3.96875
4
# 階乘練習 #讓用戶輸入數字 num = int(input('請輸入一個數字:')) factorial = 1 #確認該數是正負數 if num < 0: print('負數沒有階乘的喔') elif num == 0: print('0的階乘為1') else: for i in range(1, num + 1): factorial = factorial * i print(num, '的階乘為', factorial) #利用math庫 import math num = int(input('請輸入一個數字:')) if num < 0: print('...
71edf37aae002bf73035c2a3c18d47597d03f848
crzysab/Learn-Python-for-Beginners
/010-Operators/Operator_Special.py
375
4.15625
4
#Membership operator x = 'Hello World' print("'H' in x : ", 'H' in x) #Return True print("'S' in x : ", 'S' in x) #Return False print("'T' not in x : ", 'T' not in x) #Return True y = {1:'a', 2:'b'} print("1 in y : ", 1 in y) print("'a' in y : ", 'a' in y) #Identity operator a = 'Hello' b = 'hello' c = 234 d = 432 pr...
80e5e095c57135f5afcfe4e0ce19fd3cd3c05a2b
DemetrioCN/python_projects_DataFlair
/basic_email_slicer.py
289
3.796875
4
print("\n") print(10*"-", "Email Slicer", 10*"_") print("\n") email = input("Introduce your email: ").strip() user_name = email[:email.index('@')] domain = email[email.index('@')+1:] output = f'Your usernam is {user_name} and your domain name is {domain}' print(output) print('\n')
b0dc68843e6f552ca05ccda14ad2939a278cc921
moussadiak87/Python
/Calculette/calc_objet/calculatrice_logique.py
588
3.5625
4
class Calculatrice_logique(): def __init__(self): self.valeur1 = 0 self.valeur2 = 0 self.operateur = "" """ prendre les valeur qu'on rentre et afficher memoriser' chronologique entrer une premiere valeur entrer un operateur entrer une deuxieme valeur demander le resultat exemple : 5 *...
2932154adc80fe884c7e6236885e29d7da88a969
Tak1za/Python-DSA
/anagram_check.py
295
3.875
4
def anagramCheck(s1, s2): dict1 = {} dict2 = {} for i in s1: dict1[i] = dict1.get(i, 0) + 1 for i in s2: dict2[i] = dict2.get(i, 0) + 1 if dict1 == dict2: print("Anagram!") else: print("Not an Anagram!") anagramCheck("apple", "elppa")
e213c0827982768b418fcf20fe20b738aa2e7510
Mr0grog/example-numpy-attribute-property-issues
/example_module/__init__.py
719
3.765625
4
class ExampleClass: """ This is an example of how attributes and attributes that are properties get formatted by numpydoc. Attributes ---------- normal_attribute : str This is a normal attribute, fully specified in class docstring. property_attribute """ def __init__(self):...
2aa46b0207d58dfd08fd26bb648cc4480a3a0cec
lntr0wert/python
/lab5-4.py
448
3.5625
4
# -*- coding: utf-8 -*- import math a, b, c = input('Kvadratne rivnyanna vyglyady ax^2 + bx + c = 0 \n\n enter A, B, C :').split(' ') a1 = int(a) b1 = int(b) c1 = int(c) def descr(): descr_value = sqrt((b*b) - 4*a*c) return descr_value def x1(): x1_value = (-b + descr_value)/2*a return x1_value ...
14f350ce3f11f0a86f4f14400c81cee735331178
coultat/yieldlove
/picanha/dictionary2.py
1,212
3.703125
4
import random from random import randint class darcarta(): def __init__(self): self.cartas = {'corazones':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'], 'diamantes':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'], 'picas':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'], 'treboles':[1, 2, 3, 4, 5, 6, 7,...
8bbe6935b1b439e16df05b8bf73bbf0c9b29b54f
antongiannis/phd_tools
/phdTools/graphs.py
1,424
3.5625
4
import matplotlib.pyplot as plt def donut_chart(labels, sizes, explosion=True, colors=None): """ Creates a donut chart with explosion if selected. Parameters ---------- labels: ndarray An array with the labels for the donut chart. sizes: ndarray An array with the counts for ea...
3adb0122c6c2190389ffa9c91e2e3013f08310fa
alvinwang922/Data-Structures-and-Algorithms
/Trees/Tree-To-LinkedList.py
1,529
4.21875
4
""" Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place. You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the succes...
636179e1a741fb3ec0dc7f3f0187d16cd0e9ab5d
srishtigyawali/Quiz-game-python
/quiz slack.py
1,999
3.90625
4
Question = ["Which one is the first search engine in internet?","Number of bits used in IPV6 address","Which one is the web browser invented in 1990", "Which of the programming language is used to create program like applets?","What is the name of the first computer virus", "Why do we ...
dc6954b2f8a2b214b28b9df6e6457865392caacb
htingwang/HandsOnAlgoDS
/LeetCode/0148.Sort-List/Sort-List.py
916
3.9375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return ...
778643f545c86617fdc7094a9f6634e4c9ebd125
MaxPower9090/micro_drip_2018
/drip_time.py
1,938
3.828125
4
#!/usr/bin/python # calculates from the yyyymmdd.txt the average temperature and returns a time in seconds calculated by some logic import sys import time def drip_time(): # values are in a file yyyymmdd.txt filename = time.strftime("%Y%m%d.txt") #generates the filename by the date filename = "/home/pi/Temp/"...
cdf3e7c5d17089a74430146bae2d9e114e4cfebe
sreejithr/SoundEx-Plus-Algorithm
/soundex_plus/soundex_plus.py
3,396
3.578125
4
chars = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] H_GROUP = "7" Y_GROUP = "8" VOWEL_GROUP = "0" # Letter classes codes = [VOWEL_GROUP, "1", "2", "3", VOWEL_GROUP, "1", "2", H_GROUP, VOWEL_GROUP, "2", "2...
fe3c702df7f8d3d54b47e8ce578ba281e37e9bf2
udwivedi394/binaryTree
/checkLargestBST.py
2,563
3.953125
4
class Node: def __init__(self,data): self.data = data self.left = None self.right = None #Time complexity: O(n) #This function returns the [MaxHeight,BSTstatusofCurrentNode,minimum of subtree,maximum of subtree] def findLargestBSTUtil(root): if root==None: return [0,False,None,None] #If current node is lea...
6b70a36ccbae97df8d76efaf19ba4e58d8926f24
case/PyDomainr
/pydomainr/PyDomainr.py
3,252
3.53125
4
import requests class PyDomainr(object): def __init__(self, domain): """ Prepare the API urls """ self.DOMAIN = domain self.SEARCH = "https://domai.nr/api/json/search?q=" + self.DOMAIN self.INFO = "https://domai.nr/api/json/info?q=" + self.DOMAIN def _api_sear...
2f9a31bd41541d21d47b298e9f57ec4bec4c6823
maximiliense/Data-science-2.0
/engine/flags/flags.py
2,357
3.71875
4
import warnings def deprecated(comment=''): comment = '' if comment == '' else ' (' + comment + ')' def _deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" def new...
dc987bb71704d72569af3cb87ae82f7d6669fb01
mengqi0315/predict_car_sales_price
/workspace_for_python/Day04/1.类的创建.py
1,103
4.3125
4
# python中类的创建 # python中如何定义类中的方法 def 方法名(self,形参) # 对象的创建语法:对象=类名() # 对象的使用通过“.” class Person: def __init__(self,name,age): """ 构造方法(创建对象,初始化对象) self是指当前类对象 """ self.name = name self.age = age print("我是人类的构造方法") def introduce(self): print("我叫{},...
b4d4e8a27981ac596d7ac1e7edcce68f0bac5554
jdobner/grok-code
/grid_challenge.py
521
3.703125
4
#!/bin/python3 # Complete the gridChallenge function below. from typing import List def gridChallenge(grid : List[str]): ''' >>> gridChallenge(['ebacd', 'fghij', 'olmkn', 'trpqs', 'xywuv']) 'YES' >>> gridChallenge(['ebacd', 'aaaaa', 'olmkn', 'trpqs', 'xywuv']) 'NO' ''' m = map(sorted, gri...
c6cab78138c9cd7db3694b87b479ac97f87e1f35
Bashorun97/python-trainings
/grade rewritten.py
511
4.3125
4
print('Enter a value between 0.0 an 1.0 to determine the corresponding grade') score = float(input('Enter score: ')) msg = '' def computegrade(score): if score >= 0.90 and score <=1.00: msg = 'A' elif score >= 0.80 and score <=0.89: msg = 'B' elif score >= 0.70 and score <= 0.79: m...
d7b3fc26d5dd4bf236d1e8d2bd56ca8f2fdb662e
q737645224/python3
/python基础/python笔记/day07/exercise/charator_count.py
638
3.640625
4
# 练习: # 输入一段字符串,打印出这个字符串中出现过的字符的出现次数 # 如: # 输入: # abcdabcaba # 打印: # a: 4次 # b: 3次 # d: 1次 # c: 2次 # 注: # 不要求打印的顺序 s = input("请输入: ") # abcdabcaba # 创建一个字典用来保存字符的个数 d = {} for ch in s: # 先判断这个字符以前是否出现过 if ch not in d: # 第一次出现 d[ch] = 1 # 将次数设置为1 ...
88d8af1299c1aa9664a7ec20dddea6a766ff3b94
DanielJmz12/Evidenicas-Programacion-avanzada
/Evidencia50_lista_alturas.py
531
3.8125
4
alturas = [] suma=0 mayor = 0 menor = 0 for x in range(5): valor = float(input("ingresa una altura: ")) alturas.append(valor) suma = suma+valor promedio = suma/5 print("el promedio de alturas es: ") print(promedio) for x in range(5): if alturas[x]>promedio: mayor = mayor+1 ...
ac7c4ba6c2458b2c9f4546aa575bddf8a1b1dcde
LiBReShiNn/algorithm-practice
/python/training/factorial.py
250
4.1875
4
def factorial(num): if num == 1: return 1 return num * factorial(num - 1) def factorial_tail(acc, num): if num == 1: return acc return factorial_tail(acc * num, num-1) print(factorial(3)) print(factorial_tail(1, 3))
cda32d38509f0465e8fdf9b685c74ee2b3d462e1
BrenoSDev/PythonStart
/Introdução a Programação com Python/Listas22.py
615
3.9375
4
#Pilha de Pratos prato = 5 pilha = list(range(1, prato+1)) while True: print('\nExistem %d pratos na pilha'%len(pilha)) print('Pilha atual:', pilha) print('Digite E para empilhar um novo prato,') print('ou D para desempilhar. S para sair.') operação = input('Operação (E, D ou S): ') if operação == 'D': if len(p...
2ac9ce33f37401cb2ae967f3d1040aaf61ae15a3
himol7/Sosio-Submission
/Python/python5.py
275
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sun Dec 30 23:24:32 2018 Default Arguments @author: Himol Shah """ def print_from_stream(n, stream=None): if stream is None: stream = EvenStream() for _ in range(n): print(stream.get_next())
a2b77513f2ed5b72ac1b6b472ae61a3b675feedb
Aasthaengg/IBMdataset
/Python_codes/p02420/s443234117.py
287
3.546875
4
ans = [] while (1) : word = input().strip() try : inputLen = int( input().strip() ) except : break for i in range(0, inputLen) : h = int( input().strip() ) word = word[h:] + word[:h] ans.append(word) for s in ans : print(s)
12660f04d11f30d60b93eef79be229799d039005
olgaBovyka/BasicLanguagePython
/Урок 1/task6.py
1,134
3.6875
4
first_day_int = 0 total_int = 0 counter_int = 2 var_input = input("В первый день результат спортсмена составил a километров: ") var_input2 = input("Суммарный результат пробежек не менее b километров: ") if var_input.isdigit() and var_input2.isdigit(): first_day_int = int(var_input) total_int = int(var_input2) ...
d8b6315ddf19b537ef1d43bdc296ab36f1199140
pttran3141/python_practice
/canSum_DP.py
1,600
3.5625
4
############################################## #This solution will not work because of memo # def canSum(targetSum, numbers, memo = None): # if memo is None: memo = {} # if (targetSum in memo): # return memo[targetSum] # if (targetSum == 0): # return True # if (targetSum < 0): # retu...
b8e9c82569c7beaa0a943fa22d4332c8e1fa913e
zhangke8/Applications
/Python/ceiling floor.py
4,718
4.21875
4
##################################################################### # Author: Kevin Zhang # Date: 12/20/2014 # purpose: calculate ceiling and floor values ##################################################################### def ceiling(c): ######################################## # purpose: does ceiling ope...
3427274e83c07d602e0ebfb5a6138f9fbccf1447
joshrwhite/ECE-20875---Python-for-Data-Science
/homework2-gferrara-purdue-master/homework2.py
1,867
3.8125
4
#!/usr/bin/python3 def histogram(data, n, l, h): hist = list() for i in data: if not (isinstance(i,float) or isinstance(i,int)): print('Error in format of data. Non-float element found.') return hist if not (isinstance(n, int) and (n > 0)): print('Variable "n"...
318079ddb197fa950ff07adc50c09fa069a0cca5
ddascola/hello-world
/Lektion2/2.3.py
257
3.875
4
Number1 = input("Please write a number for calculation:") Number2 = input("Please write another number for calculation:") Number11 = int(Number1) Number22 = int(Number2) Result = Number11 + Number22 print(f"The sum of {Number11} and {Number22} is {Result}")
dd25eb37231c22a075dc5c5cb4cabc182537b08e
tollo/ICPP
/find_extreme_divisors.py
1,506
4.125
4
# Find common divisors of two numbers # Introduction to Compututation and Programming uising Python d = {} for x in 'ab': # Error handling for data types other than 'int' while True: try: input_value = int(input('Integer_' + str(x) + ': ')) break except ValueError: ...
d3d5e55b00d9c7d6fe89fa9a10379ea7c7b5d59d
RYO515/test
/for.py
1,196
3.84375
4
last_names = ['今西', '佐藤', '鈴木', '田中'] first_names = ['航平', '謙介', '康二', '康介'] # print(last_names[0] + first_names[0] + 'さん') # print(last_names[1] + first_names[1] + 'さん') # print(last_names[2] + first_names[2] + 'さん') # print(last_names[3] + first_names[3] + 'さん') for i in range(len(last_names)): print(last_names...
b474fd141e689d63b921d035fdc99c2bbc1ace83
JakeColtman/BayesianBats
/Maze.py
1,264
3.90625
4
import numpy as np import random from matplotlib import pyplot as plt def random_square(maze): x, y = random.randint(1, maze.shape[0] - 2), random.randint(1, maze.shape[0] - 2) return [x, y] def display_maze(maze): fig = plt.figure() ax = fig.add_subplot(111) im = ax.pcolor(maze) plt.show(bl...
0f054f6919ab29c17471b8bb3c0e84f4ad566f00
vineetkr7/Google-Kickstart-Round-G-2021
/dogs_and_cats.py
5,049
3.75
4
''' Problem You work for an animal shelter and you are responsible for feeding the animals. You already prepared D portions of dog food and C portions of cat food. There are a total of N animals waiting in a line, some of which are dogs and others are cats. It might be possible that all the animals in the line are...
8669bd3a222cad93f36688d7fc45663ae0314c0d
DmitryVGusev/Python_lessons_basic
/lesson03/home_work/hw03_normal.py
6,286
4.46875
4
# Задание-1: # Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента. # Первыми элементами ряда считать цифры 1 1 """ Предположим, что при обращении к ряду Фибоначчи, счет начинают все же с первого элемента, а не с нулевого """ def fibonacci(n: int, m: int): """ Функция, возращающая список и...
d21e722228887c777b7128d97345b9bdcd63f66c
monishnarendra/Python_Programs
/QuickSort.py
606
3.921875
4
import random def quicksort(list1): if len(list1) > 1: high,low,equal=[],[],[] pivot = list1[0] for i in list1: if pivot < 0: low.append(i) if pivot == 0: equal.append(i) if pivot > 0: high.appen...
e69cc88c8f710afcec7b8925bf0fcde3f13de5e7
roynitin710/gussing_game-python
/guessing.py
407
3.984375
4
import random Name=input("Enter your name= ") secret_no= random.randint(0,9) guess_count=0 guess_limit=3 while guess_count < guess_limit: guess_count +=1 guess_no = int(input(f"Guess the no. (between 0 and 9)=")) if guess_no == secret_no: print(f'{Name} You Won, {secret_no} is the secret no...
f09d0eb2a400dbdab893db63444ab64fad72833e
wxmsummer/algorithm
/leetcode/hot/98_isValidBST.py
1,256
3.515625
4
class Solution: def isValidBST(self, root:TreeNode) -> bool: # 判断以node为根节点的子树,其子树中所有的值是否都在(low, up)范围内 def helper(node, low = flaot('-inf'), up = float('inf')): if not node: return True val = node.val # 如果 if val <= low or val >= up: ...
a5ab0ce6e43243dea907bc427f774bc56e819145
TrialAnd404/ShowAndTell
/ArtificialIntelligence/mailClassifier.py
34,019
3.828125
4
#!/usr/bin/env python import math import sys import os import argparse from collections import Counter, defaultdict import pickle import nltk import re import csv """ text Classifier ------------------------- a small interface for document classification. Implement your own Naive Bayes classifier by...
4aa72de6ab4a84d64aa9ebba183f8f840eb14374
naitik30/learnpythonbyhardway_ex
/ex11.py
290
3.71875
4
print "How old are you?", age = raw_input() # 26 print "How tall are you?", height = raw_input() # 6 print "How much do you weigh?", weight = raw_input() #90 print "So, you're %r old, %r tall and %r heavy." % ( age, height, weight) # So, you're '26' old, '6' tall and '90' heavy.
b9262f9c0927b1c8495b802ad0d03c1299633d91
iafjayoza/Python
/Longest_Common_Subsequence/maximum_subarray.py
486
3.9375
4
# Kadane's algorithm for maximum sub-array problem. def max_subarray(a): current_max = global_max = a[0] subarray = [] for i in range(1,len(a)): current_max = max(a[i],current_max + a[i]) if current_max > global_max: global_max = current_max subarray.append(a[i]) ...
442dc6b6f0272515c10a3591d51be267068174f5
RaphPortland/easy_pytest
/convertisseurdetemps.py
877
4.21875
4
def convert_minutes_to_seconds(minutes): result = minutes * 60; return result; def convert_hours_to_minutes(hours): return hours * 60; def convert_days_to_hours(days): return days * 24; def convert_hours_to_seconds(hours): return hours * 60 *60; a = 0; while(a != 5): print("1 . convert_minutes_to_secon...
5e07efd4333f6ae6092a4ad87bb5ca8bb6876591
Upendradwivedi/random
/game.py
1,843
3.96875
4
print("\t\t\t***************DICE GAME*****************") print("do you want to continue-:") ch=input("write Y for yes and N for no-:") while(ch=='Y'): i=0 COUNT=0 count=0 while(i<5): import random import time player=random.randint(1,6) ai=random.randint(1,6) ...
07f17c08316b044f726206b19c509d3b049c0a6d
Guadalupe-2021/4-en-linea
/4EnLinea.py
2,774
4.0625
4
print("Bienvenido al juego") movs= int(input("ingrese la cantidad de movimientos(1 movimiento es el del jugador y el del jugador 2): ")) secuencia_1=[] contador=1 print("ingrese la secuencia") for contador in range(movs) : secuencia_1.append (int(input("Ingrese el movimiento del Jugador 1: "))) secuencia_1.append ...
39ee7394ef833575d49d448c77c4615b26339723
neelaryan2/Proof-Reading-Rewriter
/packages/preProcessing/caseCorrector.py
712
3.71875
4
import re # Written by Niraj Mahajan, Department of Computer Science, IIT Bombay. # Inputs a list of strings and returns corrections for Case # This is based on the position of full stops and ^ characters. # Corrects only the first letter of every sentence def caseCorrector(in_list): for i,elem in enumerate(in_list):...
333686eb64818cb5c7b151dee465534ac79d45ac
zbhuiyan/SoftDesSp15
/inclass/oop_practice/solutions/problem3_sol.py
1,938
4.34375
4
""" Practice problems for objects """ from math import sqrt class PointND(object): def __init__(self, coordinates): """ Initialize an n-dimensional point from a list of coordinates. coordinates: a list of numbers specifying the coordinates of the point """ self...
5a6fef06b7bd1b63b1db9ed0f88d767a12b619a9
tychonievich/cs1110s2017
/markdown/files/002/write_ex1.py
4,513
4.75
5
# 1. open file # 2. write something to file --> data are put in buffer # 3. close the file --> force data to be written to the file ### BE CAREFULE, don't open your program file with a write mode ### ### The content in your program file will be empty ### # There are several ways to open, write, and close ##########...
74bbc031e83a18db2ed79128f34173b70555089b
gabriellaec/desoft-analise-exercicios
/backup/user_288/ch37_2020_04_08_12_04_51_743382.py
166
3.515625
4
senha = 'desisto' pergunta = input('Escolha uma palavra: ') while pergunta != senha: pergunta = input('Escolha uma palavra: ') print ('você acertou a senha!')
8d403a5d079981bbc9f1c2499c8b2e1549cf908b
skJack/MachineLearningByLihang
/Chapter2/Perception.py
2,070
3.53125
4
#!/usr/bin/python import numpy as np import random import matplotlib.pyplot as plt class Perception: def __init__(self,max_iter = 10,learning_rate = 1,x_sample = None,y_label = None): self.max_iter = max_iter self.learning_rate = learning_rate self.w = 0 self.b = 0 self.w_list = [] self.b_list = []#存储所有的迭代...
c8f5a59148832b12a56f3008b75f256e4ceaf523
kirihar2/coding-competition
/find_parallel.py
1,559
3.96875
4
##Method 1: Create all rectangles and filter out ones that are not parallel to x ##Method 2: Find all lines parallel to x, then try to find the lines that have the same start and end x values ##Method 3: Find all y values with the same x. Like a bucket for each x value and their counts. set of 2 lines that have same ...
04c99b844556b05ebeabfe3b85e4817c21513531
dev1ender/learn
/largest-number.py
480
3.9375
4
from functools import cmp_to_key def compare(a,b): ab = str(a)+str(b) ba= str(b)+str(a) if ab < ba: return 1 elif ab > ba: return -1 else: return 0 letter_cmp_key = cmp_to_key(compare) def largestNumber(A): A = sorted(A, key=letter_cmp_ke...
40111d0d138bf968252e6dcd0a72b3dfdb714a8c
AlexanderRagnarsson/M
/Assignments/Assignment 9/Contentoffileinoneline.py
134
3.59375
4
read_file = open("test.txt") for line in read_file: for word in line: print(word.strip(), end=('')) read_file.close()
6c97e6cae5c0bcc93a4dfc1cbae514fa5e0f76ec
tulsishankarreddy/repository_training
/python_program/day2/seq.py
801
4.25
4
List = [10, 20, 30] #print with List value using negative indexes if(0): num = -len(List) for i in range(-1,num-1,-1): print(List[i]) #check we can change the or not tuple with in list List1 = [10,20,(40,50)] if(0): print(List1[0]) print(List1[1]) print(List1[2]) print(List1[2][0]) print(List1[2][1]) List...
f3085db08bdcd025393c3930cb820b70f92f80bf
stupidchen/leetcode
/src/leetcode/P5367.py
446
3.59375
4
class Solution: def longestPrefix(self, s: str) -> str: n = len(s) for i in range(1, n): if s[:n - i] == s[i:]: return s[i:] return '' if __name__ == '__main__': print(Solution().longestPrefix("aa")) print(Solution().longestPrefix("level")) print(Sol...
2784d54055d41c4bf29d05bebd22d48c76f715fb
vianneylotoy/TriRandom
/interval.py
373
3.53125
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- from random import randint,randrange class Intervalle: #Attribute of instances of the class def __init__(self): self.st = 0 # st: start time of the interval, self.et = 0 # et: end time of the interval self.Φ = 0 # Φ(t): Amount of energy in inte...
d645512387078f598f13e8bb1d6f849972378f41
bgayathri/Learning-Python
/Python_programs/functions.py
261
3.703125
4
def computepay(h,r): if h > 40: gross_pay = r * 40 + ((r * 1.5) * (h - 40)) else: gross_pay = h * r return gross_pay hrs = raw_input("Enter Hours:") h = float(hrs) rph = raw_input("Enter Rate:") r = float(rph) p = computepay(h,r) print p
6d3ee23c37b5bfc9c267eefefe1a75a872df55a9
aaaaatoz/handdytools
/portchecker.py
852
3.921875
4
#!/usr/bin/python import socket def checkport(host,port): ''' this function tested if the host+port is avaiable input: host: host port: tcp port output: none. the boolean result successful or not ''' result = False try: sock = socket.crea...
9d0fc3aa90abcc5713a49a2fa7143430fe11748b
Yara7L/python_learn
/basic_2.py
283
3.875
4
import numpy as np # shape的使用 def shape(): a = np.array([1, 2, 3, 4]) print(a.shape) print(a) b=a.reshape((2,2)) print(b) print(b.shape) c=a.reshape((1,-1)) print(c) print(c.shape) d=a.reshape((-1,1)) print(d) print(d.shape)
13613d9fa55d90f18555db6b817561ea35636795
iPROGRAMMER007/Beginner
/AveOfFiveNum.py
279
3.9375
4
n1=float(input('Enter first number: ')) n2=float(input('Enter second number: ')) n3=float(input('Enter third number: ')) n4=float(input('Enter forth number: ')) n5=float(input('Enter fifth number: ')) ave=(n1+n2+n3+n4+n5)/5 print('Average of five numbers =',ave )
82929fc3ae5c9c3c77c4cd9192af5d6435baf8f0
liuzhipeng17/python-common
/python基础/第三方模块/time时间模块/各种表示时间的相互转换.py
1,041
3.65625
4
# -*- coding: utf-8 -*- import time import calendar # 时间戳---UTC struct time time.gmtime(时间戳) print(time.gmtime(0)) print(time.gmtime()) #是在UTC时区,tm_hour可以看出相差8小时,中国的快了8小时 # 时间戳---Local struct time time.localtime(时间戳) print(time.localtime()) # 宿主计算机所在地的时区 print(time.localtime(0)) #UTC struct time ---时间戳 calendar...
4ba3b59b00823d6cb170d2dd1ae18016b49a17d1
2020668/python2019
/hm_04_面向对象特性/hm_14_练习.py
324
3.5625
4
# -*- coding: utf-8 -*- """ ================================= @author: keen Created on: 2019/4/25 E-mail:keen2020@outlook.com ================================= """ import random class Base(object): p = random.randint(1, 10) class My(Base): pass class Pc(Base): pass my = My() pc = Pc() print(m...
8bb344287030e6594067fbd66cca6adb0814cd81
VanessaSergeon/Python---Treehouse-Challenges
/most_classes.py
620
3.96875
4
# The dictionary will be something like: # {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'], # 'Kenneth Love': ['Python Basics', 'Python Collections']} # # Often, it's a good idea to hold onto a max_count variable. # Update it when you find a teacher with more classes than # the c...