blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
18f6de56fc61ce088b3a8bcbeb4eae9266bcc013
anantbarthwal/pythonCodes
/lecture2/bubbleSort.py
260
3.9375
4
list1 = [10, 8, 12, 2] length = len(list1) print("list1 = ", list1) for i in range(length-1): for j in range(length - i - 1): if list1[j] > list1[j+1]: list1[j], list1[j+1] = list1[j+1], list1[j] print("list after sorting= ", list1)
edf71f8f296c4e8a6748445bef1d3b14c5b36e85
rakeshsukla53/interview-preparation
/Rakesh/python-iterators/groupby_clause.py
364
3.78125
4
from itertools import groupby class Solution(object): def groupStrings(self, strings): """ :type strings: List[str] :rtype: List[List[str]] """ result = [] for k, g in groupby(strings, key=len): result.append(sorted(list(g))) return result print...
d265372b8b5d3a294bcfd0eb292ceea82f131516
qsunny/python
/coding-200/chapter11/thread_queue.py
1,919
3.578125
4
#线程间通信 import time import threading from chapter11 import variables from threading import Condition #1. 生产者当生产10个url以后就就等待,保证detail_url_list中最多只有十个url #2. 当url_list为空的时候,消费者就暂停 def get_detail_html(lock): #爬取文章详情页 detail_url_list = variables.detail_url_list while True: if len(variables.detail_ur...
bd35e4b9008cdc438ce338c3b7861ced84d559d9
Sasikumar-P/Python_revision-
/Directory.py
1,423
4.1875
4
print "*****TELEPHONE DIRECTORY*****" list1 = [] list2 = [] dict1 = {} temp = 100 n = input("enter the number of contacts :") for i in range(0,n): name1 = raw_input("Enter your name :") num1 = input("Enter your phonenumber") list1.extend([name1]) list2.extend([num1]) dict1 = dict(zip(list1,list2)) #to convert tw...
4ab51bf7845a4eb3e88974e119848c83156b4299
karangale/Airbnb_price_prediction
/airbnb_price_prediction/markers.py
1,478
3.5625
4
"""Markers for airbnb and restaurant locations.""" def airbnb_popup_frame(each): """ Create airbnb listing marker details. Args: param (tuple): This input is each row of the dataframe Returns: str: String with HTML format listing information """ picture_url = each['picture_u...
daa95e1d0332847f4d8352cd704faa809e55ab8a
abhaj2/Phyton
/sample programs_cycle_1_phyton/17.py
124
4.0625
4
#To count the number of digits in an integer c=0 x=int(input("Enter the digit")) while x!=0: x=x//10 c=c+1 print(c)
47d92a4cf671dff8897bf52b0a2325f0647eaf11
jinurajan/Datastructures
/crack-the-coding-interview/stacks_and_queues/queue_using_two_stacks.py
1,171
4
4
class Stack(object): def __init__(self): self.stack = [] def push(self, data): self.stack.append(data) def pop(self): return self.stack.pop() def peek(self): return self.stack[-1] def isempty(self): return True if not self.stack else False class QueueUsi...
933ac2242e32bbd3fe95e0a69e11fa0088ad794e
Akshidhlavanya/san
/p32.py
133
3.734375
4
x,y=map(int,input("Enter two value").split(' ')) a=map(int,input("Enter values").split(' ')) if y in a:print("yes") else:print("no")
e6ee702cd0d91f42da50f8ec0288ac1ca6ecacab
warrenzhoujing/sirbot
/rook.py
1,507
3.8125
4
#!/usr/bin/env python3 import logging from position import Position from constants import Color logging.basicConfig(level=logging.DEBUG) class Rook: def __init__(self, color=Color.WHITE.value, col=1): if col != 1 and col != 8: raise AssertionError self._color = color row = 1...
67e849d52323534b3e507e5d2bf87ce31fc65db4
SirajKarim/Python-Crash-Course
/tempCodeRunnerFile.py
151
3.546875
4
active = True while active: message = input("Enter Something \n") if message == 'quit': active = False else: print(message)
f5a1d5411fa95763b3165c9ea274dacfbd923d8b
Jongveloper/hanghae99_algorithm_class
/algorithm_practice/1157.py
867
3.9375
4
# 알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성 단, 대문자와 소문자 구분 x # 입력 : 첫째 줄에 알파벳 대소문자로 이루어진 단어가 주어짐 # 출력 : 첫째 줄에 이 단어에서 가장 많이 사용된 알파벳을 대문자로 출력 단, 가장 많이 사용된 알파벳이 여러개 존재하는경우 ?를 출력 # 문제 접근 방식 : 대소문자 구분을 하지 않기 위해 모두 대문자로 변환 words = input().upper() set_words = list(set(words)) max_word_cnt = [] for word...
6b8061f5ca3c69aa11860b16f47ed6458b5f3e27
srp2210/PythonBasic
/dp_w3resource_solutions/regular-expression/22_ find_occurrence_and_position_of_substrings_within_string.py
452
3.828125
4
""" * @author: Divyesh Patel * @email: pateldivyesh009@gmail.com * @date: 23/05/20 * @decription: the occurrence and position of the substrings within a string """ # Related Article can be found here: https://docs.python.org/3.7/howto/regex.html import re text = 'hello world this is divyesh patel, how beautiful th...
e3026fc9ce23f25604e6706b73078490c15d280a
lceric/study-workspace
/Python/study/study-function.py
9,402
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 第一行注释是为了告诉Linux/OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释; # 第二行注释是为了告诉Python解释器,按照UTF-8编码读取源代码,否则,你在源代码中写的中文输出可能会有乱码。 # 使用def语句声明函数 # *args是可变参数,args接收的是一个tuple; # **kw是关键字参数,kw接收的是一个dict。 # 写一个abs函数 def my_abs(num): if not isinstance(num, (int, float)): raise TypeE...
e693accf8d77053c220e9e1ec17add0b2b8c41b7
ravduggal/Python
/ProgramFlow/guessinggame.py
1,445
4.1875
4
answer = 5 print("Please guess number between 1 and 10: ") guess = int(input()) if guess<answer: print("Please guess higher") elif guess>answer: print("Please guess lower") else: print("You got it first time right") if guess<answer: print("Please guess higher") guess=int(input()) ...
1b2316d1a7eb4534090ebb11f8191e0776408a07
carefulcoder/PythonExercises
/Tuples.py
191
3.765625
4
# numbers = (1, 2, 3) # numbers[0] = 10 # print(numbers[0]) # unpacking coordinates = (1, 2, 3) # x = coordinates[0] # y = coordinates[1] # z = coordinates[2] x, y, z = coordinates print(y)
da32e6249ab6bd2ece18bc60f4fa18046592f420
Ferkze/fatec_python
/aulas/aula7/media_digitos.py
295
3.71875
4
def media_digitos(n): 'Media dos dígitos de um número inteiro' def soma_digitos(n): nums_str = str(n) if len(nums_str) == 1: return int(n) else: return int(nums_str[0]) + soma_digitos(nums_str[1:]) return soma_digitos(n) / len(str(n)) print(media_digitos(1234))
dadd8bb247908155ed27b2098831bda3d58fe018
minwinmin/Atcoder
/ABC153/DP.py
2,194
3.84375
4
""" ここのロジック通りにプログラムを組んでいく。 https://qiita.com/drken/items/a5e6fe22863b7992efdb#%E5%95%8F%E9%A1%8C-2%E3%83%8A%E3%83%83%E3%83%97%E3%82%B5%E3%83%83%E3%82%AF%E5%95%8F%E9%A1%8C http://wakabame.hatenablog.com/entry/2017/09/10/211428 """ """ 最大和問題 N要素を持つ数列 a[0],a[1],⋯,a[N−1] から任意の個数の項を選んで和を取った時の最大値 """ N = int(input()) a = l...
3d4161d4ca9150761be7564fd4732a632a2324f7
weizhengda/Python3
/code/11.第十一章/5.枚举的注意事项/code.py
217
3.5625
4
from enum import Enum class VIP(Enum): YELLOW = 1 GREEN = 2 BLACK = 3 RED = 4 # 别名 class Common(): YELLOW = 1 for v in VIP: print(v) for v in VIP._menbers_: print(v)
22bea87dd0d96cf13c7c7a445da304dc03d5a7be
KellyKokka/Python-snakify-exercises
/question4.py
1,193
4.21875
4
def shortest_continuous_segment(s): '''implement the function''' i = s[0] n = 0 while n<len(s): if s[n] != i: break n += 1 #after execution of the above, i will be the number forming the first continuous segment #and n will be the length of the first continuous se...
540e06892960523cb6fe31e6d74e11df96fb8cd2
MatejGladis/DiscordBot
/Roll.py
4,093
3.765625
4
# Created by Matko import random # Function IsValid checks if the entered input is number def IsValid(Expression): try: int(Expression) return True except: return False # Function AddSpaces isolate numbers and characters form each other def AddSpaces(Expression): #plus checker ...
aa4893929f9d990243444fc4416637e7eeb6149d
SulyunLee/NFL_team_embedding
/src/generate_coach_features.py
8,510
3.5625
4
''' This script generates feature vectors for each coach in each season. ''' import pandas as pd import numpy as np import argparse from POSITION_ASSIGNMENT import * from tqdm import tqdm def total_years_NFL_feature(row, df): name = row.Name year = row.Year # extract the coach'es previous year seasons...
e96bdd44689ad5fa16340db1c7862568067bc50c
cyberchaud/cracking_wPython
/p_questions/chap01/c01q02.py
1,978
3.578125
4
# Cracking Codes with Python # Chapter 01 # Practice Set 01 # Rot(x) challenges import logging import sys import getopt logging.basicConfig(filename='chap01ques02.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') logging.debug('Start of question') def main(argv): cText = '' cRot...
3c7bd1ff86bee9bbe2e3e7a74a8dbb733de10cf4
chinkushah/PyAcademy
/PyAcacdemy.py
38,491
4.15625
4
import math print("Welcome to Py Academy") for ch in range(1,100): what_subject = input("What subject may I help you with today?(Math/Physics/Chemistry) ") if what_subject == "math" or what_subject == "Math" or what_subject == "mathematics" or what_subject == "Mathematics": what_chap = input(...
fc44fe6794164926a2bc428e5fde1725ac1463f1
karthikjosyula/GrokkingAlgorithms
/GrokkingAlgorithms/BreadthFirstSearch.py
1,157
3.609375
4
#Hash table to store the friends of 1st connection friends and friends of second connection friends and so on... friendshash = {} friendshash['karthik'] = ['nani','shravan','rafi','phani'] friendshash['nani'] = ['kishore','kranthi','jaideep','joe','videesh'] friendshash['shravan'] = [] friendshash['rafi'] = ['kishore',...
ecfd202a86c64669565f43c3b6cfb7302ef567db
neha-sharmaa/python-practice
/celcius_farh.py
143
3.671875
4
def temprature(frah): return (frah * (5/9)) -32 temp = temprature(100) print(str(temp)) print('hi', end=" ") print('hello', end=" ")
482bb73b3b666c1a659db534c46bec792027039f
loveclj/DesignPatterns
/python/factory.py
1,537
3.765625
4
__author__ = 'lizhifeng' class Pizza: def cook(self): pass def cut(self): pass def get(self): pass class CherryPizza(Pizza): def cook(self): print "cook cherry pizza" def cut(self): print "cut cherry pizza" def get(self): self.cook() ...
c233acbdce355b5fbcc49ab93bdc3d07ad1268f7
GerbendH/Advent_of_Code_2020
/Day 2/main.py
1,699
3.59375
4
class Password: def __init__(self, pw): self.pw_split = pw.split(' ') self.pw_string = '' self.policy_min = 0 self.policy_max = 0 self.policy_key = '' self.get_data() def get_data(self): policy_min_max = self.pw_split[0].split('-') self.policy_m...
ebe884b4a19212d3e4c59e636c2601f063c98f54
armaan2k/Training-Exercises
/DataStructuresAndAlgorithms/Queues/QueueLinkedList.py
1,155
3.734375
4
class _Node: __slots__ = '_element','_next' def __init__(self,element,next): self._element = element self._next = next class QueueLinkedList: def __init__(self): self._front = None self._rear = None self._size = 0 def __len__(self): return self._size ...
531830eeb79bee0822b719d6dddf718f0e879764
uma-c/CodingProblemSolving
/back_tracking/target_sum_symbols.py
2,839
4.28125
4
''' You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. Find out how many ways to assign symbols to make sum of integers equal to target S. Example 1: Input: nums is [1, 1, 1, 1, 1], S...
88c34a41a599feeb42db383d361d37bbb2b56014
bhav09/rock_paper_scissor
/rockpaperscissor.py
1,238
4.0625
4
# game of rock paper scissor import random choice=['rock','scissor','paper'] def game(): game_is_still_going=True while game_is_still_going==True: player_input=input('Your turn:') pc=random.choice(choice) if pc==player_input: print('Tie') ...
3a14d4a60be3ebdd499c1dab766ce95120046c6e
Amnesia-f/Code-base
/Python/if-else和if-elif-else.py
481
3.875
4
import random computer = random.randint(0, 2) player = int(input("请输入【石头(0)、剪刀(1)、布(2)】:")) if 0 <= player <= 2: if (((player == 0) and (computer == 1)) or ((player == 1) and (computer == 2)) or ((player == 2) and (computer == 0))): print("玩家获胜,恭喜!") elif player == computer: ...
2e91518aff395e6fad10c5148b4692b045134cd3
lukassn/CodeQuests
/URI/inPython/seis_numeros_impares.py
108
3.578125
4
#coding: utf-8 x = int(input()) sai = 0 while sai < 6: if x % 2 != 0: sai += 1 print(x) x += 1
5da6e6bdcf0bc645eb5fec6e858013dd660cbb2d
NiuNiu-jupiter/Leetcode
/472. Concatenated Words.py
1,854
4.25
4
""" Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array. Example: Input: ["cat","cats","catsdogc...
2e51398ada73bde04ac2bd924d140a810278ee65
SimeonTsvetanov/Coding-Lessons
/SoftUni Lessons/Python Development/Python Fundamentals September 2019/Problems And Files/19 EXERCISE OBJECTS AND CLASSES - Дата 25-ти октомври, 1430 - 1730/05. Class.py
2,085
3.984375
4
""" Objects and Classes - Exericse Check your code: https://judge.softuni.bg/Contests/Practice/Index/1734#4 SUPyF2 Objects/Classes-Exericse - 05. Class Problem: Create a class Class. The __init__ method should receive the name of the class. It should also have 2 lists (students and grades). Create a class att...
b1189ab6bf4fdfdeb621c00ed24e1dde09928837
Curtis26/techport
/Python/Assgs/The A-Team.py
2,154
4.21875
4
""" Assignment 4 Program 1 The A-Team Write a program to read the text from a provided text file into a list, display the text on-screen, make some alterations to the text and outputs the changed text to the screen, then save the altered text as a new file. Name..: Yu Wang, Student ID....: W0421944 """ """ Pseudoco...
d1a6eba14da57f8edc9bee8a08284ca91bedf026
mariadaan/Programmeren1_2
/Week 6/adventure/item.py
456
3.875
4
class Item(object): """ Representation of an item in Adventure """ def __init__(self, name, description, initial_room_id): """ Initialize an Item give it a name, description and initial location """ self.name = name self.description = description ...
0a090e12578bc30731db9f744d3d4b389e975259
dtingg/Fall2018-PY210A
/students/DrewSmith/session06/close_far.py
442
3.8125
4
#!/usr/bin/env python """ Given three ints, a b c, return True if one of b or c is "close" (differing from a by at most 1), while the other is "far", differing from both other values by 2 or more. Note: abs(num) computes the absolute value of a number. """ def close_far(a, b, c): if abs(b - c) < 2: ret...
128b748aabccbe65c84516401e792b27672799ed
LuisTavaresJr/cursoemvideo
/ex58.py
632
3.8125
4
from random import randint from time import sleep tenta = 0 print('VOU PENSAR EM UM NÚMERO ENTRE 0 E 10 ! TENTE ADIVINHAR') computador = randint(0, 10) acertou = False while not acertou: tenta += 1 jogador = int(input('Qual seu palpite: ')) print('PROCESSANDO...') sleep(1) if jogador == computador: ...
1995f8607d414db87c40ead6316b774e976e8784
vuthysreang/python_bootcamp
/Documents/week02/sreangvuthy17/week02/ex/34_current_date.py
1,009
4.53125
5
""" Description : You will write a function that return the current date with the following format: YYYY-MM-DD. The return value must be a string. Requirements : ● Program must be named : 34_current_date.py and saved into week02/ex folder Hint : ❖ function ❖ datetime Output : ...
dcea147faf481ff1684a8e3ef45ffe037669acdb
microease/runoob-python-100-examples
/OK/015ok.py
351
3.890625
4
# 题目:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。 source = int(input("请输入您的分数:")) if source >= 90: grade = 'A' elif source >= 60 and source < 90: grade = 'B' else: grade = 'C' print("%d 属于 %s" % (source, grade))
15724b841e808e8c7c232d9bf9954d060c64d772
Maciel-Dev/ExerciciosProg2
/Exercicio5.py
304
3.71875
4
def main(): listaTeste = [1,3,4,534,62344,8534,25783902,1,613721,8,10,12] maiorNum = 0 #Função for i in listaTeste: if i > maiorNum: maiorNum = i print(maiorNum) #Utilizando Max print(max(listaTeste)) if __name__ == "__main__": main()
f1566cfc6a474eb3a8f459a5e71c9ad5197c14fd
Shreets/Python-basics-III
/search&sort/insertion_sort.py
237
3.859375
4
array = [7,2,4,1,5,3] array_length = len(array) for i in range(array_length): value = array[i] index = i while i > 0 and array[i - 1] > value: array[i] = array[i-1] i = i-1 array[i] = value print(array)
aae9a1a63e883d421e3dbe3f7e6be1c869fe5e02
Yangidan/LeetCode50
/1line.py
1,078
3.625
4
""" Fractal """ # print('\n'.join([''.join(['*'if abs((lambda a: lambda z, c, n: a(a, z, c, n))(lambda s, z, c, n: z if n == 0 else s(s, z*z+c, c, n-1))(0, 0.02*x+0.05j*y, 40)) < 2 else ' ' for x in range(-80, 20)]) for y in range(-20, 20)])) """ Heart """ # print('\n'.join([''.join([('DanLove'[(x-y)%8]if((x*0.05)**2+...
3e77614cc277f17d6d2ae2d12fd2dd7431a8b000
Programacion-Algoritmos-18-2/2bim-clase-01-CarlosCastillo10
/ejercicio-clases/clase1-2bim/manejo-excepciones/principal.py
372
3.828125
4
""" Ejemplos de manejo de excepciones """ try: edad = int(input("Ingrese su edad por favor: ")) print("Su edad es: %d" %(edad)) except NameError as e: print("Existe un error %s" %e) except ValueError as e: print("Existe un error (%s) %s" %(e.__class__ ,e)) #except Exception as e: ...
a49116753888039f05929473b5110033e1ddbd24
Saloni399/Leetcode-Solutions
/sets_generators_collections.py
7,556
4.1875
4
# Sets: unorder collection with unique values def count_unique(s): """ Count the number of unique characters in s >>> count_unique('aabb') 2 >>> count_unique('abcdef') 6 """ seen_c = [] # O(1) for c in s: # O(n) if c not in seen_c: # AS list gets longer, lenth of seen_c get...
54aa8be84033d1cf349fccb8231bedaba73649b6
threebodyyouzi/python_exercise
/day05/text_yuanzu.py
279
3.59375
4
# #!/usr/local/bin/python3.6 mytuplke1=1,2,3 mytuplke2=1,3,["a","b"] print(mytuplke1) print(mytuplke2) mytuplke2[-1].append("c") print(mytuplke2) a=("hello") b=("hello",) print(len(a)) print(len(b)) # with open("text_dict.py.dos","rb") as f: # data=f.read() # print(data)
6ea21f4fe17bbf9b0676926cf726927e7932ebda
Thitsugaya1/python
/factorial.py
260
3.828125
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 22 19:29:28 2014 @author: Toshiron """ def factorial(n): f = 1 for i in range(1, n + 1): f *= i return f n = int(raw_input("n? ")) f = factorial(n) print f #GG para esto :P
0991d549ad38eef0a4870ded942afbfab53f355f
liu666197/data1
/8.10/13 字典的方法.py
918
3.65625
4
a = { 'name': '小明', 'age': 13, 'height': 150, 'weight': 300, 'like': '篮球' } print(a) # 根据key删除 # a.pop('like') # 复制字典 b = a.copy() # 清空字典 # a.clear() # 给某个key设置一个默认值: a['aaa'] = 'bbb' # a.setdefault('aaa','bbb') # a['aaa'] = 'ccc' # 默认删除最后一项(键值对) # a.popitem() # 类似于extend # 可以将新字典当中的键值对,直接加入到原字典里面 #...
7952bbc7a733b4a56411c862e8fe2b4699cb7108
amit-kr-debug/CP
/Geeks for geeks/array/First Repeating Element.py
1,489
3.875
4
""" Given an integer array. The task is to find the first repeating element in the array i.e., an element that occurs more than once and whose index of first occurrence is smallest. Input : The first line contains an integer T denoting the total number of test cases. In each test cases, First line is number of element...
87f49313038daba1051fb4099cc4a98b5026604f
wcsanders1/HackerRank
/EvenTree/Python/EventTree.py
1,605
3.71875
4
#!/bin/python3 class Node: value = 0 total_children = 0 children = [] def __init__(self, value): self.value = value self.children = [] self.total_children = 0 def get_or_create_node(value, nodes_map): if value not in nodes_map: new_node = Node(value) node...
39b39a2d225e9a31ea07ec6fdd523f7f88123918
asmaaelk/RaspberryPiBakeOff
/RPBO.py
954
3.609375
4
import pygame from Tkinter import * ''' class MainApp(): width, height = 640, 480 screen = pygame.display.set_mode((width,height)) MainApp() class MainApp(): app = Tk() app.title("Raspberry Pi Bake-Off") app.geometry('640x480') app.mainloop() def quitApp(): app.destroy() ...
f06bc0a8ea0aad44d48e5f112caa7c7bda3de981
ptrompeter/math-series
/src/series.py
1,095
4.03125
4
#_*_ coding: utf-8 _*_ def fib(num): """Return value of ath number in fib sequence.""" if num <= 0: return 0 elif num == 1: return 1 else: return fib(num - 1) + fib(num - 2) def lucas(num): """Return value of ath number in lucas sequence.""" if num <= 0: retur...
58ba6bdc1d375db884933057766ab1349de5aede
MohamedHajr/Problem-Solving
/leetCode/single_number.py
417
3.625
4
# class Solution: # def singleNumber(self, nums: 'List[int]') -> 'int': # hashset = set() # for num in nums: # if num in hashset: # hashset.remove(num) # else: # hashset.add(num) # return hashset.pop() from functools import reduce def ...
0822e4d596de1bb806f6409f783e296400d51123
kevin-d-mcewan/ClassExamples
/Chap8_StringsDeepLook/ReplacingSubstring.py
417
4.09375
4
'''Method REPLACE takes two substrings. It searches a string for the substring in its first argument and replaces EACH occurrence with the substring in its second argument. The method returns a new string containing the results''' values = '1\t2\t3\t4\t6' print(values) print(values.replace('\t', ',')) # REPLACING can...
19aa94fcc090e7e89be6e320c74798ea0a15431f
hywu1996/TCP_UDP_DateTime_App
/Client_TCP.py
874
3.953125
4
import socket #Take IP as input from user TCP_IP = input("Please enter the server's IP Address: ") #Take PORT as input from user, make sure it is castable to int or re-prompt while True: TCP_PORT = input("Please enter the port the server is listening at: ") try: TCP_PORT = int(TCP_PORT) break except ValueError...
521bd785819288401810a2cb4f6a8459705241a9
shaurtoonetwork/Data-Structures-Implemented-In-Python
/LinkedLists/LinkedList1.py
2,762
4
4
class Node: def __init__(self,data): self.data=data self.next=None class Linkedlist: def __init__(self): self.head=None def printlist(self): cur_node=self.head while cur_node: print(cur_node.data) cur_node=cur_node.next def append(self,d...
18dbd776ff100c2d0f4222fa3bee4dd0ba3783e8
naqveez/assignment2
/assignment2.py
501
3.546875
4
import random as r arr = [] for i in range(50): arr.append(r.randint(1,1000)) print(arr) exercise = arr[0] k = 0 for j in range(0, len(arr) ,1): if exercise > arr[j] : exercise = arr[j] k = j print("Min :", exercise, " index : ", k) for j in range(0, len(arr), 1): if exercise < arr[j]: ...
4dfafe3dc3b680d9ca736fc915fc71461f41c912
zhuyoujun/DSUP
/CountBagADT.py
1,437
3.734375
4
#------------------------------------------ #Book:Data Structures and Algorithms Using Python #Author:zhuyoujun #Date:20150129 #Chapter1: ADT # Programming Projects 1.3 #Counting Bag ADT #------------------------------------------ #Implements the Counting Bag ADT using ADT. class CountBag: def __init__(self): ...
e6e894c6d9bc8b37556ca5f0fa88a7ce87f9bc78
davidadeola/My_Hackerrank_Solutions
/python/mutate_str.py
173
3.671875
4
def mutate_string(string, position, character): arr = list(string) arr[position] = character return "".join(arr) print(mutate_string("Hellothere", 5, "w"))
d44fbb08a82ce10a63315113b274c0a9f989a0de
benniatli/hotel-search-engine
/lesaGogn.py
1,413
3.5
4
import sqlite3 as lite import sys import random files = open("hotelGogn.txt",'r') file_list = files.readlines() con = lite.connect('HotelSearch.db') con.text_factory = str stringList = file_list[1].split('"') with con: cur = con.cursor() cur.execute("DROP TABLE IF EXISTS Hotels") cur.execute("CREATE TABLE...
ab05f6d770729f38ffe543d48f2a49962c5ad91d
sharda2001/Loop_PYTHON
/multi.py
136
4.03125
4
num1=int(input("enter the num1= ")) num2=int(input("enter the num2= ")) i=1 count=0 while i<=num2: count=count+num1 i=i+1 print(count)
d355c7e8ab5300c03df417194230cd58aea51cf5
Kimmix/PythonDataSci
/Day4.py
272
3.53125
4
import pandas as pd df = pd.read_csv( "http://rcs.bu.edu/examples/python/data_analysis/Salaries.csv") df_sex = df.groupby(['sex']) # print(df_sex.mean()) print(df_sex.head()) # print(df[ df['salary'] > 120000]) # print(df[ df['salary'] > 120000]) # print(df.cumsum())
b42303781bb4be9a8fc92e75b524e943046fc438
asterix135/algorithm_design
/directed_graph.py
4,710
4.21875
4
"""Vertex and Graph Classes for a directed graph""" class Vertex: """ class to keep track of vertices in a graph and their associated edges """ def __init__(self, key): """ initialize vertex with id number and empty dictionary of edges """ self._id = key self._c...
9ccefe2963dd51991f0a990e1e85e932ce21ef98
gabriellaec/desoft-analise-exercicios
/backup/user_358/ch21_2020_09_30_12_06_32_392790.py
269
3.75
4
dias=int(input('digite o valor ') horas=int(input('digite o valor ') minutos=int(input('digite o valor ') segundos=int(input('digite o valor ') a=dias*86400 b=horas*3600 c=minutos*60 d=segundos total_segundos=(a+b+c+D) print(total_segundos)
c7a813a24a9a4ea16146066553911e10cc891d00
QiliWu/leetcode-and-Project-Euler
/Project Euler/046 - Goldbach's other conjecture.py
973
3.765625
4
# -*- coding: utf-8 -*- """ Goldbach's other conjecture Problem 46 It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×12 15 = 7 + 2×22 21 = 3 + 2×32 25 = 7 + 2×32 27 = 19 + 2×22 33 = 31 + 2×12 It turns out that the conjecture was f...
a9a191affbdbfbfcfd22098eec93762a7e39f6f7
dixieduke/pythonLearning
/readfile.py
297
3.859375
4
filename = 'file.txt' with open(filename) as f: content = f.readlines() print(content) infile = open(filename, 'r') data = infile.read() infile.close() print(data) with open(filename) as fp: for i, line in enumerate(fp): print(i) print(fp.readline())
cb170204cd22f741c15fb1ee40b3bf3717b5e0ca
xxd59366/python
/pycharmContent/else/testList.py
984
3.890625
4
# 使用位置参数 str01='{} is {}'.format('bob', 15) # str02='{1} is {0}'.format(15, 'bob') # 当str01与02值相同时,索引到0就停了,所以原本不会出现index is 1的输出 # 加上一个感叹号,index输出值出现变化 str02='{1} is {0}!'.format(15, 'bob') # 使用关键字参数 str03='name is {name},age is {age}'.format(name='bob',age=23) str04='姓名:{name} ,年龄:{age}'.format(**{'name': 'b...
5636309511c5a585c7018fe83cb0c608c25b531d
anilbhatt1/Deep_Learning_EVA4_Phase2_webapp
/src/gan.py
1,713
3.578125
4
import streamlit as st from io import BytesIO from src.utils import local_css import src.gan_process as gp def write(): """ Deep Learning Model to generate images of Indian car from random vector supplied """ local_css("style.css") st.markdown("<h1 style='text-align: center; color: black;font-size: 40px...
77bc55fb00daf192980300ec10137828baffb64b
NWood-Git/phase1_assessment
/ANSWER_4_5/app/person.py
268
3.625
4
class Person: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name def __repr__(self): return f"{self.last_name.title()}, {self.first_name.title()}" # x = Person("Jack","Ryan") # print(x)
95981e6865fa1c7d45442c6b26888a84fff3594b
parveza7/euler2
/4.py
763
3.796875
4
############################################################################### # Project Euler Problem 4 # Largest palindrome product # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the produ...
413f79aee492bfe3b71a3ece8cc11d7db352ad32
Rossel/Solve_250_Coding_Challenges
/chal130.py
183
3.734375
4
x = [list(range(5)), list(range(5,9)), list(range(1,10,3))] if sum(x[0]) > sum(x[2]): print("True!") elif max(x[1]) > max(x[2]): print("False!") else: print("None!")
ea188d8858a6b171f8b23bff2d2d244eb68f8edf
Varuzhan11/My_Python_Homeworks
/day_5_practice.py
3,359
3.921875
4
"""DATA STRUCTURES""" # 1. Write a program to find the sum of the even elements in the list. Use loops and not the sum() function! lst = [21, 56, 66, 45, 42, 14, 86, 12, 31, 69, 86, 38, 82, 25, 59, 17, 6, 63, 41, 67] x = len(lst) counter = 0 for i in range(x): if lst[i] % 2 == 0: counter += lst[i] print(...
77bb64c5c4347a95b54e08d90725c0ad8c1e04df
Jagadish2019/Python_Object_Class
/src/Practice/init.py
1,741
3.875
4
#Attributes and Methods ''' 1. What is an attribute? - An attribute is a property that further defines a class. 2. What is a method ? - A method is a function within a class which can access all the attributes of a class and perform a specific task. 3. What is a class attribute? - Class attributes are attributes that...
34313d20a4d9fc40a2d05ad41ca0c762c9ac1855
rishikeshpuri/Algorithms-and-Data-Structure
/searching/Find a local minima in an array.py
470
3.640625
4
def localMinima(A): left = 0 right =len(A)-1 n=len(A) while left<=right: mid = (left+ right)//2 if A[mid] == 0 or A[mid-1] > A[mid] and mid == n-1 or A[mid] < A[mid +1]: return mid elif A[mid] > 0 and A[mid] > A[mid-1]: right = mid-1 elif A[mid] ...
46438c638150ab2d6015afd1cf836afa705bcd38
vgomesdcc/UJ_TeoCompPYTHON
/p6.py
248
3.90625
4
print("Insira seu peso") peso = float(input()) print("Insira sua altura") altura = float(input()) imc = peso/(altura*altura) if imc>30: print("O usuario esta obeso") else: print("O usuario esta abaixo da linha da obesidade")
3ff646afc00fb5b0d715df3407af9693c690a6e0
JJURIZ/pymongo
/main.py
2,297
3.765625
4
from pymongo import MongoClient # import datetime so we can have timestamps on things we add to the database. import datetime # import pprint so we can pretty print objects from the database. import pprint # pymongo connects to the default host and port if you don't specify any # parameters to the constructor when i...
9341a6636cfae3ee89930dbb5c2b0c9ec7067ccf
f2k5/Practice-python-problems
/pp_02.py
329
4.4375
4
""" Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? """ x = int(input("Enter a number: ")) y = (x % 2) if y == 0: print("The number even!") else: print("The number is od...
4b904b611a8ef78ed1e435d777ae2de4f1146abe
Offliners/Python_Practice
/code/125.py
355
3.65625
4
# saving a data structure in a file # in JSON import json data = {"alpha" : [3,5,7], "beta" : [4,6,8]} with open("code/Data/data.json","w") as f: json.dump(data,f) # ... # using text format now with open("code/Data/data.json","r") as f: restored = json.load(f) print(restored) # Output: # {'alp...
b5669988818512182da01330cbfb1cb996d956a0
kaivantaylor/Code-Wars
/007_Accumulator/final.py
1,014
4
4
# Kaivan Taylor # Summary - This time no story, no theory. The examples below show you how to # write the function accum # Examples: # accum("abcd") -> "A-Bb-Ccc-Dddd" # accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" # accum("cwAt") -> "C-Ww-Aaa-Tttt" # The paramter of accum is a string which includs only let...
1ca6f13f70c157e948a4a254644d9b5bbf84708c
alchemz/Self-Driving-Car-Engineer-Nanodegree
/Lesson 5 Miniflow/Linear.py
351
3.640625
4
""" Linear Equations """ class Linear(Node): def __init___(self, inputs, weights, bias): Node.__init__(self, [inputs, weights, bias]) def forward(self): inputs = self.inbound_nodes[0].value weights = self.inbound_nodes[1].value bias = self.inbound_nodes[2].value self.value = bias for x, w in zip(inputs,...
5e9dd96d1af0b34d05c181afe7b7170aea60b021
RichardDev01/MazeRunner
/mazerunner_sim/utils/pathfinder.py
6,328
4.03125
4
"""Module containing some useful functions for pathfinding.""" from typing import Callable, Dict, List, Tuple from queue import PriorityQueue import numpy as np Coord = Tuple[int, int] DistanceFunc = Callable[[Coord], float] def manhattan_distance(p1: Coord, p2: Coord) -> int: """ Calculate the Manhattan d...
5becfc53c48bf6a6e532bf4c8029ff02c2eb2358
anthonyho007/leetcode
/InsertCycleSortedList.py
897
3.921875
4
""" # Definition for a Node. class Node(object): def __init__(self, val, next): self.val = val self.next = next """ class Solution(object): def insert(self, head, insertVal): """ :type head: Node :type insertVal: int :rtype: Node """ if head == Non...
3964d55ba7fd5a98fde81715fd309eeaabbfc814
mariaEduarda-codes/Python
/estruturas-repetitivas/problema_media_idades.py
646
4.28125
4
""" Faça um programa para ler um número indeterminado de dados, contendo cada um, a idade de um indivíduo. O último dado, que não entrará nos cálculos, contém um valor de idade negativa. Calcular e imprimir a idade média deste grupo de indivíduos. Se for entrado um valor negativo na primeira vez, mostrar a mensag...
f10a40bcb5df9d3cde21bfd98f6717b1c16b2862
tnzw/tnzw.github.io
/py3/def/list_sorted_insert.py
1,463
3.6875
4
# list_sorted_insert.py Version 1.0.0 # Copyright (c) 2021 Tristan Cavelier <t.cavelier@free.fr> # This program is free software. It comes without any warranty, to # the extent permitted by applicable law. You can redistribute it # and/or modify it under the terms of the Do What The Fuck You Want # To Public License, V...
25e21743f88233690cfa3d616ecf0e7c2e430c21
NessOffice/Sync_Code
/codeforces/round583_div2/D_data.py
223
3.796875
4
import random n = random.randint(3, 10) m = random.randint(3, 10) print(n, m) for i in range(n): ans = "" for j in range(m): grid = random.randint(0, 10) if(grid > 9): ans += "#" else: ans += "." print(ans)
13c169058651efac15f13158d1fd01781a035fd4
anirudhganwal06/pgn2bitboard
/pgn2bitboard/main.py
4,429
3.53125
4
#!/usr/bin/env python # coding: utf-8 import numpy as np import chess import chess.pgn import random def choosePositions(positions, moves, nExcludeStarting=5, nPositions=10): """ Returns positions that will be used in our model Inputs: positions: List of all chessboard positions of a game in...
04e74e90548ec2e2dcd64b6f58389718e1813f27
kurbanuglu/lab---pro
/Ders9-BozukParaOyunu-12.03.2019.py
794
3.5625
4
# Bozuk para olarak verilecek para üstünü en az para adedi ile geri döndüren fonksiyon def coin(n): coinlist=[1,5,10,21,50,100] b=[] c=[] a=n z=len(coinlist)-1 while(a!=0): for i in range(z,-1,-1): if(a>=coinlist[i]): while(a>=coinlist[i]): ...
ae8deb999791deb33e4d9a6b091562a71d0843c3
mbriseno98/cpsc-example-code
/python/MatchmakerLite-Part1/Matchmaker.py
686
3.734375
4
# Eric Pogue # Matchmaker Lite print("") print("Matchmaker 2021") print("") print("[[Your instructions here.") print("") UserResponse1 = int(input("Iowa Hawkeye football rocks!")) desiredResponse1 = 5 compatability1 = 5 - abs(UserResponse1 - desiredResponse1) print("Question 1 compatability: " + str(compatability1))...
d5c216f69fae5be89ad021f5b86bbb9e6edbdca3
jewells07/Python
/tell()&seek().py
307
3.921875
4
with open("File.txt")as f: #It will open and close file in this block: print(f.readline()) print(f.tell()) #f=file pointer tell use where it is f.seek(10) #f=file pointer we set at the point 10 print(f.tell()) print(f.readline())
ea63c231d870fdb24d7fdfcc992eea3081ff9672
boombelka/home_work_python
/hw01_normal.py
2,782
3.6875
4
 __author__ = 'Верещагин А.В.' print(' Задание 1') # Задача-1: Дано произвольное целое число, вывести самую большую цифру этого числа. # Например, дается x = 58375. # Нужно вывести максимальную цифру в данном числе, т.е. 8. # Подразумевается, что мы не знаем это число заранее. # Число приходит в виде целого беззнаково...
7f0e99de1d600213984e1f52f33e12210913d6fa
lixinxin2019/LaGou2Q
/homework001.py
269
3.6875
4
def func1(): print("这是没有参数、没有返回值的方法") def func2(a, b): print("这是有参数、有返回值的方法") c = a + b print(f"{a}+{b} = {c}") return c if __name__ == '__main__': print(func1()) print(func2(1, 2))
56b65b480d2eb5f95fc52939b6ce65a1ad04bf52
bensenberner/ctci
/dynamic_recursive/power_set.py
588
3.578125
4
from typing import Set def power_set(original_set): memo = dict() def _power_set(s: Set) -> Set: s_tuple = tuple(s) if s_tuple in memo: return memo[s_tuple] ps = set() # go through each sub element, add them in, then add the full thing for element in s: ...
a52835ac1a288d47ae7a4e28915433d13cbadab1
yanshengjia/algorithm
/leetcode/Array/1085. Sum of Digits in the Minimum Number.py
1,117
3.75
4
""" Given an array A of positive integers, let S be the sum of the digits of the minimal element of A. Return 0 if S is odd, otherwise return 1. Example 1: Input: [34,23,1,24,75,33,54,8] Output: 0 Explanation: The minimal element is 1, and the sum of those digits is S = 1 which is odd, so the answer is 0. Example 2:...
eedba6e7fe518c3b4451c0c6a6988a06f5725e65
pedroceciliocn/intro-a-prog-py-livro
/Cap_8_Funções/exe_8_6_prog_8_2_usando_for.py
381
4.0625
4
""" Exercício 8.6 Reescreva o Programa 8.2 de forma a utilizar for em vez de while. """ # Programa 8.2 - corrigido (genérico) e com for def soma(L): total = 0 for x in range(len(L)): total += L[x] return total L = [1, 7, 2, 9, 15] print(soma(L)) # deu certo print(soma([7, 9, 12, 3, 100, 20, 4])) # ...
dbd627ee70e987dc3e5f118b46cb0febab9ac812
NiuNiu-jupiter/Leetcode
/250. Count Univalue Subtrees.py
841
4.0625
4
""" Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of the subtree have the same value. Example : Input: root = [5,1,5,5,5,null,5] 5 / \ 1 5 / \ \ 5 5 5 Output: 4 """ # Definition for a binary tree nod...
10869fde785ca577222891ec5fe53c23c31e6d1c
CapsLockAF/python-lessons-2021
/HW7_Tupl-Sets-2/t5.py
781
3.65625
4
# Задано два символьних рядка із малих і великих латинських літер та цифр. # Розробити програму, яка будує і друкує в алфавітному порядку множину # літер, які є в обох масивах, і множини літер окремо першого # і другого масивів. lowSet = set(chr(lowers) for lowers in range(97, 123)) t = ("FXRFGKJHLUjsbfbjdfgdj26568749...
5873a56607c657cc9705723da582aca6b23ece85
Iliasben96/Theorie-project
/code/algorithms/astar.py
11,206
3.734375
4
import math from code.classes.grid import Grid from code.classes.priority_queue import PriorityQueue from code.heuristics.manhattan import manhattan_heuristic from code.classes.state import State from code.heuristics.neighbor_locker import NeighborLocker class Astar: counter = 0 def __init__(self): s...
0751320cf092c9717fe86dc3037e9d84bc61f77e
Talleth/PythonUseOfTkinter
/exercise.py
4,261
3.765625
4
#=================================================================== #    Purpose:   Demonstrate usage of a GUI #=================================================================== from tkinter import* form=Tk() form.title("Change Counter") form.geometry("315x350") # Button event def buttonPress(): # Quarte...
4acbd03222536321306cdce0d03541eaa611bda9
TheJambrose/Python-4-Everyone-exercises
/ch_09/ex_09_extra.py
788
3.796875
4
import string fname = input("Enter file name: ") if len(fname) < 1 : fname = 'clown.txt' hand = open(fname) di = dict() for line in hand : line = line.rstrip() # print(line) #remove formatting and punctuation line = line.translate(line.maketrans("","", string.punctuation)) line = line.lower...
4c94a448fbc534255604c96ce9522ad61102bb81
rfmurray/psyc6273
/03 - functions; strings/workshop3answers.py
3,033
4.5
4
# workshop3.py Lecture 3 workshop problems # Add code below the following comments, to solve the stated problems. # # Some problems will require tools from earlier lectures, such as lists and # loops. This will be the case in workshop problems from now on. # 1. Define a function randt(n, u, v) that returns an n-tup...