blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
aad0345f954dec917cd5c30683c2d03fb3ff8fb1
zlavvka/SQL_train_database
/Filling_SQL.py
2,839
3.5
4
import random import datetime # Preparation for random.date function d1 = datetime.datetime.strptime('1/1/2020 0:00:00 AM', '%m/%d/%Y %H:%M:%S %p') d2 = datetime.datetime.strptime('1/1/2021 0:00:00 PM', '%m/%d/%Y %H:%M:%S %p') # insert shop_chain function for i in range (1, 100): addGuest = "INSERT INTO ...
bf35144c5063e0e168c305b1e0bb4d82acd60b70
nnbenavides/Ted-Talk-Recommender
/recommend_talks.py
3,751
3.890625
4
# Imports import pandas as pd import numpy as np from sklearn.neighbors import NearestNeighbors as nn ''' Fits a k-nearest-neighbors model to identify the 10 most similar talks to the target. Arguments: data - pandas DataFrame of numeric values, each talk represented by a row target - list of feature values corre...
2e21d3454586f206e1837116bdf79349c69a36db
GLAU-TND/python-programming-assignment4-raunaqarora21
/suffix.py
133
3.59375
4
s=list(map(str,input().split(','))) l=[] sf='s' for i in s: if i.startswith(sf): l.append(i) print(l)
1e4c671483a911f6344751685c21ac1c9004cd8c
TareqMonwer/Intro2SoftwareDesign
/Example-3/dsutils/list_funcs.py
311
3.765625
4
""" LIST FUNCTIONS """ def get_max(list): mx = float("-inf") for n in list: if n > mx: mx = n return mx def get_min(list): mn = float("inf") for num in list: if num < mn: mn = num return mn def get_avg(list): return sum(list) / len(list)
7d274e364c88ce628d4c12a2cf2db20c17d161cb
Iker-Jimenez/2020_Advent_of_Code
/day10/puzzle2.py
1,059
3.84375
4
def count_paths(current_idx, current_adapter, adapters): num_paths = 0 if current_idx == len(adapters) - 1: num_paths += 1 else: if current_idx + 1 < len(adapters) and adapters[current_idx + 1] - current_adapter <= 3: num_paths += count_paths(current_idx + 1, adapters[current_i...
fc9216a67765a0a3d31829c730cf87072dbc57f1
Iker-Jimenez/2020_Advent_of_Code
/day10/puzzle1.py
704
3.734375
4
with open('adapters.txt', 'r') as adapters_file: adapters = [] for adapter in adapters_file: adapters.append(int(adapter)) adapters.sort() print(adapters) diff_of_1 = 0 diff_of_3 = 0 previous_adapter = 0 for adapter in adapters: voltage_diff = adapter - previous_adapte...
ca803d5954db9f1e3fbe96273e53458e67428424
nitishshar/Streamlit
/app.py
3,051
3.609375
4
import streamlit as st import pandas as pd import numpy as np import pydeck as pdk import plotly.express as px DATA_URL=("MotorData.csv") st.title("Motor Vehicle Collisions in NewYork City") st.markdown("### This application is a streamlit dashboard that can used to analyse motor vehicles collision in NYC") @st.cache...
613bb408b3b2fe0c74e607c0dafdf502df4683af
HujiAnni/Controlling-Program-Flow
/Project/func-bjack_score.py
2,323
4.375
4
""" Module for scoring blackjack hands. In blackjack, face cards are worth 10, number cards are worth their value, and Aces are worth either 1 or 11, whichever is more advantageous. The latter is what makes scoring blackjack so tricky. In this module, we assume that a card hand is represented by a tuple of strings, w...
1340446e0de2804790cb2bff88080d179912b9e8
tleahy1996/TSE003
/Interface.py
5,245
3.59375
4
#python chatwindow program #Import the library (This whole thing works on tkinker) from tkinter import * from tkinter import font from tkinter import ttk from datetime import datetime #from chat import get_response, bot_name #holdover from "insert name window", user_name = "You" BG = "#ffefd5" BGtext = "#ffffff" FGt...
028ec7e282438ec7d65619b96657b466ebb1547a
Karthik-bhogi/Infytq
/Part 1/Assignment Set 3/Question1.py
1,461
3.9375
4
''' Created on Apr 23, 2021 @author: Karthik ''' def find_leap_years(given_year): list_of_leap_years=[] # Write your logic here if(given_year%4==0): # list_of_leap_years= list_of_leap_years + [given_year] for new_year in range(0,61,4): new_leap_year = new_year+given_y...
49798f3942eb35c66e22f5c0157fd6d84d872ea5
Karthik-bhogi/Infytq
/Part 1/Assignment Set 3/Question4.py
813
4.15625
4
''' Created on Apr 23, 2021 @author: Karthik ''' def check_palindrome(word): #Remove pass and write your logic here length = len(word) letter_list = "" n = 0 while(length>n): letter_list = letter_list +" "+ word[n] n = n +1 letter_list = letter_list[1:] letter_...
02b219c29e9966944971f18230fd766ed119d511
Karthik-bhogi/Infytq
/Part 1/Assignment Set 2/Question1.py
471
4.25
4
''' Created on Apr 23, 2021 @author: Karthik ''' def find_product(num1,num2,num3): product=0 #write your logic here if (num1==7) : product = num2*num3 elif (num2==7): product =num3 elif(num3==7): product =-1 else: product = num1*num2*num3 ...
c4924dafb208561d315b6d49891e96b6ef66414d
PVolovik/Hell_Puzzle
/game.py
1,358
3.546875
4
from game_analys import * game = True while game: # 925607913 84 / 104 hi = 'y'#input("Сыграем? y/n ") if hi == "y": cur_numb = NewGame(428459790) # 51 / 62 gameList = cur_numb.gameList flag = True if list_int(gameList) != 123456789 else False while flag: vvod =...
e001d549d721863ee2c13b39b3575a97b73fb47e
jamesaduke/toy-problems-new
/codewars/python-problems/5-kyu/smallest_to_add.py
1,691
3.78125
4
# This is a demo task. # # Write a function: # # def solution(A) # # that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. # # For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. # # Given A = [1, 2, 3], the function should return 4. ...
2267ede6c941ea7c4a660db7ca63a71dca2a6ee4
jamesaduke/toy-problems-new
/hacker-rank/hackerrank-problem-solving-algorithms/kangaroo.py
309
3.859375
4
# Function description: https://www.hackerrank.com/challenges/kangaroo/problem # Complete the kangaroo function below. def kangaroo(x1, v1, x2, v2): for n in range(1000): if (x1 + v1) == (x2 + v2): print("YES") x1 += v1 x2 += v2 print("NO") kangaroo(0, 2, 5, 3)
671dd496f884472b7560988fb58e7bd4c73193ac
jamesaduke/toy-problems-new
/hacker-rank/hackerrank-problem-solving-algorithms/breaking_records.py
3,208
4.15625
4
# Maria plays college basketball and wants to go pro. Each season she maintains a record of her play. She tabulates # the number of times she breaks her season record for most points and least points in a game. Points scored in the # first game establish her record for the season, and she begins counting from there. # ...
41d9e763a42992deecc975c7055bcc39e21f3ae7
jamesaduke/toy-problems-new
/codewars/python-problems/median.py
443
3.796875
4
def median(lst): sorted_list = sorted(lst) if len(sorted_list) % 2 != 0: #odd number of elements index = len(sorted_list)//2 return sorted_list[index] elif len(sorted_list) % 2 == 0: #even no. of elements index_1 = len(sorted_list)/2 - 1 index_2 = len(sorted_...
02e1bbd5061a244378361af58a938452ea7211e4
HaydenRoeder1/LunarLanderClone-CS110-
/asteroid.py
525
3.609375
4
import pygame class Asteroid(pygame.sprite.Sprite): def __init__(self, position): super().__init__() self.position = position self.velocity = (-2,0) self.image = pygame.image.load("asteroid.png").convert() self.image.set_colorkey((0,0,0)) self.rect = self.image.get_rect() def update(self): #UPDATE FUNC...
7150d1ab0b1c0243da2f187e32d7713933c3c95b
ConcreteCS/Leetcode-Python-Solutions
/Problems/lc51_solveNQueens.py
2,134
3.828125
4
class Solution(object): def solveNQueens(self, n): """ The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any orde...
bc6c660572a49c25ab3f222216eb6b4af895ed95
ConcreteCS/Leetcode-Python-Solutions
/Problems/LC0002_addTwoNumbers.py
1,162
3.828125
4
# Time: O(n) # Space: O(1) # # You are given two linked lists representing two non-negative numbers. # The digits are stored in reverse order and each of their nodes contain a single digit. # Add the two numbers and return it as a linked list. # # Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) # Output: 7 -> 0 -> 8 class List...
795a3a01c190209b62c62282572b7153957a8c14
ConcreteCS/Leetcode-Python-Solutions
/Problems/lc581_findUnsortedSubarray.py
609
4
4
class Solution(object): def findUnsortedSubarray(self, nums): """ Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return the shortest such subarray and outpu...
f0a22e37a20f98fc4c1e65e6d39cd65c30dd90ab
StylishSdp/ProgrammingTask
/Task2/递归/爬楼梯.py
510
3.796875
4
def climbStairs(n): if n == 1: return 1 elif n == 2: return 2 else: return climbStairs(n - 1) + climbStairs(n - 2) print(climbStairs(35)) #空间换时间 #前n阶的次数 = 前n-1阶的次数 + 前n-2阶的次数 def climbStairs2(n): if n == 1: return 1 elif n == 2: return 2 temp = [None] ...
74e3786f000a3477029d5ea21b4d62902b43d21e
StylishSdp/ProgrammingTask
/Task5/堆/小顶堆、大顶堆、优先级队列.py
2,308
3.765625
4
#大顶堆 def Max_heap(nums): n = len(nums) last_node = n - 1 root = (last_node - 1) // 2 while root >= 0: heapify(nums, root, n - 1) root -= 1 return nums def heapify(nums, start, end): temp = nums[start] son = 2 * start + 1 while son <= end: if son < end and nums[...
63c408a678b51c53b6f01f71a3d824306e7203f4
StylishSdp/ProgrammingTask
/Task7/零钱兑换.py
408
3.515625
4
def coinChange(coins, amount): if not coins: return 0 dp = [float('inf')] * (amount + 1) dp[0] = 0 for i in range(1, amount + 1): for coin in coins: if coin <= i: dp[i] = min(dp[i - coin] + 1, dp[i]) dp[-1] = dp[-1] if dp[-1] != float('inf') else -1 ...
efe0b82582f6c66ef8a7072b4c23985deb5248d9
StylishSdp/ProgrammingTask
/Task1/List/创建动态数组.py
3,615
3.984375
4
# #实现动态扩容的数组 # class Array: ''' 数组初始化 length 数组占用内存大小 size 数组中元素个数 ''' def __init__(self, length = 10): self.__length = length self.__size = 0 self.__data = [None] * length def __getitem__(self, item): return self.__data[item] def __resize(self, length)...
64c5be0fd07387f6467dcf31b35d01c1eb41ff3c
ProgFuncionalReactivaoct19-feb20/clase06-mrnarvaez3
/ejercicio5.py
448
3.734375
4
""" Progroamacion funcional: Funciones puras Efectos secundarios """ import csv # def lineas(archivo): # return csv.reader(archivo, delimiter = ";") def lineasDiccionario(archivo): return csv.DictReader(archivo, delimiter = ";") with open("data/data-estudiantes.csv") as midata: lineas = lineasDiccionario(midata...
1e06ef88beb16a89782d0d5b53123353c42f1f5c
PetrosBompotis/ExamExercises
/Exercise9/Exercise9.py
1,634
3.671875
4
with open('file.txt','r') as file: s = file.read() '''***************************************************************************** Μετατροπή κάθε χαρακτήρα του κειμένου του αρχείου στον αντίστοιχο αριθμό ASCII *****************************************************************************''' a=[ord(c) for c in s] '...
5a44fb6ecf1a91a40b19dc4c752f2edce4ef48d4
shusingh/AI_Class_A0
/route_pichu.py
3,897
3.515625
4
#!/usr/local/bin/python3 # # route_pichu.py : a maze solver # # Submitted by : Neelan Scheumann - nscheuma # # Based on skeleton code provided in CSCI B551, Fall 2020. import sys import json # Parse the map from a given filename def parse_map(filename): with open(filename, "r") as f: return [...
0c5cfc4dd4ef5569201091cb911b55398453717c
hzontine/dsci_402
/Assignment 3/assignment3.py
1,549
3.515625
4
#Assignment 3 #Hannah Zontine from sentiment import * from twitter_util import * popcornwords= [] def fillStopwords(popcornwords): data = open("popcornwords.txt", 'rb').read().split("\r\n") for line in data: try: popcornwords.append(line) except: print("JSON-unopenable tweet encountered") return popcornw...
b4b2a0df36b3324dec0ccd0228c147afe1bfa7e5
HazemGabr232/tearobot
/bot/requests.py
547
3.578125
4
from urllib import parse from urllib import request class Requests: """Handles HTTP requests""" def get(self, url: str, params: dict = None, **kwargs): response = request.urlopen(url) encoded_params = parse.urlencode(params) full_url = url + encoded_params return response.read...
ecf5be17f18c8b84ac33014cc0df12daae0db347
ceramey1997/BlackJack
/Card.py
751
3.703125
4
class Card(object): def __init__(self, value, suit): self.value = value self.suit = suit self.isFace(self.value) def getValue(self): return self.value def getSuit(self): return self.suit def __str__(self): return "{} of {}'s".format(sel...
c6d66730f7b16f5d6441760b8be940dcd24425da
raviverman/Butterfly_Effect
/randomization.py
3,500
4.40625
4
# Illustration of butterfly effect in Chaos Theory # Situation # Alex has got letter of acceptance from a popular university. # He has 5 subjects from which he can do his major. He has a year # to decide his choice of subject. During that year, he meets # his parents and several friends with different interests. # Al...
9387a30db09764e44c9ce59394a64e503675d382
Diptikanta/Python
/PythonExercises/Ex3-CalculateCircleAreaFromRadius.py
324
4.5
4
#This exercise will ask the user to enter the radius so that it can calculate the area of the circle #This is the first exercise which deals with the user inputs. import math radius = float(input("Enter the radius of the circle: ")) area = math.pi * radius * radius print("Radius is ", radius) print("Area is ", ar...
5944ef3dbe9d8bb199a5467b93fb7f96add6cb14
raquelinevr/python
/Avaliaçoes/ATIVIDADE 8.py
1,571
4
4
Utilizando quaisquer dos comandos, funções e operadores vistos até a Semana 8, faça programas Python para resolver as questões abaixo. 1. Escreva um programa que leia um vetor contendo 100 elementos inteiros, calcule e exiba:  A quantidade de elementos pares;  A quantidade de elementos ímpares;  A soma de to...
cbd9afa1b11eee60bdaa88c7deee5f9197222f22
Sergey0381/repo_geekbrains
/Lesson_4.2.py
175
3.6875
4
# Task 2 from itertools import groupby my_list = [200, 2, 12, 73, 1, 1, 4, 10, 7, 1, 78, 123, 55, 2] my_list.sort() new_list = [i for i,_ in groupby(my_list)] print(new_list)
416101c66da962d2e7305e2afba5a15418465a3c
Vishesh-Sharma221/School-Projects
/count_vowel.py
452
4.28125
4
# WRITE A PROGRAM TO PASS STRING TO A FUNCTION AND COUNT HOW MANY VOWELS ARE THERE. s1 = input("Enter a string: ") # ----------- defining the function --------- def count_my_string(string): count = 0 vowels = ["a","e","i","o","u"] for char in s1: if char.lower() in vowels: count += 1 ...
799c4fa35a37a7ff1e4dfd3b033d831703f42b2f
JuanJoseMA2020/Calculadora_Integrales
/Area_bajo_la curva.py
581
4.15625
4
#Calculo de Area bajo la curva #%matplotlib inline import matplotlib.pyplot as plt import numpy as np import sympy as sy y1 = input("Ingrese la ecuacion: ") def f(x): return 4*x + 3*x**2 i = input('Ingrese el limite inferior: ') s = input('Ingrese el limite superior: ') x = np.linspace(int(i)-1, int(s)+1, 1000) ...
b1e1422cf5a8e1fdd5d73a09785bdee56d162253
teethefox/FooBar
/foobar.py
376
3.796875
4
def FooBar(): for target in range(100,100001): prime = True perfSqr = False for num in range(2,target+1): if target % num == 0 and num != target: prime = False if target // num == num: perfSqr = True if prime is True: print 'Foo' elif perfSqr is Tr...
63a286a5ac6bd8d909d8b833cfbc872ad73502da
tcptsai/Traveling-Salesman-Problem-Algorithms
/code/algNN.py
2,098
3.75
4
""" Nearest Neighbor Algorithm by CSE6140 fall 2016 Group F """ import time import sys def length(tour, D): """Calculate the length of a tour according to distance matrix 'D'.""" z = D[tour[-1]][tour[0]] # edge from last to first city of the tour for i in range(1,len(tour)): z += D[tour[i]][tou...
83d08d917449479bf874026f82f64b3bb513d2a6
MrBroma/PY4E-Exercises
/Chapter-4_Functions/Lesson-4_exercises.py
3,740
4.375
4
import random # Exercise 1: Run the program on your system and see what numbers you get. # Run the program more than once and see what numbers you get. # The random function is only one of many functions that handle random numbers. # The function randint takes the parameters low and high, and returns an integer betwee...
5e4dd0e595c9e3949cc06ad74faa095170e4f625
zfree47/Intellisense
/search.py
10,274
3.640625
4
""" COMP30024 Artificial Intelligence, Semester 1 2019 Solution to Project Part A: Searching Authors: Zachary Freeman, Kalanika Weerasinghe """ import sys import json from collections import defaultdict class Node(): """A node class for A* Pathfinding""" def __init__(self, parent=None, position=None): ...
33857b23f87a4588c19e2b94b5a85c95ec0c757b
jacob-w-bonner/Unit-6-08---Python
/math.py
308
4.125
4
number1 = int(input("Enter the first factor: ")) number2 = int(input ("Enter the second factor: ")) addFunction = 0 answer = 0 if addFunction < number2: while True: answer = answer + number1 addFunction = addFunction + 1 if addFunction == number2: break print ("The product is", answer)
8b90da37713afc74917e98660e84057ee2a09382
guti7/Tweet-Generator
/03_Frequency/word_frequency.py
3,338
4.28125
4
# Analyze Word Frequency in Text by creating a histogram. # Given a source body of text, can you perform the following?: # What is the least/most frequent word(s)? # How many different words are used? # What is the average(mean/median/mode) frequency of words in the text? import timeit import string start_time = time...
3dea2541840a071be219b4a02f53e5aabb66072b
lisnb/leetcode
/Reorder List.py
2,519
3.75
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param head, a ListNode # @return nothing def reorderList(self, head): if not head or not head.next or not head.next.next: return head ...
2974061ca3c9bf0b8b5ccea17a110af3b2cc440c
chasingw/leetcode
/_7_reverse_integer.py
236
3.765625
4
''' Given a 32-bit signed integer, reverse digits of an integer. 123 - 321 -123 -321 120 21 ''' class Solution: def reverse(self, x): """ :type x: int :rtype: int """ x_str = str(x)
b499beb8dfdb24c716051eca9007d8a4f4e77eb6
sevendollar/python
/turtle_walk_2.py
952
4.21875
4
import turtle def diamond_turtle(name, size): name.left(45) for color in ['red', 'purple', 'hotpink', 'blue']: name.color(color) name.forward(size) name.left(90) def square_turtle(name, size): for color in ['red', 'purple', 'hotpink', 'blue']: name.color(color) nam...
b5b9824af766ac47e1d4b0b017befff3859078a0
NeerajaLanka/100daysofcode
/100daysDay12_global_local.py
298
3.59375
4
#global and local variables friends = 1 is global variable and friends = 2 is local variable friends = 1 def family(): def increase_friends(): friends = 2 print(f"friends inside function{friends}") increase_friends() family() print(f"friends outside function{friends}")
ec6ec75707f77e7aa8cd70ddbac0bed05960a2a1
NeerajaLanka/100daysofcode
/Day18different_shapes_usingfunction.py
423
3.96875
4
from turtle import Turtle,Screen import random turtle_obj_1 = Turtle() colors =["olive green","peru","medium violet red","royal blue","red","orange","green","purple"] def shapes(sides): angle = 360/sides for _ in range(sides): turtle_obj_1.forward(100) turtle_obj_1.right(angle) for i in range(3,...
cf56e43ad22a2aa5a5c67b4aea79b38385850a32
NeerajaLanka/100daysofcode
/Day18random_color.py
614
3.921875
4
from turtle import Turtle,Screen import turtle as t import random turtle_obj_1 = t.Turtle() t.colormode(255) turtle_obj_1.pensize(5) def random_color(): r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) x = (r,g,b) return x random_color() b = 300 while b >=1: turtl...
1b4995cc9cd36869b7aec70dc35374392c2a8c4c
NeerajaLanka/100daysofcode
/100daysDay3-pizza.py
549
4.03125
4
pizza_size = str(input("which size of pizza do you want? : ")) print(pizza_size) ppizza =str(input("do you want ppizza? y or n :")) if pizza_size == "small": s_bill = 15 print(s_bill) if ppizza == "y": s_bill +=2 print("your pizza bill is : ",s_bill) elif pizza_size == "medium": m_bill = ...
87604eb94941a6790f9f7e14bc4eb493ddb1b69e
NeerajaLanka/100daysofcode
/100daysDay5evennumbersum.py
95
3.75
4
#even number addition sum = 0 for i in range(1,101): if i%2 ==0: sum +=i print(sum)
4c7300511b405bbaf2fe79c6825726017222c1b6
NeerajaLanka/100daysofcode
/Day20 snake/score_board1.py
646
3.828125
4
from turtle import Turtle class Scoreboard(Turtle): def __init__(self): super().__init__() self.penup() self.hideturtle() self.goto(0,270) self.color("white") self.score = 0 self.update_score() def update_score(self): self.write(f"score_board :{sel...
3597edb99c66a7b527dab953c2fc24a8e1d99c92
NeerajaLanka/100daysofcode
/100daysDay3-leapyear.py
808
4.40625
4
# Write a program that works out whether if a given year is a leap year. A normal year has 365 days, leap years have 366, with an extra day in February. The reason why we have leap years is really fascinating, this video does it more justice: # https://www.youtube.com/watch?v=xX96xng7sAE # This is how you work out wh...
8e105ed6efbc1f078d40011439a3d3c71c045aca
NeerajaLanka/100daysofcode
/100daysDay9.2.py
541
3.90625
4
#nested dictionary in adictionary #list-nested inside dictionary travel_log ={ "france":{"cities_visited":["paris","lille","dijon"],"total_visits":10}, "germany":{"cities_know":["berlin","hamburg","stuttg"],"total_places":15} } print(travel_log ) #nesting dictionary in a list travel_log =[ { "country...
be15058d90df752b9edc3ea4354f2403de4b7a10
NeerajaLanka/100daysofcode
/100daysDay3-3.py
302
4.0625
4
print("welcome to roller coaster") height =input("enter your height: ") if height > 120: age = input("enter your age: ") if age<12: print("pay 5$") elif age >=12 and age <=18: print("pay 7$") else: print("pay 12$") else: print("you are not eligible to ride")
677866eee7ca048ac59b8b031e2b0c6dc00b4145
NeerajaLanka/100daysofcode
/100daysDay7dummyrandomhangman.py
625
4.1875
4
#program to generate random word and guess that word. import random list_1 =["apple","banana","grapes","cherry","mango","kiwi"] chosen_word = random.choice(list_1) print(chosen_word) length_chosen = len(chosen_word) print(length_chosen) list_chosen = list(chosen_word ) display=[ ] for i in range(length_chosen): dis...
8cd3f196ffb81ed6adce03020689dcc0194c0012
NeerajaLanka/100daysofcode
/Day18spirograph_circle.py
576
3.84375
4
from turtle import Turtle,Screen import turtle as t import random turtle_obj_1 = t.Turtle() t.colormode(255) t.bgcolor("black") turtle_obj_1.shape("turtle") turtle_obj_1.speed(20) def random_color_cir(): r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) x = (r,g,b) ...
1b2befd30bdc41b3ab70959f23f67d5d3bebffa6
Stashy12399/Schoolwork
/watercylinderprobelt6pg19.py
2,254
4.15625
4
import random import math # needed modules dim_selection = int(input("1 for choosing the dimensions of the cylinder \n2 for random dimensions")) # allows the user to select whether they want to choose their own dimensions or just use a random value def option1(): cyl1_height = float(input("Enter the height of...
3c5e4cfc6b7ef2f54a6a379f8cb3293fead65c59
noobcoderr/DataStructures_Algorithm
/Two-way_Link_List.py
3,558
3.96875
4
class Node(object): def __init__(self,val): '''双向链表节点''' self.val = val self.pre = None self.next = None class Two_way_Link_List(object): """双向链表""" def __init__(self,node=None): self._head = node #开始实现双向链表的一些功能 #判断是否是空链表 def is_empty(self): ret...
d2cd620cb8e185a462f1fee0f312eb8799e136f0
rammps18/python
/milestone_csv/app.py
1,173
4.28125
4
from utils import database USER_CHOICE=""" 'a' to add book 'l' to list book 'r' to read book 'd' to delete book 'q' to quit Enter your choice: """ def menu(): USER_INPUT=input(USER_CHOICE) while USER_INPUT != 'q': if USER_INPUT == 'a': prompt_add_book() elif USER_INPUT == 'l': ...
465fa0f133dd99da093b897efee1f5edf3d6ca3f
rammps18/python
/dict_comprehension.py
541
3.5
4
# Dict comprehension friends = ["RAM","KUMAR","SURESH","DEEPAK"] time_since_seen = [3,5,7,9] long_timers = { friends[i]:time_since_seen[i] for i in range(len(friends)) if time_since_seen[i] > 5 } print(long_timers) # set comprehension guests = ["RAJ","KUMAR","RAM","VIKRAM"] friends_lower = {n...
66b0de07e4e62be67d7fdf1542af0a51a1bfa7d2
momentum-cohort-2018-10/w2d1-currency-converter-tiana-horn
/currency.py
586
4.0625
4
def convert(rates,value,current,to): rates = [("USD", "EUR", 0.74), (“USD”, “MXN”, 19.95), (“USD”, “CAD”, 1.31)] if current == to: return value for conversion in rates: if current == conversion[0] and to == conversion[1]: return value * conversion[2] raise ValueError(f"can't ...
99ea651e1056c6b7cf28b3674583a1f37ff8e517
Guga2/TiaP
/лаба 2/python 5.py
745
3.5625
4
s='ФИО;Возраст;Категория;_Иванов Иван Иванович;23 года;Студент 3 курса;_Петров Семен Игоревич;22 года;Студент 2 курса;_Иванов Семен Игоревич;22 года;Студент 2 курса;_Акибов Ярослав Наумович;23 года;Студент 3 курса;_Борков Станислав Максимович;21 год;Студент 1 курса;_Петров Семен Семенович;21 год;Студент 1 курса;_Романо...
68c5c810c2885efbfd5f6daa94844ac3041ce0f1
solomkinmv/algorithms
/src/algorithms/misc/remove_duplicates.py
1,094
4.09375
4
""" Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For example, given input array nums = [1, 1, 2]. Your function should return length = 2, with the ...
1f3562056e41a6731c0a941efb5e2693dc1656d7
solomkinmv/algorithms
/src/algorithms/misc/check_substr.py
521
3.828125
4
def check_substr(s, sub): print s, sub length = len(sub) for i in range(len(s)): if s[i: i + length] == sub: return i return -1 if __name__ == '__main__': print check_substr('abcdefg', 'abc') print check_substr('abcdefg', 'abcdefg') print check_substr('abcdefg', 'fg') ...
354de55934969ca776f5922109ed1b872759678f
solomkinmv/algorithms
/src/algorithms/sort/merge-sort.py
1,610
4.40625
4
def merge_sort(array, p, r): """ Recursively divide arrays on small parts and then merge them. :param array: original array :param p: left index bound :param r: right index bound """ # check if we can divide array on two parts if p < r: q = (p + r) / 2 merge_sort(array, ...
6e47d94adf3801afea8099c5cf645a20cbc1352b
solomkinmv/algorithms
/src/algorithms/sort/radix-sort.py
2,118
4.53125
5
def radix_sort(array, number_of_digits): """ Main function of radix sort. Function sorts numbers by digits from smaller to bigger. :param array: original array. :param number_of_digits: maximum number of digits in one number. :return: sorted array. """ for d in range(number_of_digits): ...
4e52a5fba4a5f382bef4ce8e4b80d685196aeeaf
soelves/portfolio
/IN1000/IN1000/Uke 1/beslutninger.py
174
3.828125
4
brus=input("Vil du ha en brus? ") if brus=="Ja": print("Her har du en brus!") elif brus=="Nei": print("Den er grei.") else: print("Det forstod jeg ikke helt.")
c036e39d0a3c3928225e6d3f11fa12315d95bebd
soelves/portfolio
/IN1000/IN1000/Uke 5/repetisjon1.py
655
3.765625
4
def slaaSammen(x,y): return x + y def skrivUt(liste): for i in range(len(liste)): print(liste[i]) def hovedprogram(): mineOrd = [] a = "i" while a != "s": a = input("i for input, u for utskrift, s for avslutt: ") if a == "i": streng1 = input("Skriv inn en tekst...
886053d4ac1b40681d3045c7554ad8a214a31a3a
yashwanthguguloth24/DataStructures
/Array/Stock_buy_and_sell.py
968
4.25
4
''' The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum. Example 1: Input: N = 7 A[] = {100,180,260,310,40,535,695} Output: (0 3) (4 6) Explanation: We can buy stock on day 0, and sell it on 3rd d...
87ca2621f6411bbd2dff4ab683e6a07851c4b6ad
yashwanthguguloth24/DataStructures
/Heap/Minheap.py
2,281
3.65625
4
# My min heap class class MyMinHeap: def __init__(self,l = []): # 0 based indexing self.arr = l if self.arr == []: self.size = 0 else: self.size = len(self.arr) i = (self.size-2)//2 while i >= 0: self.MinHeapify(self.size,i) ...
be64f7b3349691f80cabd4a4060580c056743d2d
yashwanthguguloth24/DataStructures
/Array/TrappingRainWater.py
744
3.90625
4
''' Given an array arr[] of N non-negative integers representing the height of blocks. If width of each block is 1, compute how much water can be trapped between the blocks during the rainy season. Example 1: Input: N = 6 arr[] = {3,0,0,2,0,4} Output: 10 ''' def trappingWater(arr,n): left_max = 0 right_ma...
f791b86401a80d89285777c3858d07ff6535a923
pshenglh/re_study_alg
/index_eq_value.py
556
3.890625
4
def equal_index(l, left, right): if (l[left] > left and l[right] > right) or (l[left] < left and l[right] <right): return -1 center = (left+right) / 2 if center == l[center]: return center elif center < l[center]: equal_index(l, left, center) else: equal_inde...
eb5badc180af0f1e2e2800f94affcefc687d35bc
pshenglh/re_study_alg
/Doubly_linked_list.py
2,071
3.796875
4
class DulNode(object): def __init__(self, value, pre=None, next=None): self.value = value self.pre = pre self.next = next def __repr__(self): return 'Node {}'.format(self.value) class DoublyLinkedList(object): def __init__(self): self.header = DulNode(N...
305915c445931d94de7856ac55c3eece4369d82c
diba-m/StubbornMining
/Task 1/Selfish-Miner-master/selfish-miner-engine_plots.py
5,807
3.59375
4
# -*- coding: utf-8 -*- """ Created on Thu May 12 09:25:36 2016 @author: Patrick Motylinski Simplistic Python simulation of the selfish miner strategy. Algorithm constructed in accordance with the strategy as outlined in the original paper by Eyal and Sirer (arXiv:1311.0243v5) """ import random import matplotlib.pyp...
4a422a7d2b07a359ca9f110aea09865423f1ac91
tonnefi/projetos-python
/entrevistador.py
1,157
3.53125
4
# Kenozos #nm é uma infomação que você vai responder e ficara salva no cumputador! nm = str(input('qual é seu nome?')) #idd é outra informação que sera salva. idd = int(input('qual é sua idade?')) #pt1 vai... bom,salvar uma infomação...
a7fb0c536ab3e916f1c28b58f57e06ffb9cf2afc
conversekuang/python_tips
/parameters.py
309
3.796875
4
#coding:utf-8 #当函数的参数不确定时 #*args 没有key值 list,tuple, etc. #**kwargs有key值 dict def main(*args,**kwargs): for arg in args: print arg for k, v in enumerate(kwargs): print k, v if __name__ == '__main__': args = [1,2,100,50,10] kwargs = {'dict':'name'} main(args,kwargs)
640e605eb5bce3765f2b8f58ccf5649721b00408
siddharthjain1611/Deep_Learning_Prerequisites
/matplotlib/histogram.py
518
3.96875
4
from scatterplot import * # discrized probability distribution of data / the frequency counts in each bucket of values # it show how many points in x fall into each bucket plt.hist(x) plt.show() # to see random distribution # create an array of 10 elements by default R = np.random.random(10000) plt.hist(R) plt.sh...
d27a757ef0a09aa9c0b0daa7a370953b4ed70efe
siddharthjain1611/Deep_Learning_Prerequisites
/pandas/column_names.py
385
3.828125
4
import pandas as pd df = pd.read_csv('international_airline_passangers.csv', engine = 'python', skipfooter = 3) # we skip 3 head rows \ df.columns # reassign the column names and pass it a list df.columns = ["month", "passangers"] print(df.passangers) # the same as df['passangers'] # to add a new column df['ones'...
99112e97e362b0681528cb1a23df231cef2aaa6f
KIRANROUTH/Problem_Solving-Hackerrank
/Migratory Birds - Hackerrank/Solution.py
1,050
3.5625
4
#Question Link: https://www.hackerrank.com/challenges/migratory-birds/problem #!/bin/python3 import math import os import random import re import sys # Complete the migratoryBirds function below. ''' def migratoryBirds(arr): co = 0 no = 0 for x in arr: val = arr.count(x) if val > no: ...
3f0074441dc82fd3ea152ebe1b52331e919cbb43
ChafikMaiza/TP01_Python_Html_CSV
/python_basics.py
1,521
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # déclaration de codage des caractère, utiliser souvent UTF-8, pour prendre en charge #toutes du multilingue. print("Salam Alykom") # Déclaration des variables # pas de déclaration explicite # il suffit d'affecter une valeur pour spécifier le type d'une variable age = 125 #...
cbbf2bafd536ebac36209183c5229d7bc616904e
thohidu/google-algorithms
/lesson_3/bubble_sort_quiz.py
844
4.25
4
"""Write a function that bubble sorts algorithm.""" def bubble_sort(input_array): n = len(input_array) for j in range(n-1): for i in range(n-1): if input_array[i] > input_array[i+1]: input_array[i+1], input_array[i] = input_array[i], input_array[i+1] # Make it bit efficient...
9aae1bf477c8ccffc259144fb924525b3cd1019d
AlexanderMertens/freecodecamp
/scientific-computing-with-python/polygon-area-calculator/shape_calculator.py
1,381
3.671875
4
MAX_LENGTH = 50 class Rectangle: def __init__(self, width, height): self.width = width self.height = height def set_width(self, width): self.width = width def set_height(self, height): self.height = height def get_area(self): return self.width * self.height ...
3b44f75fdb42cf9c944a6aef6a0987abd83e32b8
jtwool/mastering-large-datasets
/Ch04/more_filters.py
551
3.9375
4
from itertools import filterfalse from toolz.dicttoolz import keyfilter, valfilter, itemfilter def is_even(x): if x % 2 == 0: return True else: return False def both_are_even(x): k,v = x if is_even(k) and is_even(v): return True else: return False print(list(filterfalse(is_even, range(10)))) # [1...
12d84333b4aca4efc2c21f2913b95283dd24b632
ithiriz/100py
/ex5.py
245
3.546875
4
class InputOutString(object): def __init__(self): self.i = "" def getString(self): self.i = input() def printString(self): print (self.i.upper()) make = InputOutString() make.getString() make.printString()
ab2d6ecb9539f0c0e3314892df897dd54721b73c
henryneu/Python
/sample/clas.py
891
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Student(object): """docstring for Student""" def __init__(self, name, score): # 第一个参数永远是self 表示创建的实例本身 super(Student, self).__init__() self.__name = name self.__score = score def print_score(self): print('%s: %s' % (self.__name, self.__score)) def get...
144e7e2b47d69b84d2ae2e4d8c861cb11de7f4b0
henryneu/Python
/sample/slot.py
1,251
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from types import MethodType class Student(object): pass class People(object): # slots 定义的属性仅对当前类实例起作用,对继承的子类是不起作用的 __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称 class Boy(People): __slots__ = ('grade') # 子类也定义slots,则子类实例允许的属性就是自身的加父类的 def set_score(self, scor...
7136b4b64d36587ba79dc4b5063865c9bcaad444
VivekCR7/geeksforgeeks-interview-preparation
/Linked List/Reverse a linked list.py
1,201
4.0625
4
""" Question Link: https://practice.geeksforgeeks.org/problems/reverse-a-linked-list/1 """ class Node: def __init__(self,data): self.data = data self.next = None def Takeinput(): curr_list = [int(ele) for ele in input().split()] head = tail = None for curr_data in curr_list: if curr_data == -1: ...
d546e9621b57586918faa1e45c6ba30e56fdf707
kelvinn/aoc2018
/days/day_5.py
1,338
3.625
4
import string lower_upper = list(zip(list(string.ascii_lowercase), list(string.ascii_uppercase))) upper_lower = list(zip(list(string.ascii_uppercase), list(string.ascii_lowercase))) ALL_PAIRS = ['%s%s' % pair for pair in lower_upper + upper_lower] # First implementation. Super slow. def pop_pairs(data): for i i...
4d9a807f6a9f1090816a629c389885dd62ac9da5
fredericohorst/study-codility
/lesson3_time_complexity/frog_jumps.py
623
3.65625
4
# TIME COMPLEXITY - TAPE EQUILIBRIUM PROBLEM @ codility lessons # by Frederico Horst # https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/ def Solution(x,y,d): if x == y: jumps = 0 elif x/d < .5: jumps = round(y/d) else: xd = x//d yd = y//d jum...
09990fd5fd95802015a723cbd93e290e4a118eb1
ruthironside/functions_lab_2
/function_lab_2.py
1,457
3.53125
4
tasks = [ { "description": "Wash Dishes", "completed": False, "time_taken": 10 }, { "description": "Clean Windows", "completed": False, "time_taken": 15 }, { "description": "Make Dinner", "completed": True, "time_taken": 30 }, { "description": "Feed Cat", "completed": False, "time_taken": 5 }, { "de...
a42f972a2bb08cd484e1efd382d9f044a9c61d27
toddWannaCode/algorithms-and-data-structures
/insertion_sort.py
205
3.8125
4
def insertion_sort(l): for i in range(1, len(l)): j = i while j > 0 and l[j] < l[j - 1]: l[j], l[j-1] = l[j-1], l[j] j = j - 1 print(l) return l
3387e879a9616e7c3c128c37ea59e1398498f136
KristianFenn/AdventOfCode
/Day 3/Part 2.py
630
3.625
4
def Move(dir, x, y): if dir == '>': x += 1 elif dir == '<': x -= 1 elif dir == '^': y += 1 elif dir == 'v': y -= 1 return (x, y) def Main(directions): santaDir = directions[0::2] roboDir = directions[1::2] x, y = 0, 0 delivered = list([...
b87597709436e3d572f06d7a9b7f66a7453eac62
UncleStifler/LearnPython
/lesson3/datetime_work.py.py
1,599
3.984375
4
# пример: from datetime import datetime, timedelta, date dt_now = datetime.now() # datetime.now() берет текущее время print(dt_now) dt2 = datetime(2015, 5, 16, 8, 3, 44) # Разница между двумя датами delta = dt_now - dt2 print(f"Разница составит: {delta}") dt3 = dt2 + delta # возможность создать ину...
590048ffe3cbcf12ec1e0683c73244f0ba4572e1
UncleStifler/LearnPython
/lesson3/OOP/encapsulation.py
2,110
3.6875
4
# заносим в инкапсуляцию все правила для дальнейшей работы class Product: def __init__(self, name, price, discount=0, stock=0, max_discount=20.0): self.name = name.strip() # удалили из названия пробелы в начале и в конце if len(self.name) < 2: # проверили что длина названия не менее 2 символов...
5fee16e02732cd097941ed4fb0e4832c8fab6d53
UncleStifler/LearnPython
/lesson3/tasks/referat.py
1,170
3.921875
4
""" Скачайте файл по ссылке Прочитайте содержимое файла в переменную, подсчитайте длину получившейся строки Подсчитайте количество слов в тексте Замените точки в тексте на восклицательные знаки Сохраните результат в файл referat2.txt """ from collections import Counter with open('referat.txt', 'r', enco...
60d790e7de14249c491e51aa8863a6dfff357a93
UncleStifler/LearnPython
/lesson2/TASKS/lines_task.py
440
3.84375
4
def lines(x, y): if type(x) == str and type(y) == str: if x == y: return('1') elif x != y and len(x) > len(y): return('2') elif x != y and y == 'Learn': return('3') else: return('0') print(lines('Hello', 1)) print(lines('Hello...
917619598eaa555042a0a5643c6c9a96689e1819
UncleStifler/LearnPython
/lesson1/dictionaries.py
2,356
3.71875
4
lords_of_the_rings = ['Балин', 'Бифур', 'Бомбур', 'Бодруит', 'Борин', 'Бофур', 'Гамил'] products = { 'name': 'Iphone Xs', 'stock': 5, 'price': 650, 'recomend': lords_of_the_rings } print(products) print(len(products)) # добавление элементов в словарь. Старое значение не меняется products...
7b32864d618f4208bb3fa93c9aa39c9552081c2d
BalaVenkat3/Red-Ant-Media-Hackathon
/Problem 3.py
749
3.515625
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 27 20:56:15 2021 @author: balavenkat """ base = 3 s = base*base def pattern(r,c): return (base*(r%base)+r//base+c)%s from random import sample def shuffle(s): return sample(s,len(s)) rBase = range(base) r = [ g*base + r for g in shuffle(rBase) for r...
29e92c96ee5fc121f978538aa70efb98bb30d7ee
rperezl-dev/S14-POO
/Clase_Abstracta_e_Inteface2.py
4,815
3.703125
4
from datetime import date,datetime class Empresa: def __init__(self,nom='El mas barato',ruc='0999999999',tel='042971234',dir='Juan Montalvo y Pedro Carbo'): #con atributos; son variables locales self.nombre=nom#que atributos requiere self.ruc=ruc self.telefono=tel self.direccion=...